hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
edb063eebef799414986841dc05552b5a79410b8
1,342
cc
C++
src/search/pdbs/canonical_pdbs.cc
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
null
null
null
src/search/pdbs/canonical_pdbs.cc
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
null
null
null
src/search/pdbs/canonical_pdbs.cc
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
null
null
null
#include "canonical_pdbs.h" #include "dominance_pruning.h" #include "pattern_database.h" #include <algorithm> #include <cassert> #include <iostream> #include <limits> using namespace std; namespace pdbs { CanonicalPDBs::CanonicalPDBs( shared_ptr<PDBCollection> pattern_databases, shared_ptr<MaxAdditivePDBSubsets> max_additive_subsets_, bool dominance_pruning) : max_additive_subsets(max_additive_subsets_) { assert(max_additive_subsets); if (dominance_pruning) { max_additive_subsets = prune_dominated_subsets( *pattern_databases, *max_additive_subsets); } } int CanonicalPDBs::get_value(const State &state) const { // If we have an empty collection, then max_additive_subsets = { \emptyset }. assert(!max_additive_subsets->empty()); int max_h = 0; for (const auto &subset : *max_additive_subsets) { int subset_h = 0; for (const shared_ptr<PatternDatabase> &pdb : subset) { /* Experiments showed that it is faster to recompute the h values than to cache them in an unordered_map. */ int h = pdb->get_value(state); if (h == numeric_limits<int>::max()) return numeric_limits<int>::max(); subset_h += h; } max_h = max(max_h, subset_h); } return max_h; } }
29.822222
81
0.665425
nitinkaveriappa
edb16913e2d8d03e7e31ed1debbf6b15e361a3c1
12,163
cpp
C++
Data/SQLite/src/Utility.cpp
byteman/poco
f0f7f0fd3ce0ae3098de075a9c36bbd2f2ed0a13
[ "BSL-1.0" ]
1
2020-04-09T18:58:35.000Z
2020-04-09T18:58:35.000Z
Data/SQLite/src/Utility.cpp
byteman/poco
f0f7f0fd3ce0ae3098de075a9c36bbd2f2ed0a13
[ "BSL-1.0" ]
null
null
null
Data/SQLite/src/Utility.cpp
byteman/poco
f0f7f0fd3ce0ae3098de075a9c36bbd2f2ed0a13
[ "BSL-1.0" ]
null
null
null
// // Utility.cpp // // $Id: //poco/Main/Data/SQLite/src/Utility.cpp#5 $ // // Library: SQLite // Package: SQLite // Module: Utility // // Implementation of Utility // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/SQLite/Utility.h" #include "Poco/Data/SQLite/SQLiteException.h" #include "Poco/NumberFormatter.h" #include "Poco/String.h" #include "Poco/Any.h" #include "Poco/Exception.h" #if defined(POCO_UNBUNDLED) #include <sqlite3.h> #else #include "sqlite3.h" #endif namespace Poco { namespace Data { namespace SQLite { const int Utility::THREAD_MODE_SINGLE = SQLITE_CONFIG_SINGLETHREAD; const int Utility::THREAD_MODE_MULTI = SQLITE_CONFIG_MULTITHREAD; const int Utility::THREAD_MODE_SERIAL = SQLITE_CONFIG_SERIALIZED; int Utility::_threadMode = #if (SQLITE_THREADSAFE == 0) SQLITE_CONFIG_SINGLETHREAD; #elif (SQLITE_THREADSAFE == 1) SQLITE_CONFIG_SERIALIZED; #elif (SQLITE_THREADSAFE == 2) SQLITE_CONFIG_MULTITHREAD; #endif const int Utility::OPERATION_INSERT = SQLITE_INSERT; const int Utility::OPERATION_DELETE = SQLITE_DELETE; const int Utility::OPERATION_UPDATE = SQLITE_UPDATE; const std::string Utility::SQLITE_DATE_FORMAT = "%Y-%m-%d"; const std::string Utility::SQLITE_TIME_FORMAT = "%H:%M:%S"; Utility::TypeMap Utility::_types; Poco::Mutex Utility::_mutex; Utility::Utility() { Poco::Mutex::ScopedLock l(_mutex); if (_types.empty()) { _types.insert(TypeMap::value_type("", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("BOOL", MetaColumn::FDT_BOOL)); _types.insert(TypeMap::value_type("BOOLEAN", MetaColumn::FDT_BOOL)); _types.insert(TypeMap::value_type("BIT", MetaColumn::FDT_BOOL)); _types.insert(TypeMap::value_type("UINT8", MetaColumn::FDT_UINT8)); _types.insert(TypeMap::value_type("UTINY", MetaColumn::FDT_UINT8)); _types.insert(TypeMap::value_type("UINTEGER8", MetaColumn::FDT_UINT8)); _types.insert(TypeMap::value_type("INT8", MetaColumn::FDT_INT8)); _types.insert(TypeMap::value_type("TINY", MetaColumn::FDT_INT8)); _types.insert(TypeMap::value_type("INTEGER8", MetaColumn::FDT_INT8)); _types.insert(TypeMap::value_type("UINT16", MetaColumn::FDT_UINT16)); _types.insert(TypeMap::value_type("USHORT", MetaColumn::FDT_UINT16)); _types.insert(TypeMap::value_type("UINTEGER16", MetaColumn::FDT_UINT16)); _types.insert(TypeMap::value_type("INT16", MetaColumn::FDT_INT16)); _types.insert(TypeMap::value_type("SHORT", MetaColumn::FDT_INT16)); _types.insert(TypeMap::value_type("INTEGER16", MetaColumn::FDT_INT16)); _types.insert(TypeMap::value_type("UINT", MetaColumn::FDT_UINT32)); _types.insert(TypeMap::value_type("UINT32", MetaColumn::FDT_UINT32)); _types.insert(TypeMap::value_type("UINTEGER32", MetaColumn::FDT_UINT32)); _types.insert(TypeMap::value_type("INT", MetaColumn::FDT_INT32)); _types.insert(TypeMap::value_type("INT32", MetaColumn::FDT_INT32)); _types.insert(TypeMap::value_type("INTEGER", MetaColumn::FDT_INT32)); _types.insert(TypeMap::value_type("INTEGER32", MetaColumn::FDT_INT32)); _types.insert(TypeMap::value_type("UINT64", MetaColumn::FDT_UINT64)); _types.insert(TypeMap::value_type("ULONG", MetaColumn::FDT_INT64)); _types.insert(TypeMap::value_type("UINTEGER64", MetaColumn::FDT_UINT64)); _types.insert(TypeMap::value_type("INT64", MetaColumn::FDT_INT64)); _types.insert(TypeMap::value_type("LONG", MetaColumn::FDT_INT64)); _types.insert(TypeMap::value_type("INTEGER64", MetaColumn::FDT_INT64)); _types.insert(TypeMap::value_type("COUNTER", MetaColumn::FDT_UINT64)); _types.insert(TypeMap::value_type("AUTOINCREMENT", MetaColumn::FDT_UINT64)); _types.insert(TypeMap::value_type("REAL", MetaColumn::FDT_DOUBLE)); _types.insert(TypeMap::value_type("FLOA", MetaColumn::FDT_DOUBLE)); _types.insert(TypeMap::value_type("FLOAT", MetaColumn::FDT_DOUBLE)); _types.insert(TypeMap::value_type("DOUB", MetaColumn::FDT_DOUBLE)); _types.insert(TypeMap::value_type("DOUBLE", MetaColumn::FDT_DOUBLE)); _types.insert(TypeMap::value_type("CHAR", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("CLOB", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("TEXT", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("VARCHAR", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("NCHAR", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("NCLOB", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("NTEXT", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("NVARCHAR", MetaColumn::FDT_STRING)); _types.insert(TypeMap::value_type("BLOB", MetaColumn::FDT_BLOB)); _types.insert(TypeMap::value_type("DATE", MetaColumn::FDT_DATE)); _types.insert(TypeMap::value_type("TIME", MetaColumn::FDT_TIME)); _types.insert(TypeMap::value_type("DATETIME", MetaColumn::FDT_TIMESTAMP)); _types.insert(TypeMap::value_type("TIMESTAMP", MetaColumn::FDT_TIMESTAMP)); } } std::string Utility::lastError(sqlite3* pDB) { return std::string(sqlite3_errmsg(pDB)); } MetaColumn::ColumnDataType Utility::getColumnType(sqlite3_stmt* pStmt, std::size_t pos) { poco_assert_dbg (pStmt); static Utility u; const char* pc = sqlite3_column_decltype(pStmt, (int) pos); std::string sqliteType = pc ? pc : ""; Poco::toUpperInPlace(sqliteType); sqliteType = sqliteType.substr(0, sqliteType.find_first_of(" (")); TypeMap::const_iterator it = _types.find(Poco::trimInPlace(sqliteType)); if (_types.end() == it) throw Poco::NotFoundException(); return it->second; } void Utility::throwException(int rc, const std::string& addErrMsg) { switch (rc) { case SQLITE_OK: break; case SQLITE_ERROR: throw InvalidSQLStatementException(std::string("SQL error or missing database"), addErrMsg); case SQLITE_INTERNAL: throw InternalDBErrorException(std::string("An internal logic error in SQLite"), addErrMsg); case SQLITE_PERM: throw DBAccessDeniedException(std::string("Access permission denied"), addErrMsg); case SQLITE_ABORT: throw ExecutionAbortedException(std::string("Callback routine requested an abort"), addErrMsg); case SQLITE_BUSY: throw DBLockedException(std::string("The database file is locked"), addErrMsg); case SQLITE_LOCKED: throw TableLockedException(std::string("A table in the database is locked"), addErrMsg); case SQLITE_NOMEM: throw NoMemoryException(std::string("A malloc() failed"), addErrMsg); case SQLITE_READONLY: throw ReadOnlyException(std::string("Attempt to write a readonly database"), addErrMsg); case SQLITE_INTERRUPT: throw InterruptException(std::string("Operation terminated by sqlite_interrupt()"), addErrMsg); case SQLITE_IOERR: throw IOErrorException(std::string("Some kind of disk I/O error occurred"), addErrMsg); case SQLITE_CORRUPT: throw CorruptImageException(std::string("The database disk image is malformed"), addErrMsg); case SQLITE_NOTFOUND: throw TableNotFoundException(std::string("Table or record not found"), addErrMsg); case SQLITE_FULL: throw DatabaseFullException(std::string("Insertion failed because database is full"), addErrMsg); case SQLITE_CANTOPEN: throw CantOpenDBFileException(std::string("Unable to open the database file"), addErrMsg); case SQLITE_PROTOCOL: throw LockProtocolException(std::string("Database lock protocol error"), addErrMsg); case SQLITE_EMPTY: throw InternalDBErrorException(std::string("(Internal Only) Database table is empty"), addErrMsg); case SQLITE_SCHEMA: throw SchemaDiffersException(std::string("The database schema changed"), addErrMsg); case SQLITE_TOOBIG: throw RowTooBigException(std::string("Too much data for one row of a table"), addErrMsg); case SQLITE_CONSTRAINT: throw ConstraintViolationException(std::string("Abort due to constraint violation"), addErrMsg); case SQLITE_MISMATCH: throw DataTypeMismatchException(std::string("Data type mismatch"), addErrMsg); case SQLITE_MISUSE: throw InvalidLibraryUseException(std::string("Library used incorrectly"), addErrMsg); case SQLITE_NOLFS: throw OSFeaturesMissingException(std::string("Uses OS features not supported on host"), addErrMsg); case SQLITE_AUTH: throw AuthorizationDeniedException(std::string("Authorization denied"), addErrMsg); case SQLITE_FORMAT: throw CorruptImageException(std::string("Auxiliary database format error"), addErrMsg); case SQLITE_NOTADB: throw CorruptImageException(std::string("File opened that is not a database file"), addErrMsg); case SQLITE_RANGE: throw InvalidSQLStatementException(std::string("Bind Parameter out of range (Access of invalid position 0? bind starts with 1!)"), addErrMsg); case SQLITE_ROW: break; // sqlite_step() has another row ready case SQLITE_DONE: break; // sqlite_step() has finished executing default: throw SQLiteException(std::string("Unknown error code: ") + Poco::NumberFormatter::format(rc), addErrMsg); } } bool Utility::fileToMemory(sqlite3* pInMemory, const std::string& fileName) { int rc; sqlite3* pFile; sqlite3_backup* pBackup; rc = sqlite3_open(fileName.c_str(), &pFile); if(rc == SQLITE_OK ) { pBackup = sqlite3_backup_init(pInMemory, "main", pFile, "main"); if( pBackup ) { sqlite3_backup_step(pBackup, -1); sqlite3_backup_finish(pBackup); } rc = sqlite3_errcode(pFile); } sqlite3_close(pFile); return SQLITE_OK == rc; } bool Utility::memoryToFile(const std::string& fileName, sqlite3* pInMemory) { int rc; sqlite3* pFile; sqlite3_backup* pBackup; rc = sqlite3_open(fileName.c_str(), &pFile); if(rc == SQLITE_OK ) { pBackup = sqlite3_backup_init(pFile, "main", pInMemory, "main"); if( pBackup ) { sqlite3_backup_step(pBackup, -1); sqlite3_backup_finish(pBackup); } rc = sqlite3_errcode(pFile); } sqlite3_close(pFile); return SQLITE_OK == rc; } bool Utility::isThreadSafe() { return 0 != sqlite3_threadsafe(); } int Utility::getThreadMode() { return _threadMode; } bool Utility::setThreadMode(int mode) { #if (SQLITE_THREADSAFE != 0) if (SQLITE_OK == sqlite3_shutdown()) { if (SQLITE_OK == sqlite3_config(mode)) { _threadMode = mode; if (SQLITE_OK == sqlite3_initialize()) return true; } sqlite3_initialize(); } return false; #else return false; #endif } void* Utility::eventHookRegister(sqlite3* pDB, UpdateCallbackType callbackFn, void* pParam) { typedef void(*pF)(void*, int, const char*, const char*, sqlite3_int64); return sqlite3_update_hook(pDB, reinterpret_cast<pF>(callbackFn), pParam); } void* Utility::eventHookRegister(sqlite3* pDB, CommitCallbackType callbackFn, void* pParam) { return sqlite3_commit_hook(pDB, callbackFn, pParam); } void* Utility::eventHookRegister(sqlite3* pDB, RollbackCallbackType callbackFn, void* pParam) { return sqlite3_rollback_hook(pDB, callbackFn, pParam); } } } } // namespace Poco::Data::SQLite
36.969605
144
0.757543
byteman
edb1aa145cad270457d2a8575b0c1b8292f92959
2,146
cpp
C++
src/shogun/preprocessor/SumOne.cpp
srgnuclear/shogun
33c04f77a642416376521b0cd1eed29b3256ac13
[ "Ruby", "MIT" ]
1
2015-11-05T18:31:14.000Z
2015-11-05T18:31:14.000Z
src/shogun/preprocessor/SumOne.cpp
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
src/shogun/preprocessor/SumOne.cpp
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2012 Sergey Lisitsyn * Copyright (C) 2012 Sergey Lisitsyn */ #include <shogun/preprocessor/SumOne.h> #include <shogun/preprocessor/DensePreprocessor.h> #include <shogun/mathematics/Math.h> #include <shogun/features/Features.h> using namespace shogun; CSumOne::CSumOne() : CDensePreprocessor<float64_t>() { } CSumOne::~CSumOne() { } /// initialize preprocessor from features bool CSumOne::init(CFeatures* features) { ASSERT(features->get_feature_class()==C_DENSE) ASSERT(features->get_feature_type()==F_DREAL) return true; } /// clean up allocated memory void CSumOne::cleanup() { } /// initialize preprocessor from file bool CSumOne::load(FILE* f) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } /// save preprocessor init-data to file bool CSumOne::save(FILE* f) { SG_SET_LOCALE_C; SG_RESET_LOCALE; return false; } /// apply preproc on feature matrix /// result in feature matrix /// return pointer to feature_matrix, i.e. f->get_feature_matrix(); SGMatrix<float64_t> CSumOne::apply_to_feature_matrix(CFeatures* features) { SGMatrix<float64_t> feature_matrix=((CDenseFeatures<float64_t>*)features)->get_feature_matrix(); for (int32_t i=0; i<feature_matrix.num_cols; i++) { float64_t* vec= &(feature_matrix.matrix[i*feature_matrix.num_rows]); float64_t sum = SGVector<float64_t>::sum(vec,feature_matrix.num_rows); SGVector<float64_t>::scale_vector(1.0/sum, vec, feature_matrix.num_rows); } return feature_matrix; } /// apply preproc on single feature vector /// result in feature matrix SGVector<float64_t> CSumOne::apply_to_feature_vector(SGVector<float64_t> vector) { float64_t* normed_vec = SG_MALLOC(float64_t, vector.vlen); float64_t sum = SGVector<float64_t>::sum(vector.vector, vector.vlen); for (int32_t i=0; i<vector.vlen; i++) normed_vec[i]=vector.vector[i]/sum; return SGVector<float64_t>(normed_vec,vector.vlen); }
25.247059
97
0.753029
srgnuclear
edb1ba802a364f855dfa4e5cdaa275cd1e9a6ded
10,956
cpp
C++
src/ompl/control/src/SpaceInformation.cpp
ericpairet/ompl
25c76431cef25f0100ed74d09dd88944ecca5ee1
[ "BSD-3-Clause" ]
837
2015-01-07T12:01:20.000Z
2022-03-31T08:42:42.000Z
src/ompl/control/src/SpaceInformation.cpp
ericpairet/ompl
25c76431cef25f0100ed74d09dd88944ecca5ee1
[ "BSD-3-Clause" ]
271
2015-01-12T22:05:06.000Z
2022-03-30T22:16:01.000Z
src/ompl/control/src/SpaceInformation.cpp
ericpairet/ompl
25c76431cef25f0100ed74d09dd88944ecca5ee1
[ "BSD-3-Clause" ]
452
2015-02-10T08:48:21.000Z
2022-03-23T06:53:33.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University 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. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/control/SpaceInformation.h" #include "ompl/control/SimpleDirectedControlSampler.h" #include "ompl/control/SteeredControlSampler.h" #include "ompl/util/Exception.h" #include <cassert> #include <utility> #include <limits> ompl::control::SpaceInformation::SpaceInformation( const base::StateSpacePtr &stateSpace, ControlSpacePtr controlSpace) : base::SpaceInformation(stateSpace), controlSpace_(std::move(controlSpace)) { declareParams(); } void ompl::control::SpaceInformation::declareParams() { params_.declareParam<unsigned int>("min_control_duration", [this](unsigned int n) { setMinControlDuration(n); }, [this] { return getMinControlDuration(); }); params_.declareParam<unsigned int>("max_control_duration", [this](unsigned int n) { setMaxControlDuration(n); }, [this] { return getMaxControlDuration(); }); params_.declareParam<double>("propagation_step_size", [this](double s) { setPropagationStepSize(s); }, [this] { return getPropagationStepSize(); }); } void ompl::control::SpaceInformation::setup() { base::SpaceInformation::setup(); declareParams(); // calling base::SpaceInformation::setup() clears the params if (!statePropagator_) throw Exception("State propagator not defined"); if (minSteps_ > maxSteps_) throw Exception("The minimum number of steps cannot be larger than the maximum number of steps"); if (minSteps_ == 0 && maxSteps_ == 0) { minSteps_ = 1; maxSteps_ = 10; OMPL_WARN("Assuming propagation will always have between %d and %d steps", minSteps_, maxSteps_); } if (minSteps_ < 1) throw Exception("The minimum number of steps must be at least 1"); if (stepSize_ < std::numeric_limits<double>::epsilon()) { stepSize_ = getStateValidityCheckingResolution() * getMaximumExtent(); if (stepSize_ < std::numeric_limits<double>::epsilon()) throw Exception("The propagation step size must be larger than 0"); OMPL_WARN("The propagation step size is assumed to be %f", stepSize_); } controlSpace_->setup(); if (controlSpace_->getDimension() <= 0) throw Exception("The dimension of the control space we plan in must be > 0"); } ompl::control::DirectedControlSamplerPtr ompl::control::SpaceInformation::allocDirectedControlSampler() const { if (dcsa_) return dcsa_(this); if (statePropagator_->canSteer()) return std::make_shared<SteeredControlSampler>(this); else return std::make_shared<SimpleDirectedControlSampler>(this); } void ompl::control::SpaceInformation::setDirectedControlSamplerAllocator(const DirectedControlSamplerAllocator &dcsa) { dcsa_ = dcsa; setup_ = false; } void ompl::control::SpaceInformation::clearDirectedSamplerAllocator() { dcsa_ = DirectedControlSamplerAllocator(); setup_ = false; } void ompl::control::SpaceInformation::setStatePropagator(const StatePropagatorFn &fn) { class FnStatePropagator : public StatePropagator { public: FnStatePropagator(SpaceInformation *si, StatePropagatorFn fn) : StatePropagator(si), fn_(std::move(fn)) { } void propagate(const base::State *state, const Control *control, const double duration, base::State *result) const override { fn_(state, control, duration, result); } protected: StatePropagatorFn fn_; }; setStatePropagator(std::make_shared<FnStatePropagator>(this, fn)); } void ompl::control::SpaceInformation::setStatePropagator(const StatePropagatorPtr &sp) { statePropagator_ = sp; } bool ompl::control::SpaceInformation::canPropagateBackward() const { return statePropagator_->canPropagateBackward(); } void ompl::control::SpaceInformation::propagate(const base::State *state, const Control *control, int steps, base::State *result) const { if (steps == 0) { if (result != state) copyState(result, state); } else { double signedStepSize = steps > 0 ? stepSize_ : -stepSize_; steps = abs(steps); statePropagator_->propagate(state, control, signedStepSize, result); for (int i = 1; i < steps; ++i) statePropagator_->propagate(result, control, signedStepSize, result); } } unsigned int ompl::control::SpaceInformation::propagateWhileValid(const base::State *state, const Control *control, int steps, base::State *result) const { if (steps == 0) { if (result != state) copyState(result, state); return 0; } double signedStepSize = steps > 0 ? stepSize_ : -stepSize_; steps = abs(steps); // perform the first step of propagation statePropagator_->propagate(state, control, signedStepSize, result); // if we found a valid state after one step, we can go on if (isValid(result)) { base::State *temp1 = result; base::State *temp2 = allocState(); base::State *toDelete = temp2; unsigned int r = steps; // for the remaining number of steps for (int i = 1; i < steps; ++i) { statePropagator_->propagate(temp1, control, signedStepSize, temp2); if (isValid(temp2)) std::swap(temp1, temp2); else { // the last valid state is temp1; r = i; break; } } // if we finished the for-loop without finding an invalid state, the last valid state is temp1 // make sure result contains that information if (result != temp1) copyState(result, temp1); // free the temporary memory freeState(toDelete); return r; } // if the first propagation step produced an invalid step, return 0 steps // the last valid state is the starting one (assumed to be valid) if (result != state) copyState(result, state); return 0; } void ompl::control::SpaceInformation::propagate(const base::State *state, const Control *control, int steps, std::vector<base::State *> &result, bool alloc) const { double signedStepSize = steps > 0 ? stepSize_ : -stepSize_; steps = abs(steps); if (alloc) { result.resize(steps); for (auto &i : result) i = allocState(); } else { if (result.empty()) return; steps = std::min(steps, (int)result.size()); } int st = 0; if (st < steps) { statePropagator_->propagate(state, control, signedStepSize, result[st]); ++st; while (st < steps) { statePropagator_->propagate(result[st - 1], control, signedStepSize, result[st]); ++st; } } } unsigned int ompl::control::SpaceInformation::propagateWhileValid(const base::State *state, const Control *control, int steps, std::vector<base::State *> &result, bool alloc) const { double signedStepSize = steps > 0 ? stepSize_ : -stepSize_; steps = abs(steps); if (alloc) result.resize(steps); else { if (result.empty()) return 0; steps = std::min(steps, (int)result.size()); } int st = 0; if (st < steps) { if (alloc) result[st] = allocState(); statePropagator_->propagate(state, control, signedStepSize, result[st]); if (isValid(result[st])) { ++st; while (st < steps) { if (alloc) result[st] = allocState(); statePropagator_->propagate(result[st - 1], control, signedStepSize, result[st]); if (!isValid(result[st])) { if (alloc) { freeState(result[st]); result.resize(st); } break; } ++st; } } else { if (alloc) { freeState(result[st]); result.resize(st); } } } return st; } void ompl::control::SpaceInformation::printSettings(std::ostream &out) const { base::SpaceInformation::printSettings(out); out << " - control space:" << std::endl; controlSpace_->printSettings(out); out << " - can propagate backward: " << (canPropagateBackward() ? "yes" : "no") << std::endl; out << " - propagation step size: " << stepSize_ << std::endl; out << " - propagation duration: [" << minSteps_ << ", " << maxSteps_ << "]" << std::endl; }
33.814815
117
0.596568
ericpairet
edb5df4596b031736b5437b81f07fd520c1413ce
1,797
hpp
C++
include/range/v3/view/unique.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
521
2016-02-14T00:39:01.000Z
2022-03-01T22:39:25.000Z
include/range/v3/view/unique.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
8
2017-02-21T11:47:33.000Z
2018-11-01T09:37:14.000Z
include/range/v3/view/unique.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
48
2017-02-21T10:18:13.000Z
2022-03-25T02:35:20.000Z
/// \file // Range v3 library // // Copyright Eric Niebler 2013-present // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_UNIQUE_HPP #define RANGES_V3_VIEW_UNIQUE_HPP #include <utility> #include <meta/meta.hpp> #include <range/v3/range_fwd.hpp> #include <range/v3/functional/bind_back.hpp> #include <range/v3/functional/not_fn.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/view/adjacent_filter.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/view.hpp> namespace ranges { /// \addtogroup group-views /// @{ namespace views { struct unique_fn { private: friend view_access; template<typename C> static constexpr auto CPP_fun(bind)(unique_fn unique, C pred)( // requires(!range<C>)) { return bind_back(unique, std::move(pred)); } public: template<typename Rng, typename C = equal_to> constexpr auto operator()(Rng && rng, C pred = {}) const -> CPP_ret(adjacent_filter_view<all_t<Rng>, logical_negate<C>>)( // requires viewable_range<Rng> && forward_range<Rng> && indirect_relation<C, iterator_t<Rng>>) { return {all(static_cast<Rng &&>(rng)), not_fn(pred)}; } }; /// \relates unique_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(view<unique_fn>, unique) } // namespace views /// @} } // namespace ranges #endif
27.227273
83
0.607123
berolinux
edb6256af3b3e34d3a889492de43c916f3b7dd80
2,261
hpp
C++
include/networkit/coarsening/ClusteringProjector.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
include/networkit/coarsening/ClusteringProjector.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
include/networkit/coarsening/ClusteringProjector.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
1
2020-02-05T17:39:47.000Z
2020-02-05T17:39:47.000Z
/* * ClusteringProjector.h * * Created on: 07.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #ifndef NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_ #define NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_ #include <networkit/graph/Graph.hpp> #include <networkit/structures/Partition.hpp> namespace NetworKit { /** * @ingroup coarsening */ class ClusteringProjector { public: /** * DEPRECATED * * Given * @param[in] Gcoarse * @param[in] Gfine * @param[in] fineToCoarse * @param[in] zetaCoarse a clustering of the coarse graph * * , project the clustering back to the fine graph to create a clustering of the fine graph. * @param[out] a clustering of the fine graph **/ //virtual Partition projectBack(Graph& Gcoarse, Graph& Gfine, std::vector<node>& fineToCoarse, Partition& zetaCoarse); /** * Given * @param[in] Gcoarse * @param[in] Gfine * @param[in] fineToCoarse * @param[in] zetaCoarse a clustering of the coarse graph * * , project the clustering back to the fine graph to create a clustering of the fine graph. * @param[out] a clustering of the fine graph **/ virtual Partition projectBack(const Graph& Gcoarse, const Graph& Gfine, const std::vector<node>& fineToCoarse, const Partition& zetaCoarse); /** * Project a clustering \zeta^{i} of the coarse graph G^{i} back to * the finest graph G^{0}, using the hierarchy of fine->coarse maps */ virtual Partition projectBackToFinest(const Partition& zetaCoarse, const std::vector<std::vector<node> >& maps, const Graph& Gfinest); /** * Assuming that the coarse graph resulted from contracting and represents a clustering of the finest graph * * @param[in] Gcoarse coarse graph * @param[in] Gfinest finest graph * @param[in] maps hierarchy of maps M^{i->i+1} mapping nodes in finer graph to supernodes in coarser graph */ virtual Partition projectCoarseGraphToFinestClustering(const Graph& Gcoarse, const Graph& Gfinest, const std::vector<std::vector<node> >& maps); }; } /* namespace NetworKit */ #endif // NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_
30.972603
148
0.678903
kmc-kk
edb659b91eebfa6db163ad76e4e3a47a6d9658eb
1,809
cpp
C++
Eleusis_sln/Eleusis/01_os_backend/01_Win32/Timer_Win32.cpp
bognikol/Eleusis
ee518ede31893689eb6d3c5539e0bd757aeb0294
[ "MIT" ]
4
2019-05-31T19:55:23.000Z
2020-10-27T10:00:32.000Z
Eleusis_sln/Eleusis/01_os_backend/01_Win32/Timer_Win32.cpp
bognikol/Eleusis
ee518ede31893689eb6d3c5539e0bd757aeb0294
[ "MIT" ]
null
null
null
Eleusis_sln/Eleusis/01_os_backend/01_Win32/Timer_Win32.cpp
bognikol/Eleusis
ee518ede31893689eb6d3c5539e0bd757aeb0294
[ "MIT" ]
3
2019-04-29T14:09:38.000Z
2020-10-27T10:00:33.000Z
#ifdef _WIN32 #include "Timer.h" #include <Windows.h> using namespace Eleusis; using namespace std; static std::map<void*, Timer*> _activeTimers; void CALLBACK _timerProc(_In_ HWND hwnd, _In_ UINT uMsg, _In_ UINT_PTR idEvent, _In_ DWORD dwTime) { auto l_timerIter = _activeTimers.find(reinterpret_cast<void*>(idEvent)); if (l_timerIter == _activeTimers.end()) return; Timer* l_timer = l_timerIter->second; if (l_timer->repetition_get() == TimerRepetition::Once) l_timer->stop(); if (l_timer->enabled_get()) raiseEvent l_timer->elapsed(l_timer, nullptr); } Timer::Timer(unsigned int duration, TimerRepetition repetition) : _duration(duration), _repetition(repetition) { } Timer::~Timer() { stop(); } void Timer::start() { if (_timerID == 0) { _timerID = reinterpret_cast<void*>(SetTimer(nullptr, 0, _duration, _timerProc)); _activeTimers[_timerID] = this; } else { SetTimer(nullptr, reinterpret_cast<UINT_PTR>(_timerID), _duration, _timerProc); } raiseEvent started(this, nullptr); } void Timer::stop() { if (_timerID == 0) return; KillTimer(nullptr, reinterpret_cast<UINT_PTR>(_timerID)); _activeTimers.erase(_timerID); _timerID = 0; } void Timer::duration_set(unsigned int duration) { _duration = duration; if (_timerID != 0) SetTimer(nullptr, reinterpret_cast<UINT_PTR>(_timerID), _duration, _timerProc); } unsigned int Timer::duration_get() { return _duration; } void Timer::repetition_set(TimerRepetition repetition) { _repetition = repetition; } TimerRepetition Timer::repetition_get() { return _repetition; } void Timer::enabled_set(bool enable) { _enabled = enable; } bool Timer::enabled_get() { return _enabled; } #endif
19.663043
98
0.682698
bognikol
edc232de82b448ad6a4c98b1fad9a09f9615b0a4
90,628
cpp
C++
PhysEngines/tokamak/tokamak_release/tokamaksrc/src/ne_interface.cpp
netpipe/IrrPAL
39cfbe497c0d18a3b63f1a7758a2b979977d8efb
[ "BSD-3-Clause" ]
22
2015-02-18T16:38:52.000Z
2021-04-11T06:25:28.000Z
PhysEngines/tokamak/tokamak_release/tokamaksrc/src/ne_interface.cpp
netpipe/IrrPAL
39cfbe497c0d18a3b63f1a7758a2b979977d8efb
[ "BSD-3-Clause" ]
null
null
null
PhysEngines/tokamak/tokamak_release/tokamaksrc/src/ne_interface.cpp
netpipe/IrrPAL
39cfbe497c0d18a3b63f1a7758a2b979977d8efb
[ "BSD-3-Clause" ]
9
2017-06-27T12:46:15.000Z
2022-03-17T08:27:50.000Z
/************************************************************************* * * * Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. * * All rights reserved. Email: david@tokamakphysics.com * * Web: www.tokamakphysics.com * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "math/ne_type.h" #include "math/ne_debug.h" #include "tokamak.h" #include "containers.h" #include "scenery.h" #include "collision.h" #include "constraint.h" #include "rigidbody.h" #ifdef _WIN32 #include <windows.h> #endif #include "stack.h" #include "simulator.h" #include "message.h" #include "stdio.h" #define CAST_THIS(a, b) a& b = reinterpret_cast<a&>(*this); #ifdef TOKAMAK_COMPILE_DLL BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif /**************************************************************************** * * neGeometry::SetBoxSize * ****************************************************************************/ void neGeometry::SetBoxSize(f32 width, f32 height, f32 depth) { CAST_THIS(TConvex, con); con.SetBoxSize(width, height, depth); } /**************************************************************************** * * neGeometry::SetBoxSize * ****************************************************************************/ void neGeometry::SetBoxSize(const neV3 & boxSize) { CAST_THIS(TConvex, con); con.SetBoxSize(boxSize[0], boxSize[1], boxSize[2]); } /**************************************************************************** * * neGeometry::SetCylinder * ****************************************************************************/ void neGeometry::SetCylinder(f32 diameter, f32 height) { CAST_THIS(TConvex, con); con.type = TConvex::CYLINDER; con.as.cylinder.radius = diameter * 0.5f; con.as.cylinder.radiusSq = con.as.cylinder.radius * con.as.cylinder.radius; con.as.cylinder.halfHeight = height * 0.5f; } /**************************************************************************** * * neGeometry::GetCylinder * ****************************************************************************/ neBool neGeometry::GetCylinder(f32 & diameter, f32 & height) // return false if geometry is not a cylinder { CAST_THIS(TConvex, con); if (con.type != TConvex::CYLINDER) return false; diameter = con.CylinderRadius() * 2.0f; height = con.CylinderHalfHeight() * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetConvexMesh * ****************************************************************************/ void neGeometry::SetConvexMesh(neByte * convexData) { CAST_THIS(TConvex, con); con.SetConvexMesh(convexData); } /**************************************************************************** * * neGeometry::GetConvexMesh * ****************************************************************************/ neBool neGeometry::GetConvexMesh(neByte *& convexData) { CAST_THIS(TConvex, con); if (con.type != TConvex::CONVEXDCD) return false; convexData = con.as.convexDCD.convexData; return true; } /**************************************************************************** * * neGeometry::SetTransform * ****************************************************************************/ void neGeometry::SetTransform(neT3 & t) { CAST_THIS(TConvex, con); con.SetTransform(t); } /**************************************************************************** * * neGeometry::SetMaterialIndex * ****************************************************************************/ void neGeometry::SetMaterialIndex(s32 index) { CAST_THIS(TConvex, con); con.SetMaterialId(index); } /**************************************************************************** * * neGeometry::GetMaterialIndex * ****************************************************************************/ s32 neGeometry::GetMaterialIndex() { CAST_THIS(TConvex, con); return con.matIndex; } /**************************************************************************** * * neGeometry::GetTransform * ****************************************************************************/ neT3 neGeometry::GetTransform() { CAST_THIS(TConvex, con); return con.c2p; } /**************************************************************************** * * neGeometry::SetUserData * ****************************************************************************/ void neGeometry::SetUserData(u32 userData) { CAST_THIS(TConvex, con); con.userData = userData; } /**************************************************************************** * * neGeometry::GetUserData * ****************************************************************************/ u32 neGeometry::GetUserData() { CAST_THIS(TConvex, con); return con.userData; } /**************************************************************************** * * neGeometry::GetBoxSize * ****************************************************************************/ neBool neGeometry::GetBoxSize(neV3 & boxSize) // return false if geometry is not a box { CAST_THIS(TConvex, con); if (con.type != TConvex::BOX) return false; boxSize = con.as.box.boxSize * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetSphereDiameter * ****************************************************************************/ void neGeometry::SetSphereDiameter(f32 diameter) { CAST_THIS(TConvex, con); con.type = TConvex::SPHERE; con.as.sphere.radius = diameter * 0.5f; con.as.sphere.radiusSq = con.as.sphere.radius * con.as.sphere.radius; } /**************************************************************************** * * neGeometry::GetSphereDiameter * ****************************************************************************/ neBool neGeometry::GetSphereDiameter(f32 & diameter) // return false if geometry is not a sphere { CAST_THIS(TConvex, con); if (con.type != TConvex::SPHERE) return false; diameter = con.Radius() * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetBreakFlag * ****************************************************************************/ void neGeometry::SetBreakageFlag(neBreakFlag flag) { CAST_THIS(TConvex, con); con.breakInfo.flag = flag; } /**************************************************************************** * * neGeometry::GetBreakFlag * ****************************************************************************/ neGeometry::neBreakFlag neGeometry::GetBreakageFlag() { CAST_THIS(TConvex, con); return con.breakInfo.flag; } /**************************************************************************** * * neGeometry::SetBreakageMass * ****************************************************************************/ void neGeometry::SetBreakageMass(f32 mass) { CAST_THIS(TConvex, con); con.breakInfo.mass = mass; } /**************************************************************************** * * neGeometry::GetBreakageMass * ****************************************************************************/ f32 neGeometry::GetBreakageMass() { CAST_THIS(TConvex, con); return con.breakInfo.mass; } /**************************************************************************** * * neGeometry::SetBreakageInertiaTensor * ****************************************************************************/ void neGeometry::SetBreakageInertiaTensor(const neV3 & tensor) { CAST_THIS(TConvex, con); con.breakInfo.inertiaTensor = tensor; } /**************************************************************************** * * neGeometry::GetBreakageInertiaTensor * ****************************************************************************/ neV3 neGeometry::GetBreakageInertiaTensor() { CAST_THIS(TConvex, con); return con.breakInfo.inertiaTensor; } /**************************************************************************** * * neGeometry::SetBreakageMagnitude * ****************************************************************************/ void neGeometry::SetBreakageMagnitude(f32 mag) { CAST_THIS(TConvex, con); con.breakInfo.breakMagnitude = mag; } /**************************************************************************** * * neGeometry::GetBreakageMagnitude * ****************************************************************************/ f32 neGeometry::GetBreakageMagnitude() { CAST_THIS(TConvex, con); return con.breakInfo.breakMagnitude; } /**************************************************************************** * * neGeometry::SetBreakageAbsorption * ****************************************************************************/ void neGeometry::SetBreakageAbsorption(f32 absorb) { CAST_THIS(TConvex, con); con.breakInfo.breakAbsorb = absorb; } void neGeometry::SetBreakagePlane(const neV3 & planeNormal) { CAST_THIS(TConvex, con); con.breakInfo.breakPlane = planeNormal; } neV3 neGeometry::GetBreakagePlane() { CAST_THIS(TConvex, con); return con.breakInfo.breakPlane; } /**************************************************************************** * * neGeometry::GetBreakageAbsorption * ****************************************************************************/ f32 neGeometry::GetBreakageAbsorption() { CAST_THIS(TConvex, con); return con.breakInfo.breakAbsorb; } /**************************************************************************** * * neGeometry::SetBreakNeighbourRadius * ****************************************************************************/ void neGeometry::SetBreakageNeighbourRadius(f32 radius) { CAST_THIS(TConvex, con); con.breakInfo.neighbourRadius = radius; } /**************************************************************************** * * neGeometry::GetBreakNeighbourRadius * ****************************************************************************/ f32 neGeometry::GetBreakageNeighbourRadius() { CAST_THIS(TConvex, con); return con.breakInfo.neighbourRadius; } /**************************************************************************** * * neAnimatedBody::GetPos * ****************************************************************************/ neV3 neAnimatedBody::GetPos() { CAST_THIS(neCollisionBody_, cb); return cb.b2w.pos; } /**************************************************************************** * * neAnimatedBody::SetPos * ****************************************************************************/ void neAnimatedBody::SetPos(const neV3 & p) { CAST_THIS(neCollisionBody_, cb); cb.b2w.pos = p; cb.UpdateAABB(); cb.moved = true; } /**************************************************************************** * * neAnimatedBody::GetRotationM3 * ****************************************************************************/ neM3 neAnimatedBody::GetRotationM3() { CAST_THIS(neCollisionBody_, cb); return cb.b2w.rot; } /**************************************************************************** * * neAnimatedBody::GetRotationQ * ****************************************************************************/ neQ neAnimatedBody::GetRotationQ() { CAST_THIS(neCollisionBody_, cb); neQ q; q.SetupFromMatrix3(cb.b2w.rot); return q; } /**************************************************************************** * * neAnimatedBody::SetRotation * ****************************************************************************/ void neAnimatedBody::SetRotation(const neM3 & m) { CAST_THIS(neCollisionBody_, cb); cb.b2w.rot = m; cb.moved = true; } /**************************************************************************** * * neAnimatedBody::SetRotation * ****************************************************************************/ void neAnimatedBody::SetRotation(const neQ & q) { CAST_THIS(neCollisionBody_, cb); cb.b2w.rot = q.BuildMatrix3(); cb.moved = true; } /**************************************************************************** * * neAnimatedBody::GetTransform * ****************************************************************************/ neT3 neAnimatedBody::GetTransform() { CAST_THIS(neCollisionBody_, cb); return cb.b2w; } /**************************************************************************** * * neAnimatedBody::SetCollisionID * ****************************************************************************/ void neAnimatedBody::SetCollisionID(s32 cid) { CAST_THIS(neCollisionBody_, cb); cb.cid = cid; } /**************************************************************************** * * neAnimatedBody::GetCollisionID * ****************************************************************************/ s32 neAnimatedBody::GetCollisionID() { CAST_THIS(neCollisionBody_, cb); return cb.cid; } /**************************************************************************** * * neAnimatedBody::SetUserData * ****************************************************************************/ void neAnimatedBody::SetUserData(u32 cookies) { CAST_THIS(neCollisionBody_, cb); cb.cookies = cookies; } /**************************************************************************** * * neAnimatedBody::GetUserData * ****************************************************************************/ u32 neAnimatedBody::GetUserData() { CAST_THIS(neCollisionBody_, cb); return cb.cookies; } /**************************************************************************** * * neAnimatedBody::GetGeometryCount * ****************************************************************************/ s32 neAnimatedBody::GetGeometryCount() { CAST_THIS(neCollisionBody_, cb); return cb.col.convexCount; } /**************************************************************************** * * neAnimatedBody::GetGeometry * ****************************************************************************/ /* neGeometry * neAnimatedBody::GetGeometry(s32 index) { CAST_THIS(neCollisionBody_, cb); return reinterpret_cast<neGeometry*>(cb.GetConvex(index)); } */ /**************************************************************************** * * neAnimatedBody::SetGeometry * ****************************************************************************/ /* void neAnimatedBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray) { CAST_THIS(neCollisionBody_, cb); //todo } */ /**************************************************************************** * * neAnimatedBody::UpdateBoundingInfo * ****************************************************************************/ void neAnimatedBody::UpdateBoundingInfo() { CAST_THIS(neRigidBodyBase, rb); rb.RecalcBB(); } /**************************************************************************** * * neAnimatedBody::CollideConnected * ****************************************************************************/ void neAnimatedBody::CollideConnected(neBool yes) { CAST_THIS(neRigidBodyBase, rb); rb.CollideConnected(yes); } /**************************************************************************** * * neAnimatedBody::IsCollideConnected * ****************************************************************************/ neBool neAnimatedBody::CollideConnected() { CAST_THIS(neRigidBodyBase, rb); return rb.CollideConnected(); } /**************************************************************************** * * neAnimatedBody::CollideDirectlyConnected * ****************************************************************************/ void neAnimatedBody::CollideDirectlyConnected(neBool yes) { CAST_THIS(neRigidBodyBase, rb); rb.isCollideDirectlyConnected = yes; } /**************************************************************************** * * neAnimatedBody::CollideDirectlyConnected * ****************************************************************************/ neBool neAnimatedBody::CollideDirectlyConnected() { CAST_THIS(neRigidBodyBase, rb); return rb.isCollideDirectlyConnected; } /**************************************************************************** * * neAnimatedBody::AddGeometry * ****************************************************************************/ neGeometry * neAnimatedBody::AddGeometry() { CAST_THIS(neCollisionBody_, ab); TConvex * g = ab.AddGeometry(); return reinterpret_cast<neGeometry *>(g); } /**************************************************************************** * * neAnimatedBody::RemoveGeometry * ****************************************************************************/ neBool neAnimatedBody::RemoveGeometry(neGeometry * g) { CAST_THIS(neCollisionBody_, ab); if (!ab.col.convex) return false; TConvexItem * gi = (TConvexItem *)ab.col.convex; while (gi) { TConvex * convex = reinterpret_cast<TConvex *>(gi); gi = gi->next; if (convex == reinterpret_cast<TConvex *>(g)) { if (ab.col.convex == convex) { ab.col.convex = (TConvex*)gi; } ab.sim->geometryHeap.Dealloc(convex, 1); ab.col.convexCount--; if (ab.col.convexCount == 0) { ab.col.convex = NULL; if (ab.IsInRegion() && !ab.isCustomCD) ab.sim->region.RemoveBody(&ab); } return true; } } return false; } /**************************************************************************** * * neAnimatedBody::BeginIterateGeometry * ****************************************************************************/ void neAnimatedBody::BeginIterateGeometry() { CAST_THIS(neCollisionBody_, ab); ab.BeginIterateGeometry(); } /**************************************************************************** * * neAnimatedBody::GetNextGeometry * ****************************************************************************/ neGeometry * neAnimatedBody::GetNextGeometry() { CAST_THIS(neCollisionBody_, ab); return reinterpret_cast<neGeometry *>(ab.GetNextGeometry()); } /**************************************************************************** * * neAnimatedBody::BreakGeometry * ****************************************************************************/ neRigidBody * neAnimatedBody::BreakGeometry(neGeometry * g) { CAST_THIS(neCollisionBody_, ab); neRigidBody_ * newBody = ab.sim->CreateRigidBodyFromConvex((TConvex*)g, &ab); return (neRigidBody *)newBody; } /**************************************************************************** * * neAnimatedBody::UseCustomCollisionDetection * ****************************************************************************/ void neAnimatedBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius) { CAST_THIS(neCollisionBody_, ab); if (yes) { ab.obb = *obb; ab.col.boundingRadius = boundingRadius; ab.isCustomCD = yes; if (ab.isActive && !ab.IsInRegion()) { ab.sim->region.AddBody(&ab, NULL); } } else { ab.isCustomCD = yes; this->UpdateBoundingInfo(); if (ab.IsInRegion() && GetGeometryCount() == 0) { ab.sim->region.RemoveBody(&ab); } } } /**************************************************************************** * * neAnimatedBody::UseCustomCollisionDetection * ****************************************************************************/ neBool neAnimatedBody::UseCustomCollisionDetection() { CAST_THIS(neCollisionBody_, ab); return ab.isCustomCD; } /**************************************************************************** * * neAnimatedBody::AddSensor * ****************************************************************************/ neSensor * neAnimatedBody::AddSensor() { CAST_THIS(neRigidBodyBase, ab); neSensor_ * s = ab.AddSensor(); return reinterpret_cast<neSensor *>(s); } /**************************************************************************** * * neAnimatedBody::RemoveSensor * ****************************************************************************/ neBool neAnimatedBody::RemoveSensor(neSensor * s) { CAST_THIS(neRigidBodyBase, ab); if (!ab.sensors) return false; neSensorItem * si = (neSensorItem *)ab.sensors; while (si) { neSensor_ * sensor = (neSensor_ *) si; si = si->next; if (sensor == reinterpret_cast<neSensor_*>(s)) { //reinterpret_cast<neSensorItem *>(s)->Remove(); ab.sim->sensorHeap.Dealloc(sensor, 1); return true; } } return false; } /**************************************************************************** * * neAnimatedBody::BeginIterateSensor * ****************************************************************************/ void neAnimatedBody::BeginIterateSensor() { CAST_THIS(neRigidBodyBase, ab); ab.BeginIterateSensor(); } /**************************************************************************** * * neAnimatedBody::GetNextSensor * ****************************************************************************/ neSensor * neAnimatedBody::GetNextSensor() { CAST_THIS(neRigidBodyBase, ab); return reinterpret_cast<neSensor *>(ab.GetNextSensor()); } /**************************************************************************** * * neAnimatedBody::Active * ****************************************************************************/ void neAnimatedBody::Active(neBool yes, neRigidBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::Active * ****************************************************************************/ void neAnimatedBody::Active(neBool yes, neAnimatedBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::IsActive * ****************************************************************************/ neBool neAnimatedBody::Active() { CAST_THIS(neRigidBodyBase, ab); return ab.isActive; } /**************************************************************************** * * neRigidBody::GetMass * ****************************************************************************/ f32 neRigidBody::GetMass() { CAST_THIS(neRigidBody_, rb); return rb.mass; } /**************************************************************************** * * neRigidBody::SetMass * ****************************************************************************/ void neRigidBody::SetMass(f32 mass) { CAST_THIS(neRigidBody_, rb); ASSERT(neIsFinite(mass)); rb.mass = mass; rb.oneOnMass = 1.0f / mass; } /**************************************************************************** * * neRigidBody::SetInertiaTensor * ****************************************************************************/ void neRigidBody::SetInertiaTensor(const neM3 & tensor) { CAST_THIS(neRigidBody_, rb); rb.Ibody = tensor; rb.IbodyInv.SetInvert(tensor); //ASSERT(tensor.Invert(rb.IbodyInv)); } /**************************************************************************** * * neRigidBody::SetInertiaTensor * ****************************************************************************/ void neRigidBody::SetInertiaTensor(const neV3 & tensor) { CAST_THIS(neRigidBody_, rb); neM3 i; i.SetIdentity(); i[0][0] = tensor[0]; i[1][1] = tensor[1]; i[2][2] = tensor[2]; rb.Ibody = i; rb.IbodyInv.SetInvert(rb.Ibody); } /**************************************************************************** * * neRigidBody::SetCollisionID * ****************************************************************************/ void neRigidBody::SetCollisionID(s32 cid) { CAST_THIS(neRigidBodyBase, rb); rb.cid = cid; } /**************************************************************************** * * neRigidBody::GetCollisionID * ****************************************************************************/ s32 neRigidBody::GetCollisionID() { CAST_THIS(neRigidBodyBase, rb); return rb.cid; } /**************************************************************************** * * neRigidBody::SetUserData * ****************************************************************************/ void neRigidBody::SetUserData(u32 cookies) { CAST_THIS(neRigidBodyBase, rb); rb.cookies = cookies; } /**************************************************************************** * * neRigidBody::GetUserData * ****************************************************************************/ u32 neRigidBody::GetUserData() { CAST_THIS(neRigidBodyBase, rb); return rb.cookies; } /**************************************************************************** * * neRigidBody::GetGeometryCount * ****************************************************************************/ s32 neRigidBody::GetGeometryCount() { CAST_THIS(neRigidBodyBase, rb); return rb.col.convexCount; } void neRigidBody::SetLinearDamping(f32 damp) { CAST_THIS(neRigidBody_, rb); rb.linearDamp = neAbs(damp); } f32 neRigidBody::GetLinearDamping() { CAST_THIS(neRigidBody_, rb); return rb.linearDamp; } void neRigidBody::SetAngularDamping(f32 damp) { CAST_THIS(neRigidBody_, rb); rb.angularDamp = neAbs(damp); } f32 neRigidBody::GetAngularDamping() { CAST_THIS(neRigidBody_, rb); return rb.angularDamp; } void neRigidBody::SetSleepingParameter(f32 sleepingParam) { CAST_THIS(neRigidBody_, rb); rb.sleepingParam = sleepingParam; } f32 neRigidBody::GetSleepingParameter() { CAST_THIS(neRigidBody_, rb); return rb.sleepingParam; } /**************************************************************************** * * neRigidBody::GetGeometry * ****************************************************************************/ /* neGeometry * neRigidBody::GetGeometry(s32 index) { CAST_THIS(neRigidBodyBase, rb); return reinterpret_cast<neGeometry*>(rb.GetConvex(index)); } */ /**************************************************************************** * * neRigidBody::SetGeometry * ****************************************************************************/ /* void neRigidBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray) { //todo } */ /**************************************************************************** * * neRigidBody::GetPos * ****************************************************************************/ neV3 neRigidBody::GetPos() { CAST_THIS(neRigidBody_, rb); return rb.GetPos(); } /**************************************************************************** * * neRigidBody::SetPos * ****************************************************************************/ void neRigidBody::SetPos(const neV3 & p) { CAST_THIS(neRigidBody_, rb); rb.SetPos(p); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::GetRotationM3 * ****************************************************************************/ neM3 neRigidBody::GetRotationM3() { CAST_THIS(neRigidBody_, rb); return rb.State().rot(); } /**************************************************************************** * * neRigidBody::GetRotationQ * ****************************************************************************/ neQ neRigidBody::GetRotationQ() { CAST_THIS(neRigidBody_, rb); return rb.State().q; } /**************************************************************************** * * neRigidBody::SetRotation * ****************************************************************************/ void neRigidBody::SetRotation(const neM3 & m) { ASSERT(m.IsOrthogonalNormal()); CAST_THIS(neRigidBody_, rb); rb.State().rot() = m; rb.State().q.SetupFromMatrix3(m); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::SetRotation * ****************************************************************************/ void neRigidBody::SetRotation(const neQ & q) { CAST_THIS(neRigidBody_, rb); rb.State().q = q; rb.State().rot() = q.BuildMatrix3(); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::GetTransform * ****************************************************************************/ neT3 neRigidBody::GetTransform() { CAST_THIS(neRigidBody_, rb); rb.State().b2w.rot[0].v[3] = 0.0f; rb.State().b2w.rot[1].v[3] = 0.0f; rb.State().b2w.rot[2].v[3] = 0.0f; rb.State().b2w.pos.v[3] = 1.0f; return rb.State().b2w; } /**************************************************************************** * * neRigidBody::GetVelocity * ****************************************************************************/ neV3 neRigidBody::GetVelocity() { CAST_THIS(neRigidBody_, rb); return rb.Derive().linearVel; } /**************************************************************************** * * neRigidBody::SetVelocity * ****************************************************************************/ void neRigidBody::SetVelocity(const neV3 & v) { CAST_THIS(neRigidBody_, rb); rb.Derive().linearVel = v; rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::GetAngularVelocity * ****************************************************************************/ neV3 neRigidBody::GetAngularVelocity() { CAST_THIS(neRigidBody_, rb); return rb.Derive().angularVel; } /**************************************************************************** * * neRigidBody::GetAngularMomentum * ****************************************************************************/ neV3 neRigidBody::GetAngularMomentum() { CAST_THIS(neRigidBody_, rb); return rb.State().angularMom; } /**************************************************************************** * * neRigidBody::SetAngularMomemtum * ****************************************************************************/ void neRigidBody::SetAngularMomentum(const neV3& am) { CAST_THIS(neRigidBody_, rb); rb.SetAngMom(am); rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::GetVelocityAtPoint * ****************************************************************************/ neV3 neRigidBody::GetVelocityAtPoint(const neV3 & pt) { CAST_THIS(neRigidBody_, rb); return rb.VelocityAtPoint(pt); } /**************************************************************************** * * neRigidBody::UpdateBoundingInfo * ****************************************************************************/ void neRigidBody::UpdateBoundingInfo() { CAST_THIS(neRigidBodyBase, rb); rb.RecalcBB(); } /**************************************************************************** * * neRigidBody::UpdateInertiaTensor * ****************************************************************************/ void neRigidBody::UpdateInertiaTensor() { CAST_THIS(neRigidBody_, rb); rb.RecalcInertiaTensor(); } /**************************************************************************** * * neRigidBody::SetForce * ****************************************************************************/ void neRigidBody::SetForce(const neV3 & force, const neV3 & pos) { CAST_THIS(neRigidBody_, rb); if (force.IsConsiderZero()) { rb.force = force; rb.torque = ((pos - rb.GetPos()).Cross(force)); return; } rb.force = force; rb.torque = ((pos - rb.GetPos()).Cross(force)); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::SetForce * ****************************************************************************/ void neRigidBody::SetTorque(const neV3 & torque) { CAST_THIS(neRigidBody_, rb); if (torque.IsConsiderZero()) { rb.torque = torque; return; } rb.torque = torque; rb.WakeUp(); } /**************************************************************************** * * neRigidBody::ApplyForceCOG * ****************************************************************************/ void neRigidBody::SetForce(const neV3 & force) { CAST_THIS(neRigidBody_, rb); if (force.IsConsiderZero()) { rb.force = force; return; } rb.force = force; rb.WakeUp(); } neV3 neRigidBody::GetForce() { CAST_THIS(neRigidBody_, rb); return rb.force; } neV3 neRigidBody::GetTorque() { CAST_THIS(neRigidBody_, rb); return rb.torque; } /**************************************************************************** * * neRigidBody::AddImpulse * ****************************************************************************/ void neRigidBody::ApplyImpulse(const neV3 & impulse) { CAST_THIS(neRigidBody_, rb); neV3 dv = impulse * rb.oneOnMass; rb.Derive().linearVel += dv; //rb.WakeUp(); rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::AddImpulseWithTwist * ****************************************************************************/ void neRigidBody::ApplyImpulse(const neV3 & impulse, const neV3 & pos) { CAST_THIS(neRigidBody_, rb); neV3 dv = impulse * rb.oneOnMass; neV3 da = (pos - rb.GetPos()).Cross(impulse); rb.Derive().linearVel += dv; neV3 newAM = rb.State().angularMom + da; rb.SetAngMom(newAM); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::ApplyTwist * ****************************************************************************/ void neRigidBody::ApplyTwist(const neV3 & twist) { CAST_THIS(neRigidBody_, rb); neV3 newAM = twist; rb.SetAngMom(newAM); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::AddController * ****************************************************************************/ neRigidBodyController * neRigidBody::AddController(neRigidBodyControllerCallback * controller, s32 period) { CAST_THIS(neRigidBody_, rb); return (neRigidBodyController *)rb.AddController(controller, period); } /**************************************************************************** * * neRigidBody::RemoveController * ****************************************************************************/ neBool neRigidBody::RemoveController(neRigidBodyController * rbController) { CAST_THIS(neRigidBody_, rb); if (!rb.controllers) return false; neControllerItem * ci = (neControllerItem *)rb.controllers; while (ci) { neController * con = reinterpret_cast<neController *>(ci); ci = ci->next; if (con == reinterpret_cast<neController *>(rbController)) { //reinterpret_cast<neControllerItem *>(con)->Remove(); rb.sim->controllerHeap.Dealloc(con, 1); return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateController * ****************************************************************************/ void neRigidBody::BeginIterateController() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateController(); } /**************************************************************************** * * neRigidBody::GetNextController * ****************************************************************************/ neRigidBodyController * neRigidBody::GetNextController() { CAST_THIS(neRigidBody_, rb); return (neRigidBodyController *)rb.GetNextController(); } /**************************************************************************** * * neRigidBody::GravityEnable * ****************************************************************************/ void neRigidBody::GravityEnable(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.GravityEnable(yes); } /**************************************************************************** * * neRigidBody::GravityEnable * ****************************************************************************/ neBool neRigidBody::GravityEnable() { CAST_THIS(neRigidBody_, rb); return rb.gravityOn; } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ void neRigidBody::CollideConnected(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.CollideConnected(yes); } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ neBool neRigidBody::CollideConnected() { CAST_THIS(neRigidBody_, rb); return rb.CollideConnected(); } /**************************************************************************** * * neRigidBody::CollideDirectlyConnected * ****************************************************************************/ void neRigidBody::CollideDirectlyConnected(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.isCollideDirectlyConnected = yes; } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ neBool neRigidBody::CollideDirectlyConnected() { CAST_THIS(neRigidBody_, rb); return rb.isCollideDirectlyConnected; } /**************************************************************************** * * neRigidBody::AddGeometry * ****************************************************************************/ neGeometry * neRigidBody::AddGeometry() { CAST_THIS(neRigidBody_, rb); TConvex * g = rb.AddGeometry(); return reinterpret_cast<neGeometry *>(g); } /**************************************************************************** * * neRigidBody::RemoveGeometry * ****************************************************************************/ neBool neRigidBody::RemoveGeometry(neGeometry * g) { CAST_THIS(neRigidBody_, rb); if (!rb.col.convex) return false; TConvexItem * gi = (TConvexItem *)rb.col.convex; while (gi) { TConvex * convex = reinterpret_cast<TConvex *>(gi); gi = gi->next; if (convex == reinterpret_cast<TConvex *>(g)) { if (rb.col.convex == convex) { rb.col.convex = (TConvex*)gi; } rb.sim->geometryHeap.Dealloc(convex, 1); rb.col.convexCount--; if (rb.col.convexCount == 0) { rb.col.convex = NULL; if (rb.IsInRegion() && !rb.isCustomCD) rb.sim->region.RemoveBody(&rb); } return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateGeometry * ****************************************************************************/ void neRigidBody::BeginIterateGeometry() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateGeometry(); } /**************************************************************************** * * neRigidBody::GetNextGeometry * ****************************************************************************/ neGeometry * neRigidBody::GetNextGeometry() { CAST_THIS(neRigidBody_, rb); return reinterpret_cast<neGeometry *>(rb.GetNextGeometry()); } /**************************************************************************** * * neRigidBody::BreakGeometry * ****************************************************************************/ neRigidBody * neRigidBody::BreakGeometry(neGeometry * g) { CAST_THIS(neRigidBody_, rb); neRigidBody_ * newBody = rb.sim->CreateRigidBodyFromConvex((TConvex*)g, &rb); return (neRigidBody *)newBody; } /**************************************************************************** * * neRigidBody::UseCustomCollisionDetection * ****************************************************************************/ void neRigidBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius) { CAST_THIS(neRigidBody_, rb); if (yes) { rb.obb = *obb; rb.col.boundingRadius = boundingRadius; rb.isCustomCD = yes; if (rb.isActive && !rb.IsInRegion()) { rb.sim->region.AddBody(&rb, NULL); } } else { rb.isCustomCD = yes; this->UpdateBoundingInfo(); if (rb.IsInRegion() && GetGeometryCount() == 0) { rb.sim->region.RemoveBody(&rb); } } } /**************************************************************************** * * neRigidBody::UseCustomCollisionDetection * ****************************************************************************/ neBool neRigidBody::UseCustomCollisionDetection() { CAST_THIS(neRigidBody_, rb); return rb.isCustomCD; } /**************************************************************************** * * neRigidBody::AddSensor * ****************************************************************************/ neSensor * neRigidBody::AddSensor() { CAST_THIS(neRigidBody_, rb); neSensor_ * s = rb.AddSensor(); return reinterpret_cast<neSensor *>(s); } /**************************************************************************** * * neRigidBody::RemoveSensor * ****************************************************************************/ neBool neRigidBody::RemoveSensor(neSensor * s) { CAST_THIS(neRigidBody_, rb); if (!rb.sensors) return false; neSensorItem * si = (neSensorItem *)rb.sensors; while (si) { neSensor_ * sensor = reinterpret_cast<neSensor_ *>(si); si = si->next; if (sensor == reinterpret_cast<neSensor_ *>(s)) { //reinterpret_cast<neSensorItem *>(s)->Remove(); rb.sim->sensorHeap.Dealloc(sensor, 1); return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateSensor * ****************************************************************************/ void neRigidBody::BeginIterateSensor() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateSensor(); } /**************************************************************************** * * neRigidBody::GetNextSensor * ****************************************************************************/ neSensor * neRigidBody::GetNextSensor() { CAST_THIS(neRigidBody_, rb); return reinterpret_cast<neSensor *>(rb.GetNextSensor()); } /**************************************************************************** * * neRigidBody::Active * ****************************************************************************/ void neRigidBody::Active(neBool yes, neRigidBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neRigidBody::Active * ****************************************************************************/ void neRigidBody::Active(neBool yes, neAnimatedBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::IsActive * ****************************************************************************/ neBool neRigidBody::Active() { CAST_THIS(neRigidBodyBase, ab); return ab.isActive; } neBool neRigidBody::IsIdle() { CAST_THIS(neRigidBody_, rb); return (rb.status == neRigidBody_::NE_RBSTATUS_IDLE); } /**************************************************************************** * * neSimulator::CreateSimulator * ****************************************************************************/ neSimulator * neSimulator::CreateSimulator(const neSimulatorSizeInfo & sizeInfo, neAllocatorAbstract * alloc, const neV3 * grav) { neFixedTimeStepSimulator * s = new neFixedTimeStepSimulator(sizeInfo, alloc, grav); return reinterpret_cast<neSimulator*>(s); } /**************************************************************************** * * neSimulator::DestroySimulator(neSimulator * sim); * ****************************************************************************/ void neSimulator::DestroySimulator(neSimulator * sim) { neFixedTimeStepSimulator * s = reinterpret_cast<neFixedTimeStepSimulator *>(sim); delete s; } /**************************************************************************** * * neSimulator::Gravity * ****************************************************************************/ neV3 neSimulator::Gravity() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.gravity; } /**************************************************************************** * * neSimulator::Gravity * ****************************************************************************/ void neSimulator::Gravity(const neV3 & g) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetGravity(g); /* sim.gravity = g; sim.gravityVector = g; sim.gravityVector.Normalize(); */ } /**************************************************************************** * * neSimulator::CreateRigidBody * ****************************************************************************/ neRigidBody * neSimulator::CreateRigidBody() { CAST_THIS(neFixedTimeStepSimulator, sim); neRigidBody_ * ret = sim.CreateRigidBody(); return reinterpret_cast<neRigidBody *>(ret); } /**************************************************************************** * * neSimulator::CreateRigidParticle * ****************************************************************************/ neRigidBody * neSimulator::CreateRigidParticle() { CAST_THIS(neFixedTimeStepSimulator, sim); neRigidBody_ * ret = sim.CreateRigidBody(true); return reinterpret_cast<neRigidBody *>(ret); } /**************************************************************************** * * neSimulator::CreateCollisionBody() * ****************************************************************************/ neAnimatedBody * neSimulator::CreateAnimatedBody() { CAST_THIS(neFixedTimeStepSimulator, sim); neCollisionBody_ * ret = sim.CreateCollisionBody(); return reinterpret_cast<neAnimatedBody *>(ret); } /**************************************************************************** * * neSimulator::FreeBody * ****************************************************************************/ void neSimulator::FreeRigidBody(neRigidBody * body) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Free(reinterpret_cast<neRigidBody_*>(body)); } /**************************************************************************** * * neSimulator::FreeCollisionBody * ****************************************************************************/ void neSimulator::FreeAnimatedBody(neAnimatedBody * body) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Free(reinterpret_cast<neRigidBody_*>(body)); } /**************************************************************************** * * neSimulator::GetCollisionTable * ****************************************************************************/ neCollisionTable * neSimulator::GetCollisionTable() { CAST_THIS(neFixedTimeStepSimulator, sim); return (neCollisionTable *)(&sim.colTable); } /**************************************************************************** * * neSimulator::GetMaterial * ****************************************************************************/ bool neSimulator::SetMaterial(s32 index, f32 friction, f32 restitution) { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.SetMaterial(index, friction, restitution, 0.0f); } /**************************************************************************** * * neSimulator::GetMaterial * ****************************************************************************/ bool neSimulator::GetMaterial(s32 index, f32& friction, f32& restitution) { CAST_THIS(neFixedTimeStepSimulator, sim); f32 density; return sim.GetMaterial(index, friction, restitution, density); } /**************************************************************************** * * neSimulator::Advance * ****************************************************************************/ void neSimulator::Advance(f32 sec, s32 step, nePerformanceReport * perfReport) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Advance(sec, step, perfReport); } void neSimulator::Advance(f32 sec, f32 minTimeStep, f32 maxTimeStep, nePerformanceReport * perfReport) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Advance(sec, minTimeStep, maxTimeStep, perfReport); } /**************************************************************************** * * neSimulator::SetTerrainMesh * ****************************************************************************/ void neSimulator::SetTerrainMesh(neTriangleMesh * tris) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetTerrainMesh(tris); } void neSimulator::FreeTerrainMesh() { CAST_THIS(neFixedTimeStepSimulator, sim); sim.FreeTerrainMesh(); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neRigidBody * bodyB) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; if (!bodyB) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); constr->bodyB = (neRigidBodyBase*)bodyB; neRigidBody_ * bb = (neRigidBody_*)bodyB; bb->constraintCollection.Add(&constr->bodyBHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neAnimatedBody * bodyB) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; if (!bodyB) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); constr->bodyB = (neRigidBodyBase*)bodyB; neRigidBodyBase * bb = (neRigidBodyBase*)bodyB; bb->constraintCollection.Add(&constr->bodyBHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::FreeJoint * ****************************************************************************/ void neSimulator::FreeJoint(neJoint * constraint) { CAST_THIS(neFixedTimeStepSimulator, sim); _neConstraint * c = (_neConstraint *)constraint; ASSERT(sim.constraintHeap.CheckBelongAndInUse(c)); if (c->bodyA) { c->bodyA->constraintCollection.Remove(&c->bodyAHandle); if (c->bodyB) c->bodyB->constraintCollection.Remove(&c->bodyBHandle); neConstraintHeader * h = c->bodyA->GetConstraintHeader(); if (h) { h->Remove(c); h->flag = neConstraintHeader::FLAG_NEED_REORG; } sim.constraintHeap.Dealloc(c, 1); if (c->bodyA->constraintCollection.count == 0) c->bodyA->RemoveConstraintHeader(); if (c->bodyB && c->bodyB->constraintCollection.count == 0) c->bodyB->RemoveConstraintHeader(); } else { sim.constraintHeap.Dealloc(c, 1); } } /**************************************************************************** * * neSimulator::SetCollisionCallback * ****************************************************************************/ void neSimulator::SetCollisionCallback(neCollisionCallback * fn) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetCollisionCallback(fn); } /**************************************************************************** * * neSimulator::GetCollisionCallback * ****************************************************************************/ neCollisionCallback * neSimulator::GetCollisionCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.collisionCallback; } /**************************************************************************** * * neSimulator::SetBreakageCallback * ****************************************************************************/ void neSimulator::SetBreakageCallback(neBreakageCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.breakageCallback = cb; } /**************************************************************************** * * neSimulator::GetBreakageCallback * ****************************************************************************/ neBreakageCallback * neSimulator::GetBreakageCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.breakageCallback; } /**************************************************************************** * * neSimulator::SetTerrainTriangleQueryCallback * ****************************************************************************/ void neSimulator::SetTerrainTriangleQueryCallback(neTerrainTriangleQueryCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.terrainQueryCallback = cb; } /**************************************************************************** * * neSimulator::GetTerrainTriangleQueryCallback * ****************************************************************************/ neTerrainTriangleQueryCallback * neSimulator::GetTerrainTriangleQueryCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.terrainQueryCallback; } /**************************************************************************** * * neSimulator::SetCustomCDRB2RBCallback * ****************************************************************************/ void neSimulator::SetCustomCDRB2RBCallback(neCustomCDRB2RBCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.customCDRB2RBCallback = cb; } /**************************************************************************** * * neSimulator::GetCustomCDRB2RBCallback * ****************************************************************************/ neCustomCDRB2RBCallback * neSimulator::GetCustomCDRB2RBCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.customCDRB2RBCallback; } /**************************************************************************** * * neSimulator::SetCustomCDRB2ABCallback * ****************************************************************************/ void neSimulator::SetCustomCDRB2ABCallback(neCustomCDRB2ABCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.customCDRB2ABCallback = cb; } /**************************************************************************** * * neSimulator::GetCustomCDRB2ABCallback * ****************************************************************************/ neCustomCDRB2ABCallback * neSimulator::GetCustomCDRB2ABCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.customCDRB2ABCallback; } /**************************************************************************** * * neSimulator::SetLogOutputCallback * ****************************************************************************/ void neSimulator::SetLogOutputCallback(neLogOutputCallback * fn) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetLogOutputCallback(fn); } /* f32 neSimulator::GetMagicNumber() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.magicNumber; } */ /**************************************************************************** * * neSimulator::GetLogOutputCallback * ****************************************************************************/ neLogOutputCallback * neSimulator::GetLogOutputCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.logCallback; } /**************************************************************************** * * neSimulator::SetLogOutputLevel * ****************************************************************************/ void neSimulator::SetLogOutputLevel(LOG_OUTPUT_LEVEL lvl) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetLogOutputLevel(lvl); } /**************************************************************************** * * neSimulator::GetCurrentSizeInfo * ****************************************************************************/ neSimulatorSizeInfo neSimulator::GetCurrentSizeInfo() { CAST_THIS(neFixedTimeStepSimulator, sim); neSimulatorSizeInfo ret; ret.rigidBodiesCount = sim.rigidBodyHeap.GetUsedCount(); ret.animatedBodiesCount = sim.collisionBodyHeap.GetUsedCount(); ret.rigidParticleCount = sim.rigidParticleHeap.GetUsedCount(); ret.controllersCount = sim.controllerHeap.GetUsedCount(); ret.overlappedPairsCount = sim.region.overlappedPairs.GetUsedCount(); ret.geometriesCount = sim.geometryHeap.GetUsedCount(); ret.constraintsCount = sim.constraintHeap.GetUsedCount(); ret.constraintSetsCount = sim.constraintHeaders.GetUsedCount(); // ret.constraintBufferSize = sim.miniConstraintHeap.GetUsedCount(); ret.sensorsCount = sim.sensorHeap.GetUsedCount(); ret.terrainNodesStartCount = sim.region.terrainTree.nodes.GetUsedCount(); ret.terrainNodesGrowByCount = sim.sizeInfo.terrainNodesGrowByCount; return ret; } /**************************************************************************** * * neSimulator::GetStartSizeInfo * ****************************************************************************/ neSimulatorSizeInfo neSimulator::GetStartSizeInfo() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.sizeInfo; } /**************************************************************************** * * neSimulator::GetMemoryUsage * ****************************************************************************/ void neSimulator::GetMemoryAllocated(s32 & memoryAllocated) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.GetMemoryAllocated(memoryAllocated); } /**************************************************************************** * * neJoint::SetType * ****************************************************************************/ void neJoint::SetType(ConstraintType t) { CAST_THIS(_neConstraint, c); c.SetType(t); } /**************************************************************************** * * neJoint::GetType * ****************************************************************************/ neJoint::ConstraintType neJoint::GetType() { CAST_THIS(_neConstraint, c); return c.type; } /**************************************************************************** * * neJoint::GetRigidBodyA * ****************************************************************************/ neRigidBody * neJoint::GetRigidBodyA() { CAST_THIS(_neConstraint, c); return reinterpret_cast<neRigidBody *>(c.bodyA); } /**************************************************************************** * * neJoint::GetRigidBodyB * ****************************************************************************/ neRigidBody * neJoint::GetRigidBodyB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) return NULL; if (c.bodyB->AsCollisionBody()) return NULL; return reinterpret_cast<neRigidBody *>(c.bodyB); } /**************************************************************************** * * neJoint::GetAnimatedBodyB * ****************************************************************************/ neAnimatedBody * neJoint::GetAnimatedBodyB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) return NULL; if (c.bodyB->AsRigidBody()) return NULL; return reinterpret_cast<neAnimatedBody *>(c.bodyB); } /**************************************************************************** * * neJoint::SetJointFrameA * ****************************************************************************/ void neJoint::SetJointFrameA(const neT3 & frameA) { CAST_THIS(_neConstraint, c); c.frameA = frameA; } /**************************************************************************** * * neJoint::SetJointFrameB * ****************************************************************************/ void neJoint::SetJointFrameB(const neT3 & frameB) { CAST_THIS(_neConstraint, c); c.frameB = frameB; } void neJoint::SetJointFrameWorld(const neT3 & frame) { CAST_THIS(_neConstraint, c); neT3 w2b; w2b = c.bodyA->GetB2W().FastInverse(); c.frameA = w2b * frame; if (!c.bodyB) { c.frameB = frame; return; } w2b = c.bodyB->GetB2W().FastInverse(); c.frameB = w2b * frame; } /**************************************************************************** * * neJoint::GetJointFrameA * ****************************************************************************/ neT3 neJoint::GetJointFrameA() { CAST_THIS(_neConstraint, c); if (!c.bodyA) { return c.frameA; } neT3 ret; ret = c.bodyA->State().b2w * c.frameA; return ret; } /**************************************************************************** * * neJoint::GetJointFrameB * ****************************************************************************/ neT3 neJoint::GetJointFrameB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) { return c.frameB; } neT3 ret; neCollisionBody_ * cb = c.bodyB->AsCollisionBody(); if (cb) { ret = cb->b2w * c.frameB; } else { neRigidBody_ * rb = c.bodyB->AsRigidBody(); ret = rb->State().b2w * c.frameB; } return ret; } /**************************************************************************** * * neJoint::SetJointLength * ****************************************************************************/ void neJoint::SetJointLength(f32 length) { CAST_THIS(_neConstraint, c); c.jointLength = length; } /**************************************************************************** * * neJoint::GetJointLength * ****************************************************************************/ f32 neJoint::GetJointLength() { CAST_THIS(_neConstraint, c); return c.jointLength; } /**************************************************************************** * * neJoint::Enable * ****************************************************************************/ void neJoint::Enable(neBool yes) { CAST_THIS(_neConstraint, c); c.Enable(yes); } /**************************************************************************** * * neJoint::IsEnable * ****************************************************************************/ neBool neJoint::Enable() { CAST_THIS(_neConstraint, c); return c.enable; } /**************************************************************************** * * neJoint::InfiniteMassB * ****************************************************************************/ /* void neJoint::InfiniteMassB(neBool yes) { CAST_THIS(_neConstraint, c); c.InfiniteMassB(yes); } */ /**************************************************************************** * * neJoint::SetDampingFactor * ****************************************************************************/ void neJoint::SetDampingFactor(f32 damp) { CAST_THIS(_neConstraint, c); c.jointDampingFactor = damp; } /**************************************************************************** * * neJoint::GetDampingFactor * ****************************************************************************/ f32 neJoint::GetDampingFactor() { CAST_THIS(_neConstraint, c); return c.jointDampingFactor; } /**************************************************************************** * * neJoint::SetEpsilon * ****************************************************************************/ void neJoint::SetEpsilon(f32 t) { CAST_THIS(_neConstraint, c); c.accuracy = t; } /**************************************************************************** * * neJoint::GetEpsilon * ****************************************************************************/ f32 neJoint::GetEpsilon() { CAST_THIS(_neConstraint, c); if (c.accuracy <= 0.0f) return DEFAULT_CONSTRAINT_EPSILON; return c.accuracy; } /**************************************************************************** * * neJoint::SetIteration2 * ****************************************************************************/ void neJoint::SetIteration(s32 i) { CAST_THIS(_neConstraint, c); c.iteration = i; } /**************************************************************************** * * neJoint::GetIteration2 * ****************************************************************************/ s32 neJoint::GetIteration() { CAST_THIS(_neConstraint, c); return c.iteration; } /**************************************************************************** * * neJoint::GetUpperLimit * ****************************************************************************/ f32 neJoint::GetUpperLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].upperLimit; } /**************************************************************************** * * neJoint::SetUpperLimit * ****************************************************************************/ void neJoint::SetUpperLimit(f32 upperLimit) { CAST_THIS(_neConstraint, c); c.limitStates[0].upperLimit = upperLimit; } /**************************************************************************** * * neJoint::GetLowerLimit * ****************************************************************************/ f32 neJoint::GetLowerLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].lowerLimit; } /**************************************************************************** * * neJoint::SetLowerLimit * ****************************************************************************/ void neJoint::SetLowerLimit(f32 lowerLimit) { CAST_THIS(_neConstraint, c); c.limitStates[0].lowerLimit = lowerLimit; } /**************************************************************************** * * neJoint::IsEnableLimit * ****************************************************************************/ neBool neJoint::EnableLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].enableLimit; } /**************************************************************************** * * neJoint::EnableLimite * ****************************************************************************/ void neJoint::EnableLimit(neBool yes) { CAST_THIS(_neConstraint, c); c.limitStates[0].enableLimit = yes; } /**************************************************************************** * * neJoint::GetUpperLimit2 * ****************************************************************************/ f32 neJoint::GetUpperLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].upperLimit; } /**************************************************************************** * * neJoint::SetUpperLimit2 * ****************************************************************************/ void neJoint::SetUpperLimit2(f32 upperLimit) { CAST_THIS(_neConstraint, c); c.limitStates[1].upperLimit = upperLimit; } /**************************************************************************** * * neJoint::GetLowerLimit2 * ****************************************************************************/ f32 neJoint::GetLowerLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].lowerLimit; } /**************************************************************************** * * neJoint::SetLowerLimit2 * ****************************************************************************/ void neJoint::SetLowerLimit2(f32 lowerLimit) { CAST_THIS(_neConstraint, c); c.limitStates[1].lowerLimit = lowerLimit; } /**************************************************************************** * * neJoint::IsEnableLimit2 * ****************************************************************************/ neBool neJoint::EnableLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].enableLimit; } /**************************************************************************** * * neJoint::EnableMotor * ****************************************************************************/ neBool neJoint::EnableMotor() { CAST_THIS(_neConstraint, c); return c.motors[0].enable; } /**************************************************************************** * * neJoint::EnableMotor * ****************************************************************************/ void neJoint::EnableMotor(neBool yes) { CAST_THIS(_neConstraint, c); c.motors[0].enable = yes; } /**************************************************************************** * * neJoint::SetMotor * ****************************************************************************/ void neJoint::SetMotor(MotorType motorType, f32 desireValue, f32 maxForce) { CAST_THIS(_neConstraint, c); c.motors[0].motorType = motorType; c.motors[0].desireVelocity = desireValue; c.motors[0].maxForce = neAbs(maxForce); } /**************************************************************************** * * neJoint::GetMotor * ****************************************************************************/ void neJoint::GetMotor(MotorType & motorType, f32 & desireValue, f32 & maxForce) { CAST_THIS(_neConstraint, c); motorType = c.motors[0].motorType; desireValue = c.motors[0].desireVelocity; maxForce = c.motors[0].maxForce; } /**************************************************************************** * * neJoint::EnableMotor2 * ****************************************************************************/ neBool neJoint::EnableMotor2() { CAST_THIS(_neConstraint, c); return c.motors[1].enable; } /**************************************************************************** * * neJoint::EnableMotor2 * ****************************************************************************/ void neJoint::EnableMotor2(neBool yes) { CAST_THIS(_neConstraint, c); c.motors[1].enable = yes; } /**************************************************************************** * * neJoint::SetMotor2 * ****************************************************************************/ void neJoint::SetMotor2(MotorType motorType, f32 desireValue, f32 maxForce) { CAST_THIS(_neConstraint, c); c.motors[1].motorType = motorType; c.motors[1].desireVelocity = desireValue; c.motors[1].maxForce = neAbs(maxForce); } /**************************************************************************** * * neJoint::GetMotor2 * ****************************************************************************/ void neJoint::GetMotor2(MotorType & motorType, f32 & desireValue, f32 & maxForce) { CAST_THIS(_neConstraint, c); motorType = c.motors[1].motorType; desireValue = c.motors[1].desireVelocity; maxForce = c.motors[1].maxForce; } /**************************************************************************** * * neJoint::EnableLimite * ****************************************************************************/ void neJoint::EnableLimit2(neBool yes) { CAST_THIS(_neConstraint, c); c.limitStates[1].enableLimit = yes; } /**************************************************************************** * * neJoint::AddController * ****************************************************************************/ neJointController * neJoint::AddController(neJointControllerCallback * controller, s32 period) { CAST_THIS(_neConstraint, c); return (neJointController *)c.AddController(controller, period); } /**************************************************************************** * * neJoint::RemoveController * ****************************************************************************/ neBool neJoint::RemoveController(neJointController * jController) { CAST_THIS(_neConstraint, c); if (!c.controllers) return false; neControllerItem * ci = (neControllerItem *)c.controllers; while (ci) { neController * con = reinterpret_cast<neController *>(ci); ci = ci->next; if (con == reinterpret_cast<neController *>(jController)) { //reinterpret_cast<neControllerItem *>(con)->Remove(); c.sim->controllerHeap.Dealloc(con, 1); return true; } } return false; } /**************************************************************************** * * neJoint::BeginIterateController * ****************************************************************************/ void neJoint::BeginIterateController() { CAST_THIS(_neConstraint, c); c.BeginIterateController(); } /**************************************************************************** * * neJoint::GetNextController * ****************************************************************************/ neJointController * neJoint::GetNextController() { CAST_THIS(_neConstraint, c); return (neJointController *)c.GetNextController(); } /**************************************************************************** * * neJoint::SetBSPoints * ****************************************************************************/ /* neBool neJoint::SetBSPoints(const neV3 & pointA, const neV3 & pointB) { CAST_THIS(_neConstraint, c); if (c.type != NE_Constraint_BALLSOCKET) return false; c.cpointsA[0].PtBody() = pointA; c.cpointsB[0].PtBody() = pointB; return true; } */ /**************************************************************************** * * neJoint::SetHingePoints * ****************************************************************************/ /* neBool neJoint::SetHingePoints(const neV3 & pointA1, const neV3 & pointA2, const neV3 & pointB1, const neV3 & pointB2) { CAST_THIS(_neConstraint, c); if (c.type != NE_Constraint_HINGE) return false; c.cpointsA[0].PtBody() = pointA1; c.cpointsA[1].PtBody() = pointA2; c.cpointsB[0].PtBody() = pointB1; c.cpointsB[1].PtBody() = pointB2; return true; } */ /**************************************************************************** * * neSensor::SetLineSensor * ****************************************************************************/ void neSensor::SetLineSensor(const neV3 & pos, const neV3 & lineVector) { CAST_THIS(neSensor_, sensor); sensor.pos = pos; sensor.dir = lineVector; sensor.dirNormal = lineVector; sensor.dirNormal.Normalize(); sensor.length = lineVector.Length(); } /**************************************************************************** * * neSensor::SetUserData * ****************************************************************************/ void neSensor::SetUserData(u32 cookies) { CAST_THIS(neSensor_, sensor); sensor.cookies = cookies; } /**************************************************************************** * * neSensor::GetUserData * ****************************************************************************/ u32 neSensor::GetUserData() { CAST_THIS(neSensor_, sensor); return sensor.cookies; } /**************************************************************************** * * neSensor::GetLineNormal * ****************************************************************************/ neV3 neSensor::GetLineVector() { CAST_THIS(neSensor_, sensor); return sensor.dir; } /**************************************************************************** * * neSensor::GetLineNormal * ****************************************************************************/ neV3 neSensor::GetLineUnitVector() { CAST_THIS(neSensor_, sensor); return sensor.dirNormal ; } /**************************************************************************** * * neSensor::GetLinePos * ****************************************************************************/ neV3 neSensor::GetLinePos() { CAST_THIS(neSensor_, sensor); return sensor.pos; } /**************************************************************************** * * neSensor::GetDetectDepth * ****************************************************************************/ f32 neSensor::GetDetectDepth() { CAST_THIS(neSensor_, sensor); return sensor.depth; } /**************************************************************************** * * neSensor::GetDetectNormal * ****************************************************************************/ neV3 neSensor::GetDetectNormal() { CAST_THIS(neSensor_, sensor); return sensor.normal; } /**************************************************************************** * * neSensor::GetDetectContactPoint * ****************************************************************************/ neV3 neSensor::GetDetectContactPoint() { CAST_THIS(neSensor_, sensor); return sensor.contactPoint; } /**************************************************************************** * * neSensor::GetDetectRigidBody * ****************************************************************************/ neRigidBody * neSensor::GetDetectRigidBody() { CAST_THIS(neSensor_, sensor); if (!sensor.body) return NULL; if (sensor.body->AsCollisionBody()) return NULL; return (neRigidBody *)sensor.body; } /**************************************************************************** * * neSensor::GetDetectAnimatedBody * ****************************************************************************/ neAnimatedBody * neSensor::GetDetectAnimatedBody() { CAST_THIS(neSensor_, sensor); if (!sensor.body) return NULL; if (sensor.body->AsRigidBody()) return NULL; return (neAnimatedBody *)sensor.body; } /**************************************************************************** * * neSensor:: * ****************************************************************************/ s32 neSensor::GetDetectMaterial() { CAST_THIS(neSensor_, sensor); return sensor.materialID; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neRigidBody * neRigidBodyController::GetRigidBody() { CAST_THIS(neController, c); return (neRigidBody *)c.rb; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neV3 neRigidBodyController::GetControllerForce() { CAST_THIS(neController, c); return c.forceA; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neV3 neRigidBodyController::GetControllerTorque() { CAST_THIS(neController, c); return c.torqueA; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerForce(const neV3 & force) { CAST_THIS(neController, c); c.forceA = force; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerForceWithTorque(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceA = force; c.torqueA = ((pos - c.rb->GetPos()).Cross(force)); } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerTorque(const neV3 & torque) { CAST_THIS(neController, c); c.torqueA = torque; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neJoint * neJointController::GetJoint() { CAST_THIS(neController, c); return (neJoint *)c.constraint; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerForceBodyA() { CAST_THIS(neController, c); return c.forceA; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerForceBodyB() { CAST_THIS(neController, c); return c.forceB; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerTorqueBodyA() { CAST_THIS(neController, c); return c.torqueA; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerTorqueBodyB() { CAST_THIS(neController, c); return c.torqueB; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceBodyA(const neV3 & force) { CAST_THIS(neController, c); c.forceA = force; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceWithTorqueBodyA(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceA = force; c.torqueA = ((pos - c.constraint->bodyA->GetPos()).Cross(force)); } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceWithTorqueBodyB(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceB = force; if (c.constraint->bodyB && !c.constraint->bodyB->AsCollisionBody()) { neRigidBody_ * rb = (neRigidBody_*)c.constraint->bodyB; c.torqueB = ((pos - rb->GetPos()).Cross(force)); } } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceBodyB(const neV3 & force) { CAST_THIS(neController, c); c.forceB = force; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerTorqueBodyA(const neV3 & torque) { CAST_THIS(neController, c); c.torqueA = torque; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerTorqueBodyB(const neV3 & torque) { CAST_THIS(neController, c); c.torqueB = torque; } /**************************************************************************** * * neCollisionTable::Set * ****************************************************************************/ void neCollisionTable::Set(s32 collisionID1, s32 collisionID2, neReponseBitFlag response) { CAST_THIS(neCollisionTable_, ct); ct.Set(collisionID1, collisionID2, response); } /**************************************************************************** * * neCollisionTable::Get * ****************************************************************************/ neCollisionTable::neReponseBitFlag neCollisionTable::Get(s32 collisionID1, s32 collisionID2) { CAST_THIS(neCollisionTable_, ct); ASSERT(collisionID1 < NE_COLLISION_TABLE_MAX); ASSERT(collisionID2 < NE_COLLISION_TABLE_MAX); if (collisionID1 < NE_COLLISION_TABLE_MAX && collisionID2 < NE_COLLISION_TABLE_MAX) { return ct.table[collisionID1][collisionID2]; } else { return RESPONSE_IGNORE; } } /**************************************************************************** * * neCollisionTable::GetMaxCollisionID * ****************************************************************************/ s32 neCollisionTable::GetMaxCollisionID() { return NE_COLLISION_TABLE_MAX; } /**************************************************************************** * * Helper functions * ****************************************************************************/ /**************************************************************************** * * BoxInertiaTensor * ****************************************************************************/ neV3 neBoxInertiaTensor(const neV3 & boxSize, f32 mass) { return neBoxInertiaTensor(boxSize[0], boxSize[1], boxSize[2], mass); } neV3 neBoxInertiaTensor(f32 width, f32 height, f32 depth, f32 mass) { neV3 ret; f32 maxdim = width; if (height > maxdim) maxdim = height; if (depth > maxdim) maxdim = depth; #if 0 f32 xsq = width; f32 ysq = height; f32 zsq = depth; #else f32 xsq = maxdim; f32 ysq = maxdim; f32 zsq = maxdim; #endif xsq *= xsq; ysq *= ysq; zsq *= zsq; ret[0] = (ysq + zsq) * mass / 3.0f; ret[1] = (xsq + zsq) * mass / 3.0f; ret[2] = (xsq + ysq) * mass / 3.0f; return ret; } neV3 neSphereInertiaTensor(f32 diameter, f32 mass) { f32 radius = diameter * 0.5f; f32 value = 2.0f / 5.0f * mass * radius * radius; neV3 ret; ret.Set(value); return ret; } neV3 neCylinderInertiaTensor(f32 diameter, f32 height, f32 mass) { // if (height > diameter) // { // diameter = height; // } f32 radius = diameter * 0.5f; f32 radiusSq = radius * radius; f32 Ixz = 1.0f / 12.0f * mass * height * height + 0.25f * mass * radiusSq; f32 Iyy = 0.5f * mass * radiusSq; neV3 ret; ret.Set(Ixz, Iyy, Ixz); return ret; } /* neBool IsEnableLimit(); void EnableLimit(neBool yes); f32 GetUpperLimit(); void SetUpperLimit(f32 upperLimit); f32 GetLowerLimit(); void SetLowerLimit(f32 lowerLimit); */
23.601042
129
0.399534
netpipe
edc4d3e8316cf5389f8c279780ec97dff650f17e
4,851
cpp
C++
sensing/pointcloud_preprocessor/src/downsample_filter/voxel_grid_downsample_filter_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
sensing/pointcloud_preprocessor/src/downsample_filter/voxel_grid_downsample_filter_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
sensing/pointcloud_preprocessor/src/downsample_filter/voxel_grid_downsample_filter_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * 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 Willow Garage, Inc. 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. * * $Id: voxel_grid.cpp 35876 2011-02-09 01:04:36Z rusu $ * */ #include "pointcloud_preprocessor/downsample_filter/voxel_grid_downsample_filter_nodelet.hpp" #include <pcl/kdtree/kdtree_flann.h> #include <pcl/search/kdtree.h> #include <pcl/segmentation/segment_differences.h> #include <vector> namespace pointcloud_preprocessor { VoxelGridDownsampleFilterComponent::VoxelGridDownsampleFilterComponent( const rclcpp::NodeOptions & options) : Filter("VoxelGridDownsampleFilter", options) { // set initial parameters { voxel_size_x_ = static_cast<double>(declare_parameter("voxel_size_x", 0.3)); voxel_size_y_ = static_cast<double>(declare_parameter("voxel_size_y", 0.3)); voxel_size_z_ = static_cast<double>(declare_parameter("voxel_size_z", 0.1)); } using std::placeholders::_1; set_param_res_ = this->add_on_set_parameters_callback( std::bind(&VoxelGridDownsampleFilterComponent::paramCallback, this, _1)); } void VoxelGridDownsampleFilterComponent::filter( const PointCloud2ConstPtr & input, const IndicesPtr & /*indices*/, PointCloud2 & output) { std::scoped_lock lock(mutex_); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_input(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_output(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*input, *pcl_input); pcl_output->points.reserve(pcl_input->points.size()); pcl::VoxelGrid<pcl::PointXYZ> filter; filter.setInputCloud(pcl_input); // filter.setSaveLeafLayout(true); filter.setLeafSize(voxel_size_x_, voxel_size_y_, voxel_size_z_); filter.filter(*pcl_output); pcl::toROSMsg(*pcl_output, output); output.header = input->header; } rcl_interfaces::msg::SetParametersResult VoxelGridDownsampleFilterComponent::paramCallback( const std::vector<rclcpp::Parameter> & p) { std::scoped_lock lock(mutex_); if (get_param(p, "voxel_size_x", voxel_size_x_)) { RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_x_); } if (get_param(p, "voxel_size_y", voxel_size_y_)) { RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_y_); } if (get_param(p, "voxel_size_z", voxel_size_z_)) { RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_z_); } rcl_interfaces::msg::SetParametersResult result; result.successful = true; result.reason = "success"; return result; } } // namespace pointcloud_preprocessor #include <rclcpp_components/register_node_macro.hpp> RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_preprocessor::VoxelGridDownsampleFilterComponent)
40.425
93
0.754277
meliketanrikulu
edc7747afbbb09fe4f58400834f2ad809d5c0017
1,822
cpp
C++
Tests/Unit/TestMilestone3.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
17
2018-03-29T15:24:40.000Z
2022-01-10T05:01:09.000Z
Tests/Unit/TestMilestone3.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
null
null
null
Tests/Unit/TestMilestone3.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
3
2018-04-07T06:02:05.000Z
2019-01-21T00:37:18.000Z
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "SceneTrackStatic.h" #include "TestCommon.h" #include "tinydir/tinydir.h" #include "TestCRC.h" typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef float f32; typedef double f64; typedef u8 stByte; struct SoundClass { u32 type; u32 speaker; u32 volume; u32 length; }; struct SpeakerClass { u32 type; u32 position; }; typedef u32 Speaker; typedef u32 Sound; SCENARIO("Events") { u32 recording = stCreateRecording(); stAppendSaveRecording("events.st", ST_FORMAT_BINARY, 2); SoundClass soundClass; soundClass.type = stCreateObjectType(ST_FREQUENCY_EVENT); soundClass.speaker = stAddObjectTypeComponent(soundClass.type, ST_KIND_PARENT, ST_TYPE_UINT32, 1); soundClass.volume = stAddObjectTypeComponent(soundClass.type, ST_KIND_INTENSITY, ST_TYPE_FLOAT32, 1); soundClass.length = stAddObjectTypeComponent(soundClass.type, ST_KIND_LENGTH, ST_TYPE_FLOAT32, 1); SpeakerClass speakerClass; speakerClass.type = stCreateObjectType(ST_FREQUENCY_DYNAMIC); speakerClass.position = stAddObjectTypeComponent(speakerClass.type, ST_KIND_POSITION, ST_TYPE_FLOAT32, 3); Speaker speaker = stCreateObject(speakerClass.type); stSetValue_3_float32(speaker, speakerClass.position, 3.0f, 4.0f, 5.0f); Sound sound1 = stCreateObject(soundClass.type); stSetValue_uint32(sound1, soundClass.speaker, speaker); stSubmit(1.0f); Sound sound2 = stCreateObject(soundClass.type); stSetValue_uint32(sound2, soundClass.speaker, speaker); stSubmit(1.0f); stCloseRecording(recording); }
25.661972
108
0.75247
EDFilms
edc7ce61fd54c22657f483cd36b8869abcf969aa
1,929
cpp
C++
Plugins/UE4-DialogueSystem-master/Source/DialogueSystem/Private/BTComposite_Context.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
1
2018-07-07T16:51:34.000Z
2018-07-07T16:51:34.000Z
Plugins/UE4-DialogueSystem-master/Source/DialogueSystem/Private/BTComposite_Context.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
Plugins/UE4-DialogueSystem-master/Source/DialogueSystem/Private/BTComposite_Context.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
1
2019-10-02T01:19:21.000Z
2019-10-02T01:19:21.000Z
//Copyright (c) 2016 Artem A. Mavrin and other contributors #include "DialogueSystemPrivatePCH.h" #include "BTComposite_Context.h" UBTComposite_Context::UBTComposite_Context(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { NodeName = "Context"; ExecutionMode = EContextExecutionMode::CE_Sequence; OnNextChild.BindUObject(this, &UBTComposite_Context::GetNextChildHandler); } bool UBTComposite_Context::VerifyExecution(EBTNodeResult::Type LastResult) const { if (ExecutionMode == EContextExecutionMode::CE_Sequence) return LastResult == EBTNodeResult::Succeeded; else return LastResult == EBTNodeResult::Failed; } int32 UBTComposite_Context::GetNextChildHandler(struct FBehaviorTreeSearchData& SearchData, int32 PrevChild, EBTNodeResult::Type LastResult) const { int32 NextChildIdx = BTSpecialChild::ReturnToParent; if (PrevChild == BTSpecialChild::NotInitialized) { NextChildIdx = 0; } else if (VerifyExecution(LastResult) && (PrevChild + 1) < GetChildrenNum()) { NextChildIdx = PrevChild + 1; } return NextChildIdx; } #if WITH_EDITOR FName UBTComposite_Context::GetNodeIconName() const { return FName("BTEditor.Graph.BTNode.Decorator.DoesPathExist.Icon"); } #endif FString UBTComposite_Context::GetStaticDescription() const { FString Description = ""; Description += (ExecutionMode == EContextExecutionMode::CE_Sequence) ? TEXT("Sequence \n\n") : TEXT("Selector \n\n"); for (const FBTDialogueParameter& DialogueParameter : DialogueParameters) Description += DialogueParameter.StringKey + " : " + DialogueParameter.BlackboardKey.SelectedKeyName.ToString() + TEXT(" \n"); return Description; } void UBTComposite_Context::PushArguments(FFormatNamedArguments& DialogueArguments, UBlackboardComponent * Blackboard) const { for (const FBTDialogueParameter& DialogueParameter : DialogueParameters) DialogueParameter.PushArgument(DialogueArguments, Blackboard); }
29.227273
146
0.790565
crimsonstrife
edc9c39634b83f0e12b48c78ea9bb66b3d5a3c86
10,251
cpp
C++
src/core/mp2v_hdr.cpp
fxslava/tiny_mp2v_enc
cd7f6fe8fc0652f060e466f7bb51397807c8e571
[ "MIT" ]
1
2022-02-19T15:29:18.000Z
2022-02-19T15:29:18.000Z
src/core/mp2v_hdr.cpp
fxslava/tiny_mp2v_enc
cd7f6fe8fc0652f060e466f7bb51397807c8e571
[ "MIT" ]
null
null
null
src/core/mp2v_hdr.cpp
fxslava/tiny_mp2v_enc
cd7f6fe8fc0652f060e466f7bb51397807c8e571
[ "MIT" ]
null
null
null
#include "mp2v_hdr.h" #include "misc.hpp" bool write_sequence_header(bitstream_writer_c* m_bs, sequence_header_t &sh) { m_bs->align(); m_bs->write_bits(START_CODE(sequence_header_code), 32); m_bs->write_bits(sh.horizontal_size_value, 12); m_bs->write_bits(sh.vertical_size_value, 12); m_bs->write_bits(sh.aspect_ratio_information, 4); m_bs->write_bits(sh.frame_rate_code, 4); m_bs->write_bits(sh.bit_rate_value, 18); m_bs->one_bit(); m_bs->write_bits(sh.vbv_buffer_size_value, 10); m_bs->write_bits(sh.constrained_parameters_flag, 1); m_bs->write_bits(sh.load_intra_quantiser_matrix, 1); if (sh.load_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, sh.intra_quantiser_matrix); m_bs->write_bits(sh.load_non_intra_quantiser_matrix, 1); if (sh.load_non_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, sh.non_intra_quantiser_matrix); return true; } bool write_sequence_extension(bitstream_writer_c* m_bs, sequence_extension_t &sext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(sequence_extension_id, 4); m_bs->write_bits(sext.profile_and_level_indication, 8); m_bs->write_bits(sext.progressive_sequence, 1); m_bs->write_bits(sext.chroma_format, 2); m_bs->write_bits(sext.horizontal_size_extension, 2); m_bs->write_bits(sext.vertical_size_extension, 2); m_bs->write_bits(sext.bit_rate_extension, 12); m_bs->one_bit(); m_bs->write_bits(sext.vbv_buffer_size_extension, 8); m_bs->write_bits(sext.low_delay, 1); m_bs->write_bits(sext.frame_rate_extension_n, 2); m_bs->write_bits(sext.frame_rate_extension_d, 5); return true; } bool write_sequence_display_extension(bitstream_writer_c* m_bs, sequence_display_extension_t & sdext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(sequence_display_extension_id, 4); m_bs->write_bits(sdext.video_format, 3); m_bs->write_bits(sdext.colour_description, 1); if (sdext.colour_description) { m_bs->write_bits(sdext.colour_primaries, 8); m_bs->write_bits(sdext.transfer_characteristics, 8); m_bs->write_bits(sdext.matrix_coefficients, 8); } m_bs->write_bits(sdext.display_horizontal_size, 14); m_bs->one_bit(); m_bs->write_bits(sdext.display_vertical_size, 14); return true; } bool write_sequence_scalable_extension(bitstream_writer_c* m_bs, sequence_scalable_extension_t &ssext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(sequence_scalable_extension_id, 4); m_bs->write_bits(ssext.scalable_mode, 2); m_bs->write_bits(ssext.layer_id, 4); if (ssext.scalable_mode == scalable_mode_spatial_scalability) { m_bs->write_bits(ssext.lower_layer_prediction_horizontal_size, 14); m_bs->one_bit(); m_bs->write_bits(ssext.lower_layer_prediction_vertical_size, 14); m_bs->write_bits(ssext.horizontal_subsampling_factor_m, 5); m_bs->write_bits(ssext.horizontal_subsampling_factor_n, 5); m_bs->write_bits(ssext.vertical_subsampling_factor_m, 5); m_bs->write_bits(ssext.vertical_subsampling_factor_n, 5); } if (ssext.scalable_mode == scalable_mode_temporal_scalability) { m_bs->write_bits(ssext.picture_mux_enable, 1); if (ssext.picture_mux_enable) m_bs->write_bits(ssext.mux_to_progressive_sequence, 1); m_bs->write_bits(ssext.picture_mux_order, 3); m_bs->write_bits(ssext.picture_mux_factor, 3); } return true; } bool write_group_of_pictures_header(bitstream_writer_c* m_bs, group_of_pictures_header_t &gph) { m_bs->align(); m_bs->write_bits(START_CODE(group_start_code), 32); m_bs->write_bits(gph.time_code, 25); m_bs->write_bits(gph.closed_gop, 1); m_bs->write_bits(gph.broken_link, 1); return true; } bool write_picture_header(bitstream_writer_c* m_bs, picture_header_t & ph) { m_bs->align(); m_bs->write_bits(START_CODE(picture_start_code), 32); m_bs->write_bits(ph.temporal_reference, 10); m_bs->write_bits(ph.picture_coding_type, 3); m_bs->write_bits(ph.vbv_delay, 16); if (ph.picture_coding_type == 2 || ph.picture_coding_type == 3) { m_bs->write_bits(ph.full_pel_forward_vector, 1); m_bs->write_bits(ph.forward_f_code, 3); } if (ph.picture_coding_type == 3) { m_bs->write_bits(ph.full_pel_backward_vector, 1); m_bs->write_bits(ph.backward_f_code, 3); } m_bs->zero_bit(); // skip all extra_information_picture return true; } bool write_picture_coding_extension(bitstream_writer_c* m_bs, picture_coding_extension_t &pcext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_coding_extension_id, 4); m_bs->write_bits(pcext.f_code[0][0], 4); m_bs->write_bits(pcext.f_code[0][1], 4); m_bs->write_bits(pcext.f_code[1][0], 4); m_bs->write_bits(pcext.f_code[1][1], 4); m_bs->write_bits(pcext.intra_dc_precision, 2); m_bs->write_bits(pcext.picture_structure, 2); m_bs->write_bits(pcext.top_field_first, 1); m_bs->write_bits(pcext.frame_pred_frame_dct, 1); m_bs->write_bits(pcext.concealment_motion_vectors, 1); m_bs->write_bits(pcext.q_scale_type, 1); m_bs->write_bits(pcext.intra_vlc_format, 1); m_bs->write_bits(pcext.alternate_scan, 1); m_bs->write_bits(pcext.repeat_first_field, 1); m_bs->write_bits(pcext.chroma_420_type, 1); m_bs->write_bits(pcext.progressive_frame, 1); m_bs->write_bits(pcext.composite_display_flag, 1); if (pcext.composite_display_flag) { m_bs->write_bits(pcext.v_axis, 1); m_bs->write_bits(pcext.field_sequence, 3); m_bs->write_bits(pcext.sub_carrier, 1); m_bs->write_bits(pcext.burst_amplitude, 7); m_bs->write_bits(pcext.sub_carrier_phase, 8); } return true; } bool write_quant_matrix_extension(bitstream_writer_c* m_bs, quant_matrix_extension_t &qmext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(quant_matrix_extension_id, 4); m_bs->write_bits(qmext.load_intra_quantiser_matrix, 1); if (qmext.load_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.intra_quantiser_matrix); m_bs->write_bits(qmext.load_non_intra_quantiser_matrix, 1); if (qmext.load_non_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.non_intra_quantiser_matrix); m_bs->write_bits(qmext.load_chroma_intra_quantiser_matrix, 1); if (qmext.load_chroma_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.chroma_intra_quantiser_matrix); m_bs->write_bits(qmext.load_chroma_non_intra_quantiser_matrix, 1); if (qmext.load_chroma_non_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.chroma_non_intra_quantiser_matrix); return true; } bool write_picture_display_extension(bitstream_writer_c* m_bs, picture_display_extension_t &pdext, sequence_extension_t &sext, picture_coding_extension_t &pcext) { /* calculta number_of_frame_centre_offsets */ int number_of_frame_centre_offsets; if (sext.progressive_sequence == 1) { if (pcext.repeat_first_field == 1) { if (pcext.top_field_first == 1) number_of_frame_centre_offsets = 3; else number_of_frame_centre_offsets = 2; } else number_of_frame_centre_offsets = 1; } else { if (pcext.picture_structure == picture_structure_topfield || pcext.picture_structure == picture_structure_botfield) number_of_frame_centre_offsets = 1; else { if (pcext.repeat_first_field == 1) number_of_frame_centre_offsets = 3; else number_of_frame_centre_offsets = 2; } } m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_display_extension_id, 4); for (int i = 0; i < number_of_frame_centre_offsets; i++) { m_bs->write_bits(pdext.frame_centre_horizontal_offset[i], 16); m_bs->one_bit(); m_bs->write_bits(pdext.frame_centre_vertical_offset[i], 16); m_bs->one_bit(); } return true; } bool write_picture_temporal_scalable_extension(bitstream_writer_c* m_bs, picture_temporal_scalable_extension_t& ptsext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_temporal_scalable_extension_id, 4); m_bs->write_bits(ptsext.reference_select_code, 2); m_bs->write_bits(ptsext.forward_temporal_reference, 10); m_bs->one_bit(); m_bs->write_bits(ptsext.backward_temporal_reference, 10); return true; } bool write_picture_spatial_scalable_extension(bitstream_writer_c* m_bs, picture_spatial_scalable_extension_t& pssext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_spatial_scalable_extension_id, 4); m_bs->write_bits(pssext.lower_layer_temporal_reference, 10); m_bs->one_bit(); m_bs->write_bits(pssext.lower_layer_horizontal_offset, 15); m_bs->one_bit(); m_bs->write_bits(pssext.lower_layer_vertical_offset, 15); m_bs->write_bits(pssext.spatial_temporal_weight_code_table_index, 2); m_bs->write_bits(pssext.lower_layer_progressive_frame, 1); m_bs->write_bits(pssext.lower_layer_deinterlaced_field_select, 1); return true; } bool write_copyright_extension(bitstream_writer_c* m_bs, copyright_extension_t& crext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(copiright_extension_id, 4); m_bs->write_bits(crext.copyright_flag, 1); m_bs->write_bits(crext.copyright_identifier, 8); m_bs->write_bits(crext.original_or_copy, 1); m_bs->write_bits(crext.reserved, 7); m_bs->one_bit(); m_bs->write_bits(crext.copyright_number_1, 20); m_bs->one_bit(); m_bs->write_bits(crext.copyright_number_2, 22); m_bs->one_bit(); m_bs->write_bits(crext.copyright_number_3, 22); return true; }
43.253165
163
0.727441
fxslava
edcb4239510c0b7f3e41f6388f3a86013aa56364
2,969
cpp
C++
roomedit/owl-6.43/source/owlcore/timegadg.cpp
marcelkauf/Meridian59-101
a83e2779e39bc529dc61dc02db091db7db29734c
[ "FSFAP" ]
214
2015-01-02T23:36:42.000Z
2022-03-30T01:41:41.000Z
roomedit/owl-6.43/source/owlcore/timegadg.cpp
marcelkauf/Meridian59-101
a83e2779e39bc529dc61dc02db091db7db29734c
[ "FSFAP" ]
100
2015-01-01T13:51:57.000Z
2022-03-28T15:49:36.000Z
roomedit/owl-6.43/source/owlcore/timegadg.cpp
marcelkauf/Meridian59-101
a83e2779e39bc529dc61dc02db091db7db29734c
[ "FSFAP" ]
85
2015-01-08T16:09:04.000Z
2022-02-22T05:24:56.000Z
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1995, 1996 by Borland International, All Rights Reserved // //---------------------------------------------------------------------------- #include <owl/pch.h> #if !defined(OWL_TIMEGADG_H) # include <owl/timegadg.h> #endif #include <owl/time.h> #include <owl/pointer.h> namespace owl { OWL_DIAGINFO; // /// Constructor for TTimeGadget. // TTimeGadget::TTimeGadget(TGetTimeFunc timeFunc, int id, TBorderStyle border, TAlign align, uint numChars, LPCTSTR text, TFont* font) : TTextGadget(id, border, align, numChars, text, font), TimeFunc(timeFunc) { SetShrinkWrap(false, true); } // /// String-aware overload // TTimeGadget::TTimeGadget( TGetTimeFunc timeFunc, int id, TBorderStyle border, TAlign align, uint numChars, const tstring& text, TFont* font ) : TTextGadget(id, border, align, numChars, text, font), TimeFunc(timeFunc) { SetShrinkWrap(false, true); } // /// Overriden from TGadget to inform gadget window to setup a timer // void TTimeGadget::Created() { TGadget::Created(); GetGadgetWindow()->EnableTimer(); } // /// Overridden from TGadget to display the current time. // bool TTimeGadget::IdleAction(long count) { TGadget::IdleAction(count); tstring newTime; TimeFunc(newTime); SetText(newTime.c_str()); // NOTE: Don't return true to drain system. Let GadgetWindow Timer // message indirectly trigger IdleAction. // return false; } // /// Retrieves the current time. // void TTimeGadget::GetTTime(tstring& newTime) { TTime time; newTime = time.AsString(); } // // Win32 specific // // /// Retrieves the system time using the Win32 API. // void TTimeGadget::GetSystemTime(tstring& newTime) { TAPointer<tchar> dateBuffer(new tchar[100]); TAPointer<tchar> timeBuffer(new tchar[100]); LCID lcid = ::GetUserDefaultLCID(); SYSTEMTIME systemTime; ::GetSystemTime(&systemTime); if (::GetTimeFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, timeBuffer, 100)) { if (::GetDateFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, dateBuffer, 100)) { newTime += dateBuffer; newTime += _T(" "); newTime += timeBuffer; } } } // /// Retrieves the local time using the Win32 API // void TTimeGadget::GetLocalTime(tstring& newTime) { TAPointer<tchar> dateBuffer(new tchar[100]); TAPointer<tchar> timeBuffer(new tchar[100]); LCID lcid = ::GetUserDefaultLCID(); SYSTEMTIME systemTime; ::GetLocalTime(&systemTime); if (::GetTimeFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, timeBuffer, 100)) { if (::GetDateFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, dateBuffer, 100)) { newTime += dateBuffer; newTime += _T(" "); newTime += timeBuffer; } } } } // OWL namespace /* ========================================================================== */
21.671533
88
0.6258
marcelkauf
edcd90b9ca77108547b2914295385a5947d5bdf0
19,610
cpp
C++
unix/disp_sdl.cpp
acekiller/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
1
2015-06-21T05:27:57.000Z
2015-06-21T05:27:57.000Z
unix/disp_sdl.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
unix/disp_sdl.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
/******************************************************************************* * disp_sdl.cpp * * Written by Christoph Hormann <chris_hormann@gmx.de> * * SDL (Simple direct media layer) based render display system * * from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. * Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd. * --------------------------------------------------------------------------- * NOTICE: This source code file is provided so that users may experiment * with enhancements to POV-Ray and to port the software to platforms other * than those supported by the POV-Ray developers. There are strict rules * regarding how you are permitted to use this file. These rules are contained * in the distribution and derivative versions licenses which should have been * provided with this file. * * These licences may be found online, linked from the end-user license * agreement that is located at http://www.povray.org/povlegal.html * --------------------------------------------------------------------------- * POV-Ray is based on the popular DKB raytracer version 2.12. * DKBTrace was originally written by David K. Buck. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. * --------------------------------------------------------------------------- * $File: //depot/povray/smp/unix/disp_sdl.cpp $ * $Revision: #19 $ * $Change: 5604 $ * $DateTime: 2012/01/28 15:37:41 $ * $Author: jgrimbert $ *******************************************************************************/ /********************************************************************************* * NOTICE * * This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not * final code. Use of this source file is governed by both the standard POV-Ray * licences referred to in the copyright header block above this notice, and the * following additional restrictions numbered 1 through 4 below: * * 1. This source file may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. * * 2. This notice may not be altered or removed. * * 3. Binaries generated from this source file by individuals for their own * personal use may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries * are not required to have a timeout, and thus permission is granted in * these circumstances only to disable the timeout code contained within * the beta software. * * 4. Binaries generated from this source file for use within an organizational * unit (such as, but not limited to, a company or university) may not be * distributed beyond the local organizational unit in which they were made, * unless written permission is obtained from Persistence of Vision Raytracer * Pty. Ltd. Additionally, the timeout code implemented within the beta may * not be disabled or otherwise bypassed in any manner. * * The following text is not part of the above conditions and is provided for * informational purposes only. * * The purpose of the no-redistribution clause is to attempt to keep the * circulating copies of the beta source fresh. The only authorized distribution * point for the source code is the POV-Ray website and Perforce server, where * the code will be kept up to date with recent fixes. Additionally the beta * timeout code mentioned above has been a standard part of POV-Ray betas since * version 1.0, and is intended to reduce bug reports from old betas as well as * keep any circulating beta binaries relatively fresh. * * All said, however, the POV-Ray developers are open to any reasonable request * for variations to the above conditions and will consider them on a case-by-case * basis. * * Additionally, the developers request your co-operation in fixing bugs and * generally improving the program. If submitting a bug-fix, please ensure that * you quote the revision number of the file shown above in the copyright header * (see the '$Revision:' field). This ensures that it is possible to determine * what specific copy of the file you are working with. The developers also would * like to make it known that until POV-Ray 3.7 is out of beta, they would prefer * to emphasize the provision of bug fixes over the addition of new features. * * Persons wishing to enhance this source are requested to take the above into * account. It is also strongly suggested that such enhancements are started with * a recent copy of the source. * * The source code page (see http://www.povray.org/beta/source/) sets out the * conditions under which the developers are willing to accept contributions back * into the primary source tree. Please refer to those conditions prior to making * any changes to this source, if you wish to submit those changes for inclusion * with POV-Ray. * *********************************************************************************/ #include "config.h" #ifdef HAVE_LIBSDL #include "disp_sdl.h" #include <algorithm> // this must be the last file included #include "syspovdebug.h" namespace pov_frontend { using namespace std; using namespace vfe; using namespace vfePlatform; extern boost::shared_ptr<Display> gDisplay; const UnixOptionsProcessor::Option_Info UnixSDLDisplay::Options[] = { // command line/povray.conf/environment options of this display mode can be added here // section name, option name, default, has_param, command line parameter, environment variable name, help text UnixOptionsProcessor::Option_Info("display", "scaled", "on", false, "", "POV_DISPLAY_SCALED", "scale render view to fit screen"), UnixOptionsProcessor::Option_Info("", "", "", false, "", "", "") // has to be last }; bool UnixSDLDisplay::Register(vfeUnixSession *session) { session->GetUnixOptions()->Register(Options); // TODO: correct display detection return true; } UnixSDLDisplay::UnixSDLDisplay(unsigned int w, unsigned int h, GammaCurvePtr gamma, vfeSession *session, bool visible) : UnixDisplay(w, h, gamma, session, visible) { m_valid = false; m_display_scaled = false; m_display_scale = 1.; m_screen = NULL; m_display = NULL; } UnixSDLDisplay::~UnixSDLDisplay() { Close(); } void UnixSDLDisplay::Initialise() { if (m_VisibleOnCreation) Show(); } void UnixSDLDisplay::Hide() { } bool UnixSDLDisplay::TakeOver(UnixDisplay *display) { UnixSDLDisplay *p = dynamic_cast<UnixSDLDisplay *>(display); if (p == NULL) return false; if ((GetWidth() != p->GetWidth()) || (GetHeight() != p->GetHeight())) return false; m_valid = p->m_valid; m_display_scaled = p->m_display_scaled; m_display_scale = p->m_display_scale; m_screen = p->m_screen; m_display = p->m_display; if (m_display_scaled) { int width = GetWidth(); int height = GetHeight(); // allocate a new pixel counters, dropping influence of previous picture m_PxCount.clear(); // not useful, vector was created empty, just to be sure m_PxCount.reserve(width*height); // we need that, and the loop! for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++) (*iter) = 0; } return true; } void UnixSDLDisplay::Close() { if (!m_valid) return; // FIXME: should handle this correctly for the last frame // SDL_FreeSurface(m_display); // SDL_Quit(); m_PxCount.clear(); m_valid = false; } void UnixSDLDisplay::SetCaption(bool paused) { if (!m_valid) return; boost::format f; if (m_display_scaled) f = boost::format(PACKAGE_NAME " " VERSION_BASE " SDL display (scaled at %.0f%%)%s") % (m_display_scale*100) % (paused ? " [paused]" : ""); else f = boost::format(PACKAGE_NAME " " VERSION_BASE " SDL display%s") % (paused ? " [paused]" : ""); // FIXME: SDL_WM_SetCaption() causes locks on some distros, see http://bugs.povray.org/23 // FIXME: SDL_WM_SetCaption(f.str().c_str(), PACKAGE_NAME); } void UnixSDLDisplay::Show() { if (gDisplay.get() != this) gDisplay = m_Session->GetDisplay(); if (!m_valid) { // Initialize SDL if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s.\n", SDL_GetError()); return; } int desired_bpp = 0; Uint32 video_flags = 0; int width = GetWidth(); int height = GetHeight(); vfeUnixSession *UxSession = dynamic_cast<vfeUnixSession *>(m_Session); if (UxSession->GetUnixOptions()->isOptionSet("display", "scaled")) // determine maximum display area (wrong and ugly) { SDL_Rect **modes = SDL_ListModes(NULL, SDL_FULLSCREEN); if (modes != NULL) { width = min(modes[0]->w - 10, width); height = min(modes[0]->h - 80, height); } } // calculate display area float AspectRatio = float(width)/float(height); float AspectRatio_Full = float(GetWidth())/float(GetHeight()); if (AspectRatio > AspectRatio_Full) width = int(AspectRatio_Full*float(height)); else if (AspectRatio != AspectRatio_Full) height = int(float(width)/AspectRatio_Full); // Initialize the display m_screen = SDL_SetVideoMode(width, height, desired_bpp, video_flags); if ( m_screen == NULL ) { fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n", width, height, desired_bpp, SDL_GetError()); return; } SDL_Surface *temp = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); if ( temp == NULL ) { fprintf(stderr, "Couldn't create render display surface: %s\n", SDL_GetError()); return; } m_display = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); if ( m_display == NULL ) { fprintf(stderr, "Couldn't convert bar surface: %s\n", SDL_GetError()); return; } m_PxCount.clear(); m_PxCount.reserve(width*height); for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++) (*iter) = 0; m_update_rect.x = 0; m_update_rect.y = 0; m_update_rect.w = width; m_update_rect.h = height; m_screen_rect.x = 0; m_screen_rect.y = 0; m_screen_rect.w = width; m_screen_rect.h = height; m_valid = true; m_PxCnt = UpdateInterval; if ((width == GetWidth()) && (height == GetHeight())) { m_display_scaled = false; m_display_scale = 1.; } else { m_display_scaled = true; m_display_scale = float(width) / GetWidth(); } SetCaption(false); } } inline void UnixSDLDisplay::SetPixel(unsigned int x, unsigned int y, const RGBA8& colour) { Uint8 *p = (Uint8 *) m_display->pixels + y * m_display->pitch + x * m_display->format->BytesPerPixel; Uint32 sdl_col = SDL_MapRGBA(m_display->format, colour.red, colour.green, colour.blue, colour.alpha); switch (m_display->format->BytesPerPixel) { case 1: *p = sdl_col; break; case 2: *(Uint16 *) p = sdl_col; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (sdl_col >> 16) & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = sdl_col & 0xFF; } else { p[0] = sdl_col & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = (sdl_col >> 16) & 0xFF; } break; case 4: *(Uint32 *) p = sdl_col; break; } } inline void UnixSDLDisplay::SetPixelScaled(unsigned int x, unsigned int y, const RGBA8& colour) { unsigned int ix = x * m_display_scale; unsigned int iy = y * m_display_scale; Uint8 *p = (Uint8 *) m_display->pixels + iy * m_display->pitch + ix * m_display->format->BytesPerPixel; Uint8 r, g, b, a; Uint32 old = *(Uint32 *) p; SDL_GetRGBA(old, m_display->format, &r, &g, &b, &a); unsigned int ofs = ix + iy * m_display->w; r = (r*m_PxCount[ofs] + colour.red ) / (m_PxCount[ofs]+1); g = (g*m_PxCount[ofs] + colour.green) / (m_PxCount[ofs]+1); b = (b*m_PxCount[ofs] + colour.blue ) / (m_PxCount[ofs]+1); a = (a*m_PxCount[ofs] + colour.alpha) / (m_PxCount[ofs]+1); Uint32 sdl_col = SDL_MapRGBA(m_display->format, r, g, b, a); switch (m_display->format->BytesPerPixel) { case 1: *p = sdl_col; break; case 2: *(Uint16 *) p = sdl_col; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (sdl_col >> 16) & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = sdl_col & 0xFF; } else { p[0] = sdl_col & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = (sdl_col >> 16) & 0xFF; } break; case 4: *(Uint32 *) p = sdl_col; break; } ++m_PxCount[ofs]; } void UnixSDLDisplay::UpdateCoord(unsigned int x, unsigned int y) { unsigned int rx2 = m_update_rect.x + m_update_rect.w; unsigned int ry2 = m_update_rect.y + m_update_rect.h; m_update_rect.x = min((unsigned int)m_update_rect.x, x); m_update_rect.y = min((unsigned int)m_update_rect.y, y); rx2 = max(rx2, x); ry2 = max(ry2, y); m_update_rect.w = rx2 - m_update_rect.x; m_update_rect.h = ry2 - m_update_rect.y; } void UnixSDLDisplay::UpdateCoord(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2) { unsigned int rx2 = m_update_rect.x + m_update_rect.w; unsigned int ry2 = m_update_rect.y + m_update_rect.h; m_update_rect.x = min((unsigned int)m_update_rect.x, x1); m_update_rect.y = min((unsigned int)m_update_rect.y, y1); rx2 = max(rx2, x2); ry2 = max(ry2, y2); m_update_rect.w = rx2 - m_update_rect.x; m_update_rect.h = ry2 - m_update_rect.y; } void UnixSDLDisplay::UpdateCoordScaled(unsigned int x, unsigned int y) { UpdateCoord(static_cast<unsigned int>(x * m_display_scale), static_cast<unsigned int>(y * m_display_scale)); } void UnixSDLDisplay::UpdateCoordScaled(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2) { UpdateCoord(static_cast<unsigned int>(x1 * m_display_scale), static_cast<unsigned int>(y1 * m_display_scale), static_cast<unsigned int>(x2 * m_display_scale), static_cast<unsigned int>(y2 * m_display_scale)); } void UnixSDLDisplay::DrawPixel(unsigned int x, unsigned int y, const RGBA8& colour) { if (!m_valid || x >= GetWidth() || y >= GetHeight()) return; if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0) return; if (m_display_scaled) { SetPixelScaled(x, y, colour); UpdateCoordScaled(x, y); } else { SetPixel(x, y, colour); UpdateCoord(x, y); } m_PxCnt++; if (SDL_MUSTLOCK(m_display)) SDL_UnlockSurface(m_display); } void UnixSDLDisplay::DrawRectangleFrame(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8& colour) { if (!m_valid) return; int ix1 = min(x1, GetWidth()-1); int ix2 = min(x2, GetWidth()-1); int iy1 = min(y1, GetHeight()-1); int iy2 = min(y2, GetHeight()-1); if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0) return; if (m_display_scaled) { for(unsigned int x = ix1; x <= ix2; x++) { SetPixelScaled(x, iy1, colour); SetPixelScaled(x, iy2, colour); } for(unsigned int y = iy1; y <= iy2; y++) { SetPixelScaled(ix1, y, colour); SetPixelScaled(ix2, y, colour); } UpdateCoordScaled(ix1, iy1, ix2, iy2); } else { for(unsigned int x = ix1; x <= ix2; x++) { SetPixel(x, iy1, colour); SetPixel(x, iy2, colour); } for(unsigned int y = iy1; y <= iy2; y++) { SetPixel(ix1, y, colour); SetPixel(ix2, y, colour); } UpdateCoord(ix1, iy1, ix2, iy2); } if (SDL_MUSTLOCK(m_display)) SDL_UnlockSurface(m_display); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::DrawFilledRectangle(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8& colour) { if (!m_valid) return; unsigned int ix1 = min(x1, GetWidth()-1); unsigned int ix2 = min(x2, GetWidth()-1); unsigned int iy1 = min(y1, GetHeight()-1); unsigned int iy2 = min(y2, GetHeight()-1); if (m_display_scaled) { ix1 *= m_display_scale; iy1 *= m_display_scale; ix2 *= m_display_scale; iy2 *= m_display_scale; } UpdateCoord(ix1, iy1, ix2, iy2); Uint32 sdl_col = SDL_MapRGBA(m_display->format, colour.red, colour.green, colour.blue, colour.alpha); SDL_Rect tempRect; tempRect.x = ix1; tempRect.y = iy1; tempRect.w = ix2 - ix1 + 1; tempRect.h = iy2 - iy1 + 1; SDL_FillRect(m_display, &tempRect, sdl_col); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::DrawPixelBlock(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8 *colour) { if (!m_valid) return; unsigned int ix1 = min(x1, GetWidth()-1); unsigned int ix2 = min(x2, GetWidth()-1); unsigned int iy1 = min(y1, GetHeight()-1); unsigned int iy2 = min(y2, GetHeight()-1); if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0) return; if (m_display_scaled) { for(unsigned int y = iy1, i = 0; y <= iy2; y++) for(unsigned int x = ix1; x <= ix2; x++, i++) SetPixelScaled(x, y, colour[i]); UpdateCoordScaled(ix1, iy1, ix2, iy2); } else { for(unsigned int y = y1, i = 0; y <= iy2; y++) for(unsigned int x = ix1; x <= ix2; x++, i++) SetPixel(x, y, colour[i]); UpdateCoord(ix1, iy1, ix2, iy2); } if (SDL_MUSTLOCK(m_display)) SDL_UnlockSurface(m_display); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::Clear() { for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++) (*iter) = 0; m_update_rect.x = 0; m_update_rect.y = 0; m_update_rect.w = m_display->w; m_update_rect.h = m_display->h; SDL_FillRect(m_display, &m_update_rect, (Uint32)0); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::UpdateScreen(bool Force = false) { if (!m_valid) return; if (Force || m_PxCnt >= UpdateInterval) { SDL_BlitSurface(m_display, &m_update_rect, m_screen, &m_update_rect); SDL_UpdateRect(m_screen, m_update_rect.x, m_update_rect.y, m_update_rect.w, m_update_rect.h); m_PxCnt = 0; } } void UnixSDLDisplay::PauseWhenDoneNotifyStart() { if (!m_valid) return; fprintf(stderr, "Press a key or click the display to continue..."); SetCaption(true); } void UnixSDLDisplay::PauseWhenDoneNotifyEnd() { if (!m_valid) return; SetCaption(false); fprintf(stderr, "\n\n"); } bool UnixSDLDisplay::PauseWhenDoneResumeIsRequested() { if (!m_valid) return true; SDL_Event event; bool do_quit = false; if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if ( event.key.keysym.sym == SDLK_q || event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) do_quit = true; break; case SDL_MOUSEBUTTONDOWN: do_quit = true; break; } } return do_quit; } bool UnixSDLDisplay::HandleEvents() { if (!m_valid) return false; SDL_Event event; bool do_quit = false; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if ( event.key.keysym.sym == SDLK_q ) do_quit = true; else if ( event.key.keysym.sym == SDLK_p ) { if (!m_Session->IsPausable()) break; if (m_Session->Paused()) { if (m_Session->Resume()) SetCaption(false); } else { if (m_Session->Pause()) SetCaption(true); } } break; case SDL_QUIT: do_quit = true; break; } if (do_quit) break; } return do_quit; } } #endif /* HAVE_LIBSDL */
28.753666
131
0.647119
acekiller
edcdb5fc493944a65db3ff558874a10ebd9fcb87
2,630
cpp
C++
src/caffe/layers/tile_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
123
2017-05-04T02:15:47.000Z
2021-01-04T05:04:24.000Z
src/caffe/layers/tile_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
43
2017-05-10T11:21:25.000Z
2021-01-28T14:53:01.000Z
src/caffe/layers/tile_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
32
2017-05-10T11:08:18.000Z
2020-12-17T20:03:45.000Z
#include <vector> #include "caffe/layers/tile_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> __global__ void Tile(const int nthreads, const Dtype* bottom_data, const int tile_size, const int num_tiles, const int bottom_tile_axis, Dtype* top_data) { HIP_KERNEL_LOOP(index, nthreads) { const int d = index % tile_size; const int b = (index / tile_size / num_tiles) % bottom_tile_axis; const int n = index / tile_size / num_tiles / bottom_tile_axis; const int bottom_index = (n * bottom_tile_axis + b) * tile_size + d; top_data[index] = bottom_data[bottom_index]; } } template <typename Dtype> void TileLayer<Dtype>::Forward_gpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); const int bottom_tile_axis = bottom[0]->shape(axis_); const int nthreads = top[0]->count(); hipLaunchKernelGGL(Tile<Dtype>, //) NOLINT_NEXT_LINE(whitespace/operators) dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, nthreads, bottom_data, inner_dim_, tiles_, bottom_tile_axis, top_data); } template <typename Dtype> __global__ void TileBackward(const int nthreads, const Dtype* top_diff, const int tile_size, const int num_tiles, const int bottom_tile_axis, Dtype* bottom_diff) { HIP_KERNEL_LOOP(index, nthreads) { const int d = index % tile_size; const int b = (index / tile_size) % bottom_tile_axis; const int n = index / tile_size / bottom_tile_axis; bottom_diff[index] = 0; int top_index = (n * num_tiles * bottom_tile_axis + b) * tile_size + d; for (int t = 0; t < num_tiles; ++t) { bottom_diff[index] += top_diff[top_index]; top_index += bottom_tile_axis * tile_size; } } } template <typename Dtype> void TileLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int bottom_tile_axis = bottom[0]->shape(axis_); const int tile_size = inner_dim_ / bottom_tile_axis; const int nthreads = bottom[0]->count(); hipLaunchKernelGGL(TileBackward<Dtype>, // NOLINT_NEXT_LINE(whitespace/operators) dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, nthreads, top_diff, tile_size, tiles_, bottom_tile_axis, bottom_diff); } INSTANTIATE_LAYER_GPU_FUNCS(TileLayer); } // namespace caffe
39.253731
84
0.715209
emerth
edce6b057bd3cf9b970e8fa200e93cd0e03f76e1
3,608
cpp
C++
tools/clang/test/SemaCXX/nullability.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
1,192
2017-01-23T23:27:01.000Z
2019-05-05T14:08:40.000Z
tools/clang/test/SemaCXX/nullability.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
2,214
2019-05-06T22:22:53.000Z
2022-03-31T19:38:50.000Z
tools/clang/test/SemaCXX/nullability.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
269
2019-05-07T11:59:04.000Z
2022-03-30T08:41:50.000Z
// RUN: %clang_cc1 -std=c++11 -fsyntax-only -Wno-nullability-declspec %s -verify #if __has_feature(nullability) #else # error nullability feature should be defined #endif typedef decltype(nullptr) nullptr_t; class X { }; // Nullability applies to all pointer types. typedef int (X::* _Nonnull member_function_type_1)(int); typedef int X::* _Nonnull member_data_type_1; typedef nullptr_t _Nonnull nonnull_nullptr_t; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'nullptr_t'}} // Nullability can move into member pointers (this is suppressing a warning). typedef _Nonnull int (X::* member_function_type_2)(int); typedef int (X::* _Nonnull member_function_type_3)(int); typedef _Nonnull int X::* member_data_type_2; // Adding non-null via a template. template<typename T> struct AddNonNull { typedef _Nonnull T type; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'int'}} // expected-error@-1{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'nullptr_t'}} }; typedef AddNonNull<int *>::type nonnull_int_ptr_1; typedef AddNonNull<int * _Nullable>::type nonnull_int_ptr_2; // FIXME: check that it was overridden typedef AddNonNull<nullptr_t>::type nonnull_int_ptr_3; // expected-note{{in instantiation of template class}} typedef AddNonNull<int>::type nonnull_non_pointer_1; // expected-note{{in instantiation of template class 'AddNonNull<int>' requested here}} // Non-null checking within a template. template<typename T> struct AddNonNull2 { typedef _Nonnull AddNonNull<T> invalid1; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull<T>'}} typedef _Nonnull AddNonNull2 invalid2; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull2<T>'}} typedef _Nonnull AddNonNull2<T> invalid3; // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull2<T>'}} typedef _Nonnull typename AddNonNull<T>::type okay1; // Don't move past a dependent type even if we know that nullability // cannot apply to that specific dependent type. typedef _Nonnull AddNonNull<T> (*invalid4); // expected-error{{nullability specifier '_Nonnull' cannot be applied to non-pointer type 'AddNonNull<T>'}} }; // Check passing null to a _Nonnull argument. void (*accepts_nonnull_1)(_Nonnull int *ptr); void (*& accepts_nonnull_2)(_Nonnull int *ptr) = accepts_nonnull_1; void (X::* accepts_nonnull_3)(_Nonnull int *ptr); void accepts_nonnull_4(_Nonnull int *ptr); void (&accepts_nonnull_5)(_Nonnull int *ptr) = accepts_nonnull_4; void test_accepts_nonnull_null_pointer_literal(X *x) { accepts_nonnull_1(0); // expected-warning{{null passed to a callee that requires a non-null argument}} accepts_nonnull_2(0); // expected-warning{{null passed to a callee that requires a non-null argument}} (x->*accepts_nonnull_3)(0); // expected-warning{{null passed to a callee that requires a non-null argument}} accepts_nonnull_4(0); // expected-warning{{null passed to a callee that requires a non-null argument}} accepts_nonnull_5(0); // expected-warning{{null passed to a callee that requires a non-null argument}} } template<void FP(_Nonnull int*)> void test_accepts_nonnull_null_pointer_literal_template() { FP(0); // expected-warning{{null passed to a callee that requires a non-null argument}} } template void test_accepts_nonnull_null_pointer_literal_template<&accepts_nonnull_4>(); // expected-note{{instantiation of function template specialization}}
51.542857
157
0.773559
clayne
edcfddaedb27e828416ba2d7b4f8757ab6ee43dd
3,377
cc
C++
third_party/blink/renderer/modules/webgl/oes_draw_buffers_indexed.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/modules/webgl/oes_draw_buffers_indexed.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/modules/webgl/oes_draw_buffers_indexed.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/webgl/oes_draw_buffers_indexed.h" namespace blink { OESDrawBuffersIndexed::OESDrawBuffersIndexed(WebGLRenderingContextBase* context) : WebGLExtension(context) { context->ExtensionsUtil()->EnsureExtensionEnabled( "GL_OES_draw_buffers_indexed"); } WebGLExtensionName OESDrawBuffersIndexed::GetName() const { return kOESDrawBuffersIndexed; } bool OESDrawBuffersIndexed::Supported(WebGLRenderingContextBase* context) { return context->ExtensionsUtil()->SupportsExtension( "GL_OES_draw_buffers_indexed"); } const char* OESDrawBuffersIndexed::ExtensionName() { return "OES_draw_buffers_indexed"; } void OESDrawBuffersIndexed::enableiOES(GLenum target, GLuint index) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->EnableiOES(target, index); } void OESDrawBuffersIndexed::disableiOES(GLenum target, GLuint index) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->DisableiOES(target, index); } void OESDrawBuffersIndexed::blendEquationiOES(GLuint buf, GLenum mode) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->BlendEquationiOES(buf, mode); } void OESDrawBuffersIndexed::blendEquationSeparateiOES(GLuint buf, GLenum modeRGB, GLenum modeAlpha) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->BlendEquationSeparateiOES(buf, modeRGB, modeAlpha); } void OESDrawBuffersIndexed::blendFunciOES(GLuint buf, GLenum src, GLenum dst) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->BlendFunciOES(buf, src, dst); } void OESDrawBuffersIndexed::blendFuncSeparateiOES(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->BlendFuncSeparateiOES(buf, srcRGB, dstRGB, srcAlpha, dstAlpha); } void OESDrawBuffersIndexed::colorMaskiOES(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return; scoped.Context()->ContextGL()->ColorMaskiOES(buf, r, g, b, a); } GLboolean OESDrawBuffersIndexed::isEnablediOES(GLenum target, GLuint index) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost()) return 0; return scoped.Context()->ContextGL()->IsEnablediOES(target, index); } } // namespace blink
34.814433
80
0.631626
mghgroup
edd24c2c54966acc08d2d649d9dee402dfb77ae1
15,269
cpp
C++
src/compile.cpp
fstromback/mymake
1ccb9adbc5a336e29ca222f11e9368cdd026ee1b
[ "MIT" ]
3
2017-05-30T11:29:06.000Z
2021-09-04T15:32:23.000Z
src/compile.cpp
fstromback/mymake
1ccb9adbc5a336e29ca222f11e9368cdd026ee1b
[ "MIT" ]
5
2016-01-22T20:06:19.000Z
2019-02-03T18:30:58.000Z
src/compile.cpp
fstromback/mymake
1ccb9adbc5a336e29ca222f11e9368cdd026ee1b
[ "MIT" ]
null
null
null
#include "std.h" #include "compile.h" #include "wildcard.h" #include "process.h" #include "env.h" namespace compile { Target::Target(const Path &wd, const Config &config) : wd(wd), config(config), includes(wd, config), compileVariants(config.getArray("compile")), buildDir(wd + Path(config.getVars("buildDir"))), intermediateExt(config.getVars("intermediateExt")), pchHeader(config.getVars("pch")), pchFile(buildDir + Path(config.getVars("pchFile"))), combinedPch(config.getBool("pchCompileCombined")), appendExt(config.getBool("appendExt", false)), absolutePath(config.getBool("absolutePath", false)) { buildDir.makeDir(); linkOutput = config.getBool("linkOutput", false); forwardDeps = config.getBool("forwardDeps", false); if (absolutePath) { vector<String> inc = this->config.getArray("include"); this->config.clear("include"); for (nat i = 0; i < inc.size(); i++) { this->config.add("include", toS(Path(inc[i]).makeAbsolute(wd))); } } // Add file extensions. We don't bother with uniqueness here, and let the ExtCache deal with that. validExts = config.getArray("ext"); vector<String> ign = config.getArray("ignore"); for (nat i = 0; i < ign.size(); i++) ignore << Wildcard(ign[i]); // Create build directory if it is not already created. buildDir.createDir(); // Load cached data if possible. includes.ignore(config.getArray("noIncludes")); if (!force) { includes.load(buildDir + "includes"); commands.load(buildDir + "commands"); } } Target::~Target() { // We do this in "save", since if we execute the binary, the destructor will not be executed. // includes.save(buildDir + "includes"); } void Target::clean() { DEBUG("Cleaning " << buildDir.makeRelative(wd) << "...", NORMAL); buildDir.recursiveDelete(); Path e = wd + Path(config.getVars("execDir")); e.makeDir(); DEBUG("Cleaning " << e.makeRelative(wd) << "...", NORMAL); e.recursiveDelete(); } bool Target::find() { DEBUG("Finding dependencies for target in " << wd, INFO); toCompile.clear(); ExtCache cache(validExts); CompileQueue q; String outputName = config.getVars("output"); // Compile pre-compiled header first. String pchStr = config.getVars("pch"); if (!pchStr.empty()) { if (!addFile(q, cache, pchStr, true)) { PLN("Failed to find an implementation file for the precompiled header."); PLN("Make sure to create both a header file '" << pchStr << "' and a corresponding implementation file."); return false; } } // Add initial files. addFiles(q, cache, config.getArray("input")); // Process files... while (q.any()) { Compile now = q.pop(); if (ignored(toS(now.makeRelative(wd)))) continue; if (!now.isPch && !now.autoFound && outputName.empty()) outputName = now.title(); // Check if 'now' is inside the working directory. if (!now.isChild(wd)) { // No need to follow further! DEBUG("Ignoring file outside of working directory: " << now.makeRelative(wd), VERBOSE); continue; } toCompile << now; // Add all other files we need. IncludeInfo info = includes.info(now); // Check so that any pch file is included first. if (!info.ignored && !pchStr.empty() && pchStr != info.firstInclude) { PLN(now << ":1: Precompiled header " << pchStr << " not used."); PLN("The precompiled header " << pchStr << " must be included first in each implementation file."); PLN("You need to use '#include \"" << pchStr << "\"' (exactly like that), and use 'include=./'."); return false; } for (IncludeInfo::PathSet::const_iterator i = info.includes.begin(); i != info.includes.end(); ++i) { DEBUG(now << " depends on " << *i, VERBOSE); addFile(q, cache, *i); // Is this a reference to another sub-project? if (!i->isChild(wd)) { Path parentRel = i->makeRelative(wd.parent()); if (parentRel.first() != "..") { dependsOn << parentRel.first(); } } } } if (toCompile.empty()) { PLN("No input files."); return false; } // Try to add the files which should be created by the pre-build step (if any). addPreBuildFiles(q, config.getArray("preBuildCreates")); while (q.any()) { Compile now = q.pop(); DEBUG("Adding file created by pre-build step currently not existing: " << now.makeRelative(wd), INFO); toCompile << now; } if (outputName.empty()) outputName = wd.title(); Path execDir = wd + Path(config.getVars("execDir")); execDir.createDir(); output = execDir + Path(outputName).titleNoExt(); output.makeExt(config.getStr("execExt")); return true; } // Save command line on exit. class SaveOnExit : public ProcessCallback { public: SaveOnExit(Commands *to, const String &file, const String &command) : to(to), key(file), command(command) {} // Save to. Commands *to; // Source file used as key. String key; // Command line. String command; virtual void exited(int result) { if (result == 0) to->set(key, command); } }; Process *Target::saveShellProcess(const String &file, const String &command, const Path &cwd, const Env *env) { Process *p = shellProcess(command, cwd, env); p->callback = new SaveOnExit(&commands, file, command); return p; } bool Target::compile() { nat threads = to<nat>(config.getStr("maxThreads", "1")); // Force serial execution? if (!config.getBool("parallel", true)) threads = 1; DEBUG("Using max " << threads << " threads.", VERBOSE); ProcGroup group(threads, outputState); DEBUG("Compiling target in " << wd, INFO); Env env(config); // Run pre-compile steps. { map<String, String> stepData; stepData["output"] = toS(output.makeRelative(wd)); if (!runSteps("preBuild", group, env, stepData)) return false; } map<String, String> data; data["file"] = ""; data["output"] = ""; data["pchFile"] = toS(pchFile.makeRelative(wd)); TimeCache timeCache; Timestamp latestModified(0); ostringstream intermediateFiles; for (nat i = 0; i < toCompile.size(); i++) { const Compile &src = toCompile[i]; Path output = src.makeRelative(wd).makeAbsolute(buildDir); if (appendExt) { String t = output.titleNoExt() + "_" + output.ext() + "." + intermediateExt; output.makeTitle(t); } else { output.makeExt(intermediateExt); } output.parent().createDir(); String file = toS(src.makeRelative(wd)); String out = toS(output.makeRelative(wd)); if (i > 0) intermediateFiles << ' '; intermediateFiles << out; if (ignored(file)) continue; Timestamp lastModified = includes.info(src).lastModified(timeCache); bool pchValid = true; if (src.isPch) { // Note: This implies that pchFile exists as well. pchValid = pchFile.mTime() >= lastModified; } bool skip = !force // Never skip a file if the force flag is set. && pchValid // If the pch is invalid, don't skip. && output.mTime() >= lastModified; // If the output exists and is new enough, we can skip. if (!combinedPch && src.isPch) { String cmd = config.getStr("pchCompile"); Path pchPath = Path(pchHeader).makeAbsolute(wd); String pchFile = toS(pchPath.makeRelative(wd)); data["file"] = preparePath(pchPath); data["output"] = data["pchFile"]; cmd = config.expandVars(cmd, data); if (skip && commands.check(pchFile, cmd)) { DEBUG("Skipping header " << file << "...", INFO); } else { DEBUG("Compiling header " << file << "...", NORMAL); DEBUG("Command line: " << cmd, INFO); if (!group.spawn(saveShellProcess(pchFile, cmd, wd, &env))) { return false; } // Wait for it to complete... if (!group.wait()) { return false; } } } String cmd; if (combinedPch && src.isPch) cmd = config.getStr("pchCompile"); else cmd = chooseCompile(file); if (cmd == "") { PLN("No suitable compile command-line for " << file); return false; } data["file"] = preparePath(src); data["output"] = out; cmd = config.expandVars(cmd, data); if (skip && commands.check(file, cmd)) { DEBUG("Skipping " << file << "...", INFO); DEBUG("Source modified: " << lastModified << ", output modified " << output.mTime(), DEBUG); } else { DEBUG("Compiling " << file << "...", NORMAL); DEBUG("Command line: " << cmd, INFO); if (!group.spawn(saveShellProcess(file, cmd, wd, &env))) return false; // If it is a pch, wait for it to finish. if (src.isPch) { if (!group.wait()) return false; } } // Update 'last modified'. We always want to do this, even if we did not need to compile the file. if (i == 0) latestModified = lastModified; else latestModified = max(latestModified, lastModified); } // Wait for compilation to terminate. if (!group.wait()) return false; vector<String> libs = config.getArray("localLibrary"); for (nat i = 0; i < libs.size(); i++) { Path libPath(libs[i]); if (libPath.exists()) { latestModified = max(latestModified, libPath.mTime()); } else { WARNING("Local library " << libPath << " not found. Use 'library' for system libraries."); } } // Link the output. bool skipLink = !force && output.mTime() >= latestModified; String finalOutput = toS(output.makeRelative(wd)); data["files"] = intermediateFiles.str(); data["output"] = finalOutput; vector<String> linkCmds = config.getArray("link"); std::ostringstream allCmds; for (nat i = 0; i < linkCmds.size(); i++) { linkCmds[i] = config.expandVars(linkCmds[i], data); if (i > 0) allCmds << ";"; allCmds << linkCmds[i]; } if (skipLink && commands.check(finalOutput, allCmds.str())) { DEBUG("Skipping linking.", INFO); DEBUG("Output modified " << output.mTime() << ", input modified " << latestModified, DEBUG); return true; } DEBUG("Linking " << output.title() << "...", NORMAL); for (nat i = 0; i < linkCmds.size(); i++) { const String &cmd = linkCmds[i]; DEBUG("Command line: " << cmd, INFO); if (!group.spawn(shellProcess(cmd, wd, &env))) return false; if (!group.wait()) return false; } commands.set(finalOutput, allCmds.str()); { // Run post-build steps. map<String, String> stepData; stepData["output"] = data["output"]; if (!runSteps("postBuild", group, env, stepData)) return false; } return true; } String Target::preparePath(const Path &file) { if (absolutePath) { return toS(file.makeAbsolute(wd)); } else { return toS(file.makeRelative(wd)); } } bool Target::ignored(const String &file) { for (nat j = 0; j < ignore.size(); j++) { if (ignore[j].matches(file)) { DEBUG("Ignoring " << file << " as per " << ignore[j], INFO); return true; } } return false; } bool Target::runSteps(const String &key, ProcGroup &group, const Env &env, const map<String, String> &options) { vector<String> steps = config.getArray(key); for (nat i = 0; i < steps.size(); i++) { String expanded = config.expandVars(steps[i], options); DEBUG("Running " << expanded, INFO); if (!group.spawn(shellProcess(expanded, wd, &env))) { PLN("Failed running " << key << ": " << expanded); return false; } if (!group.wait()) { PLN("Failed running " << key << ": " << expanded); return false; } } return true; } void Target::save() const { includes.save(buildDir + "includes"); commands.save(buildDir + "commands"); } int Target::execute(const vector<String> &params) const { if (!config.getBool("execute")) return 0; Path execPath = wd; if (config.has("execPath")) { execPath = Path(config.getStr("execPath")).makeAbsolute(wd); } DEBUG("Executing " << output.makeRelative(execPath) << " " << join(params) << " in " << execPath, INFO); return exec(output, params, execPath, null); } void Target::addLib(const Path &p) { config.add("localLibrary", toS(p)); } vector<Path> Target::findExt(const Path &path, ExtCache &cache) { // Earlier implementation did way too many queries for files, and has therefore been optimized. // for (nat i = 0; i < validExts.size(); i++) { // path.makeExt(validExts[i]); // if (path.exists()) // return true; // } const vector<String> &exts = cache.find(path); vector<Path> result; for (nat i = 0; i < exts.size(); i++) { result.push_back(path); result.back().makeExt(exts[i]); } if (!appendExt && result.size() > 1) { WARNING("Multiple files with the same name scheduled for compilation."); PLN("This leads to a name collision in the temporary files, leading to"); PLN("incorrect compilation, and probably also linker errors."); PLN("If you intend to compile all files below, add 'appendExt=yes' to this target."); PLN("Colliding files:\n" << join(result, "\n")); } return result; } void Target::addFiles(CompileQueue &to, ExtCache &cache, const vector<String> &src) { for (nat i = 0; i < src.size(); i++) { addFile(to, cache, src[i], false); } } void Target::addFilesRecursive(CompileQueue &to, const Path &at) { vector<Path> children = at.children(); for (nat i = 0; i < children.size(); i++) { if (children[i].isDir()) { DEBUG("Found directory " << children[i], DEBUG); addFilesRecursive(to, children[i]); } else { DEBUG("Found file " << children[i], DEBUG); if (std::find(validExts.begin(), validExts.end(), children[i].ext()) != validExts.end()) { DEBUG("Adding file " << children[i], VERBOSE); to << Compile(children[i], false, true); } } } } bool Target::addFile(CompileQueue &to, ExtCache &cache, const String &src, bool pch) { if (src.empty()) return false; if (src == "*") { addFilesRecursive(to, wd); return true; } Path path(src); path = path.makeAbsolute(wd); vector<Path> exts = findExt(path, cache); if (exts.empty()) { WARNING("The file " << src << " does not exist with any of the extensions " << join(validExts)); return false; } for (nat i = 0; i < exts.size(); i++) { to.push(Compile(exts[i], pch, false)); } return true; } void Target::addFile(CompileQueue &to, ExtCache &cache, const Path &header) { vector<Path> exts = findExt(header, cache); // No big deal if no cpp file is found for every h file. for (nat i = 0; i < exts.size(); i++) { to.push(Compile(exts[i], false, true)); } } void Target::addPreBuildFiles(CompileQueue &to, const vector<String> &src) { for (nat i = 0; i < src.size(); i++) addPreBuildFile(to, src[i]); } void Target::addPreBuildFile(CompileQueue &to, const String &src) { Path path = Path(src).makeAbsolute(wd); to.push(Compile(path, false, true)); } String Target::chooseCompile(const String &file) { for (nat i = compileVariants.size(); i > 0; i--) { const String &variant = compileVariants[i - 1]; nat colon = variant.find(':'); if (colon == String::npos) { WARNING("Compile variable without telling what filetypes it is for: " << variant); continue; } Wildcard w(variant.substr(0, colon)); if (w.matches(file)) return variant.substr(colon + 1); DEBUG("No match for " << file << " using " << variant, INFO); } return ""; } }
27.812386
113
0.62604
fstromback
edd3e5f994503a0dc71487167451233a97c68262
1,278
cpp
C++
test/edyn/sys/integrate_linvel.cpp
xissburg/EntityDynamics
115da67243da53f7b5001a83260b2f3d7a0355b4
[ "MIT" ]
null
null
null
test/edyn/sys/integrate_linvel.cpp
xissburg/EntityDynamics
115da67243da53f7b5001a83260b2f3d7a0355b4
[ "MIT" ]
null
null
null
test/edyn/sys/integrate_linvel.cpp
xissburg/EntityDynamics
115da67243da53f7b5001a83260b2f3d7a0355b4
[ "MIT" ]
null
null
null
#include "../common/common.hpp" #include <edyn/sys/integrate_linvel.hpp> TEST(integrate_linvel, test) { entt::registry registry; auto e0 = registry.create(); auto e1 = registry.create(); auto e2 = registry.create(); auto& p0 = registry.emplace<edyn::position>(e0, 2.f, 3.f, 4.f); const auto p0_0 = p0; auto& p1 = registry.emplace<edyn::position>(e1, -2.f, -3.f, -5.1f); const auto p1_0 = p1; registry.emplace<edyn::linvel>(e1, -0.33f, -0.5f, -0.1f); registry.emplace<edyn::linvel>(e2, -0.12f, -0.99f, 0.12f); // Only dynamic entities have their position updated. registry.emplace<edyn::dynamic_tag>(e0); registry.emplace<edyn::dynamic_tag>(e1); registry.emplace<edyn::dynamic_tag>(e2); const edyn::scalar dt = 0.1666f; const size_t n = 3; for (size_t i = 0; i < n; ++i) { edyn::integrate_linvel(registry, dt); } auto& p0_1 = registry.get<edyn::position>(e0); auto& p1_1 = registry.get<edyn::position>(e1); auto& v1 = registry.get<edyn::linvel>(e1); ASSERT_EQ(p0_1, p0_0); // e0 has no velocity, thus unchanged ASSERT_SCALAR_EQ(p1_1.x, (p1_0 + v1 * dt * n).x); ASSERT_SCALAR_EQ(p1_1.y, (p1_0 + v1 * dt * n).y); ASSERT_SCALAR_EQ(p1_1.z, (p1_0 + v1 * dt * n).z); }
32.769231
71
0.625978
xissburg
edd4de317474574057c3065537ea5e1e08ccfbf4
922
cpp
C++
Lab7/Q1.cpp
Uncle-Road/CS205_cpp
95d1e73676e0db65da077d1e6dc5148a5fa9a9ab
[ "MIT" ]
null
null
null
Lab7/Q1.cpp
Uncle-Road/CS205_cpp
95d1e73676e0db65da077d1e6dc5148a5fa9a9ab
[ "MIT" ]
null
null
null
Lab7/Q1.cpp
Uncle-Road/CS205_cpp
95d1e73676e0db65da077d1e6dc5148a5fa9a9ab
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; struct stringy { char *str; int ct; }; void set(stringy &stry, char *str); void show(const stringy &stry, int times = 1); void show(const char *str, int times = 1); int main() { stringy beany; char testing[] = "Reality isn't what it uesd to be."; set(beany, testing); show(beany); show(beany, 2); testing[0] = 'D'; testing[1] = 'u'; show(testing); show(testing, 3); show("Done"); return 0; } void set(stringy &stry, char *str) { int len = strlen(str); char *copy = new char[len]; strcpy(copy, str); stry.ct = len; stry.str = copy; } void show(const stringy &stry, int times) { for (int i = 0; i < times; i++) { cout << stry.str << endl; } } void show(const char *str, int times) { for (int i = 0; i < times; i++) { cout << str << endl; } }
15.896552
57
0.553145
Uncle-Road
edd5a33abc925ca38060f1594ba3d6cda727aa0c
11,056
cpp
C++
AVSCommon/Utils/test/Common/MockMediaPlayer.cpp
jbfitbit/avs-device-sdk
2e9428e9dfc9fa7c3b4bfd5106323f8c2f1643c9
[ "Apache-2.0" ]
1
2019-10-22T06:08:20.000Z
2019-10-22T06:08:20.000Z
AVSCommon/Utils/test/Common/MockMediaPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
null
null
null
AVSCommon/Utils/test/Common/MockMediaPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
1
2020-09-30T12:34:56.000Z
2020-09-30T12:34:56.000Z
/* * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "AVSCommon/Utils/MediaPlayer/MediaPlayerObserverInterface.h" #include "AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h" namespace alexaClientSDK { namespace avsCommon { namespace utils { namespace mediaPlayer { namespace test { using namespace testing; const static std::chrono::milliseconds WAIT_LOOP_INTERVAL{1}; std::shared_ptr<NiceMock<MockMediaPlayer>> MockMediaPlayer::create() { auto result = std::make_shared<NiceMock<MockMediaPlayer>>(); ON_CALL(*result.get(), attachmentSetSource(_, _)) .WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource)); ON_CALL(*result.get(), urlSetSource(_)) .WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource)); ON_CALL(*result.get(), streamSetSource(_, _)) .WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource)); ON_CALL(*result.get(), play(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockPlay)); ON_CALL(*result.get(), stop(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockStop)); ON_CALL(*result.get(), pause(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockPause)); ON_CALL(*result.get(), resume(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockResume)); ON_CALL(*result.get(), getOffset(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockGetOffset)); return result; } MockMediaPlayer::MockMediaPlayer() : RequiresShutdown{"MockMediaPlayer"}, m_playerObserver{nullptr} { // Create a 'source' for sourceId = 0 mockSetSource(); } MediaPlayerInterface::SourceId MockMediaPlayer::setSource( std::shared_ptr<avsCommon::avs::attachment::AttachmentReader> attachmentReader, const avsCommon::utils::AudioFormat* audioFormat) { return attachmentSetSource(attachmentReader, audioFormat); } MediaPlayerInterface::SourceId MockMediaPlayer::setSource( const std::string& url, std::chrono::milliseconds offset, bool repeat) { return urlSetSource(url); } MediaPlayerInterface::SourceId MockMediaPlayer::setSource(std::shared_ptr<std::istream> stream, bool repeat) { return streamSetSource(stream, repeat); } void MockMediaPlayer::setObserver(std::shared_ptr<MediaPlayerObserverInterface> playerObserver) { m_playerObserver = playerObserver; } std::shared_ptr<MediaPlayerObserverInterface> MockMediaPlayer::getObserver() const { return m_playerObserver; } void MockMediaPlayer::doShutdown() { std::lock_guard<std::mutex> lock(m_mutex); m_playerObserver.reset(); m_sources.clear(); } MediaPlayerInterface::SourceId MockMediaPlayer::mockSetSource() { std::lock_guard<std::mutex> lock(m_mutex); SourceId result = m_sources.size(); m_sources.emplace_back(std::make_shared<Source>(this, result)); return result; } bool MockMediaPlayer::mockPlay(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } EXPECT_TRUE(source->stopwatch.start()); source->started.trigger(); return true; } bool MockMediaPlayer::mockPause(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } // Ideally we would EXPECT_TRUE on pause(), however ACSDK-734 doesn't guarantee that will be okay. source->stopwatch.pause(); source->resumed.resetStateReached(); source->paused.trigger(); return true; } bool MockMediaPlayer::mockResume(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } EXPECT_TRUE(source->stopwatch.resume()); source->paused.resetStateReached(); source->resumed.trigger(); return true; } bool MockMediaPlayer::mockStop(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } source->stopwatch.stop(); source->stopped.trigger(); return true; } bool MockMediaPlayer::mockFinished(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } source->stopwatch.stop(); source->finished.trigger(); return true; } bool MockMediaPlayer::mockError(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } source->stopwatch.stop(); source->error.trigger(); return true; } bool MockMediaPlayer::mockSetOffset(SourceId sourceId, std::chrono::milliseconds offset) { auto source = getCurrentSource(sourceId); if (!source) { return false; } std::lock_guard<std::mutex> lock(m_mutex); source->offset = offset; return true; } std::chrono::milliseconds MockMediaPlayer::mockGetOffset(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return MEDIA_PLAYER_INVALID_OFFSET; } return source->stopwatch.getElapsed() + source->offset; } bool MockMediaPlayer::waitUntilNextSetSource(const std::chrono::milliseconds timeout) { auto originalSourceId = getCurrentSourceId(); auto timeLimit = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < timeLimit) { if (getCurrentSourceId() != originalSourceId) { return true; } std::this_thread::sleep_for(WAIT_LOOP_INTERVAL); } return false; } bool MockMediaPlayer::waitUntilPlaybackStarted(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->started.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackPaused(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->paused.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackResumed(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->resumed.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackStopped(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->stopped.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackFinished(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->finished.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackError(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->error.wait(timeout); } MediaPlayerInterface::SourceId MockMediaPlayer::getCurrentSourceId() { std::unique_lock<std::mutex> lock(m_mutex); return m_sources.size() - 1; } MockMediaPlayer::SourceState::SourceState( Source* source, const std::string& name, std::function<void(std::shared_ptr<observer>, SourceId)> notifyFunction) : m_source{source}, m_name{name}, m_notifyFunction{notifyFunction}, m_stateReached{false}, m_shutdown{false} { } MockMediaPlayer::SourceState::~SourceState() { { std::lock_guard<std::mutex> lock(m_mutex); m_shutdown = true; } m_wake.notify_all(); if (m_thread.joinable()) { m_thread.join(); } } void MockMediaPlayer::SourceState::trigger() { std::lock_guard<std::mutex> lock(m_mutex); if (m_stateReached) { return; } m_thread = std::thread(&MockMediaPlayer::SourceState::notify, this, DEFAULT_TIME); m_stateReached = true; m_wake.notify_all(); } void MockMediaPlayer::SourceState::notify(const std::chrono::milliseconds timeout) { std::unique_lock<std::mutex> lock(m_mutex); auto observer = m_source->mockMediaPlayer->m_playerObserver; if (!m_wake.wait_for(lock, timeout, [this]() { return (m_stateReached || m_shutdown); })) { if (observer) { lock.unlock(); observer->onPlaybackError( m_source->sourceId, ErrorType::MEDIA_ERROR_UNKNOWN, m_name + ": wait to notify timed out"); } return; } if (observer) { m_notifyFunction(observer, m_source->sourceId); } return; } bool MockMediaPlayer::SourceState::wait(const std::chrono::milliseconds timeout) { std::unique_lock<std::mutex> lock(m_mutex); if (!m_wake.wait_for(lock, timeout, [this]() { return (m_stateReached || m_shutdown); })) { return false; } return m_stateReached; } void MockMediaPlayer::SourceState::resetStateReached() { if (m_thread.joinable()) { m_thread.join(); } std::unique_lock<std::mutex> lock(m_mutex); m_stateReached = false; } static void notifyPlaybackStarted( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackStarted(sourceId); } static void notifyPlaybackPaused( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackPaused(sourceId); } static void notifyPlaybackResumed( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackResumed(sourceId); } static void notifyPlaybackStopped( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackStopped(sourceId); } static void notifyPlaybackFinished( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackFinished(sourceId); } static void notifyPlaybackError( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackError(sourceId, ErrorType::MEDIA_ERROR_INTERNAL_SERVER_ERROR, "mock error"); } MockMediaPlayer::Source::Source(MockMediaPlayer* player, SourceId id) : mockMediaPlayer{player}, sourceId{id}, offset{MEDIA_PLAYER_INVALID_OFFSET}, started{this, "started", notifyPlaybackStarted}, paused{this, "paused", notifyPlaybackPaused}, resumed{this, "resumed", notifyPlaybackResumed}, stopped{this, "stopped", notifyPlaybackStopped}, finished{this, "finished", notifyPlaybackFinished}, error{this, "error", notifyPlaybackError} { } std::shared_ptr<MockMediaPlayer::Source> MockMediaPlayer::getCurrentSource(SourceId sourceId) { if (ERROR == sourceId || sourceId != getCurrentSourceId()) { return nullptr; } return m_sources[static_cast<size_t>(sourceId)]; } } // namespace test } // namespace mediaPlayer } // namespace utils } // namespace avsCommon } // namespace alexaClientSDK
32.807122
110
0.714182
jbfitbit
edd9480978f68420ed90cb40f63dbcc1603bfd59
4,026
cpp
C++
src/server/sqlrqueries.cpp
davidwed/sqlrelay
2c830ff2517bfdb1c70a880038cd326eb7a7f0d1
[ "PHP-3.01", "CC-BY-3.0" ]
16
2018-04-23T09:58:33.000Z
2022-01-31T13:40:20.000Z
src/server/sqlrqueries.cpp
davidwed/sqlrelay
2c830ff2517bfdb1c70a880038cd326eb7a7f0d1
[ "PHP-3.01", "CC-BY-3.0" ]
null
null
null
src/server/sqlrqueries.cpp
davidwed/sqlrelay
2c830ff2517bfdb1c70a880038cd326eb7a7f0d1
[ "PHP-3.01", "CC-BY-3.0" ]
4
2020-12-23T12:17:54.000Z
2022-01-04T20:46:34.000Z
// Copyright (c) 1999-2018 David Muse // See the file COPYING for more information #include <sqlrelay/sqlrserver.h> #include <rudiments/domnode.h> #include <rudiments/stdio.h> //#define DEBUG_MESSAGES 1 #include <rudiments/debugprint.h> #include <config.h> #ifndef SQLRELAY_ENABLE_SHARED extern "C" { #include "sqlrquerydeclarations.cpp" } #endif class sqlrqueryplugin { public: sqlrquery *qr; dynamiclib *dl; }; class sqlrqueriesprivate { friend class sqlrqueries; private: sqlrservercontroller *_cont; singlylinkedlist< sqlrqueryplugin * > _llist; }; sqlrqueries::sqlrqueries(sqlrservercontroller *cont) { debugFunction(); pvt=new sqlrqueriesprivate; pvt->_cont=cont; } sqlrqueries::~sqlrqueries() { debugFunction(); unload(); delete pvt; } bool sqlrqueries::load(domnode *parameters) { debugFunction(); unload(); // run through the query list for (domnode *query=parameters->getFirstTagChild(); !query->isNullNode(); query=query->getNextTagSibling()) { debugPrintf("loading query ...\n"); // load query loadQuery(query); } return true; } void sqlrqueries::unload() { debugFunction(); for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { sqlrqueryplugin *sqlrlp=node->getValue(); delete sqlrlp->qr; delete sqlrlp->dl; delete sqlrlp; } pvt->_llist.clear(); } void sqlrqueries::loadQuery(domnode *query) { debugFunction(); // ignore non-queries if (charstring::compare(query->getName(),"query")) { return; } // get the query name const char *module=query->getAttributeValue("module"); if (!charstring::length(module)) { // try "file", that's what it used to be called module=query->getAttributeValue("file"); if (!charstring::length(module)) { return; } } debugPrintf("loading query: %s\n",module); #ifdef SQLRELAY_ENABLE_SHARED // load the query module stringbuffer modulename; modulename.append(pvt->_cont->getPaths()->getLibExecDir()); modulename.append(SQLR); modulename.append("query_"); modulename.append(module)->append(".")->append(SQLRELAY_MODULESUFFIX); dynamiclib *dl=new dynamiclib(); if (!dl->open(modulename.getString(),true,true)) { stdoutput.printf("failed to load query module: %s\n",module); char *error=dl->getError(); stdoutput.printf("%s\n",(error)?error:""); delete[] error; delete dl; return; } // load the query itself stringbuffer functionname; functionname.append("new_sqlrquery_")->append(module); sqlrquery *(*newQuery)(sqlrservercontroller *, sqlrqueries *, domnode *)= (sqlrquery *(*)(sqlrservercontroller *, sqlrqueries *, domnode *)) dl->getSymbol(functionname.getString()); if (!newQuery) { stdoutput.printf("failed to load query: %s\n",module); char *error=dl->getError(); stdoutput.printf("%s\n",(error)?error:""); delete[] error; dl->close(); delete dl; return; } sqlrquery *qr=(*newQuery)(pvt->_cont,this,query); #else dynamiclib *dl=NULL; sqlrquery *qr; #include "sqlrqueryassignments.cpp" { qr=NULL; } #endif // add the plugin to the list sqlrqueryplugin *sqlrlp=new sqlrqueryplugin; sqlrlp->qr=qr; sqlrlp->dl=dl; pvt->_llist.append(sqlrlp); } sqlrquerycursor *sqlrqueries::match(sqlrserverconnection *sqlrcon, const char *querystring, uint32_t querylength, uint16_t id) { debugFunction(); for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { sqlrquery *qr=node->getValue()->qr; if (qr->match(querystring,querylength)) { return qr->newCursor(sqlrcon,id); } } return NULL; } void sqlrqueries::endTransaction(bool commit) { for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { node->getValue()->qr->endTransaction(commit); } } void sqlrqueries::endSession() { for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { node->getValue()->qr->endSession(); } }
22.120879
71
0.687531
davidwed
edda8f308f1510c8fcb5d8dc78057614569da231
794
cpp
C++
aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/UpdateInstanceAttributeRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Connect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateInstanceAttributeRequest::UpdateInstanceAttributeRequest() : m_instanceIdHasBeenSet(false), m_attributeType(InstanceAttributeType::NOT_SET), m_attributeTypeHasBeenSet(false), m_valueHasBeenSet(false) { } Aws::String UpdateInstanceAttributeRequest::SerializePayload() const { JsonValue payload; if(m_valueHasBeenSet) { payload.WithString("Value", m_value); } return payload.View().WriteReadable(); }
20.358974
69
0.755668
perfectrecall
eddb068b4a9f579f10e8deb3e4763c77f909acf7
2,423
cpp
C++
dev/Code/Framework/AzCore/AzCore/Debug/StackTracer.cpp
stickyparticles/lumberyard
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
2
2019-11-29T09:04:54.000Z
2021-03-18T02:34:44.000Z
dev/Code/Framework/AzCore/AzCore/Debug/StackTracer.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/Framework/AzCore/AzCore/Debug/StackTracer.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
3
2019-05-13T09:41:33.000Z
2021-04-09T12:12:38.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #ifndef AZ_UNITY_BUILD #include <AzCore/Debug/StackTracer.h> #if defined(AZ_PLATFORM_WINDOWS) # include <AzCore/Debug/StackTracerWinCpp.inl> #elif defined(AZ_PLATFORM_X360) # include <AzCore/Debug/StackTracerX360Cpp.inl> #elif defined(AZ_PLATFORM_WII) # include <AzCore/Debug/StackTracerWiiCpp.inl> #elif defined(AZ_PLATFORM_LINUX) || defined(AZ_PLATFORM_APPLE) # include <AzCore/Debug/StackTracerLinux.inl> #else // DEFAULT NOT STACK TRACE SUPPORT #if defined(AZ_PLATFORM_XBONE) || defined(AZ_PLATFORM_PS4) || defined(AZ_PLATFORM_ANDROID) /* NOTE: Android has not official support, but there are solutions for different versions like https://android.googlesource.com/platform/system/core/+/kitkat-dev/libutils/CallStack.cpp for KitKat Add an implementation when we establish the supported versions!*/ #pragma message("--- No stack trace support ---") #pragma message("--- Implement it ---") #endif // By default callstack tracing is not supported. using namespace AZ; using namespace AZ::Debug; unsigned int StackRecorder::Record(StackFrame*, unsigned int, unsigned int, void*) { return false; } void SymbolStorage::LoadModuleData(const void*, unsigned int) {} unsigned int SymbolStorage::GetModuleInfoDataSize() { return 0; } void SymbolStorage::StoreModuleInfoData(void*, unsigned int) {} unsigned int SymbolStorage::GetNumLoadedModules() { return 0; } const SymbolStorage::ModuleInfo* SymbolStorage::GetModuleInfo(unsigned int) { return 0; } void SymbolStorage::RegisterModuleListeners() {} void SymbolStorage::UnregisterModuleListeners() {} void SymbolStorage::SetMapFilename(const char*) {} const char* SymbolStorage::GetMapFilename() { return 0; } void SymbolStorage::DecodeFrames(const StackFrame*, unsigned int, StackLine*) {} #endif #endif // #ifndef AZ_UNITY_BUILD
46.596154
103
0.742881
stickyparticles
eddba8dcff316a0908619f8e46fe2f8cbf86638c
6,253
ipp
C++
include/stats_incl/prob/plnorm.ipp
JohnGalbraith/stats
309c0e92d2326a58cad4544124c614e6a8a46079
[ "Apache-2.0" ]
381
2017-07-16T17:34:02.000Z
2022-03-30T09:47:58.000Z
include/stats_incl/prob/plnorm.ipp
myhhub/stats
309c0e92d2326a58cad4544124c614e6a8a46079
[ "Apache-2.0" ]
29
2017-07-14T20:45:42.000Z
2022-01-25T20:59:08.000Z
include/stats_incl/prob/plnorm.ipp
myhhub/stats
309c0e92d2326a58cad4544124c614e6a8a46079
[ "Apache-2.0" ]
70
2017-10-25T14:16:11.000Z
2022-01-25T20:57:02.000Z
/*################################################################################ ## ## Copyright (C) 2011-2021 Keith O'Hara ## ## This file is part of the StatsLib C++ library. ## ## 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. ## ################################################################################*/ /* * cdf of the univariate log-normal distribution */ // // single input namespace internal { template<typename T> statslib_constexpr T plnorm_vals_check(const T x, const T mu_par, const T sigma_par, const bool log_form) { return( !lnorm_sanity_check(x,mu_par,sigma_par) ? \ STLIM<T>::quiet_NaN() : // STLIM<T>::epsilon() > x ? \ log_zero_if<T>(log_form) : // pnorm(stmath::log(x),mu_par,sigma_par,log_form) ); } template<typename T1, typename T2, typename T3, typename TC = common_return_t<T1,T2,T3>> statslib_constexpr TC plnorm_type_check(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form) noexcept { return plnorm_vals_check(static_cast<TC>(x),static_cast<TC>(mu_par), static_cast<TC>(sigma_par),log_form); } } /** * @brief Distribution function of the Log-Normal distribution * * @param x a real-valued input. * @param mu_par the mean parameter, a real-valued input. * @param sigma_par the standard deviation parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return the cumulative distribution function evaluated at \c x. * * Example: * \code{.cpp} stats::plnorm(2.0,1.0,2.0,false); \endcode */ template<typename T1, typename T2, typename T3> statslib_constexpr common_return_t<T1,T2,T3> plnorm(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form) noexcept { return internal::plnorm_type_check(x,mu_par,sigma_par,log_form); } // // vector/matrix input namespace internal { #ifdef STATS_ENABLE_INTERNAL_VEC_FEATURES template<typename eT, typename T1, typename T2, typename rT> statslib_inline void plnorm_vec(const eT* __stats_pointer_settings__ vals_in, const T1 mu_par, const T2 sigma_par, const bool log_form, rT* __stats_pointer_settings__ vals_out, const ullint_t num_elem) { EVAL_DIST_FN_VEC(plnorm,vals_in,vals_out,num_elem,mu_par,sigma_par,log_form); } #endif } /** * @brief Distribution function of the Log-Normal distribution * * @param x a standard vector. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a vector of CDF values corresponding to the elements of \c x. * * Example: * \code{.cpp} * std::vector<double> x = {0.0, 1.0, 2.0}; * stats::plnorm(x,1.0,2.0,false); * \endcode */ #ifdef STATS_ENABLE_STDVEC_WRAPPERS template<typename eT, typename T1, typename T2, typename rT> statslib_inline std::vector<rT> plnorm(const std::vector<eT>& x, const T1 mu_par, const T2 sigma_par, const bool log_form) { STDVEC_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } #endif /** * @brief Distribution function of the Log-Normal distribution * * @param X a matrix of input values. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a matrix of CDF values corresponding to the elements of \c X. * * Example: * \code{.cpp} * arma::mat X = { {0.2, 1.7, 0.1}, * {0.9, 4.0, 0.3} }; * stats::plnorm(X,1.0,1.0,false); * \endcode */ #ifdef STATS_ENABLE_ARMA_WRAPPERS template<typename eT, typename T1, typename T2, typename rT> statslib_inline ArmaMat<rT> plnorm(const ArmaMat<eT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { ARMA_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } template<typename mT, typename tT, typename T1, typename T2> statslib_inline mT plnorm(const ArmaGen<mT,tT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { return plnorm(X.eval(),mu_par,sigma_par,log_form); } #endif /** * @brief Distribution function of the Log-Normal distribution * * @param X a matrix of input values. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a matrix of CDF values corresponding to the elements of \c X. * * Example: * \code{.cpp} * stats::plnorm(X,1.0,1.0,false); * \endcode */ #ifdef STATS_ENABLE_BLAZE_WRAPPERS template<typename eT, typename T1, typename T2, typename rT, bool To> statslib_inline BlazeMat<rT,To> plnorm(const BlazeMat<eT,To>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { BLAZE_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } #endif /** * @brief Distribution function of the Log-Normal distribution * * @param X a matrix of input values. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a matrix of CDF values corresponding to the elements of \c X. * * Example: * \code{.cpp} * stats::plnorm(X,1.0,1.0,false); * \endcode */ #ifdef STATS_ENABLE_EIGEN_WRAPPERS template<typename eT, typename T1, typename T2, typename rT, int iTr, int iTc> statslib_inline EigenMat<rT,iTr,iTc> plnorm(const EigenMat<eT,iTr,iTc>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { EIGEN_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } #endif
29.356808
115
0.691028
JohnGalbraith
eddcffc19694dcb2ae1dd0da87ee1484aecc6aca
10,522
cpp
C++
src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst/generic.cpp
MaximMilashchenko/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
2,313
2017-03-24T16:25:28.000Z
2022-03-31T03:00:30.000Z
src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst/generic.cpp
0xgpapad/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
952
2017-03-28T07:05:58.000Z
2022-03-30T09:54:02.000Z
src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst/generic.cpp
0xgpapad/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
714
2017-03-24T22:21:51.000Z
2022-03-18T19:49:57.000Z
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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 <cstddef> #include <cstdint> #if defined(ARM_COMPUTE_ENABLE_SVE) namespace arm_conv { namespace depthwise { void sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst_impl( const float *const *const input_ptrs, float *const *const outptrs, const void *params, unsigned int n_channels, const float activation_min, const float activation_max ) { const float *const inptrs[16] = { input_ptrs[0], input_ptrs[1], input_ptrs[4], input_ptrs[5], input_ptrs[2], input_ptrs[6], input_ptrs[3], input_ptrs[7], input_ptrs[8], input_ptrs[9], input_ptrs[10], input_ptrs[11], input_ptrs[12], input_ptrs[13], input_ptrs[14], input_ptrs[15], }; const float minmax_vals[2] = { activation_min, activation_max }; __asm__ __volatile__( "ldp x26, x23, [%x[inptrs], #0x0]\n" "ptrue p2.b\n" "ldp x25, x16, [%x[inptrs], #0x10]\n" "mov x15, #0x0\n" "ld1w { z15.s }, p2/Z, [%x[params]]\n" "mov z14.d, z15.d\n" "ld1w { z13.s }, p2/Z, [%x[params], #1, MUL VL]\n" "cntw x14\n" "mov z12.d, z15.d\n" "ld1w { z11.s }, p2/Z, [%x[params], #2, MUL VL]\n" "sub x13, XZR, x14\n" "mov z10.d, z15.d\n" "ld1w { z9.s }, p2/Z, [%x[params], #3, MUL VL]\n" "whilelt p1.s, XZR, %x[n_channels]\n" "mov z8.d, z15.d\n" "ld1w { z7.s }, p2/Z, [%x[params], #4, MUL VL]\n" "cmp x14, %x[n_channels]\n" "ld1w { z6.s }, p2/Z, [%x[params], #5, MUL VL]\n" "ld1w { z5.s }, p2/Z, [%x[params], #6, MUL VL]\n" "ld1w { z4.s }, p2/Z, [%x[params], #7, MUL VL]\n" "addvl %x[params], %x[params], #16\n" "ld1w { z3.s }, p1/Z, [x26, x15, LSL #2]\n" "ld1w { z2.s }, p2/Z, [%x[params], #-8, MUL VL]\n" "ld1w { z1.s }, p2/Z, [%x[params], #-7, MUL VL]\n" "addvl %x[params], %x[params], #-6\n" "ld1w { z0.s }, p1/Z, [x23, x15, LSL #2]\n" "ld1w { z31.s }, p1/Z, [x25, x15, LSL #2]\n" "ld1w { z30.s }, p1/Z, [x16, x15, LSL #2]\n" "ldp x24, x12, [%x[inptrs], #0x20]\n" "ldp x23, x11, [%x[inptrs], #0x30]\n" "ldp x10, x9, [%x[inptrs], #0x40]\n" "ld1w { z29.s }, p1/Z, [x24, x15, LSL #2]\n" "ld1w { z28.s }, p1/Z, [x12, x15, LSL #2]\n" "ld1w { z27.s }, p1/Z, [x23, x15, LSL #2]\n" "ld1w { z26.s }, p1/Z, [x11, x15, LSL #2]\n" "ld1w { z25.s }, p1/Z, [x10, x15, LSL #2]\n" "ld1w { z24.s }, p1/Z, [x9, x15, LSL #2]\n" "ldp x28, x27, [%x[inptrs], #0x50]\n" "ldp x26, x25, [%x[inptrs], #0x60]\n" "ldp x24, x23, [%x[inptrs], #0x70]\n" "ld1w { z23.s }, p1/Z, [x28, x15, LSL #2]\n" "ld1w { z22.s }, p1/Z, [x27, x15, LSL #2]\n" "ld1w { z21.s }, p1/Z, [x26, x15, LSL #2]\n" "ld1w { z20.s }, p1/Z, [x25, x15, LSL #2]\n" "ld1w { z19.s }, p1/Z, [x24, x15, LSL #2]\n" "ld1w { z18.s }, p1/Z, [x23, x15, LSL #2]\n" "ldp x22, x21, [%x[outptrs], #0x0]\n" "ldp x20, x19, [%x[outptrs], #0x10]\n" "ld1rw { z17.s }, p2/Z, [%x[minmax_vals]]\n" "ld1rw { z16.s }, p2/Z, [%x[minmax_vals], #4]\n" "bge 1f\n" "1:" // Loop "fmla z14.s, p2/M, z13.s, z3.s\n" "ld1w { z15.s }, p2/Z, [%x[params]]\n" "incw x13\n" "fmla z12.s, p2/M, z13.s, z0.s\n" "ldp x26, x23, [%x[inptrs], #0x0]\n" "mov p0.b, p1.b\n" "fmla z10.s, p2/M, z13.s, z31.s\n" "ldp x25, x16, [%x[inptrs], #0x10]\n" "mov x15, x14\n" "fmla z8.s, p2/M, z13.s, z30.s\n" "ld1w { z13.s }, p2/Z, [%x[params], #1, MUL VL]\n" "incw x14\n" "fmla z14.s, p2/M, z11.s, z0.s\n" "ldp x24, x12, [%x[inptrs], #0x20]\n" "whilelt p1.s, x15, %x[n_channels]\n" "fmla z12.s, p2/M, z11.s, z29.s\n" "ld1w { z3.s }, p1/Z, [x26, x15, LSL #2]\n" "cmp x14, %x[n_channels]\n" "fmla z10.s, p2/M, z11.s, z30.s\n" "ld1w { z0.s }, p1/Z, [x23, x15, LSL #2]\n" "ldp x23, x11, [%x[inptrs], #0x30]\n" "fmla z8.s, p2/M, z11.s, z28.s\n" "ld1w { z11.s }, p2/Z, [%x[params], #2, MUL VL]\n" "fmla z14.s, p2/M, z9.s, z29.s\n" "ld1w { z29.s }, p1/Z, [x24, x15, LSL #2]\n" "fmla z12.s, p2/M, z9.s, z27.s\n" "ld1w { z27.s }, p1/Z, [x23, x15, LSL #2]\n" "fmla z10.s, p2/M, z9.s, z28.s\n" "ldp x10, x9, [%x[inptrs], #0x40]\n" "fmla z8.s, p2/M, z9.s, z26.s\n" "ld1w { z9.s }, p2/Z, [%x[params], #3, MUL VL]\n" "fmla z14.s, p2/M, z7.s, z31.s\n" "ld1w { z31.s }, p1/Z, [x25, x15, LSL #2]\n" "fmla z12.s, p2/M, z7.s, z30.s\n" "ldp x28, x27, [%x[inptrs], #0x50]\n" "fmla z10.s, p2/M, z7.s, z25.s\n" "ldp x26, x25, [%x[inptrs], #0x60]\n" "fmla z8.s, p2/M, z7.s, z24.s\n" "ld1w { z7.s }, p2/Z, [%x[params], #4, MUL VL]\n" "fmla z14.s, p2/M, z6.s, z30.s\n" "ld1w { z30.s }, p1/Z, [x16, x15, LSL #2]\n" "fmla z12.s, p2/M, z6.s, z28.s\n" "ldp x24, x23, [%x[inptrs], #0x70]\n" "fmla z10.s, p2/M, z6.s, z24.s\n" "fmla z8.s, p2/M, z6.s, z23.s\n" "ld1w { z6.s }, p2/Z, [%x[params], #5, MUL VL]\n" "fmla z14.s, p2/M, z5.s, z28.s\n" "ld1w { z28.s }, p1/Z, [x12, x15, LSL #2]\n" "fmla z12.s, p2/M, z5.s, z26.s\n" "ld1w { z26.s }, p1/Z, [x11, x15, LSL #2]\n" "fmla z10.s, p2/M, z5.s, z23.s\n" "fmla z8.s, p2/M, z5.s, z22.s\n" "ld1w { z5.s }, p2/Z, [%x[params], #6, MUL VL]\n" "fmla z14.s, p2/M, z4.s, z25.s\n" "ld1w { z25.s }, p1/Z, [x10, x15, LSL #2]\n" "fmla z12.s, p2/M, z4.s, z24.s\n" "fmla z10.s, p2/M, z4.s, z21.s\n" "ld1w { z21.s }, p1/Z, [x26, x15, LSL #2]\n" "fmla z8.s, p2/M, z4.s, z20.s\n" "ld1w { z4.s }, p2/Z, [%x[params], #7, MUL VL]\n" "addvl %x[params], %x[params], #16\n" "fmla z14.s, p2/M, z2.s, z24.s\n" "ld1w { z24.s }, p1/Z, [x9, x15, LSL #2]\n" "fmla z12.s, p2/M, z2.s, z23.s\n" "fmla z10.s, p2/M, z2.s, z20.s\n" "ld1w { z20.s }, p1/Z, [x25, x15, LSL #2]\n" "fmla z8.s, p2/M, z2.s, z19.s\n" "ld1w { z2.s }, p2/Z, [%x[params], #-8, MUL VL]\n" "fmla z14.s, p2/M, z1.s, z23.s\n" "ld1w { z23.s }, p1/Z, [x28, x15, LSL #2]\n" "fmla z12.s, p2/M, z1.s, z22.s\n" "ld1w { z22.s }, p1/Z, [x27, x15, LSL #2]\n" "fmla z10.s, p2/M, z1.s, z19.s\n" "ld1w { z19.s }, p1/Z, [x24, x15, LSL #2]\n" "fmla z8.s, p2/M, z1.s, z18.s\n" "ld1w { z1.s }, p2/Z, [%x[params], #-7, MUL VL]\n" "addvl %x[params], %x[params], #-6\n" "fmax z14.s, p2/M, z14.s, z17.s\n" "ld1w { z18.s }, p1/Z, [x23, x15, LSL #2]\n" "fmax z12.s, p2/M, z12.s, z17.s\n" "fmax z10.s, p2/M, z10.s, z17.s\n" "fmax z8.s, p2/M, z8.s, z17.s\n" "fmin z14.s, p2/M, z14.s, z16.s\n" "st1w { z14.s }, p0, [x22, x13, LSL #2]\n" "mov z14.d, z15.d\n" "fmin z12.s, p2/M, z12.s, z16.s\n" "st1w { z12.s }, p0, [x21, x13, LSL #2]\n" "mov z12.d, z15.d\n" "fmin z10.s, p2/M, z10.s, z16.s\n" "st1w { z10.s }, p0, [x20, x13, LSL #2]\n" "mov z10.d, z15.d\n" "fmin z8.s, p2/M, z8.s, z16.s\n" "st1w { z8.s }, p0, [x19, x13, LSL #2]\n" "mov z8.d, z15.d\n" "blt 1b\n" "2:" // Tail "fmla z14.s, p2/M, z13.s, z3.s\n" "incw x13\n" "fmla z12.s, p2/M, z13.s, z0.s\n" "mov p0.b, p1.b\n" "fmla z10.s, p2/M, z13.s, z31.s\n" "fmla z8.s, p2/M, z13.s, z30.s\n" "fmla z14.s, p2/M, z11.s, z0.s\n" "fmla z12.s, p2/M, z11.s, z29.s\n" "fmla z10.s, p2/M, z11.s, z30.s\n" "fmla z8.s, p2/M, z11.s, z28.s\n" "fmla z14.s, p2/M, z9.s, z29.s\n" "fmla z12.s, p2/M, z9.s, z27.s\n" "fmla z10.s, p2/M, z9.s, z28.s\n" "fmla z8.s, p2/M, z9.s, z26.s\n" "fmla z14.s, p2/M, z7.s, z31.s\n" "fmla z12.s, p2/M, z7.s, z30.s\n" "fmla z10.s, p2/M, z7.s, z25.s\n" "fmla z8.s, p2/M, z7.s, z24.s\n" "fmla z14.s, p2/M, z6.s, z30.s\n" "fmla z12.s, p2/M, z6.s, z28.s\n" "fmla z10.s, p2/M, z6.s, z24.s\n" "fmla z8.s, p2/M, z6.s, z23.s\n" "fmla z14.s, p2/M, z5.s, z28.s\n" "fmla z12.s, p2/M, z5.s, z26.s\n" "fmla z10.s, p2/M, z5.s, z23.s\n" "fmla z8.s, p2/M, z5.s, z22.s\n" "fmla z14.s, p2/M, z4.s, z25.s\n" "fmla z12.s, p2/M, z4.s, z24.s\n" "fmla z10.s, p2/M, z4.s, z21.s\n" "fmla z8.s, p2/M, z4.s, z20.s\n" "fmla z14.s, p2/M, z2.s, z24.s\n" "fmla z12.s, p2/M, z2.s, z23.s\n" "fmla z10.s, p2/M, z2.s, z20.s\n" "fmla z8.s, p2/M, z2.s, z19.s\n" "fmla z14.s, p2/M, z1.s, z23.s\n" "fmla z12.s, p2/M, z1.s, z22.s\n" "fmla z10.s, p2/M, z1.s, z19.s\n" "fmla z8.s, p2/M, z1.s, z18.s\n" "fmax z14.s, p2/M, z14.s, z17.s\n" "fmax z12.s, p2/M, z12.s, z17.s\n" "fmax z10.s, p2/M, z10.s, z17.s\n" "fmax z8.s, p2/M, z8.s, z17.s\n" "fmin z14.s, p2/M, z14.s, z16.s\n" "st1w { z14.s }, p0, [x22, x13, LSL #2]\n" "fmin z12.s, p2/M, z12.s, z16.s\n" "fmin z10.s, p2/M, z10.s, z16.s\n" "st1w { z12.s }, p0, [x21, x13, LSL #2]\n" "fmin z8.s, p2/M, z8.s, z16.s\n" "st1w { z10.s }, p0, [x20, x13, LSL #2]\n" "st1w { z8.s }, p0, [x19, x13, LSL #2]\n" : [params] "+r" (params) : [inptrs] "r" (inptrs), [minmax_vals] "r" (minmax_vals), [n_channels] "r" ((unsigned long) n_channels), [outptrs] "r" (outptrs) : "cc", "memory", "p0", "p1", "p2", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "z0", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8", "z9", "z10", "z11", "z12", "z13", "z14", "z15", "z16", "z17", "z18", "z19", "z20", "z21", "z22", "z23", "z24", "z25", "z26", "z27", "z28", "z29", "z30", "z31" ); } } // namespace depthwise } // namespace arm_conv #endif // defined(ARM_COMPUTE_ENABLE_SVE)
41.101563
377
0.529272
MaximMilashchenko
eddd0157faf869511f780c3e1521ca932fc1a630
7,434
cpp
C++
lib/SILGen/SwitchEnumBuilder.cpp
cachemeifyoucan/swift
6780f3d8c71904ba26c0fca33a1004b5776b9be2
[ "Apache-2.0" ]
null
null
null
lib/SILGen/SwitchEnumBuilder.cpp
cachemeifyoucan/swift
6780f3d8c71904ba26c0fca33a1004b5776b9be2
[ "Apache-2.0" ]
null
null
null
lib/SILGen/SwitchEnumBuilder.cpp
cachemeifyoucan/swift
6780f3d8c71904ba26c0fca33a1004b5776b9be2
[ "Apache-2.0" ]
null
null
null
//===--- SwitchEnumBuilder.cpp --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SwitchEnumBuilder.h" #include "SILGenFunction.h" #include "swift/SIL/SILLocation.h" using namespace swift; using namespace Lowering; //===----------------------------------------------------------------------===// // SwitchCaseFullExpr Implementation //===----------------------------------------------------------------------===// SwitchCaseFullExpr::SwitchCaseFullExpr(SILGenFunction &SGF, CleanupLocation loc) : SGF(SGF), scope(SGF, loc), loc(loc), branchDest() {} SwitchCaseFullExpr::SwitchCaseFullExpr(SILGenFunction &SGF, CleanupLocation loc, SwitchCaseBranchDest branchDest) : SGF(SGF), scope(SGF, loc), loc(loc), branchDest(branchDest) {} void SwitchCaseFullExpr::exitAndBranch(SILLocation loc, ArrayRef<SILValue> branchArgs) { assert(bool(branchDest) && "Must have a branch destination!"); assert(SGF.B.hasValidInsertionPoint()); scope.pop(); // Then either do a direct branch or a branch + cleanups. if (SILBasicBlock *block = branchDest.getBlock()) { SGF.B.createBranch(loc, block, branchArgs); return; } SGF.Cleanups.emitBranchAndCleanups(branchDest.getJumpDest(), loc, branchArgs); } void SwitchCaseFullExpr::exit() { assert(!bool(branchDest) && "Should not call this if we do have a continuation block"); assert(SGF.B.hasValidInsertionPoint()); scope.pop(); } SwitchCaseFullExpr::~SwitchCaseFullExpr() { assert(!scope.isValid() && "Did not pop scope?!"); } void SwitchCaseFullExpr::unreachableExit() { // This is important to ensure that we do not actually emit any cleanups since // we already know that an unreachable was emitted. assert(!SGF.B.hasValidInsertionPoint() && "Expected to pop scope without a " "valid insertion point!"); scope.pop(); } //===----------------------------------------------------------------------===// // SwitchEnumBuilder Implementation //===----------------------------------------------------------------------===// void SwitchEnumBuilder::emit() && { bool isAddressOnly = subjectExprOperand.getType().isAddressOnly(builder.getFunction()) && getSGF().silConv.useLoweredAddresses(); using DeclBlockPair = std::pair<EnumElementDecl *, SILBasicBlock *>; { // TODO: We could store the data in CaseBB form and not have to do this. llvm::SmallVector<DeclBlockPair, 8> caseBlocks; llvm::SmallVector<ProfileCounter, 8> caseBlockCounts; std::transform(caseDataArray.begin(), caseDataArray.end(), std::back_inserter(caseBlocks), [](NormalCaseData &caseData) -> DeclBlockPair { return {caseData.decl, caseData.block}; }); std::transform(caseDataArray.begin(), caseDataArray.end(), std::back_inserter(caseBlockCounts), [](NormalCaseData &caseData) -> ProfileCounter { return caseData.count; }); SILBasicBlock *defaultBlock = defaultBlockData ? defaultBlockData->block : nullptr; ProfileCounter defaultBlockCount = defaultBlockData ? defaultBlockData->count : ProfileCounter(); ArrayRef<ProfileCounter> caseBlockCountsRef = caseBlockCounts; if (isAddressOnly) { builder.createSwitchEnumAddr(loc, subjectExprOperand.getValue(), defaultBlock, caseBlocks, caseBlockCountsRef, defaultBlockCount); } else { if (subjectExprOperand.getType().isAddress()) { // TODO: Refactor this into a maybe load. if (subjectExprOperand.hasCleanup()) { subjectExprOperand = builder.createLoadTake(loc, subjectExprOperand); } else { subjectExprOperand = builder.createLoadCopy(loc, subjectExprOperand); } } builder.createSwitchEnum(loc, subjectExprOperand.forward(getSGF()), defaultBlock, caseBlocks, caseBlockCountsRef, defaultBlockCount); } } // If we are asked to create a default block and it is specified that the // default block should be emitted before normal cases, emit it now. if (defaultBlockData && defaultBlockData->dispatchTime == DefaultDispatchTime::BeforeNormalCases) { SILBasicBlock *defaultBlock = defaultBlockData->block; SwitchCaseBranchDest branchDest = defaultBlockData->branchDest; DefaultCaseHandler handler = defaultBlockData->handler; // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); builder.emitBlock(defaultBlock); ManagedValue input = subjectExprOperand; if (!isAddressOnly) { input = builder.createOwnedPhiArgument(subjectExprOperand.getType()); } handler(input, std::move(presentScope)); builder.clearInsertionPoint(); } for (NormalCaseData &caseData : caseDataArray) { EnumElementDecl *decl = caseData.decl; SILBasicBlock *caseBlock = caseData.block; SwitchCaseBranchDest branchDest = caseData.branchDest; NormalCaseHandler handler = caseData.handler; // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); builder.emitBlock(caseBlock); ManagedValue input; if (decl->hasAssociatedValues()) { // Pull the payload out if we have one. SILType inputType = subjectExprOperand.getType().getEnumElementType( decl, builder.getModule(), builder.getFunction()); input = subjectExprOperand; if (!isAddressOnly) { input = builder.createOwnedPhiArgument(inputType); } } handler(input, std::move(presentScope)); builder.clearInsertionPoint(); } // If we are asked to create a default block and it is specified that the // default block should be emitted after normal cases, emit it now. if (defaultBlockData && defaultBlockData->dispatchTime == DefaultDispatchTime::AfterNormalCases) { SILBasicBlock *defaultBlock = defaultBlockData->block; auto branchDest = defaultBlockData->branchDest; DefaultCaseHandler handler = defaultBlockData->handler; // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); builder.emitBlock(defaultBlock); ManagedValue input = subjectExprOperand; if (!isAddressOnly) { input = builder.createOwnedPhiArgument(subjectExprOperand.getType()); } handler(input, std::move(presentScope)); builder.clearInsertionPoint(); } }
41.530726
80
0.631558
cachemeifyoucan
eddea833e533ef3eef3c32489e43f60cbe801c73
3,938
cc
C++
base/scoped_temp_dir_unittest.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
base/scoped_temp_dir_unittest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
base/scoped_temp_dir_unittest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/file_util.h" #include "base/platform_file.h" #include "base/scoped_temp_dir.h" #include "testing/gtest/include/gtest/gtest.h" TEST(ScopedTempDir, FullPath) { FilePath test_path; file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_temp_dir"), &test_path); // Against an existing dir, it should get destroyed when leaving scope. EXPECT_TRUE(file_util::DirectoryExists(test_path)); { ScopedTempDir dir; EXPECT_TRUE(dir.Set(test_path)); EXPECT_TRUE(dir.IsValid()); } EXPECT_FALSE(file_util::DirectoryExists(test_path)); { ScopedTempDir dir; EXPECT_TRUE(dir.Set(test_path)); // Now the dir doesn't exist, so ensure that it gets created. EXPECT_TRUE(file_util::DirectoryExists(test_path)); // When we call Release(), it shouldn't get destroyed when leaving scope. FilePath path = dir.Take(); EXPECT_EQ(path.value(), test_path.value()); EXPECT_FALSE(dir.IsValid()); } EXPECT_TRUE(file_util::DirectoryExists(test_path)); // Clean up. { ScopedTempDir dir; EXPECT_TRUE(dir.Set(test_path)); } EXPECT_FALSE(file_util::DirectoryExists(test_path)); } TEST(ScopedTempDir, TempDir) { // In this case, just verify that a directory was created and that it's a // child of TempDir. FilePath test_path; { ScopedTempDir dir; EXPECT_TRUE(dir.CreateUniqueTempDir()); test_path = dir.path(); EXPECT_TRUE(file_util::DirectoryExists(test_path)); FilePath tmp_dir; EXPECT_TRUE(file_util::GetTempDir(&tmp_dir)); EXPECT_TRUE(test_path.value().find(tmp_dir.value()) != std::string::npos); } EXPECT_FALSE(file_util::DirectoryExists(test_path)); } TEST(ScopedTempDir, UniqueTempDirUnderPath) { // Create a path which will contain a unique temp path. FilePath base_path; ASSERT_TRUE(file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("base_dir"), &base_path)); FilePath test_path; { ScopedTempDir dir; EXPECT_TRUE(dir.CreateUniqueTempDirUnderPath(base_path)); test_path = dir.path(); EXPECT_TRUE(file_util::DirectoryExists(test_path)); EXPECT_TRUE(base_path.IsParent(test_path)); EXPECT_TRUE(test_path.value().find(base_path.value()) != std::string::npos); } EXPECT_FALSE(file_util::DirectoryExists(test_path)); file_util::Delete(base_path, true); } TEST(ScopedTempDir, MultipleInvocations) { ScopedTempDir dir; EXPECT_TRUE(dir.CreateUniqueTempDir()); EXPECT_FALSE(dir.CreateUniqueTempDir()); EXPECT_TRUE(dir.Delete()); EXPECT_TRUE(dir.CreateUniqueTempDir()); EXPECT_FALSE(dir.CreateUniqueTempDir()); ScopedTempDir other_dir; EXPECT_TRUE(other_dir.Set(dir.Take())); EXPECT_TRUE(dir.CreateUniqueTempDir()); EXPECT_FALSE(dir.CreateUniqueTempDir()); EXPECT_FALSE(other_dir.CreateUniqueTempDir()); } #if defined(OS_WIN) TEST(ScopedTempDir, LockedTempDir) { ScopedTempDir dir; EXPECT_TRUE(dir.CreateUniqueTempDir()); int file_flags = base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_WRITE; base::PlatformFileError error_code = base::PLATFORM_FILE_OK; FilePath file_path(dir.path().Append(FILE_PATH_LITERAL("temp"))); base::PlatformFile file = base::CreatePlatformFile(file_path, file_flags, NULL, &error_code); EXPECT_NE(base::kInvalidPlatformFileValue, file); EXPECT_EQ(base::PLATFORM_FILE_OK, error_code); EXPECT_FALSE(dir.Delete()); // We should not be able to delete. EXPECT_FALSE(dir.path().empty()); // We should still have a valid path. EXPECT_TRUE(base::ClosePlatformFile(file)); // Now, we should be able to delete. EXPECT_TRUE(dir.Delete()); } #endif // defined(OS_WIN)
34.54386
80
0.711529
Scopetta197
ede2e7a54790e442082fb21277b629c73014699b
3,176
cpp
C++
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/common/sysopt.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
471
2019-06-26T09:59:09.000Z
2022-03-30T04:59:42.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/common/sysopt.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/common/sysopt.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
///////////////////////////////////////////////////////////////////////////// // Name: src/common/sysopt.cpp // Purpose: wxSystemOptions // Author: Julian Smart // Modified by: // Created: 2001-07-10 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // --------------------------------------------------------------------------- // headers // --------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #if defined(__BORLANDC__) #pragma hdrstop #endif #if wxUSE_SYSTEM_OPTIONS #include "wx/sysopt.h" #ifndef WX_PRECOMP #include "wx/app.h" #include "wx/list.h" #include "wx/string.h" #include "wx/arrstr.h" #endif // ---------------------------------------------------------------------------- // private globals // ---------------------------------------------------------------------------- static wxArrayString gs_optionNames, gs_optionValues; // ============================================================================ // wxSystemOptions implementation // ============================================================================ // Option functions (arbitrary name/value mapping) void wxSystemOptions::SetOption(const wxString& name, const wxString& value) { int idx = gs_optionNames.Index(name, false); if (idx == wxNOT_FOUND) { gs_optionNames.Add(name); gs_optionValues.Add(value); } else { gs_optionNames[idx] = name; gs_optionValues[idx] = value; } } void wxSystemOptions::SetOption(const wxString& name, int value) { SetOption(name, wxString::Format(wxT("%d"), value)); } wxString wxSystemOptions::GetOption(const wxString& name) { wxString val; int idx = gs_optionNames.Index(name, false); if ( idx != wxNOT_FOUND ) { val = gs_optionValues[idx]; } else // not set explicitly { // look in the environment: first for a variable named "wx_appname_name" // which can be set to affect the behaviour or just this application // and then for "wx_name" which can be set to change the option globally wxString var(name); var.Replace(wxT("."), wxT("_")); // '.'s not allowed in env var names var.Replace(wxT("-"), wxT("_")); // and neither are '-'s wxString appname; if ( wxTheApp ) appname = wxTheApp->GetAppName(); if ( !appname.empty() ) val = wxGetenv(wxT("wx_") + appname + wxT('_') + var); if ( val.empty() ) val = wxGetenv(wxT("wx_") + var); } return val; } int wxSystemOptions::GetOptionInt(const wxString& name) { return wxAtoi (GetOption(name)); } bool wxSystemOptions::HasOption(const wxString& name) { return !GetOption(name).empty(); } #endif // wxUSE_SYSTEM_OPTIONS
28.357143
80
0.471977
madanagopaltcomcast
ede71ec889767958aaeaabc0f5d3e3b97c2b0069
1,498
cpp
C++
samples/SamplesCommon/Parameters.cpp
alarouche/czrpc
cb2d7611d701152ace8e31230f64c0fb12e48276
[ "MIT" ]
30
2017-06-11T10:36:05.000Z
2021-09-22T13:09:40.000Z
samples/SamplesCommon/Parameters.cpp
alarouche/czrpc
cb2d7611d701152ace8e31230f64c0fb12e48276
[ "MIT" ]
1
2018-01-24T09:49:51.000Z
2018-01-24T09:49:51.000Z
samples/SamplesCommon/Parameters.cpp
alarouche/czrpc
cb2d7611d701152ace8e31230f64c0fb12e48276
[ "MIT" ]
6
2018-02-16T17:02:48.000Z
2021-09-22T13:09:44.000Z
/******************************************************************** CrazyGaze (http://www.crazygaze.com) Author : Rui Figueira Email : rui@crazygaze.com purpose: *********************************************************************/ #include "SamplesCommonPCH.h" #include "Parameters.h" namespace cz { std::string Parameters::ms_empty; Parameters::Parameters() { } void Parameters::set(int argc, char* argv[]) { if (argc<=1) return; for (int i=1; i<argc; i++) { const char *arg = argv[i]; if (*arg == '-') arg++; const char *seperator = strchr(arg, '='); if (seperator==nullptr) { m_args.emplace_back(arg, ""); } else { std::string name(arg, seperator); std::string value(++seperator); m_args.emplace_back(std::move(name), std::move(value)); } } } const Parameters::Param* Parameters::begin() const { if (m_args.size()) return &m_args[0]; else return nullptr; } const Parameters::Param* Parameters::end() const { return begin() + m_args.size(); } bool Parameters::has( const char* name ) const { for(auto &i: m_args) { if (i.name==name) { return true; } } return false; } bool Parameters::has( const std::string& name ) const { return has(name.c_str()); } const std::string& Parameters::get( const char *name ) const { for (auto &i: m_args) { if (i.name==name) return i.value; } return ms_empty; } } // namespace cz
16.831461
71
0.535381
alarouche
edea3c1be60b87c60f412f998c78bc3592f35d15
2,402
cpp
C++
cpp/godot-cpp/src/gen/Skin.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/Skin.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/Skin.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "Skin.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" namespace godot { Skin::___method_bindings Skin::___mb = {}; void Skin::___init_method_bindings() { ___mb.mb_add_bind = godot::api->godot_method_bind_get_method("Skin", "add_bind"); ___mb.mb_clear_binds = godot::api->godot_method_bind_get_method("Skin", "clear_binds"); ___mb.mb_get_bind_bone = godot::api->godot_method_bind_get_method("Skin", "get_bind_bone"); ___mb.mb_get_bind_count = godot::api->godot_method_bind_get_method("Skin", "get_bind_count"); ___mb.mb_get_bind_pose = godot::api->godot_method_bind_get_method("Skin", "get_bind_pose"); ___mb.mb_set_bind_bone = godot::api->godot_method_bind_get_method("Skin", "set_bind_bone"); ___mb.mb_set_bind_count = godot::api->godot_method_bind_get_method("Skin", "set_bind_count"); ___mb.mb_set_bind_pose = godot::api->godot_method_bind_get_method("Skin", "set_bind_pose"); } Skin *Skin::_new() { return (Skin *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"Skin")()); } void Skin::add_bind(const int64_t bone, const Transform pose) { ___godot_icall_void_int_Transform(___mb.mb_add_bind, (const Object *) this, bone, pose); } void Skin::clear_binds() { ___godot_icall_void(___mb.mb_clear_binds, (const Object *) this); } int64_t Skin::get_bind_bone(const int64_t bind_index) const { return ___godot_icall_int_int(___mb.mb_get_bind_bone, (const Object *) this, bind_index); } int64_t Skin::get_bind_count() const { return ___godot_icall_int(___mb.mb_get_bind_count, (const Object *) this); } Transform Skin::get_bind_pose(const int64_t bind_index) const { return ___godot_icall_Transform_int(___mb.mb_get_bind_pose, (const Object *) this, bind_index); } void Skin::set_bind_bone(const int64_t bind_index, const int64_t bone) { ___godot_icall_void_int_int(___mb.mb_set_bind_bone, (const Object *) this, bind_index, bone); } void Skin::set_bind_count(const int64_t bind_count) { ___godot_icall_void_int(___mb.mb_set_bind_count, (const Object *) this, bind_count); } void Skin::set_bind_pose(const int64_t bind_index, const Transform pose) { ___godot_icall_void_int_Transform(___mb.mb_set_bind_pose, (const Object *) this, bind_index, pose); } }
36.393939
189
0.781848
GDNative-Gradle
edeaaed446c368381793291a8d06207a17f67178
17,763
cc
C++
third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_test.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "base/bind.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "media/video/mock_gpu_video_accelerator_factories.h" #include "media/video/mock_video_encode_accelerator.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.h" #include "third_party/libyuv/include/libyuv/planar_functions.h" #include "third_party/webrtc/api/video/i420_buffer.h" #include "third_party/webrtc/api/video_codecs/video_encoder.h" #include "third_party/webrtc/modules/video_coding/include/video_codec_interface.h" #include "third_party/webrtc/rtc_base/time_utils.h" using ::testing::_; using ::testing::AtLeast; using ::testing::Invoke; using ::testing::Return; using ::testing::SaveArg; using ::testing::Values; using ::testing::WithArgs; namespace blink { namespace { const int kInputFrameFillY = 12; const int kInputFrameFillU = 23; const int kInputFrameFillV = 34; const uint16_t kInputFrameHeight = 234; const uint16_t kInputFrameWidth = 345; const uint16_t kStartBitrate = 100; class EncodedImageCallbackWrapper : public webrtc::EncodedImageCallback { public: using EncodedCallback = base::OnceCallback<void( const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codec_specific_info)>; EncodedImageCallbackWrapper(EncodedCallback encoded_callback) : encoded_callback_(std::move(encoded_callback)) {} Result OnEncodedImage( const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codec_specific_info) override { std::move(encoded_callback_).Run(encoded_image, codec_specific_info); return Result(Result::OK); } private: EncodedCallback encoded_callback_; }; } // anonymous namespace class RTCVideoEncoderTest : public ::testing::TestWithParam<webrtc::VideoCodecType> { public: RTCVideoEncoderTest() : encoder_thread_("vea_thread"), mock_gpu_factories_( new media::MockGpuVideoAcceleratorFactories(nullptr)), idle_waiter_(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED) {} media::MockVideoEncodeAccelerator* ExpectCreateInitAndDestroyVEA() { // The VEA will be owned by the RTCVideoEncoder once // factory.CreateVideoEncodeAccelerator() is called. media::MockVideoEncodeAccelerator* mock_vea = new media::MockVideoEncodeAccelerator(); EXPECT_CALL(*mock_gpu_factories_.get(), DoCreateVideoEncodeAccelerator()) .WillRepeatedly(Return(mock_vea)); EXPECT_CALL(*mock_vea, Initialize(_, _)) .WillOnce(Invoke(this, &RTCVideoEncoderTest::Initialize)); EXPECT_CALL(*mock_vea, UseOutputBitstreamBuffer(_)).Times(AtLeast(3)); EXPECT_CALL(*mock_vea, Destroy()).Times(1); return mock_vea; } void SetUp() override { DVLOG(3) << __func__; ASSERT_TRUE(encoder_thread_.Start()); EXPECT_CALL(*mock_gpu_factories_.get(), GetTaskRunner()) .WillRepeatedly(Return(encoder_thread_.task_runner())); mock_vea_ = ExpectCreateInitAndDestroyVEA(); } void TearDown() override { DVLOG(3) << __func__; EXPECT_TRUE(encoder_thread_.IsRunning()); RunUntilIdle(); rtc_encoder_->Release(); RunUntilIdle(); encoder_thread_.Stop(); } void RunUntilIdle() { DVLOG(3) << __func__; encoder_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&idle_waiter_))); idle_waiter_.Wait(); } void CreateEncoder(webrtc::VideoCodecType codec_type) { DVLOG(3) << __func__; media::VideoCodecProfile media_profile; switch (codec_type) { case webrtc::kVideoCodecVP8: media_profile = media::VP8PROFILE_ANY; break; case webrtc::kVideoCodecH264: media_profile = media::H264PROFILE_BASELINE; break; case webrtc::kVideoCodecVP9: media_profile = media::VP9PROFILE_PROFILE0; break; default: ADD_FAILURE() << "Unexpected codec type: " << codec_type; media_profile = media::VIDEO_CODEC_PROFILE_UNKNOWN; } rtc_encoder_ = std::make_unique<RTCVideoEncoder>(media_profile, false, mock_gpu_factories_.get()); } // media::VideoEncodeAccelerator implementation. bool Initialize(const media::VideoEncodeAccelerator::Config& config, media::VideoEncodeAccelerator::Client* client) { DVLOG(3) << __func__; client_ = client; client_->RequireBitstreamBuffers(0, config.input_visible_size, config.input_visible_size.GetArea()); return true; } void RegisterEncodeCompleteCallback( EncodedImageCallbackWrapper::EncodedCallback callback) { callback_wrapper_ = std::make_unique<EncodedImageCallbackWrapper>(std::move(callback)); rtc_encoder_->RegisterEncodeCompleteCallback(callback_wrapper_.get()); } webrtc::VideoCodec GetDefaultCodec() { webrtc::VideoCodec codec = {}; memset(&codec, 0, sizeof(codec)); codec.width = kInputFrameWidth; codec.height = kInputFrameHeight; codec.codecType = webrtc::kVideoCodecVP8; codec.startBitrate = kStartBitrate; return codec; } webrtc::VideoCodec GetDefaultTemporalLayerCodec() { const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP9; webrtc::VideoCodec codec{}; codec.codecType = codec_type; codec.width = kInputFrameWidth; codec.height = kInputFrameHeight; codec.startBitrate = kStartBitrate; codec.maxBitrate = codec.startBitrate * 2; codec.minBitrate = codec.startBitrate / 2; codec.maxFramerate = 24; codec.active = true; codec.qpMax = 30; codec.numberOfSimulcastStreams = 1; codec.mode = webrtc::VideoCodecMode::kRealtimeVideo; webrtc::VideoCodecVP9& vp9 = *codec.VP9(); vp9.numberOfTemporalLayers = 3; vp9.numberOfSpatialLayers = 1; webrtc::SpatialLayer& sl = codec.spatialLayers[0]; sl.width = kInputFrameWidth; sl.height = kInputFrameHeight; sl.maxFramerate = 24; sl.numberOfTemporalLayers = vp9.numberOfTemporalLayers; sl.targetBitrate = kStartBitrate; sl.maxBitrate = sl.targetBitrate; sl.minBitrate = sl.targetBitrate; sl.qpMax = 30; sl.active = true; return codec; } void FillFrameBuffer(rtc::scoped_refptr<webrtc::I420Buffer> frame) { CHECK(libyuv::I420Rect(frame->MutableDataY(), frame->StrideY(), frame->MutableDataU(), frame->StrideU(), frame->MutableDataV(), frame->StrideV(), 0, 0, frame->width(), frame->height(), kInputFrameFillY, kInputFrameFillU, kInputFrameFillV) == 0); } void VerifyEncodedFrame(scoped_refptr<media::VideoFrame> frame, bool force_keyframe) { DVLOG(3) << __func__; EXPECT_EQ(kInputFrameWidth, frame->visible_rect().width()); EXPECT_EQ(kInputFrameHeight, frame->visible_rect().height()); EXPECT_EQ(kInputFrameFillY, frame->visible_data(media::VideoFrame::kYPlane)[0]); EXPECT_EQ(kInputFrameFillU, frame->visible_data(media::VideoFrame::kUPlane)[0]); EXPECT_EQ(kInputFrameFillV, frame->visible_data(media::VideoFrame::kVPlane)[0]); } void ReturnFrameWithTimeStamp(scoped_refptr<media::VideoFrame> frame, bool force_keyframe) { client_->BitstreamBufferReady( 0, media::BitstreamBufferMetadata(0, force_keyframe, frame->timestamp())); } void ReturnTemporalLayerFrameWithVp9Metadata( scoped_refptr<media::VideoFrame> frame, bool force_keyframe) { int32_t bitstream_buffer_id = frame->timestamp().InMicroseconds(); CHECK(0 <= bitstream_buffer_id && bitstream_buffer_id <= 4); media::BitstreamBufferMetadata metadata(100u /* payload_size_bytes */, force_keyframe, frame->timestamp()); // Assume the number of TLs is three. TL structure is below. // TL2: [#1] /-[#3] // TL1: /_____[#2] / // TL0: [#0]-----------------[#4] media::Vp9Metadata vp9; vp9.has_reference = bitstream_buffer_id != 0 && !force_keyframe; vp9.temporal_up_switch = bitstream_buffer_id != 3; switch (bitstream_buffer_id) { case 0: vp9.temporal_idx = 0; break; case 1: vp9.temporal_idx = 2; vp9.p_diffs = {1}; break; case 2: vp9.temporal_idx = 1; vp9.p_diffs = {2}; break; case 3: vp9.temporal_idx = 2; vp9.p_diffs = {1, 3}; break; case 4: vp9.temporal_idx = 0; vp9.p_diffs = {4}; break; } metadata.vp9 = vp9; client_->BitstreamBufferReady(bitstream_buffer_id, metadata); } void VerifyTimestamp(uint32_t rtp_timestamp, int64_t capture_time_ms, const webrtc::EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codec_specific_info) { DVLOG(3) << __func__; EXPECT_EQ(rtp_timestamp, encoded_image.Timestamp()); EXPECT_EQ(capture_time_ms, encoded_image.capture_time_ms_); } protected: media::MockVideoEncodeAccelerator* mock_vea_; std::unique_ptr<RTCVideoEncoder> rtc_encoder_; media::VideoEncodeAccelerator::Client* client_; base::Thread encoder_thread_; private: std::unique_ptr<media::MockGpuVideoAcceleratorFactories> mock_gpu_factories_; std::unique_ptr<EncodedImageCallbackWrapper> callback_wrapper_; base::WaitableEvent idle_waiter_; }; TEST_P(RTCVideoEncoderTest, CreateAndInitSucceeds) { const webrtc::VideoCodecType codec_type = GetParam(); CreateEncoder(codec_type); webrtc::VideoCodec codec = GetDefaultCodec(); codec.codecType = codec_type; EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); } TEST_P(RTCVideoEncoderTest, RepeatedInitSucceeds) { const webrtc::VideoCodecType codec_type = GetParam(); CreateEncoder(codec_type); webrtc::VideoCodec codec = GetDefaultCodec(); codec.codecType = codec_type; EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); ExpectCreateInitAndDestroyVEA(); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); } INSTANTIATE_TEST_SUITE_P(CodecProfiles, RTCVideoEncoderTest, Values(webrtc::kVideoCodecVP8, webrtc::kVideoCodecH264)); TEST_F(RTCVideoEncoderTest, CreateAndInitSucceedsForTemporalLayer) { webrtc::VideoCodec tl_codec = GetDefaultTemporalLayerCodec(); CreateEncoder(tl_codec.codecType); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&tl_codec, 1, 12345)); } // Checks that WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE is returned when there is // platform error. TEST_F(RTCVideoEncoderTest, SoftwareFallbackAfterError) { const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP8; CreateEncoder(codec_type); webrtc::VideoCodec codec = GetDefaultCodec(); codec.codecType = codec_type; EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); EXPECT_CALL(*mock_vea_, Encode(_, _)) .WillOnce(Invoke([this](scoped_refptr<media::VideoFrame>, bool) { encoder_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce( &media::VideoEncodeAccelerator::Client::NotifyError, base::Unretained(client_), media::VideoEncodeAccelerator::kPlatformFailureError)); })); const rtc::scoped_refptr<webrtc::I420Buffer> buffer = webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight); FillFrameBuffer(buffer); std::vector<webrtc::VideoFrameType> frame_types; EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->Encode(webrtc::VideoFrame::Builder() .set_video_frame_buffer(buffer) .set_timestamp_rtp(0) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0) .build(), &frame_types)); RunUntilIdle(); // Expect the next frame to return SW fallback. EXPECT_EQ(WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE, rtc_encoder_->Encode(webrtc::VideoFrame::Builder() .set_video_frame_buffer(buffer) .set_timestamp_rtp(0) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0) .build(), &frame_types)); } TEST_F(RTCVideoEncoderTest, EncodeScaledFrame) { const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP8; CreateEncoder(codec_type); webrtc::VideoCodec codec = GetDefaultCodec(); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); EXPECT_CALL(*mock_vea_, Encode(_, _)) .Times(2) .WillRepeatedly(Invoke(this, &RTCVideoEncoderTest::VerifyEncodedFrame)); const rtc::scoped_refptr<webrtc::I420Buffer> buffer = webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight); FillFrameBuffer(buffer); std::vector<webrtc::VideoFrameType> frame_types; EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->Encode(webrtc::VideoFrame::Builder() .set_video_frame_buffer(buffer) .set_timestamp_rtp(0) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0) .build(), &frame_types)); const rtc::scoped_refptr<webrtc::I420Buffer> upscaled_buffer = webrtc::I420Buffer::Create(2 * kInputFrameWidth, 2 * kInputFrameHeight); FillFrameBuffer(upscaled_buffer); webrtc::VideoFrame rtc_frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(upscaled_buffer) .set_timestamp_rtp(0) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0) .build(); rtc_frame.set_ntp_time_ms(123456); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->Encode(rtc_frame, &frame_types)); } TEST_F(RTCVideoEncoderTest, PreserveTimestamps) { const webrtc::VideoCodecType codec_type = webrtc::kVideoCodecVP8; CreateEncoder(codec_type); webrtc::VideoCodec codec = GetDefaultCodec(); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&codec, 1, 12345)); const uint32_t rtp_timestamp = 1234567; const uint32_t capture_time_ms = 3456789; RegisterEncodeCompleteCallback( base::BindOnce(&RTCVideoEncoderTest::VerifyTimestamp, base::Unretained(this), rtp_timestamp, capture_time_ms)); EXPECT_CALL(*mock_vea_, Encode(_, _)) .WillOnce(Invoke(this, &RTCVideoEncoderTest::ReturnFrameWithTimeStamp)); const rtc::scoped_refptr<webrtc::I420Buffer> buffer = webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight); FillFrameBuffer(buffer); std::vector<webrtc::VideoFrameType> frame_types; webrtc::VideoFrame rtc_frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(buffer) .set_timestamp_rtp(rtp_timestamp) .set_timestamp_us(0) .set_rotation(webrtc::kVideoRotation_0) .build(); rtc_frame.set_timestamp_us(capture_time_ms * rtc::kNumMicrosecsPerMillisec); // We need to set ntp_time_ms because it will be used to derive // media::VideoFrame timestamp. rtc_frame.set_ntp_time_ms(4567891); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->Encode(rtc_frame, &frame_types)); } TEST_F(RTCVideoEncoderTest, EncodeTemporalLayer) { webrtc::VideoCodec tl_codec = GetDefaultTemporalLayerCodec(); CreateEncoder(tl_codec.codecType); EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->InitEncode(&tl_codec, 1, 12345)); size_t kNumEncodeFrames = 5u; EXPECT_CALL(*mock_vea_, Encode(_, _)) .Times(kNumEncodeFrames) .WillRepeatedly(Invoke( this, &RTCVideoEncoderTest::ReturnTemporalLayerFrameWithVp9Metadata)); for (size_t i = 0; i < kNumEncodeFrames; i++) { const rtc::scoped_refptr<webrtc::I420Buffer> buffer = webrtc::I420Buffer::Create(kInputFrameWidth, kInputFrameHeight); FillFrameBuffer(buffer); std::vector<webrtc::VideoFrameType> frame_types; EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, rtc_encoder_->Encode(webrtc::VideoFrame::Builder() .set_video_frame_buffer(buffer) .set_timestamp_rtp(0) .set_timestamp_us(i) .set_rotation(webrtc::kVideoRotation_0) .build(), &frame_types)); } } } // namespace blink
39.473333
82
0.660361
mghgroup
edeb1b7a00cce0c49960a76b69fe0b8db0f4b374
25,545
cpp
C++
source/Visitors/TerrainBrush.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/Visitors/TerrainBrush.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/Visitors/TerrainBrush.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
#include "TerrainBrush.h" #include "../Kernel/Gateway.h" #include "../Geometry/Ray3D.h" #include "../Factories/TerrainVisuals.h" #include "../Factories/TerrainPasture.h" #include "../Factories/TerrainLogic.h" #include "../Factories/WorldVisuals.h" #include "../Factories/Meadow.h" #include "../Factories/Water.h" #include "../Managers/ManagersUtils.h" #include "../Controllers/VillageModelController.h" #include "../Controllers/TileController.h" #include "../Databases/TerrainDatabase.h" #include "../Databases/ModelDatabase.h" #include "../Nodes/SpatialIndexNode.h" #include "../Nodes/SpatialIndexCell.h" #include "../Nodes/TransformGroup.h" #include "../Tools/NodeIterator.h" #include "../Tools/RangeIterator.h" #include "../Strategies/BrushBitEStrategy.h" #include "../Strategies/BrushBitDStrategy.h" #include "../Containers/ocsort.h" TerrainBrush::TerrainBrush() { strategies.append(new BrushBitEStrategy()); strategies.append(new BrushBitDStrategy()); reset(); } void TerrainBrush::visit(SpatialIndexBaseNode* node) { pointAVLTree.clear(); if (intersect(&node->getBoundsDescriptor())) { NodeIterator iter(node->getFirstChild()); while (!iter.end()) { iter.current()->accept(this); iter++; } } if (pointAVLTree.isEmpty()) return; if (saveCollPoint) { AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); if (!enabled) return; } switch (type) { case BrushTypes::TILE: editTiles(); break; case BrushTypes::GRASS: editGrass(); break; case BrushTypes::WATER: editWater(); break; case BrushTypes::MODEL: editModel(); break; default: break; } } void TerrainBrush::visit(SpatialIndexNode* node) { if (intersect(&node->getBoundsDescriptor())) { NodeIterator iter(node->getFirstChild()); while (!iter.end()) { iter.current()->accept(this); iter++; } } } void TerrainBrush::visit(SpatialIndexCell* node) { BoundsDescriptor *bounds = &node->getBoundsDescriptor(); TileController* controller; RangeIterator iter; Tuple4f packet; Tuple3f point; float distance; TerrainVisuals* visuals = Gateway::getTerrainVisuals(); TerrainDatabase* tdatabase = Gateway::getTerrainDatabase(); if (node->isVisible()) if (intersect(bounds)) { if (showGuides) { glColor3ub(255, 255, 255); bounds->render(BoundsDescriptor::AABB | BoundsDescriptor::WIRE); } if (enabled || saveCollPoint) { iter.set(visuals->getArea().x, node->getRange()); while (!iter.end()) { controller = tdatabase->getController(iter.current()); packet = intersector.intersectTriangles(ray, controller->getVertices(), visuals->getTileIndices(0), 8); if (1 == packet.w) { point.set(packet.x, packet.y, packet.z); distance = point.getDistance(ray->getOrigin()); if (2.0f < distance) pointAVLTree.insertKeyAndValue(distance, point); } iter++; } } } } void TerrainBrush::editModel() { ModelDatabase *ndatabase, *sdatabase, *vdatabase, *cdatabase; WorldVisuals* wVisuals; //int ctrlindex; GSElementInfo* info; ModelController* controller; AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); switch (layer) { case BrushLayers::CHARACTER: if (constant) { info = Gateway::getActiveCharacterInfo(); if (info->name) { cdatabase = Gateway::getCharacterDatabase(); controller = cdatabase->instantiateModel(info->name); controller->translateModel(cpoint.x, cpoint.y + 0.05f, cpoint.z); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); Gateway::getMapDescriptor().playerPositions.append(Tuple2f(cpoint.x, cpoint.z)); } } break; case BrushLayers::CRITTER: if (constant) { info = Gateway::getActiveCritterInfo(); if (info->name) { cdatabase = Gateway::getCritterDatabase(); controller = cdatabase->instantiateModel(info->name); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); float y = controller->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y; Tuple3f cen = controller->getTransformGroup()->getBoundsDescriptor().getCenterAABB(); controller->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z); wVisuals = Gateway::getWorldVisuals(); WorldObject worldObject; worldObject.flags = 0; worldObject.name = info->name; worldObject.type = WorldObjectTypes::CRITTER; worldObject.orientation = 0.0f; worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z); worldObject.windFactor = 0.0f; wVisuals->addObject(worldObject); } } break; case BrushLayers::NATURE: if (constant) { info = Gateway::getActiveNatureInfo(); if (info->name) { ndatabase = Gateway::getNatureDatabase(); controller = ndatabase->instantiateModel(info->name); controller->translateModel(cpoint.x, cpoint.y + 0.05f, cpoint.z); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); ///cannot subtract y because that would cause a problem with canopy models wVisuals = Gateway::getWorldVisuals(); WorldObject worldObject; worldObject.flags = 0; worldObject.name = info->name; worldObject.type = WorldObjectTypes::NATURE; worldObject.orientation = 0.79f; worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z); worldObject.windFactor = info->windFactor; wVisuals->addObject(worldObject); } } break; case BrushLayers::STRUCTURE: if (constant) { info = Gateway::getActiveStructureInfo(); if (info->name) { sdatabase = Gateway::getStructureDatabase(); controller = sdatabase->instantiateModel(info->name); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); float y = controller->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y; Tuple3f cen = controller->getTransformGroup()->getBoundsDescriptor().getCenterAABB(); controller->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z); wVisuals = Gateway::getWorldVisuals(); WorldObject worldObject; worldObject.flags = 0; worldObject.name = info->name; worldObject.type = WorldObjectTypes::STRUCTURE; worldObject.orientation = 0.0f; worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z); worldObject.windFactor = 0.0f; wVisuals->addObject(worldObject); } } break; case BrushLayers::VILLAGE: if (constant) { info = Gateway::getActiveVillageInfo(); if (info->name) { vdatabase = Gateway::getVillageDatabase(); VillageModelController* villageController = (VillageModelController*) vdatabase->instantiateModel(info->name); villageController->setPopulation(info->population); villageController->setMaxPopulation(info->maxpopulation); float y = villageController->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y; Tuple3f cen = villageController->getTransformGroup()->getBoundsDescriptor().getCenterAABB(); villageController->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z); } } break; default: break; } } void TerrainBrush::editTiles() { if (layer != BrushLayers::TILE) return; TileController *controller; Tuple3f *verts; Tuple4ub *cols; float s, y, d; unsigned int lflag; char col; RangeIterator tileiter; TerrainVisuals* visuals = Gateway::getTerrainVisuals(); TerrainLogic* terrainLogic = Gateway::getTerrainLogic(); TerrainDatabase* tdatabase = Gateway::getTerrainDatabase(); AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); if (mode == BrushModes::FILL) { if (constant) if (txcoordsIndex >= 0) for (unsigned int i = 0; i < tdatabase->getControllerCount(); i++) tdatabase->changeTileTexture(level, txcoordsIndex, i, !tdatabase->getController(i)->isVisible()); return; } ++pointIter; cpoint = pointIter.value(); Tuple2i area(visuals->getArea()); unsigned int xOff = clamp(int(cpoint.x - radius), 0, area.y - 1); unsigned int yOff = clamp(int(cpoint.z - radius), 0, area.x - 1); unsigned int zOff = clamp(int(cpoint.x + radius), 0, area.y - 1); unsigned int wOff = clamp(int(cpoint.z + radius), 0, area.x - 1); tileiter.set(area.x, Tuple4i(yOff, xOff, wOff, zOff)); glPointSize(2.0f); glColor3ub(255, 200, 0); glBegin(GL_POINTS); while (!tileiter.end()) { controller = tdatabase->getController(tileiter.current()); verts = controller->getVertices(); cols = controller->getColors(); switch (mode) { case BrushModes::ROTATE90: if (constant) controller->setFlags(TileFlags::TEXTURE_ROTATE90); break; case BrushModes::ROTATE180: if (constant) controller->setFlags(TileFlags::TEXTURE_ROTATE180); break; case BrushModes::ROTATE270: if (constant) controller->setFlags(TileFlags::TEXTURE_ROTATE270); break; case BrushModes::MIRRORX: if (constant) controller->setFlags(TileFlags::TEXTURE_MIRRORX); break; case BrushModes::MIRRORY: if (constant) controller->setFlags(TileFlags::TEXTURE_MIRRORY); break; //case BrushModes::VISIBLE: // // if (constant) // controller->setFlags(TileFlags::TILE_VISIBLE); // // break; // //case BrushModes::QUAD0DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD0_DIAGONAL); // // break; // //case BrushModes::QUAD1DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD1_DIAGONAL); // // break; // //case BrushModes::QUAD2DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD2_DIAGONAL); // // break; // //case BrushModes::QUAD3DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD3_DIAGONAL); // // break; // //case BrushModes::DYNAMICMIX: // // if (constant) // controller->setFlags(TileFlags::DYNAMIC_MIX); // // break; // //case BrushModes::NOTESSELATE: // // if (constant) // controller->setFlags(TileFlags::TILE_NOTESSELLATE); // // break; case BrushModes::RAISE: for (unsigned int v = 0; v < 9; v++) { d = verts[v].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; verts[v].y += time * strength * 6 * exp(s); glVertex3f(verts[v].x, verts[v].y + 0.1f, verts[v].z); } } break; case BrushModes::LOWER: for (unsigned int v = 0; v < 9; v++) { d = verts[v].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; verts[v].y += time * -strength * 6 * exp(s); glVertex3f(verts[v].x, verts[v].y + 0.1f, verts[v].z); } } break; case BrushModes::ERASE: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 3 * exp(s); col = (char)(y * 255); cols[c].w -= cols[c].w <= col ? 0 : col; glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::RESTORE: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 3 * exp(s); cols[c].w += (char)((255 - cols[c].w) * y); glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::BURN: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 2 * exp(s); col = (char)(y * 255); cols[c].x -= cols[c].x < col ? 0 : col; cols[c].y -= cols[c].y < col ? 0 : col; cols[c].z -= cols[c].z < col ? 0 : col; glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::HEAL: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 2 * exp(s); cols[c].x += (char) round((255 - cols[c].x) * y); cols[c].y += (char) round((255 - cols[c].y) * y); cols[c].z += (char) round((255 - cols[c].z) * y); glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::PAINT: if (verts[4].getDistance(cpoint) <= radius) tdatabase->changeTileTexture(level, txcoordsIndex, tileiter.current()); break; case BrushModes::MARKER: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { y = time * opacity; col = (char)(y * 255); cols[c].x -= cols[c].x <= col ? 0 : col; cols[c].y -= cols[c].y <= col ? 0 : col; cols[c].z -= cols[c].z <= col ? 0 : col; glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::PASTEL: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { cols[c].x = char(255 * opacity); cols[c].y = char(255 * opacity); cols[c].z = char(255 * opacity); glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::ERASETILE: if (verts[4].getDistance(cpoint) <= radius) tdatabase->changeTileTexture(level, -1, tileiter.current()); break; case BrushModes::LOGIC: if (logicflag != TileTypes::GRASSFIELD) if (verts[4].getDistance(cpoint) <= radius) { lflag = terrainLogic->getFlags(tileiter.current()); terrainLogic->setFlags(tileiter.current(), strategy->getType((lflag & MASK_FLAGS), logicflag)); } break; case BrushModes::FLAG: if (verts[4].getDistance(cpoint) <= radius) { lflag = terrainLogic->getFlags(tileiter.current()); terrainLogic->setFlags(tileiter.current(), strategy->getFlags(lflag, logicflag)); } break; case BrushModes::ADVANCED: if (verts[4].getDistance(cpoint) <= radius) { BrushMatrixDescriptor* descriptor = &Gateway::getBrushMatrixDescriptor(); if (!descriptor->tileList.isEmpty()) { int col = tileiter.current() - int(tileiter.current()/area.y) * area.y; int row = int(tileiter.current()/area.y); int mx = col % descriptor->dimensions.x; int my = row % descriptor->dimensions.y; Tile *mtile = &descriptor->tileList(my * descriptor->dimensions.x + mx); tdatabase->changeTileTexture(level, mtile->textureID[0], tileiter.current()); controller->clearFlags(); controller->setFlags(mtile->flags); } } break; case BrushModes::POINTER: break; default: break; } tileiter++; } glEnd(); glPointSize(1.0f); if (mode < BrushModes::PAINT) Gateway::updateSpatialIndex(cpoint, radius); } void TerrainBrush::editGrass() { if (layer != BrushLayers::GRASS && mode != BrushModes::LOGIC && type != BrushTypes::GRASS) return; if (meadowname.isBlank()) return; Tuple3f *verts; RangeIterator tileiter; GrassPatch* patch; Meadow* meadow; int meadowindex; unsigned int lflag; TerrainVisuals* visuals = Gateway::getTerrainVisuals(); TerrainDatabase* tdatabase = Gateway::getTerrainDatabase(); TerrainPasture* terrainPasture = Gateway::getTerrainPasture(); TerrainLogic* terrainLogic = Gateway::getTerrainLogic(); AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); Tuple2i area(visuals->getArea()); unsigned int xOff = clamp(int(cpoint.x - radius), 0, area.y - 1); unsigned int yOff = clamp(int(cpoint.z - radius), 0, area.x - 1); unsigned int zOff = clamp(int(cpoint.x + radius), 0, area.y - 1); unsigned int wOff = clamp(int(cpoint.z + radius), 0, area.x - 1); tileiter.set(area.x, Tuple4i(yOff, xOff, wOff, zOff)); while (!tileiter.end()) { verts = tdatabase->getController(tileiter.current())->getVertices(); if (verts[4].getDistance(cpoint) <= radius) { meadowindex = terrainPasture->getMeadowIndex(meadowname); meadow = terrainPasture->getMeadow(meadowindex); if (!meadow->containsTileIndex(tileiter.current())) { if (patch = terrainPasture->createPatch(meadowindex)) { patch->position.set(tileiter.current() - int(tileiter.current()/area.y) * area.y, int(tileiter.current()/area.y)); patch->range.set(0x00000000,0x00000000); patch->color.set(0xff); } lflag = terrainLogic->getFlags(tileiter.current()); terrainLogic->setFlags(tileiter.current(), (lflag & MASK_FLAGS) | (TileTypes::GRASSFIELD << 27)); //terrainLogic->setFlags(tileiter.current(), strategy->getType((lflag & MASK_FLAGS), logicflag)); meadow->addTileIndex(tileiter.current()); } } tileiter++; } } bool TerrainBrush::intersect(BoundsDescriptor *bounds) { Tuple3f ro; Tuple3f rd; Tuple3f d; Tuple3f a; Tuple3f e; Tuple3f c; ro = ray->getOrigin(); rd = ray->getDestination(); d = (rd - ro) * 0.5f; a.set(fabsf(d.x), fabsf(d.y), fabsf(d.z)); e = bounds->getExtents(); c = ro + d - bounds->getCenterAABB(); if (fabsf(c.x) > e.x + a.x || fabsf(c.y) > e.y + a.y || fabsf(c.z) > e.z + a.z) return false; if (fabsf(d.y * c.z - d.z * c.y) > (e.y * a.z + e.z * a.y) || fabsf(d.z * c.x - d.x * c.z) > (e.z * a.x + e.x * a.z) || fabsf(d.x * c.y - d.y * c.x) > (e.x * a.y + e.y * a.x)) return false; return true; } void TerrainBrush::editWater() { if (layer != BrushLayers::WATER) return; if (!waterModel) return; Tuple3f point; float distance; Tuple4f packet; Array < DistanceObject<unsigned int> > distObjs; DistanceObject <unsigned int> object; AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); switch (mode) { case BrushModes::VERTEX: { if (constant) waterModel->addVertex(Tuple3f(cpoint.x, cpoint.y + 0.05f, cpoint.z)); } break; case BrushModes::TRIANGLE: { if (constant) { for (unsigned int i = 0; i < waterModel->getTriangleCount(); i++) { packet = intersector.intersectTriangles(ray, waterModel->getVertices(), &waterModel->getTriangles()[i], 1); if (1 == packet.w) { point.set(packet.x, packet.y, packet.z); distance = point.getDistance(ray->getOrigin()); if (2.0f < distance) { object.set(distance, i); distObjs.append(object); } } } } if (!distObjs.isEmpty()) { OCQuickSort(distObjs, 0, distObjs.length()); waterModel->removeTriangle(distObjs(0).getObject()); } break; } } } void TerrainBrush::setRay(Ray3D* r) { ray = r; } void TerrainBrush::setPaintIndex(int index) { txcoordsIndex = index; } void TerrainBrush::setPaintLayer(int layer) { level = layer; } void TerrainBrush::enable(bool e) { enabled = e; } void TerrainBrush::enableConstant(bool enable) { constant = enable; } void TerrainBrush::setRadius(float r) { radius = r; } void TerrainBrush::update(float tick) { time = tick; } void TerrainBrush::setStrength(float s) { strength = s; } void TerrainBrush::setOpacity(float o) { opacity = o; } void TerrainBrush::setLogic(unsigned int flags) { logicflag = flags; } void TerrainBrush::setMode(int m) { mode = m; } unsigned int TerrainBrush::getMode() { return mode; } void TerrainBrush::setType(int m) { type = m; } unsigned int TerrainBrush::getType() { return type; } void TerrainBrush::setLayer(int m) { layer = m; } int TerrainBrush::getLayer() { return layer; } void TerrainBrush::enableGuides(bool enable) { showGuides = enable; } void TerrainBrush::setMeadowName(const char* name) { meadowname = name; } void TerrainBrush::setNatureTransformGroup(TransformGroup* group) { natureRoot = group; } void TerrainBrush::setCharacterTransformGroup(TransformGroup* group) { characterRoot = group; } void TerrainBrush::setCritterTransformGroup(TransformGroup* group) { critterRoot = group; } void TerrainBrush::setStructureTransformGroup(TransformGroup* group) { structureRoot = group; } void TerrainBrush::setVillageTransformGroup(TransformGroup* group) { villageRoot = group; } Tuple4f TerrainBrush::getCollisionPoint() { if (pointAVLTree.isEmpty()) return Tuple4f(0,0,0,0); return Tuple4f(cpoint.x, cpoint.y, cpoint.z, 1); } void TerrainBrush::saveCollisionPoint(bool save) { saveCollPoint = save; } void TerrainBrush::drawCollisionMark() { } void TerrainBrush::enableLogicFlag(bool enable) { if (enable) strategy = strategies(0); else strategy = strategies(1); } void TerrainBrush::setWaterModel(Water* water) { waterModel = water; } void TerrainBrush::reset() { natureRoot = 0; characterRoot = 0; structureRoot = 0; critterRoot = 0; villageRoot = 0; waterModel = 0; showGuides = false; enabled = false; constant = false; txcoordsIndex = -1; level = 0; meadowname.clear(); radius = 2.0f; strength = 0.0f; time = 0.0f; opacity = 0.0f; saveCollPoint = false; logicflag = TileLogic::FLAG_NONE | (TileTypes::UNUSED << 27); mode = BrushModes::POINTER; type = BrushTypes::NONE; layer = BrushLayers::NONE; strategy = strategies(0); } TerrainBrush::~TerrainBrush() { strategies.clear(); }
26.609375
125
0.542924
badbrainz
eded2e795fa3156c2b5aa1f2c9c45077735e4598
3,139
hpp
C++
IDemo.hpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
1
2019-06-14T08:24:17.000Z
2019-06-14T08:24:17.000Z
IDemo.hpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
null
null
null
IDemo.hpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
null
null
null
#ifndef _DEF_IDEMO_HPP #define _DEF_IDEMO_HPP #include "src/Omgl3D.hpp" #include <SFML/Window.hpp> class IDemo { public: IDemo() : width_screen(800), height_screen(600), running(true) { } virtual ~IDemo() {} virtual void yourEvent(float elapsedtime, const sf::Event & event) {} void events(float elapsedtime) { sf::Event event; while( window.GetEvent(event) ) { if( event.Type == sf::Event::Closed ) { running = false; } if( event.Type == sf::Event::KeyPressed ) { switch(event.Key.Code) { case sf::Key::Escape: running = false; break; default: break; } } yourEvent(elapsedtime, event); } const sf::Input& Input = window.GetInput(); bool LeftKeyDown = Input.IsKeyDown(sf::Key::Left); bool RightKeyDown = Input.IsKeyDown(sf::Key::Right); bool UpKeyDown = Input.IsKeyDown(sf::Key::Up); bool DownKeyDown = Input.IsKeyDown(sf::Key::Down); bool QKeyDown = Input.IsKeyDown(sf::Key::Q); bool DKeyDown = Input.IsKeyDown(sf::Key::D); bool ZKeyDown = Input.IsKeyDown(sf::Key::Z); bool SKeyDown = Input.IsKeyDown(sf::Key::S); OMGL3D::MATH::Quaternionf rotate, rotate_x, rotate_y, rotate_z; OMGL3D::MATH::Vector3f vector; if( LeftKeyDown ) { rotate_x = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 0, 1, -20*elapsedtime); } if( RightKeyDown ) { rotate_x = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 0, 1, 20*elapsedtime); } if( UpKeyDown ) { rotate_z = OMGL3D::MATH::Quaternionf::CreateQuaternion(1, 0, 0, -20*elapsedtime); } if( DownKeyDown ) { rotate_z = OMGL3D::MATH::Quaternionf::CreateQuaternion(1, 0, 0, 20*elapsedtime); } if( QKeyDown ) { rotate_y = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 1, 0, -20*elapsedtime); } if( DKeyDown ) { rotate_y = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 1, 0, 20*elapsedtime); } if( ZKeyDown ) { vector.z = -10*elapsedtime; } if( SKeyDown ) { vector.z = 10*elapsedtime; } rotate = rotate_x * rotate_y * rotate_z; //position = rotate.getMatrix4(); position *= rotate.GetMatrix4(); position *= vector; } virtual void init()=0; virtual void run()=0; void start() { init(); sf::Clock clock; while( running ) { elapsedtime = clock.GetElapsedTime(); clock.Reset(); events(elapsedtime); run(); } } protected: unsigned int width_screen, height_screen; bool running; float elapsedtime; sf::Window window; OMGL3D::MATH::Matrix4f position; }; #endif
22.582734
93
0.521822
Sebajuste
eded3f907772be78a364c272f687c920d80a74d5
3,765
cpp
C++
src/TVShader.cpp
jcmoyer/HALT
8f31eb1943b43ca0d2ab4065a2c624b67a80124f
[ "Unlicense", "MIT" ]
null
null
null
src/TVShader.cpp
jcmoyer/HALT
8f31eb1943b43ca0d2ab4065a2c624b67a80124f
[ "Unlicense", "MIT" ]
1
2015-06-29T21:53:55.000Z
2015-06-29T21:53:55.000Z
src/TVShader.cpp
jcmoyer/HALT
8f31eb1943b43ca0d2ab4065a2c624b67a80124f
[ "Unlicense", "MIT" ]
null
null
null
// ============================================================================ // Copyright (c) 2011-2012 J.C. Moyer // // 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 "TVShader.h" #include "TerminalRenderer.h" #include "TProgram.h" #include <GL/glew.h> namespace halt { const char* TVGLSLShaderSource = "#version 120 \n" "uniform mat4 tvs_Projection; \n" " \n" "attribute vec2 tvs_TexCoord; \n" "attribute vec4 tvs_Vertex; \n" "attribute vec4 tvs_Color; \n" " \n" "varying vec2 tfs_TexCoord; \n" "varying vec4 tfs_Color; \n" " \n" "void main() { \n" " gl_Position = tvs_Projection * tvs_Vertex; \n" " tfs_TexCoord = tvs_TexCoord; \n" " tfs_Color = tvs_Color; \n" "} \n"; const char* TVS_PROJECTION_MAT = "tvs_Projection"; const char* VERTEX_ATTRIBUTE_NAME = "tvs_Vertex"; const char* TEXCOORD_ATTRIBUTE_NAME = "tvs_TexCoord"; const char* COLOR_ATTRIBUTE_NAME = "tvs_Color"; TVShader::TVShader(TProgram* owner) { handle = glCreateShader(GL_VERTEX_SHADER); glShaderSource(handle, 1, &TVGLSLShaderSource, 0); glCompileShader(handle); } TVShader::~TVShader() { if (handle) glDeleteShader(handle); } void TVShader::Enable(bool state, unsigned int vertex_attrib, unsigned int tex_coord_atrrib, unsigned int color_attrib) { if (state) { glEnableVertexAttribArray(vertex_attrib); glVertexAttribPointer(vertex_attrib, 2, GL_UNSIGNED_SHORT, 0, sizeof(TerminalVertex), (void*)0); glEnableVertexAttribArray(tex_coord_atrrib); glVertexAttribPointer(tex_coord_atrrib, 2, GL_FLOAT, 0, sizeof(TerminalVertex), (void*)4); glEnableVertexAttribArray(color_attrib); glVertexAttribPointer(color_attrib, 4, GL_UNSIGNED_BYTE, 1, sizeof(TerminalVertex), (void*)12); } else { glDisableVertexAttribArray(vertex_attrib); glDisableVertexAttribArray(tex_coord_atrrib); glDisableVertexAttribArray(color_attrib); } } }
48.896104
122
0.562019
jcmoyer
edee2cbf7d760f06dd2c803002d3bf197734c071
2,738
cpp
C++
source/MeanNormalLikelihood.cpp
vishalbelsare/DIAMONDS
76409b22c9da782436b52e454a8b36bc78fca6f6
[ "MIT" ]
null
null
null
source/MeanNormalLikelihood.cpp
vishalbelsare/DIAMONDS
76409b22c9da782436b52e454a8b36bc78fca6f6
[ "MIT" ]
null
null
null
source/MeanNormalLikelihood.cpp
vishalbelsare/DIAMONDS
76409b22c9da782436b52e454a8b36bc78fca6f6
[ "MIT" ]
null
null
null
#include "MeanNormalLikelihood.h" // MeanNormalLikelihood::MeanNormalLikelihood() // // PURPOSE: // Derived class onstructor. // // INPUT: // observations: array containing the dependent variable values // uncertainties: array containing the uncertainties of the observations // model: object specifying the model to be used. // MeanNormalLikelihood::MeanNormalLikelihood(const RefArrayXd observations, const RefArrayXd uncertainties, Model &model) : Likelihood(observations, model), uncertainties(uncertainties) { double normalizeFactor; assert(observations.size() == uncertainties.size()); normalizeFactor = sqrt(observations.size()/uncertainties.pow(-2).sum()); normalizedUncertainties = uncertainties/normalizeFactor; weights = normalizedUncertainties.pow(-2); } // END MeanNormalLikelihood::MeanNormalLikelihood() // MeanNormalLikelihood::~MeanNormalLikelihood() // // PURPOSE: // Derived class destructor. // MeanNormalLikelihood::~MeanNormalLikelihood() { } // END MeanNormalLikelihood::~MeanNormalLikelihood() // MeanNormalLikelihood::getNormalizedUncertainties(); // // PURPOSE: // Get private data member normalizedUncertainties. // // OUTPUT: // uncertainties: one-dimensional array containing the // uncertainties on the dependent variable values. // ArrayXd MeanNormalLikelihood::getNormalizedUncertainties() { return normalizedUncertainties; } // END MeanNormalLikelihood::getNormalizedUncertainties() // MeanNormalLikelihood::logValue() // // PURPOSE: // Compute the natural logarithm of the mean normal likelihood for // a given set of observations, uncertainties and predictions. // The mean normal likelihood is a normal likelihood whose uncertainties // have been integrated away by means of a Jeffrey's prior. // For more details cf. Froehlich H.-E. et al. 2009, A&A, 506, 263. // // INPUT: // modelParameters: a one-dimensional array containing the actual // values of the free parameters that describe the model. // // OUTPUT: // a double number containing the natural logarithm of the // mean likelihood // double MeanNormalLikelihood::logValue(RefArrayXd modelParameters) { unsigned long n = observations.size(); double lambda0; double lambda; ArrayXd argument; ArrayXd predictions; predictions.resize(n); predictions.setZero(); model.predict(predictions, modelParameters); argument = (observations - predictions); argument = argument.square()*weights; lambda0 = lgammal(n/2.) - log(2) - (n/2.)*log(Functions::PI) + 0.5*weights.log().sum(); lambda = lambda0 - (n/2.)*log(argument.sum()); return lambda; }
23.401709
119
0.714025
vishalbelsare
edeea74178b620aff9dcaeb34437bd3eae148ce4
14,678
cpp
C++
Co-Simulation/Sumo/sumo-1.7.0/src/netedit/elements/additional/GNEBusStop.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/netedit/elements/additional/GNEBusStop.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/netedit/elements/additional/GNEBusStop.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file GNEBusStop.cpp /// @author Pablo Alvarez Lopez /// @date Nov 2015 /// // A lane area vehicles can halt at (GNE version) /****************************************************************************/ #include <foreign/fontstash/fontstash.h> #include <netedit/GNENet.h> #include <netedit/GNEUndoList.h> #include <netedit/GNEViewNet.h> #include <netedit/changes/GNEChange_Attribute.h> #include <utils/options/OptionsCont.h> #include <utils/gui/globjects/GLIncludes.h> #include <utils/gui/div/GLHelper.h> #include <utils/vehicle/SUMORouteHandler.h> #include "GNEBusStop.h" // =========================================================================== // method definitions // =========================================================================== GNEBusStop::GNEBusStop(const std::string& id, GNELane* lane, GNENet* net, const double startPos, const double endPos, const int parametersSet, const std::string& name, const std::vector<std::string>& lines, int personCapacity, double parkingLength, bool friendlyPosition, bool blockMovement) : GNEStoppingPlace(id, net, GLO_BUS_STOP, SUMO_TAG_BUS_STOP, lane, startPos, endPos, parametersSet, name, friendlyPosition, blockMovement), myLines(lines), myPersonCapacity(personCapacity), myParkingLength(parkingLength) { } GNEBusStop::~GNEBusStop() {} void GNEBusStop::updateGeometry() { // Get value of option "lefthand" double offsetSign = OptionsCont::getOptions().getBool("lefthand") ? -1 : 1; // Update common geometry of stopping place setStoppingPlaceGeometry(getParentLanes().front()->getParentEdge()->getNBEdge()->getLaneWidth(getParentLanes().front()->getIndex()) * 0.5); // Obtain a copy of the shape PositionVector tmpShape = myAdditionalGeometry.getShape(); // Move shape to side tmpShape.move2side(myNet->getViewNet()->getVisualisationSettings().stoppingPlaceSettings.stoppingPlaceSignOffset * offsetSign); // Get position of the sign mySignPos = tmpShape.getLineCenter(); // update block icon position myBlockIcon.updatePositionAndRotation(); // update child demand elements geometry for (const auto& i : getChildDemandElements()) { // special case for person trips if (i->getTagProperty().isPersonTrip()) { // update previous and next person plan GNEDemandElement* previousDemandElement = i->getParentDemandElements().front()->getPreviousChildDemandElement(i); if (previousDemandElement) { previousDemandElement->updatePartialGeometry(getParentLanes().front()); } GNEDemandElement* nextDemandElement = i->getParentDemandElements().front()->getNextChildDemandElement(i); if (nextDemandElement) { nextDemandElement->updatePartialGeometry(getParentLanes().front()); } } i->updatePartialGeometry(getParentLanes().front()); } } Boundary GNEBusStop::getCenteringBoundary() const { return myAdditionalGeometry.getShape().getBoxBoundary().grow(10); } void GNEBusStop::drawGL(const GUIVisualizationSettings& s) const { // Obtain exaggeration of the draw const double busStopExaggeration = s.addSize.getExaggeration(s, this); // first check if additional has to be drawn if (s.drawAdditionals(busStopExaggeration) && myNet->getViewNet()->getDataViewOptions().showAdditionals()) { // declare colors RGBColor baseColor, signColor; // set colors if (mySpecialColor) { baseColor = *mySpecialColor; signColor = baseColor.changedBrightness(-32); } else if (drawUsingSelectColor()) { baseColor = s.colorSettings.selectedAdditionalColor; signColor = baseColor.changedBrightness(-32); } else { baseColor = s.stoppingPlaceSettings.busStopColor; signColor = s.stoppingPlaceSettings.busStopColorSign; } // Start drawing adding an gl identificator glPushName(getGlID()); // Add a draw matrix glPushMatrix(); // translate to front myNet->getViewNet()->drawTranslateFrontAttributeCarrier(this, GLO_BUS_STOP); // set base color GLHelper::setColor(baseColor); // Draw the area using shape, shapeRotations, shapeLengths and value of exaggeration GNEGeometry::drawGeometry(myNet->getViewNet(), myAdditionalGeometry, s.stoppingPlaceSettings.busStopWidth * busStopExaggeration); // draw detail if (s.drawDetail(s.detailSettings.stoppingPlaceDetails, busStopExaggeration)) { // draw lines drawLines(s, myLines, baseColor); // draw sign drawSign(s, busStopExaggeration, baseColor, signColor, "H"); // draw lock icon myBlockIcon.drawIcon(s, busStopExaggeration); } // pop draw matrix glPopMatrix(); // Draw name if isn't being drawn for selecting drawName(getPositionInView(), s.scale, s.addName); // Pop name glPopName(); // draw connection betwen access drawConnectionAccess(s, baseColor); // draw additional name drawAdditionalName(s); // check if dotted contours has to be drawn if (s.drawDottedContour() || myNet->getViewNet()->getInspectedAttributeCarrier() == this) { GNEGeometry::drawDottedContourShape(true, s, myAdditionalGeometry.getShape(), s.stoppingPlaceSettings.busStopWidth, busStopExaggeration); } if (s.drawDottedContour() || myNet->getViewNet()->getFrontAttributeCarrier() == this) { GNEGeometry::drawDottedContourShape(false, s, myAdditionalGeometry.getShape(), s.stoppingPlaceSettings.busStopWidth, busStopExaggeration); } // draw child demand elements for (const auto& demandElement : getChildDemandElements()) { if (!demandElement->getTagProperty().isPlacedInRTree()) { demandElement->drawGL(s); } } } } std::string GNEBusStop::getAttribute(SumoXMLAttr key) const { switch (key) { case SUMO_ATTR_ID: return getID(); case SUMO_ATTR_LANE: return getParentLanes().front()->getID(); case SUMO_ATTR_STARTPOS: if (myParametersSet & STOPPINGPLACE_STARTPOS_SET) { return toString(myStartPosition); } else { return ""; } case SUMO_ATTR_ENDPOS: if (myParametersSet & STOPPINGPLACE_ENDPOS_SET) { return toString(myEndPosition); } else { return ""; } case SUMO_ATTR_NAME: return myAdditionalName; case SUMO_ATTR_FRIENDLY_POS: return toString(myFriendlyPosition); case SUMO_ATTR_LINES: return joinToString(myLines, " "); case SUMO_ATTR_PERSON_CAPACITY: return toString(myPersonCapacity); case SUMO_ATTR_PARKING_LENGTH: return toString(myParkingLength); case GNE_ATTR_BLOCK_MOVEMENT: return toString(myBlockMovement); case GNE_ATTR_SELECTED: return toString(isAttributeCarrierSelected()); case GNE_ATTR_PARAMETERS: return getParametersStr(); default: throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'"); } } void GNEBusStop::setAttribute(SumoXMLAttr key, const std::string& value, GNEUndoList* undoList) { if (value == getAttribute(key)) { return; //avoid needless changes, later logic relies on the fact that attributes have changed } switch (key) { case SUMO_ATTR_ID: case SUMO_ATTR_LANE: case SUMO_ATTR_STARTPOS: case SUMO_ATTR_ENDPOS: case SUMO_ATTR_NAME: case SUMO_ATTR_FRIENDLY_POS: case SUMO_ATTR_LINES: case SUMO_ATTR_PERSON_CAPACITY: case SUMO_ATTR_PARKING_LENGTH: case GNE_ATTR_BLOCK_MOVEMENT: case GNE_ATTR_SELECTED: case GNE_ATTR_PARAMETERS: undoList->p_add(new GNEChange_Attribute(this, key, value)); break; default: throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'"); } } bool GNEBusStop::isValid(SumoXMLAttr key, const std::string& value) { switch (key) { case SUMO_ATTR_ID: return isValidAdditionalID(value); case SUMO_ATTR_LANE: if (myNet->retrieveLane(value, false) != nullptr) { return true; } else { return false; } case SUMO_ATTR_STARTPOS: if (value.empty()) { return true; } else if (canParse<double>(value)) { return SUMORouteHandler::isStopPosValid(parse<double>(value), myEndPosition, getParentLanes().front()->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, myFriendlyPosition); } else { return false; } case SUMO_ATTR_ENDPOS: if (value.empty()) { return true; } else if (canParse<double>(value)) { return SUMORouteHandler::isStopPosValid(myStartPosition, parse<double>(value), getParentLanes().front()->getParentEdge()->getNBEdge()->getFinalLength(), POSITION_EPS, myFriendlyPosition); } else { return false; } case SUMO_ATTR_NAME: return SUMOXMLDefinitions::isValidAttribute(value); case SUMO_ATTR_FRIENDLY_POS: return canParse<bool>(value); case SUMO_ATTR_LINES: return canParse<std::vector<std::string> >(value); case SUMO_ATTR_PERSON_CAPACITY: return canParse<int>(value) && (parse<int>(value) > 0 || parse<int>(value) == -1); case SUMO_ATTR_PARKING_LENGTH: return canParse<double>(value) && (parse<double>(value) >= 0); case GNE_ATTR_BLOCK_MOVEMENT: return canParse<bool>(value); case GNE_ATTR_SELECTED: return canParse<bool>(value); case GNE_ATTR_PARAMETERS: return Parameterised::areParametersValid(value); default: throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'"); } } // =========================================================================== // private // =========================================================================== void GNEBusStop::setAttribute(SumoXMLAttr key, const std::string& value) { switch (key) { case SUMO_ATTR_ID: myNet->getAttributeCarriers()->updateID(this, value); // Change IDs of all access children for (const auto& access : getChildAdditionals()) { access->setMicrosimID(getID()); } break; case SUMO_ATTR_LANE: replaceAdditionalParentLanes(value); break; case SUMO_ATTR_STARTPOS: if (!value.empty()) { myStartPosition = parse<double>(value); myParametersSet |= STOPPINGPLACE_STARTPOS_SET; } else { myParametersSet &= ~STOPPINGPLACE_STARTPOS_SET; } break; case SUMO_ATTR_ENDPOS: if (!value.empty()) { myEndPosition = parse<double>(value); myParametersSet |= STOPPINGPLACE_ENDPOS_SET; } else { myParametersSet &= ~STOPPINGPLACE_ENDPOS_SET; } break; case SUMO_ATTR_NAME: myAdditionalName = value; break; case SUMO_ATTR_FRIENDLY_POS: myFriendlyPosition = parse<bool>(value); break; case SUMO_ATTR_LINES: myLines = GNEAttributeCarrier::parse<std::vector<std::string> >(value); break; case SUMO_ATTR_PERSON_CAPACITY: myPersonCapacity = GNEAttributeCarrier::parse<int>(value); break; case SUMO_ATTR_PARKING_LENGTH: myParkingLength = GNEAttributeCarrier::parse<double>(value); break; case GNE_ATTR_BLOCK_MOVEMENT: myBlockMovement = parse<bool>(value); break; case GNE_ATTR_SELECTED: if (parse<bool>(value)) { selectAttributeCarrier(); } else { unselectAttributeCarrier(); } break; case GNE_ATTR_PARAMETERS: setParametersStr(value); break; default: throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'"); } } void GNEBusStop::drawConnectionAccess(const GUIVisualizationSettings& s, const RGBColor& color) const { if (!s.drawForPositionSelection && !s.drawForRectangleSelection) { // Add a draw matrix for details glPushMatrix(); // move to GLO_BUS_STOP glTranslated(0, 0, GLO_BUS_STOP); // set color GLHelper::setColor(color); // draw lines between BusStops and Access for (const auto& access : getChildAdditionals()) { GLHelper::drawBoxLine(access->getAdditionalGeometry().getPosition(), RAD2DEG(myBlockIcon.getPosition().angleTo2D(access->getAdditionalGeometry().getPosition())) - 90, myBlockIcon.getPosition().distanceTo2D(access->getAdditionalGeometry().getPosition()), .05); } // pop draw matrix glPopMatrix(); } } /****************************************************************************/
40.65928
203
0.60451
uruzahe
edef4a097eb4ce91d4567df08e1e1433603dd67d
32,877
cpp
C++
T3000/T3ModulesOutputDlg.cpp
daven-que/T3000_Building_Automation_System
cc56967e9bf849ebc5ec47950b74e8dc765f720c
[ "MIT" ]
null
null
null
T3000/T3ModulesOutputDlg.cpp
daven-que/T3000_Building_Automation_System
cc56967e9bf849ebc5ec47950b74e8dc765f720c
[ "MIT" ]
null
null
null
T3000/T3ModulesOutputDlg.cpp
daven-que/T3000_Building_Automation_System
cc56967e9bf849ebc5ec47950b74e8dc765f720c
[ "MIT" ]
null
null
null
// T3ModulesOutputDlg.cpp : implementation file // #include "stdafx.h" #include "T3000.h" #include "T3ModulesOutputDlg.h" #include "afxdialogex.h" #include "global_function.h" // CT3ModulesOutputDlg dialog DWORD WINAPI _ReadMultiRegisters_T3_Output(LPVOID pParam) { CT3ModulesOutputDlg* pFrame=(CT3ModulesOutputDlg*)(pParam); CString g_strT3000LogString; int heatbeat = 0; while(pFrame->IsWindowVisible ()) { if (!is_connect()) { Sleep(1000); continue; } if (pFrame->m_isstop) { // heatbeat ++; Sleep(1000); if (heatbeat >10) { pFrame->m_isstop = FALSE; heatbeat =0; } continue; } for(int i=0; i<4; i++) { int multy_ret = 0; if (pFrame->m_isstop) { break; } multy_ret = Read_Multi(g_tstat_id,&product_register_value[i*100],i*100,100); Sleep(100); if(multy_ret<0) break; } PostMessage(g_hwnd_now,WM_REFRESH_BAC_INPUT_LIST,0,0); } return 0; return 0; } IMPLEMENT_DYNAMIC(CT3ModulesOutputDlg, CFormView) CT3ModulesOutputDlg::CT3ModulesOutputDlg() : CFormView(CT3ModulesOutputDlg::IDD) { hFirstThread = NULL; m_isstop = FALSE; } CT3ModulesOutputDlg::~CT3ModulesOutputDlg() { if(hFirstThread != NULL) TerminateThread(hFirstThread, 0); } void CT3ModulesOutputDlg::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_T3OUTPUTS, m_outputlist); } #ifdef _DEBUG void CT3ModulesOutputDlg::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void CT3ModulesOutputDlg::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG BEGIN_MESSAGE_MAP(CT3ModulesOutputDlg, CFormView) ON_MESSAGE(WM_REFRESH_BAC_INPUT_LIST,Fresh_Input_List) ON_MESSAGE(WM_LIST_ITEM_CHANGED,Change_Input_Item) ON_NOTIFY(NM_CLICK, IDC_LIST_T3OUTPUTS, &CT3ModulesOutputDlg::OnNMClickList_output) ON_NOTIFY(NM_DBLCLK, IDC_LIST_T3OUTPUTS, &CT3ModulesOutputDlg::OnNMDblclkListT3outputs) END_MESSAGE_MAP() // CT3ModulesOutputDlg message handlers void CT3ModulesOutputDlg::Fresh() { CString strTemp; g_hwnd_now = this->m_hWnd; m_sn = m_sn=product_register_value[0]+product_register_value[1]*256 +product_register_value[2]*256*256+product_register_value[3]*256*256*256; m_outputlist.ShowWindow(SW_HIDE); m_outputlist.DeleteAllItems(); while(m_outputlist.DeleteColumn(0)); if (product_register_value[7] == PM_T34AO) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(1, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(2, _T("Value"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); for(int i=1; i<9; i++) { strTemp.Format(_T("Digit Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); //strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } for(int i=9; i<13; i++) { strTemp.Format(_T("Analog Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); // strTemp.Format(_T("%d"),product_register_value[108+(i-8)-1]); if (product_register_value[108+(i-8)-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } for(int i = 1; i<13; i++) { m_outputlist.SetItemText(i-1,1,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,2,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,2,L"On"); } else { if (i<9) { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } else { strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,2,strTemp); } } } else if (product_register_value[7] == PM_T3IOA) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[8]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } for(int i=1; i<9; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); // strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,1,strTemp); m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T38AI8AO6DO) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString); bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } for(int i=1; i<15; i++) { if (i<9) { strTemp= Get_Table_Name(m_sn,_T("Analog_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { // if (product_register_value[100+i-1] == 0) // { // strTemp = _T("Off"); // } // else // { // strTemp = _T("On"); // } strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,1,strTemp); } else { strTemp= Get_Table_Name(m_sn,_T("Digital_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } m_outputlist.SetItemText(i-1,1,strTemp); } m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); } } else if (product_register_value[7] == PM_T38I13O) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(1, _T("Output Value"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(2, _T("Light Switch"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(3, _T("Auto/Manual"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(4, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); for(int i=1; i<14; i++) { strTemp = Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i-1,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[13]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue2(product_register_value[117]); for (int i=8; i<13; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } CString CstresultDO; for(int i = 1; i<=13; i++) { // CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { CstresultDO = _T("Off"); } else { CstresultDO = _T("On"); } m_outputlist.SetItemText(i-1,1,CstresultDO); if (product_register_value[216+i-1]>0) { CstresultDO=Get_Table_Name(m_sn,_T("Input"),product_register_value[216+i-1]); } else { CstresultDO=_T("UNUSED"); } m_outputlist.SetItemText(i-1,2,CstresultDO); if (((product_register_value[215]>>(i-1))&0x01)==1) { CstresultDO=_T("Manual"); } else { CstresultDO=_T("Auto"); } m_outputlist.SetItemText(i-1,3,CstresultDO); m_outputlist.SetItemText(i-1,4,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T36CT) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString); for(int i=1; i<6; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); } CString CstresultDO; int b0,b1,b; for(int i = 1; i<=5; i++) { CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); m_outputlist.SetItemText(i-1,2,CstresultDO); b0=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+1); b1=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+2); b=b1*2+b0; if (i==5) { b0=Get_Bit_FromRegister(product_register_value[124],1); b1=Get_Bit_FromRegister(product_register_value[124],2); b=b1*2+b0; } if (b==0) { CstresultDO=_T("OFF"); } else if (b==1) { CstresultDO=_T("ON"); } else if (b==2) { CstresultDO=_T("AUTO"); } else { CstresultDO=_T(""); } m_outputlist.SetItemText(i-1,1,CstresultDO); } } m_outputlist.ShowWindow(SW_SHOW); if(hFirstThread != NULL) TerminateThread(hFirstThread, 0); hFirstThread=NULL; if (!hFirstThread) { hFirstThread = CreateThread(NULL,NULL,_ReadMultiRegisters_T3_Output,this,NULL,0); } } LRESULT CT3ModulesOutputDlg::Fresh_Input_List(WPARAM wParam,LPARAM lParam) { m_sn=product_register_value[0]+product_register_value[1]*256+product_register_value[2]*256*256+product_register_value[3]*256*256*256; CString strTemp; int fresh_type = (int)wParam; int fresh_row =(int) lParam; if (fresh_type == 0) { m_outputlist.DeleteAllItems(); if (product_register_value[7] == PM_T34AO) { for(int i=1; i<9; i++) { strTemp.Format(_T("Digit Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); // strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } for(int i=9; i<13; i++) { strTemp.Format(_T("Analog Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); strTemp.Format(_T("%d"),product_register_value[108+(i-8)-1]); if (product_register_value[108+(i-8)-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } for(int i = 1; i<13; i++) { m_outputlist.SetItemText(i-1,1,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,2,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,2,L"On"); } else { if (i<9) { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } else { strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,2,strTemp); } } } else if (product_register_value[7] == PM_T3IOA) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[8]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } for(int i=1; i<9; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); // strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,1,strTemp); m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T38I13O) { for(int i=1; i<14; i++) { strTemp = Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i-1,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[13]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue2(product_register_value[117]); for (int i=8; i<13; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } CString CstresultDO; for(int i = 1; i<=13; i++) { //CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,1,strTemp); if (product_register_value[216+i-1]>0) { CstresultDO=Get_Table_Name(m_sn,_T("Input"),product_register_value[216+i-1]); } else { CstresultDO=_T("UNUSED"); } m_outputlist.SetItemText(i-1,2,CstresultDO); if (((product_register_value[215]>>(i-1))&0x01)==1) { CstresultDO=_T("Manual"); } else { CstresultDO=_T("Auto"); } m_outputlist.SetItemText(i-1,3,CstresultDO); m_outputlist.SetItemText(i-1,4,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T36CT) { for(int i=1; i<6; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); } CString CstresultDO; int b0,b1,b; for(int i = 1; i<=5; i++) { CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); m_outputlist.SetItemText(i-1,2,CstresultDO); b0=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+1); b1=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+2); b=b1*2+b0; if (i==5) { b0=Get_Bit_FromRegister(product_register_value[124],1); b1=Get_Bit_FromRegister(product_register_value[124],2); b=b1*2+b0; } if (b==0) { CstresultDO=_T("OFF"); } else if (b==1) { CstresultDO=_T("ON"); } else if (b==2) { CstresultDO=_T("AUTO"); } else { CstresultDO=_T(""); } m_outputlist.SetItemText(i-1,1,CstresultDO); } } else if (product_register_value[7] == PM_T38AI8AO6DO) { bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } for(int i=1; i<15; i++) { if (i<9) { strTemp= Get_Table_Name(m_sn,_T("Analog_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { // if (product_register_value[100+i-1] == 0) // { // strTemp = _T("Off"); // } // else // { // strTemp = _T("On"); // } strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,1,strTemp); } else { strTemp= Get_Table_Name(m_sn,_T("Digital_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } m_outputlist.SetItemText(i-1,1,strTemp); } m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); } } } return 0; } LRESULT CT3ModulesOutputDlg::Change_Input_Item(WPARAM wParam,LPARAM lParam) { int lRow = (int)wParam; int lCol = (int)lParam; CString strText = m_outputlist.GetItemText (lRow,lCol); if (product_register_value[7] == PM_T34AO) { if (lCol == 2) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } } } else if (product_register_value[7] == PM_T3IOA) { } else if (product_register_value[7] == PM_T38I13O) { } else if (product_register_value[7] == PM_T36CT) { } else if (product_register_value[7] == PM_T38AI8AO6DO) { if (lCol == 1) { bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } if (SwitchValue[lRow] ==2) { int OutputValue = _wtoi (strText); if (OutputValue!=product_register_value[100+lRow]) { if (lRow<8) { int ret = write_one (g_tstat_id,100+lRow,OutputValue,1); if (ret>0) { product_register_value[100+lRow] = OutputValue; } } } PostMessage (WM_REFRESH_BAC_INPUT_LIST,0,0); } else { m_outputlist.Set_Edit (false); return 0; } } } return 0; } /* @1:Different Product responce to the different functionality @2: */ void CT3ModulesOutputDlg::OnNMClickList_output(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); CString temp_cstring; long lRow,lCol; m_outputlist.Set_Edit(true); DWORD dwPos=GetMessagePos();//Get which line is click by user.Set the check box, when user enter Insert it will jump to program dialog CPoint point( GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos)); m_outputlist.ScreenToClient(&point); LVHITTESTINFO lvinfo; lvinfo.pt=point; lvinfo.flags=LVHT_ABOVE; int nItem=m_outputlist.SubItemHitTest(&lvinfo); BOOL Is_Range = FALSE; int Range_Address = -1; int Value_Address = -1; int Value_Length = 0; lRow = lvinfo.iItem; lCol = lvinfo.iSubItem; m_isstop = TRUE; if(lRow>m_outputlist.GetItemCount()) //如果点击区超过最大行号,则点击是无效的 { return; } if(lRow<0) { return; } if (product_register_value[7] == PM_T34AO) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } if (lCol == 2) { // m_isstop =TRUE; m_outputlist.Set_Edit (false); if (SwitchValue[lRow] == 2) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } else if (product_register_value[7] == PM_T3IOA) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[8]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } if (lCol == 1) { if (SwitchValue[lRow] == 2) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } else if (product_register_value[7] == PM_T38AI8AO6DO) { bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } if (lCol == 1) { if (SwitchValue[lRow] == 2) { if (lRow>7) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } } else if (product_register_value[7] == PM_T38I13O) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[13]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue2(product_register_value[117]); for (int i=8; i<13; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } if (lCol == 1) { if (SwitchValue[lRow] == 2) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } else if (product_register_value[7] == PM_T36CT) { } } void CT3ModulesOutputDlg::OnNMDblclkListT3outputs(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); *pResult = 0; } BOOL CT3ModulesOutputDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN) { CRect list_rect,win_rect; m_outputlist.GetWindowRect(list_rect); ScreenToClient(&list_rect); ::GetWindowRect(this->m_hWnd,win_rect); m_outputlist.Set_My_WindowRect(win_rect); m_outputlist.Set_My_ListRect(list_rect); m_outputlist.Get_clicked_mouse_position(); return TRUE; } return CFormView::PreTranslateMessage(pMsg); }
29.068966
138
0.52082
daven-que
edf0d3adec736d669ec7476f4a15d48edd902b8d
693
hpp
C++
lib/libcpp/FadalightMesh/FadalightMesh/patchinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/FadalightMesh/FadalightMesh/patchinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/FadalightMesh/FadalightMesh/patchinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#ifndef __FadalightMesh_PatchInfo_h #define __FadalightMesh_PatchInfo_h #include "Alat/vector.hpp" #include "Alat/armadillo.hpp" /*--------------------------------------------------------------------------*/ namespace FadalightMesh { class PatchInfo { public: ~PatchInfo(); PatchInfo(); PatchInfo( const PatchInfo& patchinfo); PatchInfo& operator=( const PatchInfo& patchinfo); std::string getClassName() const; PatchInfo* clone() const; alat::Vector<alat::armaivec> cells, edgesinner, edgesouter, nodes; arma::field<arma::mat> sidecoeffs; arma::field<arma::imat> sideindices; }; } /*--------------------------------------------------------------------------*/ #endif
23.896552
78
0.572872
beckerrh
edf30d98197266a8a41a4d0ff63bcc4a00f5a898
30,358
hpp
C++
Primitives/General/Mat4x4.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
Primitives/General/Mat4x4.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
Primitives/General/Mat4x4.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
// // Mat4x4.h // DataStructures // // Created by James Landess on 11/11/16. // Copyright (c) 2016 James Landess. All rights reserved. // #ifndef DataStructures_Mat4x4_h #define DataStructures_Mat4x4_h #include "StaticArray.hpp" #include "Vec4.hpp" #include "Mat2x4.hpp" #include "Mat3x4.hpp" #include "Mat4x3.hpp" #include "TypeTraits/StaticallySized.h" namespace LD { namespace Detail { template<typename T> class tMat4x4 { private: tVec4<T> Rows[4]; public: inline tMat4x4(); inline tMat4x4(const typename TypeAid<T, 16>::CoreType & a); inline tMat4x4(const typename TypeAid<T, 16>::CoreType & a0, const typename TypeAid<T, 16>::CoreType & b0, const typename TypeAid<T, 16>::CoreType & c0,const typename TypeAid<T, 16>::CoreType & d0, const typename TypeAid<T, 16>::CoreType & a1, const typename TypeAid<T, 16>::CoreType & b1, const typename TypeAid<T, 16>::CoreType & c1,const typename TypeAid<T, 16>::CoreType & d1, const typename TypeAid<T, 16>::CoreType & a2, const typename TypeAid<T, 16>::CoreType & b2, const typename TypeAid<T, 16>::CoreType & c2,const typename TypeAid<T, 16>::CoreType & d2, const typename TypeAid<T, 16>::CoreType & a3, const typename TypeAid<T, 16>::CoreType & b3, const typename TypeAid<T, 16>::CoreType & c3,const typename TypeAid<T, 16>::CoreType & d3); inline tMat4x4(const tVec4<T> &a, const tVec4<T> & b, const tVec4<T> & c, const tVec4<T> & d); inline tMat4x4(const tMat2x2<T> & a); inline tMat4x4(const tMat3x3<T> & a); inline tVec4<T> & operator [] (const PDP::UInteger & index); inline const tVec4<T> & operator [] (const PDP::UInteger & index) const; inline tMat4x4 & operator = (const typename TypeAid<T, 16>::CoreType & a); inline tMat4x4 & operator = (const tMat2x2<T> & object); inline tMat4x4 & operator = (const tMat3x3<T> & object); }; template<typename T> tMat4x4<T>::tMat4x4() { this->Rows[0] = this->Rows[1] = this->Rows[2] = this->Rows[3] = 0; } template<typename T> tMat4x4<T>::tMat4x4(const typename TypeAid<T, 16>::CoreType & a) { this->Rows[0] = this->Rows[1] = this->Rows[2] = this->Rows[3] = a; } template<typename T> tMat4x4<T>::tMat4x4(const typename TypeAid<T, 16>::CoreType & a0, const typename TypeAid<T, 16>::CoreType & b0, const typename TypeAid<T, 16>::CoreType & c0,const typename TypeAid<T, 16>::CoreType & d0, const typename TypeAid<T, 16>::CoreType & a1, const typename TypeAid<T, 16>::CoreType & b1, const typename TypeAid<T, 16>::CoreType & c1,const typename TypeAid<T, 16>::CoreType & d1, const typename TypeAid<T, 16>::CoreType & a2, const typename TypeAid<T, 16>::CoreType & b2, const typename TypeAid<T, 16>::CoreType & c2,const typename TypeAid<T, 16>::CoreType & d2, const typename TypeAid<T, 16>::CoreType & a3, const typename TypeAid<T, 16>::CoreType & b3, const typename TypeAid<T, 16>::CoreType & c3,const typename TypeAid<T, 16>::CoreType & d3) { this->Rows[0] = tVec4<T>(a0,b0,c0,d0); this->Rows[1] = tVec4<T>(a1,b1,c1,d1); this->Rows[2] = tVec4<T>(a2,b2,c2,d2); this->Rows[3] = tVec4<T>(a3,b3,c3,d3); } template<typename T> tMat4x4<T>::tMat4x4(const tVec4<T> &a, const tVec4<T> & b, const tVec4<T> & c, const tVec4<T> & d) { this->Rows[0] = a; this->Rows[1] = b; this->Rows[2] = c; this->Rows[3] = d; } template<typename T> tVec4<T> & tMat4x4<T>::operator[](const PDP::UInteger &index) { return this->Rows[index]; } template<typename T> const tVec4<T> & tMat4x4<T>::operator[](const PDP::UInteger &index) const { return this->Rows[index]; } template<typename T> tMat4x4<T> & tMat4x4<T>::operator=(const typename TypeAid<T, 16>::CoreType &a) { this->Rows[0] = tVec4<T>(a,0,0,0); this->Rows[1] = tVec4<T>(0,a,0,0); this->Rows[2] = tVec4<T>(0,0,a,0); this->Rows[3] = tVec4<T>(0,0,0,a); return (*this); } template <typename U, typename T> inline tMat4x4<T>& operator+= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] += s; a[1] += s; a[2] += s; a[3] += s; return a; } template <typename U, typename T> inline tMat4x4<T>& operator+= (tMat4x4<U> & a, const tMat4x4<T> & b ) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; a[3] += b[3]; return a; } template <typename U, typename T> inline tMat4x4<T> & operator-= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] -= s; a[1] -= s; a[2] -= s; a[3] -= s; return a; } template <typename U, typename T> inline tMat4x4<T> & operator-= (tMat4x4<U> & a, const tMat4x4<T> & m) { a[0] -= m[0]; a[1] -= m[1]; a[2] -= m[2]; a[3] -= m[3]; return a; } template <typename U, typename T> inline tMat4x4<T> & operator*= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] *= s; a[1] *= s; a[2] *= s; a[3] *= s; return a; } template <typename U, typename T> inline tMat4x4<T> & operator*= (tMat4x4<U> & a, const tMat4x4<T> & m) { return (a = a * m); } template <typename U, typename T> inline tMat4x4<T> & operator /= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] /= s; a[1] /= s; a[2] /= s; a[3] /= s; return a; } template <typename T> struct compute_inversetMat4x4 { inline static tMat4x4<T> call( const tMat4x4<T> & m) { const T & Coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; const T & Coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3]; const T & Coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3]; const T & Coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; const T & Coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3]; const T & Coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3]; const T & Coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; const T & Coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2]; const T & Coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2]; const T & Coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; const T & Coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3]; const T & Coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3]; const T & Coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; const T & Coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2]; const T & Coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2]; const T & Coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; const T & Coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1]; const T & Coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1]; const tVec4<T> Fac0(Coef00, Coef00, Coef02, Coef03); const tVec4<T> Fac1(Coef04, Coef04, Coef06, Coef07); const tVec4<T> Fac2(Coef08, Coef08, Coef10, Coef11); const tVec4<T> Fac3(Coef12, Coef12, Coef14, Coef15); const tVec4<T> Fac4(Coef16, Coef16, Coef18, Coef19); const tVec4<T> Fac5(Coef20, Coef20, Coef22, Coef23); const tVec4<T> Vec0(m[1][0], m[0][0], m[0][0], m[0][0]); const tVec4<T> Vec1(m[1][1], m[0][1], m[0][1], m[0][1]); const tVec4<T> Vec2(m[1][2], m[0][2], m[0][2], m[0][2]); const tVec4<T> Vec3(m[1][3], m[0][3], m[0][3], m[0][3]); const tVec4<T> Inv0(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2); const tVec4<T> Inv1(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4); const tVec4<T> Inv2(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5); const tVec4<T> Inv3(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5); const tVec4<T> SignA(+1, -1, +1, -1); const tVec4<T> SignB(-1, +1, -1, +1); const tMat4x4<T> Inverse(Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB); const tVec4<T> Row0(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]); const tVec4<T> Dot0(m[0] * Row0); const T Dot1 = (Dot0.x + Dot0.y) + (Dot0.z + Dot0.w); const T OneOverDeterminant = static_cast<T>(1) / Dot1; return Inverse * OneOverDeterminant; } }; template <typename U, typename T> inline tMat4x4<T> & operator/= (tMat4x4<U> & a, const tMat4x4<T> & m) { return (a = a* compute_inversetMat4x4<T>::call(m)); } template <typename T> inline tMat4x4<T> & operator++ (tMat4x4<T> & m) { m[0]; m[1]; m[2]; m[3]; return m; } template <typename T> inline tMat4x4<T> & operator-- (tMat4x4<T> & m) { m[0]; m[1]; m[2]; m[3]; return m; } template <typename T> inline tMat4x4<T> & operator++(tMat4x4<T> & m,int) { ++m; return m; } template <typename T> inline tMat4x4<T> & operator--(tMat4x4<T> & m, int) { --m; return m; } // Binary operators template <typename T, typename U> inline tMat4x4<T> operator+ ( tMat4x4<T> const & m, const typename TypeAid<U, 16>::CoreType &s ) { return tMat4x4<T>( m[0] + s, m[1] + s, m[2] + s, m[3] + s); } template <typename T, typename U> inline tMat4x4<T> operator+ ( const typename TypeAid<T, 16>::CoreType &s, tMat4x4<U> const & m ) { return tMat4x4<T>( m[0] + s, m[1] + s, m[2] + s, m[3] + s); } template <typename T, typename U> inline tMat4x4<T> operator+ ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { return tMat4x4<T>( m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2], m1[3] + m2[3]); } template <typename T, typename U> inline tMat4x4<T> operator- ( tMat4x4<T> const & m, const typename TypeAid<U, 16>::CoreType &s ) { return tMat4x4<T>( m[0] - s, m[1] - s, m[2] - s, m[3] - s); } template <typename T, typename U> inline tMat4x4<T> operator- ( const typename TypeAid<T, 16>::CoreType &s, tMat4x4<U> const & m ) { return tMat4x4<T>( s - m[0], s - m[1], s - m[2], s - m[3]); } template <typename T> inline tMat4x4<T> operator- ( tMat4x4<T> const &m1, tMat4x4<T> const &m2 ) { return tMat4x4<T>( m1[0] - m2[0], m1[1] - m2[1], m1[2] - m2[2], m1[3] - m2[3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tMat4x4<T> const & m, const typename TypeAid<U, 16>::CoreType &s ) { return tMat4x4<T>( m[0] * s, m[1] * s, m[2] * s, m[3] * s); } template <typename T, typename U> inline tMat4x4<T> operator* ( const typename TypeAid<U, 16>::CoreType &s, tMat4x4<T> const & m ) { return tMat4x4<T>( m[0] * s, m[1] * s, m[2] * s, m[3] * s); } template <typename T, typename U> inline tVec4<T> operator* ( tMat4x4<T> const & m, tVec4<U> const & v ) { tVec4<T> const Mov0(v[0]); tVec4<T> const Mov1(v[1]); tVec4<T> const Mul0 = m[0] * Mov0; tVec4<T> const Mul1 = m[1] * Mov1; tVec4<T> const Add0 = Mul0 + Mul1; tVec4<T> const Mov2(v[2]); tVec4<T> const Mov3(v[3]); tVec4<T> const Mul2 = m[2] * Mov2; tVec4<T> const Mul3 = m[3] * Mov3; tVec4<T> const Add1 = Mul2 + Mul3; tVec4<T> const Add2 = Add0 + Add1; return Add2; } template <typename T, typename U> inline tVec4<T> operator* ( tVec4<T> const & v, tMat4x4<T> const & m ) { return tMat4x4<T>( m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2] + m[0][3] * v[3], m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2] + m[1][3] * v[3], m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2] + m[2][3] * v[3], m[3][0] * v[0] + m[3][1] * v[1] + m[3][2] * v[2] + m[3][3] * v[3]); } template <typename T, typename U> inline tMat2x4<T> operator* ( tMat4x4<T> const & m1, tMat2x4<U> const & m2 ) { return tMat2x4<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3]); } template <typename T, typename U> inline tMat4x4<T> operator*(tMat4x4<T> const & m1, tMat4x4<U> const & m2) { tMat4x4<T> t; // write to temp for (PDP::UShort i=0; i < 4; i++) { for (PDP::UShort j=0; j < 4; j++) { t[i][j] = m1[i][0]*m2[0][j] + m1[i][1]*m2[1][j] + m1[i][2]*m2[2][j] + m1[i][3]*m2[3][j]; } } return t; } template <typename T, typename U> inline tMat3x4<T> operator* ( tMat4x4<T> const & m1, tMat3x4<U> const & m2 ) { return tMat3x4<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3], m1[0][3] * m2[2][0] + m1[1][3] * m2[2][1] + m1[2][3] * m2[2][2] + m1[3][3] * m2[2][3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tVec4<T> const & m1, tMat4x4<U> const & m2 ) { tMat4x4<T> const SrcA0 = m1[0]; tVec4<T> const SrcA1 = m1[1]; tVec4<T> const SrcA2 = m1[2]; tVec4<T> const SrcA3 = m1[3]; tVec4<T> const SrcB0 = m2[0]; tVec4<T> const SrcB1 = m2[1]; tVec4<T> const SrcB2 = m2[2]; tVec4<T> const SrcB3 = m2[3]; tVec4<T> Result(0); Result[0] = SrcA0 * SrcB0[0] + SrcA1 * SrcB0[1] + SrcA2 * SrcB0[2] + SrcA3 * SrcB0[3]; Result[1] = SrcA0 * SrcB1[0] + SrcA1 * SrcB1[1] + SrcA2 * SrcB1[2] + SrcA3 * SrcB1[3]; Result[2] = SrcA0 * SrcB2[0] + SrcA1 * SrcB2[1] + SrcA2 * SrcB2[2] + SrcA3 * SrcB2[3]; Result[3] = SrcA0 * SrcB3[0] + SrcA1 * SrcB3[1] + SrcA2 * SrcB3[2] + SrcA3 * SrcB3[3]; return Result; } template <typename T, typename U> inline tMat4x4<T> operator/ ( tMat4x4<T> const & m, typename TypeAid<U, 16>::CoreType const & s ) { return tMat4x4<T>( m[0] / s, m[1] / s, m[2] / s, m[3] / s); } template <typename T, typename U> inline tMat4x4<T> operator/ ( typename TypeAid<T, 16>::CoreType const & s, tMat4x4<U> const & m ) { return tMat4x4<T>( s / m[0], s / m[1], s / m[2], s / m[3]); } template <typename T, typename U> inline tVec4<T> operator/ ( tMat4x4<T> const & m, tVec4<U> const & v ) { return compute_inversetMat4x4<T>::call(m)*v; } template <typename T, typename U> inline tVec4<T> operator/ ( tVec4<T> const & v, tMat4x4<U> const & m ) { return v * compute_inversetMat4x4<U>::call(m); } template <typename T, typename U> inline tMat4x4<T> operator/ ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { tMat4x4<T> m1_copy(m1); return m1_copy /= m2; } // Unary constant operators template <typename T> inline tMat4x4<T> const operator- ( tMat4x4<T> const & m ) { return tMat4x4<T>( -m[0], -m[1], -m[2], -m[3]); } template <typename T> inline tMat4x4<T> const operator++ ( tMat4x4<T> const & m, int ) { return tMat4x4<T>( m[0] + static_cast<T>(1), m[1] + static_cast<T>(1), m[2] + static_cast<T>(1), m[3] + static_cast<T>(1)); } template <typename T> inline tMat4x4<T> const operator-- ( tMat4x4<T> const & m, int ) { return tMat4x4<T>( m[0] - static_cast<T>(1), m[1] - static_cast<T>(1), m[2] - static_cast<T>(1), m[3] - static_cast<T>(1)); } ////////////////////////////////////// // Boolean operators template <typename T, typename U> inline bool operator== ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { return (m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]) && (m1[3] == m2[3]); } template <typename T, typename U> inline bool operator!= ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { return (m1[0] != m2[0]) || (m1[1] != m2[1]) || (m1[2] != m2[2]) || (m1[3] != m2[3]); } template <typename T, typename U> inline tMat4x3<T> operator* ( tMat4x3<T> const & m1, tMat4x4<U> const & m2 ) { return tMat4x3<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3], m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3], m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3], m1[0][2] * m2[3][0] + m1[1][2] * m2[3][1] + m1[2][2] * m2[3][2] + m1[3][2] * m2[3][3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tMat3x4<T> const & m1, tMat4x3<U> const & m2 ) { const T & SrcA00 = m1[0][0]; const T & SrcA01 = m1[0][1]; const T & SrcA02 = m1[0][2]; const T & SrcA03 = m1[0][3]; const T & SrcA10 = m1[1][0]; const T & SrcA11 = m1[1][1]; const T & SrcA12 = m1[1][2]; const T & SrcA13 = m1[1][3]; const T & SrcA20 = m1[2][0]; const T & SrcA21 = m1[2][1]; const T & SrcA22 = m1[2][2]; const T & SrcA23 = m1[2][3]; const T & SrcB00 = m2[0][0]; const T & SrcB01 = m2[0][1]; const T & SrcB02 = m2[0][2]; const T & SrcB10 = m2[1][0]; const T & SrcB11 = m2[1][1]; const T & SrcB12 = m2[1][2]; const T & SrcB20 = m2[2][0]; const T & SrcB21 = m2[2][1]; const T & SrcB22 = m2[2][2]; const T & SrcB30 = m2[3][0]; const T & SrcB31 = m2[3][1]; const T & SrcB32 = m2[3][2]; tMat4x4<T> Result(T(0)); Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01 + SrcA20 * SrcB02; Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01 + SrcA21 * SrcB02; Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01 + SrcA22 * SrcB02; Result[0][3] = SrcA03 * SrcB00 + SrcA13 * SrcB01 + SrcA23 * SrcB02; Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11 + SrcA20 * SrcB12; Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11 + SrcA21 * SrcB12; Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11 + SrcA22 * SrcB12; Result[1][3] = SrcA03 * SrcB10 + SrcA13 * SrcB11 + SrcA23 * SrcB12; Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21 + SrcA20 * SrcB22; Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21 + SrcA21 * SrcB22; Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21 + SrcA22 * SrcB22; Result[2][3] = SrcA03 * SrcB20 + SrcA13 * SrcB21 + SrcA23 * SrcB22; Result[3][0] = SrcA00 * SrcB30 + SrcA10 * SrcB31 + SrcA20 * SrcB32; Result[3][1] = SrcA01 * SrcB30 + SrcA11 * SrcB31 + SrcA21 * SrcB32; Result[3][2] = SrcA02 * SrcB30 + SrcA12 * SrcB31 + SrcA22 * SrcB32; Result[3][3] = SrcA03 * SrcB30 + SrcA13 * SrcB31 + SrcA23 * SrcB32; return Result; } template <typename T, typename U> inline tMat4x2<T> operator* ( tMat4x2<T> const & m1, tMat4x4<U> const & m2 ) { return tMat4x2<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3], m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tMat2x4<T> const & m1, tMat4x2<U> const & m2 ) { const T & SrcA00 = m1[0][0]; const T & SrcA01 = m1[0][1]; const T & SrcA02 = m1[0][2]; const T & SrcA03 = m1[0][3]; const T & SrcA10 = m1[1][0]; const T & SrcA11 = m1[1][1]; const T & SrcA12 = m1[1][2]; const T & SrcA13 = m1[1][3]; const T & SrcB00 = m2[0][0]; const T & SrcB01 = m2[0][1]; const T & SrcB10 = m2[1][0]; const T & SrcB11 = m2[1][1]; const T & SrcB20 = m2[2][0]; const T & SrcB21 = m2[2][1]; const T & SrcB30 = m2[3][0]; const T & SrcB31 = m2[3][1]; tMat4x4<T> Result(T(0)); Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01; Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01; Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01; Result[0][3] = SrcA03 * SrcB00 + SrcA13 * SrcB01; Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11; Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11; Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11; Result[1][3] = SrcA03 * SrcB10 + SrcA13 * SrcB11; Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21; Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21; Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21; Result[2][3] = SrcA03 * SrcB20 + SrcA13 * SrcB21; Result[3][0] = SrcA00 * SrcB30 + SrcA10 * SrcB31; Result[3][1] = SrcA01 * SrcB30 + SrcA11 * SrcB31; Result[3][2] = SrcA02 * SrcB30 + SrcA12 * SrcB31; Result[3][3] = SrcA03 * SrcB30 + SrcA13 * SrcB31; return Result; } } typedef Detail::tMat4x4<PDP::UInteger> UMat4x4; typedef Detail::tMat4x4<PDP::Integer> IMat4x4; typedef Detail::tMat4x4<float> Mat4x4; typedef Detail::tMat4x4<double> DMat4x4; typedef Detail::tMat4x4<unsigned short> USMat4x4; typedef Detail::tMat4x4<short> SMat4x4; //typedef Detail::tMat4x4<PDP::Half> HMat4x4; } namespace LD { namespace Detail { template<typename T> struct StaticallySized<LD::Detail::tMat4x4<T>>: public LD::Detail::IntegralConstant<bool,true> { }; } } #endif
36.531889
210
0.40164
jlandess
edf4d6c14d2cf3c573aca49985a79226597e3f85
5,614
hpp
C++
test/parser_default_parameters_extra_args_in_between.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
test/parser_default_parameters_extra_args_in_between.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
test/parser_default_parameters_extra_args_in_between.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Á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 #ifndef CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP #define CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP CYNODELIC_TESTER_TEST_CASE(parser_default_parameters_extra_args_in_between); CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,all_long_flags_called) { using prs = mfl::parser< mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>, mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>, mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>> >; argv_maker test_argv( "test", "--first", "1", "extra_args", "431","33", "--second", "1","2", "__XYZ__", "--third", "1","2","3" ); prs::parse(static_cast<int>(test_argv.size()),test_argv.data()); CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1); CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),13); CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),13); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2)),3); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2)),3); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first"))); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--second"))); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--third"))); } CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,single_long_flag_called) { using prs = mfl::parser< mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>, mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>, mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>> >; argv_maker test_argv( "test", "aaaaaaaaaa", "12345", "--first", "12" ); prs::parse(static_cast<int>(test_argv.size()),test_argv.data()); CYNODELIC_TESTER_MESSAGE << "prs::finished_at() = " << prs::finished_at(); CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1); CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),4); CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),4); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0,0)),12); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0,0)),12); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2,0)),0); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first"))); CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--second"))); CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--third"))); } CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,two_long_flags_called) { using prs = mfl::parser< mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>, mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>, mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>> >; argv_maker test_argv( "test", "--first", "963", "AAA", "--extra_arg", "--second", "34","56" ); prs::parse(static_cast<int>(test_argv.size()),test_argv.data()); CYNODELIC_TESTER_MESSAGE << "prs::finished_at() = " << prs::finished_at(); CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1); CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),7); CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),7); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0,0)),963); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0,0)),34); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1,0)),56); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0,0)),963); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0,0)),34); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1,0)),56); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2,0)),0); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first"))); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--second"))); CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--third"))); } #endif // CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP
38.452055
97
0.731386
cynodelic
edf4e86f8a89845491b36e5786f8d7bf6cb4ceac
2,242
cpp
C++
PDFWriter/Trace.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
1,039
2015-01-18T20:03:11.000Z
2022-03-24T02:46:05.000Z
PDFWriter/Trace.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
414
2015-01-22T15:08:45.000Z
2022-02-07T13:51:48.000Z
PDFWriter/Trace.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
209
2015-03-30T23:04:26.000Z
2022-03-28T18:58:47.000Z
/* Source File : Trace.cpp Copyright 2011 Gal Kahana PDFWriter 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 "Trace.h" #include "Log.h" #include "SafeBufferMacrosDefs.h" #include <stdio.h> #include <stdarg.h> Trace& Trace::DefaultTrace(){ static Trace default_trace; return default_trace; } Trace::Trace(void) { mLog = NULL; mLogFilePath = "Log.txt"; mShouldLog = false; } Trace::~Trace(void) { delete mLog; } void Trace::SetLogSettings(const std::string& inLogFilePath,bool inShouldLog,bool inPlaceUTF8Bom) { mShouldLog = inShouldLog; mPlaceUTF8Bom = inPlaceUTF8Bom; mLogFilePath = inLogFilePath; mLogStream = NULL; if(mLog != NULL) { delete mLog; mLog = NULL; //if(mShouldLog) // mLog = new Log(mLogFilePath,inPlaceUTF8Bom); } } void Trace::SetLogSettings(IByteWriter* inLogStream,bool inShouldLog) { mShouldLog = inShouldLog; mLogStream = inLogStream; mPlaceUTF8Bom = false; if(mLog != NULL) { delete mLog; mLog = NULL; if(mShouldLog) mLog = new Log(mLogStream); } } void Trace::TraceToLog(const char* inFormat,...) { if(mShouldLog) { if(NULL == mLog) { if(mLogStream) mLog = new Log(mLogStream); else mLog = new Log(mLogFilePath,mPlaceUTF8Bom); } va_list argptr; va_start(argptr, inFormat); SAFE_VSPRINTF(mBuffer, MAX_TRACE_SIZE,inFormat,argptr); va_end(argptr); mLog->LogEntry(std::string(mBuffer)); } } void Trace::TraceToLog(const char* inFormat,va_list inList) { if(mShouldLog) { if(NULL == mLog) { if(mLogStream) mLog = new Log(mLogStream); else mLog = new Log(mLogFilePath,mPlaceUTF8Bom); } SAFE_VSPRINTF(mBuffer, MAX_TRACE_SIZE,inFormat,inList); mLog->LogEntry(std::string(mBuffer)); } }
19.327586
97
0.706512
thmclellan
edf588e5457f30f9518d52db556e6fabe3d044eb
17,796
cpp
C++
src/gui-qt4/libs/seiscomp3/gui/map/rectangularprojection.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/gui-qt4/libs/seiscomp3/gui/map/rectangularprojection.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/gui-qt4/libs/seiscomp3/gui/map/rectangularprojection.cpp
yannikbehr/seiscomp3
ebb44c77092555eef7786493d00ac4efc679055f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * SeisComP Public License for more details. * ***************************************************************************/ #include <seiscomp3/gui/map/rectangularprojection.h> #include <seiscomp3/gui/map/texturecache.ipp> #include <seiscomp3/math/geo.h> #include <math.h> #include <iostream> #define deg2rad(d) (M_PI*(d)/180.0) #define rad2deg(d) (180.0*(d)/M_PI) #define HALF_PI (M_PI/2) const qreal ooPi = 1.0 / M_PI; namespace Seiscomp { namespace Gui { namespace Map { REGISTER_PROJECTION_INTERFACE(RectangularProjection, "Rectangular"); namespace { const qreal ooLat = 1.0 / 90.0; const qreal ooLon = 1.0 / 180.0; bool checkPrecision(double val, int scale) { double sval = val*scale; return fabs(sval-round(sval)) < 1E-8; } QString lat2String(qreal lat) { if ( checkPrecision(lat, 1) ) return QString("%1%2").arg(abs((int)lat)).arg(lat < 0?" S":lat > 0?" N":""); else if ( checkPrecision(lat, 10) ) return QString("%1%2").arg(fabs(lat), 0, 'f', 1).arg(lat < 0?" S":lat > 0?" N":""); else if ( checkPrecision(lat, 100) ) return QString("%1%2").arg(fabs(lat), 0, 'f', 2).arg(lat < 0?" S":lat > 0?" N":""); else if ( checkPrecision(lat, 1000) ) return QString("%1%2").arg(fabs(lat), 0, 'f', 3).arg(lat < 0?" S":lat > 0?" N":""); else if ( checkPrecision(lat, 10000) ) return QString("%1%2").arg(fabs(lat), 0, 'f', 4).arg(lat < 0?" S":lat > 0?" N":""); else return QString("%1%2").arg(fabs(lat), 0, 'f', 5).arg(lat < 0?" S":lat > 0?" N":""); } QString lon2String(qreal lon) { lon = fmod(lon, 360.0); if ( lon < 0 ) lon += 360.0; if ( lon > 180.0 ) lon -= 360.0; if ( checkPrecision(lon, 1) ) return QString("%1%2").arg(abs((int)lon)).arg(lon < 0?" W":lon > 0?" E":""); else if ( checkPrecision(lon, 10) ) return QString("%1%2").arg(fabs(lon), 0, 'f', 1).arg(lon < 0?" W":lon > 0?" E":""); else if ( checkPrecision(lon, 100) ) return QString("%1%2").arg(fabs(lon), 0, 'f', 2).arg(lon < 0?" W":lon > 0?" E":""); else if ( checkPrecision(lon, 1000) ) return QString("%1%2").arg(fabs(lon), 0, 'f', 3).arg(lon < 0?" W":lon > 0?" E":""); else if ( checkPrecision(lon, 10000) ) return QString("%1%2").arg(fabs(lon), 0, 'f', 4).arg(lon < 0?" W":lon > 0?" E":""); else return QString("%1%2").arg(fabs(lon), 0, 'f', 5).arg(lon < 0?" W":lon > 0?" E":""); } } RectangularProjection::RectangularProjection() : Projection() { _enableLowZoom = false; } void RectangularProjection::setLowZoomEnabled(bool e) { _enableLowZoom = e; } bool RectangularProjection::isRectangular() const { return true; } bool RectangularProjection::wantsGridAntialiasing() const { return false; } template <typename PROC> void RectangularProjection::render(QImage &img, TextureCache *cache) { _screenRadius = std::min(_width*0.25, _height*0.5); QSize size(img.size()); qreal radius = _screenRadius * _radius; double dt; qreal visibleRadius; if ( !_enableLowZoom ) { if ( radius < _halfWidth ) radius = _width*0.25; if ( radius < _halfHeight ) radius = _height*0.5; visibleRadius = radius / _screenRadius; } else visibleRadius = _radius; dt = 1.0 / qreal(radius-1); setVisibleRadius(visibleRadius); QPoint center = QPoint(_halfWidth, _halfHeight); int fromY, toY; fromY = 0; toY = size.height(); qreal iyf = center.y() * dt; if ( iyf > 1.0 ) { if ( _enableLowZoom ) { fromY = (iyf - 1.0) * radius; toY = img.height() - fromY; } iyf = 1.0; } QRgb *data = (QRgb *)img.bits(); int centerX = center.x(); qreal upY = _center.y() + iyf; qreal downY = upY - (toY - fromY) * dt; if ( downY < -1.0 ) { downY = -1.0; upY = downY + (toY - fromY) * dt; _visibleCenter.setY((upY + downY) * 0.5); } if ( upY > 1.0 ) { upY = 1.0; downY = upY - (toY - fromY) * dt; _visibleCenter.setY((upY + downY) * 0.5); } data += fromY * img.width(); qreal y = upY; //qreal ixf = (qreal)centerX / radius; qreal ixf = 2.0; qint64 pxf = qint64(ixf*radius); qint64 fx, tx; fx = centerX - pxf; tx = centerX + pxf; if ( fx < 0 ) { ixf += fx * dt; fx = 0; } // Clip to left border if ( tx < 2 ) tx = 0; // Clip to right border if ( tx >= size.width()-2 ) tx = size.width()-1; int fromX = (int)fx; int toX = (int)tx; if ( cache == NULL ) return; qreal pixelRatio = 2.0*_scale / cache->tileHeight(); if ( cache->isMercatorProjected() ) pixelRatio *= 2; if ( pixelRatio < 1 ) pixelRatio = 1; int level = (int)(log(pixelRatio) / log(2.0) + 0.7); if ( level > cache->maxLevel() ) level = cache->maxLevel(); qreal leftX = 2.0*_center.x() - ixf; qreal rightX = 2.0*_center.x() + ixf; int pixels = toX - fromX + 1; Coord leftTu; Coord rightTu; leftTu.value = (leftX*0.5+1.0) * Coord::value_type(Coord::fraction_half_max); rightTu.value = (rightX*0.5+1.0) * Coord::value_type(Coord::fraction_half_max); if ( cache->isMercatorProjected() ) { for ( int i = fromY; i < toY; ++i, y -= dt ) { if ( y <= -1.0 ) y = -1.0 + dt; Coord tv; qreal lat = y; if ( lat > 0.94 ) lat = 0.94; else if ( lat < -0.94 ) lat = -0.94; lat = ooPi*asinh(tan(lat*HALF_PI)); tv.value = (1.0f-lat) * Coord::value_type(Coord::fraction_half_max); PROC::fetch(cache, data[fromX], leftTu, tv, level); PROC::fetch(cache, data[toX], rightTu, tv, level); // Shift only by 30 bits to keep the sign bit in the lower 32 bit Coord::value_type xDelta = rightTu.value - leftTu.value; qint64 stepU = (qint64(xDelta) << 30) / pixels; qint64 stepper; Coord lon; stepper = qint64(leftTu.value) << 30; stepper += stepU; for ( int k = 1; k < pixels; ++k ) { lon.value = stepper >> 30; PROC::fetch(cache, data[fromX + k], lon, tv, level); stepper += stepU; } data += size.width(); } } else { for ( int i = fromY; i < toY; ++i, y -= dt ) { if ( y <= -1.0 ) y = -1.0 + dt; Coord tv; tv.value = (1.0-y) * Coord::value_type(Coord::fraction_half_max); PROC::fetch(cache, data[fromX], leftTu, tv, level); PROC::fetch(cache, data[toX], rightTu, tv, level); // Shift only by 30 bits to keep the sign bit in the lower 32 bit Coord::value_type xDelta = rightTu.value - leftTu.value; qint64 stepU = (qint64(xDelta) << 30) / pixels; qint64 stepper; Coord lon; stepper = qint64(leftTu.value) << 30; stepper += stepU; for ( int k = 1; k < pixels; ++k ) { lon.value = stepper >> 30; PROC::fetch(cache, data[fromX + k], lon, tv, level); stepper += stepU; } data += size.width(); } } } void RectangularProjection::render(QImage& img, bool highQuality, TextureCache *cache) { if ( highQuality ) render<BilinearFilter>(img, cache); else render<NearestFilter>(img, cache); } bool RectangularProjection::project(QPoint &screenCoords, const QPointF &geoCoords) const { qreal x = geoCoords.x() * ooLon; qreal lat = geoCoords.y(); if ( lat > 90.0 ) { lat = 180.0 - lat; x += 1.0; if ( x > 1.0 ) x -= 2.0; } else if ( lat < -90.0 ) { lat = -180.0 - lat; x += 1.0; if ( x > 1.0 ) x -= 2.0; } qreal y = lat * ooLat; x = (x - _visibleCenter.x()) * _halfMapWidth; y = (y - _visibleCenter.y()) * _scale; if ( x > _halfMapWidth ) x -= _mapWidth; if ( x < -_halfMapWidth ) x += _mapWidth; screenCoords.setX(_halfWidth + x); screenCoords.setY(_halfHeight - y); return true; } bool RectangularProjection::unproject(QPointF &geoCoords, const QPoint &screenCoords) const { qreal x = screenCoords.x() - _halfWidth; qreal y = _halfHeight - screenCoords.y(); if ( x < -_halfMapWidth || x > _halfMapWidth ) return false; if ( y < -_scale || y > _scale ) return false; x = x / (qreal)_halfMapWidth + _visibleCenter.x(); y = y / (qreal)_scale + _visibleCenter.y(); x *= 180.0; y *= 90.0; if ( x < -180.0 ) x += 360.0; if ( x > 180.0 ) x -= 360.0; geoCoords.setX(x); geoCoords.setY(y); return true; } void RectangularProjection::centerOn(const QPointF &geoCoords) { qreal x = geoCoords.x() * ooLon; qreal y = geoCoords.y() * ooLat; if ( x < -1.0 ) x += 2.0; if ( x > 1.0 ) x -= 2.0; if ( y < -1.0 ) y = -1.0; if ( y > 1.0 ) y = 1.0; _center = QPointF(x,y); _visibleCenter = _center; } int RectangularProjection::lineSteps(const QPointF &p0, const QPointF &p1) { // Calculate the distance between p0 and p1 in pixels and // divide its manhattanLength by 20 double dist, azi1, azi2; Math::Geo::delazi(p0.y(), p0.x(), p1.y(), p1.x(), &dist, &azi1, &azi2); if ( azi1 > 359.0 && azi1 < 1.0 && azi1 > 179.0 && azi1 < 180.0 ) return 1; //return dist * pixelPerDegree() * (1.0 / 20.0); return 20; } void RectangularProjection::drawImage(QImage &buffer, const QRectF &geoReference, const QImage &image, bool highQuality) { if ( image.format() != QImage::Format_RGB32 && image.format() != QImage::Format_ARGB32 ) return; bool useAlpha = image.format() == QImage::Format_ARGB32; QPoint p00, p11; qreal minLat, maxLat; qreal minLon, maxLon; minLat = geoReference.top(); maxLat = geoReference.bottom(); minLon = geoReference.left(); maxLon = geoReference.right(); if ( minLat > maxLat ) std::swap(minLat, maxLat); project(p00, QPointF(minLon, minLat)); project(p11, QPointF(maxLon, maxLat)); bool wrap = fabs(maxLon - minLon) >= 360.; int x0 = p00.x(); int x1 = p11.x(); int y0 = p00.y(); int y1 = p11.y(); // X can be wrapped, so we have to check more cases if ( geoReference.width() < 180.0f ) { if ( x0 >= _width ) { if ( x1 < 0 || x1 >= _width ) return; } if ( x1 < 0 ) { if ( x0 < 0 || x0 >= _width ) return; } } if ( y0 > y1 ) std::swap(y0,y1); // Y has no wrapping, so the checks are more simply if ( y0 >= _height ) return; if ( y1 < 0 ) return; bool drawTwoParts = false; // Quick hack just for testing // TODO: This special case has to be handled. if ( x0 >= x1 || wrap ) { drawTwoParts = true; if ( x0 >= x1 ) x0 -= _mapWidth; else if ( wrap ) x0 = x1 - _mapWidth; } int scaledWidth = x1-x0+1; int scaledHeight = y1-y0+1; Coord ratioX, ratioY; ratioX.parts.hi = image.width(); ratioX.parts.lo = 0; ratioY.parts.hi = image.height(); ratioY.parts.lo = 0; ratioX.value /= scaledWidth; ratioY.value /= scaledHeight; while ( true ) { int width = image.width(); int height = image.height(); Coord xofs, yofs; int x0c = x0, y0c = y0, x1c = x1; // Something has to be painted const QRgb *data = (const QRgb*)image.bits(); QRgb *targetData = (QRgb*)buffer.bits(); int targetWidth = buffer.width(); if ( x0c < 0 ) { xofs.value = ratioX.value * -x0c; x0c = 0; } else xofs.value = 0; if ( x1c >= _width ) x1c = _width-1; if ( y0c < 0 ) { yofs.value = ratioY.value * -y0c; height -= yofs.parts.hi; data += image.width() * yofs.parts.hi; y0c = 0; } else yofs.value = 0; if ( y1 >= _height ) y1 = _height-1; targetData += targetWidth * y0c + x0c; Coord y; y.parts.hi = 0; y.parts.lo = yofs.parts.lo; if ( useAlpha ) { if ( highQuality ) { for ( int i = y0c; i <= y1; ++i ) { QRgb *targetPixel = targetData; Coord x; x.value = xofs.value; for ( int j = x0c; j <= x1c; ++j ) { QRgb c; getTexelBilinear(c, data, width, height, x, y); int alpha = qAlpha(c); int iAlpha = 255 - alpha; *targetPixel = qRgb( (qRed(c)*alpha + qRed(*targetPixel)*iAlpha) >> 8, (qGreen(c)*alpha + qGreen(*targetPixel)*iAlpha) >> 8, (qBlue(c)*alpha + qBlue(*targetPixel)*iAlpha) >> 8 ); ++targetPixel; x.value += ratioX.value; } targetData += targetWidth; y.value += ratioY.value; int skipLines = y.parts.hi; height -= skipLines; while ( skipLines ) { data += width; --skipLines; } y.parts.hi = 0; } } else { for ( int i = y0c; i <= y1; ++i ) { QRgb *targetPixel = targetData; Coord x; x.value = xofs.value; for ( int j = x0c; j <= x1c; ++j ) { QRgb c = data[x.parts.hi]; int alpha = qAlpha(c); int iAlpha = 255 - alpha; *targetPixel = qRgb( (qRed(c)*alpha + qRed(*targetPixel)*iAlpha) >> 8, (qGreen(c)*alpha + qGreen(*targetPixel)*iAlpha) >> 8, (qBlue(c)*alpha + qBlue(*targetPixel)*iAlpha) >> 8 ); ++targetPixel; x.value += ratioX.value; } targetData += targetWidth; y.value += ratioY.value; int skipLines = y.parts.hi; while ( skipLines ) { data += width; --skipLines; } y.parts.hi = 0; } } } else { if ( highQuality ) { for ( int i = y0c; i <= y1; ++i ) { QRgb *targetPixel = targetData; Coord x; x.value = xofs.value; for ( int j = x0c; j <= x1c; ++j ) { getTexelBilinear(*targetPixel, data, width, height, x, y); ++targetPixel; x.value += ratioX.value; } targetData += targetWidth; y.value += ratioY.value; int skipLines = y.parts.hi; height -= skipLines; while ( skipLines ) { data += width; --skipLines; } y.parts.hi = 0; } } else { for ( int i = y0c; i <= y1; ++i ) { QRgb *targetPixel = targetData; Coord x; x.value = xofs.value; for ( int j = x0c; j <= x1c; ++j ) { *targetPixel = data[x.parts.hi]; ++targetPixel; x.value += ratioX.value; } targetData += targetWidth; y.value += ratioY.value; int skipLines = y.parts.hi; while ( skipLines ) { data += width; --skipLines; } y.parts.hi = 0; } } } if ( drawTwoParts ) { x0 += _mapWidth; x1 += _mapWidth; drawTwoParts = false; } else break; } } bool RectangularProjection::drawLine(QPainter &p, const QPointF &from, const QPointF &to) { QPoint x0, x1; bool x0Visible, x1Visible; x0Visible = project(x0, from); x1Visible = project(x1, to); if ( !x0Visible || !x1Visible ) return false; qreal degx0 = fmod(from.x(), 360.0); qreal degx1 = fmod(to.x(), 360.0); int dir = x1.x() - x0.x(); qreal degdir = degx1 - degx0; if ( degdir > 180 ) degdir -= 360; if ( degdir < -180 ) degdir += 360; if ( (dir * degdir) < 0 ) { if ( x1.x() > x0.x() ) { int leftX = _halfWidth - _halfMapWidth; int leftY = x0.y() + ((leftX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() - _mapWidth) - x0.x()); p.drawLine(x0, QPoint(leftX, leftY)); p.drawLine(QPoint(leftX + _mapWidth, leftY), x1); } else { int rightX = _halfWidth + _halfMapWidth; int rightY = x0.y() + ((rightX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() + _mapWidth) - x0.x()); p.drawLine(x0, QPoint(rightX, rightY)); p.drawLine(QPoint(rightX - _mapWidth, rightY), x1); } } else p.drawLine(x0, x1); return true; } void RectangularProjection::moveTo(const QPointF &p) { Projection::moveTo(p); _cursorLon = fmod(p.x(), 360.0); } bool RectangularProjection::lineTo(QPainter &p, const QPointF &to) { QPoint x1; bool x1Visible; x1Visible = project(x1, to); qreal degx1 = fmod(to.x(), 360.0); if ( !_cursorVisible || !x1Visible ) { _cursorLon = degx1; _cursor = x1; _cursorVisible = x1Visible; return false; } int dir = x1.x() - _cursor.x(); qreal degdir = degx1 - _cursorLon; if ( degdir > 180 ) degdir -= 360; if ( degdir < -180 ) degdir += 360; QPoint &x0 = _cursor; if ( (dir * degdir) < 0 ) { if ( x1.x() > x0.x() ) { int leftX = _halfWidth - _halfMapWidth; int leftY = x0.y() + ((leftX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() - _mapWidth) - x0.x()); p.drawLine(x0, QPoint(leftX, leftY)); p.drawLine(QPoint(leftX + _mapWidth, leftY), x1); } else { int rightX = _halfWidth + _halfMapWidth; int rightY = x0.y() + ((rightX - x0.x()) * (x1.y() - x0.y())) / ((x1.x() + _mapWidth) - x0.x()); p.drawLine(x0, QPoint(rightX, rightY)); p.drawLine(QPoint(rightX - _mapWidth, rightY), x1); } } else p.drawLine(x0, x1); _cursorLon = degx1; _cursor = x1; _cursorVisible = x1Visible; return true; } bool RectangularProjection::drawLatCircle(QPainter &p, qreal lon) { QPoint pp; if ( project(pp, QPointF(lon, 90)) ) { if ( pp.x() >= 0 && pp.x() < _width ) { int top = std::max(0, pp.y()); int bottom = std::min(_height-1, pp.y() + (int)_halfMapWidth); p.drawLine(pp.x(), top, pp.x(), bottom); p.drawText(QRect((int)pp.x() + 2, top, _width, _height), Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, lon2String(lon)); return true; } } return false; } bool RectangularProjection::drawLonCircle(QPainter &p, qreal lat) { QPoint pp; if ( project(pp, QPointF(0, lat)) ) { if ( pp.y() >= 0 && pp.y() < _height ) { int left = std::max(0,_halfWidth - (int)(_scale*2)); int right = std::min(_width-1, _halfWidth + (int)(_scale*2)); p.drawLine(left, pp.y(), right, pp.y()); p.drawText(QRect(left, pp.y(), _width, _height), Qt::AlignLeft | Qt::AlignTop | Qt::TextSingleLine, lat2String(lat)); return true; } } return false; } } } }
22.903475
128
0.571196
yannikbehr
edf5ac4512886af5808226f06babb0e66e541335
2,158
cpp
C++
aws-cpp-sdk-mgn/source/model/IdentificationHints.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-mgn/source/model/IdentificationHints.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-mgn/source/model/IdentificationHints.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mgn/model/IdentificationHints.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace mgn { namespace Model { IdentificationHints::IdentificationHints() : m_awsInstanceIDHasBeenSet(false), m_fqdnHasBeenSet(false), m_hostnameHasBeenSet(false), m_vmPathHasBeenSet(false), m_vmWareUuidHasBeenSet(false) { } IdentificationHints::IdentificationHints(JsonView jsonValue) : m_awsInstanceIDHasBeenSet(false), m_fqdnHasBeenSet(false), m_hostnameHasBeenSet(false), m_vmPathHasBeenSet(false), m_vmWareUuidHasBeenSet(false) { *this = jsonValue; } IdentificationHints& IdentificationHints::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("awsInstanceID")) { m_awsInstanceID = jsonValue.GetString("awsInstanceID"); m_awsInstanceIDHasBeenSet = true; } if(jsonValue.ValueExists("fqdn")) { m_fqdn = jsonValue.GetString("fqdn"); m_fqdnHasBeenSet = true; } if(jsonValue.ValueExists("hostname")) { m_hostname = jsonValue.GetString("hostname"); m_hostnameHasBeenSet = true; } if(jsonValue.ValueExists("vmPath")) { m_vmPath = jsonValue.GetString("vmPath"); m_vmPathHasBeenSet = true; } if(jsonValue.ValueExists("vmWareUuid")) { m_vmWareUuid = jsonValue.GetString("vmWareUuid"); m_vmWareUuidHasBeenSet = true; } return *this; } JsonValue IdentificationHints::Jsonize() const { JsonValue payload; if(m_awsInstanceIDHasBeenSet) { payload.WithString("awsInstanceID", m_awsInstanceID); } if(m_fqdnHasBeenSet) { payload.WithString("fqdn", m_fqdn); } if(m_hostnameHasBeenSet) { payload.WithString("hostname", m_hostname); } if(m_vmPathHasBeenSet) { payload.WithString("vmPath", m_vmPath); } if(m_vmWareUuidHasBeenSet) { payload.WithString("vmWareUuid", m_vmWareUuid); } return payload; } } // namespace Model } // namespace mgn } // namespace Aws
17.983333
72
0.712697
perfectrecall
edfca4da0ac988ec35bb064d320585eb1bd51517
2,041
hpp
C++
sdk/include/vill_runtime.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/vill_runtime.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/vill_runtime.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
#ifndef WPP_VILL_RUNTIME_H #define WPP_VILL_RUNTIME_H #include <vector> #include "wlexer.hpp" #include "werr.hpp" #include "errors.hpp" using namespace wpp; using namespace wpp::how; namespace mill{ struct vill_type { typedef unsigned char int_u8; typedef unsigned short int_u16; typedef unsigned int int_u32; typedef unsigned __int64 int_u64; typedef char int_i8; typedef short int_i16; typedef int int_i32; typedef __int64 int_i64; typedef float float32; typedef double float64; typedef long double float80; typedef char* astring; typedef wchar_t* string; typedef unsigned char ubyte; typedef char byte; typedef char achar; typedef wchar_t wchar; typedef void* obj_ptr; typedef bool boolean; }; struct vill_register { union { vill_type::int_u8 val_u8; vill_type::int_u16 val_u16; vill_type::int_u32 val_u32; vill_type::int_u64 val_u64; vill_type::int_i8 val_i8; vill_type::int_i16 val_i16; vill_type::int_i32 val_i32; vill_type::int_i64 val_i64; vill_type::float32 val_f32; vill_type::float64 val_f64; vill_type::float80 val_f80; vill_type::boolean val_bool; vill_type::obj_ptr val_ptr; vill_type::string val_string; vill_type::astring val_astring; }; }; struct vill_flag_register { unsigned int C : 1; //carry unsigned int Z : 1; //zero unsigned int S : 1; //sign unsigned int O : 1; //overflow }; class vill_runtime { public: static const int void_ptr_size = 4; public: std::vector<vill_register>* ptr_registeres; vill_flag_register flag_register; int* ptr_stackes; int* stack_bp; int* stack_sp; public: void set_err_ptr(wErr* err_ptr); wErr* get_err_ptr(); void error(error::err nError, const wchar_t* str, wtoken& tk); private: wErr* err_ptr_; public: //std::map<std::wstring /*dll*/,std::map<std::wstring /*alias*/, int>> * ptr_extern_method_; vill_runtime(); ~vill_runtime(); public: void reset(); //int step_next(); //int step_continue(); }; } //namespace mill #endif //WPP_VILL_RUNTIME
20.826531
93
0.721215
qianxj
edfd13d9bfd361bf7b8d660786bd30f12d8a3887
3,257
cpp
C++
src/qt/qtbase/src/platformsupport/fbconvenience/qfbvthandler.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2021-02-09T10:24:31.000Z
2021-02-09T10:24:31.000Z
src/qt/qtbase/src/platformsupport/fbconvenience/qfbvthandler.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/platformsupport/fbconvenience/qfbvthandler.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfbvthandler_p.h" #include <QtCore/private/qcrashhandler_p.h> #include <QtGui/private/qguiapplication_p.h> #if defined(Q_OS_LINUX) && !defined(QT_NO_EVDEV) #define HAS_VT #endif #ifdef HAS_VT #include <sys/ioctl.h> #include <linux/kd.h> #ifdef K_OFF #define KBD_OFF_MODE K_OFF #else #define KBD_OFF_MODE K_RAW #endif #endif // HAS_VT QT_BEGIN_NAMESPACE QFbVtHandler *QFbVtHandler::self = 0; QFbVtHandler::QFbVtHandler(QObject *parent) : QObject(parent), m_tty(-1) { Q_ASSERT(!self); self = this; #ifdef HAS_VT if (!isatty(0)) return; m_tty = 0; ::ioctl(m_tty, KDGKBMODE, &m_oldKbdMode); if (!qgetenv("QT_QPA_ENABLE_TERMINAL_KEYBOARD").toInt()) { ::ioctl(m_tty, KDSKBMODE, KBD_OFF_MODE); QGuiApplicationPrivate *appd = QGuiApplicationPrivate::instance(); Q_ASSERT(appd); QSegfaultHandler::initialize(appd->argv, appd->argc); QSegfaultHandler::installCrashHandler(crashHandler); } #endif } QFbVtHandler::~QFbVtHandler() { self->cleanup(); self = 0; } void QFbVtHandler::cleanup() { if (m_tty == -1) return; #ifdef HAS_VT ::ioctl(m_tty, KDSKBMODE, m_oldKbdMode); #endif } void QFbVtHandler::crashHandler() { Q_ASSERT(self); self->cleanup(); } QT_END_NAMESPACE
29.080357
77
0.691741
viewdy
edfd4cd91aa90cab43923857b0fa64373512c528
529
cc
C++
src/chrome/browser/android/tab_android_test_stubs.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
chrome/browser/android/tab_android_test_stubs.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/android/tab_android_test_stubs.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file contains stubs for some Chrome for Android specific code that is // needed to compile some tests. #include "chrome/browser/android/tab_android.h" // static TabAndroid* TabAndroid::FromWebContents(content::WebContents* web_contents) { return NULL; } // static TabAndroid* TabAndroid::GetNativeTab(JNIEnv* env, jobject obj) { return NULL; }
27.842105
77
0.754253
jxjnjjn
edfd7a28c843e40343ea0a65db8f777051851afb
1,565
cpp
C++
plugins/community/repos/JW-Modules/src/JWModules.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/JW-Modules/src/JWModules.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/JW-Modules/src/JWModules.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "JWModules.hpp" RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BlankPanelSmall); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BlankPanelMedium); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BlankPanelLarge); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, Cat); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, BouncyBalls); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, FullScope); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, GridSeq); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, Quantizer); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, MinMax); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, NoteSeq); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, SimpleClock); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, ThingThing); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, WavHead); RACK_PLUGIN_MODEL_DECLARE(JW_Modules, XYPad); RACK_PLUGIN_INIT(JW_Modules) { RACK_PLUGIN_INIT_ID(); RACK_PLUGIN_INIT_VERSION("0.6.3"); RACK_PLUGIN_INIT_WEBSITE("https://github.com/jeremywen/JW-Modules"); RACK_PLUGIN_MODEL_ADD(JW_Modules, BlankPanelSmall); RACK_PLUGIN_MODEL_ADD(JW_Modules, BlankPanelMedium); RACK_PLUGIN_MODEL_ADD(JW_Modules, BlankPanelLarge); RACK_PLUGIN_MODEL_ADD(JW_Modules, Cat); RACK_PLUGIN_MODEL_ADD(JW_Modules, BouncyBalls); RACK_PLUGIN_MODEL_ADD(JW_Modules, FullScope); RACK_PLUGIN_MODEL_ADD(JW_Modules, GridSeq); RACK_PLUGIN_MODEL_ADD(JW_Modules, Quantizer); RACK_PLUGIN_MODEL_ADD(JW_Modules, MinMax); RACK_PLUGIN_MODEL_ADD(JW_Modules, NoteSeq); RACK_PLUGIN_MODEL_ADD(JW_Modules, SimpleClock); RACK_PLUGIN_MODEL_ADD(JW_Modules, ThingThing); RACK_PLUGIN_MODEL_ADD(JW_Modules, WavHead); RACK_PLUGIN_MODEL_ADD(JW_Modules, XYPad); }
41.184211
71
0.851757
guillaume-plantevin
610225e400813be30b8aef719cc410c2e1d47bc2
27,534
hpp
C++
test/fixtures/cpp-root/external/geode-nativeclient-9.1/include/geode/CacheableBuiltins.hpp
Pivotal-Field-Engineering/cpp-buildpack
17f03c5c5019073397cdb6aba5b9d630c85e33ea
[ "Apache-2.0" ]
1
2019-05-29T01:20:58.000Z
2019-05-29T01:20:58.000Z
test/fixtures/cpp-root/external/geode-nativeclient-9.1/include/geode/CacheableBuiltins.hpp
Pivotal-Field-Engineering/cpp-buildpack
17f03c5c5019073397cdb6aba5b9d630c85e33ea
[ "Apache-2.0" ]
null
null
null
test/fixtures/cpp-root/external/geode-nativeclient-9.1/include/geode/CacheableBuiltins.hpp
Pivotal-Field-Engineering/cpp-buildpack
17f03c5c5019073397cdb6aba5b9d630c85e33ea
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef GEODE_CACHEABLEBUILTINS_H_ #define GEODE_CACHEABLEBUILTINS_H_ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @file CacheableBuiltins.hpp * @brief Contains generic template definitions for Cacheable types * and instantiations for built-in types. */ #include <cstring> #include "Cacheable.hpp" #include "CacheableKey.hpp" #include "Serializer.hpp" #include "CacheableKeys.hpp" #include "CacheableString.hpp" namespace apache { namespace geode { namespace client { /** sprintf implementation. */ extern int gf_sprintf(char* buffer, const char* fmt, ...); /** snprintf implementation. */ extern int gf_snprintf(char* buffer, int32_t maxLength, const char* fmt, ...); /** Template CacheableKey class for primitive types. */ template <typename TObj, int8_t TYPEID, const char* TYPENAME, const char* SPRINTFSYM, int32_t STRSIZE> class CacheableKeyType : public CacheableKey { protected: TObj m_value; inline CacheableKeyType() : m_value(apache::geode::client::serializer::zeroObject<TObj>()) {} inline CacheableKeyType(const TObj value) : m_value(value) {} public: /** Gets the contained value. */ inline TObj value() const { return m_value; } // Cacheable methods /** Serialize this object to given <code>DataOutput</code>. */ virtual void toData(DataOutput& output) const { apache::geode::client::serializer::writeObject(output, m_value); } /** Deserialize this object from given <code>DataInput</code>. */ virtual Serializable* fromData(DataInput& input) { apache::geode::client::serializer::readObject(input, m_value); return this; } /** * Return the classId of the instance being serialized. * * This is used by deserialization to determine what instance * type to create and deserialize into. */ virtual int32_t classId() const { return 0; } /** * Return the typeId byte of the instance being serialized. * * This is used by deserialization to determine what instance * type to create and deserialize into. */ virtual int8_t typeId() const { return TYPEID; } /** Return a string representation of the object. */ virtual CacheableStringPtr toString() const { char buffer[STRSIZE + 1]; gf_sprintf(buffer, SPRINTFSYM, m_value); return CacheableString::create(buffer); } // CacheableKey methods /** Return the hashcode for this key. */ virtual int32_t hashcode() const { return apache::geode::client::serializer::hashcode(m_value); } /** Return true if this key matches other. */ virtual bool operator==(const CacheableKey& other) const { if (other.typeId() != TYPEID) { return false; } const CacheableKeyType& otherValue = static_cast<const CacheableKeyType&>(other); return apache::geode::client::serializer::equals(m_value, otherValue.m_value); } /** Return true if this key matches other key value. */ inline bool operator==(const TObj other) const { return apache::geode::client::serializer::equals(m_value, other); } /** * Copy the string form of the object into a char* buffer for * logging purposes. */ virtual int32_t logString(char* buffer, int32_t maxLength) const { char fmt[64]; gf_sprintf(fmt, "%s( %s )", TYPENAME, SPRINTFSYM); return gf_snprintf(buffer, maxLength, fmt, m_value); } /** * Return the size in bytes of the instance being serialized. * * This is used to determine whether the cache is using up more * physical memory than it has been configured to use. The method can * return zero if the user does not require the ability to control * cache memory utilization. */ virtual uint32_t objectSize() const { return sizeof(CacheableKeyType); } }; // Forward declaration for SharedArrayPtr template <typename TObj, int8_t TYPEID> class SharedArrayPtr; /** Function to copy an array from source to destination. */ template <typename TObj> inline void copyArray(TObj* dest, const TObj* src, int32_t length) { std::memcpy(dest, src, length * sizeof(TObj)); } /** * Function to copy an array of <code>SharedPtr</code>s from * source to destination. */ template <typename TObj> inline void copyArray(SharedPtr<TObj>* dest, const SharedPtr<TObj>* src, int32_t length) { for (int32_t index = 0; index < length; index++) { dest[index] = src[index]; } } /** * Function to copy an array of <code>SharedArrayPtr</code>s from * source to destination. */ template <typename TObj, int8_t TYPEID> inline void copyArray(SharedArrayPtr<TObj, TYPEID>* dest, const SharedArrayPtr<TObj, TYPEID>* src, int32_t length) { for (int32_t index = 0; index < length; index++) { dest[index] = src[index]; } } /** Template class for array of primitive types. */ template <typename TObj, int8_t TYPEID> class CacheableArrayType : public Cacheable { protected: TObj* m_value; int32_t m_length; inline CacheableArrayType() : m_value(NULL), m_length(0) {} inline CacheableArrayType(int32_t length) : m_length(length) { if (length > 0) { GF_NEW(m_value, TObj[length]); } } inline CacheableArrayType(TObj* value, int32_t length) : m_value(value), m_length(length) {} inline CacheableArrayType(const TObj* value, int32_t length, bool copy) : m_value(NULL), m_length(length) { if (length > 0) { GF_NEW(m_value, TObj[length]); copyArray(m_value, value, length); } } virtual ~CacheableArrayType() { GF_SAFE_DELETE_ARRAY(m_value); } private: // Private to disable copy constructor and assignment operator. CacheableArrayType(const CacheableArrayType& other) : m_value(other.m_value), m_length(other.m_length) {} CacheableArrayType& operator=(const CacheableArrayType& other) { return *this; } public: /** Get the underlying array. */ inline const TObj* value() const { return m_value; } /** Get the length of the array. */ inline int32_t length() const { return m_length; } /** Get the element at given index. */ inline TObj operator[](uint32_t index) const { if (static_cast<int32_t>(index) >= m_length) { throw OutOfRangeException( "CacheableArray::operator[]: Index out of range."); } return m_value[index]; } // Cacheable methods /** Serialize this object to the given <code>DataOutput</code>. */ virtual void toData(DataOutput& output) const { apache::geode::client::serializer::writeObject(output, m_value, m_length); } /** Deserialize this object from the given <code>DataInput</code>. */ virtual Serializable* fromData(DataInput& input) { GF_SAFE_DELETE_ARRAY(m_value); apache::geode::client::serializer::readObject(input, m_value, m_length); return this; } /** * Return the classId of the instance being serialized. * * This is used by deserialization to determine what instance * type to create and deserialize into. */ virtual int32_t classId() const { return 0; } /** * Return the typeId byte of the instance being serialized. * * This is used by deserialization to determine what instance * type to create and deserialize into. */ virtual int8_t typeId() const { return TYPEID; } /** * Return the size in bytes of the instance being serialized. * * This is used to determine whether the cache is using up more * physical memory than it has been configured to use. The method can * return zero if the user does not require the ability to control * cache memory utilization. */ virtual uint32_t objectSize() const { return static_cast<uint32_t>( sizeof(CacheableArrayType) + apache::geode::client::serializer::objectSize(m_value, m_length)); } }; /** * Template class for CacheableArrayType SharedPtr's that adds [] operator */ template <typename TObj, int8_t TYPEID> class SharedArrayPtr : public SharedPtr<CacheableArrayType<TObj, TYPEID> > { private: typedef CacheableArrayType<TObj, TYPEID> TArray; public: /** Default constructor. */ inline SharedArrayPtr() : SharedPtr<CacheableArrayType<TObj, TYPEID> >() {} /** Constructor, given a pointer to array. */ inline SharedArrayPtr(const TArray* ptr) : SharedPtr<CacheableArrayType<TObj, TYPEID> >(ptr) {} /** Constructor, given a null SharedBase. */ inline SharedArrayPtr(const NullSharedBase* ptr) : SharedPtr<CacheableArrayType<TObj, TYPEID> >(ptr) {} /** Constructor, given another SharedArrayPtr. */ inline SharedArrayPtr(const SharedArrayPtr& other) : SharedPtr<CacheableArrayType<TObj, TYPEID> >(other) {} /** Constructor, given another kind of SharedArrayPtr. */ template <typename TOther, int8_t OTHERID> inline SharedArrayPtr(const SharedArrayPtr<TOther, OTHERID>& other) : SharedPtr<CacheableArrayType<TObj, TYPEID> >(other) {} /** Constructor, given another SharedPtr. */ template <typename TOther> inline SharedArrayPtr(const SharedPtr<TOther>& other) : SharedPtr<CacheableArrayType<TObj, TYPEID> >(other) {} /** Get the element at given index. */ inline TObj operator[](uint32_t index) const { return SharedPtr<CacheableArrayType<TObj, TYPEID> >::ptr()->operator[]( index); } /** Deserialize self */ inline Serializable* fromData(DataInput& input) { return SharedPtr<CacheableArrayType<TObj, TYPEID> >::ptr()->fromData(input); } }; /** Template class for container Cacheable types. */ template <typename TBase, int8_t TYPEID> class CacheableContainerType : public Cacheable, public TBase { protected: inline CacheableContainerType() : TBase() {} inline CacheableContainerType(const int32_t n) : TBase(n) {} public: // Cacheable methods /** Serialize this object to the given <code>DataOutput</code>. */ virtual void toData(DataOutput& output) const { apache::geode::client::serializer::writeObject(output, *this); } /** Deserialize this object from the given <code>DataInput</code>. */ virtual Serializable* fromData(DataInput& input) { apache::geode::client::serializer::readObject(input, *this); return this; } /** * Return the classId of the instance being serialized. * * This is used by deserialization to determine what instance * type to create and deserialize into. */ virtual int32_t classId() const { return 0; } /** * Return the typeId byte of the instance being serialized. * * This is used by deserialization to determine what instance * type to create and deserialize into. */ virtual int8_t typeId() const { return TYPEID; } /** * Return the size in bytes of the instance being serialized. * * This is used to determine whether the cache is using up more * physical memory than it has been configured to use. The method can * return zero if the user does not require the ability to control * cache memory utilization. */ virtual uint32_t objectSize() const { return static_cast<uint32_t>( sizeof(CacheableContainerType) + apache::geode::client::serializer::objectSize(*this)); } }; #ifdef _SOLARIS #define TEMPLATE_EXPORT template class #else #ifdef BUILD_CPPCACHE #define TEMPLATE_EXPORT template class CPPCACHE_EXPORT #else #define TEMPLATE_EXPORT extern template class CPPCACHE_EXPORT #endif #endif // Disable extern template warning on MSVC compiler #ifdef _MSC_VER #pragma warning(disable : 4231) #endif #define _GF_CACHEABLE_KEY_TYPE_DEF_(p, k, sz) \ extern const char tName_##k[]; \ extern const char tStr_##k[]; \ TEMPLATE_EXPORT \ CacheableKeyType<p, GeodeTypeIds::k, tName_##k, tStr_##k, sz>; \ typedef CacheableKeyType<p, GeodeTypeIds::k, tName_##k, tStr_##k, sz> _##k; \ class CPPCACHE_EXPORT k; \ typedef SharedPtr<k> k##Ptr; // use a class instead of typedef for bug #283 #define _GF_CACHEABLE_KEY_TYPE_(p, k, sz) \ class CPPCACHE_EXPORT k : public _##k { \ protected: \ inline k() : _##k() {} \ inline k(const p value) : _##k(value) {} \ \ public: \ /** Factory function registered with serialization registry. */ \ static Serializable* createDeserializable() { return new k(); } \ /** Factory function to create a new default instance. */ \ inline static k##Ptr create() { return k##Ptr(new k()); } \ /** Factory function to create an instance with the given value. */ \ inline static k##Ptr create(const p value) { \ return k##Ptr(new k(value)); \ } \ }; \ inline CacheableKeyPtr createKey(const p value) { return k::create(value); } \ inline CacheablePtr createValue(const p value) { return k::create(value); } #define _GF_CACHEABLE_ARRAY_TYPE_DEF_(p, c) \ TEMPLATE_EXPORT CacheableArrayType<p, GeodeTypeIds::c>; \ typedef CacheableArrayType<p, GeodeTypeIds::c> _##c; \ class CPPCACHE_EXPORT c; \ typedef SharedArrayPtr<p, GeodeTypeIds::c> c##Ptr; // use a class instead of typedef for bug #283 #define _GF_CACHEABLE_ARRAY_TYPE_(p, c) \ class CPPCACHE_EXPORT c : public _##c { \ protected: \ inline c() : _##c() {} \ inline c(int32_t length) : _##c(length) {} \ inline c(p* value, int32_t length) : _##c(value, length) {} \ inline c(const p* value, int32_t length, bool copy) \ : _##c(value, length, true) {} \ \ private: \ /* Private to disable copy constructor and assignment operator. */ \ c(const c& other); \ c& operator=(const c& other); \ \ public: \ /** Factory function registered with serialization registry. */ \ static Serializable* createDeserializable() { return new c(); } \ /** Factory function to create a new default instance. */ \ inline static c##Ptr create() { return c##Ptr(new c()); } \ /** Factory function to create a cacheable array of given size. */ \ inline static c##Ptr create(int32_t length) { \ return c##Ptr(new c(length)); \ } \ /** Create a cacheable array copying from the given array. */ \ inline static c##Ptr create(const p* value, int32_t length) { \ return (value != NULL ? c##Ptr(new c(value, length, true)) : NULLPTR); \ } \ /** \ \ * \ \ * \ \ \ * Create a cacheable array taking ownership of the given array \ \ * \ \ * \ \ \ * without creating a copy. \ \ * \ \ * \ \ \ * \ \ * \ \ * \ \ \ * Note that the application has to ensure that the given array is \ \ * \ \ * \ \ \ * not deleted (apart from this class) and is allocated on the heap \ \ * \ \ * \ \ \ * using the "new" operator. \ \ * \ \ * \ \ \ */ \ inline static c##Ptr createNoCopy(p* value, int32_t length) { \ return (value != NULL ? c##Ptr(new c(value, length)) : NULLPTR); \ } \ }; #define _GF_CACHEABLE_CONTAINER_TYPE_DEF_(p, c) \ TEMPLATE_EXPORT CacheableContainerType<p, GeodeTypeIds::c>; \ typedef CacheableContainerType<p, GeodeTypeIds::c> _##c; \ class CPPCACHE_EXPORT c; \ typedef SharedPtr<c> c##Ptr; // use a class instead of typedef for bug #283 #define _GF_CACHEABLE_CONTAINER_TYPE_(p, c) \ class CPPCACHE_EXPORT c : public _##c { \ protected: \ inline c() : _##c() {} \ inline c(const int32_t n) : _##c(n) {} \ \ public: \ /** Iterator for this type. */ \ typedef p::Iterator Iterator; \ /** Factory function registered with serialization registry. */ \ static Serializable* createDeserializable() { return new c(); } \ /** Factory function to create a default instance. */ \ inline static c##Ptr create() { return c##Ptr(new c()); } \ /** Factory function to create an instance with the given size. */ \ inline static c##Ptr create(const int32_t n) { return c##Ptr(new c(n)); } \ }; // Instantiations for the built-in CacheableKeys _GF_CACHEABLE_KEY_TYPE_DEF_(bool, CacheableBoolean, 3); /** * An immutable wrapper for booleans that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(bool, CacheableBoolean, 3); _GF_CACHEABLE_ARRAY_TYPE_DEF_(bool, BooleanArray); /** * An immutable wrapper for array of booleans that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(bool, BooleanArray); _GF_CACHEABLE_KEY_TYPE_DEF_(uint8_t, CacheableByte, 15); /** * An immutable wrapper for bytes that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(uint8_t, CacheableByte, 15); _GF_CACHEABLE_KEY_TYPE_DEF_(double, CacheableDouble, 63); /** * An immutable wrapper for doubles that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(double, CacheableDouble, 63); _GF_CACHEABLE_KEY_TYPE_DEF_(float, CacheableFloat, 63); /** * An immutable wrapper for floats that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(float, CacheableFloat, 63); _GF_CACHEABLE_KEY_TYPE_DEF_(int16_t, CacheableInt16, 15); /** * An immutable wrapper for 16-bit integers that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(int16_t, CacheableInt16, 15); _GF_CACHEABLE_KEY_TYPE_DEF_(int32_t, CacheableInt32, 15); /** * An immutable wrapper for 32-bit integers that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(int32_t, CacheableInt32, 15); _GF_CACHEABLE_KEY_TYPE_DEF_(int64_t, CacheableInt64, 31); /** * An immutable wrapper for 64-bit integers that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(int64_t, CacheableInt64, 31); _GF_CACHEABLE_KEY_TYPE_DEF_(wchar_t, CacheableWideChar, 3); /** * An immutable wrapper for wide-characters that can serve as * a distributable key object for caching. */ _GF_CACHEABLE_KEY_TYPE_(wchar_t, CacheableWideChar, 3); _GF_CACHEABLE_ARRAY_TYPE_DEF_(wchar_t, CharArray); /** * An immutable wrapper for array of wide-characters that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(wchar_t, CharArray); // Instantiations for array built-in Cacheables _GF_CACHEABLE_ARRAY_TYPE_DEF_(uint8_t, CacheableBytes); /** * An immutable wrapper for byte arrays that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(uint8_t, CacheableBytes); _GF_CACHEABLE_ARRAY_TYPE_DEF_(double, CacheableDoubleArray); /** * An immutable wrapper for array of doubles that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(double, CacheableDoubleArray); _GF_CACHEABLE_ARRAY_TYPE_DEF_(float, CacheableFloatArray); /** * An immutable wrapper for array of floats that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(float, CacheableFloatArray); _GF_CACHEABLE_ARRAY_TYPE_DEF_(int16_t, CacheableInt16Array); /** * An immutable wrapper for array of 16-bit integers that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(int16_t, CacheableInt16Array); _GF_CACHEABLE_ARRAY_TYPE_DEF_(int32_t, CacheableInt32Array); /** * An immutable wrapper for array of 32-bit integers that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(int32_t, CacheableInt32Array); _GF_CACHEABLE_ARRAY_TYPE_DEF_(int64_t, CacheableInt64Array); /** * An immutable wrapper for array of 64-bit integers that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(int64_t, CacheableInt64Array); _GF_CACHEABLE_ARRAY_TYPE_DEF_(CacheableStringPtr, CacheableStringArray); /** * An immutable wrapper for array of strings that can serve as * a distributable object for caching. */ _GF_CACHEABLE_ARRAY_TYPE_(CacheableStringPtr, CacheableStringArray); // Instantiations for container types (Vector/HashMap/HashSet) Cacheables _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableVector); /** * A mutable <code>Cacheable</code> vector wrapper that can serve as * a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableVector); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashMapOfCacheable, CacheableHashMap); /** * A mutable <code>CacheableKey</code> to <code>Serializable</code> * hash map that can serve as a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_HashMapOfCacheable, CacheableHashMap); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashSetOfCacheableKey, CacheableHashSet); /** * A mutable <code>CacheableKey</code> hash set wrapper that can serve as * a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_HashSetOfCacheableKey, CacheableHashSet); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableArrayList); /** * A mutable <code>Cacheable</code> array list wrapper that can serve as * a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableArrayList); // linketlist for JSON formattor issue _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableLinkedList); /** * A mutable <code>Cacheable</code> array list wrapper that can serve as * a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableLinkedList); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_VectorOfCacheable, CacheableStack); /** * A mutable <code>Cacheable</code> stack wrapper that can serve as * a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_VectorOfCacheable, CacheableStack); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashMapOfCacheable, CacheableHashTable); /** * A mutable <code>CacheableKey</code> to <code>Serializable</code> * hash map that can serve as a distributable object for caching. */ _GF_CACHEABLE_CONTAINER_TYPE_(_HashMapOfCacheable, CacheableHashTable); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashMapOfCacheable, CacheableIdentityHashMap); /** * A mutable <code>CacheableKey</code> to <code>Serializable</code> * hash map that can serve as a distributable object for caching. This is * provided for compability with java side, though is functionally identical * to <code>CacheableHashMap</code> i.e. does not provide the semantics of * java <code>IdentityHashMap</code>. */ _GF_CACHEABLE_CONTAINER_TYPE_(_HashMapOfCacheable, CacheableIdentityHashMap); _GF_CACHEABLE_CONTAINER_TYPE_DEF_(_HashSetOfCacheableKey, CacheableLinkedHashSet); /** * A mutable <code>CacheableKey</code> hash set wrapper that can serve as * a distributable object for caching. This is provided for compability * with java side, though is functionally identical to * <code>CacheableHashSet</code> i.e. does not provide the predictable * iteration semantics of java <code>LinkedHashSet</code>. */ _GF_CACHEABLE_CONTAINER_TYPE_(_HashSetOfCacheableKey, CacheableLinkedHashSet); } // namespace client } // namespace geode } // namespace apache #endif // GEODE_CACHEABLEBUILTINS_H_
39.16643
80
0.61237
Pivotal-Field-Engineering
61031ac5703be3b9d58c60c5fb3a0873902273d3
3,887
hpp
C++
Frame/SDK/Core/AFRWLock.hpp
zyb2013/ARK
d4f8b9cbeb4ec22c0b7a66396501e8dcc71a6aeb
[ "Apache-2.0" ]
null
null
null
Frame/SDK/Core/AFRWLock.hpp
zyb2013/ARK
d4f8b9cbeb4ec22c0b7a66396501e8dcc71a6aeb
[ "Apache-2.0" ]
null
null
null
Frame/SDK/Core/AFRWLock.hpp
zyb2013/ARK
d4f8b9cbeb4ec22c0b7a66396501e8dcc71a6aeb
[ "Apache-2.0" ]
1
2019-09-09T21:26:59.000Z
2019-09-09T21:26:59.000Z
/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #pragma once #include "SDK/Core/AFPlatform.hpp" #include "SDK/Core/AFNoncopyable.hpp" namespace ark { #if ARK_PLATFORM == PLATFORM_WIN class AFCReaderWriterLock : public AFNoncopyable { public: explicit AFCReaderWriterLock() { m_Readers = 0; InitializeCriticalSection(&m_Writer); InitializeCriticalSection(&m_ReaderCount); m_ClearReadersEvent = CreateEvent(NULL, TRUE, TRUE, NULL); } ~AFCReaderWriterLock() { WaitForSingleObject(m_ClearReadersEvent, INFINITE); CloseHandle(m_ClearReadersEvent); DeleteCriticalSection(&m_Writer); DeleteCriticalSection(&m_ReaderCount); } /*Read, reset events */ void ReaderLock(void) { EnterCriticalSection(&m_Writer); EnterCriticalSection(&m_ReaderCount); if (++m_Readers == 1) { ::ResetEvent(m_ClearReadersEvent); } LeaveCriticalSection(&m_ReaderCount); LeaveCriticalSection(&m_Writer); } void ReaderUnlock(void) { EnterCriticalSection(&m_ReaderCount); if (--m_Readers == 0) { ::SetEvent(m_ClearReadersEvent); } LeaveCriticalSection(&m_ReaderCount); } void WriterLock(void) { EnterCriticalSection(&m_Writer); WaitForSingleObject(m_ClearReadersEvent, INFINITE); } void WriterUnLock(void) { LeaveCriticalSection(&m_Writer); } private: CRITICAL_SECTION m_Writer; CRITICAL_SECTION m_ReaderCount; int m_Readers; HANDLE m_ClearReadersEvent; }; #else class AFCReaderWriterLock : public AFNoncopyable { public: AFCReaderWriterLock() { ::pthread_rwlock_init(&rwlock, NULL); } ~AFCReaderWriterLock() { ::pthread_rwlock_destroy(&rwlock); } void ReaderLock() { ::pthread_rwlock_rdlock(&rwlock); } void ReaderUnlock(void) { ::pthread_rwlock_unlock(&rwlock); } void WriterLock(void) { ::pthread_rwlock_wrlock(&rwlock); } void WriterUnLock(void) { ::pthread_rwlock_unlock(&rwlock); } private: pthread_rwlock_t rwlock; }; #endif class AFScopeRdLock : public AFNoncopyable { public: explicit AFScopeRdLock(AFCReaderWriterLock& lock) : rwlock(lock) { rwlock.ReaderLock(); } ~AFScopeRdLock() { rwlock.ReaderUnlock(); } private: AFCReaderWriterLock& rwlock; }; class AFScopeWrLock : public AFNoncopyable { public: explicit AFScopeWrLock(AFCReaderWriterLock& lock) : rwlock(lock) { rwlock.WriterLock(); } ~AFScopeWrLock() { rwlock.WriterUnLock(); } private: AFCReaderWriterLock& rwlock; }; }
23
74
0.581425
zyb2013
61035e572c4d4f3462a25672f11baa47330bc2cf
28,079
cpp
C++
Checkpoint.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
Checkpoint.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
Checkpoint.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 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. */ #define LOG_TAG "Checkpoint" #include "Checkpoint.h" #include "VoldUtil.h" #include "VolumeManager.h" #include <fstream> #include <list> #include <memory> #include <string> #include <thread> #include <vector> #include <android-base/file.h> #include <android-base/logging.h> #include <android-base/parseint.h> #include <android-base/properties.h> #include <android-base/unique_fd.h> #include <android/hardware/boot/1.0/IBootControl.h> #include <cutils/android_reboot.h> #include <fcntl.h> #include <fs_mgr.h> #include <linux/fs.h> #include <mntent.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/statvfs.h> #include <unistd.h> using android::base::GetBoolProperty; using android::base::GetUintProperty; using android::base::SetProperty; using android::binder::Status; using android::fs_mgr::Fstab; using android::fs_mgr::ReadDefaultFstab; using android::fs_mgr::ReadFstabFromFile; using android::hardware::hidl_string; using android::hardware::boot::V1_0::BoolResult; using android::hardware::boot::V1_0::CommandResult; using android::hardware::boot::V1_0::IBootControl; using android::hardware::boot::V1_0::Slot; namespace android { namespace vold { namespace { const std::string kMetadataCPFile = "/metadata/vold/checkpoint"; binder::Status error(const std::string& msg) { PLOG(ERROR) << msg; return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str())); } binder::Status error(int error, const std::string& msg) { LOG(ERROR) << msg; return binder::Status::fromServiceSpecificError(error, String8(msg.c_str())); } bool setBowState(std::string const& block_device, std::string const& state) { std::string bow_device = fs_mgr_find_bow_device(block_device); if (bow_device.empty()) return false; if (!android::base::WriteStringToFile(state, bow_device + "/bow/state")) { PLOG(ERROR) << "Failed to write to file " << bow_device + "/bow/state"; return false; } return true; } } // namespace Status cp_supportsCheckpoint(bool& result) { result = false; for (const auto& entry : fstab_default) { if (entry.fs_mgr_flags.checkpoint_blk || entry.fs_mgr_flags.checkpoint_fs) { result = true; return Status::ok(); } } return Status::ok(); } Status cp_supportsBlockCheckpoint(bool& result) { result = false; for (const auto& entry : fstab_default) { if (entry.fs_mgr_flags.checkpoint_blk) { result = true; return Status::ok(); } } return Status::ok(); } Status cp_supportsFileCheckpoint(bool& result) { result = false; for (const auto& entry : fstab_default) { if (entry.fs_mgr_flags.checkpoint_fs) { result = true; return Status::ok(); } } return Status::ok(); } Status cp_startCheckpoint(int retry) { bool result; if (!cp_supportsCheckpoint(result).isOk() || !result) return error(ENOTSUP, "Checkpoints not supported"); if (retry < -1) return error(EINVAL, "Retry count must be more than -1"); std::string content = std::to_string(retry + 1); if (retry == -1) { sp<IBootControl> module = IBootControl::getService(); if (module) { std::string suffix; auto cb = [&suffix](hidl_string s) { suffix = s; }; if (module->getSuffix(module->getCurrentSlot(), cb).isOk()) content += " " + suffix; } } if (!android::base::WriteStringToFile(content, kMetadataCPFile)) return error("Failed to write checkpoint file"); return Status::ok(); } namespace { volatile bool isCheckpointing = false; volatile bool needsCheckpointWasCalled = false; // Protects isCheckpointing, needsCheckpointWasCalled and code that makes decisions based on status // of isCheckpointing std::mutex isCheckpointingLock; } Status cp_commitChanges() { std::lock_guard<std::mutex> lock(isCheckpointingLock); if (!isCheckpointing) { return Status::ok(); } if (android::base::GetProperty("persist.vold.dont_commit_checkpoint", "0") == "1") { LOG(WARNING) << "NOT COMMITTING CHECKPOINT BECAUSE persist.vold.dont_commit_checkpoint IS 1"; return Status::ok(); } sp<IBootControl> module = IBootControl::getService(); if (module) { CommandResult cr; module->markBootSuccessful([&cr](CommandResult result) { cr = result; }); if (!cr.success) return error(EINVAL, "Error marking booted successfully: " + std::string(cr.errMsg)); LOG(INFO) << "Marked slot as booted successfully."; // Clears the warm reset flag for next reboot. if (!SetProperty("ota.warm_reset", "0")) { LOG(WARNING) << "Failed to reset the warm reset flag"; } } // Must take action for list of mounted checkpointed things here // To do this, we walk the list of mounted file systems. // But we also need to get the matching fstab entries to see // the original flags std::string err_str; Fstab mounts; if (!ReadFstabFromFile("/proc/mounts", &mounts)) { return error(EINVAL, "Failed to get /proc/mounts"); } // Walk mounted file systems for (const auto& mount_rec : mounts) { const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point); if (!fstab_rec) continue; if (fstab_rec->fs_mgr_flags.checkpoint_fs) { if (fstab_rec->fs_type == "f2fs") { std::string options = mount_rec.fs_options + ",checkpoint=enable"; if (mount(mount_rec.blk_device.c_str(), mount_rec.mount_point.c_str(), "none", MS_REMOUNT | fstab_rec->flags, options.c_str())) { return error(EINVAL, "Failed to remount"); } } } else if (fstab_rec->fs_mgr_flags.checkpoint_blk) { if (!setBowState(mount_rec.blk_device, "2")) return error(EINVAL, "Failed to set bow state"); } } SetProperty("vold.checkpoint_committed", "1"); LOG(INFO) << "Checkpoint has been committed."; isCheckpointing = false; if (!android::base::RemoveFileIfExists(kMetadataCPFile, &err_str)) return error(err_str.c_str()); return Status::ok(); } namespace { void abort_metadata_file() { std::string oldContent, newContent; int retry = 0; struct stat st; int result = stat(kMetadataCPFile.c_str(), &st); // If the file doesn't exist, we aren't managing a checkpoint retry counter if (result != 0) return; if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) { PLOG(ERROR) << "Failed to read checkpoint file"; return; } std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" ")); if (!android::base::ParseInt(retryContent, &retry)) { PLOG(ERROR) << "Could not parse retry count"; return; } if (retry > 0) { newContent = "0"; if (!android::base::WriteStringToFile(newContent, kMetadataCPFile)) PLOG(ERROR) << "Could not write checkpoint file"; } } } // namespace void cp_abortChanges(const std::string& message, bool retry) { if (!cp_needsCheckpoint()) return; if (!retry) abort_metadata_file(); android_reboot(ANDROID_RB_RESTART2, 0, message.c_str()); } bool cp_needsRollback() { std::string content; bool ret; ret = android::base::ReadFileToString(kMetadataCPFile, &content); if (ret) { if (content == "0") return true; if (content.substr(0, 3) == "-1 ") { std::string oldSuffix = content.substr(3); sp<IBootControl> module = IBootControl::getService(); std::string newSuffix; if (module) { auto cb = [&newSuffix](hidl_string s) { newSuffix = s; }; module->getSuffix(module->getCurrentSlot(), cb); if (oldSuffix == newSuffix) return true; } } } return false; } bool cp_needsCheckpoint() { std::lock_guard<std::mutex> lock(isCheckpointingLock); // Make sure we only return true during boot. See b/138952436 for discussion if (needsCheckpointWasCalled) return isCheckpointing; needsCheckpointWasCalled = true; bool ret; std::string content; sp<IBootControl> module = IBootControl::getService(); if (isCheckpointing) return isCheckpointing; if (module && module->isSlotMarkedSuccessful(module->getCurrentSlot()) == BoolResult::FALSE) { isCheckpointing = true; return true; } ret = android::base::ReadFileToString(kMetadataCPFile, &content); if (ret) { ret = content != "0"; isCheckpointing = ret; return ret; } return false; } bool cp_isCheckpointing() { return isCheckpointing; } namespace { const std::string kSleepTimeProp = "ro.sys.cp_msleeptime"; const uint32_t msleeptime_default = 1000; // 1 s const uint32_t max_msleeptime = 3600000; // 1 h const std::string kMinFreeBytesProp = "ro.sys.cp_min_free_bytes"; const uint64_t min_free_bytes_default = 100 * (1 << 20); // 100 MiB const std::string kCommitOnFullProp = "ro.sys.cp_commit_on_full"; const bool commit_on_full_default = true; static void cp_healthDaemon(std::string mnt_pnt, std::string blk_device, bool is_fs_cp) { struct statvfs data; uint32_t msleeptime = GetUintProperty(kSleepTimeProp, msleeptime_default, max_msleeptime); uint64_t min_free_bytes = GetUintProperty(kMinFreeBytesProp, min_free_bytes_default, (uint64_t)-1); bool commit_on_full = GetBoolProperty(kCommitOnFullProp, commit_on_full_default); struct timespec req; req.tv_sec = msleeptime / 1000; msleeptime %= 1000; req.tv_nsec = msleeptime * 1000000; while (isCheckpointing) { uint64_t free_bytes = 0; if (is_fs_cp) { statvfs(mnt_pnt.c_str(), &data); free_bytes = ((uint64_t) data.f_bavail) * data.f_frsize; } else { std::string bow_device = fs_mgr_find_bow_device(blk_device); if (!bow_device.empty()) { std::string content; if (android::base::ReadFileToString(bow_device + "/bow/free", &content)) { free_bytes = std::strtoull(content.c_str(), NULL, 10); } } } if (free_bytes < min_free_bytes) { if (commit_on_full) { LOG(INFO) << "Low space for checkpointing. Commiting changes"; cp_commitChanges(); break; } else { LOG(INFO) << "Low space for checkpointing. Rebooting"; cp_abortChanges("checkpoint,low_space", false); break; } } nanosleep(&req, NULL); } } } // namespace Status cp_prepareCheckpoint() { // Log to notify CTS - see b/137924328 for context LOG(INFO) << "cp_prepareCheckpoint called"; std::lock_guard<std::mutex> lock(isCheckpointingLock); if (!isCheckpointing) { return Status::ok(); } Fstab mounts; if (!ReadFstabFromFile("/proc/mounts", &mounts)) { return error(EINVAL, "Failed to get /proc/mounts"); } for (const auto& mount_rec : mounts) { const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point); if (!fstab_rec) continue; if (fstab_rec->fs_mgr_flags.checkpoint_blk) { android::base::unique_fd fd( TEMP_FAILURE_RETRY(open(mount_rec.mount_point.c_str(), O_RDONLY | O_CLOEXEC))); if (fd == -1) { PLOG(ERROR) << "Failed to open mount point" << mount_rec.mount_point; continue; } struct fstrim_range range = {}; range.len = ULLONG_MAX; nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME); if (ioctl(fd, FITRIM, &range)) { PLOG(ERROR) << "Failed to trim " << mount_rec.mount_point; continue; } nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start; LOG(INFO) << "Trimmed " << range.len << " bytes on " << mount_rec.mount_point << " in " << nanoseconds_to_milliseconds(time) << "ms for checkpoint"; setBowState(mount_rec.blk_device, "1"); } if (fstab_rec->fs_mgr_flags.checkpoint_blk || fstab_rec->fs_mgr_flags.checkpoint_fs) { std::thread(cp_healthDaemon, std::string(mount_rec.mount_point), std::string(mount_rec.blk_device), fstab_rec->fs_mgr_flags.checkpoint_fs == 1) .detach(); } } return Status::ok(); } namespace { const int kSectorSize = 512; typedef uint64_t sector_t; struct log_entry { sector_t source; // in sectors of size kSectorSize sector_t dest; // in sectors of size kSectorSize uint32_t size; // in bytes uint32_t checksum; } __attribute__((packed)); struct log_sector_v1_0 { uint32_t magic; uint16_t header_version; uint16_t header_size; uint32_t block_size; uint32_t count; uint32_t sequence; uint64_t sector0; } __attribute__((packed)); // MAGIC is BOW in ascii const int kMagic = 0x00574f42; // Partially restored MAGIC is WOB in ascii const int kPartialRestoreMagic = 0x00424f57; void crc32(const void* data, size_t n_bytes, uint32_t* crc) { static uint32_t table[0x100] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D}; for (size_t i = 0; i < n_bytes; ++i) { *crc ^= ((uint8_t*)data)[i]; *crc = table[(uint8_t)*crc] ^ *crc >> 8; } } // A map of relocations. // The map must be initialized so that relocations[0] = 0 // During restore, we replay the log records in reverse, copying from dest to // source // To validate, we must be able to read the 'dest' sectors as though they had // been copied but without actually copying. This map represents how the sectors // would have been moved. To read a sector s, find the index <= s and read // relocations[index] + s - index typedef std::map<sector_t, sector_t> Relocations; void relocate(Relocations& relocations, sector_t dest, sector_t source, int count) { // Find first one we're equal to or greater than auto s = --relocations.upper_bound(source); // Take slice Relocations slice; slice[dest] = source - s->first + s->second; ++s; // Add rest of elements for (; s != relocations.end() && s->first < source + count; ++s) slice[dest - source + s->first] = s->second; // Split range at end of dest auto dest_end = --relocations.upper_bound(dest + count); relocations[dest + count] = dest + count - dest_end->first + dest_end->second; // Remove all elements in [dest, dest + count) relocations.erase(relocations.lower_bound(dest), relocations.lower_bound(dest + count)); // Add new elements relocations.insert(slice.begin(), slice.end()); } // A map of sectors that have been written to. // The final entry must always be False. // When we restart the restore after an interruption, we must take care that // when we copy from dest to source, that the block we copy to was not // previously copied from. // i e. A->B C->A; If we replay this sequence, we end up copying C->B // We must save our partial result whenever we finish a page, or when we copy // to a location that was copied from earlier (our source is an earlier dest) typedef std::map<sector_t, bool> Used_Sectors; bool checkCollision(Used_Sectors& used_sectors, sector_t start, sector_t end) { auto second_overlap = used_sectors.upper_bound(start); auto first_overlap = --second_overlap; if (first_overlap->second) { return true; } else if (second_overlap != used_sectors.end() && second_overlap->first < end) { return true; } return false; } void markUsed(Used_Sectors& used_sectors, sector_t start, sector_t end) { auto start_pos = used_sectors.insert_or_assign(start, true).first; auto end_pos = used_sectors.insert_or_assign(end, false).first; if (start_pos == used_sectors.begin() || !std::prev(start_pos)->second) { start_pos++; } if (std::next(end_pos) != used_sectors.end() && !std::next(end_pos)->second) { end_pos++; } if (start_pos->first < end_pos->first) { used_sectors.erase(start_pos, end_pos); } } // Restores the given log_entry's data from dest -> source // If that entry is a log sector, set the magic to kPartialRestoreMagic and flush. void restoreSector(int device_fd, Used_Sectors& used_sectors, std::vector<char>& ls_buffer, log_entry* le, std::vector<char>& buffer) { log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]); uint32_t index = le - ((log_entry*)&ls_buffer[ls.header_size]); int count = (le->size - 1) / kSectorSize + 1; if (checkCollision(used_sectors, le->source, le->source + count)) { fsync(device_fd); lseek64(device_fd, 0, SEEK_SET); ls.count = index + 1; ls.magic = kPartialRestoreMagic; write(device_fd, &ls_buffer[0], ls.block_size); fsync(device_fd); used_sectors.clear(); used_sectors[0] = false; } markUsed(used_sectors, le->dest, le->dest + count); if (index == 0 && ls.sequence != 0) { log_sector_v1_0* next = reinterpret_cast<log_sector_v1_0*>(&buffer[0]); if (next->magic == kMagic) { next->magic = kPartialRestoreMagic; } } lseek64(device_fd, le->source * kSectorSize, SEEK_SET); write(device_fd, &buffer[0], le->size); if (index == 0) { fsync(device_fd); } } // Read from the device // If we are validating, the read occurs as though the relocations had happened std::vector<char> relocatedRead(int device_fd, Relocations const& relocations, bool validating, sector_t sector, uint32_t size, uint32_t block_size) { if (!validating) { std::vector<char> buffer(size); lseek64(device_fd, sector * kSectorSize, SEEK_SET); read(device_fd, &buffer[0], size); return buffer; } std::vector<char> buffer(size); for (uint32_t i = 0; i < size; i += block_size, sector += block_size / kSectorSize) { auto relocation = --relocations.upper_bound(sector); lseek64(device_fd, (sector + relocation->second - relocation->first) * kSectorSize, SEEK_SET); read(device_fd, &buffer[i], block_size); } return buffer; } } // namespace Status cp_restoreCheckpoint(const std::string& blockDevice, int restore_limit) { bool validating = true; std::string action = "Validating"; int restore_count = 0; for (;;) { Relocations relocations; relocations[0] = 0; Status status = Status::ok(); LOG(INFO) << action << " checkpoint on " << blockDevice; base::unique_fd device_fd(open(blockDevice.c_str(), O_RDWR | O_CLOEXEC)); if (device_fd < 0) return error("Cannot open " + blockDevice); log_sector_v1_0 original_ls; read(device_fd, reinterpret_cast<char*>(&original_ls), sizeof(original_ls)); if (original_ls.magic == kPartialRestoreMagic) { validating = false; action = "Restoring"; } else if (original_ls.magic != kMagic) { return error(EINVAL, "No magic"); } LOG(INFO) << action << " " << original_ls.sequence << " log sectors"; for (int sequence = original_ls.sequence; sequence >= 0 && status.isOk(); sequence--) { auto ls_buffer = relocatedRead(device_fd, relocations, validating, 0, original_ls.block_size, original_ls.block_size); log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]); Used_Sectors used_sectors; used_sectors[0] = false; if (ls.magic != kMagic && (ls.magic != kPartialRestoreMagic || validating)) { status = error(EINVAL, "No magic"); break; } if (ls.block_size != original_ls.block_size) { status = error(EINVAL, "Block size mismatch"); break; } if ((int)ls.sequence != sequence) { status = error(EINVAL, "Expecting log sector " + std::to_string(sequence) + " but got " + std::to_string(ls.sequence)); break; } LOG(INFO) << action << " from log sector " << ls.sequence; for (log_entry* le = reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]) + ls.count - 1; le >= reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]); --le) { // This is very noisy - limit to DEBUG only LOG(VERBOSE) << action << " " << le->size << " bytes from sector " << le->dest << " to " << le->source << " with checksum " << std::hex << le->checksum; auto buffer = relocatedRead(device_fd, relocations, validating, le->dest, le->size, ls.block_size); uint32_t checksum = le->source / (ls.block_size / kSectorSize); for (size_t i = 0; i < le->size; i += ls.block_size) { crc32(&buffer[i], ls.block_size, &checksum); } if (le->checksum && checksum != le->checksum) { status = error(EINVAL, "Checksums don't match"); break; } if (validating) { relocate(relocations, le->source, le->dest, (le->size - 1) / kSectorSize + 1); } else { restoreSector(device_fd, used_sectors, ls_buffer, le, buffer); restore_count++; if (restore_limit && restore_count >= restore_limit) { status = error(EAGAIN, "Hit the test limit"); break; } } } } if (!status.isOk()) { if (!validating) { LOG(ERROR) << "Checkpoint restore failed even though checkpoint validation passed"; return status; } LOG(WARNING) << "Checkpoint validation failed - attempting to roll forward"; auto buffer = relocatedRead(device_fd, relocations, false, original_ls.sector0, original_ls.block_size, original_ls.block_size); lseek64(device_fd, 0, SEEK_SET); write(device_fd, &buffer[0], original_ls.block_size); return Status::ok(); } if (!validating) break; validating = false; action = "Restoring"; } return Status::ok(); } Status cp_markBootAttempt() { std::string oldContent, newContent; int retry = 0; struct stat st; int result = stat(kMetadataCPFile.c_str(), &st); // If the file doesn't exist, we aren't managing a checkpoint retry counter if (result != 0) return Status::ok(); if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) return error("Failed to read checkpoint file"); std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" ")); if (!android::base::ParseInt(retryContent, &retry)) return error(EINVAL, "Could not parse retry count"); if (retry > 0) { retry--; newContent = std::to_string(retry); if (!android::base::WriteStringToFile(newContent, kMetadataCPFile)) return error("Could not write checkpoint file"); } return Status::ok(); } void cp_resetCheckpoint() { std::lock_guard<std::mutex> lock(isCheckpointingLock); needsCheckpointWasCalled = false; } } // namespace vold } // namespace android
37.488652
99
0.635671
lighthouse-os
610411775e48998fe94d2266f16faa552b075df6
220
cpp
C++
NonOpt/tests/testPoint.cpp
frankecurtis/NonOpt
f81ff1c818dcde382cf6045a671bf8bc1d3a3467
[ "MIT" ]
4
2021-06-27T18:13:59.000Z
2022-01-25T00:36:56.000Z
NonOpt/tests/testPoint.cpp
frankecurtis/NonOpt
f81ff1c818dcde382cf6045a671bf8bc1d3a3467
[ "MIT" ]
null
null
null
NonOpt/tests/testPoint.cpp
frankecurtis/NonOpt
f81ff1c818dcde382cf6045a671bf8bc1d3a3467
[ "MIT" ]
1
2021-06-27T18:14:02.000Z
2021-06-27T18:14:02.000Z
// Copyright (C) 2022 Frank E. Curtis // // This code is published under the MIT License. // // Author(s) : Frank E. Curtis #include "testPoint.hpp" // Main function int main() { return testPointImplementation(1); }
15.714286
48
0.681818
frankecurtis
61049f69be37617afa2968b10a34abecbfb62b3a
1,500
cpp
C++
FantasyBrawl_Project/Motor2D/UI_Clock.cpp
project2-tmp/Base_Code
72cd8b375a912c2760e62f273c74de7c0c6d939e
[ "MIT" ]
6
2019-04-14T18:17:35.000Z
2021-07-29T02:22:24.000Z
FantasyBrawl_Project/Motor2D/UI_Clock.cpp
project2-tmp/Base_Code
72cd8b375a912c2760e62f273c74de7c0c6d939e
[ "MIT" ]
7
2019-03-21T22:00:20.000Z
2019-06-12T00:37:31.000Z
FantasyBrawl_Project/Motor2D/UI_Clock.cpp
CheckTheDog/Fantasy-Brawl
72cd8b375a912c2760e62f273c74de7c0c6d939e
[ "MIT" ]
2
2019-11-18T09:13:31.000Z
2021-02-03T21:02:52.000Z
#include "UI_Clock.h" #include "j1App.h" #include "j1Render.h" #include "j1Gui.h" #include "Brofiler\Brofiler.h" void Clock::setStartValue(int new_start_value) { start_value = new_start_value; } void Clock::setAlarm(int alarm) { alarms.push_back(alarm); } void Clock::restartChrono() { switch (this->type) { case TIMER: time = start_value; break; case STOPWATCH: time = 0; break; } } void Clock::BlitElement() { BROFILER_CATEGORY("Clock Blit", Profiler::Color::PowderBlue); time_elapsed = counter.ReadSec(); switch (type) { case STOPWATCH: if (time != time_elapsed) { time = time_elapsed; if (callback != nullptr) //If has callback send event { for (int i = 0; i < alarms.size(); i++) { if (time == (int)alarms[i]) callback->OnUIEvent(this, STOPWATCH_ALARM); } } std::string secs = std::to_string(time); //p2SString secs("%04d", time); if (last_secs != secs) text->setText(secs); section = text->section; last_secs = std::to_string(time); } break; case TIMER: if (start_value - time_elapsed != time && time != 0) { time = start_value - time_elapsed; if (time == 0 && callback != nullptr) //If has callback send event callback->OnUIEvent(this, TIMER_ZERO); //p2SString secs("%d", time); std::string secs = std::to_string(time); if (last_secs != secs) text->setText(secs); section = text->section; last_secs = std::to_string(time); } break; } text->BlitElement(); }
18.072289
69
0.637333
project2-tmp
610b46c5733d2a5a9c820a4c7717ed352c7bb78f
899
cpp
C++
Box3D/src/TextureBuffer.cpp
Campeanu/Box3D
2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec
[ "MIT" ]
1
2020-07-20T15:55:43.000Z
2020-07-20T15:55:43.000Z
Box3D/src/TextureBuffer.cpp
Campeanu/Box3D
2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec
[ "MIT" ]
null
null
null
Box3D/src/TextureBuffer.cpp
Campeanu/Box3D
2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec
[ "MIT" ]
null
null
null
#include <Box3D/Renderer/TextureBuffer.hpp> namespace box3d { TextureBuffer::TextureBuffer() { glGenTextures(1, &this->m_rendererID); glBindTexture(GL_TEXTURE_2D, this->m_rendererID); } TextureBuffer::~TextureBuffer() { } void TextureBuffer::createTexImage2D(box3d::Application& app) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, app.GetWindow().GetWidth(), app.GetWindow().GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); } void TextureBuffer::setTextureAtributes() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void TextureBuffer::bind() const { glBindTexture(GL_TEXTURE_2D, this->m_rendererID); } void TextureBuffer::unbind() const { glBindTexture(GL_TEXTURE_2D, 0); } }
23.051282
139
0.668521
Campeanu
610db94c6406ed230e555896ad6e1363f96da9b6
393
hpp
C++
deps/boost/include/boost/graph/detail/empty_header.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
80
2021-09-07T12:44:32.000Z
2022-03-29T01:22:19.000Z
deps/boost/include/boost/graph/detail/empty_header.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
2
2021-12-23T02:49:42.000Z
2022-02-15T05:28:24.000Z
deps/boost/include/boost/graph/detail/empty_header.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
25
2021-09-14T06:24:25.000Z
2022-03-20T06:55:07.000Z
#ifndef BOOST_GRAPH_DETAIL_EMPTY_HEADER_HPP_INCLUDED #define BOOST_GRAPH_DETAIL_EMPTY_HEADER_HPP_INCLUDED // Copyright 2018 Peter Dimov // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0 (See accompanying file // LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) #endif // #ifndef BOOST_GRAPH_DETAIL_EMPTY_HEADER_HPP_INCLUDED
35.727273
63
0.804071
kindlychung
610f458c09000c569e26b8984cdb126628f11bb9
4,459
hpp
C++
src/3rd party/boost/boost/python/object/inheritance.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/python/object/inheritance.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/python/object/inheritance.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #ifndef INHERITANCE_DWA200216_HPP # define INHERITANCE_DWA200216_HPP # include <boost/python/type_id.hpp> # include <boost/shared_ptr.hpp> # include <boost/mpl/if.hpp> # include <boost/type_traits/object_traits.hpp> # include <boost/type_traits/is_polymorphic.hpp> # include <boost/detail/workaround.hpp> namespace boost { namespace python { namespace objects { typedef type_info class_id; using python::type_id; // Types used to get address and id of most derived type typedef std::pair<void*,class_id> dynamic_id_t; typedef dynamic_id_t (*dynamic_id_function)(void*); BOOST_PYTHON_DECL void register_dynamic_id_aux( class_id static_id, dynamic_id_function get_dynamic_id); BOOST_PYTHON_DECL void add_cast( class_id src_t, class_id dst_t, void* (*cast)(void*), bool polymorphic); BOOST_PYTHON_DECL void* find_static_type(void* p, class_id src, class_id dst); BOOST_PYTHON_DECL void* find_dynamic_type(void* p, class_id src, class_id dst); // // a generator with an execute() function which, given a source type // and a pointer to an object of that type, returns its most-derived // /reachable/ type identifier and object pointer. // // first, the case where T has virtual functions template <class T> struct polymorphic_id_generator { static dynamic_id_t execute(void* p_) { T* p = static_cast<T*>(p_); return std::make_pair(dynamic_cast<void*>(p), class_id(typeid(*p))); } }; // now, the non-polymorphic case. template <class T> struct non_polymorphic_id_generator { static dynamic_id_t execute(void* p_) { return std::make_pair(p_, python::type_id<T>()); } }; // Now the generalized selector template <class T> struct dynamic_id_generator { typedef typename mpl::if_c< is_polymorphic<T>::value , polymorphic_id_generator<T> , non_polymorphic_id_generator<T> >::type type; }; // Register the dynamic id function for T with the type-conversion // system. template <class T> void register_dynamic_id(T* = 0) { typedef typename dynamic_id_generator<T>::type generator; register_dynamic_id_aux( python::type_id<T>(), &generator::execute); } // // a generator with an execute() function which, given a void* // pointing to an object of type Source will attempt to convert it to // an object of type Target. // template <class Source, class Target> struct dynamic_cast_generator { static void* execute(void* source) { return dynamic_cast<Target*>( static_cast<Source*>(source)); } }; template <class Source, class Target> struct implicit_cast_generator { static void* execute(void* source) { Target* result = static_cast<Source*>(source); return result; } }; template <class Source, class Target> struct cast_generator { // It's OK to return false, since we can always cast up with // dynamic_cast<> if neccessary. # if BOOST_WORKAROUND(__MWERKS__, <= 0x2407) BOOST_STATIC_CONSTANT(bool, is_upcast = false); # else BOOST_STATIC_CONSTANT( bool, is_upcast = ( is_base_and_derived<Target,Source>::value )); # endif typedef typename mpl::if_c< is_upcast # if BOOST_WORKAROUND(__MWERKS__, <= 0x2407) // grab a few more implicit_cast cases for CodeWarrior || !is_polymorphic<Source>::value || !is_polymorphic<Target>::value # endif , implicit_cast_generator<Source,Target> , dynamic_cast_generator<Source,Target> >::type type; }; template <class Source, class Target> inline void register_conversion( // We need this parameter because CWPro7 can't determine // which is the base reliably. bool is_downcast = !cast_generator<Source,Target>::is_upcast // These parameters shouldn't be used, they're an MSVC bug workaround , Source* = 0, Target* = 0) { typedef typename cast_generator<Source,Target>::type generator; add_cast(python::type_id<Source>() , python::type_id<Target>() , &generator::execute , is_downcast); } }}} // namespace boost::python::object #endif // INHERITANCE_DWA200216_HPP
28.767742
79
0.705539
OLR-xray
611314e88ba3e5f3b90ccc91ccf45e4fadfa70d0
9,694
cpp
C++
src/MainBackTracking.cpp
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
1
2020-10-25T07:14:48.000Z
2020-10-25T07:14:48.000Z
src/MainBackTracking.cpp
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
null
null
null
src/MainBackTracking.cpp
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
2
2020-10-02T12:24:38.000Z
2020-10-25T07:00:24.000Z
#include <fstream> #include <sstream> #include <filesystem> #include <string> #include <algorithm> #include <vector> #include "backTracking/TOP_Backtracking.hpp" #include "greedy/GreedyPaths.hpp" using namespace std; namespace fs = std::filesystem; /** * Struct that represent Chao's results */ struct chaoResults { string file; double chaoOptimum; }; /** * MainBackTracking.cpp is a main that takes all the instances and solve them with the backtracking algorithm. Bacause * of the long time that takes the backtracking, it is possible to set a maxTime limit that it takes to resolve * each instance (default value 3 minutes). The main perform a metaheuristic backtracking because it use the greedy * algorithm (with its parameter maxDeviation) plus some other solutions built to solve the TOP problem. * the solution are compared with Chao's ones to evaluate the performance and the resoluts of the backtracking algorithm. * All the outputs are saved in different files to sum up the information and the outputs from which it is obtained * the best optimum. * * Input file: * paramTimeBt.txt : file in which are contained tthe max time permitted to execute the backtracking algorithm * on each instance, expressed in second. * Mandatory info: time for each instance. If not provided, default at 3 minutes. * The file is located in "parametes_in" directory. * * chaoResults.txt : file in which are contained Chao's results, used to compare greedy scores whith Chao's ones. * The file is located in "parametes_in" directory. * * "instances" files : files that contain the instances to solve. * The files are located in "instances" directory. * * Output files: * SolBacktracking.csv : file in which it is saved for each instance the algorithm results and the comparison whith chao's one. * The file is located in "solutions" directory. * * "outputs/backtracking/[#]" files : for all the instances, it is saved a file which contain the input and the output in standard * form. Some useful information as the path, the hop and the score obtained are provided. * The file are located in "outputs/backtracking/[#]" directory. * * "outputs/routeHops/backtarcking/[#]" files : for all the instances it is saved the solution obtained if hops form to read and use * it in the resolution of other algortims (i.e. Local Search). * The files are located in "outputs/routeHops/backtracking/[#]" directory. * * Usage: * ./MainBackT.exe [version of algorithm] * - version : * 1 : if with default parameters * 2 : if with parameters readed by Greedy output files * * @param argc number of items in the command line * @param argv items in the command line * @return resolve all the instances and print outputs and parameters in files */ int main(int argc, char* argv[]) { double maxTime = 3.0 * 60.0; // Default Time limit: 3 minutes int errors = 0, cnt_istances = 0; bool timeDefault = false; vector<chaoResults> chaoRes; string line; if (argc < 1) { cerr << argc << " ERROR: insert Backtracking algorithm's version [#1 or #2]" << endl; return 1; } //Open the file conteining the max time for execute the program for each instance ifstream paramTime("./paramIn/paramTimeBt.txt"); if (!paramTime) { cerr << " ERROR: Unable to open MaxTime file" << endl; timeDefault = true; } if(!timeDefault) { while(getline(paramTime, line)) { std::istringstream iss(line); //Split the input string std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (results[0] == "timeMax") { maxTime = stod(results[1]); } else { continue; } } paramTime.close(); } cout << "LOG: timeMax limit set to " << maxTime << "s" << endl; //Open and read the file of Chao's results ifstream optStream("./paramIn/chaoResults.txt"); if (!optStream) { throw runtime_error(" ERROR: Unable to open Chao's file"); } // Read all the lines into chao's file while(getline(optStream, line)) { std::istringstream iss(line); //Split the input string std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); chaoRes.push_back({.file = results[0], .chaoOptimum = stod(results[1])}); //Populate the vector of chao's results } optStream.close(); //Open and write the file of results for each instance fs::create_directories("solutions"); string titleFile = "solutions/SolBacktracking#"; titleFile.push_back(*argv[1]); ofstream solutionsStream(titleFile + ".csv"); if(!solutionsStream) { throw runtime_error(" ERROR: Unable to open Solution file"); } if(*argv[1] == '2') { solutionsStream << "# TimeMax limit set to " << maxTime << "s [Custom parameters] " << endl; } else { solutionsStream << "# TimeMax limit set to " << maxTime << "s [Default parameters] " << endl; } for (const auto &file : fs::directory_iterator("./instances")) { //For each instance TOP_Input in; string line; // Default weight parameters double wProfit = 1.1; double wTime = 0.7; double maxDeviation = 1.5; // Max deviation admitted to the path double wNonCost = 0.0; if (file.path().extension() != ".txt") continue; cerr << "Processing: " << file.path().filename() << endl; { ifstream is(file.path()); if (!is) { ++errors; cerr << " ERROR: Unable to open Instance file" << endl; continue; } is >> in; in.name = file.path().filename().replace_extension("").string(); } if(*argv[1] == '2') { // Second version without greedy parameters, otherwise with default parameters //Open the file conteining the params // If found param, set it, otherwise use default value ifstream paramStream(GetGreedyBestParamsPath(in.name)); if (!paramStream) { throw runtime_error("ERROR: Cannot find Greedy parameter file: run Greedy algorithm or use default parameters"); } while(getline(paramStream, line)) { std::istringstream iss(line); //Split the input string std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (results[0] == "Profit") { // Skip first line continue; } if (results[2] == "null") { // Default parameters break; } if(results[1] == "wProfit:") { wProfit = stod(results[2]); } else if(results[1] == "wTime:") { wTime = stod(results[2]); } else if(results[1] == "maxDeviation:") { maxDeviation = stod(results[2]); } else if(results[1] == "wNonCost:") { wNonCost = stod(results[2]); } } paramStream.close(); } cerr << "LOG: param <" << wProfit << "; " << wTime << "; " << maxDeviation << "; " << wNonCost << ">" << endl; TOP_Walker tw(in, wProfit, wTime, maxDeviation, wNonCost, 0); TOP_Checker ck; Backtrack(tw, ck, maxTime); { // Print the output string titleDir = "outputs/backtracking/#"; titleDir.push_back(*argv[1]); fs::create_directories(titleDir); std::ofstream os(titleDir / file.path().filename().replace_extension(".out")); if (!os) { ++errors; std::cerr << " ERROR: Unable to open output file" << std::endl; continue; } if (ck.GetBestCost() == 0) { os << in; os << "h 0"; } else { os << in << ck.GetBest(); } } { string titleDir = "outputs/routeHops/backtracking/#"; titleDir.push_back(*argv[1]); fs::create_directories(titleDir); std::ofstream os(titleDir / file.path().filename().replace_extension(".out")); if (!os) { ++errors; std::cerr << " ERROR: Unable to open output file" << std::endl; continue; } if (ck.GetBestCost() == 0) { os << in; os << "h 0"; } else { os << ck.GetBest(); } } // Print a ".csv" file with all the scores if(chaoRes[cnt_istances].file == file.path().filename()) { // Compare with Chao if(chaoRes[cnt_istances].chaoOptimum == -ck.GetBestCost()) { solutionsStream << file.path().filename() << "," << chaoRes[cnt_istances].chaoOptimum << "," << -ck.GetBestCost() << "," << 1.0 << endl; ++cnt_istances; continue; } solutionsStream << file.path().filename() << "," << chaoRes[cnt_istances].chaoOptimum << "," << -ck.GetBestCost() << "," << -ck.GetBestCost() / chaoRes[cnt_istances].chaoOptimum << endl; ++cnt_istances; } else { // New map found solutionsStream << file.path().filename() << "," << -ck.GetBestCost() << "," << "(new map)" << endl; } } solutionsStream.close(); return 0; }
37.573643
136
0.583454
DarioDaF
61141b5b467eae9d8a3d1dac9687fe78e6c2a95b
3,214
cpp
C++
isaac_variant_caller/src/lib/blt_util/istream_line_splitter.cpp
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
21
2015-01-09T01:11:28.000Z
2019-09-04T03:48:21.000Z
isaac_variant_caller/src/lib/blt_util/istream_line_splitter.cpp
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
4
2015-07-23T09:38:39.000Z
2018-02-01T05:37:26.000Z
isaac_variant_caller/src/lib/blt_util/istream_line_splitter.cpp
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
13
2015-01-29T16:41:26.000Z
2021-06-25T02:42:32.000Z
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Copyright (c) 2009-2013 Illumina, Inc. // // This software is provided under the terms and conditions of the // Illumina Open Source Software License 1. // // You should have received a copy of the Illumina Open Source // Software License 1 along with this program. If not, see // <https://github.com/sequencing/licenses/> // /// \file /// /// an efficient (and slightly unsafe) class for basic tab-delimited files, etc... /// /// \author Chris Saunders /// #include "blt_util/blt_exception.hh" #include "blt_util/istream_line_splitter.hh" #include <cassert> #include <cstring> #include <iostream> #include <sstream> void istream_line_splitter:: write_line(std::ostream& os) const { for (unsigned i(0); i<_n_word; ++i) { if (i) os << _sep; os << word[i]; } os << "\n"; } void istream_line_splitter:: dump(std::ostream& os) const { os << "\tline_no: " << _line_no << "\n"; os << "\tline: "; write_line(os); } void istream_line_splitter:: increase_buffer_size() { assert(_buf_size>1); const unsigned old_buf_size(_buf_size); const char* old_buf(_buf); _buf_size *= 2; _buf=new char[_buf_size]; memcpy(_buf,old_buf,(old_buf_size-1)*sizeof(char)); delete [] old_buf; } static bool check_istream(std::istream& is, unsigned& line_no) { if (is) { line_no++; // regular successful line read: return true; } if (is.eof()) return false; else if (is.fail()) { if (is.bad()) { std::ostringstream oss; oss << "ERROR: unexpected failure while attempting to read line " << (line_no+1) << "\n"; throw blt_exception(oss.str().c_str()); } is.clear(); } // incomplete line read in this case, have to increase buffer size: return true; } bool istream_line_splitter:: parse_line() { _n_word=0; _is.getline(_buf,_buf_size); const unsigned previous_line_no(_line_no); if (! check_istream(_is,_line_no)) return false; // normal eof unsigned buflen(strlen(_buf)); while (((buflen+1) == _buf_size) && (previous_line_no==_line_no)) { increase_buffer_size(); _is.getline(_buf+buflen,_buf_size-buflen); if (! check_istream(_is,_line_no)) { std::ostringstream oss; oss << "ERROR: Unexpected read failure in parse_line() at line_no: " << _line_no << "\n"; throw blt_exception(oss.str().c_str()); } buflen=(strlen(_buf)); } if ((buflen+1) >_buf_size) { std::ostringstream oss; oss << "ERROR: Unexpected read failure in parse_line() at line_no: " << _line_no << "\n"; throw blt_exception(oss.str().c_str()); } if (NULL == _buf) return false; assert(buflen); // do a low-level separator parse: { char* p(_buf); word[0]=p; unsigned i(1); while (i<_max_word) { if ((*p == '\n') || (*p == '\0')) break; if (*p == _sep) { *p = '\0'; word[i++] = p+1; } ++p; } _n_word=i; } return true; }
22.633803
101
0.574673
sequencing
61156337b8c0e2c4f61baf2c1ed44e0641c7cc21
7,791
hpp
C++
src/Engine/Renderer/RenderTechnique/RenderTechnique.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/RenderTechnique/RenderTechnique.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/RenderTechnique/RenderTechnique.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
#ifndef RADIUMENGINE_RENDERTECHNIQUE_HPP #define RADIUMENGINE_RENDERTECHNIQUE_HPP #include <Engine/RaEngine.hpp> #include <Engine/Renderer/RenderTechnique/ShaderConfiguration.hpp> #include <memory> #include <map> #include <functional> namespace Ra { namespace Engine { class ShaderProgram; class Material; } } namespace Ra { namespace Engine { // TODO (Mathias) : Adapt RenderTechnique for multi-material purpose // TODO transform the folowing ideas and insight into a real doc ... // --> Interface that must be implemented by a RenderTechnique // --> depthAmbiant Pass // This pass must compute the Z of each Fragment and, optionally, the ambiant term // (see DepthAmbiantPass shader of Forward Renderer) // --> opaqueLighting Pass // This pass must compute the lighting of the opaque aspect of the material // (see BlinnPhong shader of Forward Renderer) // --> transparentLighting Pass // This pass must compute the lighting of the transparent aspect of the material // (see LitOIT shader of Forward Renderer) // // --> modify RenderObject so that it is able to activate the required technique for rendering // This is done but not yet finalized ... main rendering (internal render) is fixed, secondary renderings (ui, // debug, ...) still have the possibilities to bypass the notion of Technique" // // A RenderTechnique correspond to a set shader configuration allowing to manage a Material while rendering. // The set of configurations must contains what is required to render objects in the following ways : // 1- depth and ambiant-environment lighting : // Required for the depth pre-pass of several renderers. // Must initialise the color. Initialization at 0 or to the base color of the fragments resulting from // ambiant-Environment lighting // * Default/Reference : DepthAmbiantPass shaders // 2- Opaque lighting : THIS ONE IS MANDATORY, EACH MATERIAL MUST AT LEAST BE RENDERABLE AS OPAQUE OBJECT // Main configuration, computes the resluting color according to a lighting configuration. // The lighting configuration might contains one or severa sources of different types. // * Default/Reference : BlinnPhong shaders // 3- Transparent lighting : // Same as opaque lighting but for transparent objects // * Default/Reference LitOIT shaders // 4- WhatElse ???? // /* Exemple of use from Forward Renderer * * depthAmbiant pass * Build a RenderParameters object defining the ambiant lighting configuration (envmap or irradiancemap or * constant factor of base color. * for each RenderObject * call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_DEPTH_AMBIANT); * * opaqueLighting pass : * For each light sources set (from 1 to N light sources) * Build a RenderParameters object defining the lighting configuration. * For each RenderObject * call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_LIGHT_OPAQUE); * * transparentLighting pass * For each light sources set (from 1 to N light sources) * Build a RenderParameters object defining the lighting configuration. * For each RenderObject * call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_LIGHT_TRANSPARENT); * * Each technique must be configured with its own shaders. * * TODO : Default rendertechnique must be renderer dependant ... */ class RA_ENGINE_API RenderTechnique { public: enum PassName { Z_PREPASS = 1 << 0, LIGHTING_OPAQUE = 1 << 1, LIGHTING_TRANSPARENT = 1 << 2, NO_PASS = 0 }; RenderTechnique(); RenderTechnique(const RenderTechnique &); ~RenderTechnique(); void setConfiguration(const ShaderConfiguration &newConfig, PassName pass = LIGHTING_OPAQUE); // TODO : do we need all the config or only the basic part ? ShaderConfiguration getConfiguration(PassName pass = LIGHTING_OPAQUE) const; const ShaderProgram *getShader(PassName pass = LIGHTING_OPAQUE) const; void setMaterial(const std::shared_ptr<Material> &material); const std::shared_ptr<Material> &getMaterial() const; void resetMaterial(Material *mat); void updateGL(); bool shaderIsDirty(PassName pass = LIGHTING_OPAQUE) const; // creates a Radium default rendertechnique : // Z_PREPASS = DepthDepthAmbientPass // LIGHTING_OPAQUE = BlinnPhong // LIGHTING_TRANSPARENT = LitOIT static Ra::Engine::RenderTechnique createDefaultRenderTechnique(); private: using ConfigurationSet = std::map<PassName, ShaderConfiguration>; using ShaderSet = std::map<PassName, const ShaderProgram *>; ConfigurationSet shaderConfig; ShaderSet shaders; std::shared_ptr<Material> material = nullptr; // Change this if there is more than 8 configurations unsigned char dirtyBits = (Z_PREPASS | LIGHTING_OPAQUE | LIGHTING_TRANSPARENT); unsigned char setPasses = NO_PASS; }; /////////////////////////////////////////////// //// Radium defined technique /// /////////////////////////////////////////////// namespace EngineRenderTechniques { // A default technique function is a function that will fill the given RenderTEchnique with the default // configurations associated with a material using DefaultTechniqueBuilder = std::function<void(RenderTechnique &, bool)>; /** register a new default builder for a technique * @return true if builder added, false else (e.g, a builder with the same name exists) */ RA_ENGINE_API bool registerDefaultTechnique(const std::string &name, DefaultTechniqueBuilder builder); /** remove a default builder * @return true if builder removed, false else (e.g, a builder with the same name does't exists) */ RA_ENGINE_API bool removeDefaultTechnique(const std::string &name); /** * @param name name of the technique to construct * @return a pair containing the search result and, if true, the functor to call to build the technique. */ RA_ENGINE_API std::pair<bool, DefaultTechniqueBuilder> getDefaultTechnique(const std::string &name); } } // namespace Engine } // namespace Ra #endif // RADIUMENGINE_RENDERTECHNIQUE_HPP
48.391304
139
0.583237
nmellado
611749d79751c8e45b0f44c0693379bee1e65e8e
8,269
cxx
C++
vital/tools/config_explorer.cxx
aaron-bray/kwiver
be55ec5a511ba5b9f2af94b268ac5f9a657accc4
[ "BSD-3-Clause" ]
null
null
null
vital/tools/config_explorer.cxx
aaron-bray/kwiver
be55ec5a511ba5b9f2af94b268ac5f9a657accc4
[ "BSD-3-Clause" ]
null
null
null
vital/tools/config_explorer.cxx
aaron-bray/kwiver
be55ec5a511ba5b9f2af94b268ac5f9a657accc4
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2016 by Kitware, Inc. * 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 name of Kitware, Inc. nor the names of any 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 AUTHORS 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. */ /** * \file * \brief config_explorer tool */ // Would be nice to provide better insight into config reading process. // - Scan search path and report files found in a concise list. // - How config_parser resolves include files. // #include <vital/config/config_block_io.h> #include <vital/config/config_block.h> #include <vital/config/config_parser.h> #include <kwiversys/CommandLineArguments.hxx> #include <cstdlib> #include <iostream> #include <vector> #include <string> typedef kwiversys::CommandLineArguments argT; // Global options bool opt_config( false ); bool opt_detail_ds( false ); bool opt_detail_dc( false ); bool opt_help( false ); std::vector< std::string > opt_path; std::string opt_app_name( "config_explorer" ); std::string opt_app_version; std::string opt_install_prefix; // ------------------------------------------------------------------ void print_help() { std::cout << "This program assists in debugging config loading problems. It loads a \n" << "configuration and displays the contents or displays the search path.\n" << "Additional paths can be specified in \"KWIVER_CONFIG_PATH\" environment variable\n" << "or on the command line with the -I or --path options.\n" << "\n" << "Options are:\n" << " -h / --help displays usage information\n" << " --path name add directory to config search path(can appear multiple times)\n" << " -Iname add directory to config search path(can appear multiple times)\n" << " -ds generate detailed application-specific search paths\n" << " -dc generate detailed config contents output\n" << " -a name alternate application name\n" << " -v version optional application version string\n" << " --prefix dir optional non-standard install prefix directory\n" << "\n" << "If -ds is specified, the detailed search paths that apply to the application are\n" << "displayed only otherwise, the config file is loaded.\n" << "\n" << "The option -dc only has effect when a config file is specified and causes a\n" << "detailed output of the config entries.\n" << "\n" << "If -I or --path are specified, then the config file is only searched for using\n" << "the specified path. The application name based paths are not used.\n" ; return; } // ------------------------------------------------------------------ int path_callback( const char* argument, // name of argument const char* value, // value of argument void* call_data ) // data from register call { const std::string p( value ); opt_path.push_back( p ); return 1; // return true for OK } // ------------------------------------------------------------------ int main( int argc, char* argv[] ) { std::string plugin_name; kwiversys::CommandLineArguments arg; arg.Initialize( argc, argv ); arg.StoreUnusedArguments( true ); arg.AddArgument( "-h", argT::NO_ARGUMENT, &opt_help, "Display usage information" ); arg.AddArgument( "--help", argT::NO_ARGUMENT, &opt_help, "Display usage information" ); // details arg.AddArgument( "-ds", argT::NO_ARGUMENT, &opt_detail_ds, "Display detailed application search path" ); arg.AddArgument( "-dc", argT::NO_ARGUMENT, &opt_detail_dc, "Display detailed config contents" ); // manual search path arg.AddCallback( "--path", argT::SPACE_ARGUMENT, path_callback, 0, "Add directory to config search path" ); arg.AddCallback( "-I", argT::CONCAT_ARGUMENT, path_callback, 0, "Add directory to config search path" ); // auto search path generation arg.AddArgument( "-a", argT::SPACE_ARGUMENT, &opt_app_name, "Application name" ); arg.AddArgument( "-v", argT::SPACE_ARGUMENT, &opt_app_version, "Application version string" ); arg.AddArgument( "--prefix", argT::SPACE_ARGUMENT, &opt_install_prefix, "Non-standard installation prefix. (e.g. /opt/kitware)" ); if ( ! arg.Parse() ) { std::cerr << "Problem parsing arguments" << std::endl; exit( 0 ); } if ( opt_help ) { print_help(); return EXIT_SUCCESS; } char** newArgv = 0; int newArgc = 0; arg.GetUnusedArguments(&newArgc, &newArgv); // // Display application specific search path. // if ( opt_detail_ds ) { kwiver::vital::config_path_list_t search_path = kwiver::vital::application_config_file_paths( opt_app_name, opt_app_version, opt_install_prefix ); std::cout << "Application specific configuration search paths for\n" << " App name: " << opt_app_name << std::endl << " App version: " << opt_app_version << std::endl << " Install Prefix: " << opt_install_prefix << std::endl << std::endl; for( auto path : search_path ) { std::cout << path << std::endl; } return EXIT_SUCCESS; } // Read in config if( newArgc == 1 ) { std::cout << "Missing file name.\n" << "Usage: " << newArgv[0] << " config-file-name\n" << " " << newArgv[0] << " --help for usage details\n" << std::endl; return EXIT_FAILURE; } const std::string config_file = newArgv[1]; arg.DeleteRemainingArguments(newArgc, &newArgv); kwiver::vital::config_block_sptr config; if ( ! opt_path.empty() ) { std::cout << "Using custom search path.\n"; config = kwiver::vital::read_config_file( config_file, opt_path ); } else { std::cout << "Using application default search path.\n"; config = kwiver::vital::read_config_file( config_file, opt_app_name, opt_app_version, opt_install_prefix, true ); // merge all configs } // // Dump details of config // if ( opt_detail_dc ) { std::cout << "Config contents for\n" << " App name: " << opt_app_name << std::endl << " App version: " << opt_app_version << std::endl << " Install Prefix: " << opt_install_prefix << std::endl << std::endl; kwiver::vital::write_config( config, std::cout ); } return EXIT_SUCCESS; } // main
36.267544
113
0.603942
aaron-bray
611804bc06cfdcc8aacb073d92f8163593ef0a30
54,166
cpp
C++
core/src/fpdfapi/fpdf_render/fpdf_render.cpp
NDevTK/PDFium
ba665a1a77edcd3fdcaa2173a4233680113a9bed
[ "BSD-3-Clause" ]
303
2015-03-13T08:31:24.000Z
2022-03-21T10:06:45.000Z
core/src/fpdfapi/fpdf_render/fpdf_render.cpp
speedyzhou/PDFium-2
ee6088e63bfdee81153ef1eeec9b90e42c87064f
[ "BSD-3-Clause" ]
8
2021-07-11T08:05:25.000Z
2022-02-11T03:38:22.000Z
core/src/fpdfapi/fpdf_render/fpdf_render.cpp
speedyzhou/PDFium-2
ee6088e63bfdee81153ef1eeec9b90e42c87064f
[ "BSD-3-Clause" ]
100
2015-03-13T08:28:56.000Z
2022-02-18T03:19:39.000Z
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "../../../include/fpdfapi/fpdf_render.h" #include "../../../include/fpdfapi/fpdf_module.h" #include "../fpdf_page/pageint.h" #include "../../../include/fxge/fx_ge.h" #include "../../../include/fxcodec/fx_codec.h" #include "render_int.h" CPDF_DocRenderData::CPDF_DocRenderData(CPDF_Document* pPDFDoc) : m_pPDFDoc(pPDFDoc) , m_pFontCache(NULL) { } CPDF_DocRenderData::~CPDF_DocRenderData() { Clear(TRUE); } void CPDF_DocRenderData::Clear(FX_BOOL bRelease) { FX_POSITION pos; { pos = m_Type3FaceMap.GetStartPosition(); while (pos) { CPDF_Font* pFont; CPDF_CountedObject<CPDF_Type3Cache*>* cache; m_Type3FaceMap.GetNextAssoc(pos, pFont, cache); if (bRelease || cache->m_nCount < 2) { delete cache->m_Obj; delete cache; m_Type3FaceMap.RemoveKey(pFont); } } } #ifndef _FPDFAPI_MINI_ { pos = m_TransferFuncMap.GetStartPosition(); while (pos) { CPDF_Object* key; CPDF_CountedObject<CPDF_TransferFunc*>* value; m_TransferFuncMap.GetNextAssoc(pos, key, value); if (bRelease || value->m_nCount < 2) { delete value->m_Obj; delete value; m_TransferFuncMap.RemoveKey(key); } } } #endif if (m_pFontCache) { if (bRelease) { delete m_pFontCache; m_pFontCache = NULL; } else { m_pFontCache->FreeCache(FALSE); } } } FX_BOOL CPDF_DocRenderData::Initialize() { m_pFontCache = FX_NEW CFX_FontCache; return TRUE; } CPDF_Type3Cache* CPDF_DocRenderData::GetCachedType3(CPDF_Type3Font* pFont) { CPDF_CountedObject<CPDF_Type3Cache*>* pCache; if (!m_Type3FaceMap.Lookup(pFont, pCache)) { CPDF_Type3Cache* pType3 = FX_NEW CPDF_Type3Cache(pFont); pCache = FX_NEW CPDF_CountedObject<CPDF_Type3Cache*>; pCache->m_Obj = pType3; pCache->m_nCount = 1; m_Type3FaceMap.SetAt(pFont, pCache); } pCache->m_nCount++; return pCache->m_Obj; } void CPDF_DocRenderData::ReleaseCachedType3(CPDF_Type3Font* pFont) { CPDF_CountedObject<CPDF_Type3Cache*>* pCache; if (!m_Type3FaceMap.Lookup(pFont, pCache)) { return; } pCache->m_nCount--; } class CPDF_RenderModule : public CPDF_RenderModuleDef { public: virtual ~CPDF_RenderModule() {} virtual FX_BOOL Installed() { return TRUE; } virtual CPDF_DocRenderData* CreateDocData(CPDF_Document* pDoc); virtual void DestroyDocData(CPDF_DocRenderData* p); virtual void ClearDocData(CPDF_DocRenderData* p); virtual CPDF_DocRenderData* GetRenderData() { return &m_RenderData; } virtual CPDF_PageRenderCache* CreatePageCache(CPDF_Page* pPage) { return FX_NEW CPDF_PageRenderCache(pPage); } virtual void DestroyPageCache(CPDF_PageRenderCache* pCache); virtual CPDF_RenderConfig* GetConfig() { return &m_RenderConfig; } private: CPDF_DocRenderData m_RenderData; CPDF_RenderConfig m_RenderConfig; }; CPDF_DocRenderData* CPDF_RenderModule::CreateDocData(CPDF_Document* pDoc) { CPDF_DocRenderData* pData = FX_NEW CPDF_DocRenderData(pDoc); pData->Initialize(); return pData; } void CPDF_RenderModule::DestroyDocData(CPDF_DocRenderData* pDocData) { delete pDocData; } void CPDF_RenderModule::ClearDocData(CPDF_DocRenderData* p) { if (p) { p->Clear(FALSE); } } void CPDF_RenderModule::DestroyPageCache(CPDF_PageRenderCache* pCache) { delete pCache; } void CPDF_ModuleMgr::InitRenderModule() { if (m_pRenderModule) { delete m_pRenderModule; } m_pRenderModule = FX_NEW CPDF_RenderModule; } CPDF_RenderOptions::CPDF_RenderOptions() : m_ColorMode(RENDER_COLOR_NORMAL) , m_Flags(RENDER_CLEARTYPE) , m_Interpolation(0) , m_AddFlags(0) , m_pOCContext(NULL) , m_dwLimitCacheSize(1024 * 1024 * 100) , m_HalftoneLimit(-1) { #if defined(_FPDFAPI_MINI_) m_Flags |= RENDER_LIMITEDIMAGECACHE; #endif } FX_ARGB CPDF_RenderOptions::TranslateColor(FX_ARGB argb) const { if (m_ColorMode == RENDER_COLOR_NORMAL) { return argb; } if (m_ColorMode == RENDER_COLOR_ALPHA) { return argb; } int a, r, g, b; ArgbDecode(argb, a, r, g, b); int gray = FXRGB2GRAY(r, g, b); if (m_ColorMode == RENDER_COLOR_TWOCOLOR) { int color = (r - gray) * (r - gray) + (g - gray) * (g - gray) + (b - gray) * (b - gray); if (gray < 35 && color < 20) { return ArgbEncode(a, m_ForeColor); } if (gray > 221 && color < 20) { return ArgbEncode(a, m_BackColor); } return argb; } int fr = FXSYS_GetRValue(m_ForeColor); int fg = FXSYS_GetGValue(m_ForeColor); int fb = FXSYS_GetBValue(m_ForeColor); int br = FXSYS_GetRValue(m_BackColor); int bg = FXSYS_GetGValue(m_BackColor); int bb = FXSYS_GetBValue(m_BackColor); r = (br - fr) * gray / 255 + fr; g = (bg - fg) * gray / 255 + fg; b = (bb - fb) * gray / 255 + fb; return ArgbEncode(a, r, g, b); } CPDF_RenderStatus::CPDF_RenderStatus() { m_pContext = NULL; m_bStopped = FALSE; m_Level = 0; m_pDevice = NULL; m_pCurObj = NULL; m_pStopObj = NULL; m_HalftoneLimit = 0; m_pObjectRenderer = NULL; m_bPrint = FALSE; m_Transparency = 0; m_DitherBits = 0; m_bDropObjects = FALSE; m_bStdCS = FALSE; m_GroupFamily = 0; m_bLoadMask = FALSE; m_pType3Char = NULL; m_T3FillColor = 0; m_pFormResource = NULL; m_pPageResource = NULL; m_curBlend = FXDIB_BLEND_NORMAL; } CPDF_RenderStatus::~CPDF_RenderStatus() { if (m_pObjectRenderer) { delete m_pObjectRenderer; } } FX_BOOL CPDF_RenderStatus::Initialize(int level, CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice, const CFX_AffineMatrix* pDeviceMatrix, const CPDF_PageObject* pStopObj, const CPDF_RenderStatus* pParentState, const CPDF_GraphicStates* pInitialStates, const CPDF_RenderOptions* pOptions, int transparency, FX_BOOL bDropObjects, CPDF_Dictionary* pFormResource, FX_BOOL bStdCS, CPDF_Type3Char* pType3Char, FX_ARGB fill_color, FX_DWORD GroupFamily, FX_BOOL bLoadMask) { m_Level = level; m_pContext = pContext; m_pDevice = pDevice; m_DitherBits = pDevice->GetDeviceCaps(FXDC_DITHER_BITS); m_bPrint = m_pDevice->GetDeviceClass() != FXDC_DISPLAY; if (pDeviceMatrix) { m_DeviceMatrix = *pDeviceMatrix; } m_pStopObj = pStopObj; if (pOptions) { m_Options = *pOptions; } m_bDropObjects = bDropObjects; m_bStdCS = bStdCS; m_T3FillColor = fill_color; m_pType3Char = pType3Char; m_GroupFamily = GroupFamily; m_bLoadMask = bLoadMask; m_pFormResource = pFormResource; m_pPageResource = m_pContext->m_pPageResources; if (pInitialStates && !m_pType3Char) { m_InitialStates.CopyStates(*pInitialStates); if (pParentState) { CPDF_ColorStateData* pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)m_InitialStates.m_ColorState; CPDF_ColorStateData* pParentData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)pParentState->m_InitialStates.m_ColorState; if (!pColorData || pColorData->m_FillColor.IsNull()) { CPDF_ColorStateData* pData = m_InitialStates.m_ColorState.GetModify(); pData->m_FillRGB = pParentData->m_FillRGB; pData->m_FillColor.Copy(&pParentData->m_FillColor); } if (!pColorData || pColorData->m_StrokeColor.IsNull()) { CPDF_ColorStateData* pData = m_InitialStates.m_ColorState.GetModify(); pData->m_StrokeRGB = pParentData->m_FillRGB; pData->m_StrokeColor.Copy(&pParentData->m_StrokeColor); } } } else { m_InitialStates.DefaultStates(); } #if defined(_FPDFAPI_MINI_)||defined(_FXCORE_LIMITED_CPU_) m_HalftoneLimit = CPDF_ModuleMgr::Get()->GetRenderModule()->GetConfig()->m_HalftoneLimit; if (pOptions && pOptions->m_HalftoneLimit >= 0) { m_HalftoneLimit = pOptions->m_HalftoneLimit; } #endif m_pObjectRenderer = NULL; m_Transparency = transparency; return TRUE; } void CPDF_RenderStatus::RenderObjectList(const CPDF_PageObjects* pObjs, const CFX_AffineMatrix* pObj2Device) { if (m_Level > 32) { return; } CFX_FloatRect clip_rect = m_pDevice->GetClipBox(); CFX_AffineMatrix device2object; device2object.SetReverse(*pObj2Device); device2object.TransformRect(clip_rect); int index = 0; FX_POSITION pos = pObjs->GetFirstObjectPosition(); while(pos) { index ++; CPDF_PageObject* pCurObj = pObjs->GetNextObject(pos); if (pCurObj == m_pStopObj) { m_bStopped = TRUE; return; } if (!pCurObj) { continue; } if(pCurObj == NULL || pCurObj->m_Left > clip_rect.right || pCurObj->m_Right < clip_rect.left || pCurObj->m_Bottom > clip_rect.top || pCurObj->m_Top < clip_rect.bottom) { continue; } RenderSingleObject(pCurObj, pObj2Device); if (m_bStopped) { return; } } } void CPDF_RenderStatus::RenderSingleObject(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device) { if (m_Level > 32) { return; } m_pCurObj = pObj; if (m_Options.m_pOCContext && pObj->m_ContentMark.NotNull()) if (!m_Options.m_pOCContext->CheckObjectVisible(pObj)) { return; } ProcessClipPath(pObj->m_ClipPath, pObj2Device); if (ProcessTransparency(pObj, pObj2Device)) { return; } ProcessObjectNoClip(pObj, pObj2Device); } FX_BOOL CPDF_RenderStatus::ContinueSingleObject(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device, IFX_Pause* pPause) { if (m_pObjectRenderer) { if (m_pObjectRenderer->Continue(pPause)) { return TRUE; } if (!m_pObjectRenderer->m_Result) { DrawObjWithBackground(pObj, pObj2Device); } #ifdef _FPDFAPI_MINI_ if (m_DitherBits) { DitherObjectArea(pObj, pObj2Device); } #endif delete m_pObjectRenderer; m_pObjectRenderer = NULL; return FALSE; } m_pCurObj = pObj; if (m_Options.m_pOCContext && pObj->m_ContentMark.NotNull()) if (!m_Options.m_pOCContext->CheckObjectVisible(pObj)) { return FALSE; } ProcessClipPath(pObj->m_ClipPath, pObj2Device); if (ProcessTransparency(pObj, pObj2Device)) { return FALSE; } if (pObj->m_Type == PDFPAGE_IMAGE) { m_pObjectRenderer = IPDF_ObjectRenderer::Create(pObj->m_Type); if (!m_pObjectRenderer->Start(this, pObj, pObj2Device, FALSE)) { if (!m_pObjectRenderer->m_Result) { DrawObjWithBackground(pObj, pObj2Device); } #ifdef _FPDFAPI_MINI_ if (m_DitherBits) { DitherObjectArea(pObj, pObj2Device); } #endif delete m_pObjectRenderer; m_pObjectRenderer = NULL; return FALSE; } return ContinueSingleObject(pObj, pObj2Device, pPause); } ProcessObjectNoClip(pObj, pObj2Device); return FALSE; } IPDF_ObjectRenderer* IPDF_ObjectRenderer::Create(int type) { IPDF_ObjectRenderer* pRenderer = NULL; if (type == PDFPAGE_IMAGE) { pRenderer = FX_NEW CPDF_ImageRenderer; } return pRenderer; } FX_BOOL CPDF_RenderStatus::GetObjectClippedRect(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device, FX_BOOL bLogical, FX_RECT &rect) const { rect = pObj->GetBBox(pObj2Device); FX_RECT rtClip = m_pDevice->GetClipBox(); if (!bLogical) { CFX_Matrix dCTM = m_pDevice->GetCTM(); FX_FLOAT a = FXSYS_fabs(dCTM.a); FX_FLOAT d = FXSYS_fabs(dCTM.d); if (a != 1.0f || d != 1.0f) { rect.right = rect.left + (FX_INT32)FXSYS_ceil((FX_FLOAT)rect.Width() * a); rect.bottom = rect.top + (FX_INT32)FXSYS_ceil((FX_FLOAT)rect.Height() * d); rtClip.right = rtClip.left + (FX_INT32)FXSYS_ceil((FX_FLOAT)rtClip.Width() * a); rtClip.bottom = rtClip.top + (FX_INT32)FXSYS_ceil((FX_FLOAT)rtClip.Height() * d); } } rect.Intersect(rtClip); return rect.IsEmpty(); } void CPDF_RenderStatus::DitherObjectArea(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device) { CFX_DIBitmap* pBitmap = m_pDevice->GetBitmap(); if (pBitmap == NULL) { return; } FX_RECT rect; if (GetObjectClippedRect(pObj, pObj2Device, FALSE, rect)) { return; } if (m_DitherBits == 2) { static FX_ARGB pal[4] = {0, 85, 170, 255}; pBitmap->DitherFS(pal, 4, &rect); } else if (m_DitherBits == 3) { static FX_ARGB pal[8] = {0, 36, 73, 109, 146, 182, 219, 255}; pBitmap->DitherFS(pal, 8, &rect); } else if (m_DitherBits == 4) { static FX_ARGB pal[16] = {0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255}; pBitmap->DitherFS(pal, 16, &rect); } } void CPDF_RenderStatus::ProcessObjectNoClip(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device) { FX_BOOL bRet = FALSE; switch (pObj->m_Type) { case PDFPAGE_TEXT: bRet = ProcessText((CPDF_TextObject*)pObj, pObj2Device, NULL); break; case PDFPAGE_PATH: bRet = ProcessPath((CPDF_PathObject*)pObj, pObj2Device); break; case PDFPAGE_IMAGE: bRet = ProcessImage((CPDF_ImageObject*)pObj, pObj2Device); break; case PDFPAGE_SHADING: bRet = ProcessShading((CPDF_ShadingObject*)pObj, pObj2Device); break; case PDFPAGE_FORM: bRet = ProcessForm((CPDF_FormObject*)pObj, pObj2Device); break; #if defined(_FPDFAPI_MINI_) case PDFPAGE_INLINES: bRet = ProcessInlines((CPDF_InlineImages*)pObj, pObj2Device); break; #endif } if (!bRet) { DrawObjWithBackground(pObj, pObj2Device); } } FX_BOOL CPDF_RenderStatus::DrawObjWithBlend(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device) { FX_BOOL bRet = FALSE; switch (pObj->m_Type) { case PDFPAGE_PATH: bRet = ProcessPath((CPDF_PathObject*)pObj, pObj2Device); break; case PDFPAGE_IMAGE: bRet = ProcessImage((CPDF_ImageObject *)pObj, pObj2Device); break; case PDFPAGE_FORM: bRet = ProcessForm((CPDF_FormObject*)pObj, pObj2Device); break; } return bRet; } void CPDF_RenderStatus::GetScaledMatrix(CFX_Matrix &matrix) const { CFX_Matrix dCTM = m_pDevice->GetCTM(); matrix.a *= FXSYS_fabs(dCTM.a); matrix.d *= FXSYS_fabs(dCTM.d); } void CPDF_RenderStatus::DrawObjWithBackground(const CPDF_PageObject* pObj, const CFX_AffineMatrix* pObj2Device) { #if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_) FX_RECT rect; if (GetObjectClippedRect(pObj, pObj2Device, FALSE, rect)) { return; } int res = 300; if (pObj->m_Type == PDFPAGE_IMAGE && m_pDevice->GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER) { res = 0; } CPDF_ScaledRenderBuffer buffer; if (!buffer.Initialize(m_pContext, m_pDevice, &rect, pObj, &m_Options, res)) { return; } CFX_AffineMatrix matrix = *pObj2Device; matrix.Concat(*buffer.GetMatrix()); GetScaledMatrix(matrix); CPDF_Dictionary* pFormResource = NULL; if (pObj->m_Type == PDFPAGE_FORM) { CPDF_FormObject* pFormObj = (CPDF_FormObject*)pObj; if (pFormObj->m_pForm && pFormObj->m_pForm->m_pFormDict) { pFormResource = pFormObj->m_pForm->m_pFormDict->GetDict(FX_BSTRC("Resources")); } } CPDF_RenderStatus status; status.Initialize(m_Level + 1, m_pContext, buffer.GetDevice(), buffer.GetMatrix(), NULL, NULL, NULL, &m_Options, m_Transparency, m_bDropObjects, pFormResource); status.RenderSingleObject(pObj, &matrix); buffer.OutputToDevice(); #endif } FX_BOOL CPDF_RenderStatus::ProcessForm(CPDF_FormObject* pFormObj, const CFX_AffineMatrix* pObj2Device) { CPDF_Dictionary* pOC = pFormObj->m_pForm->m_pFormDict->GetDict(FX_BSTRC("OC")); if (pOC && m_Options.m_pOCContext && !m_Options.m_pOCContext->CheckOCGVisible(pOC)) { return TRUE; } CFX_AffineMatrix matrix = pFormObj->m_FormMatrix; matrix.Concat(*pObj2Device); CPDF_Dictionary* pResources = NULL; if (pFormObj->m_pForm && pFormObj->m_pForm->m_pFormDict) { pResources = pFormObj->m_pForm->m_pFormDict->GetDict(FX_BSTRC("Resources")); } CPDF_RenderStatus status; status.Initialize(m_Level + 1, m_pContext, m_pDevice, NULL, m_pStopObj, this, pFormObj, &m_Options, m_Transparency, m_bDropObjects, pResources, FALSE); status.m_curBlend = m_curBlend; m_pDevice->SaveState(); status.RenderObjectList(pFormObj->m_pForm, &matrix); m_bStopped = status.m_bStopped; m_pDevice->RestoreState(); return TRUE; } FX_BOOL IsAvailableMatrix(const CFX_AffineMatrix& matrix) { if (matrix.a == 0 || matrix.d == 0) { return matrix.b != 0 && matrix.c != 0; } if (matrix.b == 0 || matrix.c == 0) { return matrix.a != 0 && matrix.d != 0; } return TRUE; } FX_BOOL CPDF_RenderStatus::ProcessPath(CPDF_PathObject* pPathObj, const CFX_AffineMatrix* pObj2Device) { int FillType = pPathObj->m_FillType; FX_BOOL bStroke = pPathObj->m_bStroke; ProcessPathPattern(pPathObj, pObj2Device, FillType, bStroke); if (FillType == 0 && !bStroke) { return TRUE; } FX_DWORD fill_argb = 0; if (FillType) { fill_argb = GetFillArgb(pPathObj); } FX_DWORD stroke_argb = 0; if (bStroke) { stroke_argb = GetStrokeArgb(pPathObj); } CFX_AffineMatrix path_matrix = pPathObj->m_Matrix; path_matrix.Concat(*pObj2Device); if (!IsAvailableMatrix(path_matrix)) { return TRUE; } if (FillType && (m_Options.m_Flags & RENDER_RECT_AA)) { FillType |= FXFILL_RECT_AA; } if (m_Options.m_Flags & RENDER_FILL_FULLCOVER) { FillType |= FXFILL_FULLCOVER; } if (m_Options.m_Flags & RENDER_NOPATHSMOOTH) { FillType |= FXFILL_NOPATHSMOOTH; } if (bStroke) { FillType |= FX_FILL_STROKE; } #if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_) const CPDF_GeneralStateData* pGeneralData = ((CPDF_PageObject*)pPathObj)->m_GeneralState; if (pGeneralData && pGeneralData->m_StrokeAdjust) { FillType |= FX_STROKE_ADJUST; } #endif if (m_pType3Char) { FillType |= FX_FILL_TEXT_MODE; } CFX_GraphStateData graphState(*pPathObj->m_GraphState); if (m_Options.m_Flags & RENDER_THINLINE) { graphState.m_LineWidth = 0; } return m_pDevice->DrawPath(pPathObj->m_Path, &path_matrix, &graphState, fill_argb, stroke_argb, FillType, 0, NULL, m_curBlend); } CPDF_TransferFunc* CPDF_RenderStatus::GetTransferFunc(CPDF_Object* pObj) const { ASSERT(pObj != NULL); CPDF_DocRenderData* pDocCache = m_pContext->m_pDocument->GetRenderData(); if (!pDocCache) { return NULL; } return pDocCache->GetTransferFunc(pObj); } FX_ARGB CPDF_RenderStatus::GetFillArgb(const CPDF_PageObject* pObj, FX_BOOL bType3) const { CPDF_ColorStateData* pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)pObj->m_ColorState; if (m_pType3Char && !bType3 && (!m_pType3Char->m_bColored || (m_pType3Char->m_bColored && (!pColorData || pColorData->m_FillColor.IsNull())))) { return m_T3FillColor; } else if (!pColorData || pColorData->m_FillColor.IsNull()) { pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)m_InitialStates.m_ColorState; } FX_COLORREF rgb = pColorData->m_FillRGB; if (rgb == (FX_DWORD) - 1) { return 0; } const CPDF_GeneralStateData* pGeneralData = pObj->m_GeneralState; int alpha; if (pGeneralData) { alpha = (FX_INT32)(pGeneralData->m_FillAlpha * 255); #ifndef _FPDFAPI_MINI_ if (pGeneralData->m_pTR) { if (!pGeneralData->m_pTransferFunc) { ((CPDF_GeneralStateData*)pGeneralData)->m_pTransferFunc = GetTransferFunc(pGeneralData->m_pTR); } if (pGeneralData->m_pTransferFunc) { rgb = pGeneralData->m_pTransferFunc->TranslateColor(rgb); } } #endif } else { alpha = 255; } return m_Options.TranslateColor(ArgbEncode(alpha, rgb)); } FX_ARGB CPDF_RenderStatus::GetStrokeArgb(const CPDF_PageObject* pObj) const { CPDF_ColorStateData* pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)pObj->m_ColorState; if (m_pType3Char && (!m_pType3Char->m_bColored || (m_pType3Char->m_bColored && (!pColorData || pColorData->m_StrokeColor.IsNull())))) { return m_T3FillColor; } else if (!pColorData || pColorData->m_StrokeColor.IsNull()) { pColorData = (CPDF_ColorStateData*)(const CPDF_ColorStateData*)m_InitialStates.m_ColorState; } FX_COLORREF rgb = pColorData->m_StrokeRGB; if (rgb == (FX_DWORD) - 1) { return 0; } const CPDF_GeneralStateData* pGeneralData = pObj->m_GeneralState; int alpha; if (pGeneralData) { alpha = (FX_INT32)(pGeneralData->m_StrokeAlpha * 255); #ifndef _FPDFAPI_MINI_ if (pGeneralData->m_pTR) { if (!pGeneralData->m_pTransferFunc) { ((CPDF_GeneralStateData*)pGeneralData)->m_pTransferFunc = GetTransferFunc(pGeneralData->m_pTR); } if (pGeneralData->m_pTransferFunc) { rgb = pGeneralData->m_pTransferFunc->TranslateColor(rgb); } } #endif } else { alpha = 255; } return m_Options.TranslateColor(ArgbEncode(alpha, rgb)); } void CPDF_RenderStatus::ProcessClipPath(CPDF_ClipPath ClipPath, const CFX_AffineMatrix* pObj2Device) { if (ClipPath.IsNull()) { if (m_LastClipPath.IsNull()) { return; } m_pDevice->RestoreState(TRUE); m_LastClipPath.SetNull(); return; } if (m_LastClipPath == ClipPath) { return; } m_LastClipPath = ClipPath; m_pDevice->RestoreState(TRUE); int nClipPath = ClipPath.GetPathCount(); int i; for (i = 0; i < nClipPath; i++) { const CFX_PathData* pPathData = ClipPath.GetPath(i); if (pPathData == NULL) { continue; } if (pPathData->GetPointCount() == 0) { CFX_PathData EmptyPath; EmptyPath.AppendRect(-1, -1, 0, 0); int fill_mode = FXFILL_WINDING; m_pDevice->SetClip_PathFill(&EmptyPath, NULL, fill_mode); } else { int ClipType = ClipPath.GetClipType(i); m_pDevice->SetClip_PathFill(pPathData, pObj2Device, ClipType); } } int textcount = ClipPath.GetTextCount(); if (textcount == 0) { return; } if (m_pDevice->GetDeviceClass() == FXDC_DISPLAY && !(m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_SOFT_CLIP)) { return; } CFX_PathData* pTextClippingPath = NULL; for (i = 0; i < textcount; i ++) { CPDF_TextObject* pText = ClipPath.GetText(i); if (pText == NULL) { if (pTextClippingPath) { int fill_mode = FXFILL_WINDING; if (m_Options.m_Flags & RENDER_NOTEXTSMOOTH) { fill_mode |= FXFILL_NOPATHSMOOTH; } m_pDevice->SetClip_PathFill(pTextClippingPath, NULL, fill_mode); delete pTextClippingPath; pTextClippingPath = NULL; } } else { if (pTextClippingPath == NULL) { pTextClippingPath = FX_NEW CFX_PathData; } ProcessText(pText, pObj2Device, pTextClippingPath); } } if (pTextClippingPath) { delete pTextClippingPath; } } void CPDF_RenderStatus::DrawClipPath(CPDF_ClipPath ClipPath, const CFX_AffineMatrix* pObj2Device) { if (ClipPath.IsNull()) { return; } int fill_mode = 0; if (m_Options.m_Flags & RENDER_NOPATHSMOOTH) { fill_mode |= FXFILL_NOPATHSMOOTH; } int nClipPath = ClipPath.GetPathCount(); int i; for (i = 0; i < nClipPath; i++) { const CFX_PathData* pPathData = ClipPath.GetPath(i); if (pPathData == NULL) { continue; } CFX_GraphStateData stroke_state; if (m_Options.m_Flags & RENDER_THINLINE) { stroke_state.m_LineWidth = 0; } m_pDevice->DrawPath(pPathData, pObj2Device, &stroke_state, 0, 0xffff0000, fill_mode); } } FX_BOOL CPDF_RenderStatus::SelectClipPath(CPDF_PathObject* pPathObj, const CFX_AffineMatrix* pObj2Device, FX_BOOL bStroke) { CFX_AffineMatrix path_matrix = pPathObj->m_Matrix; path_matrix.Concat(*pObj2Device); if (bStroke) { CFX_GraphStateData graphState(*pPathObj->m_GraphState); if (m_Options.m_Flags & RENDER_THINLINE) { graphState.m_LineWidth = 0; } return m_pDevice->SetClip_PathStroke(pPathObj->m_Path, &path_matrix, &graphState); } int fill_mode = pPathObj->m_FillType; if (m_Options.m_Flags & RENDER_NOPATHSMOOTH) { fill_mode |= FXFILL_NOPATHSMOOTH; } return m_pDevice->SetClip_PathFill(pPathObj->m_Path, &path_matrix, fill_mode); } FX_BOOL CPDF_RenderStatus::ProcessTransparency(const CPDF_PageObject* pPageObj, const CFX_AffineMatrix* pObj2Device) { const CPDF_GeneralStateData* pGeneralState = pPageObj->m_GeneralState; int blend_type = pGeneralState ? pGeneralState->m_BlendType : FXDIB_BLEND_NORMAL; if (blend_type == FXDIB_BLEND_UNSUPPORTED) { return TRUE; } CPDF_Dictionary* pSMaskDict = pGeneralState ? (CPDF_Dictionary*)pGeneralState->m_pSoftMask : NULL; if (pSMaskDict) { if (pPageObj->m_Type == PDFPAGE_IMAGE && ((CPDF_ImageObject*)pPageObj)->m_pImage->GetDict()->KeyExist(FX_BSTRC("SMask"))) { pSMaskDict = NULL; } } CPDF_Dictionary* pFormResource = NULL; FX_FLOAT group_alpha = 1.0f; int Transparency = m_Transparency; FX_BOOL bGroupTransparent = FALSE; if (pPageObj->m_Type == PDFPAGE_FORM) { CPDF_FormObject* pFormObj = (CPDF_FormObject*)pPageObj; const CPDF_GeneralStateData *pStateData = pFormObj->m_GeneralState.GetObject(); if (pStateData) { group_alpha = pStateData->m_FillAlpha; } Transparency = pFormObj->m_pForm->m_Transparency; bGroupTransparent = Transparency & PDFTRANS_ISOLATED ? TRUE : FALSE; if (pFormObj->m_pForm->m_pFormDict) { pFormResource = pFormObj->m_pForm->m_pFormDict->GetDict("Resources"); } } FX_BOOL bTextClip = FALSE; if (pPageObj->m_ClipPath.NotNull() && pPageObj->m_ClipPath.GetTextCount() && m_pDevice->GetDeviceClass() == FXDC_DISPLAY && !(m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_SOFT_CLIP)) { bTextClip = TRUE; } if ((m_Options.m_Flags & RENDER_OVERPRINT) && pPageObj->m_Type == PDFPAGE_IMAGE && pGeneralState && pGeneralState->m_FillOP && pGeneralState->m_StrokeOP) { CPDF_Document* pDocument = NULL; CPDF_Page* pPage = NULL; if (m_pContext->m_pPageCache) { pPage = m_pContext->m_pPageCache->GetPage(); pDocument = pPage->m_pDocument; } else { pDocument = ((CPDF_ImageObject*)pPageObj)->m_pImage->GetDocument(); } CPDF_Dictionary* pPageResources = pPage ? pPage->m_pPageResources : NULL; CPDF_Object* pCSObj = ((CPDF_ImageObject*)pPageObj)->m_pImage->GetStream()->GetDict()->GetElementValue(FX_BSTRC("ColorSpace")); CPDF_ColorSpace* pColorSpace = pDocument->LoadColorSpace(pCSObj, pPageResources); if (pColorSpace) { int format = pColorSpace->GetFamily(); if (format == PDFCS_DEVICECMYK || format == PDFCS_SEPARATION || format == PDFCS_DEVICEN) { blend_type = FXDIB_BLEND_DARKEN; } pDocument->GetPageData()->ReleaseColorSpace(pCSObj); } } if (pSMaskDict == NULL && group_alpha == 1.0f && blend_type == FXDIB_BLEND_NORMAL && !bTextClip && !bGroupTransparent) { return FALSE; } FX_BOOL isolated = Transparency & PDFTRANS_ISOLATED; if (m_bPrint) { FX_BOOL bRet = FALSE; int rendCaps = m_pDevice->GetRenderCaps(); if (!((Transparency & PDFTRANS_ISOLATED) || pSMaskDict || bTextClip) && (rendCaps & FXRC_BLEND_MODE)) { int oldBlend = m_curBlend; m_curBlend = blend_type; bRet = DrawObjWithBlend(pPageObj, pObj2Device); m_curBlend = oldBlend; } if (!bRet) { DrawObjWithBackground(pPageObj, pObj2Device); } return TRUE; } FX_RECT rect = pPageObj->GetBBox(pObj2Device); rect.Intersect(m_pDevice->GetClipBox()); if (rect.IsEmpty()) { return TRUE; } CFX_Matrix deviceCTM = m_pDevice->GetCTM(); FX_FLOAT scaleX = FXSYS_fabs(deviceCTM.a); FX_FLOAT scaleY = FXSYS_fabs(deviceCTM.d); int width = FXSYS_round((FX_FLOAT)rect.Width() * scaleX); int height = FXSYS_round((FX_FLOAT)rect.Height() * scaleY); CFX_FxgeDevice bitmap_device; CFX_DIBitmap* oriDevice = NULL; if (!isolated && (m_pDevice->GetRenderCaps() & FXRC_GET_BITS)) { oriDevice = FX_NEW CFX_DIBitmap; if (!m_pDevice->CreateCompatibleBitmap(oriDevice, width, height)) { return TRUE; } m_pDevice->GetDIBits(oriDevice, rect.left, rect.top); } if (!bitmap_device.Create(width, height, FXDIB_Argb, 0, oriDevice)) { return TRUE; } CFX_DIBitmap* bitmap = bitmap_device.GetBitmap(); bitmap->Clear(0); CFX_AffineMatrix new_matrix = *pObj2Device; new_matrix.TranslateI(-rect.left, -rect.top); new_matrix.Scale(scaleX, scaleY); CFX_DIBitmap* pTextMask = NULL; if (bTextClip) { pTextMask = FX_NEW CFX_DIBitmap; if (!pTextMask->Create(width, height, FXDIB_8bppMask)) { delete pTextMask; return TRUE; } pTextMask->Clear(0); CFX_FxgeDevice text_device; text_device.Attach(pTextMask); for (FX_DWORD i = 0; i < pPageObj->m_ClipPath.GetTextCount(); i ++) { CPDF_TextObject* textobj = pPageObj->m_ClipPath.GetText(i); if (textobj == NULL) { break; } CFX_AffineMatrix text_matrix; textobj->GetTextMatrix(&text_matrix); CPDF_TextRenderer::DrawTextPath(&text_device, textobj->m_nChars, textobj->m_pCharCodes, textobj->m_pCharPos, textobj->m_TextState.GetFont(), textobj->m_TextState.GetFontSize(), &text_matrix, &new_matrix, textobj->m_GraphState, (FX_ARGB) - 1, 0, NULL); } } CPDF_RenderStatus bitmap_render; bitmap_render.Initialize(m_Level + 1, m_pContext, &bitmap_device, NULL, m_pStopObj, NULL, NULL, &m_Options, 0, m_bDropObjects, pFormResource, TRUE); bitmap_render.ProcessObjectNoClip(pPageObj, &new_matrix); m_bStopped = bitmap_render.m_bStopped; if (pSMaskDict) { CFX_AffineMatrix smask_matrix; FXSYS_memcpy32(&smask_matrix, pGeneralState->m_SMaskMatrix, sizeof smask_matrix); smask_matrix.Concat(*pObj2Device); CFX_DIBSource* pSMaskSource = LoadSMask(pSMaskDict, &rect, &smask_matrix); if (pSMaskSource) { bitmap->MultiplyAlpha(pSMaskSource); delete pSMaskSource; } } if (pTextMask) { bitmap->MultiplyAlpha(pTextMask); delete pTextMask; pTextMask = NULL; } if (Transparency & PDFTRANS_GROUP && group_alpha != 1.0f) { bitmap->MultiplyAlpha((FX_INT32)(group_alpha * 255)); } Transparency = m_Transparency; if (pPageObj->m_Type == PDFPAGE_FORM) { Transparency |= PDFTRANS_GROUP; } CompositeDIBitmap(bitmap, rect.left, rect.top, 0, 255, blend_type, Transparency); if (oriDevice) { delete oriDevice; } return TRUE; } CFX_DIBitmap* CPDF_RenderStatus::GetBackdrop(const CPDF_PageObject* pObj, const FX_RECT& rect, int& left, int& top, FX_BOOL bBackAlphaRequired) { FX_RECT bbox = rect; bbox.Intersect(m_pDevice->GetClipBox()); left = bbox.left; top = bbox.top; CFX_Matrix deviceCTM = m_pDevice->GetCTM(); FX_FLOAT scaleX = FXSYS_fabs(deviceCTM.a); FX_FLOAT scaleY = FXSYS_fabs(deviceCTM.d); int width = FXSYS_round(bbox.Width() * scaleX); int height = FXSYS_round(bbox.Height() * scaleY); CFX_DIBitmap* pBackdrop = FX_NEW CFX_DIBitmap; if (bBackAlphaRequired && !m_bDropObjects) { pBackdrop->Create(width, height, FXDIB_Argb); } else { m_pDevice->CreateCompatibleBitmap(pBackdrop, width, height); } if (pBackdrop->GetBuffer() == NULL) { delete pBackdrop; return NULL; } FX_BOOL bNeedDraw; if (pBackdrop->HasAlpha()) { bNeedDraw = !(m_pDevice->GetRenderCaps() & FXRC_ALPHA_OUTPUT); } else { bNeedDraw = !(m_pDevice->GetRenderCaps() & FXRC_GET_BITS); } if (!bNeedDraw) { m_pDevice->GetDIBits(pBackdrop, left, top); return pBackdrop; } CFX_AffineMatrix FinalMatrix = m_DeviceMatrix; FinalMatrix.TranslateI(-left, -top); FinalMatrix.Scale(scaleX, scaleY); pBackdrop->Clear(pBackdrop->HasAlpha() ? 0 : 0xffffffff); CFX_FxgeDevice device; device.Attach(pBackdrop); m_pContext->Render(&device, pObj, &m_Options, &FinalMatrix); return pBackdrop; } void CPDF_RenderContext::GetBackground(CFX_DIBitmap* pBuffer, const CPDF_PageObject* pObj, const CPDF_RenderOptions* pOptions, CFX_AffineMatrix* pFinalMatrix) { CFX_FxgeDevice device; device.Attach(pBuffer); if (m_pBackgroundDraw) { m_pBackgroundDraw->OnDrawBackground(&device, pFinalMatrix); } else { FX_RECT rect(0, 0, device.GetWidth(), device.GetHeight()); device.FillRect(&rect, 0xffffffff); } Render(&device, pObj, pOptions, pFinalMatrix); } CPDF_GraphicStates* CPDF_RenderStatus::CloneObjStates(const CPDF_GraphicStates* pSrcStates, FX_BOOL bStroke) { if (!pSrcStates) { return NULL; } CPDF_GraphicStates* pStates = FX_NEW CPDF_GraphicStates; if (!pStates) { return NULL; } pStates->CopyStates(*pSrcStates); CPDF_Color* pObjColor = bStroke ? pSrcStates->m_ColorState.GetStrokeColor() : pSrcStates->m_ColorState.GetFillColor(); if (!pObjColor->IsNull()) { CPDF_ColorStateData* pColorData = pStates->m_ColorState.GetModify(); pColorData->m_FillRGB = bStroke ? pSrcStates->m_ColorState.GetObject()->m_StrokeRGB : pSrcStates->m_ColorState.GetObject()->m_FillRGB; pColorData->m_StrokeRGB = pColorData->m_FillRGB; } return pStates; } CPDF_RenderContext::CPDF_RenderContext() { } void CPDF_RenderContext::Create(CPDF_Document* pDoc, CPDF_PageRenderCache* pPageCache, CPDF_Dictionary* pPageResources, FX_BOOL bFirstLayer) { m_pBackgroundDraw = NULL; m_pDocument = pDoc; m_pPageResources = pPageResources; m_pPageCache = pPageCache; m_bFirstLayer = bFirstLayer; } void CPDF_RenderContext::Create(CPDF_Page* pPage, FX_BOOL bFirstLayer) { m_pBackgroundDraw = NULL; m_pDocument = pPage->m_pDocument; m_pPageResources = pPage->m_pPageResources; m_pPageCache = pPage->GetRenderCache(); m_bFirstLayer = bFirstLayer; } CPDF_RenderContext::~CPDF_RenderContext() { } void CPDF_RenderContext::Clear() { m_pDocument = NULL; m_pPageResources = NULL; m_pPageCache = NULL; m_pBackgroundDraw = NULL; m_bFirstLayer = TRUE; m_ContentList.RemoveAll(); } void CPDF_RenderContext::AppendObjectList(CPDF_PageObjects* pObjs, const CFX_AffineMatrix* pObject2Device) { _PDF_RenderItem* pItem = m_ContentList.AddSpace(); pItem->m_pObjectList = pObjs; if (pObject2Device) { pItem->m_Matrix = *pObject2Device; } else { pItem->m_Matrix.SetIdentity(); } } void CPDF_RenderContext::Render(CFX_RenderDevice* pDevice, const CPDF_RenderOptions* pOptions, const CFX_AffineMatrix* pLastMatrix) { Render(pDevice, NULL, pOptions, pLastMatrix); } void CPDF_RenderContext::Render(CFX_RenderDevice* pDevice, const CPDF_PageObject* pStopObj, const CPDF_RenderOptions* pOptions, const CFX_AffineMatrix* pLastMatrix) { int count = m_ContentList.GetSize(); for (int j = 0; j < count; j ++) { pDevice->SaveState(); _PDF_RenderItem* pItem = m_ContentList.GetDataPtr(j); if (pLastMatrix) { CFX_AffineMatrix FinalMatrix = pItem->m_Matrix; FinalMatrix.Concat(*pLastMatrix); CPDF_RenderStatus status; status.Initialize(0, this, pDevice, pLastMatrix, pStopObj, NULL, NULL, pOptions, pItem->m_pObjectList->m_Transparency, FALSE, NULL); status.RenderObjectList(pItem->m_pObjectList, &FinalMatrix); #if !defined(_FPDFAPI_MINI_) if (status.m_Options.m_Flags & RENDER_LIMITEDIMAGECACHE) { m_pPageCache->CacheOptimization(status.m_Options.m_dwLimitCacheSize); } #endif if (status.m_bStopped) { pDevice->RestoreState(); break; } } else { CPDF_RenderStatus status; status.Initialize(0, this, pDevice, NULL, pStopObj, NULL, NULL, pOptions, pItem->m_pObjectList->m_Transparency, FALSE, NULL); status.RenderObjectList(pItem->m_pObjectList, &pItem->m_Matrix); #if !defined(_FPDFAPI_MINI_) if (status.m_Options.m_Flags & RENDER_LIMITEDIMAGECACHE) { m_pPageCache->CacheOptimization(status.m_Options.m_dwLimitCacheSize); } #endif if (status.m_bStopped) { pDevice->RestoreState(); break; } } pDevice->RestoreState(); } } void CPDF_RenderContext::DrawObjectList(CFX_RenderDevice* pDevice, CPDF_PageObjects* pObjs, const CFX_AffineMatrix* pObject2Device, const CPDF_RenderOptions* pOptions) { AppendObjectList(pObjs, pObject2Device); Render(pDevice, pOptions); } CPDF_ProgressiveRenderer::CPDF_ProgressiveRenderer() { m_pRenderer = NULL; m_pContext = NULL; m_pDevice = NULL; m_Status = Ready; } CPDF_ProgressiveRenderer::~CPDF_ProgressiveRenderer() { Clear(); } void CPDF_ProgressiveRenderer::Clear() { if (m_pRenderer) { delete m_pRenderer; m_pDevice->RestoreState(); m_pRenderer = NULL; } m_Status = Ready; } void CPDF_ProgressiveRenderer::Start(CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice, const CPDF_RenderOptions* pOptions, IFX_Pause* pPause, FX_BOOL bDropObjects) { if (m_Status != Ready) { m_Status = Failed; return; } m_pContext = pContext; m_pDevice = pDevice; m_pOptions = pOptions; m_bDropObjects = bDropObjects; if (pContext == NULL || pDevice == NULL) { m_Status = Failed; return; } m_Status = ToBeContinued; m_ObjectPos = NULL; m_LayerIndex = 0; m_ObjectIndex = 0; m_PrevLastPos = NULL; Continue(pPause); } #ifdef _FPDFAPI_MINI_ #define RENDER_STEP_LIMIT 20 #else #define RENDER_STEP_LIMIT 100 #endif void CPDF_ProgressiveRenderer::Continue(IFX_Pause* pPause) { if (m_Status != ToBeContinued) { return; } FX_DWORD nLayers = m_pContext->m_ContentList.GetSize(); for (; m_LayerIndex < nLayers; m_LayerIndex ++) { _PDF_RenderItem* pItem = m_pContext->m_ContentList.GetDataPtr(m_LayerIndex); FX_POSITION LastPos = pItem->m_pObjectList->GetLastObjectPosition(); if (m_ObjectPos == NULL) { if (LastPos == m_PrevLastPos) { if (!pItem->m_pObjectList->IsParsed()) { pItem->m_pObjectList->ContinueParse(pPause); if (!pItem->m_pObjectList->IsParsed()) { return; } LastPos = pItem->m_pObjectList->GetLastObjectPosition(); } } if (LastPos == m_PrevLastPos) { if (m_pRenderer) { delete m_pRenderer; m_pRenderer = NULL; m_pDevice->RestoreState(); m_ObjectPos = NULL; m_PrevLastPos = NULL; } continue; } if (m_PrevLastPos) { m_ObjectPos = m_PrevLastPos; pItem->m_pObjectList->GetNextObject(m_ObjectPos); } else { m_ObjectPos = pItem->m_pObjectList->GetFirstObjectPosition(); } m_PrevLastPos = LastPos; } if (m_pRenderer == NULL) { m_ObjectPos = pItem->m_pObjectList->GetFirstObjectPosition(); m_ObjectIndex = 0; m_pRenderer = FX_NEW CPDF_RenderStatus(); m_pRenderer->Initialize(0, m_pContext, m_pDevice, NULL, NULL, NULL, NULL, m_pOptions, pItem->m_pObjectList->m_Transparency, m_bDropObjects, NULL); m_pDevice->SaveState(); m_ClipRect = m_pDevice->GetClipBox(); CFX_AffineMatrix device2object; device2object.SetReverse(pItem->m_Matrix); device2object.TransformRect(m_ClipRect); } int objs_to_go = CPDF_ModuleMgr::Get()->GetRenderModule()->GetConfig()->m_RenderStepLimit; while (m_ObjectPos) { CPDF_PageObject* pCurObj = pItem->m_pObjectList->GetObjectAt(m_ObjectPos); if (pCurObj && pCurObj->m_Left <= m_ClipRect.right && pCurObj->m_Right >= m_ClipRect.left && pCurObj->m_Bottom <= m_ClipRect.top && pCurObj->m_Top >= m_ClipRect.bottom) { if (m_pRenderer->ContinueSingleObject(pCurObj, &pItem->m_Matrix, pPause)) { return; } #if !defined(_FPDFAPI_MINI_) if (pCurObj->m_Type == PDFPAGE_IMAGE && m_pRenderer->m_Options.m_Flags & RENDER_LIMITEDIMAGECACHE) { m_pContext->GetPageCache()->CacheOptimization(m_pRenderer->m_Options.m_dwLimitCacheSize); } #endif if (pCurObj->m_Type == PDFPAGE_FORM || pCurObj->m_Type == PDFPAGE_SHADING) { objs_to_go = 0; } else { objs_to_go --; } } m_ObjectIndex ++; pItem->m_pObjectList->GetNextObject(m_ObjectPos); if (objs_to_go == 0) { if (pPause && pPause->NeedToPauseNow()) { return; } objs_to_go = CPDF_ModuleMgr::Get()->GetRenderModule()->GetConfig()->m_RenderStepLimit; } } if (!pItem->m_pObjectList->IsParsed()) { return; } delete m_pRenderer; m_pRenderer = NULL; m_pDevice->RestoreState(); m_ObjectPos = NULL; m_PrevLastPos = NULL; if (pPause && pPause->NeedToPauseNow()) { m_LayerIndex++; return; } } m_Status = Done; } int CPDF_ProgressiveRenderer::EstimateProgress() { if (!m_pContext) { return 0; } FX_DWORD nLayers = m_pContext->m_ContentList.GetSize(); int nTotal = 0, nRendered = 0; for (FX_DWORD layer = 0; layer < nLayers; layer ++) { _PDF_RenderItem* pItem = m_pContext->m_ContentList.GetDataPtr(layer); int nObjs = pItem->m_pObjectList->CountObjects(); if (layer == m_LayerIndex) { nRendered += m_ObjectIndex; } else if (layer < m_LayerIndex) { nRendered += nObjs; } nTotal += nObjs; } if (nTotal == 0) { return 0; } return 100 * nRendered / nTotal; } CPDF_TransferFunc* CPDF_DocRenderData::GetTransferFunc(CPDF_Object* pObj) { if (pObj == NULL) { return NULL; } CPDF_CountedObject<CPDF_TransferFunc*>* pTransferCounter; if (!m_TransferFuncMap.Lookup(pObj, pTransferCounter)) { CPDF_TransferFunc* pTransfer = NULL; CPDF_Function* pFuncs[3] = {NULL, NULL, NULL}; FX_BOOL bUniTransfer = TRUE; int i; FX_BOOL bIdentity = TRUE; if (pObj->GetType() == PDFOBJ_ARRAY) { bUniTransfer = FALSE; CPDF_Array* pArray = (CPDF_Array*)pObj; if (pArray->GetCount() < 3) { return NULL; } for (FX_DWORD i = 0; i < 3; i ++) { pFuncs[2 - i] = CPDF_Function::Load(pArray->GetElementValue(i)); if (pFuncs[2 - i] == NULL) { return NULL; } } } else { pFuncs[0] = CPDF_Function::Load(pObj); if (pFuncs[0] == NULL) { return NULL; } } pTransfer = FX_NEW CPDF_TransferFunc; pTransfer->m_pPDFDoc = m_pPDFDoc; pTransferCounter = FX_NEW CPDF_CountedObject<CPDF_TransferFunc*>; pTransferCounter->m_nCount = 1; pTransferCounter->m_Obj = pTransfer; m_TransferFuncMap.SetAt(pObj, pTransferCounter); static const int kMaxOutputs = 16; FX_FLOAT output[kMaxOutputs]; FXSYS_memset32(output, 0, sizeof(output)); FX_FLOAT input; int noutput; for (int v = 0; v < 256; v ++) { input = (FX_FLOAT)v / 255.0f; if (bUniTransfer) { if (pFuncs[0] && pFuncs[0]->CountOutputs() <= kMaxOutputs) { pFuncs[0]->Call(&input, 1, output, noutput); } int o = FXSYS_round(output[0] * 255); if (o != v) { bIdentity = FALSE; } for (i = 0; i < 3; i ++) { pTransfer->m_Samples[i * 256 + v] = o; } } else for (i = 0; i < 3; i ++) { if (pFuncs[i] && pFuncs[i]->CountOutputs() <= kMaxOutputs) { pFuncs[i]->Call(&input, 1, output, noutput); int o = FXSYS_round(output[0] * 255); if (o != v) { bIdentity = FALSE; } pTransfer->m_Samples[i * 256 + v] = o; } else { pTransfer->m_Samples[i * 256 + v] = v; } } } for (i = 0; i < 3; i ++) if (pFuncs[i]) { delete pFuncs[i]; } pTransfer->m_bIdentity = bIdentity; } pTransferCounter->m_nCount++; return pTransferCounter->m_Obj; } void CPDF_DocRenderData::ReleaseTransferFunc(CPDF_Object* pObj) { CPDF_CountedObject<CPDF_TransferFunc*>* pTransferCounter; if (!m_TransferFuncMap.Lookup(pObj, pTransferCounter)) { return; } pTransferCounter->m_nCount--; } CPDF_RenderConfig::CPDF_RenderConfig() { m_HalftoneLimit = 0; #ifdef _FPDFAPI_MINI_ m_RenderStepLimit = 20; #else m_RenderStepLimit = 100; #endif } CPDF_RenderConfig::~CPDF_RenderConfig() { } CPDF_DeviceBuffer::CPDF_DeviceBuffer() { m_pBitmap = NULL; m_pDevice = NULL; m_pContext = NULL; m_pObject = NULL; } CPDF_DeviceBuffer::~CPDF_DeviceBuffer() { if (m_pBitmap) { delete m_pBitmap; } } FX_BOOL CPDF_DeviceBuffer::Initialize(CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice, FX_RECT* pRect, const CPDF_PageObject* pObj, int max_dpi) { m_pDevice = pDevice; m_pContext = pContext; m_Rect = *pRect; m_pObject = pObj; m_Matrix.TranslateI(-pRect->left, -pRect->top); #if _FXM_PLATFORM_ != _FXM_PLATFORM_APPLE_ int horz_size = pDevice->GetDeviceCaps(FXDC_HORZ_SIZE); int vert_size = pDevice->GetDeviceCaps(FXDC_VERT_SIZE); if (horz_size && vert_size && max_dpi) { int dpih = pDevice->GetDeviceCaps(FXDC_PIXEL_WIDTH) * 254 / (horz_size * 10); int dpiv = pDevice->GetDeviceCaps(FXDC_PIXEL_HEIGHT) * 254 / (vert_size * 10); if (dpih > max_dpi) { m_Matrix.Scale((FX_FLOAT)(max_dpi) / dpih, 1.0f); } if (dpiv > max_dpi) { m_Matrix.Scale(1.0f, (FX_FLOAT)(max_dpi) / (FX_FLOAT)dpiv); } } #ifdef _FPDFAPI_MINI_ m_Matrix.Scale(0.5f, 0.5f); #endif #endif CFX_Matrix ctm = m_pDevice->GetCTM(); FX_FLOAT fScaleX = FXSYS_fabs(ctm.a); FX_FLOAT fScaleY = FXSYS_fabs(ctm.d); m_Matrix.Concat(fScaleX, 0, 0, fScaleY, 0, 0); CFX_FloatRect rect(*pRect); m_Matrix.TransformRect(rect); FX_RECT bitmap_rect = rect.GetOutterRect(); m_pBitmap = FX_NEW CFX_DIBitmap; m_pBitmap->Create(bitmap_rect.Width(), bitmap_rect.Height(), FXDIB_Argb); return TRUE; } void CPDF_DeviceBuffer::OutputToDevice() { if (m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_GET_BITS) { if (m_Matrix.a == 1.0f && m_Matrix.d == 1.0f) { m_pDevice->SetDIBits(m_pBitmap, m_Rect.left, m_Rect.top); } else { m_pDevice->StretchDIBits(m_pBitmap, m_Rect.left, m_Rect.top, m_Rect.Width(), m_Rect.Height()); } } else { #if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_) CFX_DIBitmap buffer; m_pDevice->CreateCompatibleBitmap(&buffer, m_pBitmap->GetWidth(), m_pBitmap->GetHeight()); m_pContext->GetBackground(&buffer, m_pObject, NULL, &m_Matrix); buffer.CompositeBitmap(0, 0, buffer.GetWidth(), buffer.GetHeight(), m_pBitmap, 0, 0); m_pDevice->StretchDIBits(&buffer, m_Rect.left, m_Rect.top, m_Rect.Width(), m_Rect.Height()); #endif } } CPDF_ScaledRenderBuffer::CPDF_ScaledRenderBuffer() { m_pBitmapDevice = NULL; } CPDF_ScaledRenderBuffer::~CPDF_ScaledRenderBuffer() { if (m_pBitmapDevice) { delete m_pBitmapDevice; } } #ifndef _FPDFAPI_MINI_ #define _FPDFAPI_IMAGESIZE_LIMIT_ (30 * 1024 * 1024) #else #define _FPDFAPI_IMAGESIZE_LIMIT_ (10 * 1024 * 1024) #endif FX_BOOL CPDF_ScaledRenderBuffer::Initialize(CPDF_RenderContext* pContext, CFX_RenderDevice* pDevice, FX_RECT* pRect, const CPDF_PageObject* pObj, const CPDF_RenderOptions *pOptions, int max_dpi) { FXSYS_assert(pRect != NULL); m_pDevice = pDevice; if (m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_GET_BITS) { return TRUE; } m_pContext = pContext; m_Rect = *pRect; m_pObject = pObj; m_Matrix.TranslateI(-pRect->left, -pRect->top); int horz_size = pDevice->GetDeviceCaps(FXDC_HORZ_SIZE); int vert_size = pDevice->GetDeviceCaps(FXDC_VERT_SIZE); if (horz_size && vert_size && max_dpi) { int dpih = pDevice->GetDeviceCaps(FXDC_PIXEL_WIDTH) * 254 / (horz_size * 10); int dpiv = pDevice->GetDeviceCaps(FXDC_PIXEL_HEIGHT) * 254 / (vert_size * 10); if (dpih > max_dpi) { m_Matrix.Scale((FX_FLOAT)(max_dpi) / dpih, 1.0f); } if (dpiv > max_dpi) { m_Matrix.Scale(1.0f, (FX_FLOAT)(max_dpi) / (FX_FLOAT)dpiv); } } m_pBitmapDevice = FX_NEW CFX_FxgeDevice; FXDIB_Format dibFormat = FXDIB_Rgb; FX_INT32 bpp = 24; if (m_pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_ALPHA_OUTPUT) { dibFormat = FXDIB_Argb; bpp = 32; } CFX_FloatRect rect; FX_INT32 iWidth, iHeight, iPitch; while (1) { rect = *pRect; m_Matrix.TransformRect(rect); FX_RECT bitmap_rect = rect.GetOutterRect(); iWidth = bitmap_rect.Width(); iHeight = bitmap_rect.Height(); iPitch = (iWidth * bpp + 31) / 32 * 4; if (iWidth * iHeight < 1) { return FALSE; } if (iPitch * iHeight <= _FPDFAPI_IMAGESIZE_LIMIT_ && m_pBitmapDevice->Create(iWidth, iHeight, dibFormat)) { break; } m_Matrix.Scale(0.5f, 0.5f); } #if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_) m_pContext->GetBackground(m_pBitmapDevice->GetBitmap(), m_pObject, pOptions, &m_Matrix); #endif return TRUE; } void CPDF_ScaledRenderBuffer::OutputToDevice() { if (m_pBitmapDevice) { m_pDevice->StretchDIBits(m_pBitmapDevice->GetBitmap(), m_Rect.left, m_Rect.top, m_Rect.Width(), m_Rect.Height()); } } FX_BOOL IPDF_OCContext::CheckObjectVisible(const CPDF_PageObject* pObj) { const CPDF_ContentMarkData* pData = pObj->m_ContentMark; int nItems = pData->CountItems(); for (int i = 0; i < nItems; i ++) { CPDF_ContentMarkItem& item = pData->GetItem(i); if (item.GetName() == FX_BSTRC("OC") && item.GetParamType() == CPDF_ContentMarkItem::PropertiesDict) { CPDF_Dictionary* pOCG = (CPDF_Dictionary*)item.GetParam(); if (!CheckOCGVisible(pOCG)) { return FALSE; } } } return TRUE; }
36.377435
164
0.626389
NDevTK
61181e255dba50705ff9e8c1f1abbb38f943af9f
3,091
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcBoundaryCurve.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcBoundaryCurve.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcBoundaryCurve.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcBoundaryCurve.h" #include "ifcpp/IFC4/include/IfcCompositeCurveSegment.h" #include "ifcpp/IFC4/include/IfcLogical.h" #include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4/include/IfcStyledItem.h" // ENTITY IfcBoundaryCurve IfcBoundaryCurve::IfcBoundaryCurve() {} IfcBoundaryCurve::IfcBoundaryCurve( int id ) { m_entity_id = id; } IfcBoundaryCurve::~IfcBoundaryCurve() {} shared_ptr<BuildingObject> IfcBoundaryCurve::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcBoundaryCurve> copy_self( new IfcBoundaryCurve() ); for( size_t ii=0; ii<m_Segments.size(); ++ii ) { auto item_ii = m_Segments[ii]; if( item_ii ) { copy_self->m_Segments.push_back( dynamic_pointer_cast<IfcCompositeCurveSegment>(item_ii->getDeepCopy(options) ) ); } } if( m_SelfIntersect ) { copy_self->m_SelfIntersect = dynamic_pointer_cast<IfcLogical>( m_SelfIntersect->getDeepCopy(options) ); } return copy_self; } void IfcBoundaryCurve::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCBOUNDARYCURVE" << "("; writeEntityList( stream, m_Segments ); stream << ","; if( m_SelfIntersect ) { m_SelfIntersect->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcBoundaryCurve::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcBoundaryCurve::toString() const { return L"IfcBoundaryCurve"; } void IfcBoundaryCurve::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcBoundaryCurve, expecting 2, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } readEntityReferenceList( args[0], m_Segments, map ); m_SelfIntersect = IfcLogical::createObjectFromSTEP( args[1], map ); } void IfcBoundaryCurve::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcCompositeCurveOnSurface::getAttributes( vec_attributes ); } void IfcBoundaryCurve::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcCompositeCurveOnSurface::getAttributesInverse( vec_attributes_inverse ); } void IfcBoundaryCurve::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcCompositeCurveOnSurface::setInverseCounterparts( ptr_self_entity ); } void IfcBoundaryCurve::unlinkFromInverseCounterparts() { IfcCompositeCurveOnSurface::unlinkFromInverseCounterparts(); }
46.134328
234
0.748302
promethe42
611bac00a3264f6058c1cfbcd0fac6fd9a2e3fd0
3,191
cc
C++
app_ipc_scheduler/shm_sem.cc
xyyeh/Cpp_tutorials
cb5c750a61013d252e1a7e53100690315bfa931b
[ "Unlicense" ]
1
2019-12-04T06:03:10.000Z
2019-12-04T06:03:10.000Z
app_ipc_scheduler/shm_sem.cc
xyyeh/cpp_tutorials
cb5c750a61013d252e1a7e53100690315bfa931b
[ "Unlicense" ]
null
null
null
app_ipc_scheduler/shm_sem.cc
xyyeh/cpp_tutorials
cb5c750a61013d252e1a7e53100690315bfa931b
[ "Unlicense" ]
null
null
null
#include "shm_sem.h" #include <errno.h> #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <iostream> const std::string ShmSemaphore::sLockSemaphoreName = "/semaphoreInit"; ShmSemaphore::ShmSemaphore(const std::string& sName) : name_(sName), ptr_(nullptr), shm_id_(-1), sem_id_(nullptr), size_(0) { /** * Semaphore open */ sem_id_ = sem_open(sLockSemaphoreName.c_str(), O_CREAT, S_IRUSR | S_IWUSR, 1); } bool ShmSemaphore::Create(size_t nSize, int mode /*= READ_WRITE*/) { size_ = nSize; shm_id_ = shm_open(name_.c_str(), O_CREAT | mode, 0666); if (shm_id_ < 0) { switch (errno) { case EACCES: throw ShmException("Permission Exception "); break; case EEXIST: throw ShmException( "Shared memory object specified by name already exists."); break; case EINVAL: throw ShmException("Invalid shared memory name passed."); break; case EMFILE: throw ShmException( "The process already has the maximum number of files open."); break; case ENAMETOOLONG: throw ShmException("The length of name exceeds PATH_MAX."); break; case ENFILE: throw ShmException( "The limit on the total number of files open on the system has " "been reached"); break; default: throw ShmException( "Invalid exception occurred in shared memory creation"); break; } } /* adjusting mapped file size (make room for the whole segment to map) -- * ftruncate() */ ftruncate(shm_id_, size_); return true; } bool ShmSemaphore::Attach(int mode /*= A_READ | A_WRITE*/) { /* requesting the shared segment -- mmap() */ ptr_ = mmap(NULL, size_, mode, MAP_SHARED, shm_id_, 0); if (ptr_ == nullptr) { throw ShmException("Exception in attaching the shared memory region"); } return true; } bool ShmSemaphore::Detach() { munmap(ptr_, size_); } bool ShmSemaphore::Lock() { sem_wait(sem_id_); } bool ShmSemaphore::Trylock() { return (sem_trywait(sem_id_) == 0); } bool ShmSemaphore::Unlock() { return (sem_post(sem_id_) == 0); } bool ShmSemaphore::UnlockSingle() { int sem_val; if (sem_getvalue(sem_id_, &sem_val) == 0) { if (sem_val == 0) { return (sem_post(sem_id_) == 0); } else { return false; } } return false; } ShmSemaphore::~ShmSemaphore() { Clear(); } void ShmSemaphore::Clear() { if (shm_id_ != -1) { if (shm_unlink(name_.c_str()) < 0) { perror("shm_unlink"); } } /** * Semaphore unlink: Remove a named semaphore from the system. */ if (sem_id_ != NULL) { /** * Semaphore Close: Close a named semaphore */ if (sem_close(sem_id_) < 0) { perror("sem_close"); } /** * Semaphore unlink: Remove a named semaphore from the system. */ if (sem_unlink(sLockSemaphoreName.c_str()) < 0) { perror("sem_unlink"); } } } ShmException::ShmException(const std::string& message, bool bSysMsg /*= false*/) throw() {} ShmException::~ShmException() throw() {}
26.371901
80
0.614854
xyyeh
611c1e7b0d7ba67d1acff4e21384108bd224e246
13,543
cpp
C++
build/externals/build_tbb/src/tbbmalloc/backref.cpp
adityaddy/GSoC_CernVM-FS
cd4dd6937eb4b862f1128a236d394e4734db0b75
[ "Apache-2.0", "BSD-3-Clause" ]
20
2015-05-08T02:43:27.000Z
2018-03-08T11:08:17.000Z
build/externals/build_tbb/src/tbbmalloc/backref.cpp
adityaddy/GSoC_CernVM-FS
cd4dd6937eb4b862f1128a236d394e4734db0b75
[ "Apache-2.0", "BSD-3-Clause" ]
5
2015-05-06T23:43:04.000Z
2015-08-13T19:14:37.000Z
build/externals/build_tbb/src/tbbmalloc/backref.cpp
adityaddy/GSoC_CernVM-FS
cd4dd6937eb4b862f1128a236d394e4734db0b75
[ "Apache-2.0", "BSD-3-Clause" ]
3
2015-07-07T18:44:07.000Z
2018-10-26T19:36:50.000Z
/* Copyright 2005-2014 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #include "tbbmalloc_internal.h" #include <new> /* for placement new */ namespace rml { namespace internal { /********* backreferences ***********************/ /* Each slab block and each large memory object header contains BackRefIdx * that points out in some BackRefBlock which points back to this block or header. */ struct BackRefBlock : public BlockI { BackRefBlock *nextForUse; // the next in the chain of blocks with free items FreeObject *bumpPtr; // bump pointer moves from the end to the beginning of the block FreeObject *freeList; // list of all blocks that were allocated from raw mem (i.e., not from backend) BackRefBlock *nextRawMemBlock; int allocatedCount; // the number of objects allocated int myNum; // the index in the master MallocMutex blockMutex; // true if this block has been added to the listForUse chain, // modifications protected by masterMutex bool addedToForUse; BackRefBlock(const BackRefBlock *blockToUse, int num) : nextForUse(NULL), bumpPtr((FreeObject*)((uintptr_t)blockToUse + slabSize - sizeof(void*))), freeList(NULL), nextRawMemBlock(NULL), allocatedCount(0), myNum(num), addedToForUse(false) { memset(&blockMutex, 0, sizeof(MallocMutex)); // index in BackRefMaster must fit to uint16_t MALLOC_ASSERT(!(myNum >> 16), ASSERT_TEXT); } // clean all but header void zeroSet() { memset(this+1, 0, BackRefBlock::bytes-sizeof(BackRefBlock)); } static const int bytes = slabSize; }; // max number of backreference pointers in slab block static const int BR_MAX_CNT = (BackRefBlock::bytes-sizeof(BackRefBlock))/sizeof(void*); struct BackRefMaster { /* A slab block can hold up to ~2K back pointers to slab blocks or large objects, * so it can address at least 32MB. The array of 64KB holds 8K pointers * to such blocks, addressing ~256 GB. */ static const size_t bytes = 64*1024; static const int dataSz; /* space is reserved for master table and 4 leaves taking into account VirtualAlloc allocation granularity */ static const int leaves = 4; static const size_t masterSize = BackRefMaster::bytes+leaves*BackRefBlock::bytes; // take into account VirtualAlloc 64KB granularity static const size_t blockSpaceSize = 64*1024; Backend *backend; BackRefBlock *active; // if defined, use it for allocations BackRefBlock *listForUse; // the chain of data blocks with free items BackRefBlock *allRawMemBlocks; intptr_t lastUsed; // index of the last used block bool rawMemUsed; MallocMutex requestNewSpaceMutex; BackRefBlock *backRefBl[1]; // the real size of the array is dataSz BackRefBlock *findFreeBlock(); void addToForUseList(BackRefBlock *bl); void initEmptyBackRefBlock(BackRefBlock *newBl); bool requestNewSpace(); }; const int BackRefMaster::dataSz = 1+(BackRefMaster::bytes-sizeof(BackRefMaster))/sizeof(BackRefBlock*); static MallocMutex masterMutex; static BackRefMaster *backRefMaster; bool initBackRefMaster(Backend *backend) { bool rawMemUsed; BackRefMaster *master = (BackRefMaster*)backend->getBackRefSpace(BackRefMaster::masterSize, &rawMemUsed); if (! master) return false; master->backend = backend; master->listForUse = master->allRawMemBlocks = NULL; master->rawMemUsed = rawMemUsed; master->lastUsed = -1; memset(&master->requestNewSpaceMutex, 0, sizeof(MallocMutex)); for (int i=0; i<BackRefMaster::leaves; i++) { BackRefBlock *bl = (BackRefBlock*)((uintptr_t)master + BackRefMaster::bytes + i*BackRefBlock::bytes); bl->zeroSet(); master->initEmptyBackRefBlock(bl); if (i) master->addToForUseList(bl); else // active leaf is not needed in listForUse master->active = bl; } // backRefMaster is read in getBackRef, so publish it in consistent state FencedStore((intptr_t&)backRefMaster, (intptr_t)master); return true; } void destroyBackRefMaster(Backend *backend) { if (backRefMaster) { // Is initBackRefMaster() called? for (BackRefBlock *curr=backRefMaster->allRawMemBlocks; curr; ) { BackRefBlock *next = curr->nextRawMemBlock; // allRawMemBlocks list is only for raw mem blocks backend->putBackRefSpace(curr, BackRefMaster::blockSpaceSize, /*rawMemUsed=*/true); curr = next; } backend->putBackRefSpace(backRefMaster, BackRefMaster::masterSize, backRefMaster->rawMemUsed); } } void BackRefMaster::addToForUseList(BackRefBlock *bl) { bl->nextForUse = listForUse; listForUse = bl; bl->addedToForUse = true; } void BackRefMaster::initEmptyBackRefBlock(BackRefBlock *newBl) { intptr_t nextLU = lastUsed+1; new (newBl) BackRefBlock(newBl, nextLU); backRefBl[nextLU] = newBl; // lastUsed is read in getBackRef, and access to backRefBl[lastUsed] // is possible only after checking backref against current lastUsed FencedStore(lastUsed, nextLU); } bool BackRefMaster::requestNewSpace() { bool rawMemUsed; MALLOC_STATIC_ASSERT(!(blockSpaceSize % BackRefBlock::bytes), "Must request space for whole number of blocks."); // only one thread at a time may add blocks MallocMutex::scoped_lock newSpaceLock(requestNewSpaceMutex); if (listForUse) // double check that only one block is available return true; BackRefBlock *newBl = (BackRefBlock*)backend->getBackRefSpace(blockSpaceSize, &rawMemUsed); if (!newBl) return false; // touch a page for the 1st time without taking masterMutex ... for (BackRefBlock *bl = newBl; (uintptr_t)bl < (uintptr_t)newBl + blockSpaceSize; bl = (BackRefBlock*)((uintptr_t)bl + BackRefBlock::bytes)) bl->zeroSet(); MallocMutex::scoped_lock lock(masterMutex); // ... and share under lock // use the first block in the batch to maintain the list of "raw" memory // to be released at shutdown if (rawMemUsed) { newBl->nextRawMemBlock = backRefMaster->allRawMemBlocks; backRefMaster->allRawMemBlocks = newBl; } for (BackRefBlock *bl = newBl; (uintptr_t)bl < (uintptr_t)newBl + blockSpaceSize; bl = (BackRefBlock*)((uintptr_t)bl + BackRefBlock::bytes)) { initEmptyBackRefBlock(bl); if (active->allocatedCount == BR_MAX_CNT) active = bl; // active leaf is not needed in listForUse else addToForUseList(bl); } return true; } BackRefBlock *BackRefMaster::findFreeBlock() { if (active->allocatedCount < BR_MAX_CNT) return active; if (listForUse) { // use released list MallocMutex::scoped_lock lock(masterMutex); if (active->allocatedCount == BR_MAX_CNT && listForUse) { active = listForUse; listForUse = listForUse->nextForUse; MALLOC_ASSERT(active->addedToForUse, ASSERT_TEXT); active->addedToForUse = false; } } else if (lastUsed-1 < backRefMaster->dataSz) { // allocate new data node if (!requestNewSpace()) return NULL; } else // no free space in BackRefMaster, give up return NULL; return active; } void *getBackRef(BackRefIdx backRefIdx) { // !backRefMaster means no initialization done, so it can't be valid memory // see addEmptyBackRefBlock for fences around lastUsed if (!FencedLoad((intptr_t&)backRefMaster) || backRefIdx.getMaster() > FencedLoad(backRefMaster->lastUsed) || backRefIdx.getOffset() >= BR_MAX_CNT) return NULL; return *(void**)((uintptr_t)backRefMaster->backRefBl[backRefIdx.getMaster()] + sizeof(BackRefBlock)+backRefIdx.getOffset()*sizeof(void*)); } void setBackRef(BackRefIdx backRefIdx, void *newPtr) { MALLOC_ASSERT(backRefIdx.getMaster()<=backRefMaster->lastUsed && backRefIdx.getOffset()<BR_MAX_CNT, ASSERT_TEXT); *(void**)((uintptr_t)backRefMaster->backRefBl[backRefIdx.getMaster()] + sizeof(BackRefBlock) + backRefIdx.getOffset()*sizeof(void*)) = newPtr; } BackRefIdx BackRefIdx::newBackRef(bool largeObj) { BackRefBlock *blockToUse; void **toUse; BackRefIdx res; bool lastBlockFirstUsed = false; do { MALLOC_ASSERT(backRefMaster, ASSERT_TEXT); blockToUse = backRefMaster->findFreeBlock(); if (!blockToUse) return BackRefIdx(); toUse = NULL; { // the block is locked to find a reference MallocMutex::scoped_lock lock(blockToUse->blockMutex); if (blockToUse->freeList) { toUse = (void**)blockToUse->freeList; blockToUse->freeList = blockToUse->freeList->next; MALLOC_ASSERT(!blockToUse->freeList || ((uintptr_t)blockToUse->freeList>=(uintptr_t)blockToUse && (uintptr_t)blockToUse->freeList < (uintptr_t)blockToUse + slabSize), ASSERT_TEXT); } else if (blockToUse->allocatedCount < BR_MAX_CNT) { toUse = (void**)blockToUse->bumpPtr; blockToUse->bumpPtr = (FreeObject*)((uintptr_t)blockToUse->bumpPtr - sizeof(void*)); if (blockToUse->allocatedCount == BR_MAX_CNT-1) { MALLOC_ASSERT((uintptr_t)blockToUse->bumpPtr < (uintptr_t)blockToUse+sizeof(BackRefBlock), ASSERT_TEXT); blockToUse->bumpPtr = NULL; } } if (toUse) { if (!blockToUse->allocatedCount && !backRefMaster->listForUse) lastBlockFirstUsed = true; blockToUse->allocatedCount++; } } // end of lock scope } while (!toUse); // The first thread that uses the last block requests new space in advance; // possible failures are ignored. if (lastBlockFirstUsed) backRefMaster->requestNewSpace(); res.master = blockToUse->myNum; uintptr_t offset = ((uintptr_t)toUse - ((uintptr_t)blockToUse + sizeof(BackRefBlock)))/sizeof(void*); // Is offset too big? MALLOC_ASSERT(!(offset >> 15), ASSERT_TEXT); res.offset = offset; if (largeObj) res.largeObj = largeObj; return res; } void removeBackRef(BackRefIdx backRefIdx) { MALLOC_ASSERT(!backRefIdx.isInvalid(), ASSERT_TEXT); MALLOC_ASSERT(backRefIdx.getMaster()<=backRefMaster->lastUsed && backRefIdx.getOffset()<BR_MAX_CNT, ASSERT_TEXT); BackRefBlock *currBlock = backRefMaster->backRefBl[backRefIdx.getMaster()]; FreeObject *freeObj = (FreeObject*)((uintptr_t)currBlock + sizeof(BackRefBlock) + backRefIdx.getOffset()*sizeof(void*)); MALLOC_ASSERT(((uintptr_t)freeObj>(uintptr_t)currBlock && (uintptr_t)freeObj<(uintptr_t)currBlock + slabSize), ASSERT_TEXT); { MallocMutex::scoped_lock lock(currBlock->blockMutex); freeObj->next = currBlock->freeList; MALLOC_ASSERT(!freeObj->next || ((uintptr_t)freeObj->next > (uintptr_t)currBlock && (uintptr_t)freeObj->next < (uintptr_t)currBlock + slabSize), ASSERT_TEXT); currBlock->freeList = freeObj; currBlock->allocatedCount--; } // TODO: do we need double-check here? if (!currBlock->addedToForUse && currBlock!=backRefMaster->active) { MallocMutex::scoped_lock lock(masterMutex); if (!currBlock->addedToForUse && currBlock!=backRefMaster->active) backRefMaster->addToForUseList(currBlock); } } /********* End of backreferences ***********************/ } // namespace internal } // namespace rml
41.542945
109
0.650742
adityaddy
611fa4ac41a6851dcbe458a1a7832aa58ac77640
35,105
cc
C++
tensorflow/core/kernels/training_ops.cc
vsilyaev/tensorflow
f41959ccb2d9d4c722fe8fc3351401d53bcf4900
[ "Apache-2.0" ]
4
2021-06-11T09:43:32.000Z
2021-11-17T11:15:52.000Z
tensorflow/core/kernels/training_ops.cc
cleargraphinc/tensorflow
21fac39c471dede0e4ae62dd60e2b0b85db48415
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/training_ops.cc
cleargraphinc/tensorflow
21fac39c471dede0e4ae62dd60e2b0b85db48415
[ "Apache-2.0" ]
2
2016-05-18T12:48:06.000Z
2019-03-30T03:56:31.000Z
#define EIGEN_USE_THREADS #include "tensorflow/core/kernels/training_ops.h" #include "tensorflow/core/framework/op_kernel.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; namespace functor { static inline bool DoInline(int64 size) { return size <= (256ll << 10); } template <typename T> struct ApplyGradientDescent<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::Flat var, typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstFlat grad) { if (DoInline(var.size())) { var -= grad * lr(); } else { var.device(d) -= grad * lr(); } } }; template <typename T> struct ApplyAdagrad<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::Flat var, typename TTypes<T>::Flat accum, typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstFlat grad) { if (DoInline(var.size())) { accum += grad.square(); var -= grad * lr() * accum.rsqrt(); } else { accum.device(d) += grad.square(); var.device(d) -= grad * lr() * accum.rsqrt(); } } }; template <typename T> struct ApplyMomentum<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::Flat var, typename TTypes<T>::Flat accum, typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstFlat grad, typename TTypes<T>::ConstScalar momentum) { if (DoInline(var.size())) { accum = accum * momentum() + grad; var -= accum * lr(); } else { accum.device(d) = accum * momentum() + grad; var.device(d) -= accum * lr(); } } }; template <typename T> struct ApplyAdam<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::Flat var, typename TTypes<T>::Flat m, typename TTypes<T>::Flat v, typename TTypes<T>::ConstScalar beta1_power, typename TTypes<T>::ConstScalar beta2_power, typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstScalar beta1, typename TTypes<T>::ConstScalar beta2, typename TTypes<T>::ConstScalar epsilon, typename TTypes<T>::ConstFlat grad) { const T alpha = lr() * std::sqrt(1 - beta2_power()) / (1 - beta1_power()); if (DoInline(var.size())) { m += (grad - m) * (1 - beta1()); v += (grad.square() - v) * (1 - beta2()); var -= (m * alpha) / (v.sqrt() + epsilon()); } else { m.device(d) += (grad - m) * (1 - beta1()); v.device(d) += (grad.square() - v) * (1 - beta2()); var.device(d) -= (m * alpha) / (v.sqrt() + epsilon()); } } }; template <typename T> struct ApplyRMSProp<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::Flat var, typename TTypes<T>::Flat ms, typename TTypes<T>::Flat mom, typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstScalar rho, typename TTypes<T>::ConstScalar momentum, typename TTypes<T>::ConstScalar epsilon, typename TTypes<T>::ConstFlat grad) { if (DoInline(var.size())) { ms += (grad.square() - ms) * (1 - rho()); mom = mom * momentum() + (grad * lr()) / ((ms + epsilon()).sqrt()); var -= mom; } else { ms.device(d) += (grad.square() - ms) * (1 - rho()); mom.device(d) = mom * momentum() + (grad * lr()) / ((ms + epsilon()).sqrt()); var.device(d) -= mom; } } }; } // namespace functor template <typename Device, typename T> class ApplyGradientDescentOp : public OpKernel { public: explicit ApplyGradientDescentOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override { if (use_exclusive_lock_) { mutex_lock l(*ctx->input_ref_mutex(0)); DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } else { DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; void DoValidate(OpKernelContext* ctx) { Tensor var = ctx->mutable_input(0, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); const Tensor& alpha = ctx->input(1); OP_REQUIRES(ctx, TensorShapeUtils::IsLegacyScalar(alpha.shape()), errors::InvalidArgument("alpha is not a scalar: ", alpha.shape().DebugString())); const Tensor& delta = ctx->input(2); OP_REQUIRES( ctx, var.shape().IsSameSize(delta.shape()), errors::InvalidArgument("var and delta do not have the same shape", var.shape().DebugString(), " ", delta.shape().DebugString())); } void DoCompute(OpKernelContext* ctx) { const Device& device = ctx->template eigen_device<Device>(); Tensor var = ctx->mutable_input(0, use_exclusive_lock_); const Tensor& alpha = ctx->input(1); const Tensor& delta = ctx->input(2); functor::ApplyGradientDescent<Device, T>()( device, var.flat<T>(), alpha.scalar<T>(), delta.flat<T>()); } }; #define REGISTER_KERNELS(D, T) \ REGISTER_KERNEL_BUILDER( \ Name("ApplyGradientDescent").Device(DEVICE_##D).TypeConstraint<T>("T"), \ ApplyGradientDescentOp<D##Device, T>); REGISTER_KERNELS(CPU, float); REGISTER_KERNELS(CPU, double); #if GOOGLE_CUDA // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void ApplyGradientDescent<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::Flat var, \ typename TTypes<T>::ConstScalar alpha, \ typename TTypes<T>::ConstFlat delta); \ extern template struct ApplyGradientDescent<GPUDevice, T>; DECLARE_GPU_SPEC(float); DECLARE_GPU_SPEC(double); #undef DECLARE_GPU_SPEC } // namespace functor REGISTER_KERNELS(GPU, float); REGISTER_KERNELS(GPU, double); #endif #undef REGISTER_KERNELS template <typename Device, typename T> class ApplyAdagradOp : public OpKernel { public: explicit ApplyAdagradOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override { if (use_exclusive_lock_) { mutex_lock l1(*ctx->input_ref_mutex(0)); // Don't try to acquire a lock on the second ref as they share the same // mutex. // // mutex_lock l2(*ctx->input_ref_mutex(1)); DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } else { DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; void DoValidate(OpKernelContext* ctx) { Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor accum = ctx->mutable_input(1, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); OP_REQUIRES( ctx, accum.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(1))); const Tensor& lr = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsLegacyScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); const Tensor& grad = ctx->input(3); OP_REQUIRES( ctx, var.shape().IsSameSize(accum.shape()), errors::InvalidArgument("var and accum do not have the same shape", var.shape().DebugString(), " ", accum.shape().DebugString())); OP_REQUIRES( ctx, var.shape().IsSameSize(grad.shape()), errors::InvalidArgument("var and delta do not have the same shape", var.shape().DebugString(), " ", grad.shape().DebugString())); } void DoCompute(OpKernelContext* ctx) { const Device& device = ctx->template eigen_device<Device>(); Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor accum = ctx->mutable_input(1, use_exclusive_lock_); const Tensor& lr = ctx->input(2); const Tensor& grad = ctx->input(3); functor::ApplyAdagrad<Device, T>()(device, var.flat<T>(), accum.flat<T>(), lr.scalar<T>(), grad.flat<T>()); } }; typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; #define REGISTER_KERNELS(D, T) \ REGISTER_KERNEL_BUILDER( \ Name("ApplyAdagrad").Device(DEVICE_##D).TypeConstraint<T>("T"), \ ApplyAdagradOp<D##Device, T>); REGISTER_KERNELS(CPU, float); REGISTER_KERNELS(CPU, double); #if GOOGLE_CUDA // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void ApplyAdagrad<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::Flat var, \ typename TTypes<T>::Flat accum, typename TTypes<T>::ConstScalar lr, \ typename TTypes<T>::ConstFlat grad); \ extern template struct ApplyAdagrad<GPUDevice, T>; DECLARE_GPU_SPEC(float); DECLARE_GPU_SPEC(double); #undef DECLARE_GPU_SPEC } // namespace functor REGISTER_KERNELS(GPU, float); REGISTER_KERNELS(GPU, double); #endif #undef REGISTER_KERNELS // Note, this op works on cpu only. template <typename T, typename Tindex> class SparseApplyAdagradOp : public OpKernel { public: explicit SparseApplyAdagradOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override NO_THREAD_SAFETY_ANALYSIS { mutex* mu_var = ctx->input_ref_mutex(0); // mu_accum is actually the same mutex as mu_var since currently we use a // global mutex. // // mutex* mu_accum = ctx->input_ref_mutex(1); if (use_exclusive_lock_) { mu_var->lock(); } Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor accum = ctx->mutable_input(1, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); OP_REQUIRES( ctx, accum.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(1))); OP_REQUIRES( ctx, var.shape().IsSameSize(accum.shape()), errors::InvalidArgument("var and accum do not have the same shape", var.shape().DebugString(), " ", accum.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVectorOrHigher(var.shape()), errors::InvalidArgument("var must be at least 1 dimensional")); const Tensor& lr = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsLegacyScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); const Tensor& grad = ctx->input(3); const Tensor& indices = ctx->input(4); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()), errors::InvalidArgument("indices must be one-dimensional")); for (int d = 1; d < var.dims(); d++) { OP_REQUIRES(ctx, var.dim_size(d) == grad.dim_size(d), errors::InvalidArgument(strings::StrCat( "var and grad must match in dimension ", d))); } const Tindex N = indices.dim_size(0); OP_REQUIRES( ctx, grad.dim_size(0) == N, errors::InvalidArgument( "grad must be the same size as indices in the first dimension.")); if (N > 0) { const Tindex first_dim_size = var.dim_size(0); // Validate all the indices are in range auto indices_vec = indices.vec<Tindex>(); for (Tindex i = 0; i < N; i++) { const Tindex index = indices_vec(i); OP_REQUIRES(ctx, index >= 0 && index < first_dim_size, errors::InvalidArgument( strings::StrCat("Index ", index, " at offset ", i, " in indices is out of range"))); } auto var_flat = var.flat_outer_dims<T>(); auto accum_flat = accum.flat_outer_dims<T>(); auto grad_flat = grad.flat_outer_dims<T>(); T lr_scalar = lr.scalar<T>()(); // Note(yonghui): It might be worth multi-threading square() and rsqrt(). for (Tindex i = 0; i < N; i++) { const Tindex index = indices_vec(i); auto a = accum_flat.template chip<0>(index); auto g = grad_flat.template chip<0>(i); auto v = var_flat.template chip<0>(index); a += g.square(); v -= g.constant(lr_scalar) * g * a.rsqrt(); } } if (use_exclusive_lock_) { mu_var->unlock(); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; }; #define REGISTER_KERNELS(T, Tindices) \ REGISTER_KERNEL_BUILDER(Name("SparseApplyAdagrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .TypeConstraint<Tindices>("Tindices"), \ SparseApplyAdagradOp<T, Tindices>); REGISTER_KERNELS(float, int32); REGISTER_KERNELS(float, int64); REGISTER_KERNELS(double, int32); REGISTER_KERNELS(double, int64); #undef REGISTER_KERNELS template <typename Device, typename T> class ApplyMomentumOp : public OpKernel { public: explicit ApplyMomentumOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override { if (use_exclusive_lock_) { mutex_lock l1(*ctx->input_ref_mutex(0)); // Don't try to acquire a lock on the second ref as they share the same // mutex. // // mutex_lock l2(*ctx->input_ref_mutex(1)); DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } else { DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; void DoValidate(OpKernelContext* ctx) { Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor accum = ctx->mutable_input(1, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); OP_REQUIRES( ctx, accum.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(1))); const Tensor& lr = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); const Tensor& grad = ctx->input(3); OP_REQUIRES( ctx, var.shape().IsSameSize(accum.shape()), errors::InvalidArgument("var and accum do not have the same shape", var.shape().DebugString(), " ", accum.shape().DebugString())); OP_REQUIRES( ctx, var.shape().IsSameSize(grad.shape()), errors::InvalidArgument("var and delta do not have the same shape", var.shape().DebugString(), " ", grad.shape().DebugString())); const Tensor& momentum = ctx->input(4); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum.shape()), errors::InvalidArgument("momentum is not a scalar: ", momentum.shape().DebugString())); } void DoCompute(OpKernelContext* ctx) { const Device& device = ctx->template eigen_device<Device>(); Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor accum = ctx->mutable_input(1, use_exclusive_lock_); const Tensor& lr = ctx->input(2); const Tensor& grad = ctx->input(3); const Tensor& momentum = ctx->input(4); functor::ApplyMomentum<Device, T>()(device, var.flat<T>(), accum.flat<T>(), lr.scalar<T>(), grad.flat<T>(), momentum.scalar<T>()); } }; typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; #define REGISTER_KERNELS(D, T) \ REGISTER_KERNEL_BUILDER( \ Name("ApplyMomentum").Device(DEVICE_##D).TypeConstraint<T>("T"), \ ApplyMomentumOp<D##Device, T>); REGISTER_KERNELS(CPU, float); REGISTER_KERNELS(CPU, double); #if GOOGLE_CUDA // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void ApplyMomentum<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::Flat var, \ typename TTypes<T>::Flat accum, typename TTypes<T>::ConstScalar lr, \ typename TTypes<T>::ConstFlat grad, \ typename TTypes<T>::ConstScalar momentum); \ extern template struct ApplyMomentum<GPUDevice, T>; DECLARE_GPU_SPEC(float); DECLARE_GPU_SPEC(double); #undef DECLARE_GPU_SPEC } // namespace functor REGISTER_KERNELS(GPU, float); REGISTER_KERNELS(GPU, double); #endif #undef REGISTER_KERNELS // Note, this op works on cpu only. template <typename T, typename Tindex> class SparseApplyMomentumOp : public OpKernel { public: explicit SparseApplyMomentumOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override NO_THREAD_SAFETY_ANALYSIS { mutex* mu_var = ctx->input_ref_mutex(0); // mu_accum is actually the same mutex as mu_var since currently we use a // global mutex. // // mutex* mu_accum = ctx->input_ref_mutex(1); if (use_exclusive_lock_) { mu_var->lock(); } Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor accum = ctx->mutable_input(1, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); OP_REQUIRES( ctx, accum.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(1))); OP_REQUIRES( ctx, var.shape().IsSameSize(accum.shape()), errors::InvalidArgument("var and accum do not have the same shape", var.shape().DebugString(), " ", accum.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVectorOrHigher(var.shape()), errors::InvalidArgument("var must be at least 1 dimensional")); const Tensor& lr = ctx->input(2); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); const Tensor& grad = ctx->input(3); const Tensor& indices = ctx->input(4); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(indices.shape()), errors::InvalidArgument("indices must be one-dimensional")); for (int d = 1; d < var.dims(); d++) { OP_REQUIRES(ctx, var.dim_size(d) == grad.dim_size(d), errors::InvalidArgument(strings::StrCat( "var and grad must match in dimension ", d))); } const Tindex N = indices.dim_size(0); OP_REQUIRES( ctx, grad.dim_size(0) == N, errors::InvalidArgument( "grad must be the same size as indices in the first dimension.")); const Tensor& momentum = ctx->input(5); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum.shape()), errors::InvalidArgument("momentum is not a scalar: ", momentum.shape().DebugString())); if (N > 0) { const Tindex first_dim_size = var.dim_size(0); // Validate all the indices are in range auto indices_vec = indices.vec<Tindex>(); for (Tindex i = 0; i < N; i++) { const Tindex index = indices_vec(i); OP_REQUIRES(ctx, index >= 0 && index < first_dim_size, errors::InvalidArgument( strings::StrCat("Index ", index, " at offset ", i, " in indices is out of range"))); } auto var_flat = var.flat_outer_dims<T>(); auto accum_flat = accum.flat_outer_dims<T>(); auto grad_flat = grad.flat_outer_dims<T>(); T lr_scalar = lr.scalar<T>()(); T momentum_scalar = momentum.scalar<T>()(); for (Tindex i = 0; i < N; i++) { const Tindex index = indices_vec(i); auto a = accum_flat.template chip<0>(index); auto g = grad_flat.template chip<0>(i); auto v = var_flat.template chip<0>(index); a = a * a.constant(momentum_scalar) + g; v -= a.constant(lr_scalar) * a; } } if (use_exclusive_lock_) { mu_var->unlock(); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; }; #define REGISTER_KERNELS(T, Tindices) \ REGISTER_KERNEL_BUILDER(Name("SparseApplyMomentum") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .TypeConstraint<Tindices>("Tindices"), \ SparseApplyMomentumOp<T, Tindices>); REGISTER_KERNELS(float, int32); REGISTER_KERNELS(float, int64); REGISTER_KERNELS(double, int32); REGISTER_KERNELS(double, int64); #undef REGISTER_KERNELS template <typename Device, typename T> class ApplyAdamOp : public OpKernel { public: explicit ApplyAdamOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override { if (use_exclusive_lock_) { // all input refs share the same mutex mutex_lock l1(*ctx->input_ref_mutex(0)); DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } else { DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; void DoValidate(OpKernelContext* ctx) { Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor m = ctx->mutable_input(1, use_exclusive_lock_); Tensor v = ctx->mutable_input(2, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); OP_REQUIRES( ctx, m.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(1))); OP_REQUIRES( ctx, v.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(2))); const Tensor& beta1_power = ctx->input(3); const Tensor& beta2_power = ctx->input(4); const Tensor& lr = ctx->input(5); const Tensor& beta1 = ctx->input(6); const Tensor& beta2 = ctx->input(7); const Tensor& epsilon = ctx->input(8); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_power.shape()), errors::InvalidArgument("beta1_power is not a scalar: ", beta1_power.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2_power.shape()), errors::InvalidArgument("beta2_power is not a scalar: ", beta2_power.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1.shape()), errors::InvalidArgument("beta1 is not a scalar: ", beta1.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2.shape()), errors::InvalidArgument("beta2 is not a scalar: ", beta2.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()), errors::InvalidArgument("epsilon is not a scalar: ", epsilon.shape().DebugString())); const Tensor& grad = ctx->input(9); OP_REQUIRES(ctx, var.shape().IsSameSize(m.shape()), errors::InvalidArgument("var and m do not have the same shape", var.shape().DebugString(), " ", m.shape().DebugString())); OP_REQUIRES(ctx, var.shape().IsSameSize(v.shape()), errors::InvalidArgument("var and v do not have the same shape", var.shape().DebugString(), " ", v.shape().DebugString())); OP_REQUIRES( ctx, var.shape().IsSameSize(grad.shape()), errors::InvalidArgument("var and grad do not have the same shape", var.shape().DebugString(), " ", grad.shape().DebugString())); } void DoCompute(OpKernelContext* ctx) { const Device& device = ctx->template eigen_device<Device>(); Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor m = ctx->mutable_input(1, use_exclusive_lock_); Tensor v = ctx->mutable_input(2, use_exclusive_lock_); const Tensor& beta1_power = ctx->input(3); const Tensor& beta2_power = ctx->input(4); const Tensor& lr = ctx->input(5); const Tensor& beta1 = ctx->input(6); const Tensor& beta2 = ctx->input(7); const Tensor& epsilon = ctx->input(8); const Tensor& grad = ctx->input(9); functor::ApplyAdam<Device, T>()(device, var.flat<T>(), m.flat<T>(), v.flat<T>(), beta1_power.scalar<T>(), beta2_power.scalar<T>(), lr.scalar<T>(), beta1.scalar<T>(), beta2.scalar<T>(), epsilon.scalar<T>(), grad.flat<T>()); } }; typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; #define REGISTER_KERNELS(D, T) \ REGISTER_KERNEL_BUILDER( \ Name("ApplyAdam").Device(DEVICE_##D).TypeConstraint<T>("T"), \ ApplyAdamOp<D##Device, T>); REGISTER_KERNELS(CPU, float); REGISTER_KERNELS(CPU, double); #if GOOGLE_CUDA // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void ApplyAdam<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::Flat var, \ typename TTypes<T>::Flat m, typename TTypes<T>::Flat v, \ typename TTypes<T>::ConstScalar beta1_power, \ typename TTypes<T>::ConstScalar beta2_power, \ typename TTypes<T>::ConstScalar lr, \ typename TTypes<T>::ConstScalar beta1, \ typename TTypes<T>::ConstScalar beta2, \ typename TTypes<T>::ConstScalar epsilon, \ typename TTypes<T>::ConstFlat grad); \ extern template struct ApplyAdam<GPUDevice, T>; DECLARE_GPU_SPEC(float); DECLARE_GPU_SPEC(double); #undef DECLARE_GPU_SPEC } // namespace functor REGISTER_KERNELS(GPU, float); REGISTER_KERNELS(GPU, double); #endif #undef REGISTER_KERNELS template <typename Device, typename T> class ApplyRMSPropOp : public OpKernel { public: explicit ApplyRMSPropOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_locking", &use_exclusive_lock_)); } void Compute(OpKernelContext* ctx) override { if (use_exclusive_lock_) { // all input refs share the same mutex mutex_lock l1(*ctx->input_ref_mutex(0)); DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } else { DoValidate(ctx); if (!ctx->status().ok()) return; DoCompute(ctx); } ctx->forward_ref_input_to_ref_output(0, 0); } private: bool use_exclusive_lock_; void DoValidate(OpKernelContext* ctx) { Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor ms = ctx->mutable_input(1, use_exclusive_lock_); Tensor mom = ctx->mutable_input(2, use_exclusive_lock_); OP_REQUIRES( ctx, var.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(0))); OP_REQUIRES( ctx, ms.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(1))); OP_REQUIRES( ctx, mom.IsInitialized(), errors::FailedPrecondition( "Attempting to use uninitialized variables: ", def().input(2))); const Tensor& lr = ctx->input(3); const Tensor& rho = ctx->input(4); const Tensor& momentum = ctx->input(5); const Tensor& epsilon = ctx->input(6); const Tensor& grad = ctx->input(7); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr.shape()), errors::InvalidArgument("lr is not a scalar: ", lr.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(rho.shape()), errors::InvalidArgument("rho is not a scalar: ", rho.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum.shape()), errors::InvalidArgument("momentum is not a scalar: ", momentum.shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon.shape()), errors::InvalidArgument("epsilon is not a scalar: ", epsilon.shape().DebugString())); OP_REQUIRES(ctx, var.shape().IsSameSize(ms.shape()), errors::InvalidArgument("var and ms do not have the same shape", var.shape().DebugString(), " ", ms.shape().DebugString())); OP_REQUIRES(ctx, var.shape().IsSameSize(mom.shape()), errors::InvalidArgument( "var and mom do not have the same shape", var.shape().DebugString(), " ", mom.shape().DebugString())); OP_REQUIRES( ctx, var.shape().IsSameSize(grad.shape()), errors::InvalidArgument("var and grad do not have the same shape", var.shape().DebugString(), " ", grad.shape().DebugString())); } void DoCompute(OpKernelContext* ctx) { const Device& device = ctx->template eigen_device<Device>(); Tensor var = ctx->mutable_input(0, use_exclusive_lock_); Tensor ms = ctx->mutable_input(1, use_exclusive_lock_); Tensor mom = ctx->mutable_input(2, use_exclusive_lock_); const Tensor& lr = ctx->input(3); const Tensor& rho = ctx->input(4); const Tensor& momentum = ctx->input(5); const Tensor& epsilon = ctx->input(6); const Tensor& grad = ctx->input(7); functor::ApplyRMSProp<Device, T>()(device, var.flat<T>(), ms.flat<T>(), mom.flat<T>(), lr.scalar<T>(), rho.scalar<T>(), momentum.scalar<T>(), epsilon.scalar<T>(), grad.flat<T>()); } }; typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; #define REGISTER_KERNELS(D, T) \ REGISTER_KERNEL_BUILDER( \ Name("ApplyRMSProp").Device(DEVICE_##D).TypeConstraint<T>("T"), \ ApplyRMSPropOp<D##Device, T>); REGISTER_KERNELS(CPU, float); REGISTER_KERNELS(CPU, double); #if GOOGLE_CUDA // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T) \ template <> \ void ApplyRMSProp<GPUDevice, T>::operator()( \ const GPUDevice& d, typename TTypes<T>::Flat var, \ typename TTypes<T>::Flat ms, typename TTypes<T>::Flat mom, \ typename TTypes<T>::ConstScalar lr, typename TTypes<T>::ConstScalar rho, \ typename TTypes<T>::ConstScalar momentum, \ typename TTypes<T>::ConstScalar epsilon, \ typename TTypes<T>::ConstFlat grad); \ extern template struct ApplyRMSProp<GPUDevice, T>; DECLARE_GPU_SPEC(float); DECLARE_GPU_SPEC(double); #undef DECLARE_GPU_SPEC } // namespace functor REGISTER_KERNELS(GPU, float); REGISTER_KERNELS(GPU, double); #endif #undef REGISTER_KERNELS } // namespace tensorflow
39.666667
80
0.579234
vsilyaev
6120212e344a69fbb446a123d1d724c58b9aae7b
4,487
cpp
C++
src/3rdparty/opennurbs/opennurbs_sum.cpp
ouxianghui/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
12
2021-03-26T03:23:30.000Z
2021-12-31T10:05:44.000Z
src/3rdparty/opennurbs/opennurbs_sum.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
null
null
null
src/3rdparty/opennurbs/opennurbs_sum.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
9
2021-06-23T08:26:40.000Z
2022-01-20T07:18:10.000Z
/* $NoKeywords: $ */ /* // // Copyright (c) 1993-2007 Robert McNeel & Associates. All rights reserved. // Rhinoceros is a registered trademark of Robert McNeel & Assoicates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // // For complete openNURBS copyright information see <http://www.opennurbs.org>. // //////////////////////////////////////////////////////////////// */ #include "opennurbs.h" ON_Sum::ON_Sum() { Begin(0.0); } int ON_Sum::SummandCount() const { return m_pos_count + m_neg_count + m_zero_count; } void ON_Sum::Begin( double starting_value ) { m_sum_err = 0.0; m_pos_sum = 0.0; m_neg_sum = 0.0; m_pos_sum1_count = 0; m_pos_sum2_count = 0; m_pos_sum3_count = 0; m_neg_sum1_count = 0; m_neg_sum2_count = 0; m_neg_sum3_count = 0; m_pos_count = 0; m_neg_count = 0; m_zero_count = 0; if ( starting_value > 0.0 ) { m_pos_sum = starting_value; } else if ( starting_value < 0.0 ) { m_neg_sum = starting_value; } } double ON_Sum::SortAndSum( int count, double* a ) { // note that the arrays passed to ON_Sum::SortAndSum() are all // homogeneous in sign double s = 0.0; if ( count > 0 ) { if ( count >= 2 ) { ON_SortDoubleArray( ON::quick_sort, a, count ); //double a0 = fabs(a[0]); //double a1 = fabs(a[count-1]); m_sum_err += ON_EPSILON*( fabs(a[count-1]) + count*fabs(a[0]) ); } if ( a[count] < 0.0 ) { a += count-1; while (count--) s += *a--; } else { while (count--) s += *a++; } } return s; } void ON_Sum::Plus( double x ) { if (x > 0.0) { m_pos_count++; m_pos_sum1[m_pos_sum1_count++] = x; if ( m_pos_sum1_count == sum1_max_count ) { m_pos_sum2[m_pos_sum2_count++] = SortAndSum( m_pos_sum1_count, m_pos_sum1 ); m_pos_sum1_count = 0; if ( m_pos_sum2_count == sum2_max_count ) { m_pos_sum3[m_pos_sum3_count++] = SortAndSum( m_pos_sum2_count, m_pos_sum2 ); m_pos_sum2_count = 0; if ( m_pos_sum3_count == sum3_max_count ) { x = SortAndSum( m_pos_sum3_count, m_pos_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_pos_sum) ); m_pos_sum += x; m_pos_sum3_count = 0; } } } } else if ( x < 0.0 ) { m_neg_count++; m_neg_sum1[m_neg_sum1_count++] = x; if ( m_neg_sum1_count == sum1_max_count ) { m_neg_sum2[m_neg_sum2_count++] = SortAndSum( m_neg_sum1_count, m_neg_sum1 ); m_neg_sum1_count = 0; if ( m_neg_sum2_count == sum2_max_count ) { m_neg_sum3[m_neg_sum3_count++] = SortAndSum( m_neg_sum2_count, m_neg_sum2 ); m_neg_sum2_count = 0; if ( m_neg_sum3_count == sum3_max_count ) { x = SortAndSum( m_neg_sum3_count, m_neg_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_neg_sum) ); m_neg_sum += x; m_neg_sum3_count = 0; } } } } else m_zero_count++; } void ON_Sum::operator=(double x) { Begin(x); } void ON_Sum::operator+=(double x) { Plus(x); } void ON_Sum::operator-=(double x) { Plus(-x); } double ON_Sum::Total( double* error_estimate ) { double x; if ( m_pos_sum1_count > 0 ) { m_pos_sum2[m_pos_sum2_count++] = SortAndSum( m_pos_sum1_count, m_pos_sum1 ); m_pos_sum1_count = 0; } if ( m_pos_sum2_count > 0 ) { m_pos_sum3[m_pos_sum3_count++] = SortAndSum( m_pos_sum2_count, m_pos_sum2 ); m_pos_sum2_count = 0; } if ( m_pos_sum3_count > 0 ) { x = SortAndSum( m_pos_sum3_count, m_pos_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_pos_sum) ); m_pos_sum += x; m_pos_sum3_count = 0; } if ( m_neg_sum1_count > 0 ) { m_neg_sum2[m_neg_sum2_count++] = SortAndSum( m_neg_sum1_count, m_neg_sum1 ); m_neg_sum1_count = 0; } if ( m_neg_sum2_count > 0 ) { m_neg_sum3[m_neg_sum3_count++] = SortAndSum( m_neg_sum2_count, m_neg_sum2 ); m_neg_sum2_count = 0; } if ( m_neg_sum3_count > 0 ) { x = SortAndSum( m_neg_sum3_count, m_neg_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_neg_sum) ); m_neg_sum += x; m_neg_sum3_count = 0; } if ( error_estimate ) { *error_estimate = m_sum_err + ON_EPSILON*(fabs(m_pos_sum) + fabs(m_neg_sum)); } return m_pos_sum + m_neg_sum; }
22.77665
84
0.605973
ouxianghui
6120ab687cee271ca7b08ec5588be7eafbc170b0
1,731
cpp
C++
datasets/github_cpp_10/7/62.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/7/62.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/7/62.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <math.h> using namespace std; int result_array[] = {0,0,1,4,6,8,9,7,2,13,12}; int array[] = {1,2,3,4,5,6}; int elements = 6; int merge_sort(int inArray[], int total_elements, bool count_inversion) { int inversion = 0; if (total_elements <= 1 ) { return 1; } merge_sort(&inArray[0], total_elements/2, false); merge_sort(&inArray[(total_elements/2)], total_elements - (total_elements/2) , false); int *arraya = &inArray[0]; int *arrayb = &inArray[(total_elements/2)]; int i=0, j=0, k=0; cout << "Dumping Array A " << total_elements << " :"; for(int m = 0; m < total_elements/2; m++) cout << arraya[m] << " " ; cout << endl; cout << "Dumping Array B " << total_elements << " :"; for(int m = 0; m < total_elements - total_elements/2; m++) cout << arrayb[m] << " " ; cout << endl; for( k = 0; k < total_elements; k++) { if (arraya[i] < arrayb[j]) { if ( i < total_elements/2 ) { result_array[k] = arraya[i]; i++; } else { result_array[k] = arrayb[j]; j++; } } else { if ( j < (total_elements - total_elements/2) ) { result_array[k] = arrayb[j]; j++; if (count_inversion) { inversion += (total_elements/2 - i) ; } } else { result_array[k] = arraya[i]; i++; } } } for (k =0; k < total_elements; k++) { inArray[k] = result_array[k]; } cout << "Level Sorted:"; for(int m = 0; m < total_elements; m++) cout << result_array[m] << " " ; cout << endl; if (count_inversion) { cout << "Need to count inversion " << inversion << endl; } } int main(int argc, char **argv) { merge_sort (array, elements, true); }
16.805825
87
0.558637
yijunyu
612162de4c5e1dd79b5da101291f113d4f8c40e9
22,412
cpp
C++
ControlWnd.cpp
Memotech-Bill/CamTest
5b45ed610ba84ce4ef6feb5c5cd53a75f8797b2d
[ "BSD-2-Clause" ]
null
null
null
ControlWnd.cpp
Memotech-Bill/CamTest
5b45ed610ba84ce4ef6feb5c5cd53a75f8797b2d
[ "BSD-2-Clause" ]
null
null
null
ControlWnd.cpp
Memotech-Bill/CamTest
5b45ed610ba84ce4ef6feb5c5cd53a75f8797b2d
[ "BSD-2-Clause" ]
null
null
null
// ControlWnd.cpp - A window for containing camera controls. #include <wx/panel.h> #include <wx/choice.h> #include <wx/checkbox.h> #include <wx/slider.h> #include <wx/spinctrl.h> #include <wx/stattext.h> #include <libcamera/controls.h> #include <libcamera/control_ids.h> #include "ControlWnd.h" BEGIN_EVENT_TABLE(ControlWnd, wxPanel) EVT_CHOICE(wxID_ANY, ControlWnd::OnChoice) EVT_SLIDER(wxID_ANY, ControlWnd::OnSlider) EVT_CHECKBOX(wxID_ANY, ControlWnd::OnCheckBox) EVT_SPINCTRL(wxID_ANY, ControlWnd::OnSpinCtrl) END_EVENT_TABLE() /*** ControlWnd ******************************************************* Constructor. Inputs: parent = Parent window. Coding history: WJB 19/06/21 Converted from MovieCap */ ControlWnd::ControlWnd (wxWindow *parent) : wxPanel (parent) { // printf ("ControlWnd constructor.\n"); // Create controls. LoadCtl (); m_fgsz = new wxFlexGridSizer (2); m_fgsz->AddGrowableCol (1); std::vector<ImgCtl>::iterator it; int iCtrl; for (iCtrl = 0, it = m_victl.begin (); it != m_victl.end (); ++iCtrl, ++it) { const char *psDesc = it->GetDesc ().c_str (); // printf ("Create image control \"%s\"\n", psDesc); wxString sDesc = wxString (psDesc, wxConvUTF8); m_fgsz->Add (new wxStaticText (this, wxID_ANY, sDesc), 0, wxALIGN_CENTRE_VERTICAL); int iType = it->GetType (); int iMin, iMax, iDef, iVal; it->GetData (iMin, iMax, iDef, iVal); if ( iType == 1 ) { wxBoxSizer *phbsz1 = new wxBoxSizer (wxHORIZONTAL); m_fgsz->Add (phbsz1, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL); wxSlider *pslide = new wxSlider (this, 3*iCtrl, iVal, iMin, iMax, wxDefaultPosition, wxSize (100,-1)); pslide->Enable (it->Enabled ()); phbsz1->Add (pslide, 1, wxEXPAND | wxALIGN_CENTRE_VERTICAL); wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl + 1, wxT(""), wxDefaultPosition, wxSize (120, -1), wxSP_VERTICAL); pspin->SetRange (iMin, iMax); pspin->SetValue (iVal); pspin->Enable (it->Enabled ()); phbsz1->Add (pspin, 0, wxALIGN_CENTRE_VERTICAL); } else if ( iType == 2 ) { wxCheckBox * pchk = new wxCheckBox (this, 3*iCtrl, wxT("")); pchk->SetValue (it->Enabled ()); m_fgsz->Add (pchk, 0, wxEXPAND); } else if ( iType == 3 ) { wxChoice * pchc = new wxChoice (this, 3*iCtrl); for ( int iItem = iMin; iItem <= iMax; ++iItem ) { const char *psMenu = it->GetMenuItem (iItem).c_str (); // printf ("Menu item %d = \"%s\"\n", iItem, psMenu); pchc->Append (wxString (psMenu, wxConvUTF8)); } pchc->SetSelection (iVal - iMin); m_fgsz->Add (pchc, 0, wxEXPAND); } else if ( iType == 4 ) { wxBoxSizer *phbsz1 = new wxBoxSizer (wxHORIZONTAL); m_fgsz->Add (phbsz1, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL); wxCheckBox * pchk = new wxCheckBox (this, 3*iCtrl, wxT("")); pchk->SetValue (it->Enabled ()); phbsz1->Add (pchk, 0, wxALIGN_CENTRE_VERTICAL); wxSlider *pslide = new wxSlider (this, 3*iCtrl + 1, iVal, iMin, iMax, wxDefaultPosition, wxSize (100,-1)); pslide->Enable (it->Enabled ()); phbsz1->Add (pslide, 1, wxALIGN_CENTRE_VERTICAL); wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl + 2, wxT(""), wxDefaultPosition, wxSize (120, -1), wxSP_VERTICAL); pspin->SetRange (iMin, iMax); pspin->SetValue (iVal); pspin->Enable (it->Enabled ()); phbsz1->Add (pspin, 0, wxALIGN_CENTRE_VERTICAL); } else if ( iType == 5 ) { wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl, wxT(""), wxDefaultPosition, wxSize (120, -1), wxSP_VERTICAL); pspin->SetRange (iMin, iMax); pspin->SetValue (iVal); m_fgsz->Add (pspin, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL); } else if ( iType == 6 ) { wxBoxSizer *phbsz1 = new wxBoxSizer (wxHORIZONTAL); m_fgsz->Add (phbsz1, 0, wxEXPAND | wxALIGN_CENTRE_VERTICAL); wxCheckBox * pchk = new wxCheckBox (this, 3*iCtrl, wxT("")); pchk->SetValue (it->Enabled ()); phbsz1->Add (pchk, 0, wxALIGN_CENTRE_VERTICAL); wxSpinCtrl *pspin = new wxSpinCtrl (this, 3*iCtrl + 2, wxT(""), wxDefaultPosition, wxSize (120, -1), wxSP_VERTICAL); pspin->SetRange (iMin, iMax); pspin->SetValue (iVal); pspin->Enable (it->Enabled ()); phbsz1->Add (pspin, 1, wxALIGN_CENTRE_VERTICAL); } } m_fgsz->Add (new wxStaticText (this, wxID_ANY, ""), 0, wxALIGN_CENTRE_VERTICAL); m_fgsz->Add (new wxButton (this, ID_SNAP, "Snap"), 0, wxALIGN_CENTRE_VERTICAL); SetSizer (m_fgsz); m_fgsz->SetSizeHints (this); } /*** ~ControlWnd ****************************************************** Destructor. Coding history: WJB 19/ 6/21 Empty version. */ ControlWnd::~ControlWnd (void) { // printf ("ControlWnd destructor.\n"); } /*** LoadCtl ******************************************************* Load all the controls for the image capture device. Coding history: WJB 19/ 6/21 Converted from MovieCap */ void ControlWnd::LoadCtl (void) { ImgCtl ctl (0); m_victl.clear (); /* Brightness */ ctl.m_iID = ctrlBright; // Control ID. ctl.m_sName = "Brightness"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 100; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 50; // Default value. ctl.m_iValue = 50; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Contrast */ ctl.m_iID = ctrlCont; // Control ID. ctl.m_sName = "Contrast"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = -100; // Minimum control value. ctl.m_iMax = 100; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 0; // Default value. ctl.m_iValue = 0; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Saturation */ ctl.m_iID = ctrlSat; // Control ID. ctl.m_sName = "Saturation"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = -100; // Minimum control value. ctl.m_iMax = 100; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 0; // Default value. ctl.m_iValue = 0; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Exposure Compensation */ ctl.m_iID = ctrlExpComp; // Control ID. ctl.m_sName = "Exposure Comp."; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = -10; // Minimum control value. ctl.m_iMax = 10; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 0; // Default value. ctl.m_iValue = 0; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); /* White Balance */ ctl.m_iID = ctrlWhiteBal; // Control ID. ctl.m_sName = "White Balance"; // Control name. ctl.m_iType = 3; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 8; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 1; // Default value. ctl.m_iValue = 1; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; ctl.m_vsMenu.push_back (std::string ("Off")); ctl.m_vsMenu.push_back (std::string ("Auto")); ctl.m_vsMenu.push_back (std::string ("Incandescent")); ctl.m_vsMenu.push_back (std::string ("Tungsten")); ctl.m_vsMenu.push_back (std::string ("Fluorescent")); ctl.m_vsMenu.push_back (std::string ("Indoor")); ctl.m_vsMenu.push_back (std::string ("Daylight")); ctl.m_vsMenu.push_back (std::string ("Cloudy")); ctl.m_vsMenu.push_back (std::string ("Custom")); m_victl.push_back (ctl); ctl.m_vsMenu.clear (); /* Exposure Mode */ ctl.m_iID = ctrlExMode; // Control ID. ctl.m_sName = "Exposure Mode"; // Control name. ctl.m_iType = 3; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 4; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 1; // Default value. ctl.m_iValue = 1; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; ctl.m_vsMenu.push_back (std::string ("Off")); ctl.m_vsMenu.push_back (std::string ("Normal")); ctl.m_vsMenu.push_back (std::string ("Short")); ctl.m_vsMenu.push_back (std::string ("Long")); ctl.m_vsMenu.push_back (std::string ("Custom")); m_victl.push_back (ctl); ctl.m_vsMenu.clear (); /* Meter Mode */ ctl.m_iID = ctrlMeterMode; // Control ID. ctl.m_sName = "Meter Mode"; // Control name. ctl.m_iType = 3; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 3; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 0; // Default value. ctl.m_iValue = 0; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; ctl.m_vsMenu.push_back (std::string ("Centre-weighted")); ctl.m_vsMenu.push_back (std::string ("Spot")); ctl.m_vsMenu.push_back (std::string ("Matrix")); ctl.m_vsMenu.push_back (std::string ("Custom")); m_victl.push_back (ctl); ctl.m_vsMenu.clear (); /* Exposure Time */ ctl.m_iID = ctrlExp; // Control ID. ctl.m_sName = "Exposure Time"; // Control name. ctl.m_iType = 6; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 1000000; // Maximum control value. ctl.m_iStep = 1000; // Control value step. ctl.m_iDefault = 10000; // Default value. ctl.m_iValue = 10000; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Analog Gain */ ctl.m_iID = ctrlAlgGain; // Control ID. ctl.m_sName = "Analog Gain"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 400; // Maximum control value. ctl.m_iStep = 10; // Control value step. ctl.m_iDefault = 100; // Default value. ctl.m_iValue = 100; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); #if HAVE_DIG_GAIN /* Digital Gain */ ctl.m_iID = ctrlDigGain; // Control ID. ctl.m_sName = "Digital Gain"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 6400; // Maximum control value. ctl.m_iStep = 100; // Control value step. ctl.m_iDefault = 100; // Default value. ctl.m_iValue = 100; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); #endif /* Red Gain */ ctl.m_iID = ctrlRedGain; // Control ID. ctl.m_sName = "Red Gain"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 800; // Maximum control value. ctl.m_iStep = 10; // Control value step. ctl.m_iDefault = 100; // Default value. ctl.m_iValue = 100; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Blue Gain */ ctl.m_iID = ctrlBlueGain; // Control ID. ctl.m_sName = "Blue Gain"; // Control name. ctl.m_iType = 4; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 800; // Maximum control value. ctl.m_iStep = 10; // Control value step. ctl.m_iDefault = 100; // Default value. ctl.m_iValue = 100; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Dynamic Noise Reduction */ ctl.m_iID = ctrlDenoise; // Control ID. ctl.m_sName = "Denoise"; // Control name. ctl.m_iType = 3; // Control type. ctl.m_iMin = 0; // Minimum control value. ctl.m_iMax = 3; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 0; // Default value. ctl.m_iValue = 0; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; ctl.m_vsMenu.push_back (std::string ("Off")); ctl.m_vsMenu.push_back (std::string ("Low")); ctl.m_vsMenu.push_back (std::string ("Medium")); ctl.m_vsMenu.push_back (std::string ("High")); m_victl.push_back (ctl); ctl.m_vsMenu.clear (); /* Image scale */ ctl.m_iID = ctrlScale; // Control ID. ctl.m_sName = "Image Scale"; // Control name. ctl.m_iType = 1; // Control type. ctl.m_iMin = 1; // Minimum control value. ctl.m_iMax = 5; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 1; // Default value. ctl.m_iValue = 1; // Current value. ctl.m_bEnable = true; ctl.m_bChanged = false; m_victl.push_back (ctl); /* Camera Run */ ctl.m_iID = ctrlRun; // Control ID. ctl.m_sName = "Camera Run"; // Control name. ctl.m_iType = 2; // Control type. ctl.m_iMin = 1; // Minimum control value. ctl.m_iMax = 5; // Maximum control value. ctl.m_iStep = 1; // Control value step. ctl.m_iDefault = 1; // Default value. ctl.m_iValue = 1; // Current value. ctl.m_bEnable = false; ctl.m_bChanged = false; m_victl.push_back (ctl); } /*** ApplyControls ************************************************************************************* Apply control settings to camera WJB 19/ 6/21 First draft */ void ControlWnd::ApplyControls (libcamera::ControlList &controls_) { controls_.clear (); /* Brightness */ if ( m_victl[ctrlBright].m_bEnable ) controls_.set(libcamera::controls::Brightness, m_victl[ctrlBright].m_iValue / 50.0 - 1.0); /* Contrast */ if ( m_victl[ctrlCont].m_bEnable ) controls_.set(libcamera::controls::Contrast, m_victl[ctrlCont].m_iValue / 100.0 + 1.0); /* Saturation */ if ( m_victl[ctrlSat].m_bEnable ) controls_.set(libcamera::controls::Saturation, m_victl[ctrlSat].m_iValue / 100.0 + 1.0); /* Exposure Compensation */ if ( m_victl[ctrlExpComp].m_bEnable ) controls_.set(libcamera::controls::ExposureValue, m_victl[ctrlExpComp].m_iValue / 4.0); /* White Balance */ if ( ( m_victl[ctrlWhiteBal].m_bEnable ) && ( m_victl[ctrlWhiteBal].m_iValue > 0 ) ) { controls_.set(libcamera::controls::AwbEnable, true); controls_.set(libcamera::controls::AwbMode, m_victl[ctrlWhiteBal].m_iValue - 1); } else { controls_.set(libcamera::controls::AwbEnable, false); } /* Exposure Mode */ if ( ( m_victl[ctrlExMode].m_bEnable ) && m_victl[ctrlExMode].m_iValue > 0 ) { controls_.set(libcamera::controls::AeEnable, true); controls_.set(libcamera::controls::AeExposureMode, m_victl[ctrlExMode].m_iValue - 1); } else { controls_.set(libcamera::controls::AeEnable, false); } /* Meter Mode */ if ( m_victl[ctrlMeterMode].m_bEnable ) controls_.set(libcamera::controls::AeMeteringMode, m_victl[ctrlMeterMode].m_iValue); /* Exposure Time */ if ( m_victl[ctrlExp].m_bEnable ) controls_.set(libcamera::controls::ExposureTime, m_victl[ctrlExp].m_iValue); // else controls_.set(libcamera::controls::ExposureTime, 0); /* Analog Gain */ if ( m_victl[ctrlAlgGain].m_bEnable ) controls_.set(libcamera::controls::AnalogueGain, m_victl[ctrlAlgGain].m_iValue / 100.0); #if HAVE_DIG_GAIN /* Digital Gain */ if ( m_victl[ctrlDigGain].m_bEnable ) controls_.set(libcamera::controls::DigitalGain, m_victl[ctrlDigGain].m_iValue / 100.0); #endif /* Red & Blue Gains */ if ( ( m_victl[ctrlRedGain].m_bEnable ) && ( m_victl[ctrlBlueGain].m_bEnable ) ) controls_.set(libcamera::controls::ColourGains, {float(m_victl[ctrlRedGain].m_iValue / 100.0), float(m_victl[ctrlBlueGain].m_iValue / 100.0)}); else if ( ( m_victl[ctrlWhiteBal].m_bEnable ) && ( m_victl[ctrlWhiteBal].m_iValue > 0 ) ) controls_.set(libcamera::controls::ColourGains, {0.0f, 0.0f}); // fval = picam->awb_gains_r; printf ("awb_gains_r = %10.3E\n", fval); /* Dynamic noise reduction */ if ( m_victl[ctrlDenoise].m_bEnable ) controls_.set(libcamera::controls::draft::NoiseReductionMode, libcamera::controls::draft::NoiseReductionModeEnum(m_victl[ctrlDenoise].m_iValue)); } /*** OnChoice ********************************************************* Update a camera control. Inputs: e = Choice event. Coding history: WJB 28/ 5/10 First draft. WJB 4/ 9/11 Revised for separate controls. */ void ControlWnd::OnChoice (wxCommandEvent &e) { int iCtrl = e.GetId () / 3; wxChoice * pchc = (wxChoice *) e.GetEventObject (); ImgCtl * pictl = &m_victl[iCtrl]; int iMin, iMax, iDefault, iValue; pictl->GetData (iMin, iMax, iDefault, iValue); iValue = pchc->GetSelection () + iMin; pictl->Set (iValue); } /*** OnCheckBox ********************************************************* Update a camera control. Inputs: e = Choice event. Coding history: WJB 4/ 9/11 Revised for separate controls. */ void ControlWnd::OnCheckBox (wxCommandEvent &e) { int iCtrl = e.GetId () / 3; wxCheckBox *pchk = (wxCheckBox *) e.GetEventObject (); bool bEnable = pchk->GetValue (); ImgCtl * pictl = &m_victl[iCtrl]; pictl->Enable (bEnable); if ( pictl->GetType () == 4 ) { wxSlider * psld = (wxSlider *) pchk->GetNextSibling (); wxSpinCtrl *pspin = (wxSpinCtrl *) psld->GetNextSibling (); psld->Enable (bEnable); pspin->Enable (bEnable); } else if ( pictl->GetType () == 6 ) { wxSpinCtrl *pspin = (wxSpinCtrl *) pchk->GetNextSibling (); pspin->Enable (bEnable); } if ( iCtrl == ctrlRedGain ) { m_victl[ctrlBlueGain].m_bEnable = bEnable; ((wxCheckBox *)FindWindow (3 * ctrlBlueGain))->SetValue (bEnable); FindWindow (3 * ctrlBlueGain + 1)->Enable (bEnable); FindWindow (3 * ctrlBlueGain + 2)->Enable (bEnable); } else if ( iCtrl == ctrlBlueGain ) { m_victl[ctrlRedGain].m_bEnable = bEnable; ((wxCheckBox *)FindWindow (3 * ctrlRedGain))->SetValue (bEnable); FindWindow (3 * ctrlRedGain + 1)->Enable (bEnable); FindWindow (3 * ctrlRedGain + 2)->Enable (bEnable); } } /*** OnSlider ********************************************************* Update a camera control. Inputs: e = Choice event. Coding history: WJB 4/ 9/11 Revised for separate controls. WJB 11/ 9/11 Display both slider and spin control. */ void ControlWnd::OnSlider (wxCommandEvent &e) { int iCtrl = e.GetId () / 3; wxSlider * psld = (wxSlider *) e.GetEventObject (); wxSpinCtrl *pspin = (wxSpinCtrl *) psld->GetNextSibling (); ImgCtl * pictl = &m_victl[iCtrl]; int iVal = psld->GetValue (); // printf ("OnSlider: this = %p, m_grabimg = %p, iCtrl = %d, pictl = %p, iVal = %d\n", // this, m_grabimg, iCtrl, pictl, iVal); pspin->SetValue (iVal); pictl->Set (iVal); } /*** OnSpinCtrl ********************************************************* Update a camera control. Inputs: e = Choice event. Coding history: WJB 11/ 9/11 Display both slider and spin control. */ void ControlWnd::OnSpinCtrl (wxSpinEvent &e) { int iCtrl = e.GetId () / 3; wxSpinCtrl *pspin = (wxSpinCtrl *) e.GetEventObject (); ImgCtl * pictl = &m_victl[iCtrl]; int iVal = pspin->GetValue (); // printf ("OnSpinCtrl: this = %p, m_grabimg = %p, iCtrl = %d, pictl = %p, iVal = %d\n", // this, m_grabimg, iCtrl, pictl, iVal); pictl->Set (iVal); if ( pictl->GetType () < 5 ) { wxSlider * psld = (wxSlider *) pspin->GetPrevSibling (); psld->SetValue (iVal); } }
36.983498
104
0.543727
Memotech-Bill
6121bd54330ddad58bd7d2f63de990cc1fca7162
1,830
cpp
C++
src/bind/enums.cpp
jonathf/pyvroom
7f7c755c763ddc416455ea8c5168b53ae1477084
[ "BSD-2-Clause" ]
13
2021-12-28T13:04:45.000Z
2022-01-06T22:05:51.000Z
src/bind/enums.cpp
VROOM-Project/pyvroom
7f7c755c763ddc416455ea8c5168b53ae1477084
[ "BSD-2-Clause" ]
26
2022-01-06T09:36:45.000Z
2022-03-26T11:43:14.000Z
src/bind/enums.cpp
VROOM-Project/pyvroom
7f7c755c763ddc416455ea8c5168b53ae1477084
[ "BSD-2-Clause" ]
4
2022-01-06T14:34:56.000Z
2022-03-29T11:53:48.000Z
#include <pybind11/pybind11.h> #include "structures/typedefs.h" namespace py = pybind11; void init_enums(py::module_ &m) { py::enum_<vroom::ROUTER>(m, "ROUTER") .value("OSRM", vroom::ROUTER::OSRM) .value("LIBOSRM", vroom::ROUTER::LIBOSRM) .value("ORS", vroom::ROUTER::ORS) .value("VALHALLA", vroom::ROUTER::VALHALLA) .export_values(); py::enum_<vroom::JOB_TYPE>(m, "JOB_TYPE") .value("SINGLE", vroom::JOB_TYPE::SINGLE) .value("PICKUP", vroom::JOB_TYPE::PICKUP) .value("DELIVERY", vroom::JOB_TYPE::DELIVERY) .export_values(); py::enum_<vroom::STEP_TYPE>(m, "STEP_TYPE") .value("START", vroom::STEP_TYPE::START) .value("JOB", vroom::STEP_TYPE::JOB) .value("BREAK", vroom::STEP_TYPE::BREAK) .value("END", vroom::STEP_TYPE::END) .export_values(); py::enum_<vroom::HEURISTIC>(m, "HEURISTIC") .value("BASIC", vroom::HEURISTIC::BASIC) .value("DYNAMIC", vroom::HEURISTIC::DYNAMIC) .value("INIT_ROUTES", vroom::HEURISTIC::INIT_ROUTES) .export_values(); py::enum_<vroom::INIT>(m, "INIT") .value("NONE", vroom::INIT::NONE) .value("HIGHER_AMOUNT", vroom::INIT::HIGHER_AMOUNT) .value("NEAREST", vroom::INIT::NEAREST) .value("FURTHEST", vroom::INIT::FURTHEST) .value("EARLIEST_DEADLINE", vroom::INIT::EARLIEST_DEADLINE) .export_values(); py::enum_<vroom::VIOLATION>(m, "VIOLATION") .value("LEAD_TIME", vroom::VIOLATION::LEAD_TIME) .value("DELAY", vroom::VIOLATION::DELAY) .value("LOAD", vroom::VIOLATION::LOAD) .value("MAX_TASKS", vroom::VIOLATION::MAX_TASKS) .value("SKILLS", vroom::VIOLATION::SKILLS) .value("PRECEDENCE", vroom::VIOLATION::PRECEDENCE) .value("MISSING_BREAK", vroom::VIOLATION::MISSING_BREAK) .export_values(); }
34.528302
65
0.636612
jonathf
6122cab5f27d1d277b43618ff1bfc370bbfa5e8b
1,585
cpp
C++
gurobi912/linux64/examples/c++/lp_c++.cpp
UtileFuzzball/test_eran
34d5f49dd4cac2a95cb915499a57a8a11829b93e
[ "Apache-2.0" ]
null
null
null
gurobi912/linux64/examples/c++/lp_c++.cpp
UtileFuzzball/test_eran
34d5f49dd4cac2a95cb915499a57a8a11829b93e
[ "Apache-2.0" ]
null
null
null
gurobi912/linux64/examples/c++/lp_c++.cpp
UtileFuzzball/test_eran
34d5f49dd4cac2a95cb915499a57a8a11829b93e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021, Gurobi Optimization, LLC */ /* This example reads an LP model from a file and solves it. If the model is infeasible or unbounded, the example turns off presolve and solves the model again. If the model is infeasible, the example computes an Irreducible Inconsistent Subsystem (IIS), and writes it to a file */ #include "gurobi_c++.h" using namespace std; int main(int argc, char *argv[]) { if (argc < 2) { cout << "Usage: lp_c++ filename" << endl; return 1; } try { GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env, argv[1]); model.optimize(); int optimstatus = model.get(GRB_IntAttr_Status); if (optimstatus == GRB_INF_OR_UNBD) { model.set(GRB_IntParam_Presolve, 0); model.optimize(); optimstatus = model.get(GRB_IntAttr_Status); } if (optimstatus == GRB_OPTIMAL) { double objval = model.get(GRB_DoubleAttr_ObjVal); cout << "Optimal objective: " << objval << endl; } else if (optimstatus == GRB_INFEASIBLE) { cout << "Model is infeasible" << endl; // compute and write out IIS model.computeIIS(); model.write("model.ilp"); } else if (optimstatus == GRB_UNBOUNDED) { cout << "Model is unbounded" << endl; } else { cout << "Optimization was stopped with status = " << optimstatus << endl; } } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch (...) { cout << "Error during optimization" << endl; } return 0; }
25.983607
68
0.618927
UtileFuzzball
61230ace2f9b1752d62cdd15a133f9914978b183
2,002
cpp
C++
staging_vespalib/src/vespa/vespalib/objects/objectdumper.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
staging_vespalib/src/vespa/vespalib/objects/objectdumper.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
staging_vespalib/src/vespa/vespalib/objects/objectdumper.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "objectdumper.h" #include <vespa/vespalib/util/stringfmt.h> namespace vespalib { void ObjectDumper::addIndent() { int n = _currIndent; if (n < 0) { n = 0; } _str.append(vespalib::string(n, ' ')); } void ObjectDumper::addLine(const vespalib::string &line) { addIndent(); _str.append(line); _str.push_back('\n'); } void ObjectDumper::openScope() { _currIndent += _indent; } void ObjectDumper::closeScope() { _currIndent -= _indent; } ObjectDumper::ObjectDumper(int indent) : _str(), _indent(indent), _currIndent(0) { } ObjectDumper::~ObjectDumper() = default; //----------------------------------------------------------------------------- void ObjectDumper::openStruct(const vespalib::string &name, const vespalib::string &type) { if (name.empty()) { addLine(make_string("%s {", type.c_str())); } else { addLine(make_string("%s: %s {", name.c_str(), type.c_str())); } openScope(); } void ObjectDumper::closeStruct() { closeScope(); addLine("}"); } void ObjectDumper::visitBool(const vespalib::string &name, bool value) { addLine(make_string("%s: %s", name.c_str(), value? "true" : "false")); } void ObjectDumper::visitInt(const vespalib::string &name, int64_t value) { addLine(make_string("%s: %" PRId64 "", name.c_str(), value)); } void ObjectDumper::visitFloat(const vespalib::string &name, double value) { addLine(make_string("%s: %g", name.c_str(), value)); } void ObjectDumper::visitString(const vespalib::string &name, const vespalib::string &value) { addLine(make_string("%s: '%s'", name.c_str(), value.c_str())); } void ObjectDumper::visitNull(const vespalib::string &name) { addLine(make_string("%s: <NULL>", name.c_str())); } void ObjectDumper::visitNotImplemented() { addLine("<member visit not implemented>"); } } // namespace vespalib
19.436893
104
0.62987
Anlon-Burke
6128a4c15889980b3b1ee077a76d527bdf67d19a
3,157
hpp
C++
include/hip/hcc_detail/program_state.hpp
baryluk/HIP
cb1a3bb60f1c89c6967eefb432f4762182a113f2
[ "MIT" ]
7
2022-03-23T07:04:20.000Z
2022-03-30T02:44:42.000Z
include/hip/hcc_detail/program_state.hpp
baryluk/HIP
cb1a3bb60f1c89c6967eefb432f4762182a113f2
[ "MIT" ]
null
null
null
include/hip/hcc_detail/program_state.hpp
baryluk/HIP
cb1a3bb60f1c89c6967eefb432f4762182a113f2
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <hsa/amd_hsa_kernel_code.h> #include <hsa/hsa.h> #include <hsa/hsa_ext_amd.h> #include <hsa/hsa_ven_amd_loader.h> #include <cstddef> #include <cstdint> #include <cstdlib> #include <hip/hip_common.h> struct ihipModuleSymbol_t; using hipFunction_t = ihipModuleSymbol_t*; namespace hip_impl { // This section contains internal APIs that // needs to be exported #ifdef __GNUC__ #pragma GCC visibility push (default) #endif struct kernarg_impl; class kernarg { public: kernarg(); kernarg(kernarg&&); ~kernarg(); std::uint8_t* data(); std::size_t size(); void reserve(std::size_t); void resize(std::size_t); private: kernarg_impl* impl; }; class kernargs_size_align; class program_state_impl; class program_state { public: program_state(); ~program_state(); program_state(const program_state&) = delete; hipFunction_t kernel_descriptor(std::uintptr_t, hsa_agent_t); kernargs_size_align get_kernargs_size_align(std::uintptr_t); hsa_executable_t load_executable(const char*, const size_t, hsa_executable_t, hsa_agent_t); hsa_executable_t load_executable_no_copy(const char*, const size_t, hsa_executable_t, hsa_agent_t); void* global_addr_by_name(const char* name); private: friend class agent_globals_impl; program_state_impl* impl; }; class kernargs_size_align { public: std::size_t size(std::size_t n) const; std::size_t alignment(std::size_t n) const; const void* getHandle() const {return handle;}; private: const void* handle; friend kernargs_size_align program_state::get_kernargs_size_align(std::uintptr_t); }; #ifdef __GNUC__ #pragma GCC visibility pop #endif inline __attribute__((visibility("hidden"))) program_state& get_program_state() { static program_state ps; return ps; } } // Namespace hip_impl.
29.231481
86
0.714602
baryluk
6129455e861a8422a65a57f3961ec70be44e7e88
1,789
hh
C++
test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh
centreon-lab/centreon-connectors
3e80bea5c5d999bbce0fcb33b819ddc1cab4d917
[ "Apache-2.0" ]
5
2015-09-04T11:54:52.000Z
2016-12-29T02:36:21.000Z
test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh
centreon-lab/centreon-connectors
3e80bea5c5d999bbce0fcb33b819ddc1cab4d917
[ "Apache-2.0" ]
19
2015-07-29T10:00:06.000Z
2022-03-09T08:42:10.000Z
test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/plugin.hh
centreon-lab/centreon-connectors
3e80bea5c5d999bbce0fcb33b819ddc1cab4d917
[ "Apache-2.0" ]
6
2016-02-05T15:12:03.000Z
2021-09-02T19:40:35.000Z
/* ** Copyright 2011-2013 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CCB_CONNECTOR_PLUGIN #define CCB_CONNECTOR_PLUGIN #include <list> #include <map> #include <string> #include <sys/types.h> #include <vector> #include "com/centreon/benchmark/connector/benchmark.hh" #include "com/centreon/benchmark/connector/namespace.hh" CCB_CONNECTOR_BEGIN() /** * @class plugin plugin.hh "com/centreon/benchmark/connector/plugin.hh" * @brief Implementation of benchmark for testing nagios plugin. * * This class is an implementation of benchmark for testing nagios * plugin. */ class plugin : public benchmark { public: plugin(std::string const& commands_file, std::list<std::string> const& args); plugin(plugin const& right); ~plugin() throw(); plugin& operator=(plugin const& right); void run(); private: void _cleanup(); plugin& _internal_copy(plugin const& right); void _recv_data(int fd); void _start_plugin(char** args); void _wait_plugin(bool block); std::list<std::string> _args; std::vector<std::string> _commands; std::string _commands_file; unsigned int _current_running; std::map<pid_t, int> _pid; }; CCB_CONNECTOR_END() #endif // !CCB_CONNECTOR_PLUGIN
27.523077
79
0.735048
centreon-lab
612b25568304beac9252ad293051a6b32b490e51
640
hpp
C++
nall/algorithm.hpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
nall/algorithm.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
nall/algorithm.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#pragma once #include <nall/traits.hpp> #undef min #undef max namespace nall { namespace { template<typename T, typename U> auto min(const T& t, const U& u) -> T { return t < u ? t : u; } template<typename T, typename U, typename... P> auto min(const T& t, const U& u, P&&... p) -> T { return t < u ? min(t, forward<P>(p)...) : min(u, forward<P>(p)...); } template<typename T, typename U> auto max(const T& t, const U& u) -> T { return t > u ? t : u; } template<typename T, typename U, typename... P> auto max(const T& t, const U& u, P&&... p) -> T { return t > u ? max(t, forward<P>(p)...) : max(u, forward<P>(p)...); } }}
23.703704
97
0.578125
13824125580
612b7ef1217b575603d93e385bdd11d3036066c3
653
hpp
C++
Include/Math.hpp
cschladetsch/TurtleGraphics
93fcec0831761a6c58592a452da54b01fd3f89d1
[ "MIT" ]
2
2021-08-14T17:36:11.000Z
2021-10-21T04:53:06.000Z
Include/Math.hpp
cschladetsch/TurtleGraphics
93fcec0831761a6c58592a452da54b01fd3f89d1
[ "MIT" ]
null
null
null
Include/Math.hpp
cschladetsch/TurtleGraphics
93fcec0831761a6c58592a452da54b01fd3f89d1
[ "MIT" ]
null
null
null
#pragma once #include <cmath> namespace TurtleGraphics { constexpr float float_epsilon = 0.001f; constexpr float double_epsilon = 0.00001f; inline bool ApproxEqual(const float a, const float b) { return fabs(a - b) < float_epsilon; } inline bool ApproxEqual(const double a, const double b) { return fabs(a - static_cast<long double>(b)) < double_epsilon; } inline int Round(const float x) { return x < 0 ? static_cast<int>(x - 0.5f) : static_cast<int>(x + 0.5f); } template <typename Ty> Ty Clamp(const Ty x, Ty min, Ty max) { return x < min ? min : x > max ? max : x; } } // namespace TurtleGraphics
23.321429
76
0.655436
cschladetsch
612b89d2508c51039bb46e37ae3fadc8963ded74
10,582
cpp
C++
game/server/tfo/weapon_stg44.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
13
2016-04-05T23:23:16.000Z
2022-03-20T11:06:04.000Z
game/server/tfo/weapon_stg44.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
null
null
null
game/server/tfo/weapon_stg44.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
4
2016-04-05T23:23:19.000Z
2021-05-16T05:09:46.000Z
//========= Copyright Bernt Andreas Eide, All rights reserved. ============// // // Purpose: MP44 / STG44 // //=============================================================================// #include "cbase.h" #include "basehlcombatweapon.h" #include "NPCevent.h" #include "basecombatcharacter.h" #include "AI_BaseNPC.h" #include "player.h" #include "game.h" #include "in_buttons.h" #include "grenade_ar2.h" #include "AI_Memory.h" #include "soundent.h" #include "rumble_shared.h" #include "gamestats.h" #include "te_effect_dispatch.h" #include "particle_parse.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class CWeaponSTG44 : public CHLSelectFireMachineGun { DECLARE_DATADESC(); public: DECLARE_CLASS( CWeaponSTG44, CHLSelectFireMachineGun ); CWeaponSTG44(); DECLARE_SERVERCLASS(); void Precache( void ); void AddViewKick( void ); int GetOverloadCapacity() { return 10; } void ItemPostFrame( void ); int GetMinBurst() { return 2; } int GetMaxBurst() { return 5; } virtual void Equip( CBaseCombatCharacter *pOwner ); bool Reload( void ); float GetFireRate( void ) { return 0.100f; } int CapabilitiesGet( void ) { return bits_CAP_WEAPON_RANGE_ATTACK1; } virtual const Vector& GetBulletSpread( void ) { static Vector cone; if (m_bIsIronsighted) cone = VECTOR_CONE_1DEGREES; else cone = VECTOR_CONE_7DEGREES; return cone; } const WeaponProficiencyInfo_t *GetProficiencyValues(); void FireNPCPrimaryAttack( CBaseCombatCharacter *pOperator, Vector &vecShootOrigin, Vector &vecShootDir ); void Operator_ForceNPCFire( CBaseCombatCharacter *pOperator, bool bSecondary ); void Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ); DECLARE_ACTTABLE(); }; IMPLEMENT_SERVERCLASS_ST(CWeaponSTG44, DT_WeaponSTG44) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( weapon_stg44, CWeaponSTG44 ); PRECACHE_WEAPON_REGISTER(weapon_stg44); BEGIN_DATADESC( CWeaponSTG44 ) END_DATADESC() acttable_t CWeaponSTG44::m_acttable[] = { { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_SMG1, true }, { ACT_RELOAD, ACT_RELOAD_SMG1, true }, { ACT_IDLE, ACT_IDLE_SMG1, true }, { ACT_IDLE_ANGRY, ACT_IDLE_ANGRY_SMG1, true }, { ACT_WALK, ACT_WALK_RIFLE, true }, { ACT_WALK_AIM, ACT_WALK_AIM_RIFLE, true }, // Readiness activities (not aiming) { ACT_IDLE_RELAXED, ACT_IDLE_SMG1_RELAXED, false },//never aims { ACT_IDLE_STIMULATED, ACT_IDLE_SMG1_STIMULATED, false }, { ACT_IDLE_AGITATED, ACT_IDLE_ANGRY_SMG1, false },//always aims { ACT_WALK_RELAXED, ACT_WALK_RIFLE_RELAXED, false },//never aims { ACT_WALK_STIMULATED, ACT_WALK_RIFLE_STIMULATED, false }, { ACT_WALK_AGITATED, ACT_WALK_AIM_RIFLE, false },//always aims { ACT_RUN_RELAXED, ACT_RUN_RIFLE_RELAXED, false },//never aims { ACT_RUN_STIMULATED, ACT_RUN_RIFLE_STIMULATED, false }, { ACT_RUN_AGITATED, ACT_RUN_AIM_RIFLE, false },//always aims // Readiness activities (aiming) { ACT_IDLE_AIM_RELAXED, ACT_IDLE_SMG1_RELAXED, false },//never aims { ACT_IDLE_AIM_STIMULATED, ACT_IDLE_AIM_RIFLE_STIMULATED, false }, { ACT_IDLE_AIM_AGITATED, ACT_IDLE_ANGRY_SMG1, false },//always aims { ACT_WALK_AIM_RELAXED, ACT_WALK_RIFLE_RELAXED, false },//never aims { ACT_WALK_AIM_STIMULATED, ACT_WALK_AIM_RIFLE_STIMULATED, false }, { ACT_WALK_AIM_AGITATED, ACT_WALK_AIM_RIFLE, false },//always aims { ACT_RUN_AIM_RELAXED, ACT_RUN_RIFLE_RELAXED, false },//never aims { ACT_RUN_AIM_STIMULATED, ACT_RUN_AIM_RIFLE_STIMULATED, false }, { ACT_RUN_AIM_AGITATED, ACT_RUN_AIM_RIFLE, false },//always aims //End readiness activities { ACT_WALK_AIM, ACT_WALK_AIM_RIFLE, true }, { ACT_WALK_CROUCH, ACT_WALK_CROUCH_RIFLE, true }, { ACT_WALK_CROUCH_AIM, ACT_WALK_CROUCH_AIM_RIFLE, true }, { ACT_RUN, ACT_RUN_RIFLE, true }, { ACT_RUN_AIM, ACT_RUN_AIM_RIFLE, true }, { ACT_RUN_CROUCH, ACT_RUN_CROUCH_RIFLE, true }, { ACT_RUN_CROUCH_AIM, ACT_RUN_CROUCH_AIM_RIFLE, true }, { ACT_GESTURE_RANGE_ATTACK1, ACT_GESTURE_RANGE_ATTACK_SMG1, true }, { ACT_RANGE_ATTACK1_LOW, ACT_RANGE_ATTACK_SMG1_LOW, true }, { ACT_COVER_LOW, ACT_COVER_SMG1_LOW, false }, { ACT_RANGE_AIM_LOW, ACT_RANGE_AIM_SMG1_LOW, false }, { ACT_RELOAD_LOW, ACT_RELOAD_SMG1_LOW, false }, { ACT_GESTURE_RELOAD, ACT_GESTURE_RELOAD_SMG1, true }, { ACT_HL2MP_IDLE, ACT_HL2MP_IDLE_SMG1, false }, { ACT_HL2MP_RUN, ACT_HL2MP_RUN_SMG1, false }, { ACT_HL2MP_IDLE_CROUCH, ACT_HL2MP_IDLE_CROUCH_SMG1, false }, { ACT_HL2MP_WALK_CROUCH, ACT_HL2MP_WALK_CROUCH_SMG1, false }, { ACT_HL2MP_GESTURE_RANGE_ATTACK, ACT_HL2MP_GESTURE_RANGE_ATTACK_SMG1, false }, { ACT_HL2MP_GESTURE_RELOAD, ACT_GESTURE_RELOAD_SMG1, false }, { ACT_HL2MP_JUMP, ACT_HL2MP_JUMP_SMG1, false }, { ACT_RANGE_ATTACK1, ACT_RANGE_ATTACK_SMG1, false }, }; IMPLEMENT_ACTTABLE(CWeaponSTG44); //========================================================= CWeaponSTG44::CWeaponSTG44( ) { m_fMinRange1 = 0;// No minimum range. m_fMaxRange1 = 1400; m_bMagazineStyleReloads = true; // Magazine style reloads m_bAltFiresUnderwater = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSTG44::Precache( void ) { BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: Give this weapon longer range when wielded by an ally NPC. //----------------------------------------------------------------------------- void CWeaponSTG44::Equip( CBaseCombatCharacter *pOwner ) { if( pOwner->Classify() == CLASS_PLAYER_ALLY ) { m_fMaxRange1 = 3000; } else { m_fMaxRange1 = 1400; } BaseClass::Equip( pOwner ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSTG44::FireNPCPrimaryAttack( CBaseCombatCharacter *pOperator, Vector &vecShootOrigin, Vector &vecShootDir ) { // FIXME: use the returned number of bullets to account for >10hz firerate WeaponSoundRealtime( SINGLE_NPC ); CSoundEnt::InsertSound( SOUND_COMBAT|SOUND_CONTEXT_GUNFIRE, pOperator->GetAbsOrigin(), SOUNDENT_VOLUME_MACHINEGUN, 0.2, pOperator, SOUNDENT_CHANNEL_WEAPON, pOperator->GetEnemy() ); pOperator->FireBullets( 1, vecShootOrigin, vecShootDir, VECTOR_CONE_PRECALCULATED, MAX_TRACE_LENGTH, m_iPrimaryAmmoType, 2, entindex(), 0 ); pOperator->DoMuzzleFlash(); m_iClip1 = m_iClip1 - 1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSTG44::Operator_ForceNPCFire( CBaseCombatCharacter *pOperator, bool bSecondary ) { // Ensure we have enough rounds in the clip m_iClip1++; Vector vecShootOrigin, vecShootDir; QAngle angShootDir; GetAttachment( LookupAttachment( "muzzle" ), vecShootOrigin, angShootDir ); AngleVectors( angShootDir, &vecShootDir ); FireNPCPrimaryAttack( pOperator, vecShootOrigin, vecShootDir ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSTG44::Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ) { switch( pEvent->event ) { case EVENT_WEAPON_SMG1: { Vector vecShootOrigin, vecShootDir; QAngle angDiscard; // Support old style attachment point firing if ((pEvent->options == NULL) || (pEvent->options[0] == '\0') || (!pOperator->GetAttachment(pEvent->options, vecShootOrigin, angDiscard))) { vecShootOrigin = pOperator->Weapon_ShootPosition(); } CAI_BaseNPC *npc = pOperator->MyNPCPointer(); ASSERT( npc != NULL ); vecShootDir = npc->GetActualShootTrajectory( vecShootOrigin ); FireNPCPrimaryAttack( pOperator, vecShootOrigin, vecShootDir ); } break; default: BaseClass::Operator_HandleAnimEvent( pEvent, pOperator ); break; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CWeaponSTG44::Reload( void ) { bool fRet; float fCacheTime = m_flNextSecondaryAttack; fRet = DefaultReload( GetMaxClip1(), GetMaxClip2(), ACT_VM_RELOAD ); if ( fRet ) { // Undo whatever the reload process has done to our secondary // attack timer. We allow you to interrupt reloading to fire // a grenade. m_flNextSecondaryAttack = GetOwner()->m_flNextAttack = fCacheTime; WeaponSound( RELOAD ); CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); CEffectData data; data.m_vOrigin = pOwner->WorldSpaceCenter() + RandomVector( 0, 0 ); data.m_vAngles = QAngle( 90, random->RandomInt( 0, 360 ), 0 ); data.m_nEntIndex = entindex(); DispatchEffect( "ClipEject", data ); } return fRet; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponSTG44::AddViewKick( void ) { #define EASY_DAMPEN 0.5f #define MAX_VERTICAL_KICK 1.0f //Degrees #define SLIDE_LIMIT 2.0f //Seconds //Get the view kick CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( pPlayer == NULL ) return; DoMachineGunKick( pPlayer, EASY_DAMPEN, MAX_VERTICAL_KICK, m_fFireDuration, SLIDE_LIMIT ); } void CWeaponSTG44::ItemPostFrame( void ) { BaseClass::ItemPostFrame(); CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( pPlayer == NULL ) return; // Ammo Fix int CurrAmmo = pPlayer->GetAmmoCount(m_iPrimaryAmmoType); if ( CurrAmmo <= 29 && CurrAmmo >= 1 ) { pPlayer->RemoveAmmo( CurrAmmo, m_iPrimaryAmmoType ); } } //---------------------------------------------------------------------------- const WeaponProficiencyInfo_t *CWeaponSTG44::GetProficiencyValues() { static WeaponProficiencyInfo_t proficiencyTable[] = { { 7.0, 0.75 }, { 5.00, 0.75 }, { 10.0/3.0, 0.75 }, { 5.0/3.0, 0.75 }, { 1.00, 1.0 }, }; COMPILE_TIME_ASSERT( ARRAYSIZE(proficiencyTable) == WEAPON_PROFICIENCY_PERFECT + 1); return proficiencyTable; }
32.965732
181
0.626347
BerntA
612b9a750ba7eaff8b20a1e339279183d01df9ff
4,488
cpp
C++
tf2_src/utils/vgui_panel_zoo/QueryBoxDemo.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/utils/vgui_panel_zoo/QueryBoxDemo.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/utils/vgui_panel_zoo/QueryBoxDemo.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "DemoPage.h" #include <VGUI/IVGui.h> #include <vgui_controls/Controls.h> #include <Keyvalues.h> #include <vgui_controls/Button.h> #include <vgui_controls/QueryBox.h> using namespace vgui; // Query boxes are windows that pop up in response to events. // They are useful for asking questions (like... "Are you sure you want to do this?"). // In this example we will trigger the opening of a query box when // a button is pressed. // Query boxes are Message boxes that have an OK and a Cancel button, // each button may be linked to an additional command in order to trigger an // appropriate response. class QueryBoxDemo: public DemoPage { public: QueryBoxDemo(Panel *parent, const char *name); ~QueryBoxDemo(); void OnButtonClicked(); void ShowQueryBox(); void OnOK(); void OnCancel(); private: Button *m_pButton; DECLARE_PANELMAP(); }; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- QueryBoxDemo::QueryBoxDemo(Panel *parent, const char *name) : DemoPage(parent, name) { // Create a button to trigger the message box. m_pButton = new Button(this, "AButton", "Click Me For A Question"); // Size the button to its text. m_pButton->SizeToContents(); // Set its position. m_pButton->SetPos(100, 100); // Install a command that will be executed when the button is pressed // Here we use a KeyValues command, this is mapped using the Message map // below to a function. m_pButton->SetCommand(new KeyValues ("ButtonClicked")); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- QueryBoxDemo::~QueryBoxDemo() { } //----------------------------------------------------------------------------- // Purpose: Respond to a message based action signal // Popup the query box. //----------------------------------------------------------------------------- void QueryBoxDemo::OnButtonClicked() { ivgui()->DPrintf("Button was clicked.\n"); // When the button is clicked we open the message box in response. ShowQueryBox(); } //----------------------------------------------------------------------------- // Purpose: Display a query box //----------------------------------------------------------------------------- void QueryBoxDemo::ShowQueryBox() { // create a new message box. // The first arg is the name of the window and will be across the top. // The second arg is the text that will appear in the message box. QueryBox *pQuery = new QueryBox ("Message Window", "Will you pick OK or Cancel?"); // Make ourselves the target of the button messages pQuery->AddActionSignalTarget(this); // Install the message to be sent when the ok button is clicked. pQuery->SetOKCommand(new KeyValues("OKClicked")); // Install the message to be sent when the cancel button is clicked. pQuery->SetCancelCommand(new KeyValues("Cancel")); // This command will pop up the message box and hold it there until we click // a button. When a button is clicked the query box object is destroyed. pQuery->DoModal(); } //----------------------------------------------------------------------------- // Purpose: Respond to a message based action signal // Respond to the OK button in the query box. //----------------------------------------------------------------------------- void QueryBoxDemo::OnOK() { ivgui()->DPrintf("Query received the OK.\n"); } //----------------------------------------------------------------------------- // Purpose: Respond to a message based action signal // Respond to the Cancel button in the query box //----------------------------------------------------------------------------- void QueryBoxDemo::OnCancel() { ivgui()->DPrintf("Query was canceled.\n"); } MessageMapItem_t QueryBoxDemo::m_MessageMap[] = { MAP_MESSAGE( QueryBoxDemo, "ButtonClicked", OnButtonClicked ), MAP_MESSAGE( QueryBoxDemo, "OKClicked", OnOK ), MAP_MESSAGE( QueryBoxDemo, "Cancel", OnCancel ), }; IMPLEMENT_PANELMAP(QueryBoxDemo, DemoPage); Panel* QueryBoxDemo_Create(Panel *parent) { return new QueryBoxDemo(parent, "QueryBoxDemo"); }
30.324324
86
0.552362
IamIndeedGamingAsHardAsICan03489
612be61ed565e42e7d013d3e11699fdc54e7f1f8
4,004
hpp
C++
Library/Deps/MessagePack/Include/msgpack/preprocessor/iteration/iterate.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
Library/Deps/MessagePack/Include/msgpack/preprocessor/iteration/iterate.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
Library/Deps/MessagePack/Include/msgpack/preprocessor/iteration/iterate.hpp
rneogns/simpleio
20830a2b9b22c31eab23508acd25b275b53103c9
[ "MIT" ]
null
null
null
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * 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) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef MSGPACK_PREPROCESSOR_ITERATION_ITERATE_HPP # define MSGPACK_PREPROCESSOR_ITERATION_ITERATE_HPP # # include <msgpack/preprocessor/arithmetic/dec.hpp> # include <msgpack/preprocessor/arithmetic/inc.hpp> # include <msgpack/preprocessor/array/elem.hpp> # include <msgpack/preprocessor/array/size.hpp> # include <msgpack/preprocessor/cat.hpp> # include <msgpack/preprocessor/slot/slot.hpp> # include <msgpack/preprocessor/tuple/elem.hpp> # # /* MSGPACK_PP_ITERATION_DEPTH */ # # define MSGPACK_PP_ITERATION_DEPTH() 0 # # /* MSGPACK_PP_ITERATION */ # # define MSGPACK_PP_ITERATION() MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_, MSGPACK_PP_ITERATION_DEPTH()) # # /* MSGPACK_PP_ITERATION_START && MSGPACK_PP_ITERATION_FINISH */ # # define MSGPACK_PP_ITERATION_START() MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_START_, MSGPACK_PP_ITERATION_DEPTH()) # define MSGPACK_PP_ITERATION_FINISH() MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FINISH_, MSGPACK_PP_ITERATION_DEPTH()) # # /* MSGPACK_PP_ITERATION_FLAGS */ # # define MSGPACK_PP_ITERATION_FLAGS() (MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FLAGS_, MSGPACK_PP_ITERATION_DEPTH())()) # # /* MSGPACK_PP_FRAME_ITERATION */ # # define MSGPACK_PP_FRAME_ITERATION(i) MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_, i) # # /* MSGPACK_PP_FRAME_START && MSGPACK_PP_FRAME_FINISH */ # # define MSGPACK_PP_FRAME_START(i) MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_START_, i) # define MSGPACK_PP_FRAME_FINISH(i) MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FINISH_, i) # # /* MSGPACK_PP_FRAME_FLAGS */ # # define MSGPACK_PP_FRAME_FLAGS(i) (MSGPACK_PP_CAT(MSGPACK_PP_ITERATION_FLAGS_, i)()) # # /* MSGPACK_PP_RELATIVE_ITERATION */ # # define MSGPACK_PP_RELATIVE_ITERATION(i) MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_) # # define MSGPACK_PP_RELATIVE_0(m) MSGPACK_PP_CAT(m, MSGPACK_PP_ITERATION_DEPTH()) # define MSGPACK_PP_RELATIVE_1(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH())) # define MSGPACK_PP_RELATIVE_2(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH()))) # define MSGPACK_PP_RELATIVE_3(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH())))) # define MSGPACK_PP_RELATIVE_4(m) MSGPACK_PP_CAT(m, MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_DEC(MSGPACK_PP_ITERATION_DEPTH()))))) # # /* MSGPACK_PP_RELATIVE_START && MSGPACK_PP_RELATIVE_FINISH */ # # define MSGPACK_PP_RELATIVE_START(i) MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_START_) # define MSGPACK_PP_RELATIVE_FINISH(i) MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_FINISH_) # # /* MSGPACK_PP_RELATIVE_FLAGS */ # # define MSGPACK_PP_RELATIVE_FLAGS(i) (MSGPACK_PP_CAT(MSGPACK_PP_RELATIVE_, i)(MSGPACK_PP_ITERATION_FLAGS_)()) # # /* MSGPACK_PP_ITERATE */ # # define MSGPACK_PP_ITERATE() MSGPACK_PP_CAT(MSGPACK_PP_ITERATE_, MSGPACK_PP_INC(MSGPACK_PP_ITERATION_DEPTH())) # # define MSGPACK_PP_ITERATE_1 <msgpack/preprocessor/iteration/detail/iter/forward1.hpp> # define MSGPACK_PP_ITERATE_2 <msgpack/preprocessor/iteration/detail/iter/forward2.hpp> # define MSGPACK_PP_ITERATE_3 <msgpack/preprocessor/iteration/detail/iter/forward3.hpp> # define MSGPACK_PP_ITERATE_4 <msgpack/preprocessor/iteration/detail/iter/forward4.hpp> # define MSGPACK_PP_ITERATE_5 <msgpack/preprocessor/iteration/detail/iter/forward5.hpp> # # endif
48.240964
146
0.731518
rneogns
612da374e6268428770467a74984697b73f626f1
7,226
cpp
C++
export/debug/macos/obj/src/__ASSET__flixel_flixel_ui_img_finger_small_png.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
export/debug/macos/obj/src/__ASSET__flixel_flixel_ui_img_finger_small_png.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
export/debug/macos/obj/src/__ASSET__flixel_flixel_ui_img_finger_small_png.cpp
EnvyBun/KB-FNF-MOD
f7541661229c587bf99f0508cc3eba7043f8c177
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED___ASSET__flixel_flixel_ui_img_finger_small_png #include <__ASSET__flixel_flixel_ui_img_finger_small_png.h> #endif #ifndef INCLUDED_haxe_Resource #include <haxe/Resource.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics_ImageBuffer #include <lime/graphics/ImageBuffer.h> #endif #ifndef INCLUDED_lime_graphics_ImageType #include <lime/graphics/ImageType.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_a8b28c08cd7936ec_346_new,"__ASSET__flixel_flixel_ui_img_finger_small_png","new",0x4e817064,"__ASSET__flixel_flixel_ui_img_finger_small_png.new","lime/_internal/macros/AssetsMacro.hx",346,0xc651f030) HX_LOCAL_STACK_FRAME(_hx_pos_db845bbd0c26ed3d_600_boot,"__ASSET__flixel_flixel_ui_img_finger_small_png","boot",0x5ad9e7ae,"__ASSET__flixel_flixel_ui_img_finger_small_png.boot","ManifestResources.hx",600,0xf77aa668) void __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__construct( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type){ HX_STACKFRAME(&_hx_pos_a8b28c08cd7936ec_346_new) HXLINE( 375) super::__construct(null(),null(),null(),null(),null(),null(),null()); HXLINE( 377) this->_hx___fromBytes(::haxe::Resource_obj::getBytes(::__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName),null()); } Dynamic __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__CreateEmpty() { return new __ASSET__flixel_flixel_ui_img_finger_small_png_obj; } void *__ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_vtable = 0; Dynamic __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > _hx_result = new __ASSET__flixel_flixel_ui_img_finger_small_png_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4],inArgs[5],inArgs[6]); return _hx_result; } bool __ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x33f052f7) { return inClassId==(int)0x00000001 || inClassId==(int)0x33f052f7; } else { return inClassId==(int)0x57173132; } } ::String __ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName; ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__new( ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) { ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > __this = new __ASSET__flixel_flixel_ui_img_finger_small_png_obj(); __this->__construct(buffer,offsetX,offsetY,width,height,color,type); return __this; } ::hx::ObjectPtr< __ASSET__flixel_flixel_ui_img_finger_small_png_obj > __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__alloc(::hx::Ctx *_hx_ctx, ::lime::graphics::ImageBuffer buffer, ::Dynamic offsetX, ::Dynamic offsetY, ::Dynamic width, ::Dynamic height, ::Dynamic color, ::lime::graphics::ImageType type) { __ASSET__flixel_flixel_ui_img_finger_small_png_obj *__this = (__ASSET__flixel_flixel_ui_img_finger_small_png_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(__ASSET__flixel_flixel_ui_img_finger_small_png_obj), true, "__ASSET__flixel_flixel_ui_img_finger_small_png")); *(void **)__this = __ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_vtable; __this->__construct(buffer,offsetX,offsetY,width,height,color,type); return __this; } __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__ASSET__flixel_flixel_ui_img_finger_small_png_obj() { } bool __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"resourceName") ) { outValue = ( resourceName ); return true; } } return false; } bool __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 12: if (HX_FIELD_EQ(inName,"resourceName") ) { resourceName=ioValue.Cast< ::String >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *__ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticStorageInfo[] = { {::hx::fsString,(void *) &__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName,HX_("resourceName",39,7a,62,90)}, { ::hx::fsUnknown, 0, null()} }; #endif static void __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName,"resourceName"); }; #ifdef HXCPP_VISIT_ALLOCS static void __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(__ASSET__flixel_flixel_ui_img_finger_small_png_obj::resourceName,"resourceName"); }; #endif ::hx::Class __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__mClass; static ::String __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticFields[] = { HX_("resourceName",39,7a,62,90), ::String(null()) }; void __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__register() { __ASSET__flixel_flixel_ui_img_finger_small_png_obj _hx_dummy; __ASSET__flixel_flixel_ui_img_finger_small_png_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("__ASSET__flixel_flixel_ui_img_finger_small_png",72,ae,28,1f); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &__ASSET__flixel_flixel_ui_img_finger_small_png_obj::__GetStatic; __mClass->mSetStaticField = &__ASSET__flixel_flixel_ui_img_finger_small_png_obj::__SetStatic; __mClass->mMarkFunc = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(__ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< __ASSET__flixel_flixel_ui_img_finger_small_png_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = __ASSET__flixel_flixel_ui_img_finger_small_png_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void __ASSET__flixel_flixel_ui_img_finger_small_png_obj::__boot() { { HX_STACKFRAME(&_hx_pos_db845bbd0c26ed3d_600_boot) HXDLIN( 600) resourceName = HX_("__ASSET__:image___ASSET__flixel_flixel_ui_img_finger_small_png",80,fb,be,f7); } }
48.173333
313
0.822862
EnvyBun
612f9ba694f2ea62f7cc3612ff26f7299c05fa8f
1,858
cpp
C++
subprojects/graphite2/src/gr_char_info.cpp
asheraryam/godot_tl
ca2fc4151bd8141241151dd6e29768608600473a
[ "Unlicense" ]
25
2019-04-05T14:14:25.000Z
2021-11-08T09:40:52.000Z
subprojects/graphite2/src/gr_char_info.cpp
asheraryam/godot_tl
ca2fc4151bd8141241151dd6e29768608600473a
[ "Unlicense" ]
27
2019-04-05T14:18:26.000Z
2022-01-19T17:44:39.000Z
subprojects/graphite2/src/gr_char_info.cpp
asheraryam/godot_tl
ca2fc4151bd8141241151dd6e29768608600473a
[ "Unlicense" ]
6
2019-04-05T14:06:16.000Z
2022-02-18T03:38:18.000Z
/* GRAPHITE2 LICENSING Copyright 2010, SIL International All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of 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 Lesser General Public License for more details. You should also have received a copy of the GNU Lesser General Public License along with this library in the file named "LICENSE". If not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA or visit their web page on the internet at http://www.fsf.org/licenses/lgpl.html. Alternatively, the contents of this file may be used under the terms of the Mozilla Public License (http://mozilla.org/MPL) or 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. */ #include <cassert> #include "graphite2/Segment.h" #include "inc/CharInfo.h" extern "C" { unsigned int gr_cinfo_unicode_char(const gr_char_info* p/*not NULL*/) { assert(p); return p->unicodeChar(); } int gr_cinfo_break_weight(const gr_char_info* p/*not NULL*/) { assert(p); return p->breakWeight(); } int gr_cinfo_after(const gr_char_info *p/*not NULL*/) { assert(p); return p->after(); } int gr_cinfo_before(const gr_char_info *p/*not NULL*/) { assert(p); return p->before(); } size_t gr_cinfo_base(const gr_char_info *p/*not NULL*/) { assert(p); return p->base(); } } // extern "C"
28.151515
76
0.720129
asheraryam
9ecea26f4cd94cceb3df7ad768c739f9a2fb80fe
1,151
hpp
C++
src/sip-0x/parser/tokens/TokenSIPVersion.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2021-06-03T15:56:32.000Z
2021-06-03T15:56:32.000Z
src/sip-0x/parser/tokens/TokenSIPVersion.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2015-08-05T05:51:49.000Z
2015-08-05T05:51:49.000Z
src/sip-0x/parser/tokens/TokenSIPVersion.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
null
null
null
#if !defined(SIP0X_PARSER_TOKENSIPVERSION_HPP__) #define SIP0X_PARSER_TOKENSIPVERSION_HPP__ #include "parser/tokens/TokenAbstract.hpp" #include "parser/tokens/Operators.hpp" #include "parser/tokens/Token.hpp" #include "parser/tokens/TokenRegex.hpp" #include "parser/factory/FactoryContextSIPVersion.hpp" namespace sip0x { namespace parser { // SIP-Version = "SIP" "/" 1*DIGIT "." 1*DIGIT class TokenSIPVersion : public TokenAbstract { protected: Sequence<Token, TokenDigits, Token, TokenDigits> _sequence; public: TokenSIPVersion(void) : TokenAbstract("SIPVersion"), _sequence(Token("SIP/"), TokenDigits(), Token("."), TokenDigits()) { _sequence.disable_factory(true); } virtual ~TokenSIPVersion(void) { } protected: virtual ParserResult handle_read(sip0x::utils::InputTokenStream& iss, FactoryContext* ctx) const override { return _sequence.read(iss, ctx); } virtual FactoryContext* create_factory(void) const override { return new FactoryContextSIPVersion(); } }; } } #endif // SIP0X_PARSER_TOKENSIPVERSION_HPP__
26.767442
113
0.694179
zanfire
9ecf6445c565af4b25c30b86595de8d8d9ebadfe
6,194
cpp
C++
src/demos/irrlicht/demo_IRR_ballSMC.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
null
null
null
src/demos/irrlicht/demo_IRR_ballSMC.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
null
null
null
src/demos/irrlicht/demo_IRR_ballSMC.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Demo code about collisions and contacts using the penalty method (SMC) // // ============================================================================= #include "chrono/physics/ChSystemSMC.h" #include "chrono/physics/ChContactContainerSMC.h" #include "chrono_irrlicht/ChIrrApp.h" #include <irrlicht.h> // Use the namespaces of Chrono using namespace chrono; using namespace chrono::irrlicht; // Use the main namespaces of Irrlicht using namespace irr; using namespace irr::core; using namespace irr::scene; using namespace irr::video; using namespace irr::io; using namespace irr::gui; void AddWall(std::shared_ptr<ChBody> body, const ChVector<>& dim, const ChVector<>& loc, std::shared_ptr<ChMaterialSurface> mat) { body->GetCollisionModel()->AddBox(mat, dim.x(), dim.y(), dim.z(), loc); auto box = chrono_types::make_shared<ChBoxShape>(); box->GetBoxGeometry().Size = dim; box->GetBoxGeometry().Pos = loc; box->SetColor(ChColor(1, 0, 0)); box->SetFading(0.6f); body->AddAsset(box); } int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // Simulation parameters double gravity = -9.81; double time_step = 0.00001; double out_step = 2000 * time_step; // Parameters for the falling ball int ballId = 100; double radius = 1; double mass = 1000; ChVector<> pos(0, 2, 0); ChQuaternion<> rot(1, 0, 0, 0); ChVector<> init_vel(0, 0, 0); // Parameters for the containing bin int binId = 200; double width = 2; double length = 2; double height = 1; double thickness = 0.1; // Create the system ChSystemSMC msystem; // The following two lines are optional, since they are the default options. They are added for future reference, // i.e. when needed to change those models. msystem.SetContactForceModel(ChSystemSMC::ContactForceModel::Hertz); msystem.SetAdhesionForceModel(ChSystemSMC::AdhesionForceModel::Constant); msystem.Set_G_acc(ChVector<>(0, gravity, 0)); // Change the default collision effective radius of curvature collision::ChCollisionInfo::SetDefaultEffectiveCurvatureRadius(1); // Create the Irrlicht visualization ChIrrApp application(&msystem, L"SMC demo", core::dimension2d<u32>(800, 600)); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(0, 3, -6)); // This means that contactforces will be shown in Irrlicht application application.SetSymbolscale(1e-4); application.SetContactsDrawMode(IrrContactsDrawMode::CONTACT_FORCES); // Create a material (will be used by both objects) auto material = chrono_types::make_shared<ChMaterialSurfaceSMC>(); material->SetRestitution(0.1f); material->SetFriction(0.4f); material->SetAdhesion(0); // Magnitude of the adhesion in Constant adhesion model // Create the falling ball auto ball = chrono_types::make_shared<ChBody>(); ball->SetIdentifier(ballId); ball->SetMass(mass); ball->SetPos(pos); ball->SetRot(rot); ball->SetPos_dt(init_vel); // ball->SetWvel_par(ChVector<>(0,0,3)); ball->SetBodyFixed(false); ball->SetCollide(true); ball->GetCollisionModel()->ClearModel(); ball->GetCollisionModel()->AddSphere(material, radius); ball->GetCollisionModel()->BuildModel(); ball->SetInertiaXX(0.4 * mass * radius * radius * ChVector<>(1, 1, 1)); auto sphere = chrono_types::make_shared<ChSphereShape>(); sphere->GetSphereGeometry().rad = radius; ball->AddAsset(sphere); auto mtexture = chrono_types::make_shared<ChTexture>(); mtexture->SetTextureFilename(GetChronoDataFile("textures/bluewhite.png")); ball->AddAsset(mtexture); msystem.AddBody(ball); // Create container auto bin = chrono_types::make_shared<ChBody>(); bin->SetIdentifier(binId); bin->SetMass(1); bin->SetPos(ChVector<>(0, 0, 0)); bin->SetRot(ChQuaternion<>(1, 0, 0, 0)); bin->SetCollide(true); bin->SetBodyFixed(true); bin->GetCollisionModel()->ClearModel(); AddWall(bin, ChVector<>(width, thickness, length), ChVector<>(0, 0, 0), material); ////AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(-width + thickness, height, 0), material); ////AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(width - thickness, height, 0), material); ////AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, -length + thickness), material); ////AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, length - thickness), material); bin->GetCollisionModel()->BuildModel(); msystem.AddBody(bin); // Complete asset construction application.AssetBindAll(); application.AssetUpdateAll(); // The soft-real-time cycle double time = 0.0; double out_time = 0.0; while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); tools::drawGrid(application.GetVideoDriver(), 0.2, 0.2, 20, 20, ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)), video::SColor(255, 80, 100, 100), true); while (time < out_time) { msystem.DoStepDynamics(time_step); time += time_step; } out_time += out_step; application.EndScene(); } return 0; }
34.220994
130
0.638683
Ruochun
9ed36b848f34902d45895d054f7e3672e71cc7a6
636
cpp
C++
cses/Two_Sets.cpp
st3v3nmw/competitive-programming
581d36c1c128e0e3ee3a0b52628e932ab43821d4
[ "MIT" ]
null
null
null
cses/Two_Sets.cpp
st3v3nmw/competitive-programming
581d36c1c128e0e3ee3a0b52628e932ab43821d4
[ "MIT" ]
null
null
null
cses/Two_Sets.cpp
st3v3nmw/competitive-programming
581d36c1c128e0e3ee3a0b52628e932ab43821d4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { ll n; cin >> n; vector<ll> v1, v2; ll sum = n * (n + 1) / 2; if (sum % 2 != 0) { cout << "NO" << endl; return 0; } sum /= 2; for (int i = n; i > 0; i--) { if (sum - i >= 0) { v1.push_back(i); sum -= i; } else v2.push_back(i); } cout << "YES\n" << endl; cout << v1.size() << endl; for(int e : v1) cout << e << " "; cout << endl; cout << v2.size() << endl; for(int e : v2) cout << e << " "; cout << endl; }
18.705882
33
0.386792
st3v3nmw
9ed37dde31bb526b67de1ccd08c65acbe15ca049
2,156
cpp
C++
inference-engine/thirdparty/clDNN/tests/test_cases/softmax_loss_grad_gpu_test.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2020-02-09T23:25:37.000Z
2021-01-19T09:44:12.000Z
inference-engine/thirdparty/clDNN/tests/test_cases/softmax_loss_grad_gpu_test.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
4
2021-04-01T08:29:48.000Z
2021-08-30T16:12:52.000Z
inference-engine/thirdparty/clDNN/tests/test_cases/softmax_loss_grad_gpu_test.cpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
/* // Copyright (c) 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. */ /////////////////////////////////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "api/memory.hpp" #include <api/input_layout.hpp> #include "api/softmax_loss_grad.hpp" #include <api/data.hpp> #include <api/topology.hpp> #include <api/network.hpp> #include <api/engine.hpp> #include "test_utils/test_utils.h" using namespace cldnn; using namespace tests; TEST(softmax_loss_grad_f32_fw_gpu, basic1) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 4, 1 } }); auto labels = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 1, 1 } }); set_values(input, { 8.f, 0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 4.f }); set_values(labels, { 1.f, 3.f }); topology topology( input_layout("input", input.get_layout()), data("labels", labels), softmax_loss_grad("softmax_loss_grad", "input", "labels") ); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "softmax_loss_grad"); auto output_prim = outputs.begin()->second.get_memory(); auto output_ptr = output_prim.pointer<float>(); std::vector<float> expected_output_vec = { 8.f, -0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 3.f }; for (unsigned int i = 0; i < expected_output_vec.size(); i++) { EXPECT_FLOAT_EQ(expected_output_vec[i], output_ptr[i]); } }
33.169231
99
0.646568
anton-potapov
9ed42813791eb28e968c11a32c0668ffdf14571b
15,456
cpp
C++
Source/AliveLibAE/ParticleBurst.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
1
2021-04-11T23:44:43.000Z
2021-04-11T23:44:43.000Z
Source/AliveLibAE/ParticleBurst.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
Source/AliveLibAE/ParticleBurst.cpp
THEONLYDarkShadow/alive_reversing
680d87088023f2d5f2a40c42d6543809281374fb
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ParticleBurst.hpp" #include "Math.hpp" #include "Game.hpp" #include "Function.hpp" #include "Events.hpp" #include "Sfx.hpp" #include "ScreenManager.hpp" #include "Map.hpp" #include "stdlib.hpp" struct ParticleBurst_Item { FP field_0_x; FP field_4_y; FP field_8_z; FP field_C_x_speed; FP field_10_y_speed; FP field_14_z_speed; AnimationUnknown field_18_anim; }; ALIVE_ASSERT_SIZEOF(ParticleBurst_Item, 0x88); ParticleBurst* ParticleBurst::ctor_41CF50(FP xpos, FP ypos, unsigned int numOfParticles, FP scale, BurstType type, signed __int16 count) { BaseAnimatedWithPhysicsGameObject_ctor_424930(0); SetVTable(this, 0x5447DC); field_4_typeId = Types::eParticleBurst_29; // TODO: Check it if (numOfParticles > 5) { numOfParticles /= 2; } if (count > 13) { count = 13; } else if (count <= 0) { count = 1; } field_106_count = count; field_CC_sprite_scale = scale; field_F4_ppRes = ResourceManager::Allocate_New_Locked_Resource_49BF40(ResourceManager::ResourceType::Resource_3DGibs, 0, sizeof(ParticleBurst_Item) * numOfParticles); if (field_F4_ppRes) { field_F8_pRes = reinterpret_cast<ParticleBurst_Item*>(*field_F4_ppRes); for (DWORD i = 0; i < numOfParticles; i++) { // Placement new each element new (&field_F8_pRes[i]) ParticleBurst_Item(); SetVTable(&field_F8_pRes[i].field_18_anim, 0x5447CC); } field_104_type = type; switch (field_104_type) { case BurstType::eFallingRocks_0: Animation_Init_424E10(6484, 71, 36, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kDebrisID00), 1, 1u); field_20_animation.field_4_flags.Clear(AnimFlags::eBit15_bSemiTrans); field_20_animation.field_4_flags.Set(AnimFlags::eBit16_bBlending); break; case BurstType::eSticks_1: Animation_Init_424E10(1704, 49, 29, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kStickGib), 1, 1u); field_20_animation.field_4_flags.Clear(AnimFlags::eBit15_bSemiTrans); field_20_animation.field_4_flags.Set(AnimFlags::eBit16_bBlending); break; case BurstType::eBigPurpleSparks_2: Animation_Init_424E10(9912, 122, 43, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kDeathFlareResID), 1, 1u); field_20_animation.field_4_flags.Set(AnimFlags::eBit15_bSemiTrans); field_20_animation.field_4_flags.Set(AnimFlags::eBit16_bBlending); field_20_animation.field_B_render_mode = TPageAbr::eBlend_1; break; case BurstType::eBigRedSparks_3: case BurstType::eGreenSparks_5: case BurstType::eSmallPurpleSparks_6: Animation_Init_424E10(9912, 122, 43, Add_Resource_4DC130(ResourceManager::Resource_Animation, ResourceID::kDeathFlareResID), 1, 1u); field_20_animation.field_B_render_mode = TPageAbr::eBlend_1; field_20_animation.field_4_flags.Set(AnimFlags::eBit15_bSemiTrans); field_20_animation.field_4_flags.Clear(AnimFlags::eBit16_bBlending); if (field_104_type == BurstType::eBigRedSparks_3) { field_20_animation.field_8_r = 254; field_20_animation.field_9_g = 148; field_20_animation.field_A_b = 18; } else if (field_104_type == BurstType::eSmallPurpleSparks_6) { field_20_animation.field_8_r = 127; field_20_animation.field_9_g = 127; field_20_animation.field_A_b = 127; } else { field_20_animation.field_8_r = 0; field_20_animation.field_9_g = 255; field_20_animation.field_A_b = 32; } break; default: break; } if (field_6_flags.Get(BaseGameObject::eListAddFailed_Bit1)) { field_6_flags.Set(BaseGameObject::eDead_Bit3); } else { if (field_CC_sprite_scale == FP_FromInteger(1)) { field_D6_scale = 1; field_20_animation.field_C_render_layer = Layer::eLayer_39; } else { field_D6_scale = 0; field_20_animation.field_C_render_layer = Layer::eLayer_20; } field_FC_number_of_particles = static_cast<short>(numOfParticles); field_100_timer = sGnFrame_5C1B84 + 91; field_B8_xpos = xpos; field_BC_ypos = ypos; for (DWORD i = 0; i < numOfParticles; i++) { field_F8_pRes[i].field_18_anim.field_68_anim_ptr = &field_20_animation; field_F8_pRes[i].field_18_anim.field_C_render_layer = field_20_animation.field_C_render_layer; field_F8_pRes[i].field_18_anim.field_6C_scale = FP_FromDouble(0.95) * field_CC_sprite_scale; field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit3_Render); field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit25_bDecompressDone); // TODO: HIWORD &= ~0x0100u ?? field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit15_bSemiTrans, field_20_animation.field_4_flags.Get(AnimFlags::eBit15_bSemiTrans)); field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit16_bBlending, field_20_animation.field_4_flags.Get(AnimFlags::eBit16_bBlending)); if (type == BurstType::eBigPurpleSparks_2) { if (i % 2) { field_F8_pRes[i].field_18_anim.field_4_flags.Set(AnimFlags::eBit16_bBlending); } } field_F8_pRes[i].field_18_anim.field_8_r = field_20_animation.field_8_r; field_F8_pRes[i].field_18_anim.field_9_g = field_20_animation.field_9_g; field_F8_pRes[i].field_18_anim.field_A_b = field_20_animation.field_A_b; field_F8_pRes[i].field_0_x = field_B8_xpos; field_F8_pRes[i].field_4_y = field_BC_ypos; field_F8_pRes[i].field_8_z = FP_FromInteger(0); Random_Speed_41CEE0(&field_F8_pRes[i].field_C_x_speed); Random_Speed_41CEE0(&field_F8_pRes[i].field_10_y_speed); // OG bug sign could be wrong here as it called random again to Abs() it! FP zRandom = {}; field_F8_pRes[i].field_14_z_speed = -FP_Abs(*Random_Speed_41CEE0(&zRandom)); } } } else { field_6_flags.Set(BaseGameObject::eDead_Bit3); } return this; } BaseGameObject* ParticleBurst::VDestructor(signed int flags) { return vdtor_41D4E0(flags); } void ParticleBurst::VUpdate() { vUpdate_41D590(); } void ParticleBurst::VRender(PrimHeader** ppOt) { vRender_41D7B0(ppOt); } FP* ParticleBurst::Random_Speed_41CEE0(FP* random) { const FP v2 = FP_FromRaw((Math_NextRandom() - 128) << LOBYTE(field_106_count)); *random = v2 * field_CC_sprite_scale; return random; } ParticleBurst* ParticleBurst::vdtor_41D4E0(signed int flags) { dtor_41D510(); if (flags & 1) { ae_delete_free_495540(this); } return this; } void ParticleBurst::dtor_41D510() { SetVTable(this, 0x5447DC); if (field_F4_ppRes) { ResourceManager::FreeResource_49C330(field_F4_ppRes); } BaseAnimatedWithPhysicsGameObject_dtor_424AD0(); } void ParticleBurst::vRender_41D7B0(PrimHeader** ppOt) { bool bFirst = true; if (sNum_CamSwappers_5C1B66 == 0) { field_20_animation.field_14_scale = field_CC_sprite_scale; const FP camX = pScreenManager_5BB5F4->field_20_pCamPos->field_0_x; const FP camY = pScreenManager_5BB5F4->field_20_pCamPos->field_4_y; for (int i = 0; i < field_FC_number_of_particles; i++) { if (field_F8_pRes[i].field_0_x < camX) { continue; } if (field_F8_pRes[i].field_0_x > camX + FP_FromInteger(640)) { continue; } if (field_F8_pRes[i].field_4_y < camY) { continue; } if (field_F8_pRes[i].field_4_y > camY + FP_FromInteger(240)) { continue; } const FP zPos = field_F8_pRes[i].field_8_z; // TODO: Much duplicated code in each branch if (bFirst) { field_20_animation.field_14_scale = FP_FromInteger(100) / (zPos + FP_FromInteger(300)); field_20_animation.field_14_scale *= field_CC_sprite_scale; field_20_animation.field_14_scale *= FP_FromInteger(field_106_count) / FP_FromInteger(13); if (field_20_animation.field_14_scale <= FP_FromInteger(1)) { field_20_animation.vRender_40B820( FP_GetExponent(field_F8_pRes[i].field_0_x - camX), FP_GetExponent(field_F8_pRes[i].field_4_y - camY), ppOt, 0, 0); bFirst = false; PSX_RECT frameRect = {}; field_20_animation.Get_Frame_Rect_409E10(&frameRect); if (field_106_count == 9) { if (field_20_animation.field_8_r > 5) { field_20_animation.field_8_r -= 6; } else { field_20_animation.field_8_r = 0; } if (field_20_animation.field_9_g > 5) { field_20_animation.field_9_g -= 6; } else { field_20_animation.field_9_g = 0; } if (field_20_animation.field_A_b > 5) { field_20_animation.field_A_b -= 6; } else { field_20_animation.field_A_b = 0; } } pScreenManager_5BB5F4->InvalidateRect_40EC90( frameRect.x, frameRect.y, frameRect.w, frameRect.h, pScreenManager_5BB5F4->field_3A_idx); } } else { field_F8_pRes[i].field_18_anim.field_6C_scale = FP_FromInteger(100) / (zPos + FP_FromInteger(300)); field_F8_pRes[i].field_18_anim.field_6C_scale *= field_CC_sprite_scale; field_F8_pRes[i].field_18_anim.field_6C_scale *= FP_FromInteger(field_106_count) / FP_FromInteger(13); if (field_F8_pRes[i].field_18_anim.field_6C_scale <= FP_FromInteger(1)) { field_F8_pRes[i].field_18_anim.vRender_40B820( FP_GetExponent(field_F8_pRes[i].field_0_x - camX), FP_GetExponent(field_F8_pRes[i].field_4_y - camY), ppOt, 0, 0); PSX_RECT frameRect = {}; field_F8_pRes[i].field_18_anim.GetRenderedSize_40C980(&frameRect); if (field_106_count == 9) { if (field_F8_pRes[i].field_18_anim.field_8_r > 5) { field_F8_pRes[i].field_18_anim.field_8_r -= 6; } else { field_F8_pRes[i].field_18_anim.field_8_r = 0; } if (field_F8_pRes[i].field_18_anim.field_9_g > 5) { field_F8_pRes[i].field_18_anim.field_9_g -= 6; } else { field_F8_pRes[i].field_18_anim.field_9_g = 0; } if (field_F8_pRes[i].field_18_anim.field_A_b > 5) { field_F8_pRes[i].field_18_anim.field_A_b -= 6; } else { field_F8_pRes[i].field_18_anim.field_A_b = 0; } } pScreenManager_5BB5F4->InvalidateRect_40EC90( frameRect.x, frameRect.y, frameRect.w, frameRect.h, pScreenManager_5BB5F4->field_3A_idx); } } } } } void ParticleBurst::vUpdate_41D590() { const int v3 = field_CC_sprite_scale != FP_FromInteger(1) ? 2 : 4; for (int i = 0; i < field_FC_number_of_particles; i++) { field_F8_pRes[i].field_0_x += field_F8_pRes[i].field_C_x_speed; field_F8_pRes[i].field_4_y += field_F8_pRes[i].field_10_y_speed; field_F8_pRes[i].field_8_z += field_F8_pRes[i].field_14_z_speed; field_F8_pRes[i].field_10_y_speed += FP_FromDouble(0.25); if (field_106_count == 9) { if ((sGnFrame_5C1B84 + i) & v3) { field_F8_pRes[i].field_0_x -= FP_FromInteger(1); } else { field_F8_pRes[i].field_0_x += FP_FromInteger(1); } } if (field_F8_pRes[i].field_8_z + FP_FromInteger(300) < FP_FromInteger(15)) { field_F8_pRes[i].field_14_z_speed = -field_F8_pRes[i].field_14_z_speed; field_F8_pRes[i].field_8_z += field_F8_pRes[i].field_14_z_speed; // TODO: Never used by OG ?? //Math_RandomRange_496AB0(-64, 46); // TODO: This might be wrong const short volume = static_cast<short>(Math_RandomRange_496AB0(-10, 10) + ((field_100_timer - sGnFrame_5C1B84) / 91) + 25); const BYTE next_rand = Math_NextRandom(); if (next_rand < 43) { SFX_Play_46FC20(SoundEffect::ParticleBurst_27, volume, CameraPos::eCamLeft_3); } else if (next_rand >= 85) { SFX_Play_46FC20(SoundEffect::ParticleBurst_27, volume, CameraPos::eCamRight_4); } else { SFX_Play_46FC20(SoundEffect::ParticleBurst_27, volume, CameraPos::eCamCurrent_0); } } } if (static_cast<int>(sGnFrame_5C1B84) > field_100_timer) { field_6_flags.Set(BaseGameObject::eDead_Bit3); } if (Event_Get_422C00(kEventDeathReset)) { field_6_flags.Set(BaseGameObject::eDead_Bit3); } }
35.777778
170
0.551889
THEONLYDarkShadow
9ed55f3e8b285a0b17d289c1443def0bd4afc0b4
854
hpp
C++
inc/RingBuffer.hpp
izissise/network
7267690fdaa379331b130e5bdd7ee87649c240b2
[ "MIT" ]
1
2015-05-06T09:21:07.000Z
2015-05-06T09:21:07.000Z
inc/RingBuffer.hpp
izissise/network
7267690fdaa379331b130e5bdd7ee87649c240b2
[ "MIT" ]
1
2015-06-14T17:23:11.000Z
2015-06-15T09:41:16.000Z
inc/RingBuffer.hpp
izissise/network
7267690fdaa379331b130e5bdd7ee87649c240b2
[ "MIT" ]
null
null
null
#ifndef RINGBUFFER_H # define RINGBUFFER_H # include <cstdint> # include <memory> # include <cstring> # include "ASocket.hpp" namespace Network { class RingBuffer { public: RingBuffer(size_t size = 4096); virtual ~RingBuffer() = default; void writeBuffer(const Network::Buffer& data); void readBuffer(Network::Buffer& data, size_t rSize); size_t getBuffSize() const {return _buffSize;}; void extendRingBuffer(size_t addSize); void rollbackReadBuffer(size_t rbsize); inline size_t getLeftRead() const { return (((_idxW + _buffSize) - _idxR) % _buffSize); }; inline size_t getLeftWrite() const { return (((_idxR + _buffSize - 1) - _idxW) % _buffSize); }; //Iterators protected: size_t _buffSize; size_t _idxR; size_t _idxW; std::unique_ptr<uint8_t[]> _buffer; }; }; #endif // RINGBUFFER_H
18.977778
59
0.687354
izissise
9ed895dfa81ebb1d5ea1140288e6f94bb98564d3
166
cpp
C++
src/GlobalDefinitions.cpp
KanjiuAkuma/Ts3Tools
2f1c9675ba7aef4d6b8ba6c7070d78f7341f9af3
[ "MIT" ]
null
null
null
src/GlobalDefinitions.cpp
KanjiuAkuma/Ts3Tools
2f1c9675ba7aef4d6b8ba6c7070d78f7341f9af3
[ "MIT" ]
null
null
null
src/GlobalDefinitions.cpp
KanjiuAkuma/Ts3Tools
2f1c9675ba7aef4d6b8ba6c7070d78f7341f9af3
[ "MIT" ]
null
null
null
/** * Created by Joscha Vack on 12/9/2019. * **/ #include "GlobalDefinitions.h" TS3Functions ts3Functions; char* pluginID = nullptr; ServerList serverList {};
16.6
40
0.698795
KanjiuAkuma
9edb100510240b459c4ce833507d90c8772568b3
134
hxx
C++
src/Providers/UNIXProviders/PackageInConnector/UNIX_PackageInConnector_SOLARIS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/PackageInConnector/UNIX_PackageInConnector_SOLARIS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/PackageInConnector/UNIX_PackageInConnector_SOLARIS.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_SOLARIS #ifndef __UNIX_PACKAGEINCONNECTOR_PRIVATE_H #define __UNIX_PACKAGEINCONNECTOR_PRIVATE_H #endif #endif
11.166667
43
0.858209
brunolauze
9edba13854fcf939f5ddc8c8d376a3f7fef575d3
986
cc
C++
src/problems/problem1.cc
JeffGos/jg-project-euler
a2a7ca473e7b7c42907c10410eaf6b859bf48086
[ "MIT" ]
null
null
null
src/problems/problem1.cc
JeffGos/jg-project-euler
a2a7ca473e7b7c42907c10410eaf6b859bf48086
[ "MIT" ]
null
null
null
src/problems/problem1.cc
JeffGos/jg-project-euler
a2a7ca473e7b7c42907c10410eaf6b859bf48086
[ "MIT" ]
null
null
null
#include "problem1.h" #include <iostream> void problem1BruteForce(long upperLimit) { printf("Problem 1 - Brute Force\n"); int multiplesOf3And5Count = 0; for (int i = 0; i < upperLimit; i++) { if (i % 3 == 0 || i % 5 == 0) { multiplesOf3And5Count += i; } } printf("Multiples of 3 and 5 below %ld = %d", upperLimit, multiplesOf3And5Count); } int getMultiples(int argument, int upperLimit) { int multiplesCount = 0; int i = 1; int loops = (upperLimit - 1) / argument; while (i <= loops) { int multiple = argument * i; multiplesCount += multiple; i++; } return multiplesCount; } void problem1Multiples(long upperLimit) { printf("Problem 1 - Multiples\n"); int multiplesOf3And5Count = 0; multiplesOf3And5Count += getMultiples(3, upperLimit); multiplesOf3And5Count += getMultiples(5, upperLimit); multiplesOf3And5Count -= getMultiples(15, upperLimit); printf("Multiples of 3 and 5 below %ld = %d", upperLimit, multiplesOf3And5Count); }
18.961538
84
0.678499
JeffGos
9edc97ffd6e552814d246ea613138d0bb56fd02e
911
cpp
C++
TOI16/Programming TH/1082.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Programming TH/1082.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Programming TH/1082.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int findset(vector<int> &subset,int u) { if(subset[u] == -1) return u; subset[u] = findset(subset,subset[u]); return subset[u]; } void kruskal(vector<pair<int,pair<int,int> > > edge,int V) { vector<int> subset(V,-1); vector<pair<int,pair<int,int> > > MST; sort(edge.begin(),edge.end()); for(auto E : edge) { int setu = findset(subset,E.second.first); int setv = findset(subset,E.second.second); if(setu != setv) { MST.push_back(E); subset[setu] = setv; if(MST.size() == V-1) break; } } for(auto E : MST) cout<<E.second.first+1<<" "<<E.second.second+1<<'\n'; } main() { ios_base::sync_with_stdio(0); cin.tie(0); int V,E; cin>>V>>E; vector<pair<int,pair<int,int> > > edge; int u,v,w; for(int i=0;i<E;i++) { cin>>u>>v>>w; u-- , v--; edge.push_back(make_pair(w,make_pair(u,v))); } kruskal(edge,V); }
16.267857
58
0.592755
mrmuffinnxz
9edf160b8ebfaeac3b522893ab8d155fe747c0b5
921
cpp
C++
src/session_settings.cpp
aldenml/libtorrent
f484a0eff66c1d8932d694e1785da204ac1a2769
[ "BSL-1.0", "BSD-3-Clause" ]
1
2020-07-20T17:01:46.000Z
2020-07-20T17:01:46.000Z
src/session_settings.cpp
aldenml/libtorrent
f484a0eff66c1d8932d694e1785da204ac1a2769
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/session_settings.cpp
aldenml/libtorrent
f484a0eff66c1d8932d694e1785da204ac1a2769
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2007, 2015, 2017, 2019-2021, Arvid Norberg All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #include "libtorrent/aux_/session_settings.hpp" #include "libtorrent/settings_pack.hpp" #include <functional> namespace libtorrent { namespace aux { session_settings::session_settings() = default; session_settings::session_settings(settings_pack const& p) { apply_pack_impl(&p, m_store); } void session_settings::bulk_set(std::function<void(session_settings_single_thread&)> f) { std::unique_lock<std::mutex> l(m_mutex); f(m_store); } void session_settings::bulk_get(std::function<void(session_settings_single_thread const&)> f) const { std::unique_lock<std::mutex> l(m_mutex); f(m_store); } session_settings_single_thread::session_settings_single_thread() { initialize_default_settings(*this); } } }
21.418605
100
0.7557
aldenml
9edf6a4ae70cd22e037174a94570c2576ef70371
1,125
cc
C++
0.mycode/05_ReplaceSpaces.cc
ebayboy/CodingInterviewChinese2
b5695e780ee64774e3e9f5eff662e7a1440d56de
[ "BSD-3-Clause" ]
null
null
null
0.mycode/05_ReplaceSpaces.cc
ebayboy/CodingInterviewChinese2
b5695e780ee64774e3e9f5eff662e7a1440d56de
[ "BSD-3-Clause" ]
null
null
null
0.mycode/05_ReplaceSpaces.cc
ebayboy/CodingInterviewChinese2
b5695e780ee64774e3e9f5eff662e7a1440d56de
[ "BSD-3-Clause" ]
null
null
null
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; /* 题目: 替换空格 请实现一个函数,把字符串中的每个空格替换成“%20”, 例如,输入”We are happy.”,则输出”We%20are%20happy.”。 */ char *replace_spaces(const char *src, size_t slen) { char *desc = NULL; size_t count = 0; size_t j = 0; //malloc mem for (size_t i = 0; i < slen; i++) { if (src[i] == ' ') { count++; } } desc = (char *)malloc(slen + count * 2); //copy for (size_t i = 0; i < slen; i++) { if (src[i] == ' ') { desc[j++] = '%'; desc[j++] = '2'; desc[j++] = '0'; } else { desc[j++] = src[i]; } } desc[j++] = '\0'; return desc; } int main(int argc, const char **argv) { char *str = (char *)"We are happy."; size_t len = strlen(str); char *dest = replace_spaces(str, len); if (strcmp(dest, "We%20are%20happy.") == 0) cout << "dest replace sucess!" << endl; else cout << "Error: dest replace failed!" << endl; return 0; }
17.578125
54
0.466667
ebayboy
9ee291a6b0754a5e26582ac390fce378f8e9d97b
6,324
cpp
C++
src/IECoreHoudini/ToHoudiniCurvesConverter.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
5
2016-07-26T06:09:28.000Z
2022-03-07T03:58:51.000Z
src/IECoreHoudini/ToHoudiniCurvesConverter.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
null
null
null
src/IECoreHoudini/ToHoudiniCurvesConverter.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
3
2015-03-25T18:45:24.000Z
2020-02-15T15:37:18.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2013, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software 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 "GU/GU_PrimNURBCurve.h" #include "IECore/DespatchTypedData.h" #include "IECoreHoudini/ToHoudiniAttribConverter.h" #include "IECoreHoudini/ToHoudiniCurvesConverter.h" #include "IECoreHoudini/TypeTraits.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniCurvesConverter ); ToHoudiniGeometryConverter::Description<ToHoudiniCurvesConverter> ToHoudiniCurvesConverter::m_description( CurvesPrimitiveTypeId ); ToHoudiniCurvesConverter::ToHoudiniCurvesConverter( const VisibleRenderable *renderable ) : ToHoudiniGeometryConverter( renderable, "Converts an IECore::CurvesPrimitive to a Houdini GU_Detail." ) { } ToHoudiniCurvesConverter::~ToHoudiniCurvesConverter() { } bool ToHoudiniCurvesConverter::doConversion( const VisibleRenderable *renderable, GU_Detail *geo ) const { const CurvesPrimitive *curves = static_cast<const CurvesPrimitive *>( renderable ); if ( !curves ) { return false; } bool periodic = curves->periodic(); bool duplicatedEnds = !periodic && ( curves->basis() == CubicBasisf::bSpline() ); size_t numPoints = curves->variableSize( PrimitiveVariable::Vertex ); if ( duplicatedEnds ) { numPoints -= 4 * curves->numCurves(); } GA_Range newPoints = appendPoints( geo, numPoints ); if ( !newPoints.isValid() || newPoints.empty() ) { return false; } GA_OffsetList pointOffsets; pointOffsets.reserve( newPoints.getEntries() ); for ( GA_Iterator it=newPoints.begin(); !it.atEnd(); ++it ) { pointOffsets.append( it.getOffset() ); } const std::vector<int> &verticesPerCurve = curves->verticesPerCurve()->readable(); int order = ( curves->basis() == CubicBasisf::bSpline() ) ? 4 : 2; bool interpEnds = !(periodic && ( curves->basis() == CubicBasisf::bSpline() )); GA_OffsetList offsets; offsets.reserve( verticesPerCurve.size() ); size_t vertCount = 0; size_t numPrims = geo->getNumPrimitives(); for ( size_t c=0; c < verticesPerCurve.size(); c++ ) { size_t numVerts = duplicatedEnds ? verticesPerCurve[c] - 4 : verticesPerCurve[c]; GU_PrimNURBCurve *curve = GU_PrimNURBCurve::build( geo, numVerts, order, periodic, interpEnds, false ); if ( !curve ) { return false; } offsets.append( geo->primitiveOffset( numPrims + c ) ); for ( size_t v=0; v < numVerts; v++ ) { curve->setVertexPoint( v, pointOffsets.get( vertCount + v ) ); } vertCount += numVerts; } GA_Range newPrims( geo->getPrimitiveMap(), offsets ); transferAttribs( geo, newPoints, newPrims ); return true; } PrimitiveVariable ToHoudiniCurvesConverter::processPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primVar ) const { const CurvesPrimitive *curves = static_cast<const CurvesPrimitive *>( primitive ); if ( !curves ) { return primVar; } // adjust for duplicated end points bool duplicatedEnds = !curves->periodic() && ( curves->basis() == CubicBasisf::bSpline() ); if ( duplicatedEnds && primVar.interpolation == IECore::PrimitiveVariable::Vertex ) { RemoveDuplicateEnds func( curves->verticesPerCurve()->readable() ); DataPtr data = despatchTypedData<RemoveDuplicateEnds, TypeTraits::IsVectorAttribTypedData, DespatchTypedDataIgnoreError>( primVar.data, func ); return PrimitiveVariable( IECore::PrimitiveVariable::Vertex, data ); } return primVar; } void ToHoudiniCurvesConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const { const Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() ); if ( primitive ) { transferAttribValues( primitive, geo, points, prims, PrimitiveVariable::Vertex ); } } ToHoudiniCurvesConverter::RemoveDuplicateEnds::RemoveDuplicateEnds( const std::vector<int> &vertsPerCurve ) : m_vertsPerCurve( vertsPerCurve ) { } template <typename T> ToHoudiniCurvesConverter::RemoveDuplicateEnds::ReturnType ToHoudiniCurvesConverter::RemoveDuplicateEnds::operator()( typename T::ConstPtr data ) const { assert( data ); typedef typename T::ValueType::value_type ValueType; const std::vector<ValueType> &origValues = data->readable(); typename T::Ptr result = new T(); std::vector<ValueType> &newValues = result->writable(); size_t index = 0; for ( size_t i=0; i < m_vertsPerCurve.size(); i++ ) { for ( size_t j=0; j < (size_t)m_vertsPerCurve[i]; j++, index++ ) { if ( j > 1 && j < (size_t)m_vertsPerCurve[i]-2 ) { newValues.push_back( origValues[index] ); } } } return result; }
34.747253
150
0.716635
gcodebackups
9ee335d58e0df8e45c1a362325de449a3fb45a6c
12,441
cc
C++
chrome/browser/autofill/credit_card_field_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-03-10T13:08:49.000Z
2018-03-10T13:08:49.000Z
chrome/browser/autofill/credit_card_field_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/autofill/credit_card_field_unittest.cc
GnorTech/chromium
e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:19:31.000Z
2020-11-04T07:19:31.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/autofill_field.h" #include "chrome/browser/autofill/autofill_scanner.h" #include "chrome/browser/autofill/credit_card_field.h" #include "chrome/common/form_field_data.h" #include "testing/gtest/include/gtest/gtest.h" class CreditCardFieldTest : public testing::Test { public: CreditCardFieldTest() {} protected: ScopedVector<const AutofillField> list_; scoped_ptr<CreditCardField> field_; FieldTypeMap field_type_map_; // Downcast for tests. static CreditCardField* Parse(AutofillScanner* scanner) { return static_cast<CreditCardField*>(CreditCardField::Parse(scanner)); } private: DISALLOW_COPY_AND_ASSIGN(CreditCardFieldTest); }; TEST_F(CreditCardFieldTest, Empty) { AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get()); } TEST_F(CreditCardFieldTest, NonParse) { list_.push_back(new AutofillField); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get()); } TEST_F(CreditCardFieldTest, ParseCreditCardNoNumber) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Exp Month"); field.name = ASCIIToUTF16("ccmonth"); list_.push_back(new AutofillField(field, ASCIIToUTF16("month1"))); field.label = ASCIIToUTF16("Exp Year"); field.name = ASCIIToUTF16("ccyear"); list_.push_back(new AutofillField(field, ASCIIToUTF16("year2"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get()); } TEST_F(CreditCardFieldTest, ParseCreditCardNoDate) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number1"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_EQ(static_cast<CreditCardField*>(NULL), field_.get()); } TEST_F(CreditCardFieldTest, ParseMiniumCreditCard) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number1"))); field.label = ASCIIToUTF16("Exp Month"); field.name = ASCIIToUTF16("ccmonth"); list_.push_back(new AutofillField(field, ASCIIToUTF16("month2"))); field.label = ASCIIToUTF16("Exp Year"); field.name = ASCIIToUTF16("ccyear"); list_.push_back(new AutofillField(field, ASCIIToUTF16("year3"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("number1")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number1")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("month2")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month2")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("year3")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR, field_type_map_[ASCIIToUTF16("year3")]); } TEST_F(CreditCardFieldTest, ParseFullCreditCard) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Card Type"); field.name = ASCIIToUTF16("card_type"); list_.push_back(new AutofillField(field, ASCIIToUTF16("type"))); field.label = ASCIIToUTF16("Name on Card"); field.name = ASCIIToUTF16("name_on_card"); list_.push_back(new AutofillField(field, ASCIIToUTF16("name"))); field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number"))); field.label = ASCIIToUTF16("Exp Month"); field.name = ASCIIToUTF16("ccmonth"); list_.push_back(new AutofillField(field, ASCIIToUTF16("month"))); field.label = ASCIIToUTF16("Exp Year"); field.name = ASCIIToUTF16("ccyear"); list_.push_back(new AutofillField(field, ASCIIToUTF16("year"))); field.label = ASCIIToUTF16("Verification"); field.name = ASCIIToUTF16("verification"); list_.push_back(new AutofillField(field, ASCIIToUTF16("cvc"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("type")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_TYPE, field_type_map_[ASCIIToUTF16("type")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("name")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("number")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("month")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("year")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR, field_type_map_[ASCIIToUTF16("year")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("cvc")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_VERIFICATION_CODE, field_type_map_[ASCIIToUTF16("cvc")]); } TEST_F(CreditCardFieldTest, ParseExpMonthYear) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Name on Card"); field.name = ASCIIToUTF16("name_on_card"); list_.push_back(new AutofillField(field, ASCIIToUTF16("name1"))); field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number2"))); field.label = ASCIIToUTF16("ExpDate Month / Year"); field.name = ASCIIToUTF16("ExpDate"); list_.push_back(new AutofillField(field, ASCIIToUTF16("month3"))); field.label = ASCIIToUTF16("ExpDate Month / Year"); field.name = ASCIIToUTF16("ExpDate"); list_.push_back(new AutofillField(field, ASCIIToUTF16("year4"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("month3")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month3")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("year4")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR, field_type_map_[ASCIIToUTF16("year4")]); } TEST_F(CreditCardFieldTest, ParseExpMonthYear2) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Name on Card"); field.name = ASCIIToUTF16("name_on_card"); list_.push_back(new AutofillField(field, ASCIIToUTF16("name1"))); field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number2"))); field.label = ASCIIToUTF16("Expiration date Month / Year"); field.name = ASCIIToUTF16("ExpDate"); list_.push_back(new AutofillField(field, ASCIIToUTF16("month3"))); field.label = ASCIIToUTF16("Expiration date Month / Year"); field.name = ASCIIToUTF16("ExpDate"); list_.push_back(new AutofillField(field, ASCIIToUTF16("year4"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("month3")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_MONTH, field_type_map_[ASCIIToUTF16("month3")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("year4")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR, field_type_map_[ASCIIToUTF16("year4")]); } TEST_F(CreditCardFieldTest, ParseExpField) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Name on Card"); field.name = ASCIIToUTF16("name_on_card"); list_.push_back(new AutofillField(field, ASCIIToUTF16("name1"))); field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number2"))); field.label = ASCIIToUTF16("Expiration Date (MM/YYYY)"); field.name = ASCIIToUTF16("cc_exp"); list_.push_back(new AutofillField(field, ASCIIToUTF16("exp3"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("exp3")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR, field_type_map_[ASCIIToUTF16("exp3")]); } TEST_F(CreditCardFieldTest, ParseExpField2DigitYear) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Name on Card"); field.name = ASCIIToUTF16("name_on_card"); list_.push_back(new AutofillField(field, ASCIIToUTF16("name1"))); field.label = ASCIIToUTF16("Card Number"); field.name = ASCIIToUTF16("card_number"); list_.push_back(new AutofillField(field, ASCIIToUTF16("number2"))); field.label = ASCIIToUTF16("Expiration Date (MM/YY)"); field.name = ASCIIToUTF16("cc_exp"); list_.push_back(new AutofillField(field, ASCIIToUTF16("exp3"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("number2")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NUMBER, field_type_map_[ASCIIToUTF16("number2")]); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("exp3")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR, field_type_map_[ASCIIToUTF16("exp3")]); } TEST_F(CreditCardFieldTest, ParseCreditCardHolderNameWithCCFullName) { FormFieldData field; field.form_control_type = "text"; field.label = ASCIIToUTF16("Name"); field.name = ASCIIToUTF16("ccfullname"); list_.push_back(new AutofillField(field, ASCIIToUTF16("name1"))); AutofillScanner scanner(list_.get()); field_.reset(Parse(&scanner)); ASSERT_NE(static_cast<CreditCardField*>(NULL), field_.get()); ASSERT_TRUE(field_->ClassifyField(&field_type_map_)); ASSERT_TRUE( field_type_map_.find(ASCIIToUTF16("name1")) != field_type_map_.end()); EXPECT_EQ(CREDIT_CARD_NAME, field_type_map_[ASCIIToUTF16("name1")]); }
39
78
0.747207
GnorTech
9ee49a10c4b53cd5e34bfb1f8b4fa06ec39e7967
4,988
cpp
C++
src/archutils/Darwin/Crash.cpp
SharpnelXu/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
[ "MIT" ]
1
2022-02-22T01:24:02.000Z
2022-02-22T01:24:02.000Z
src/archutils/Darwin/Crash.cpp
john-marinelli/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
[ "MIT" ]
1
2019-05-04T02:30:57.000Z
2019-05-04T02:30:57.000Z
src/archutils/Darwin/Crash.cpp
john-marinelli/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
[ "MIT" ]
3
2019-05-02T01:50:23.000Z
2020-05-25T01:08:36.000Z
#include "Etterna/Globals/global.h" #include "Crash.h" #include "Core/Services/Locator.hpp" #include "Core/Platform/Platform.hpp" #include "Core/Misc/AppInfo.hpp" #include <CoreServices/CoreServices.h> #include <sys/types.h> #include <fmt/format.h> #if defined(HAVE_UNISTD_H) #include <unistd.h> #endif #include <sys/sysctl.h> std::string CrashHandler::GetLogsDirectory() { FSRef fs; char dir[PATH_MAX]; if (FSFindFolder( kUserDomain, kDomainLibraryFolderType, kDontCreateFolder, &fs) || FSRefMakePath(&fs, (UInt8*)dir, PATH_MAX)) { return "/tmp"; } return fmt::format("{}/Logs/{}", dir, Core::AppInfo::APP_TITLE); } // XXX Can we use LocalizedString here instead? #define LSTRING(b, x) \ CFBundleCopyLocalizedString((b), CFStringCreateWithCString(kCFAllocatorDefault, x, kCFStringEncodingUTF8), NULL, CFSTR("Localizable")) void CrashHandler::InformUserOfCrash(const std::string& sPath) { CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef sAlternate = LSTRING(bundle, fmt::format("Quit {}", Core::AppInfo::APP_TITLE).c_str()); /* XXX Translate these and remove the redefine of LSTRING. Another way to do * this would be to pass bundle's URL to CFUserNotificationDisplayAlert's * localizationURL parameter and let it do it. This wouldn't work for sBody * though. */ CFStringRef sDefault = LSTRING(bundle, "File Bug Report"); CFStringRef sOther = LSTRING(bundle, "Open crashinfo.txt"); CFStringRef sTitle = LSTRING(bundle, fmt::format("{} has crashed", Core::AppInfo::APP_TITLE).c_str()); CFStringRef sFormat = LSTRING(bundle, fmt::format("{} has crashed" "Debugging information has been output to\n\n%s\n\n" "Please file a bug report at\n\n%s", Core::AppInfo::APP_TITLE).c_str()); CFStringRef sBody = CFStringCreateWithFormat( kCFAllocatorDefault, NULL, sFormat, sPath.c_str(), Core::AppInfo::BUG_REPORT_URL); CFOptionFlags response = kCFUserNotificationCancelResponse; CFTimeInterval timeout = 0.0; // Should we ever time out? CFUserNotificationDisplayAlert(timeout,kCFUserNotificationStopAlertLevel, NULL, NULL, NULL, sTitle, sBody, sDefault, sAlternate, sOther, &response); switch (response) { case kCFUserNotificationDefaultResponse: Core::Platform::openWebsite(Core::AppInfo::BUG_REPORT_URL); // Fall through. case kCFUserNotificationOtherResponse: // Open the file with the default application (probably TextEdit). Core::Platform::openWebsite("file://" + sPath); break; } CFRelease(sBody); CFRelease(sFormat); CFRelease(sTitle); CFRelease(sOther); CFRelease(sDefault); CFRelease(sAlternate); } /* IMPORTANT: Because the definition of the kinfo_proc structure (in * <sys/sysctl.h>) is conditionalized by __APPLE_API_UNSTABLE, you should * restrict use of the [below] code to the debug build of your program. * http://developer.apple.com/qa/qa2004/qa1361.html */ bool CrashHandler::IsDebuggerPresent() { #ifdef DEBUG int ret; int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() }; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Call sysctl. size = sizeof(info); ret = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); // We're being debugged if the P_TRACED flag is set. return ret == 0 && (info.kp_proc.p_flag & P_TRACED) != 0; #else return false; #endif } void CrashHandler::DebugBreak() { // TODO: Following command is depreciated. // DebugStr("\pDebugBreak()"); } /* * (c) 2003-2006 Steve Checkoway * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
35.884892
135
0.722735
SharpnelXu
9ee5e43a2859b187873bc2d9f637b488645dd736
5,855
cpp
C++
src/CGeomLight3D.cpp
colinw7/CGeometry3D
15c009b57bfcdcc5ca13ef2acfe94b6831a4c865
[ "MIT" ]
1
2021-12-23T02:21:22.000Z
2021-12-23T02:21:22.000Z
src/CGeomLight3D.cpp
colinw7/CGeometry3D
15c009b57bfcdcc5ca13ef2acfe94b6831a4c865
[ "MIT" ]
null
null
null
src/CGeomLight3D.cpp
colinw7/CGeometry3D
15c009b57bfcdcc5ca13ef2acfe94b6831a4c865
[ "MIT" ]
null
null
null
#include <CGeomLight3D.h> #include <CGeometry3D.h> #include <CGeomZBuffer.h> #include <CGeomPyramid3D.h> #include <CImageMgr.h> #include "images/Sun.h" CGeomLight3DMgr:: CGeomLight3DMgr() { } void CGeomLight3DMgr:: addLight(CGeomLight3D *light) { lights_.push_back(light); light->setMgr(this); } void CGeomLight3DMgr:: deleteLight(CGeomLight3D *light) { LightList::iterator plight1 = lights_.begin(); LightList::iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) if (*plight1 == light) break; if (plight1 != plight2) { LightList::iterator plight0 = plight1; ++plight1; for ( ; plight1 != plight2; plight0 = plight1++) *plight0 = *plight1; lights_.pop_back(); } } void CGeomLight3DMgr:: modelToPixel(const CGeomCamera3D &camera) const { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->modelToPixel(camera); } void CGeomLight3DMgr:: drawWireframe(CGeomCamera3D &, CGeomZBuffer *) { //LightList::const_iterator plight1 = lights_.begin(); //LightList::const_iterator plight2 = lights_.end (); //for ( ; plight1 != plight2; ++plight1) // (*plight1)->drawWireframe(camera, zbuffer); } void CGeomLight3DMgr:: drawSolid(CGeomCamera3D &, CGeomZBuffer *) { //LightList::const_iterator plight1 = lights_.begin(); //LightList::const_iterator plight2 = lights_.end (); //for ( ; plight1 != plight2; ++plight1) // (*plight1)->drawSolid(camera, zbuffer); } CRGBA CGeomLight3DMgr:: lightPoint(const CPoint3D &point, const CVector3D &normal, const CMaterial &material) const { CRGBA rgba = material.getEmission(); rgba += getAmbient()*material.getAmbient(); LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->lightPoint(rgba, point, normal, material); rgba.setAlpha(material.getDiffuse().getAlpha()); return rgba; } CImagePtr CGeomLight3DMgr:: getImage() { static CImagePtr ptr; static bool read; if (! read) { CImageNameSrc src("CGeomLight3D/Sun"); ptr = CImageMgrInst->createImage(src); ptr->read(Sun_data, SUN_DATA_LEN); read = false; } return ptr; } void CGeomLight3DMgr:: moveX(double dx) { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->moveX(dx); } void CGeomLight3DMgr:: moveY(double dy) { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->moveY(dy); } void CGeomLight3DMgr:: moveZ(double dz) { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->moveZ(dz); } void CGeomLight3DMgr:: rotateX(double dx) { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->rotateX(dx); } void CGeomLight3DMgr:: rotateY(double dy) { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->rotateY(dy); } void CGeomLight3DMgr:: rotateZ(double dz) { LightList::const_iterator plight1 = lights_.begin(); LightList::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->getObject()->rotateZ(dz); } //---------- CGeomLight3D:: CGeomLight3D(CGeomScene3D *pscene, const std::string &name) { object_ = CGeometryInst->createObject3D(pscene, name); CGeomPyramid3D::addGeometry(object_, 0, 0, 0, 0.1, 0.1); object_->rotateModelX(-M_PI*0.5); object_->unsetFaceFlags(CGeomFace3D::LIGHTED); object_->setFaceColor(CRGBA(1,1,0)); } CGeomLight3D:: CGeomLight3D(const CGeomLight3D &light) : mgr_ (light.mgr_), object_ (light.object_), data_ (light.data_), enabled_(light.enabled_) { } CGeomLight3D & CGeomLight3D:: operator=(const CGeomLight3D &light) { mgr_ = light.mgr_; object_ = light.object_; data_ = light.data_; enabled_ = light.enabled_; return *this; } void CGeomLight3D:: drawImage(CGeomZBuffer *zbuffer) { if (mgr_) { CImagePtr image = mgr_->getImage(); const CPoint3D &pixel = object_->getPositionPoint().getPixel(); zbuffer->drawImage(int(pixel.x), int(pixel.y), pixel.z, image); } } void CGeomLight3D:: lightPoint(CRGBA &rgba, const CPoint3D &point, const CVector3D &normal, const CMaterial &material) const { if (! getEnabled()) return; // Ambient CRGBA ambient = getAmbient()*material.getAmbient(); // Diffuse CVector3D dlight(point, object_->getPositionPoint().getViewed()); dlight.normalize(); //uncomment if light both sides //double dot = fabs(dlight.dotProduct(normal)); double dot = dlight.dotProduct(normal); if (dot < 0.0) dot = 0.0; CRGBA diffuse = dot*getDiffuse()*material.getDiffuse(); // Specular CRGBA specular(0,0,0,1); if (dot > 0.0) { CVector3D viewpoint(0,0,1); CVector3D sum(viewpoint + dlight); sum.normalize(); double dot1 = sum.dotProduct(normal); if (dot1 < 0.0) dot1 = 0.0; specular = pow(dot1, material.getShininess())*getSpecular()*material.getSpecular(); } double dist = CVector3D(point, object_->getPositionPoint().getViewed()).length(); rgba += getAttenuation(dist)*getSpotEffect(point)*(ambient + diffuse + specular); //rgba += diffuse; rgba.setAlpha(material.getDiffuse().getAlpha()); }
20.329861
91
0.682152
colinw7
9ee63a11f3a00f146be2413047aad5fc8465af25
461
cpp
C++
Fast Fibonacci/Fast Fibonacci/main.cpp
brunorabelo/URI-Online-Judge
87051c4fa7339c0ed6d9613739b70cedea2fe090
[ "MIT" ]
null
null
null
Fast Fibonacci/Fast Fibonacci/main.cpp
brunorabelo/URI-Online-Judge
87051c4fa7339c0ed6d9613739b70cedea2fe090
[ "MIT" ]
null
null
null
Fast Fibonacci/Fast Fibonacci/main.cpp
brunorabelo/URI-Online-Judge
87051c4fa7339c0ed6d9613739b70cedea2fe090
[ "MIT" ]
null
null
null
// // main.cpp // Fast Fibonacci // // Created by MacBook on 02/05/17. // Copyright © 2017 Bruno Botelho. All rights reserved. // #include <stdio.h> #include <math.h> int main(int argc, const char * argv[]) { // insert code here... int n; double result; scanf("%d",&n); result= pow(((1+sqrt(5))/2.0),n)-pow((1-sqrt(5))/2.0, n); result/=sqrt(5); printf("%.1lf\n",result); return 0; }
15.366667
61
0.518438
brunorabelo
9ee66585da00aa5a4f090a4e5378a7a608273a44
1,626
hpp
C++
GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/graph_optimizer/g2o/edge/edge_se3_priorxyz.hpp
lanqing30/SensorFusionCourse
3fcf935d6a4191563afcf2d95b34718fba7f705a
[ "Apache-2.0" ]
7
2021-03-19T05:51:44.000Z
2021-09-16T06:10:16.000Z
03-localization with map/lidar_localization/include/lidar_localization/models/graph_optimizer/g2o/edge/edge_se3_priorxyz.hpp
WeihengXia0123/LiDar-SLAM
834060da7ee0125cefd310d6215821551bac16c3
[ "MIT" ]
null
null
null
03-localization with map/lidar_localization/include/lidar_localization/models/graph_optimizer/g2o/edge/edge_se3_priorxyz.hpp
WeihengXia0123/LiDar-SLAM
834060da7ee0125cefd310d6215821551bac16c3
[ "MIT" ]
6
2021-02-17T12:31:08.000Z
2022-01-22T17:12:44.000Z
/* * @Description: GNSS 坐标做观测时使用的先验边 * @Author: Ren Qian * @Date: 2020-03-01 18:05:35 */ #ifndef LIDAR_LOCALIZATION_MODELS_GRAPH_OPTIMIZER_G2O_EDGE_EDGE_SE3_PRIORXYZ_HPP_ #define LIDAR_LOCALIZATION_MODELS_GRAPH_OPTIMIZER_G2O_EDGE_EDGE_SE3_PRIORXYZ_HPP_ #include <g2o/types/slam3d/types_slam3d.h> #include <g2o/types/slam3d_addons/types_slam3d_addons.h> namespace g2o { class EdgeSE3PriorXYZ : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW EdgeSE3PriorXYZ() :g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3>() { } void computeError() override { const g2o::VertexSE3* v1 = static_cast<const g2o::VertexSE3*>(_vertices[0]); Eigen::Vector3d estimate = v1->estimate().translation(); _error = estimate - _measurement; } void setMeasurement(const Eigen::Vector3d& m) override { _measurement = m; } virtual bool read(std::istream& is) override { Eigen::Vector3d v; is >> v(0) >> v(1) >> v(2); setMeasurement(Eigen::Vector3d(v)); for (int i = 0; i < information().rows(); ++i) { for (int j = i; j < information().cols(); ++j) { is >> information()(i, j); // update cross-diagonal element: if (i != j) { information()(j, i) = information()(i, j); } } } return true; } virtual bool write(std::ostream& os) const override { Eigen::Vector3d v = _measurement; os << v(0) << " " << v(1) << " " << v(2) << " "; for (int i = 0; i < information().rows(); ++i) for (int j = i; j < information().cols(); ++j) os << " " << information()(i, j); return os.good(); } }; } #endif
26.225806
87
0.646986
lanqing30
9eeabe215b2ffe2a8763142d9ee64ea8c27c4a8b
2,834
cc
C++
libcurv/program.cc
curv3d/curv
f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a
[ "Apache-2.0" ]
921
2019-01-13T18:47:47.000Z
2022-03-28T03:36:18.000Z
libcurv/program.cc
curv3d/curv
f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a
[ "Apache-2.0" ]
93
2019-01-11T15:35:01.000Z
2022-01-14T17:42:05.000Z
libcurv/program.cc
curv3d/curv
f3b7a0045b681df86ec25f1f97c4e6feb7dd5c6a
[ "Apache-2.0" ]
59
2019-01-20T09:37:59.000Z
2022-02-17T15:12:10.000Z
// Copyright 2016-2021 Doug Moen // Licensed under the Apache License, version 2.0 // See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0 #include <libcurv/program.h> #include <libcurv/analyser.h> #include <libcurv/builtin.h> #include <libcurv/context.h> #include <libcurv/definition.h> #include <libcurv/exception.h> #include <libcurv/parser.h> #include <libcurv/scanner.h> #include <libcurv/system.h> namespace curv { struct File_Phrase : public Phrase { Src_Loc loc_; File_Phrase(const Filesystem::path& path, Source::Type type) : loc_{make<Source>(path.string(), type), Token{}} { } virtual Src_Loc location() const override { return loc_; } virtual Shared<Meaning> analyse(Environ& env, Interp) const override { throw Exception(At_Phrase(*this, env), "internal error: File_Phrase::analyse"); } }; void Program::compile(Shared<const Source> source, Scanner_Opts scopts, Environ& env, Interp terp) { Scanner scanner(move(source), sstate_, scopts); phrase_ = parse_program(scanner); if (auto def = phrase_->as_definition(env, Fail::soft)) { module_ = analyse_module(*def, env); } else { meaning_ = phrase_->analyse(env, terp); } frame_ = {make_tail_array<Frame>(env.frame_maxslots_, sstate_, sstate_.file_frame_, nullptr, nullptr)}; } void Program::compile(Shared<const Source> source, Environ& env, Interp terp) { compile(move(source), Scanner_Opts(), env, terp); } void Program::compile(Shared<const Source> source) { Builtin_Environ env{sstate_.system_.std_namespace(), sstate_}; compile(move(source), env, Interp::expr()); } void Program::compile(Shared<const Source> source, Scanner_Opts scopts) { Builtin_Environ env{sstate_.system_.std_namespace(), sstate_}; compile(move(source), scopts, env, Interp::expr()); } void Program::compile(Filesystem::path path, Source::Type type, Value val) { value_ = val; phrase_ = make<File_Phrase>(path, type); } const Phrase& Program::syntax() const { return *nub_phrase(phrase_); } Value Program::eval() { if (value_) return value_; else if (module_ != nullptr) { throw Exception(At_Program(*this), "definition found; expecting an expression"); } else { auto expr = meaning_->to_operation(sstate_); frame_->next_op_ = &*expr; return tail_eval_frame(move(frame_)); } } Shared<Module> Program::exec(Operation::Executor& ex) { if (value_) { ex.push_value(value_, At_Program(*this)); return nullptr; } else if (module_) { return module_->eval_module(*frame_); } else { auto op = meaning_->to_operation(sstate_); op->exec(*frame_, ex); return nullptr; } } } // namespace curv
24.859649
79
0.666196
curv3d
9eeac48053307fb03a645a6874a8da9a77eb374c
956
cpp
C++
CodeForces/304A - Pythagorean Theorem II.cpp
MrSiz/Coding
6e3454c9143563748b98f192102c3b6ff4c3be4f
[ "MIT" ]
null
null
null
CodeForces/304A - Pythagorean Theorem II.cpp
MrSiz/Coding
6e3454c9143563748b98f192102c3b6ff4c3be4f
[ "MIT" ]
null
null
null
CodeForces/304A - Pythagorean Theorem II.cpp
MrSiz/Coding
6e3454c9143563748b98f192102c3b6ff4c3be4f
[ "MIT" ]
null
null
null
#include <set> #include <queue> #include <string> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <climits> #include <iostream> #include <map> #include <cmath> #include <algorithm> using namespace std; #define pr(x) //(cout << #x << ' ' << x << ' ') #define prln(x) //(cout << #x << ' ' << x << endl) #define ll long long void file() { freopen("in.txt", "r", stdin); } int main() { //file(); int n; prln(1111); scanf("%d", &n); int cnt = 0; prln(n); for (int i = 1; i <= n; ++i){ prln(11); for (int j = i + 1; j <= n; ++j){ int temp = i * i + j * j; int k = sqrt(temp); if (k > n) continue; if (k * k != temp) continue; if (i + j > k && i + k > j && j + k > i) cnt++; } } prln(12333); printf("%d\n", cnt); return 0; }
19.12
50
0.433054
MrSiz