hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
601bd697fc193f02877d446a76b53f1984261c15
674
hpp
C++
daemon/examples/gui/functions.hpp
Krozark/Salamandre
75cfd7f3868ed159711c14792920fc0c0db2b3f1
[ "BSD-2-Clause" ]
null
null
null
daemon/examples/gui/functions.hpp
Krozark/Salamandre
75cfd7f3868ed159711c14792920fc0c0db2b3f1
[ "BSD-2-Clause" ]
null
null
null
daemon/examples/gui/functions.hpp
Krozark/Salamandre
75cfd7f3868ed159711c14792920fc0c0db2b3f1
[ "BSD-2-Clause" ]
null
null
null
#ifndef FUNCTIONS_HPP #define FUNCTIONS_HPP #include <string> #include <vector> #define ROOT_DIR "gui/save" /** * \brief define some class used later */ namespace ntw { namespace cli { class Client; } } namespace test { /** * \param id_medecin the medecin id * \param id_patient the patient id * \param filepath the filename */ void createFile(int id_medecin,int id_patient,const std::string& filename,std::vector<std::string>& file_paths); /** * */ void moveForSave(int id_medecin,int id_patient,const std::string& filename,std::vector<std::string>& file_to_signal,const std::string& to); } #endif
18.216216
143
0.661721
[ "vector" ]
601c052f441286242414be50e8b8f4a5fbada4d7
4,140
cc
C++
src/solvers/test/solver_linear_jfnk.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/solvers/test/solver_linear_jfnk.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/solvers/test/solver_linear_jfnk.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
#include <iostream> #include "UnitTest++.h" #include "Teuchos_RCP.hpp" #include "Epetra_MpiComm.h" #include "Epetra_Vector.h" #include "exceptions.hh" #include "FnBaseDefs.hh" #include "SolverJFNK.hh" #include "SolverFnBase.hh" using namespace Amanzi; SUITE(SOLVERS) { class LinearFn : public AmanziSolvers::SolverFnBase<Epetra_Vector> { public: LinearFn() {} LinearFn(const Teuchos::RCP<Epetra_Map>& map) : map_(map) { rhs_ = Teuchos::rcp(new Epetra_Vector(*map_)); soln_ = Teuchos::rcp(new Epetra_Vector(*map_)); }; ~LinearFn() {}; LinearFn(const LinearFn& other) : map_(other.map_) {} Teuchos::RCP<LinearFn> Clone() const { return Teuchos::rcp(new LinearFn(*this)); } // computes the non-linear functional r = F(u) virtual void Residual(const Teuchos::RCP<Epetra_Vector>& u, const Teuchos::RCP<Epetra_Vector>& r) { Apply(*u, *r); r->Update(-1., *rhs_, 1.); } // preconditioner toolkit virtual int ApplyPreconditioner(const Teuchos::RCP<const Epetra_Vector>& r, const Teuchos::RCP<Epetra_Vector>& Pr) { return ApplyInverse(*r, *Pr); } virtual void UpdatePreconditioner(const Teuchos::RCP<const Epetra_Vector>& u) {} // error analysis virtual double ErrorNorm(const Teuchos::RCP<const Epetra_Vector>& u, const Teuchos::RCP<const Epetra_Vector>& du) { double res; du->NormInf(&res); return res; } virtual int Apply(const Epetra_Vector& v, Epetra_Vector& mv) const { for (int i = 0; i < 5; i++) mv[i] = 2 * v[i]; for (int i = 1; i < 5; i++) mv[i] -= v[i - 1]; for (int i = 0; i < 4; i++) mv[i] -= v[i + 1]; return 0; } virtual int ApplyInverse(const Epetra_Vector& v, Epetra_Vector& hv) const { for (int i = 0; i < 5; i++) hv[i] = v[i]; return 0; } void SetSolution(const Epetra_Vector& soln) { *soln_ = soln; Apply(soln, *rhs_); } bool CheckSolution(const Epetra_Vector& soln) { for (int i=0; i< 5; i++) { CHECK_CLOSE(soln[i], (*soln_)[i], 1e-6); } return true; } virtual const Epetra_Map& DomainMap() const { return *map_; } virtual const Epetra_Map& RangeMap() const { return *map_; } private: Teuchos::RCP<Epetra_Map> map_; Teuchos::RCP<Epetra_Vector> rhs_; Teuchos::RCP<Epetra_Vector> soln_; }; TEST(JFNK_SOLVER_LINEAR) { std::cout << "Checking JFNK solver on linear problem..." << std::endl; Epetra_MpiComm* comm = new Epetra_MpiComm(MPI_COMM_SELF); Teuchos::RCP<Epetra_Map> map = Teuchos::rcp(new Epetra_Map(5, 0, *comm)); // create the SolverFnBase object Teuchos::RCP<LinearFn> fn = Teuchos::rcp(new LinearFn(map)); Epetra_Vector soln(*map); soln[0] = -0.1666666666666; soln[1] = 0.6666666666666; soln[2] = 0.5; soln[3] = 0.33333333333333; soln[4] = 0.16666666666666; fn->SetSolution(soln); // create the JFNK object Teuchos::ParameterList jfnk_list; jfnk_list.sublist("nonlinear solver").set("solver type", "Newton"); jfnk_list.sublist("nonlinear solver").sublist("Newton parameters").sublist("verbose object") .set("verbosity level", "extreme"); jfnk_list.sublist("nonlinear solver").sublist("Newton parameters").set("monitor", "monitor residual"); jfnk_list.sublist("JF matrix parameters").set("finite difference epsilon", 1e-7); jfnk_list.sublist("linear operator").set("iterative method", "pcg"); jfnk_list.sublist("linear operator").sublist("pcg parameters").sublist("verbose object") .set("verbosity level", "extreme"); Teuchos::RCP<AmanziSolvers::SolverJFNK<Epetra_Vector,Epetra_Map> > jfnk = Teuchos::rcp(new AmanziSolvers::SolverJFNK<Epetra_Vector,Epetra_Map>(jfnk_list)); jfnk->Init(fn, *map); // initial guess Teuchos::RCP<Epetra_Vector> u = Teuchos::rcp(new Epetra_Vector(*map)); jfnk->Solve(u); fn->CheckSolution(*u); CHECK_EQUAL(1, jfnk->num_itrs()); delete comm; }; }
30.666667
106
0.624638
[ "object" ]
601ea0d0e977b47a48f86020cee18fc602c2edc8
9,206
cpp
C++
src/common/updating/updating.cpp
darecluval/PowerToys
0840fce32e58c25e5273ffd84b43f8187183f7fa
[ "MIT" ]
6
2021-04-15T14:07:17.000Z
2021-09-05T13:31:32.000Z
src/common/updating/updating.cpp
sahwar/PowerToys
ff4a78a7f93a3b63e605ae955745d3f40d4608d4
[ "MIT" ]
null
null
null
src/common/updating/updating.cpp
sahwar/PowerToys
ff4a78a7f93a3b63e605ae955745d3f40d4608d4
[ "MIT" ]
3
2021-09-05T13:31:36.000Z
2021-10-03T16:23:26.000Z
#include "pch.h" #include <common/version/version.h> #include <common/version/helper.h> #include "http_client.h" #include "notifications.h" #include "updating.h" #include <common/utils/json.h> #include <common/SettingsAPI/settings_helpers.h> #include <common/notifications/notifications.h> namespace // Strings in this namespace should not be localized { const wchar_t LATEST_RELEASE_ENDPOINT[] = L"https://api.github.com/repos/microsoft/PowerToys/releases/latest"; const wchar_t ALL_RELEASES_ENDPOINT[] = L"https://api.github.com/repos/microsoft/PowerToys/releases"; const size_t MAX_DOWNLOAD_ATTEMPTS = 3; } namespace updating { std::optional<VersionHelper> extract_version_from_release_object(const json::JsonObject& release_object) { try { return VersionHelper{ winrt::to_string(release_object.GetNamedString(L"tag_name")) }; } catch (...) { } return std::nullopt; } std::pair<Uri, std::wstring> extract_installer_asset_download_info(const json::JsonObject& release_object) { const std::wstring_view required_architecture = get_architecture_string(get_current_architecture()); constexpr const std::wstring_view required_filename_pattern = updating::INSTALLER_FILENAME_PATTERN; // Desc-sorted by its priority const std::array<std::wstring_view, 2> asset_extensions = { L".exe", L".msi" }; for (const auto asset_extension : asset_extensions) { for (auto asset_elem : release_object.GetNamedArray(L"assets")) { auto asset{ asset_elem.GetObjectW() }; std::wstring filename_lower = asset.GetNamedString(L"name", {}).c_str(); std::transform(begin(filename_lower), end(filename_lower), begin(filename_lower), ::towlower); const bool extension_matched = filename_lower.ends_with(asset_extension); const bool architecture_matched = filename_lower.find(required_architecture) != std::wstring::npos; const bool filename_matched = filename_lower.find(required_filename_pattern) != std::wstring::npos; const bool asset_matched = extension_matched && architecture_matched && filename_matched; if (extension_matched && architecture_matched && filename_matched) { return std::make_pair(Uri{ asset.GetNamedString(L"browser_download_url") }, std::move(filename_lower)); } } } throw std::runtime_error("Release object doesn't have the required asset"); } std::future<nonstd::expected<github_version_info, std::wstring>> get_github_version_info_async(const notifications::strings& strings, const bool prerelease) { // If the current version starts with 0.0.*, it means we're on a local build from a farm and shouldn't check for updates. if (VERSION_MAJOR == 0 && VERSION_MINOR == 0) { co_return nonstd::make_unexpected(strings.GITHUB_NEW_VERSION_USING_LOCAL_BUILD_ERROR); } try { http::HttpClient client; json::JsonObject release_object; const VersionHelper current_version(VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION); VersionHelper github_version = current_version; if (prerelease) { const auto body = co_await client.request(Uri{ ALL_RELEASES_ENDPOINT }); for (const auto& json : json::JsonValue::Parse(body).GetArray()) { auto potential_release_object = json.GetObjectW(); const bool is_prerelease = potential_release_object.GetNamedBoolean(L"prerelease", false); auto extracted_version = extract_version_from_release_object(potential_release_object); if (!is_prerelease || !extracted_version || *extracted_version <= github_version) { continue; } // Do not break, since https://developer.github.com/v3/repos/releases/#list-releases // doesn't specify the order in which release object appear github_version = std::move(*extracted_version); release_object = std::move(potential_release_object); } } else { const auto body = co_await client.request(Uri{ LATEST_RELEASE_ENDPOINT }); release_object = json::JsonValue::Parse(body).GetObjectW(); if (auto extracted_version = extract_version_from_release_object(release_object)) { github_version = *extracted_version; } } if (github_version <= current_version) { co_return version_up_to_date{}; } Uri release_page_url{ release_object.GetNamedString(L"html_url") }; auto installer_download_url = extract_installer_asset_download_info(release_object); co_return new_version_download_info{ std::move(release_page_url), std::move(github_version), std::move(installer_download_url.first), std::move(installer_download_url.second) }; } catch (...) { } co_return nonstd::make_unexpected(strings.GITHUB_NEW_VERSION_CHECK_ERROR); } bool could_be_costly_connection() { using namespace winrt::Windows::Networking::Connectivity; ConnectionProfile internetConnectionProfile = NetworkInformation::GetInternetConnectionProfile(); return internetConnectionProfile.IsWwanConnectionProfile(); } std::filesystem::path get_pending_updates_path() { auto path_str{ PTSettingsHelper::get_root_save_folder_location() }; path_str += L"\\Updates"; return { std::move(path_str) }; } std::filesystem::path create_download_path() { auto installer_download_dst = get_pending_updates_path(); std::error_code _; std::filesystem::create_directories(installer_download_dst, _); return installer_download_dst; } std::future<bool> try_autoupdate(const bool download_updates_automatically, const notifications::strings& strings) { const auto version_check_result = co_await get_github_version_info_async(strings); if (!version_check_result) { co_return false; } if (std::holds_alternative<version_up_to_date>(*version_check_result)) { co_return true; } const auto new_version = std::get<new_version_download_info>(*version_check_result); if (download_updates_automatically && !could_be_costly_connection()) { auto installer_download_dst = create_download_path() / new_version.installer_filename; bool download_success = false; for (size_t i = 0; i < MAX_DOWNLOAD_ATTEMPTS; ++i) { try { http::HttpClient client; co_await client.download(new_version.installer_download_url, installer_download_dst); download_success = true; break; } catch (...) { // reattempt to download or do nothing } } if (!download_success) { updating::notifications::show_install_error(new_version, strings); co_return false; } updating::notifications::show_version_ready(new_version, strings); } else { updating::notifications::show_visit_github(new_version, strings); } co_return true; } std::future<std::wstring> download_update(const notifications::strings& strings) { const auto version_check_result = co_await get_github_version_info_async(strings); if (!version_check_result || std::holds_alternative<version_up_to_date>(*version_check_result)) { co_return L""; } const auto new_version = std::get<new_version_download_info>(*version_check_result); auto installer_download_dst = create_download_path() / new_version.installer_filename; updating::notifications::show_download_start(new_version, strings); try { auto progressUpdateHandle = [&](float progress) { updating::notifications::update_download_progress(new_version, progress, strings); }; http::HttpClient client; co_await client.download(new_version.installer_download_url, installer_download_dst, progressUpdateHandle); } catch (...) { updating::notifications::show_install_error(new_version, strings); co_return L""; } co_return new_version.installer_filename; } }
41.845455
160
0.620465
[ "object", "transform" ]
e747917ab4e9010a0151d4dcbdf0690afb93519c
1,546
cpp
C++
iree/compiler/Dialect/Shape/IR/ShapeInterface.cpp
schoppmp/iree
d573c3dbb4eef8044764ae6d80ca79e37e8de522
[ "Apache-2.0" ]
2
2021-10-03T15:58:09.000Z
2021-11-17T10:34:35.000Z
iree/compiler/Dialect/Shape/IR/ShapeInterface.cpp
BernhardRiemann/iree
471349762b316f7d6b83eb5f9089255d78052758
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/Shape/IR/ShapeInterface.cpp
BernhardRiemann/iree
471349762b316f7d6b83eb5f9089255d78052758
[ "Apache-2.0" ]
1
2021-01-29T09:30:09.000Z
2021-01-29T09:30:09.000Z
// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Dialect/Shape/IR/ShapeInterface.h" namespace mlir { namespace iree_compiler { namespace Shape { //===----------------------------------------------------------------------===// // CallbackCustomOpShapeBuilder //===----------------------------------------------------------------------===// void CallbackCustomOpShapeBuilder::insertRankedShapeBuilder( llvm::StringRef operationName, RankedShapeBuilder callback) { rankedShapeBuilders.insert( std::make_pair(operationName, std::move(callback))); } Value CallbackCustomOpShapeBuilder::buildRankedShape( RankedShapeType resultShape, Operation *inputOperation, OpBuilder &builder) { auto it = rankedShapeBuilders.find(inputOperation->getName().getStringRef()); if (it == rankedShapeBuilders.end()) { return nullptr; } return it->second(resultShape, inputOperation, builder); } } // namespace Shape } // namespace iree_compiler } // namespace mlir
35.136364
80
0.677232
[ "shape" ]
e74b0f7eb41e93d457f05b576673991bea270aa6
17,516
cpp
C++
src/classad_support/collectionServer.cpp
sridish123/htcondor
481d975fd8602242f6a052aab04e20b0b560db89
[ "Apache-2.0" ]
217
2015-01-08T04:49:42.000Z
2022-03-27T10:11:58.000Z
src/classad_support/collectionServer.cpp
sridish123/htcondor
481d975fd8602242f6a052aab04e20b0b560db89
[ "Apache-2.0" ]
185
2015-05-03T13:26:31.000Z
2022-03-28T03:08:59.000Z
src/classad_support/collectionServer.cpp
sridish123/htcondor
481d975fd8602242f6a052aab04e20b0b560db89
[ "Apache-2.0" ]
133
2015-02-11T09:17:45.000Z
2022-03-31T07:28:54.000Z
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "condor_attributes.h" #include "condor_io.h" #include "classad/common.h" #include "classad/transaction.h" #include "collectionServer.h" using namespace std; namespace classad { ClassAdCollectionServer:: ClassAdCollectionServer( ) : ClassAdCollection() { // Our parent, ClassAdCollection, handles everything. return; } ClassAdCollectionServer:: ~ClassAdCollectionServer( ) { // Our parent, ClassAdCollection, handles everything. return; } //------------------------------------------------------------------------------ // Remote network mode interface //------------------------------------------------------------------------------ int ClassAdCollectionServer:: HandleClientRequest( int command, Sock *clientSock ) { ClassAd *rec=NULL; char *tmp=NULL; string buffer; CondorErrno = ERR_OK; CondorErrMsg = ""; // if the operation is "connect", just keep the sock and return if( command == ClassAdCollOp_Connect ) { clientSock->decode( ); clientSock->end_of_message( ); return( 1 ); } // if the operation is "disconnect", just close the client sock if( command == ClassAdCollOp_Disconnect ) { clientSock->decode( ); clientSock->end_of_message( ); return( 0 ); } // read the classad off the wire if( !clientSock->get( tmp ) || !clientSock->end_of_message( ) ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "failed to read client request"; return( -1 ); } // parse the classad buffer = tmp; free( tmp ); // the 'rec' classad below is deleted by HandleQuery, HandleReadOnly..., // or OperateInNetworkMode as necessary if( !( rec = parser.ParseClassAd( buffer ) ) ) { CondorErrMsg += "; failed to parse client request"; return( -1 ); } // handle query command if( command == ClassAdCollOp_QueryView ) { return( HandleQuery( rec, clientSock ) ? +1 : -1 ); } // handle read only commands separate from modify commands if( command >= __ClassAdCollOp_ReadOps_Begin__ && command <= __ClassAdCollOp_ReadOps_End__ ) { return( HandleReadOnlyCommands( command, rec, clientSock ) ? +1 : -1 ); } // else handle command in "network mode" ... return( OperateInNetworkMode( command, rec, clientSock ) ? +1 : -1 ); } bool ClassAdCollectionServer:: OperateInNetworkMode( int opType, ClassAd *logRec, Sock *clientSock ) { int ackOpType; bool failed = false; ClassAd ack; switch( opType ) { // acks for open and commit xaction operations case ClassAdCollOp_OpenTransaction: case ClassAdCollOp_CommitTransaction: case ClassAdCollOp_AbortTransaction: case ClassAdCollOp_ForgetTransaction: { string xactionName; ServerTransaction *xaction; logRec->EvaluateAttrString( "XactionName", xactionName ); // set the ack type if( opType == ClassAdCollOp_OpenTransaction ) { ackOpType = ClassAdCollOp_AckOpenTransaction; ack.InsertAttr( ATTR_OP_TYPE,ClassAdCollOp_AckOpenTransaction ); } else if( opType == ClassAdCollOp_CommitTransaction ) { ackOpType = ClassAdCollOp_AckCommitTransaction; ack.InsertAttr(ATTR_OP_TYPE,ClassAdCollOp_AckCommitTransaction); } // (abort and forget don't have acks) // play the transaction operation if( !PlayXactionOp( opType, xactionName, logRec, xaction ) ) { // if failed, insert error cause in ack and kill xaction failed = true; delete logRec; ClassAd *errorCause = xaction->ExtractErrorCause( ); ack.Insert( "ErrorCause", errorCause ); if( xaction ) delete xaction; xactionTable.erase( xactionName ); break; } // don't delete logRec just yet --- need it for WriteLogEntry // in ForgetTransaction case below if( opType == ClassAdCollOp_CommitTransaction ) { // log transaction if possible (the xaction is logged only // after it is played on the in-memory data structure so that // we make a persistent record of the xaction iff the // in-memory commit succeeds) if( !xaction || !xaction->Log( log_fp, &unparser ) ) { delete logRec; CondorErrno = ERR_FATAL_ERROR; CondorErrMsg = "FATAL ERROR: in memory commit succeeded, " "but log failed"; return( false ); } } else if( opType == ClassAdCollOp_ForgetTransaction ) { // no ack for ForgetTransaction bool rval = WriteLogEntry( log_fp, logRec ); delete logRec; return( rval ); } else if( opType == ClassAdCollOp_AbortTransaction ) { // no ack for abort transaction, and no logging either delete logRec; return( true ); } // opType must be OpenTransaction or CommitTransaction here // (if CommitTransaction, the xaction has also been logged) delete logRec; break; } // all view ops require acks case ClassAdCollOp_CreateSubView: case ClassAdCollOp_CreatePartition: case ClassAdCollOp_DeleteView: case ClassAdCollOp_SetViewInfo: { ackOpType = ClassAdCollOp_AckViewOp; ack.InsertAttr( ATTR_OP_TYPE, ClassAdCollOp_AckViewOp ); failed= !PlayViewOp(opType,logRec) || !WriteLogEntry(log_fp,logRec); delete logRec; break; } // acks for classad ops only if requested case ClassAdCollOp_AddClassAd: case ClassAdCollOp_UpdateClassAd: case ClassAdCollOp_ModifyClassAd: case ClassAdCollOp_RemoveClassAd: { string xactionName, key; bool wantAck = false; logRec->EvaluateAttrString( "XactionName", xactionName ); logRec->EvaluateAttrBool( "WantAck", wantAck ); logRec->EvaluateAttrString( "Key", key ); ack.InsertAttr( ATTR_OP_TYPE, ClassAdCollOp_AckClassAdOp ); ackOpType = ClassAdCollOp_AckClassAdOp; if( xactionName == "" ) { // not in xaction; just play the operation failed = !PlayClassAdOp( opType, logRec ) || !WriteLogEntry(log_fp,logRec ); delete logRec; if( !wantAck ) return( !failed ); break; } // in transaction; add record to transaction ServerTransaction *xaction; XactionTable::iterator itr = xactionTable.find( xactionName ); if( itr == xactionTable.end( ) ) { CondorErrno = ERR_NO_SUCH_TRANSACTION; CondorErrMsg = "transaction "+xactionName+" doesn't exist"; if( wantAck ) { ack.Insert( "ErrorCause", logRec ); break; } else { delete logRec; } return( true ); } xaction = itr->second; xaction->AppendRecord( opType, key, logRec ); if( !wantAck ) return( true ); } } // send the ack to the client string buffer; ack.InsertAttr( "CondorErrno", failed ? CondorErrno : ERR_OK ); ack.InsertAttr( "CondorErrMsg", failed ? CondorErrMsg : "" ); unparser.Unparse( buffer, &ack ); clientSock->encode( ); if(!clientSock->put(ackOpType) || !clientSock->put((char*)buffer.c_str()) || !clientSock->end_of_message( ) ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "unable to send ack to client"; return( false ); } return( true ); } bool ClassAdCollectionServer:: HandleQuery( ClassAd *query, Sock *clientSock ) { string viewName, key, buffer; MatchClassAd mad; vector<string> attrs; bool wantResults, wantPostlude; ExprTree *tProjAttrs; // unpack attributes; assume reasonable defaults on error if( !query->EvaluateAttrString( ATTR_VIEW_NAME, viewName ) ) { viewName = "root"; } if( !query->EvaluateAttrBool( "WantResults", wantResults ) ) { wantResults = true; } if( !query->EvaluateAttrBool( "WantPostlude", wantPostlude ) ) { wantPostlude = false; } if( wantResults ) { // unpack projection attributes tProjAttrs = query->Lookup( "ProjectionAttrs" ); if( tProjAttrs && tProjAttrs->GetKind( )==ExprTree::EXPR_LIST_NODE ) { ExprListIterator itr; Value val; string attr; itr.Initialize( (ExprList*)tProjAttrs ); while( !itr.IsAfterLast( ) ) { itr.CurrentValue( val ); if( val.IsStringValue( attr ) ) { attrs.push_back( attr ); } itr.NextExpr( ); } if( attrs.size( ) == 0 ) { tProjAttrs = NULL; } } } // setup to evaluate query View *view; ClassAd *ad; ViewMembers::iterator vmi; ViewRegistry::iterator vri = viewRegistry.find( viewName ); int count = 0; bool match; vector<string>::iterator itr; ExprTree *tree; if( vri == viewRegistry.end( ) ) { CondorErrno = ERR_NO_SUCH_VIEW; CondorErrMsg = "view " + viewName + " not found"; goto cleanup; } view = vri->second; mad.ReplaceLeftAd( query ); clientSock->encode( ); // iterate over view members for( vmi=view->viewMembers.begin(); vmi!=view->viewMembers.end(); vmi++ ) { // test the match vmi->GetKey( key ); ad = GetClassAd( key ); mad.ReplaceRightAd( ad ); match = false; mad.EvaluateAttrBool( "RightMatchesLeft", match ); mad.RemoveRightAd( ); if( match ) { count++; // send ad if necessary if( wantResults ) { buffer = "[Key=\"" + key; buffer += "\";Ad="; // if no projection attrs specified, send whole ad if( !tProjAttrs ) { unparser.Unparse( buffer, ad ); } else { // project ad's attributes buffer += "["; for( itr=attrs.begin( ); itr!=attrs.end( ); itr++ ) { if( ( tree = ad->Lookup( *itr ) ) ) { buffer += *itr; buffer += " = "; unparser.Unparse( buffer, tree ); buffer += ";"; } } buffer += "]"; } buffer += "]"; if( !clientSock->put((char*)buffer.c_str()) ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "failed to send query results"; return( false ); } } } } // send <done> if( !clientSock->put("<done>") ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "failed to send result delimiter <done>"; return( false ); } cleanup: // if postlude is requested, send it if( wantPostlude ) { // reuse query ad memory query->Clear( ); query->InsertAttr( ATTR_VIEW_NAME, viewName ); query->InsertAttr( "NumResults", count ); query->InsertAttr( "CondorErrno", CondorErrno ); query->InsertAttr( "CondorErrMsg", CondorErrMsg ); buffer = ""; unparser.Unparse( buffer, query ); if( !clientSock->put( (char*)buffer.c_str( ) ) ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "failed to send query postlude"; return( false ); } } if( !clientSock->end_of_message( ) ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "failed to send end_of_message() to client"; return( false ); } return( true ); } bool ClassAdCollectionServer:: HandleReadOnlyCommands( int command, ClassAd *rec, Sock *clientSock ) { string buffer; ClassAd ack; ack.InsertAttr( ATTR_OP_TYPE, ClassAdCollOp_AckReadOp ); switch( command ) { case ClassAdCollOp_GetClassAd: { string key; ClassAd *ad; if( !rec->EvaluateAttrString( ATTR_KEY, key ) ) { CondorErrno = ERR_NO_KEY; CondorErrMsg = "bad or missing key"; } else if( ( ad = GetClassAd( key ) ) ) { ack.Insert( ATTR_AD, ad ); CondorErrno = ERR_OK; CondorErrMsg = ""; } ack.InsertAttr( "CondorErrno", CondorErrno ); ack.InsertAttr( "CondorErrMsg", CondorErrMsg ); unparser.Unparse( buffer, &ack ); // remove ad from ack so that it is not destroyed! ack.Remove( ATTR_AD ); break; } case ClassAdCollOp_GetViewInfo: { string viewName; ClassAd *viewInfo; if( !rec->EvaluateAttrString( ATTR_VIEW_NAME, viewName ) ) { CondorErrno = ERR_NO_VIEW_NAME; CondorErrMsg = "bad or missing view name"; } else if( GetViewInfo( viewName, viewInfo ) ) { ack.Insert( ATTR_VIEW_INFO, viewInfo ); CondorErrno = ERR_OK; CondorErrMsg = ""; } ack.InsertAttr( "CondorErrno", CondorErrno ); ack.InsertAttr( "CondorErrMsg", CondorErrMsg ); unparser.Unparse( buffer, &ack ); break; } case ClassAdCollOp_GetPartitionedViewNames: case ClassAdCollOp_GetSubordinateViewNames: { string viewName; vector<string> views; vector<string>::iterator vi; bool rval; if( !rec->EvaluateAttrString( ATTR_VIEW_NAME, viewName ) ) { ack.InsertAttr( "CondorErrno", ERR_NO_VIEW_NAME ); ack.InsertAttr( "CondorErrMsg","bad or missing view name" ); unparser.Unparse( buffer, &ack ); break; } rval = (command==ClassAdCollOp_GetPartitionedViewNames) ? GetPartitionedViewNames( viewName, views ): GetSubordinateViewNames( viewName, views ); // if unsuccessful if( !rval ) { ack.InsertAttr( "CondorErrno", CondorErrno ); ack.InsertAttr( "CondorErrMsg", CondorErrMsg ); unparser.Unparse( buffer, &ack ); break; } // else, pack view names into ack vector<ExprTree*> names; Value val; for( vi=views.begin( ); vi!=views.end( ); vi++ ) { val.SetStringValue( *vi ); names.push_back( Literal::MakeLiteral( val ) ); } ack.Insert( command==ClassAdCollOp_GetPartitionedViewNames? ATTR_PARTITIONED_VIEWS : ATTR_SUBORDINATE_VIEWS, ExprList::MakeExprList( names ) ); ack.InsertAttr( "CondorErrno", ERR_OK ); ack.InsertAttr( "CondorErrMsg", "" ); unparser.Unparse( buffer, &ack ); break; } case ClassAdCollOp_FindPartitionName: { string viewName, partition; ClassAd *rep; Value val; bool rval; if( !rec->EvaluateAttrString( ATTR_VIEW_NAME, viewName ) ) { ack.InsertAttr( "CondorErrno", ERR_NO_VIEW_NAME ); ack.InsertAttr( "CondorErrMsg", "bad or missing view name" ); unparser.Unparse( buffer, &ack ); break; } if( !rec->EvaluateAttr(ATTR_AD, val) || !val.IsClassAdValue(rep) ) { ack.InsertAttr( "CondorErrno", ERR_BAD_CLASSAD ); ack.InsertAttr("CondorErrMsg","bad or missing representative"); unparser.Unparse( buffer, &ack ); break; } rval = FindPartitionName( viewName, rep, partition ); ack.InsertAttr( "Result", rval ); ack.InsertAttr( "PartitionName", partition ); ack.InsertAttr( "CondorErrno", CondorErrno ); ack.InsertAttr( "CondorErrMsg", CondorErrMsg ); unparser.Unparse( buffer, &ack ); } case ClassAdCollOp_IsActiveTransaction: case ClassAdCollOp_IsCommittedTransaction: { string xactionName; bool rval; if( !rec->EvaluateAttrString( "XactionName", xactionName ) ) { ack.InsertAttr( "CondorErrno", ERR_NO_TRANSACTION_NAME ); ack.InsertAttr("CondorErrMsg","bad or missing transaction " "name"); unparser.Unparse( buffer, &ack ); break; } rval = ( command==ClassAdCollOp_IsActiveTransaction ) ? IsActiveTransaction( xactionName ) : IsCommittedTransaction( xactionName ); ack.InsertAttr( "Result", rval ); ack.InsertAttr( "CondorErrno", CondorErrno ); ack.InsertAttr( "CondorErrMsg", CondorErrMsg ); unparser.Unparse( buffer, &ack ); break; } case ClassAdCollOp_GetServerTransactionState: { string xactionName; int rval; if( !rec->EvaluateAttrString( "XactionName", xactionName ) ) { ack.InsertAttr( "CondorErrno", ERR_NO_TRANSACTION_NAME ); ack.InsertAttr("CondorErrMsg","bad or missing transaction " "name"); unparser.Unparse( buffer, &ack ); break; } if( IsActiveTransaction( xactionName ) ) { rval = ServerTransaction::ACTIVE; } else if( IsCommittedTransaction( xactionName ) ) { rval = ServerTransaction::COMMITTED; } else { rval = ServerTransaction::ABSENT; } ack.InsertAttr( "Result", rval ); ack.InsertAttr( "CondorErrno", CondorErrno ); ack.InsertAttr( "CondorErrMsg", CondorErrMsg ); unparser.Unparse( buffer, &ack ); break; } case ClassAdCollOp_GetAllActiveTransactions: case ClassAdCollOp_GetAllCommittedTransactions: { vector<string> xactionNames; vector<string>::iterator xi; if( command==ClassAdCollOp_GetAllActiveTransactions ) { GetAllActiveTransactions( xactionNames ); } else { GetAllCommittedTransactions( xactionNames ); } // pack names into ack vector<ExprTree*> names; Value val; for( xi=xactionNames.begin( ); xi!=xactionNames.end( ); xi++ ) { val.SetStringValue( *xi ); names.push_back( Literal::MakeLiteral( val ) ); } ack.Insert( command==ClassAdCollOp_GetAllActiveTransactions? "ActiveTransactions" : "CommittedTransactions", ExprList::MakeExprList( names ) ); ack.InsertAttr( "CondorErrno", ERR_OK ); ack.InsertAttr( "CondorErrMsg", "" ); unparser.Unparse( buffer, &ack ); break; } default: CLASSAD_EXCEPT( "invalid command: %d should not get here", command ); return( false ); } // send reply to client delete rec; clientSock->encode( ); if( !clientSock->put((int)ClassAdCollOp_AckReadOp) || !clientSock->put((char*)buffer.c_str( )) || !clientSock->end_of_message( ) ) { CondorErrno = ERR_COMMUNICATION_ERROR; CondorErrMsg = "unable to ack read command"; return( false ); } return( true ); } }
29.438655
80
0.66522
[ "vector" ]
e7530b5d4fb82b5beda77f55b62e127b4f73533e
4,241
hh
C++
include/qpdf/QPDFEFStreamObjectHelper.hh
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
1,812
2015-01-27T09:07:20.000Z
2022-03-30T23:03:15.000Z
include/qpdf/QPDFEFStreamObjectHelper.hh
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
584
2015-01-24T00:31:12.000Z
2022-03-24T21:42:38.000Z
include/qpdf/QPDFEFStreamObjectHelper.hh
tomty89/qpdf
e0775238b8b011755b9682555a8449b8a71f33eb
[ "Apache-2.0" ]
204
2015-04-09T16:28:06.000Z
2022-03-29T14:29:45.000Z
// Copyright (c) 2005-2021 Jay Berkenbilt // // This file is part of qpdf. // // 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. // // Versions of qpdf prior to version 7 were released under the terms // of version 2.0 of the Artistic License. At your option, you may // continue to consider qpdf to be licensed under those terms. Please // see the manual for additional information. #ifndef QPDFEFSTREAMOBJECTHELPER_HH #define QPDFEFSTREAMOBJECTHELPER_HH #include <qpdf/QPDFObjectHelper.hh> #include <qpdf/DLL.h> #include <qpdf/QPDFObjectHandle.hh> #include <functional> // This class provides a higher level interface around Embedded File // Streams, which are discussed in section 7.11.4 of the ISO-32000 PDF // specification. class QPDFEFStreamObjectHelper: public QPDFObjectHelper { public: QPDF_DLL QPDFEFStreamObjectHelper(QPDFObjectHandle); QPDF_DLL virtual ~QPDFEFStreamObjectHelper() = default; // Date parameters are strings that conform to the PDF spec for // date/time strings, which is "D:yyyymmddhhmmss<z>" where <z> is // either "Z" for UTC or "-hh'mm'" or "+hh'mm'" for timezone // offset. Examples: "D:20210207161528-05'00'", // "D:20210207211528Z". See QUtil::qpdf_time_to_pdf_time. QPDF_DLL std::string getCreationDate(); QPDF_DLL std::string getModDate(); // Get size as reported in the object; return 0 if not present. QPDF_DLL size_t getSize(); // Subtype is a mime type such as "text/plain" QPDF_DLL std::string getSubtype(); // Return the MD5 checksum as stored in the object as a binary // string. This does not check consistency with the data. If not // present, return an empty string. QPDF_DLL std::string getChecksum(); // Setters return a reference to this object so that they can be // used as fluent interfaces, e.g. // efsoh.setCreationDate(x).setModDate(y); // Create a new embedded file stream with the given stream data, // which can be provided in any of several ways. To get the new // object back, call getObjectHandle() on the returned object. The // checksum and size are computed automatically and stored. Other // parameters may be supplied using setters defined below. QPDF_DLL static QPDFEFStreamObjectHelper createEFStream(QPDF& qpdf, PointerHolder<Buffer> data); QPDF_DLL static QPDFEFStreamObjectHelper createEFStream(QPDF& qpdf, std::string const& data); // The provider function must write the data to the given // pipeline. The function may be called multiple times by the qpdf // library. You can pass QUtil::file_provider(filename) as the // provider to have the qpdf library provide the contents of // filename as a binary. QPDF_DLL static QPDFEFStreamObjectHelper createEFStream(QPDF& qpdf, std::function<void(Pipeline*)> provider); // Setters for other parameters QPDF_DLL QPDFEFStreamObjectHelper& setCreationDate(std::string const&); QPDF_DLL QPDFEFStreamObjectHelper& setModDate(std::string const&); // Set subtype as a mime-type, e.g. "text/plain" or // "application/pdf". QPDF_DLL QPDFEFStreamObjectHelper& setSubtype(std::string const&); private: QPDFObjectHandle getParam(std::string const& pkey); void setParam(std::string const& pkey, QPDFObjectHandle const&); static QPDFEFStreamObjectHelper newFromStream(QPDFObjectHandle stream); class Members { friend class QPDFEFStreamObjectHelper; public: QPDF_DLL ~Members() = default; private: Members(); Members(Members const&) = delete; }; PointerHolder<Members> m; }; #endif // QPDFEFSTREAMOBJECTHELPER_HH
34.479675
75
0.714926
[ "object" ]
e75eda290ab8c46e89766b2a7ce14d262f7423ec
1,164
cpp
C++
cpp/example_code/ses/verify_email_identity.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
null
null
null
cpp/example_code/ses/verify_email_identity.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
1
2020-03-18T17:00:15.000Z
2020-03-18T17:04:05.000Z
cpp/example_code/ses/verify_email_identity.cpp
brmur/aws-doc-sdk-examples
9158f493ee2c016f0b4a2260e8f43acc7b0b49e6
[ "Apache-2.0" ]
null
null
null
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 /* Purpose: verify_email_identity.cpp demonstrates how to send an Amazon SES verification email.] */ #include <aws/core/Aws.h> #include <aws/email/SESClient.h> #include <aws/email/model/VerifyEmailIdentityRequest.h> #include <aws/email/model/VerifyEmailIdentityResult.h> #include <iostream> int main(int argc, char **argv) { if (argc != 2) { std::cout << "Usage: verify_email_address <email_address>"; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String email_address(argv[1]); Aws::SES::SESClient ses; Aws::SES::Model::VerifyEmailIdentityRequest vea_req; vea_req.SetEmailAddress(email_address); auto vea_out = ses.VerifyEmailIdentity(vea_req); if (vea_out.IsSuccess()) { std::cout << "Email verification initiated" << std::endl; } else { std::cout << "Error initiating email verification" << vea_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options); return 0; }
24.25
92
0.649485
[ "model" ]
e7625727468e771f5dddc35bfc92d099331d2bd2
2,939
cpp
C++
src/capi/property.cpp
AspirinCode/chemfiles
155c0c28396e61db0adfc7a81a4c085abfe5c28a
[ "BSD-3-Clause" ]
2
2019-01-24T12:51:20.000Z
2019-01-24T12:51:24.000Z
src/capi/property.cpp
AspirinCode/chemfiles
155c0c28396e61db0adfc7a81a4c085abfe5c28a
[ "BSD-3-Clause" ]
null
null
null
src/capi/property.cpp
AspirinCode/chemfiles
155c0c28396e61db0adfc7a81a4c085abfe5c28a
[ "BSD-3-Clause" ]
null
null
null
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include "chemfiles/shared_allocator.hpp" #include "chemfiles/capi/property.h" #include "chemfiles/capi.hpp" #include "chemfiles/Property.hpp" using namespace chemfiles; static_assert(sizeof(chfl_property_kind) == sizeof(int), "Wrong size for chfl_property_kind enum"); extern "C" CHFL_PROPERTY* chfl_property_bool(bool value) { CHFL_PROPERTY* property = nullptr; CHFL_ERROR_GOTO( property = shared_allocator::make_shared<Property>(value); ) return property; error: chfl_free(property); return nullptr; } extern "C" CHFL_PROPERTY* chfl_property_double(double value) { CHFL_PROPERTY* property = nullptr; CHFL_ERROR_GOTO( property = shared_allocator::make_shared<Property>(value); ) return property; error: chfl_free(property); return nullptr; } extern "C" CHFL_PROPERTY* chfl_property_string(const char* value) { CHFL_PROPERTY* property = nullptr; CHFL_ERROR_GOTO( property = shared_allocator::make_shared<Property>(value); ) return property; error: chfl_free(property); return nullptr; } extern "C" CHFL_PROPERTY* chfl_property_vector3d(const chfl_vector3d value) { CHFL_PROPERTY* property = nullptr; CHFL_ERROR_GOTO( property = shared_allocator::make_shared<Property>(vector3d(value)); ) return property; error: chfl_free(property); return nullptr; } extern "C" chfl_status chfl_property_get_kind(const CHFL_PROPERTY* const property, chfl_property_kind* kind) { CHECK_POINTER(property); CHECK_POINTER(kind); CHFL_ERROR_CATCH( *kind = static_cast<chfl_property_kind>(property->kind()); ) } extern "C" chfl_status chfl_property_get_bool(const CHFL_PROPERTY* const property, bool* value) { CHECK_POINTER(property); CHECK_POINTER(value); CHFL_ERROR_CATCH( *value = property->as_bool(); ) } extern "C" chfl_status chfl_property_get_double(const CHFL_PROPERTY* const property, double* value) { CHECK_POINTER(property); CHECK_POINTER(value); CHFL_ERROR_CATCH( *value = property->as_double(); ) } extern "C" chfl_status chfl_property_get_string(const CHFL_PROPERTY* const property, char* const buffer, uint64_t buffsize) { CHECK_POINTER(property); CHECK_POINTER(buffer); CHFL_ERROR_CATCH( const auto& string = property->as_string(); strncpy(buffer, string.c_str(), checked_cast(buffsize) - 1); buffer[buffsize - 1] = '\0'; ) } extern "C" chfl_status chfl_property_get_vector3d(const CHFL_PROPERTY* const property, chfl_vector3d value) { CHECK_POINTER(property); CHECK_POINTER(value); CHFL_ERROR_CATCH( auto vector = property->as_vector3d(); value[0] = vector[0]; value[1] = vector[1]; value[2] = vector[2]; ) }
29.09901
125
0.709085
[ "vector" ]
e763e81e42b2dddc03b236477c83b32e77becb68
8,579
cpp
C++
src/ProfileGenerator/ConditionHypothesis.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/ProfileGenerator/ConditionHypothesis.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/ProfileGenerator/ConditionHypothesis.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2010 by BBNT Solutions LLC // All Rights Reserved. #include "Generic/common/leak_detection.h" // This must be the first #include #include "ProfileGenerator/ConditionHypothesis.h" #include "ProfileGenerator/Profile.h" #include "boost/algorithm/string/split.hpp" #include "boost/algorithm/string/classification.hpp" #include "boost/foreach.hpp" #include "boost/bind.hpp" #include "boost/algorithm/string.hpp" #include <iostream> #include <wchar.h> ConditionHypothesis::ConditionHypothesis(PGFact_ptr fact) { addFact(fact); PGFactArgument_ptr answerArg = fact->getAnswerArgument(); if (answerArg) _value = answerArg->getLiteralStringValue(); else _value = L""; // don't want to remove all "the"s, as they are a good signal that a condition is bad if (boost::iequals(_value, L"the flu")) _value = L"flu"; if (boost::iequals(_value, L"pregnant")) _value = L"pregnancy"; std::list<std::wstring> prefixesToRemove; prefixesToRemove.push_back(L"their "); prefixesToRemove.push_back(L"his "); prefixesToRemove.push_back(L"her "); prefixesToRemove.push_back(L"its "); prefixesToRemove.push_back(L"fewer "); prefixesToRemove.push_back(L"more "); prefixesToRemove.push_back(L"advanced "); prefixesToRemove.push_back(L"popular "); prefixesToRemove.push_back(L"adjuvant "); prefixesToRemove.push_back(L"adjuvent "); prefixesToRemove.push_back(L"treat "); prefixesToRemove.push_back(L"control "); prefixesToRemove.push_back(L"treats "); prefixesToRemove.push_back(L"controls "); // repeat to make sure we get rid of all of them for (int i = 0; i < 2; i++) { BOOST_FOREACH(std::wstring prefix, prefixesToRemove) { if (boost::istarts_with(_value, prefix)) _value = _value.substr(prefix.size()); } } // eliminate things like "my mom's diabetes" but not "Alzheimer's disease" size_t possessive = _value.find(L"'s"); if (possessive != std::wstring::npos && possessive + 3 < _value.size()) { std::wstring test_str = _value.substr(possessive+3); if (!boost::istarts_with(test_str, L"disease")) _value = test_str; } std::list<std::wstring> suffixesToRemove; suffixesToRemove.push_back(L","); suffixesToRemove.push_back(L"-LRB-"); suffixesToRemove.push_back(L":"); suffixesToRemove.push_back(L";"); suffixesToRemove.push_back(L" and "); suffixesToRemove.push_back(L" who "); suffixesToRemove.push_back(L" & "); BOOST_FOREACH(std::wstring suffix, suffixesToRemove) { size_t index = _value.find(suffix); if (index != std::wstring::npos) _value = _value.substr(0, index); } boost::trim(_value); if (_value == L"") _value = L"NONE"; _normalizedValue = _value; boost::to_lower(_normalizedValue); std::list<std::wstring> prefixesToRemoveForNormalization; prefixesToRemoveForNormalization.push_back(L"the "); prefixesToRemoveForNormalization.push_back(L"a "); prefixesToRemoveForNormalization.push_back(L"an "); prefixesToRemoveForNormalization.push_back(L"acute "); prefixesToRemoveForNormalization.push_back(L"high "); prefixesToRemoveForNormalization.push_back(L"serious "); prefixesToRemoveForNormalization.push_back(L"chronic "); prefixesToRemoveForNormalization.push_back(L"terminal "); BOOST_FOREACH(std::wstring prefix, prefixesToRemoveForNormalization) { if (boost::istarts_with(_normalizedValue, prefix)) _normalizedValue = _normalizedValue.substr(prefix.size()); } } std::wstring ConditionHypothesis::getDisplayValue() { if (_value == L"blood pressure" || _value == L"cholesterol") { // always high if unspecified return L"high " + _value; } return _value; } std::wstring ConditionHypothesis::getNormalizedDisplayValue() { return _normalizedValue; } bool ConditionHypothesis::isEquiv(GenericHypothesis_ptr hypoth) { ConditionHypothesis_ptr conditionHypoth = boost::dynamic_pointer_cast<ConditionHypothesis>(hypoth); if (conditionHypoth == ConditionHypothesis_ptr()) // cast failed return false; std::wstring other_norm_value = conditionHypoth->getNormalizedDisplayValue(); if (boost::iequals(_normalizedValue, other_norm_value)) return true; if (boost::istarts_with(_normalizedValue, other_norm_value) || boost::istarts_with(other_norm_value, _normalizedValue)) { //std::wcout << L"STARTS WITH: " << _value << L" & " << other_norm_value << L"<br>\n"; return true; } return false; } bool ConditionHypothesis::isSimilar(GenericHypothesis_ptr hypoth) { if (isEquiv(hypoth)) return true; ConditionHypothesis_ptr conditionHypoth = boost::dynamic_pointer_cast<ConditionHypothesis>(hypoth); if (conditionHypoth == ConditionHypothesis_ptr()) // cast failed return false; std::wstring other_norm_value = conditionHypoth->getNormalizedDisplayValue(); if (boost::iends_with(_normalizedValue, other_norm_value) || boost::iends_with(other_norm_value, _normalizedValue)) return true; if (boost::iends_with(_normalizedValue, L"stroke") && boost::iends_with(other_norm_value, L"stroke")) return true; return false; } void ConditionHypothesis::addSupportingHypothesis(GenericHypothesis_ptr hypo) { ConditionHypothesis_ptr conditionHypo = boost::dynamic_pointer_cast<ConditionHypothesis>(hypo); if (conditionHypo == ConditionHypothesis_ptr()) return; BOOST_FOREACH(PGFact_ptr fact, conditionHypo->getSupportingFacts()) { addFact(fact); } std::wstring other_value = conditionHypo->getDisplayValue(); std::wstring other_norm_value = conditionHypo->getNormalizedDisplayValue(); if (_value == L"cholesterol" && (other_value == L"high cholesterol" || other_value == L"low cholesterol")) { _value = other_value; _normalizedValue = other_norm_value; } if (boost::iequals(_normalizedValue, other_norm_value)) { //pass } else if (boost::istarts_with(_normalizedValue, other_norm_value)) { std::vector<std::wstring> thisWords; std::vector<std::wstring> otherWords; boost::split(thisWords, _normalizedValue, boost::is_any_of(L" ")); boost::split(otherWords, other_norm_value, boost::is_any_of(L" ")); if (thisWords.size() == otherWords.size()) { // switch to the shorter, probably a plural? _value = other_value; _normalizedValue = other_norm_value; } } else if (boost::iends_with(other_norm_value, _normalizedValue)) { _value = other_value; _normalizedValue = other_norm_value; } } int ConditionHypothesis::rankAgainst(GenericHypothesis_ptr hypo) { // prefer specific forms of cancer if (getDisplayValue() == L"cancer" && boost::iends_with(hypo->getDisplayValue(), L"cancer")) return WORSE; else if (hypo->getDisplayValue() == L"cancer" && boost::iends_with(getDisplayValue(), L"cancer")) return BETTER; // Prefer the one with more facts if (nSupportingFacts() > hypo->nSupportingFacts()) return BETTER; else if (hypo->nSupportingFacts() > nSupportingFacts()) return WORSE; // Prefer the one with a better score group if (getBestScoreGroup() < hypo->getBestScoreGroup()) return BETTER; else if (hypo->getBestScoreGroup() < getBestScoreGroup()) return WORSE; // Break ties and show more recent epoch facts (with id as proxy) ahead of older epoch if (getNewestFactID() > hypo->getNewestFactID()) return BETTER; else if (hypo->getNewestFactID() > getNewestFactID()) return WORSE; // should never happen unless they share facts, which they shouldn't return SAME; } bool ConditionHypothesis::isIllegalHypothesis(ProfileSlot_ptr slot, std::string& rationale) { if (boost::istarts_with(_value, L"the ")) { rationale = "starts with 'the '"; return true; } if (_value == L"disease") { rationale = "boring"; return true; } if (boost::istarts_with(_value, L"an ") || boost::istarts_with(_value, L"a ")) { rationale = "starts with 'an/a '"; return true; } if ((_value == L"death" || _value == L"deaths") && slot->getUniqueId() != "side_effect") { rationale = "death is not something that can be studied/treated"; return true; } if ((boost::istarts_with(_value, L"a ") || boost::istarts_with(_value, L"an ")) && (boost::iends_with(_value, L"'s disease"))) { rationale = "boring"; return true; } if (_value == L"NONE") { rationale = "empty"; return true; } return false; } bool ConditionHypothesis::isRiskyHypothesis(ProfileSlot_ptr slot, std::string& rationale) { if (getBestScoreGroup() != 1) return true; return false; }
33.251938
123
0.711505
[ "vector" ]
e7662b037c971c33e3a41ce00905d82149ae19b4
15,405
cc
C++
src/subprocess-unix.cc
SRI-CSL/stegotorus
6b46bb403293a4b39aec21a8bbd9fcb01e8b6930
[ "BSD-3-Clause-Clear" ]
72
2015-03-31T11:22:25.000Z
2021-11-23T23:15:51.000Z
src/subprocess-unix.cc
SRI-CSL/stegotorus
6b46bb403293a4b39aec21a8bbd9fcb01e8b6930
[ "BSD-3-Clause-Clear" ]
2
2018-02-22T04:05:40.000Z
2021-05-13T11:47:32.000Z
src/subprocess-unix.cc
SRI-CSL/stegotorus
6b46bb403293a4b39aec21a8bbd9fcb01e8b6930
[ "BSD-3-Clause-Clear" ]
18
2015-04-15T00:47:09.000Z
2020-12-16T10:26:21.000Z
/* Copyright 2012, 2013 SRI International * Portions copyright 2003-2011 Roger Dingledine, Nick Mathewson, * and/or The Tor Project, Inc. * Portions copyright 1991-2012 The Regents of the University of California * and/or various FreeBSD contributors. * See LICENSE for other credits and copying information. */ // This file should be acceptably portable to all Unix implementations // still in wide use. #include "util.h" #include "subprocess.h" #include <map> #include <sstream> #include <sys/stat.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #ifdef HAVE_PATHS_H #include <paths.h> #endif #ifndef _PATH_DEFPATH #define _PATH_DEFPATH "/usr/bin:/bin" #endif #ifndef PATH_MAX # ifdef MAXPATHLEN # define PATH_MAX MAXPATHLEN # else # define PATH_MAX 4096 # endif #endif #ifndef OPEN_MAX # define OPEN_MAX 256 #endif extern char **environ; using std::map; using std::vector; using std::string; // Space for hex values of child state, a slash, saved_errno (with // leading minus) and newline (no null) #define HEX_ERRNO_SIZE (sizeof(int)*2 + 4) // State codes for the child side of the fork. #define CHILD_STATE_REDIRECT_STDIN 1 #define CHILD_STATE_REDIRECT_STDOUT 2 #define CHILD_STATE_REDIRECT_STDERR 3 #define CHILD_STATE_CLOSEFROM 4 #define CHILD_STATE_EXEC 5 // Some C libraries get very unhappy with you if you ignore the result // of a write call, but where it's used in this file, there is nothing // whatsoever we can do if it fails. #define IGNORE_FAILURE(expr) do { if (expr) {} } while (0) // We have not prevented copying of |subprocess| objects, so it is // possible that |wait| will be called more than once for the same // PID, with no state in the object to tell us so. To prevent // problems, maintain a table of processes that we have waited for. // We make no attempt to prune this table; its memory requirements // should be trivial for the expected uses of this API. static map<pid_t, int> already_waited; // Internal utilities and replacements for system library routines // that may or may not exist. #ifndef HAVE_CLOSEFROM static void closefrom(int lowfd) { #ifdef F_CLOSEM // Try F_CLOSEM if it's defined. But it might not work. if (fcntl(lowfd, F_CLOSEM, 0) == 0) return; #endif // If /proc/self/fd is available, use it. // N.B. Theoretically you are not allowed to use opendir() after fork() // as it's not async-signal-safe. This is overwhelmingly unlikely to // cause problems in practice. DIR *dirp; if ((dirp = opendir("/proc/self/fd")) != 0) { struct dirent *dent; char *endp; while ((dent = readdir(dirp)) != NULL) { unsigned long fd = strtoul(dent->d_name, &endp, 10); if (dent->d_name != endp && *endp == '\0' && fd < (unsigned long)INT_MAX && fd >= (unsigned long)lowfd && fd != (unsigned long)dirfd(dirp)) close((int)fd); } closedir(dirp); return; } // As a last resort, blindly close all possible fd numbers // between lowfd and _SC_OPEN_MAX. unsigned long maxfd = sysconf(_SC_OPEN_MAX); if (maxfd == (unsigned long)(-1L)) maxfd = OPEN_MAX; for (unsigned long fd = lowfd; fd < maxfd; fd++) close((int)fd); } #endif #ifndef HAVE_EXECVPE // Implementation courtesy FreeBSD 9.0 src/lib/libc/gen/exec.c // some adjustments made with reference to the glibc implementation static int execvpe(const char *name, char * const argv[], char * const envp[]) { const char *path; const char *p, *q; size_t lp, ln; bool eacces = false; char buf[PATH_MAX]; // If it's an empty path name, fail immediately. if (*name == '\0') { errno = ENOENT; return -1; } // If it's an absolute or relative pathname, do not search $PATH. if (strchr(name, '/')) { execve(name, argv, envp); return -1; } ln = strlen(name); // Get the path to search. Intentionally uses the parent // environment, not 'envp'. if (!(path = getenv("PATH"))) path = _PATH_DEFPATH; q = path; do { p = q; while (*q != '\0' && *q != ':') q++; // Double, leading and trailing colons mean the current directory. if (q == p) { p = "."; lp = 1; } else lp = q - p; q++; // If the path is too long, complain and skip it. This is a // possible security issue; given a way to make the path too long // the user may execute the wrong program. if (lp + ln + 2 > sizeof(buf)) { IGNORE_FAILURE(write(2, "execvpe: ", 8)); IGNORE_FAILURE(write(2, p, lp)); IGNORE_FAILURE(write(2, ": path too long\n", 16)); continue; } memcpy(buf, p, lp); buf[lp] = '/'; memcpy(buf + lp + 1, name, ln); buf[lp + ln + 1] = '\0'; execve(buf, argv, envp); switch (errno) { // These errors all indicate that we should try the next directory. case EACCES: // Remember that at least one failure was due to a permission check; // this will be preferentially reported, unless we hit something even // more serious. eacces = true; case ELOOP: case ENAMETOOLONG: case ENOENT: case ENOTDIR: case ESTALE: case ETIMEDOUT: continue; default: // On any other error, give up. // Shell fallback for ENOEXEC deliberately removed, as it is a // historical vestige and involves allocating memory. return -1; } } while (*q); if (eacces) errno = EACCES; return -1; } #endif /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler * safe. * * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available. * * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where * in the processs of starting the child process did the failure occur (see * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of * errno when the failure occurred. */ static void format_helper_exit_status(unsigned char child_state, int saved_errno, char *hex_errno) { unsigned int unsigned_errno; char *cur; size_t i; /* Fill hex_errno with spaces, and a trailing newline (memset may not be signal handler safe, so we can't use it) */ for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++) hex_errno[i] = ' '; hex_errno[HEX_ERRNO_SIZE - 1] = '\n'; /* Convert errno to be unsigned for hex conversion */ if (saved_errno < 0) { unsigned_errno = (unsigned int) -saved_errno; } else { unsigned_errno = (unsigned int) saved_errno; } /* Convert errno to hex (start before \n) */ cur = hex_errno + HEX_ERRNO_SIZE - 2; /* Check for overflow on first iteration of the loop */ if (cur < hex_errno) return; do { *cur-- = "0123456789ABCDEF"[unsigned_errno % 16]; unsigned_errno /= 16; } while (unsigned_errno != 0 && cur >= hex_errno); /* Prepend the minus sign if errno was negative */ if (saved_errno < 0 && cur >= hex_errno) *cur-- = '-'; /* Leave a gap */ if (cur >= hex_errno) *cur-- = '/'; /* Check for overflow on first iteration of the loop */ if (cur < hex_errno) return; /* Convert child_state to hex */ do { *cur-- = "0123456789ABCDEF"[child_state % 16]; child_state /= 16; } while (child_state != 0 && cur >= hex_errno); } /** Start a program in the background. If <b>filename</b> contains a '/', * then it will be treated as an absolute or relative path. Otherwise the * system path will be searched for <b>filename</b>. The strings in * <b>argv</b> will be passed as the command line arguments of the child * program (following convention, argv[0] should normally be the filename of * the executable), and the strings in <b>envp</b> will be passed as its * environment variables. * * The child's standard input and output will both be /dev/null; * the child's standard error will be whatever it is in the parent * (unless it is closed in the parent, in which case it will also be * /dev/null) * * All file descriptors numbered higher than 2 will be closed. * * On success, returns the PID of the child; on failure, returns -1. */ static pid_t do_fork_exec(const char *const filename, const char **argv, const char **envp) { pid_t pid = fork(); if (pid == -1) { log_warn("Failed to fork child process: %s", strerror(errno)); return -1; } if (pid != 0) { // In parent. // If we spawn a child, wait for it, the PID counter wraps // completely around, and then we spawn another child which // happens to get exactly the same PID as the first one, we had // better remove the old record from the already_waited table or // we won't ever actually wait for the new child. The odds of // this are small, but not ridiculously small. already_waited.erase(pid); return pid; } // In child char hex_errno[HEX_ERRNO_SIZE]; unsigned int child_state = CHILD_STATE_REDIRECT_STDIN; close(0); if (open("/dev/null", O_RDONLY) != 0) goto error; child_state = CHILD_STATE_REDIRECT_STDOUT; close(1); if (open("/dev/null", O_WRONLY) != 1) goto error; child_state = CHILD_STATE_REDIRECT_STDERR; if (!isatty(2) && errno == EBADF) { if (open("/dev/null", O_WRONLY) != 2) goto error; } child_state = CHILD_STATE_CLOSEFROM; closefrom(3); child_state = CHILD_STATE_EXEC; // We need the casts because execvpe doesn't declare argv or envp // as const, even though it does not modify them. execvpe(filename, (char *const *) argv, (char *const *)envp); error: format_helper_exit_status(child_state, errno, hex_errno); #define error_message "ERR: Failed to spawn child process: code " IGNORE_FAILURE(write(2, error_message, sizeof error_message - 1)); IGNORE_FAILURE(write(2, hex_errno, sizeof hex_errno)); #undef error_message _exit(255); } // Wrapper: marshal the C++-y vector and map into the form the kernel // expects. static pid_t do_fork_exec(vector<string> const& args, vector<string> const& env) { char const* argv[args.size() + 1]; char const* envp[env.size() + 1]; for (size_t i = 0; i < args.size(); i++) argv[i] = args[i].c_str(); argv[args.size()] = 0; for (size_t i = 0; i < env.size(); i++) envp[i] = env[i].c_str(); envp[env.size()] = 0; return do_fork_exec(argv[0], argv, envp); } static void decode_status(int status, int& state, int& rc) { if (WIFEXITED(status)) { rc = WEXITSTATUS(status); state = CLD_EXITED; } else if (WIFSIGNALED(status)) { rc = WTERMSIG(status); #ifdef WCOREDUMP if (WCOREDUMP(status)) state = CLD_DUMPED; else #endif state = CLD_KILLED; } else { // we do not use WUNTRACED, WCONTINUED, or ptrace, so the other // WIF* possibilities should never happen log_abort("impossible wait status %04x", (unsigned int)status); } } static bool wait_common(pid_t pid, int& state, int& rc, bool wnohang) { if (pid == -1) { // Map failure to fork into the same exit state that we get if // there's a failure in between fork and exec. state = CLD_EXITED; rc = 255; return true; } map<pid_t, int>::iterator p = already_waited.find(pid); if (p != already_waited.end()) { decode_status(p->second, state, rc); return true; } int status; pid_t rv = waitpid(pid, &status, wnohang ? WNOHANG : 0); if (rv == pid) { decode_status(status, state, rc); already_waited.insert(std::make_pair(pid, status)); return true; } else if (rv == 0 && wnohang) { return false; } else { log_warn("waitpid(%d) failed: %s", pid, strerror(errno)); return false; } } // subprocess methods subprocess::subprocess(vector<string> const& args, vector<string> const& env) : pid(do_fork_exec(args, env)), state(0), returncode(-1) { } subprocess subprocess::call(vector<string> const& args, vector<string> const& env) { subprocess proc(args, env); proc.wait(); return proc; } bool subprocess::poll() { return wait_common(pid, state, returncode, true); } void subprocess::wait() { wait_common(pid, state, returncode, false); } // public utilities vector<string> get_environ(const char *exclude) { vector<string> result; size_t exlen = exclude ? strlen(exclude) : 0; for (char **p = environ; *p; p++) if (!exclude || strncmp(exclude, *p, exlen)) result.push_back(*p); return result; } void daemonize() { if (getppid() == 1) // already a daemon return; // Close standard I/O file descriptors and reopen them on /dev/null. // We do this before forking (a) to avoid any possibility of // double-flushed stdio buffers, and (b) so we can exit // unsuccessfully in the unlikely event of a failure. fflush(NULL); // flush all open stdio buffers close(0); if (open("/dev/null", O_RDONLY) != 0) log_abort("/dev/null: %s", strerror(errno)); close(1); if (open("/dev/null", O_WRONLY) != 1) log_abort("/dev/null: %s", strerror(errno)); // N.B. log_abort might be writing somewhere other than stderr. // In fact, we rather hope it is, 'cos otherwise all logs from // the child are gonna go to the bit bucket. close(2); if (open("/dev/null", O_WRONLY) != 2) log_abort("/dev/null: %s", strerror(errno)); pid_t pid = fork(); if (pid < 0) log_abort("fork failed: %s", strerror(errno)); if (pid > 0) // Parent // The use of _exit instead of exit here is deliberate. // It's the process that carries on from this function that // should do atexit cleanups (eventually). _exit(0); // Become a session leader, and then fork one more time and exit in // the parent. (This puts the process that will actually be the // daemon in an orphaned process group. On some systems, this is // necessary to ensure that the daemon can never acquire a controlling // terminal again. XXX On some systems will the grandchild receive // an unwanted, probably-fatal SIGHUP when its session leader exits?) setsid(); if (fork()) _exit(0); // For the moment we do not chdir anywhere, because the HTTP steg expects // to find its traces relative to the cwd. FIXME. } pidfile::pidfile(std::string const& p) : path(p), errcode(0), rmcode(0) { if (path.empty()) return; std::ostringstream ss; ss << getpid() << '\n'; char *b = xstrdup(ss.str().c_str()); size_t n = ss.str().size(); int f = open(path.c_str(), O_WRONLY|O_CREAT|O_EXCL, 0666); if (f == -1) { errcode = errno; free(b); return; } do { ssize_t r = write(f, b, n); if (r < 0) { errcode = errno; close(f); rmcode = remove(path.c_str()); if(rmcode != 0){ rmcode = errno; } free(b); return; } n -= r; b += r; } while (n > 0); // Sadly, close() can fail, and in this case it actually matters. if (close(f)) { errcode = errno; rmcode = remove(path.c_str()); if(rmcode != 0){ rmcode = errno; } } free(b); } pidfile::~pidfile() { if (!errcode && !path.empty()){ rmcode = remove(path.c_str()); if(rmcode != 0){ rmcode = errno; } } } pidfile::operator bool() const { return !errcode; } const char * pidfile::errmsg() const { return errcode ? strerror(errcode) : 0; }
26.560345
78
0.648685
[ "object", "vector" ]
e766f8ccfaa7fe32c49378dec6b874cf718f6cd0
973
cpp
C++
201510_201609/1114_codefes2015_final/D.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
201510_201609/1114_codefes2015_final/D.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
201510_201609/1114_codefes2015_final/D.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #include <cmath> #include <tuple> #include <string> using namespace std; typedef long long ll; int main() { int N; cin >> N; int S[100010]; int T[100010]; for (auto i=0; i<N; i++) { cin >> S[i] >> T[i]; } int imos[100010]; fill(imos, imos+100010, 0); for (auto i=0; i<N; i++) { imos[S[i]]++; imos[T[i]]--; } for (auto i=1; i<100010; i++) { imos[i] += imos[i-1]; } int m = 0; for (auto i=0; i<100010; i++) { m = max(m, imos[i]); } int lb, ub; for (auto i=0; i<100010; i++) { if (imos[i] == m) { lb = i; break; } } for (auto i=100009; i>=0; i--) { if (imos[i] == m) { ub = i; break; } } for (auto i=0; i<N; i++) { if ((lb >= S[i]) && (ub < T[i])) { cout << m-1 << endl; return 0; } } cout << m << endl; }
16.775862
38
0.476876
[ "vector" ]
e76bb9332fb3420f18fb2a02a54f5f5af2a4adcd
10,330
cpp
C++
MFC-MyDAQ-DMM/MFC-MyDAQ-DMMDlg.cpp
ermin-muratovic/MFC-MyDAQ-DMM
5bd5493b2df1036483b5fc2e2ace67d05fb38e64
[ "MIT" ]
null
null
null
MFC-MyDAQ-DMM/MFC-MyDAQ-DMMDlg.cpp
ermin-muratovic/MFC-MyDAQ-DMM
5bd5493b2df1036483b5fc2e2ace67d05fb38e64
[ "MIT" ]
null
null
null
MFC-MyDAQ-DMM/MFC-MyDAQ-DMMDlg.cpp
ermin-muratovic/MFC-MyDAQ-DMM
5bd5493b2df1036483b5fc2e2ace67d05fb38e64
[ "MIT" ]
null
null
null
 // MFC-MyDAQ-DMMDlg.cpp : implementation file // #include "stdafx.h" #include "MFC-MyDAQ-DMM.h" #include "MFC-MyDAQ-DMMDlg.h" #include "afxdialogex.h" #include "MyDAQ.h" #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <list> #ifdef _DEBUG #define new DEBUG_NEW #endif using namespace std; HBITMAP voltBmp; HBITMAP ampBmp; MyDAQ myDAQ = MyDAQ::MyDAQ(); string mydaqName; bool isRunning = false; // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCMyDAQDMMDlg dialog CMFCMyDAQDMMDlg::CMFCMyDAQDMMDlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_MFCMYDAQDMM_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMFCMyDAQDMMDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_VALUELABEL, value_label); DDX_Control(pDX, IDC_UNITLABEL, unit_label); DDX_Control(pDX, IDC_DEVICECOMBO, device_combobox); DDX_Control(pDX, IDC_BUTTONVDC, vdc_button); DDX_Control(pDX, IDC_BUTTONVAC, vac_button); DDX_Control(pDX, IDC_BUTTONADC, adc_button); DDX_Control(pDX, IDC_BUTTONAAC, aac_button); DDX_Control(pDX, IDC_BUTTONOHM, ohm_button); DDX_Control(pDX, IDC_MODECOMBO, mode_combobox); DDX_Control(pDX, IDC_RANGECOMBO, range_combobox); DDX_Control(pDX, IDC_IMAGECONTAINER, image_container); DDX_Control(pDX, IDC_BUTTONRUN, run_button); DDX_Control(pDX, IDC_BUTTONSTOP, stop_button); } BEGIN_MESSAGE_MAP(CMFCMyDAQDMMDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_CBN_DROPDOWN(IDC_DEVICECOMBO, &CMFCMyDAQDMMDlg::OnCbnDropdownDevicecombo) ON_BN_CLICKED(IDC_BUTTONVDC, &CMFCMyDAQDMMDlg::OnBnClickedButtonvdc) ON_BN_CLICKED(IDC_BUTTONVAC, &CMFCMyDAQDMMDlg::OnBnClickedButtonvac) ON_BN_CLICKED(IDC_BUTTONADC, &CMFCMyDAQDMMDlg::OnBnClickedButtonadc) ON_BN_CLICKED(IDC_BUTTONAAC, &CMFCMyDAQDMMDlg::OnBnClickedButtonaac) ON_BN_CLICKED(IDC_BUTTONOHM, &CMFCMyDAQDMMDlg::OnBnClickedButtonohm) ON_CBN_SELCHANGE(IDC_MODECOMBO, &CMFCMyDAQDMMDlg::OnCbnSelchangeModecombo) ON_BN_CLICKED(IDC_BUTTONRUN, &CMFCMyDAQDMMDlg::OnBnClickedButtonrun) ON_BN_CLICKED(IDC_BUTTONSTOP, &CMFCMyDAQDMMDlg::OnBnClickedButtonstop) END_MESSAGE_MAP() // CMFCMyDAQDMMDlg message handlers BOOL CMFCMyDAQDMMDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here initGUI(); updateDevicesCombobox(myDAQ.getConnectedDevices()); updateButtonStyle(); return TRUE; // return TRUE unless you set the focus to a control } void CMFCMyDAQDMMDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCMyDAQDMMDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCMyDAQDMMDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCMyDAQDMMDlg::initGUI() { // modify font CFont *f1 = new CFont; string font = "Arial Bold"; f1->CreatePointFont(260, (LPCTSTR)font.c_str()); value_label.SetFont(f1); unit_label.SetFont(f1); // init mode combobox mode_combobox.AddString((LPCTSTR)(CA2T)"Auto"); mode_combobox.AddString((LPCTSTR)(CA2T)"Specify range"); mode_combobox.SetCurSel(0); range_combobox.EnableWindow(FALSE); string voltImagePath = ".\\res\\jack-connection-description-volt.bmp"; string ampImagePath = ".\\res\\jack-connection-description-ampere.bmp"; CRect rect; image_container.GetWindowRect(&rect); voltBmp = (HBITMAP)LoadImage(0, (LPCWSTR)(CA2T)voltImagePath.c_str(), IMAGE_BITMAP, rect.Width(), rect.Height(), LR_LOADFROMFILE); ampBmp = (HBITMAP)LoadImage(0, (LPCWSTR)(CA2T)ampImagePath.c_str(), IMAGE_BITMAP, rect.Width(), rect.Height(), LR_LOADFROMFILE); image_container.ModifyStyle(0xF, SS_BITMAP, SWP_NOSIZE); } void CMFCMyDAQDMMDlg::updateDevicesCombobox(list<string> devices) { device_combobox.ResetContent(); if (devices.size() > 0) { list<string>::iterator it; for (it = devices.begin(); it != devices.end(); it++) { device_combobox.AddString((LPCTSTR)(CA2T)(*it).c_str()); } run_button.EnableWindow(true); stop_button.EnableWindow(false); } else { device_combobox.AddString((LPCTSTR)(CA2T)"No device connected"); run_button.EnableWindow(false); stop_button.EnableWindow(false); } device_combobox.SetCurSel(0); } void CMFCMyDAQDMMDlg::OnCbnDropdownDevicecombo() { updateDevicesCombobox(myDAQ.getConnectedDevices()); } void CMFCMyDAQDMMDlg::updateButtonStyle() { vdc_button.SetState(false); vac_button.SetState(false); adc_button.SetState(false); aac_button.SetState(false); ohm_button.SetState(false); switch (myDAQ.mode) { case VDC: image_container.SetBitmap(voltBmp); vdc_button.SetState(true); unit_label.SetWindowTextW(_T("V")); break; case ADC: image_container.SetBitmap(ampBmp); adc_button.SetState(true); unit_label.SetWindowTextW(_T("A")); break; case OHM: image_container.SetBitmap(voltBmp); ohm_button.SetState(true); unit_label.SetWindowTextW(_T("Ω")); break; } } void CMFCMyDAQDMMDlg::OnBnClickedButtonvdc() { myDAQ.mode = VDC; updateButtonStyle(); } void CMFCMyDAQDMMDlg::OnBnClickedButtonvac() { AfxMessageBox(_T("This function is not implemented!")); } void CMFCMyDAQDMMDlg::OnBnClickedButtonadc() { myDAQ.mode = ADC; updateButtonStyle(); } void CMFCMyDAQDMMDlg::OnBnClickedButtonaac() { AfxMessageBox(_T("This function is not implemented!")); } void CMFCMyDAQDMMDlg::OnBnClickedButtonohm() { myDAQ.mode = OHM; updateButtonStyle(); } void CMFCMyDAQDMMDlg::OnCbnSelchangeModecombo() { int sel = mode_combobox.GetCurSel(); if (sel == 1) { AfxMessageBox(_T("This function is not implemented!")); } mode_combobox.SetCurSel(0); } UINT run(LPVOID Param) { ASSERT(Param != NULL); CMFCMyDAQDMMDlg* dlg = reinterpret_cast<CMFCMyDAQDMMDlg*>(Param); while (isRunning) { dlg->readDMM(mydaqName); } return true; } void CMFCMyDAQDMMDlg::OnBnClickedButtonrun() { myDAQ.clearValues(); CString mydaqSelection; device_combobox.GetLBText(device_combobox.GetCurSel(), mydaqSelection); mydaqName = string((CT2CA)mydaqSelection); device_combobox.EnableWindow(false); mode_combobox.EnableWindow(false); run_button.EnableWindow(false); vdc_button.EnableWindow(false); vac_button.EnableWindow(false); adc_button.EnableWindow(false); aac_button.EnableWindow(false); ohm_button.EnableWindow(false); stop_button.EnableWindow(true); run_button.SetState(true); isRunning = true; AfxBeginThread(run, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL); } void CMFCMyDAQDMMDlg::readDMM(string mydaq) { float value; switch (myDAQ.mode) { case VDC: value = myDAQ.readDCVolt(mydaq); if (value < 0.1) { value = value * 1000; unit_label.SetWindowTextW(_T("mV")); } else { unit_label.SetWindowTextW(_T("V")); } break; case ADC: value = myDAQ.readDCCur(mydaq); if (value < 0.1) { value = value * 1000; unit_label.SetWindowTextW(_T("mA")); } else { unit_label.SetWindowTextW(_T("A")); } break; case OHM: value = myDAQ.readResist(mydaq); if (value > 1000000) { value = value / 1000000; unit_label.SetWindowTextW(_T("MΩ")); } else if (value > 2000) { value = value / 1000; unit_label.SetWindowTextW(_T("kΩ")); } else { unit_label.SetWindowTextW(_T("Ω")); } break; } stringstream s; s << fixed << setprecision(2) << value; value_label.SetWindowTextW((LPCTSTR)(CA2T)s.str().c_str()); } void CMFCMyDAQDMMDlg::OnBnClickedButtonstop() { isRunning = false; device_combobox.EnableWindow(true); mode_combobox.EnableWindow(true); vdc_button.EnableWindow(true); vac_button.EnableWindow(true); adc_button.EnableWindow(true); aac_button.EnableWindow(true); ohm_button.EnableWindow(true); run_button.EnableWindow(true); stop_button.EnableWindow(false); run_button.SetState(false); saveData(); } void CMFCMyDAQDMMDlg::saveData() { FILE *pFile; errno_t err = 0; err = fopen_s(&pFile, "data.txt", "w+"); list<float>::iterator it; for (it = myDAQ.values.begin(); it != myDAQ.values.end(); it++) { switch (myDAQ.mode) { case VDC: fprintf(pFile, "%.4f V\n", (*it)); break; case ADC: fprintf(pFile, "%.4f A\n", (*it)); break; case OHM: fprintf(pFile, "%.4f Ohm\n", (*it)); break; } } fclose(pFile); AfxMessageBox(_T("Read values have been saved in data.txt!")); }
23.912037
131
0.735431
[ "model" ]
e772ece40ac0f192a55c27160b3c4308646e4012
5,083
cpp
C++
test/unittest/mount_test/fstabapi_unittest.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
null
null
null
test/unittest/mount_test/fstabapi_unittest.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
null
null
null
test/unittest/mount_test/fstabapi_unittest.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
1
2021-09-13T11:17:34.000Z
2021-09-13T11:17:34.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fstabapi_unittest.h" #include <cctype> #include <cstdio> #include <fstream> #include <iostream> #include <memory> #include <string> #include <sys/mount.h> #include <unistd.h> #include <vector> #include "fs_manager/fs_manager.h" #include "fs_manager/mount.h" #include "log/log.h" #include "utils.h" using namespace testing::ext; using namespace updater_ut; using namespace updater; using namespace std; namespace updater_ut { void FstabApiUnitTest::SetUp(void) { cout << "Updater Unit MountUnitTest Begin!" << endl; } // end void FstabApiUnitTest::TearDown(void) { cout << "Updater Unit MountUnitTest End!" << endl; } // do something at the each function begining void FstabApiUnitTest::SetUpTestCase(void) {} // do something at the each function end void FstabApiUnitTest::TearDownTestCase(void) {} HWTEST_F(FstabApiUnitTest, ReadFstabFromFile_unitest, TestSize.Level1) { Fstab *fstab = nullptr; const std::string fstabFile1 = "/data/fstab.updater1"; fstab = ReadFstabFromFile(fstabFile1.c_str(), false); EXPECT_EQ(fstab, nullptr); const std::string fstabFile2 = "/data/updater/mount_unitest/ReadFstabFromFile1.fstable"; fstab = ReadFstabFromFile(fstabFile2.c_str(), false); EXPECT_EQ(fstab, nullptr); const std::string fstabFile3 = "/data/updater/mount_unitest/ReadFstabFromFile2.fstable"; fstab = ReadFstabFromFile(fstabFile3.c_str(), false); EXPECT_EQ(fstab, nullptr); const std::string fstabFile4 = "/data/updater/mount_unitest/ReadFstabFromFile3.fstable"; fstab = ReadFstabFromFile(fstabFile4.c_str(), false); EXPECT_EQ(fstab, nullptr); const std::string fstabFile5 = "/data/updater/mount_unitest/ReadFstabFromFile4.fstable"; fstab = ReadFstabFromFile(fstabFile5.c_str(), false); EXPECT_EQ(fstab, nullptr); const std::string fstabFile6 = "/data/updater/mount_unitest/ReadFstabFromFile5.fstable"; fstab = ReadFstabFromFile(fstabFile6.c_str(), false); EXPECT_NE(fstab, nullptr); ReleaseFstab(fstab); } HWTEST_F(FstabApiUnitTest, FindFstabItemForPath_unitest, TestSize.Level1) { const std::string fstabFile1 = "/data/updater/mount_unitest/FindFstabItemForPath1.fstable"; Fstab *fstab = nullptr; fstab = ReadFstabFromFile(fstabFile1.c_str(), false); ASSERT_NE(fstab, nullptr); FstabItem* item = nullptr; const std::string path1 = ""; item = FindFstabItemForPath(*fstab, path1.c_str()); if (item == nullptr) { SUCCEED(); } const std::string path2 = "/data"; item = FindFstabItemForPath(*fstab, path2.c_str()); if (item != nullptr) { SUCCEED(); } const std::string path3 = "/data2"; item = FindFstabItemForPath(*fstab, path3.c_str()); if (item == nullptr) { SUCCEED(); } const std::string path4 = "/data2/test"; item = FindFstabItemForPath(*fstab, path4.c_str()); if (item != nullptr) { SUCCEED(); } ReleaseFstab(fstab); fstab = nullptr; } HWTEST_F(FstabApiUnitTest, FindFstabItemForMountPoint_unitest, TestSize.Level1) { const std::string fstabFile1 = "/data/updater/mount_unitest/FindFstabItemForMountPoint1.fstable"; Fstab *fstab = nullptr; fstab = ReadFstabFromFile(fstabFile1.c_str(), false); ASSERT_NE(fstab, nullptr); FstabItem* item = nullptr; const std::string mp1 = "/data"; const std::string mp2 = "/data2"; item = FindFstabItemForMountPoint(*fstab, mp2.c_str()); if (item == nullptr) { SUCCEED(); } const std::string mp3 = "/data"; item = FindFstabItemForMountPoint(*fstab, mp3.c_str()); if (item != nullptr) { SUCCEED(); } ReleaseFstab(fstab); fstab = nullptr; } HWTEST_F(FstabApiUnitTest, GetMountFlags_unitest, TestSize.Level1) { const std::string fstabFile1 = "/data/updater/mount_unitest/GetMountFlags1.fstable"; Fstab *fstab = nullptr; fstab = ReadFstabFromFile(fstabFile1.c_str(), false); ASSERT_NE(fstab, nullptr); struct FstabItem* item = nullptr; const std::string mp = "/hos"; item = FindFstabItemForMountPoint(*fstab, mp.c_str()); if (item == nullptr) { SUCCEED(); } const int bufferSize = 512; char fsSpecificOptions[bufferSize] = {0}; unsigned long flags = GetMountFlags(item->mountOptions, fsSpecificOptions, bufferSize); EXPECT_EQ(flags, static_cast<unsigned long>(MS_NOSUID | MS_NODEV | MS_NOATIME)); ReleaseFstab(fstab); fstab = nullptr; } } // namespace updater_ut
33.662252
101
0.701751
[ "vector" ]
e77464eb6a8e246c38c7a7d65e832219df3305cd
2,243
cpp
C++
examples/cpp/queries/hierarchy/src/main.cpp
logankaser/flecs
6638a030604542835908463feabbe621c58b057a
[ "MIT" ]
2
2021-09-09T13:20:15.000Z
2021-09-09T20:23:25.000Z
examples/cpp/queries/hierarchy/src/main.cpp
NrdyBhu1/flecs
b6a36158ba42f23638c370d5f38aa55774987a65
[ "MIT" ]
null
null
null
examples/cpp/queries/hierarchy/src/main.cpp
NrdyBhu1/flecs
b6a36158ba42f23638c370d5f38aa55774987a65
[ "MIT" ]
null
null
null
#include <hierarchy.h> #include <iostream> struct Position { double x, y; }; // Tags for local/world position struct Local { }; struct World { }; int main(int, char *[]) { flecs::world ecs; // Create a hierarchy. For an explanation see the entities/hierarchy example auto sun = ecs.entity("Sun") .add<Position, World>() .set<Position, Local>({1, 1}); ecs.entity("Mercury") .child_of(sun) .add<Position, World>() .set<Position, Local>({1, 1}); ecs.entity("Venus") .child_of(sun) .add<Position, World>() .set<Position, Local>({2, 2}); auto earth = ecs.entity("Earth") .child_of(sun) .add<Position, World>() .set<Position, Local>({3, 3}); ecs.entity("Moon") .child_of(earth) .add<Position, World>() .set<Position, Local>({0.1, 0.1}); // Create a hierarchical query to compute the global position from the // local position and the parent position. auto q = ecs.query_builder<const Position, const Position, Position>() // Make sure to select the correct world/local positions .arg(1).object<Local>() .arg(2).object<World>() .arg(3).object<World>() // Extend the 2nd query argument to select it from the parent .arg(2) // Get from the parent, in breadth-first order (cascade) .set(flecs::Parent | flecs::Cascade) // Make parent component optional so we also match the root (sun) .oper(flecs::Optional) // Finalize the query .build(); // Do the transform q.iter([](flecs::iter& it, const Position *p, const Position *p_parent, Position *p_out) { for (auto i : it) { p_out[i].x = p[i].x; p_out[i].y = p[i].y; if (p_parent) { p_out[i].x += p_parent->x; p_out[i].y += p_parent->y; } } }); // Print world positions ecs.each([](flecs::entity e, flecs::pair<Position, World> p) { std::cout << e.name() << ": {" << p->x << ", " << p->y << "}\n"; }); }
29.12987
80
0.518948
[ "object", "transform" ]
e7799e848e5594c88ab06c82d16cf9ef0337eae6
8,847
cpp
C++
Examples/Grass/main.cpp
leaf3d/leaf3d
c3eb0661a05b448bb02a7a62dbf0a50f339ca3e4
[ "MIT" ]
26
2016-02-04T21:54:09.000Z
2022-02-04T18:21:11.000Z
Examples/Grass/main.cpp
leaf3d/leaf3d
c3eb0661a05b448bb02a7a62dbf0a50f339ca3e4
[ "MIT" ]
3
2016-02-06T14:02:15.000Z
2018-05-02T07:54:02.000Z
Examples/Grass/main.cpp
leaf3d/leaf3d
c3eb0661a05b448bb02a7a62dbf0a50f339ca3e4
[ "MIT" ]
6
2016-02-06T09:39:47.000Z
2021-12-16T16:01:10.000Z
/* * This file is part of the leaf3d project. * * Copyright 2014-2015 Emanuele Bertoldi. All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. * * You should have received a copy of the modified BSD License along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license.php> */ #include <stdio.h> #include <leaf3d/leaf3d.h> #include <leaf3d/leaf3dut.h> #include <glad/glad.h> #include <GLFW/glfw3.h> #define WINDOW_WIDTH 1024 #define WINDOW_HEIGHT 768 #define GRASS_DENSITY 200 #define GRASS_COLOR L3DVec3(0.85f,0.85f,0.55f) #define GRASS_COLOR_VAR L3DVec3(0.2f,0.2f,0.3f) #define GRASS_HEIGHT 0.75f #define GRASS_HEIGHT_VAR 5.0f #define GRASS_FIELD_SIZE 1000.0f #define GRASS_DISTANCE_LOD3 GRASS_FIELD_SIZE * 0.5 * 1.0f #define GRASS_DISTANCE_LOD2 GRASS_FIELD_SIZE * 0.5 * 0.6f #define GRASS_DISTANCE_LOD1 GRASS_FIELD_SIZE * 0.5 * 0.3f #define AMBIENT_COLOR L3DVec4(0.8f, 0.8f, 1, 0.6f) #define SUN_LIGHT_COLOR L3DVec4(0.8f, 0.7f, 0.6f, 1) using namespace l3d; int main() { // -------------------------------- INIT ------------------------------- // // Init GLFW. if (glfwInit() != GL_TRUE) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } // Create a rendering window with OpenGL 3.2 context. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "leaf3d", L3D_NULLPTR, L3D_NULLPTR); glfwMakeContextCurrent(window); // Init leaf3d. if (l3dInit() != L3D_TRUE) { fprintf(stderr, "Failed to initialize leaf3d\n"); return -2; } // Init leaf3dut. if (l3dutInit() != L3D_TRUE) { fprintf(stderr, "Failed to initialize leaf3dut\n"); return -3; } // ----------------------------- RESOURCES ----------------------------- // // Load a shader program with support for lighting (Blinn-Phong). L3DHandle blinnPhongShaderProgram = l3dutLoadShaderProgram("basic.vert", "blinnphong.frag"); // Load a shader program for sky box. L3DHandle skyBoxShaderProgram = l3dutLoadShaderProgram("skyBox.vert", "skyBox.frag"); // Load a shader program for grass plane rendering. L3DHandle grassPlaneShaderProgram = l3dutLoadShaderProgram("basic.vert", "grassPlane.frag"); // Load a shader program for realistic grass blades rendering. L3DHandle grassBladesShaderProgram = l3dutLoadShaderProgram("basic.vert", "grassBlades.frag", "grassBlades.geom"); // Load a sky box. L3DHandle skyBoxCubeMap = l3dutLoadTextureCube( "skybox2_right.jpg", "skybox2_left.jpg", "skybox2_top.jpg", "skybox2_bottom.jpg", "skybox2_back.jpg", "skybox2_front.jpg" ); L3DHandle skyBoxMaterial = l3dLoadMaterial("skyBoxMaterial", skyBoxShaderProgram); l3dAddTextureToMaterial(skyBoxMaterial, "cubeMap", skyBoxCubeMap); L3DHandle skyBox = l3dLoadSkyBox(skyBoxMaterial); // Load a grass plane. L3DHandle grassTexture = l3dutLoadTexture2D("grass_diffuse.jpg"); L3DHandle grassDirtTexture = l3dutLoadTexture2D("grass_dirt_diffuse.jpg"); L3DHandle grassPlaneMaterial = l3dLoadMaterial("grassPlaneMaterial", grassPlaneShaderProgram, GRASS_COLOR); l3dAddTextureToMaterial(grassPlaneMaterial, "diffuseMap", grassTexture); l3dAddTextureToMaterial(grassPlaneMaterial, "dirtMap", grassDirtTexture); L3DHandle grassPlane = l3dLoadGrid(1, grassPlaneMaterial, L3DVec2(30, 30), L3D_ALPHA_BLEND_MESH_RENDERLAYER); l3dRotateMesh(grassPlane, 1.57f, L3DVec3(-1, 0, 0)); l3dScaleMesh(grassPlane, L3DVec3(GRASS_FIELD_SIZE, GRASS_FIELD_SIZE, 1)); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD3", GRASS_DISTANCE_LOD3); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD2", GRASS_DISTANCE_LOD2); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD1", GRASS_DISTANCE_LOD1); // Load grass blades. L3DHandle grassBladesTexture = l3dutLoadTexture2D("grass_blade_diffuse.png"); L3DHandle grassBladesMaterial = l3dLoadMaterial("grassBladeMaterial", grassBladesShaderProgram, GRASS_COLOR); l3dAddTextureToMaterial(grassBladesMaterial, "diffuseMap", grassBladesTexture); L3DHandle grassBlades = l3dLoadGrid(GRASS_DENSITY, grassBladesMaterial, L3DVec2(1, 1), L3D_ALPHA_BLEND_MESH_RENDERLAYER); l3dRotateMesh(grassBlades, 1.57f, L3DVec3(-1, 0, 0)); l3dScaleMesh(grassBlades, L3DVec3(GRASS_FIELD_SIZE * 0.5, GRASS_FIELD_SIZE * 0.5, 1)); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD3", GRASS_DISTANCE_LOD3 * 0.5f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD2", GRASS_DISTANCE_LOD2 * 0.5f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD1", GRASS_DISTANCE_LOD1 * 0.5f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassHeight", GRASS_HEIGHT); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassHeightVariation", GRASS_HEIGHT_VAR); l3dSetShaderProgramUniformVec3(grassBladesShaderProgram, "u_grassColorVariation", GRASS_COLOR_VAR); // Load a crate. L3DHandle crateTexture = l3dutLoadTexture2D("crate.jpg"); L3DHandle crateSpecTexture = l3dutLoadTexture2D("crate_spec.jpg"); L3DHandle crateNormTexture = l3dutLoadTexture2D("crate_norm.jpg"); L3DHandle crateMaterial = l3dLoadMaterial("crateMaterial", blinnPhongShaderProgram); l3dAddTextureToMaterial(crateMaterial, "diffuseMap", crateTexture); l3dAddTextureToMaterial(crateMaterial, "specularMap", crateSpecTexture); l3dAddTextureToMaterial(crateMaterial, "normalMap", crateNormTexture); L3DHandle cube1 = l3dLoadCube(crateMaterial); l3dRotateMesh(cube1, 0.75f); l3dTranslateMesh(cube1, L3DVec3(10, 3, -20)); l3dScaleMesh(cube1, L3DVec3(6, 6, 6)); // Load a tree. unsigned int meshCount = 0; L3DHandle* tree = l3dutLoadMeshes("tree1.obj", blinnPhongShaderProgram, &meshCount); for (int i=0; i<meshCount; ++i) { l3dRotateMesh(tree[i], 0.75f); l3dTranslateMesh(tree[i], L3DVec3(-45, 0, 20)); l3dScaleMesh(tree[i], L3DVec3(10, 10, 10)); } // Load a directional light. L3DHandle sunLight = l3dLoadDirectionalLight(L3DVec3(-2, -1, 5), SUN_LIGHT_COLOR); // Set the global ambient light color. l3dSetShaderProgramUniformVec4(blinnPhongShaderProgram, "u_ambientColor", AMBIENT_COLOR); // Create a camera. L3DHandle camera = l3dLoadCamera( "Default", glm::lookAt( glm::vec3(0.0f, 15.0f, 40.0f), glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) ), glm::perspective(45.0f, (GLfloat)WINDOW_WIDTH/(GLfloat)WINDOW_HEIGHT, 10.0f, GRASS_FIELD_SIZE) ); // Create a forward rendering pipeline. L3DHandle renderQueue = l3dLoadForwardRenderQueue(WINDOW_WIDTH, WINDOW_HEIGHT, L3DVec4(0, 0, 0.05f, 1)); // ---------------------------- RENDERING ------------------------------ // double lastTime = glfwGetTime(); while(!glfwWindowShouldClose(window)) { double now = glfwGetTime(); double dt = now - lastTime; lastTime = now; // Poll window events. glfwPollEvents(); // Render current frame. l3dRenderFrame(camera, renderQueue); // Apply a rotation to the camera. l3dRotateCamera(camera, 0.5f * dt); // Swap buffers. glfwSwapBuffers(window); // Print speed. l3dutPrintFrameStats(dt); } // ---------------------------- TERMINATE ----------------------------- // // Terminate leaf3dut. l3dutTerminate(); // Terminate leaf3d. l3dTerminate(); // Terminate GLFW. glfwTerminate(); return 0; }
40.958333
125
0.701707
[ "render" ]
e783d686a0d6e94569a7f3c40883598a26c2a4ab
10,008
cpp
C++
lib/tlrCore/Image.cpp
darbyjohnston/tlRender
0bdb8aa3795a0098811a7c3ed6add3023bcfd55a
[ "BSD-3-Clause" ]
59
2021-04-26T23:38:35.000Z
2022-03-23T15:21:44.000Z
lib/tlrCore/Image.cpp
darbyjohnston/tlRender
0bdb8aa3795a0098811a7c3ed6add3023bcfd55a
[ "BSD-3-Clause" ]
17
2021-04-30T02:03:08.000Z
2022-01-11T19:54:47.000Z
lib/tlrCore/Image.cpp
darbyjohnston/tlRender
0bdb8aa3795a0098811a7c3ed6add3023bcfd55a
[ "BSD-3-Clause" ]
5
2021-06-07T16:11:53.000Z
2021-12-10T23:29:45.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2021-2022 Darby Johnston // All rights reserved. #include <tlrCore/Image.h> #include <tlrCore/Assert.h> #include <tlrCore/Error.h> #include <tlrCore/String.h> #include <algorithm> #include <array> #include <cstring> #include <iostream> using namespace tlr::core; namespace tlr { namespace imaging { math::BBox2i getBBox(float aspect, const imaging::Size& size) noexcept { math::BBox2i out; const float sizeAspect = size.getAspect(); math::BBox2i bbox; if (sizeAspect > aspect) { out = math::BBox2i( size.w / 2.F - (size.h * aspect) / 2.F, 0, size.h * aspect, size.h); } else { out = math::BBox2i( 0, size.h / 2.F - (size.w / aspect) / 2.F, size.w, size.w / aspect); } return out; } std::ostream& operator << (std::ostream& os, const imaging::Size& value) { os << value.w << "x" << value.h; return os; } std::istream& operator >> (std::istream& is, imaging::Size& out) { std::string s; is >> s; auto split = string::split(s, 'x'); if (split.size() != 2) { throw ParseError(); } out.w = std::stoi(split[0]); out.h = std::stoi(split[1]); return is; } TLR_ENUM_IMPL( PixelType, "None", "L_U8", "L_U16", "L_U32", "L_F16", "L_F32", "LA_U8", "LA_U16", "LA_U32", "LA_F16", "LA_F32", "RGB_U8", "RGB_U10", "RGB_U16", "RGB_U32", "RGB_F16", "RGB_F32", "RGBA_U8", "RGBA_U16", "RGBA_U32", "RGBA_F16", "RGBA_F32", "YUV_420P"); TLR_ENUM_SERIALIZE_IMPL(PixelType); TLR_ENUM_IMPL( YUVRange, "Full", "Video"); TLR_ENUM_SERIALIZE_IMPL(YUVRange); uint8_t getChannelCount(PixelType value) noexcept { const std::array<uint8_t, static_cast<size_t>(PixelType::Count)> values = { 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 3 }; return values[static_cast<size_t>(value)]; } uint8_t getBitDepth(PixelType value) noexcept { const std::array<uint8_t, static_cast<size_t>(PixelType::Count)> values = { 0, 8, 16, 32, 16, 32, 8, 16, 32, 16, 32, 8, 10, 16, 32, 16, 32, 8, 16, 32, 16, 32, 0 }; return values[static_cast<size_t>(value)]; } PixelType getIntType(std::size_t channelCount, std::size_t bitDepth) noexcept { PixelType out = PixelType::None; switch (channelCount) { case 1: switch (bitDepth) { case 8: out = PixelType::L_U8; break; case 16: out = PixelType::L_U16; break; case 32: out = PixelType::L_U32; break; } break; case 2: switch (bitDepth) { case 8: out = PixelType::LA_U8; break; case 16: out = PixelType::LA_U16; break; case 32: out = PixelType::LA_U32; break; } break; case 3: switch (bitDepth) { case 8: out = PixelType::RGB_U8; break; case 10: out = PixelType::RGB_U10; break; case 16: out = PixelType::RGB_U16; break; case 32: out = PixelType::RGB_U32; break; } break; case 4: switch (bitDepth) { case 8: out = PixelType::RGBA_U8; break; case 16: out = PixelType::RGBA_U16; break; case 32: out = PixelType::RGBA_U32; break; } break; } return out; } PixelType getFloatType(std::size_t channelCount, std::size_t bitDepth) noexcept { PixelType out = PixelType::None; switch (channelCount) { case 1: switch (bitDepth) { case 16: out = PixelType::L_F16; break; case 32: out = PixelType::L_F32; break; } break; case 2: switch (bitDepth) { case 16: out = PixelType::LA_F16; break; case 32: out = PixelType::LA_F32; break; } break; case 3: switch (bitDepth) { case 16: out = PixelType::RGB_F16; break; case 32: out = PixelType::RGB_F32; break; } break; case 4: switch (bitDepth) { case 16: out = PixelType::RGBA_F16; break; case 32: out = PixelType::RGBA_F32; break; } break; } return out; } PixelType getClosest(PixelType value, const std::vector<PixelType>& types) { std::map<size_t, PixelType> diff; for (const auto& type : types) { diff[abs(static_cast<int>(getChannelCount(value)) - static_cast<int>(getChannelCount(type))) + abs(static_cast<int>(getBitDepth(value)) - static_cast<int>(getBitDepth(type)))] = type; } return !diff.empty() ? diff.begin()->second : PixelType::None; } size_t align(size_t value, size_t alignment) { return (value / alignment * alignment) + (value % alignment != 0 ? alignment : 0); } std::size_t getDataByteCount(const Info& info) { std::size_t out = 0; const size_t w = info.size.w; const size_t h = info.size.h; const size_t alignment = info.layout.alignment; switch (info.pixelType) { case PixelType::L_U8: out = align(w, alignment) * h; break; case PixelType::L_U16: out = align(w * 2, alignment) * h; break; case PixelType::L_U32: out = align(w * 4, alignment) * h; break; case PixelType::L_F16: out = align(w * 2, alignment) * h; break; case PixelType::L_F32: out = align(w * 4, alignment) * h; break; case PixelType::LA_U8: out = align(w * 2, alignment) * h; break; case PixelType::LA_U16: out = align(w * 2 * 2, alignment) * h; break; case PixelType::LA_U32: out = align(w * 2 * 4, alignment) * h; break; case PixelType::LA_F16: out = align(w * 2 * 2, alignment) * h; break; case PixelType::LA_F32: out = align(w * 2 * 4, alignment) * h; break; case PixelType::RGB_U8: out = align(w * 3, alignment) * h; break; case PixelType::RGB_U10: out = align(w * 4, alignment) * h; break; case PixelType::RGB_U16: out = align(w * 3 * 2, alignment) * h; break; case PixelType::RGB_U32: out = align(w * 3 * 4, alignment) * h; break; case PixelType::RGB_F16: out = align(w * 3 * 2, alignment) * h; break; case PixelType::RGB_F32: out = align(w * 3 * 4, alignment) * h; break; case PixelType::RGBA_U8: out = align(w * 4, alignment) * h; break; case PixelType::RGBA_U16: out = align(w * 4 * 2, alignment) * h; break; case PixelType::RGBA_U32: out = align(w * 4 * 4, alignment) * h; break; case PixelType::RGBA_F16: out = align(w * 4 * 2, alignment) * h; break; case PixelType::RGBA_F32: out = align(w * 4 * 4, alignment) * h; break; case PixelType::YUV_420P: //! \todo Is YUV data aligned? out = w * h + (w / 2 * h / 2) * 2; break; default: break; } return out; } std::ostream& operator << (std::ostream& os, const imaging::Info& value) { os << value.size << "," << value.pixelType; return os; } void Image::_init(const Info& info) { _info = info; _dataByteCount = imaging::getDataByteCount(info); _data = new uint8_t[_dataByteCount]; } Image::Image() {} Image::~Image() { delete[] _data; } std::shared_ptr<Image> Image::create(const Info& info) { auto out = std::shared_ptr<Image>(new Image); out->_init(info); return out; } void Image::setTags(const std::map<std::string, std::string>& value) { _tags = value; } void Image::zero() { std::memset(_data, 0, _dataByteCount); } } }
32.38835
111
0.433153
[ "vector" ]
e7863cfc703198e58f5cbc6d0738ad6b809f8d20
4,948
cpp
C++
prj.objed/objedutils/src/objedmarkup.cpp
usilinsergey/objed
a5d0c82382a6546d5d4c649f153eec94c4ade0ee
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
prj.objed/objedutils/src/objedmarkup.cpp
usilinsergey/objed
a5d0c82382a6546d5d4c649f153eec94c4ade0ee
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
prj.objed/objedutils/src/objedmarkup.cpp
usilinsergey/objed
a5d0c82382a6546d5d4c649f153eec94c4ade0ee
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Copyright (c) 2011-2013, Sergey Usilin. All rights reserved. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of copyright holders. */ #include <QFileInfo> #include <QFile> #include <QDir> #include <objedutils/objedmarkup.h> #include <objedutils/objedexp.h> #include <json-cpp/json.h> ObjedMarkup::ObjedMarkup(bool autoSave) : autoSave(autoSave), starred(false) { return; } ObjedMarkup::ObjedMarkup(const QString &markupPath, bool autoSave) : autoSave(autoSave), starred(false) { open(markupPath); } ObjedMarkup::~ObjedMarkup() { close(); } void ObjedMarkup::open(const QString &markupPath) { close(); this->starred = false; this->objectList.clear(); this->markupPath = markupPath; QFile markupFile(markupPath); markupFile.setFileName(markupPath); if (markupFile.open(QIODevice::ReadOnly) == false) return; QByteArray data = markupFile.readAll(); if (data.length() <= 0) return; Json::Value root; Json::Reader reader; if (reader.parse(data.constData(), root) == false) return; starred = root["starred"].asBool(); Json::Value objects = root["objects"]; if (objects.isArray()) { for (size_t i = 0; i < objects.size(); i++) { Json::Value jsonObject = objects[i]; if (jsonObject.isArray() && jsonObject.size() >= 4) { int x = jsonObject[0u].asInt(); int y = jsonObject[1u].asInt(); int width = jsonObject[2u].asInt(); int height = jsonObject[3u].asInt(); objectList.append(QRect(x, y, width, height)); } } } } void ObjedMarkup::save(const QString &markupPath) { if (markupPath.isEmpty() == false) this->markupPath = markupPath; if (this->markupPath.isEmpty() == true) return; if (QFileInfo(this->markupPath).absoluteDir().exists() == false) QDir().mkpath(QFileInfo(this->markupPath).absolutePath()); QFile markupFile(this->markupPath); if (markupFile.open(QIODevice::WriteOnly) == false) throw ObjedException(QString("Cannot save markup to %0").arg(this->markupPath)); Json::Value root; root["starred"] = starred; foreach (QRect object, objectList) { Json::Value jsonRect; jsonRect.append(object.x()); jsonRect.append(object.y()); jsonRect.append(object.width()); jsonRect.append(object.height()); root["objects"].append(jsonRect); } Json::FastWriter writer; markupFile.write(writer.write(root).c_str()); } void ObjedMarkup::close() { save(); starred = false; objectList.clear(); markupPath.clear(); } void ObjedMarkup::setStarred(bool starred) { if (this->starred == starred) return; this->starred = starred; if (autoSave) save(); } void ObjedMarkup::appendObject(const QRect &object) { if (object.isEmpty() || objectList.contains(object)) return; objectList.append(object); if (autoSave) save(); } void ObjedMarkup::removeObject(const QRect &object) { if (object.isEmpty() || !objectList.contains(object)) return; objectList.removeAll(object); if (autoSave) save(); } void ObjedMarkup::modifyObject(const QRect &oldObject, const QRect &newObject) { if (oldObject.isEmpty() || newObject.isEmpty() || !objectList.contains(oldObject)) return; if (oldObject == newObject) return; objectList.removeAll(oldObject); objectList.append(newObject); if (autoSave) save(); } bool ObjedMarkup::isOpened() const { return markupPath.isEmpty() == false; } bool ObjedMarkup::isStarred() const { return starred; } QList<QRect> ObjedMarkup::objects() const { return objectList; }
26.042105
103
0.711196
[ "object" ]
e788bcd834940c6d437013cbfc44e075b58f4ffa
8,980
cxx
C++
MITK/Applications/CreatePolyDataFromImage/niftkCreatePolyDataFromImage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Applications/CreatePolyDataFromImage/niftkCreatePolyDataFromImage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Applications/CreatePolyDataFromImage/niftkCreatePolyDataFromImage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ /*! * \file niftkCreatePolyDataFromImage.cxx * \page niftkCreatePolyDataFromImage * \section niftkCreatePolyDataFromImageSummary niftkCreatePolyDataFromImage creates poly data by thresholding the input target image and applying marching cubes. */ #include <itkCommandLineHelper.h> #include <niftkCommandLineParser.h> #include <mitkIOUtil.h> #include <niftkImageToSurfaceFilter.h> #include <niftkLogHelper.h> struct niftk::CommandLineArgumentDescription clArgList[] = { {OPT_STRING|OPT_REQ, "i", "fileName", "Input image."}, {OPT_STRING|OPT_REQ, "o", "fileName", "Output .stl model."}, {OPT_DOUBLE, "t", "double", "[100.0] Threshold value."}, {OPT_INT, "e", "int", "[0] Extraction type either (0) vtk Marching cubes or (1) corrected marching cubes 33."}, {OPT_DOUBLE, "ir", "double", "[1.0] Input image downsampling ratio."}, {OPT_INT, "isType", "int", "[0] Input image smoothing either (0) no smoothing, (1) Gaussian smoothing, or" "(2) Median smoothing."}, {OPT_FLOAT, "isRad", "float", "[0.5] Input image smoothing radius."}, {OPT_INT, "isIter", "int", "[1] Input image smoothing number of iterations."}, {OPT_INT, "d", "int", "[0] surface decimation type either (0) no decimation, (1) Decimate Pro, (2) Quadratic VTK, " "(3) Quadratic, (4) Quadratic Tri, (5) Melax, or (6) Shortest Edge."}, {OPT_INT, "ssType", "int", "[0] output surface smoothing either (0) no smoothing, (1) Taubin smoothing," "(2) curvature normal smoothing, (3) inverse edge length smoothing, (4) Windowed Sinc smoothing, (5) standard VTK smoothing."}, {OPT_FLOAT, "ssRad", "float", "[0.5] Output surface smoothing radius."}, {OPT_INT, "ssIter", "int", "[1] Output surface smoothing number of iterations."}, {OPT_FLOAT, "tarRed", "float", "[0.1] Polydata reduction ratio."}, {OPT_SWITCH, "cleanSurfOn", NULL, "Turn on small object removal."}, {OPT_INT, "cleanT", "int", "[1000] Polygon threshold for small object removal."}, {OPT_DONE, NULL, NULL, "Program to extract a polydata object from an image using corrected marching cubes 33.\n" } }; enum { O_INPUT_IMAGE, O_OUTPUT_POLYDATA, O_THRESHOLD, O_EXTRACTION_TYPE, O_SAMPLE_RATIO, O_INPUT_SMOOTH_TYPE, O_INPUT_SMOOTH_RAD, O_INPUT_SMOOTH_ITER, O_DECIMATION, O_SURF_SMOOTH_TYPE, O_SURF_SMOOTH_RAD, O_SURF_SMOOTH_ITER, O_TARGET_RED, O_USE_CLEAN_SURF, O_CLEAN_THRESHOLD }; //----------------------------------------------------------------------- // main() // ------------------------------------------------------------------------- int main( int argc, char *argv[] ) { std::string fileInputImage; std::string fileOutputPolyData; double threshold = 100.0; int extractionType = 0; double samplingRatio = 1.0; int inputSmoothingType = 0; int inputSmoothingIterations = 1; float inputSmoothingRadius = 0.5f; int decimationType = 0; float targetReduction = 0.1f; int surfSmoothingType = 0; int surfSmoothingIterations = 1; float surfSmoothingRadius = 0.5f; bool useSurfClean = false; int surfCleanThreshold = 1000; niftk::CommandLineParser CommandLineOptions(argc, argv, clArgList, false); CommandLineOptions.GetArgument(O_INPUT_IMAGE, fileInputImage); CommandLineOptions.GetArgument(O_OUTPUT_POLYDATA, fileOutputPolyData); CommandLineOptions.GetArgument(O_THRESHOLD, threshold); CommandLineOptions.GetArgument(O_EXTRACTION_TYPE, extractionType); CommandLineOptions.GetArgument(O_SAMPLE_RATIO, samplingRatio); CommandLineOptions.GetArgument(O_INPUT_SMOOTH_TYPE, inputSmoothingType); CommandLineOptions.GetArgument(O_INPUT_SMOOTH_RAD, inputSmoothingRadius); CommandLineOptions.GetArgument(O_INPUT_SMOOTH_ITER, inputSmoothingIterations); CommandLineOptions.GetArgument(O_DECIMATION, decimationType); CommandLineOptions.GetArgument(O_SURF_SMOOTH_TYPE, surfSmoothingType); CommandLineOptions.GetArgument(O_SURF_SMOOTH_RAD, surfSmoothingRadius); CommandLineOptions.GetArgument(O_SURF_SMOOTH_ITER, surfSmoothingIterations); CommandLineOptions.GetArgument(O_TARGET_RED, targetReduction); CommandLineOptions.GetArgument(O_USE_CLEAN_SURF, useSurfClean); CommandLineOptions.GetArgument(O_CLEAN_THRESHOLD, surfCleanThreshold); // load in image mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(fileInputImage); if (inputImage.IsNull()) { std::cerr << "Unable to load input image " << fileInputImage.c_str() << "." << std::endl; return EXIT_FAILURE; } // Create a mask of the correct dimension niftk::ImageToSurfaceFilter::Pointer surfaceFilter = niftk::ImageToSurfaceFilter::New(); surfaceFilter->SetInput(inputImage); surfaceFilter->SetThreshold(threshold); surfaceFilter->SetSamplingRatio(samplingRatio); if (extractionType == 0) { surfaceFilter->SetSurfaceExtractionType(niftk::ImageToSurfaceFilter::StandardExtractor); } else if (extractionType == 1) { surfaceFilter->SetSurfaceExtractionType(niftk::ImageToSurfaceFilter::EnhancedCPUExtractor); } if (inputSmoothingType == 0) { surfaceFilter->SetPerformInputSmoothing(false); } else if (inputSmoothingType == 1) { surfaceFilter->SetPerformInputSmoothing(true); surfaceFilter->SetInputSmoothingType(niftk::ImageToSurfaceFilter::GaussianSmoothing); } else if (inputSmoothingType == 2) { surfaceFilter->SetPerformInputSmoothing(true); surfaceFilter->SetInputSmoothingType(niftk::ImageToSurfaceFilter::MedianSmoothing); } surfaceFilter->SetInputSmoothingIterations(inputSmoothingIterations); surfaceFilter->SetInputSmoothingRadius(inputSmoothingRadius); if (surfSmoothingType == 0) { surfaceFilter->SetPerformSurfaceSmoothing(false); } else if (surfSmoothingType == 1) { surfaceFilter->SetPerformSurfaceSmoothing(true); surfaceFilter->SetSurfaceSmoothingType(niftk::ImageToSurfaceFilter::TaubinSmoothing); } else if (surfSmoothingType == 2) { surfaceFilter->SetPerformSurfaceSmoothing(true); surfaceFilter->SetSurfaceSmoothingType(niftk::ImageToSurfaceFilter::CurvatureNormalSmooth); } else if (surfSmoothingType == 3) { surfaceFilter->SetPerformSurfaceSmoothing(true); surfaceFilter->SetSurfaceSmoothingType(niftk::ImageToSurfaceFilter::InverseEdgeLengthSmooth); } else if (surfSmoothingType == 4) { surfaceFilter->SetPerformSurfaceSmoothing(true); surfaceFilter->SetSurfaceSmoothingType(niftk::ImageToSurfaceFilter::WindowedSincSmoothing); } else if (surfSmoothingType == 5) { surfaceFilter->SetPerformSurfaceSmoothing(true); surfaceFilter->SetSurfaceSmoothingType(niftk::ImageToSurfaceFilter::StandardVTKSmoothing); } surfaceFilter->SetSurfaceSmoothingIterations(surfSmoothingIterations); surfaceFilter->SetSurfaceSmoothingRadius(surfSmoothingRadius); if (decimationType == 0) { surfaceFilter->SetPerformSurfaceDecimation(false); } else if (decimationType == 1) { surfaceFilter->SetPerformSurfaceDecimation(true); surfaceFilter->SetSurfaceDecimationType(niftk::ImageToSurfaceFilter::DecimatePro); } else if (decimationType == 2) { surfaceFilter->SetPerformSurfaceDecimation(true); surfaceFilter->SetSurfaceDecimationType(niftk::ImageToSurfaceFilter::QuadricVTK); } else if (decimationType == 3) { surfaceFilter->SetPerformSurfaceDecimation(true); surfaceFilter->SetSurfaceDecimationType(niftk::ImageToSurfaceFilter::Quadric); } else if (decimationType == 4) { surfaceFilter->SetPerformSurfaceDecimation(true); surfaceFilter->SetSurfaceDecimationType(niftk::ImageToSurfaceFilter::QuadricTri); } else if (decimationType == 5) { surfaceFilter->SetPerformSurfaceDecimation(true); surfaceFilter->SetSurfaceDecimationType(niftk::ImageToSurfaceFilter::Melax); } else if (decimationType == 6) { surfaceFilter->SetPerformSurfaceDecimation(true); surfaceFilter->SetSurfaceDecimationType(niftk::ImageToSurfaceFilter::ShortestEdge); } surfaceFilter->SetTargetReduction(targetReduction); surfaceFilter->SetPerformSurfaceCleaning(useSurfClean); surfaceFilter->SetSurfaceCleaningThreshold(surfCleanThreshold); surfaceFilter->Update(); mitk::Surface::Pointer surf = surfaceFilter->GetOutput(); if (surf.IsNull()) { std::cerr << "Unable to create surface." << std::endl; return EXIT_FAILURE; } // Will throw on failure. mitk::IOUtil::Save(surf, fileOutputPolyData); return EXIT_SUCCESS; }
33.259259
162
0.724388
[ "object", "model" ]
e78d888415ea0bcfdd8ec846504e87a5144ccf22
2,917
hpp
C++
src/mbgl/map/tile_data.hpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
src/mbgl/map/tile_data.hpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
src/mbgl/map/tile_data.hpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
#ifndef MBGL_MAP_TILE_DATA #define MBGL_MAP_TILE_DATA #include <mbgl/util/noncopyable.hpp> #include <mbgl/map/tile_id.hpp> #include <mbgl/renderer/debug_bucket.hpp> #include <mbgl/geometry/debug_font_buffer.hpp> #include <atomic> #include <string> #include <functional> namespace mbgl { class StyleLayer; class Worker; class TileData : private util::noncopyable { public: // initial: // Initial state, only used when the TileData object is created. // // invalid: // FIXME: This state has a bit of overlap with 'initial' and 'obsolete'. // // We report TileData being 'invalid' on Source::hasTile if we don't have the // TileData yet, then Source creates a request. This is misleading because // the TileData object is not effectively on the 'invalid' state and will // cause tiles on 'invalid' state to get reloaded. // // loading: // A request to the FileSource was made for the actual tile data and TileData // is waiting for it to arrive. // // loaded: // The actual tile data has arrived and the tile can be parsed. // // partial: // TileData is partially parsed, some buckets are still waiting for dependencies // to arrive, but it is good for rendering. Partial tiles can also be re-parsed, // but might remain in the same state if dependencies are still missing. // // parsed: // TileData is fully parsed and its contents won't change from this point. This // is the only state which is safe to cache this object. // // obsolete: // The TileData can go to obsolete from any state, due to parsing or loading error, // request cancellation or because the tile is no longer in use. enum class State { initial, invalid, loading, loaded, partial, parsed, obsolete }; // Tile data considered "Ready" can be used for rendering. Data in // partial state is still waiting for network resources but can also // be rendered, although layers will be missing. inline static bool isReadyState(const State& state) { return state == State::partial || state == State::parsed; } TileData(const TileID&); virtual ~TileData() = default; // Mark this tile as no longer needed and cancel any pending work. virtual void cancel() = 0; virtual Bucket* getBucket(const StyleLayer&) = 0; virtual void redoPlacement(float, bool) {} bool isReady() const { return isReadyState(state); } State getState() const { return state; } std::string getError() const { return error; } const TileID id; // Contains the tile ID string for painting debug information. DebugBucket debugBucket; DebugFontBuffer debugFontBuffer; protected: std::atomic<State> state; std::string error; }; } #endif
28.320388
89
0.65821
[ "geometry", "object" ]
e78e92c9f5dc673b7a6c63e7e64d816535d61523
39,561
cpp
C++
dev/Code/Sandbox/Editor/TerrainTexturePainter.cpp
akulamartin/lumberyard
2d4be458a02845179be098e40cdc0c48f28f3b5a
[ "AML" ]
2
2020-12-22T01:02:01.000Z
2020-12-22T01:02:05.000Z
dev/Code/Sandbox/Editor/TerrainTexturePainter.cpp
akulamartin/lumberyard
2d4be458a02845179be098e40cdc0c48f28f3b5a
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/TerrainTexturePainter.cpp
akulamartin/lumberyard
2d4be458a02845179be098e40cdc0c48f28f3b5a
[ "AML" ]
null
null
null
/* * 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. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "TerrainTexturePainter.h" #include "Viewport.h" #include "Objects/DisplayContext.h" #include "TerrainPainterPanel.h" #include "MainWindow.h" #include "CryEditDoc.h" #include "Terrain/Layer.h" #include "Util/ImagePainter.h" #include <I3DEngine.h> #include <ITerrain.h> #include "Terrain/TerrainManager.h" #include "Terrain/SurfaceType.h" #include "Terrain/Heightmap.h" #ifdef AZ_PLATFORM_WINDOWS #include <InitGuid.h> #endif #include <AzToolsFramework/Commands/LegacyCommand.h> // {C3EE67BE-F167-4E48-93B6-47D184DC06F8} DEFINE_GUID(TERRAIN_PAINTER_TOOL_GUID, 0xc3ee67be, 0xf167, 0x4e48, 0x93, 0xb6, 0x47, 0xd1, 0x84, 0xdc, 0x6, 0xf8); struct CUndoTPSector { CUndoTPSector() { m_pImg = 0; m_pImgRedo = 0; } QPoint tile; int x, y; int w; uint32 dwSize; CImageEx* m_pImg; CImageEx* m_pImgRedo; }; struct CUndoTPLayerIdSector { CUndoTPLayerIdSector() { m_pImg = 0; m_pImgRedo = 0; } int x, y; Weightmap* m_pImg; Weightmap* m_pImgRedo; }; struct CUndoTPElement { std::vector <CUndoTPSector> sects; std::vector <CUndoTPLayerIdSector> layerIds; ~CUndoTPElement() { Clear(); } void AddSector(float fpx, float fpy, float radius) { CHeightmap* heightmap = GetIEditor()->GetHeightmap(); CRGBLayer* pRGBLayer = GetIEditor()->GetTerrainManager()->GetRGBLayer(); uint32 dwMaxRes = pRGBLayer->CalcMaxLocalResolution(0, 0, 1, 1); uint32 dwTileCountX = pRGBLayer->GetTileCountX(); uint32 dwTileCountY = pRGBLayer->GetTileCountY(); float gx1 = fpx - radius - 2.0f / dwMaxRes; float gx2 = fpx + radius + 2.0f / dwMaxRes; float gy1 = fpy - radius - 2.0f / dwMaxRes; float gy2 = fpy + radius + 2.0f / dwMaxRes; // Make sure we stay within valid ranges. gx1 = clamp_tpl(gx1, 0.0f, 1.0f); gy1 = clamp_tpl(gy1, 0.0f, 1.0f); gx2 = clamp_tpl(gx2, 0.0f, 1.0f); gy2 = clamp_tpl(gy2, 0.0f, 1.0f); QRect recTiles = QRect( QPoint((uint32)floor(gx1 * dwTileCountX), (uint32)floor(gy1 * dwTileCountY)), QPoint((uint32)ceil(gx2 * dwTileCountX), (uint32)ceil(gy2 * dwTileCountY))); for (uint32 dwTileY = recTiles.top(); dwTileY < recTiles.bottom(); ++dwTileY) { for (uint32 dwTileX = recTiles.left(); dwTileX < recTiles.right(); ++dwTileX) { uint32 dwLocalSize = pRGBLayer->GetTileResolution(dwTileX, dwTileY); uint32 dwSize = pRGBLayer->GetTileResolution(dwTileX, dwTileY) * pRGBLayer->GetTileCountX(); uint32 gwid = dwSize * radius * 4; if (gwid < 32) { gwid = 32; } else if (gwid < 64) { gwid = 64; } else if (gwid < 128) { gwid = 128; } else { gwid = 256; } float x1 = gx1; float x2 = gx2; float y1 = gy1; float y2 = gy2; if (x1 < (float)dwTileX / dwTileCountX) { x1 = (float)dwTileX / dwTileCountX; } if (y1 < (float)dwTileY / dwTileCountY) { y1 = (float)dwTileY / dwTileCountY; } if (x2 > (float)(dwTileX + 1) / dwTileCountX) { x2 = (float)(dwTileX + 1) / dwTileCountX; } if (y2 > (float)(dwTileY + 1) / dwTileCountY) { y2 = (float)(dwTileY + 1) / dwTileCountY; } uint32 wid = gwid; if (wid > dwLocalSize) { wid = dwLocalSize; } QRect recSects = QRect( QPoint(((int)floor(x1 * dwSize / wid)) * wid, ((int)floor(y1 * dwSize / wid)) * wid), QPoint(((int)ceil(x2 * dwSize / wid)) * wid, ((int)ceil(y2 * dwSize / wid)) * wid)); for (uint32 sy = recSects.top(); sy < recSects.bottom(); sy += wid) { for (uint32 sx = recSects.left(); sx < recSects.right(); sx += wid) { bool bFind = false; for (int i = sects.size() - 1; i >= 0; i--) { CUndoTPSector* pSect = &sects[i]; if (pSect->tile.x() == dwTileX && pSect->tile.y() == dwTileY) { if (pSect->x == sx && pSect->y == sy) { bFind = true; break; } } } if (!bFind) { CUndoTPSector newSect; newSect.x = sx; newSect.y = sy; newSect.w = wid; newSect.tile.rx() = dwTileX; newSect.tile.ry() = dwTileY; newSect.dwSize = dwSize; newSect.m_pImg = new CImageEx; newSect.m_pImg->Allocate(newSect.w, newSect.w); CUndoTPSector* pSect = &newSect; pRGBLayer->GetSubImageStretched((float)pSect->x / pSect->dwSize, (float)pSect->y / pSect->dwSize, (float)(pSect->x + pSect->w) / pSect->dwSize, (float)(pSect->y + pSect->w) / pSect->dwSize, *pSect->m_pImg); sects.push_back(newSect); } } } } } // Store LayerIDs const uint32 layerSize = 64; QRect reclids = QRect( QPoint((uint32)floor(gx1 * heightmap->GetWidth() / layerSize), (uint32)floor(gy1 * heightmap->GetHeight() / layerSize)), QPoint((uint32)ceil(gx2 * heightmap->GetWidth() / layerSize), (uint32)ceil(gy2 * heightmap->GetHeight() / layerSize))); for (uint32 ly = reclids.top(); ly < reclids.bottom(); ly++) { for (uint32 lx = reclids.left(); lx < reclids.right(); lx++) { bool bFind = false; for (int i = layerIds.size() - 1; i >= 0; i--) { CUndoTPLayerIdSector* pSect = &layerIds[i]; if (pSect->x == lx && pSect->y == ly) { bFind = true; break; } } if (!bFind) { CUndoTPLayerIdSector newSect; CUndoTPLayerIdSector* pSect = &newSect; pSect->m_pImg = new Weightmap(); pSect->x = lx; pSect->y = ly; heightmap->GetWeightmapBlock(pSect->x * layerSize, pSect->y * layerSize, layerSize, layerSize, *pSect->m_pImg); layerIds.push_back(newSect); } } } } void Paste(bool bIsRedo = false) { CHeightmap* heightmap = GetIEditor()->GetHeightmap(); CRGBLayer* pRGBLayer = GetIEditor()->GetTerrainManager()->GetRGBLayer(); bool bFirst = true; QPoint gminp; QPoint gmaxp; AABB aabb(AABB::RESET); for (int i = sects.size() - 1; i >= 0; i--) { CUndoTPSector* pSect = &sects[i]; pRGBLayer->SetSubImageStretched((float)pSect->x / pSect->dwSize, (float)pSect->y / pSect->dwSize, (float)(pSect->x + pSect->w) / pSect->dwSize, (float)(pSect->y + pSect->w) / pSect->dwSize, *(bIsRedo ? pSect->m_pImgRedo : pSect->m_pImg)); aabb.Add(Vec3((float)pSect->x / pSect->dwSize, (float)pSect->y / pSect->dwSize, 0)); aabb.Add(Vec3((float)(pSect->x + pSect->w) / pSect->dwSize, (float)(pSect->y + pSect->w) / pSect->dwSize, 0)); } // LayerIDs for (int i = layerIds.size() - 1; i >= 0; i--) { CUndoTPLayerIdSector* pSect = &layerIds[i]; heightmap->SetWeightmapBlock(pSect->x * pSect->m_pImg->GetWidth(), pSect->y * pSect->m_pImg->GetHeight(), *(bIsRedo ? pSect->m_pImgRedo : pSect->m_pImg)); heightmap->UpdateEngineTerrain(pSect->x * pSect->m_pImg->GetWidth(), pSect->y * pSect->m_pImg->GetHeight(), pSect->m_pImg->GetWidth(), pSect->m_pImg->GetHeight(), true, false); } if (!aabb.IsReset()) { QRect rc( QPoint(aabb.min.x* heightmap->GetWidth(), aabb.min.y* heightmap->GetHeight()), QPoint(aabb.max.x* heightmap->GetWidth() - 1, aabb.max.y* heightmap->GetHeight() - 1) ); heightmap->UpdateLayerTexture(rc); } } void StoreRedo() { CHeightmap* heightmap = GetIEditor()->GetHeightmap(); for (int i = sects.size() - 1; i >= 0; i--) { CUndoTPSector* pSect = &sects[i]; if (!pSect->m_pImgRedo) { pSect->m_pImgRedo = new CImageEx(); pSect->m_pImgRedo->Allocate(pSect->w, pSect->w); CRGBLayer* pRGBLayer = GetIEditor()->GetTerrainManager()->GetRGBLayer(); pRGBLayer->GetSubImageStretched((float)pSect->x / pSect->dwSize, (float)pSect->y / pSect->dwSize, (float)(pSect->x + pSect->w) / pSect->dwSize, (float)(pSect->y + pSect->w) / pSect->dwSize, *pSect->m_pImgRedo); } } // LayerIds for (int i = layerIds.size() - 1; i >= 0; i--) { CUndoTPLayerIdSector* pSect = &layerIds[i]; if (!pSect->m_pImgRedo) { pSect->m_pImgRedo = new Weightmap(); heightmap->GetWeightmapBlock(pSect->x * pSect->m_pImg->GetWidth(), pSect->y * pSect->m_pImg->GetHeight(), pSect->m_pImg->GetWidth(), pSect->m_pImg->GetHeight(), *pSect->m_pImgRedo); } } } void Clear() { for (int i = 0; i < sects.size(); i++) { CUndoTPSector* pSect = &sects[i]; delete pSect->m_pImg; pSect->m_pImg = 0; delete pSect->m_pImgRedo; pSect->m_pImgRedo = 0; } for (int i = 0; i < layerIds.size(); i++) { CUndoTPLayerIdSector* pSect = &layerIds[i]; delete pSect->m_pImg; pSect->m_pImg = 0; delete pSect->m_pImgRedo; pSect->m_pImgRedo = 0; } } int GetSize() { int size = 0; for (int i = 0; i < sects.size(); i++) { CUndoTPSector* pSect = &sects[i]; if (pSect->m_pImg) { size += pSect->m_pImg->GetSize(); } if (pSect->m_pImgRedo) { size += pSect->m_pImgRedo->GetSize(); } } for (int i = 0; i < layerIds.size(); i++) { CUndoTPLayerIdSector* pSect = &layerIds[i]; if (pSect->m_pImg) { size += pSect->m_pImg->GetSize(); } if (pSect->m_pImgRedo) { size += pSect->m_pImgRedo->GetSize(); } } return size; } }; ////////////////////////////////////////////////////////////////////////// //! Undo object. class CUndoTexturePainter : public IUndoObject { public: CUndoTexturePainter(CTerrainTexturePainter* pTool) { m_pUndo = pTool->m_pTPElem; pTool->m_pTPElem = 0; } protected: virtual void Release() { delete m_pUndo; delete this; }; virtual int GetSize() { return sizeof(*this) + (m_pUndo ? m_pUndo->GetSize() : 0); }; virtual QString GetDescription() { return "Terrain Painter Modify"; }; virtual void Undo(bool bUndo) { if (bUndo) { m_pUndo->StoreRedo(); } if (m_pUndo) { m_pUndo->Paste(); } } virtual void Redo() { if (m_pUndo) { m_pUndo->Paste(true); } } private: CUndoTPElement* m_pUndo; }; CTextureBrush CTerrainTexturePainter::m_brush; namespace { int s_toolPanelId = 0; CTerrainPainterPanel* s_toolPanel = 0; }; ////////////////////////////////////////////////////////////////////////// CTerrainTexturePainter::CTerrainTexturePainter() { m_brush.maxRadius = 1000.0f; SetStatusText(tr("Paint Texture Layers")); m_heightmap = GetIEditor()->GetHeightmap(); assert(m_heightmap); m_3DEngine = GetIEditor()->Get3DEngine(); assert(m_3DEngine); m_renderer = GetIEditor()->GetRenderer(); assert(m_renderer); m_pointerPos(0, 0, 0); GetIEditor()->ClearSelection(); ////////////////////////////////////////////////////////////////////////// // Initialize sectors. ////////////////////////////////////////////////////////////////////////// SSectorInfo sectorInfo; m_heightmap->GetSectorsInfo(sectorInfo); m_bIsPainting = false; m_pTPElem = 0; } ////////////////////////////////////////////////////////////////////////// CTerrainTexturePainter::~CTerrainTexturePainter() { m_pointerPos(0, 0, 0); if (GetIEditor()->IsUndoRecording()) { GetIEditor()->CancelUndo(); } } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::BeginEditParams(IEditor* ie, int flags) { if (!s_toolPanelId) { s_toolPanel = new CTerrainPainterPanel(*this); s_toolPanelId = GetIEditor()->AddRollUpPage(ROLLUP_TERRAIN, tr("Layer Painter"), s_toolPanel); MainWindow::instance()->setFocus(); s_toolPanel->SetBrush(m_brush); } } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::EndEditParams() { if (s_toolPanelId) { GetIEditor()->RemoveRollUpPage(ROLLUP_TERRAIN, s_toolPanelId); s_toolPanel = 0; s_toolPanelId = 0; } } ////////////////////////////////////////////////////////////////////////// bool CTerrainTexturePainter::MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags) { bool bPainting = false; bool hitTerrain = false; m_pointerPos = view->ViewToWorld(point, &hitTerrain, true); m_brush.bErase = false; if (m_bIsPainting) { if (event == eMouseLDown || event == eMouseLUp) { Action_StopUndo(); } } if ((flags & MK_CONTROL) != 0) // pick layerid { if (event == eMouseLDown) { Action_PickLayerId(); } } else if (event == eMouseLDown || (event == eMouseMove && (flags & MK_LBUTTON))) // paint { // Terrain can only exist in the positive quadrant, so don't even try to paint when // we're outside those bounds. if ((m_pointerPos.x >= 0.0f) && (m_pointerPos.y >= 0.0f) && hitTerrain) { Action_Paint(); } } #if AZ_TRAIT_OS_PLATFORM_APPLE GetIEditor()->SetStatusText(tr("L-Mouse:Paint [ ]: Change Brush Radius Shift+[ ]:Change Brush Hardness ⌘L-Mouse:Pick LayerId")); #else GetIEditor()->SetStatusText(tr("L-Mouse:Paint [ ]: Change Brush Radius Shift+[ ]:Change Brush Hardness CTRL+L-Mouse:Pick LayerId")); #endif return true; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Display(DisplayContext& dc) { dc.SetColor(0, 1, 0, 1); if (m_pointerPos.x == 0 && m_pointerPos.y == 0 && m_pointerPos.z == 0) { return; // mouse cursor not in window } dc.DepthTestOff(); dc.DrawTerrainCircle(m_pointerPos, m_brush.radius, 0.2f); dc.DepthTestOn(); } ////////////////////////////////////////////////////////////////////////// bool CTerrainTexturePainter::OnKeyDown(CViewport* view, uint32 nChar, uint32 nRepCnt, uint32 nFlags) { bool bProcessed = false; bool shiftKeyPressed = Qt::ShiftModifier & QApplication::queryKeyboardModifiers(); bool controlKeyPressed = Qt::ControlModifier & QApplication::queryKeyboardModifiers(); if (nChar == VK_OEM_6) { if (!shiftKeyPressed && !controlKeyPressed) { m_brush.radius = clamp_tpl(m_brush.radius + 1, m_brush.minRadius, m_brush.maxRadius); bProcessed = true; } // If you press shift & control together, you can adjust both sliders at the same time. if (shiftKeyPressed) { m_brush.colorHardness = clamp_tpl(m_brush.colorHardness + 0.01f, 0.0f, 1.0f); bProcessed = true; } if (controlKeyPressed) { m_brush.detailHardness = clamp_tpl(m_brush.detailHardness + 0.01f, 0.0f, 1.0f); bProcessed = true; } } else if (nChar == VK_OEM_4) { if (!shiftKeyPressed && !controlKeyPressed) { m_brush.radius = clamp_tpl(m_brush.radius - 1, m_brush.minRadius, m_brush.maxRadius); bProcessed = true; } // If you press shift & control together, you can adjust both sliders at the same time. if (shiftKeyPressed) { m_brush.colorHardness = clamp_tpl(m_brush.colorHardness - 0.01f, 0.0f, 1.0f); bProcessed = true; } if (controlKeyPressed) { m_brush.detailHardness = clamp_tpl(m_brush.detailHardness - 0.01f, 0.0f, 1.0f); bProcessed = true; } } if (bProcessed && s_toolPanel) { s_toolPanel->SetBrush(m_brush); } return bProcessed; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Action_PickLayerId() { int iTerrainSize = m_3DEngine->GetTerrainSize(); // in m int hmapWidth = m_heightmap->GetWidth(); int hmapHeight = m_heightmap->GetHeight(); int iX = (int)((m_pointerPos.y * hmapWidth) / iTerrainSize); // maybe +0.5f is needed int iY = (int)((m_pointerPos.x * hmapHeight) / iTerrainSize); // maybe +0.5f is needed if (iX >= 0 && iX < iTerrainSize) { if (iY >= 0 && iY < iTerrainSize) { LayerWeight weight = m_heightmap->GetLayerWeightAt(iX, iY); CLayer* pLayer = GetIEditor()->GetTerrainManager()->FindLayerByLayerId(weight.GetLayerId(0)); s_toolPanel->SelectLayer(pLayer); } } } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Action_Paint() { ////////////////////////////////////////////////////////////////////////// // Paint spot on selected layer. ////////////////////////////////////////////////////////////////////////// CLayer* pLayer = GetSelectedLayer(); if (!pLayer) { return; } Vec3 center(m_pointerPos.x, m_pointerPos.y, 0); static bool bPaintLock = false; if (bPaintLock) { return; } bPaintLock = true; PaintLayer(pLayer, center, false); GetIEditor()->GetDocument()->SetModifiedFlag(TRUE); GetIEditor()->SetModifiedModule(eModifiedTerrain); GetIEditor()->UpdateViews(eUpdateHeightmap); bPaintLock = false; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Action_Flood() { ////////////////////////////////////////////////////////////////////////// // Paint spot on selected layer. ////////////////////////////////////////////////////////////////////////// CLayer* pLayer = GetSelectedLayer(); if (!pLayer) { return; } static bool bPaintLock = false; if (bPaintLock) { return; } bPaintLock = true; PaintLayer(pLayer, Vec3(0.0f), true); GetIEditor()->GetDocument()->SetModifiedFlag(TRUE); GetIEditor()->SetModifiedModule(eModifiedTerrain); GetIEditor()->UpdateViews(eUpdateHeightmap); bPaintLock = false; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::PaintLayer(CLayer* pLayer, const Vec3& center, bool bFlood) { float fTerrainSize = (float)m_3DEngine->GetTerrainSize(); // in m // If we're doing a flood fill, set our paint brush to the center of the terrain with a radius that covers the entire terrain // regardless of what's been passed in. float radius = bFlood ? m_3DEngine->GetTerrainSize() * 0.5f : m_brush.radius; Vec3 brushCenter = bFlood ? Vec3(radius, radius, 0.0f) : center; SEditorPaintBrush br(*GetIEditor()->GetHeightmap(), *pLayer, m_brush.bMaskByLayerSettings, m_brush.m_dwMaskLayerId, bFlood); br.m_cFilterColor = m_brush.m_cFilterColor * m_brush.m_fBrightness; br.m_cFilterColor.rgb2srgb(); br.fRadius = radius / fTerrainSize; br.color = m_brush.value; if (m_brush.bErase) { br.color = 0; } // Paint spot on layer mask. { float fX = brushCenter.y / fTerrainSize; // 0..1 float fY = brushCenter.x / fTerrainSize; // 0..1 // change terrain texture if (m_brush.colorHardness > 0.0f) { br.hardness = m_brush.colorHardness; CRGBLayer* pRGBLayer = GetIEditor()->GetTerrainManager()->GetRGBLayer(); assert(pRGBLayer->CalcMinRequiredTextureExtend()); // load m_texture is needed/possible pLayer->PrecacheTexture(); if (pLayer->m_texture.IsValid()) { Action_CollectUndo(fX, fY, br.fRadius); pRGBLayer->PaintBrushWithPatternTiled(fX, fY, br, pLayer->m_texture); } } if (m_brush.detailHardness > 0.0f) // we also want to change the detail layer data { br.hardness = m_brush.detailHardness; // get unique layerId uint32 dwLayerId = pLayer->GetOrRequestLayerId(); m_heightmap->PaintLayerId(fX, fY, br, dwLayerId); } } ////////////////////////////////////////////////////////////////////////// // Update Terrain textures. ////////////////////////////////////////////////////////////////////////// { // For updating our runtime terrain textures, we adjust our minimum "affected" pixel values to // be one up and to the left from where we've painted. This is because our runtime textures // use bilinear filtering, which puts a copy of the first pixel in a sector into the last pixel // in the previous sector. So if we modified the first pixel of a sector, subtracting // one will cause us to properly update the runtime texture for the previous sector as well. const Vec3 bilinearOffset = Vec3(1.0f, 1.0f, 0.0f); Vec3 vMin = brushCenter - Vec3(radius, radius, 0.0f) - bilinearOffset; Vec3 vMax = brushCenter + Vec3(radius, radius, 0.0f); int iTerrainSize = m_3DEngine->GetTerrainSize(); // in meters int iTexSectorSize = m_3DEngine->GetTerrainTextureNodeSizeMeters(); // in meters if (!iTexSectorSize) { assert(0); // maybe we should visualized this to the user return; // you need to calculated the surface texture first } // Get the range of sectors that have been modified so that we can update the runtime textures // currently in use. int iMinSecX = (int)floor(vMin.x / (float)iTexSectorSize); int iMinSecY = (int)floor(vMin.y / (float)iTexSectorSize); int iMaxSecX = (int)ceil (vMax.x / (float)iTexSectorSize); int iMaxSecY = (int)ceil (vMax.y / (float)iTexSectorSize); iMinSecX = max(iMinSecX, 0); iMinSecY = max(iMinSecY, 0); iMaxSecX = min(iMaxSecX, iTerrainSize / iTexSectorSize); iMaxSecY = min(iMaxSecY, iTerrainSize / iTexSectorSize); float fTerrainSize = (float)m_3DEngine->GetTerrainSize(); // in m // update rectangle in 0..1 range float fGlobalMinX = max(vMin.x / fTerrainSize, 0.0f), fGlobalMinY = max(vMin.y / fTerrainSize, 0.0f); float fGlobalMaxX = vMax.x / fTerrainSize, fGlobalMaxY = vMax.y / fTerrainSize; for (int iY = iMinSecY; iY < iMaxSecY; ++iY) { for (int iX = iMinSecX; iX < iMaxSecX; ++iX) { m_heightmap->UpdateSectorTexture(QPoint(iY, iX), fGlobalMinY, fGlobalMinX, fGlobalMaxY, fGlobalMaxX); } } } ////////////////////////////////////////////////////////////////////////// // Update surface types. ////////////////////////////////////////////////////////////////////////// // Build rectangle in heightmap coordinates. { float fTerrainSize = (float)m_3DEngine->GetTerrainSize(); // in m int hmapWidth = m_heightmap->GetWidth(); int hmapHeight = m_heightmap->GetHeight(); float fX = brushCenter.y * hmapWidth / fTerrainSize; float fY = brushCenter.x * hmapHeight / fTerrainSize; int unitSize = m_heightmap->GetUnitSize(); float fHMRadius = radius / unitSize; // clip against heightmap borders int left = max((int)floor(fX - fHMRadius), 0); int top = max((int)floor(fY - fHMRadius), 0); int width = min((int)ceil(fX + fHMRadius), hmapWidth); int height = min((int)ceil(fY + fHMRadius), hmapHeight); // Update surface types at 3d engine terrain. m_heightmap->UpdateEngineTerrain(left, top, width, height, false, true); } } ////////////////////////////////////////////////////////////////////////// CLayer* CTerrainTexturePainter::GetSelectedLayer() const { //CString selLayer = s_toolPanel->GetSelectedLayer(); CLayer* pSelLayer = s_toolPanel->GetSelectedLayer(); for (int i = 0; i < GetIEditor()->GetTerrainManager()->GetLayerCount(); i++) { CLayer* pLayer = GetIEditor()->GetTerrainManager()->GetLayer(i); if (pSelLayer == pLayer) { return pLayer; } } return 0; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Action_StartUndo() { if (m_bIsPainting) { return; } m_pTPElem = new CUndoTPElement; m_bIsPainting = true; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Action_CollectUndo(float x, float y, float radius) { if (!m_bIsPainting) { Action_StartUndo(); } m_pTPElem->AddSector(x, y, radius); } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Action_StopUndo() { if (!m_bIsPainting) { return; } AzToolsFramework::UndoSystem::URSequencePoint* undoOperation = nullptr; AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(undoOperation, &AzToolsFramework::ToolsApplicationRequests::BeginUndoBatch, "Texture Layer Painting"); if (undoOperation) { auto undoCommand = aznew AzToolsFramework::LegacyCommand<IUndoObject>("Texture Layer Painting Command", AZStd::make_unique<CUndoTexturePainter>(this)); undoCommand->SetParent(undoOperation); // This transfers ownership to undoOperation object who will delete undoCommand. } AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast(&AzToolsFramework::ToolsApplicationRequests::EndUndoBatch); m_bIsPainting = false; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::Command_Activate() { CEditTool* pTool = GetIEditor()->GetEditTool(); if (pTool && qobject_cast<CTerrainTexturePainter*>(pTool)) { // Already active. return; } GetIEditor()->SelectRollUpBar(ROLLUP_TERRAIN); // This needs to be done after the terrain tab is selected, because in // Cry-Free mode the terrain tool could be closed, whereas in legacy // mode the rollupbar is never deleted, it's only hidden pTool = new CTerrainTexturePainter(); GetIEditor()->SetEditTool(pTool); MainWindow::instance()->update(); } const GUID& CTerrainTexturePainter::GetClassID() { return TERRAIN_PAINTER_TOOL_GUID; } ////////////////////////////////////////////////////////////////////////// void CTerrainTexturePainter::RegisterTool(CRegistrationContext& rc) { rc.pClassFactory->RegisterClass(new CQtViewClass<CTerrainTexturePainter>("EditTool.TerrainPainter", "Terrain", ESYSTEM_CLASS_EDITTOOL)); CommandManagerHelper::RegisterCommand(rc.pCommandManager, "edit_tool", "terrain_painter_activate", "", "", functor(CTerrainTexturePainter::Command_Activate)); } float CTerrainTexturePainter::PyGetBrushRadius() { return m_brush.radius; } void CTerrainTexturePainter::PySetBrushRadius(float radius) { m_brush.radius = radius; RefreshUI(); } float CTerrainTexturePainter::PyGetBrushColorHardness() { return m_brush.colorHardness; } void CTerrainTexturePainter::PySetBrushColorHardness(float colorHardness) { m_brush.colorHardness = colorHardness; RefreshUI(); } float CTerrainTexturePainter::PyGetBrushDetailHardness() { return m_brush.detailHardness; } void CTerrainTexturePainter::PySetBrushDetailHardness(float detailHardness) { m_brush.detailHardness = detailHardness; RefreshUI(); } bool CTerrainTexturePainter::PyGetBrushMaskByLayerSettings() { return m_brush.bMaskByLayerSettings; } void CTerrainTexturePainter::PySetBrushMaskByLayerSettings(bool maskByLayerSettings) { m_brush.bMaskByLayerSettings = maskByLayerSettings; RefreshUI(); } QString CTerrainTexturePainter::PyGetBrushMaskLayer() { IEditor *editor = GetIEditor(); AZ_Assert(editor, "Editor instance doesn't exist!"); if (editor) { CTerrainManager *terrainManager = editor->GetTerrainManager(); AZ_Assert(terrainManager, "Terrain Manager instance doesn't exist!"); if (terrainManager) { CLayer* layer = terrainManager->FindLayerByLayerId(m_brush.m_dwMaskLayerId); return layer ? layer->GetLayerName() : ""; } } return ""; } void CTerrainTexturePainter::PySetBrushMaskLayer(const char *layerName) { CLayer* layer = FindLayer(layerName); m_brush.m_dwMaskLayerId = layer ? layer->GetCurrentLayerId() : CTextureBrush::sInvalidMaskId; RefreshUI(); } boost::python::tuple CTerrainTexturePainter::PyGetLayerBrushColor(const char *layerName) { CLayer* layer = FindLayer(layerName); if (layer) { ColorF color = layer->GetLayerFilterColor(); return boost::python::make_tuple(color.r, color.g, color.b); } return boost::python::make_tuple(0.0f, 0.0f, 0.0f); } void CTerrainTexturePainter::PySetLayerBrushColor(const char *layerName, float red, float green, float blue) { CLayer* layer = FindLayer(layerName); if (layer) { layer->SetLayerFilterColor(ColorF(red, green, blue)); } RefreshUI(); } float CTerrainTexturePainter::PyGetLayerBrushColorBrightness(const char *layerName) { CLayer* layer = FindLayer(layerName); return layer ? layer->GetLayerBrightness() : 0.0f; } void CTerrainTexturePainter::PySetLayerBrushColorBrightness(const char *layerName, float colorBrightness) { CLayer* layer = FindLayer(layerName); if (layer) { layer->SetLayerBrightness(colorBrightness); } RefreshUI(); } void CTerrainTexturePainter::PyPaintLayer(const char *layerName, float centerX, float centerY, float centerZ, bool floodFill) { CLayer *brushLayer = nullptr; IEditor *editor = GetIEditor(); AZ_Assert(editor, "Editor instance doesn't exist!"); if (!editor) { return; } CTerrainManager *terrainManager = editor->GetTerrainManager(); AZ_Assert(terrainManager, "Terrain Manager instance doesn't exist!"); if (!terrainManager) { return; } // Select the given layer, deselect the rest. If more than one layer has the same name, // the first one will be selected. for (int i = 0; i < terrainManager->GetLayerCount(); i++) { CLayer *layer = terrainManager->GetLayer(i); if ((!brushLayer) && (QString::compare(layer->GetLayerName(), layerName) == 0)) { layer->SetSelected(true); brushLayer = layer; } else { layer->SetSelected(false); } } if (!brushLayer) { return; } Command_Activate(); RefreshUI(); CEditTool* editTool = editor->GetEditTool(); if (editTool && qobject_cast<CTerrainTexturePainter*>(editTool)) { CTerrainTexturePainter* paintTool = reinterpret_cast<CTerrainTexturePainter*>(editTool); paintTool->PaintLayer(brushLayer, Vec3(centerX, centerY, centerZ), floodFill); editor->GetDocument()->SetModifiedFlag(TRUE); editor->SetModifiedModule(eModifiedTerrain); editor->UpdateViews(eUpdateHeightmap); } } CLayer* CTerrainTexturePainter::FindLayer(const char *layerName) { IEditor *editor = GetIEditor(); AZ_Assert(editor, "Editor instance doesn't exist!"); if (editor) { AZ_Assert(editor->GetTerrainManager(), "Terrain Mananger doesn't exist!"); if (editor->GetTerrainManager()) { return editor->GetTerrainManager()->FindLayer(layerName); } } return nullptr; } void CTerrainTexturePainter::RefreshUI() { if (s_toolPanel) { s_toolPanel->SetBrush(m_brush); IEditor *editor = GetIEditor(); AZ_Assert(editor, "Editor instance doesn't exist!"); if (editor) { editor->Notify(eNotify_OnInvalidateControls); } } } REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetBrushRadius, terrain, get_layer_painter_brush_radius, "Get the terrain layer painter brush radius.", "terrain.get_layer_painter_brush_radius()"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetBrushRadius, terrain, set_layer_painter_brush_radius, "Set the terrain layer painter brush radius.", "terrain.set_layer_painter_brush_radius(float radius)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetBrushColorHardness, terrain, get_layer_painter_brush_color_opacity, "Get the terrain layer painter brush color opacity.", "terrain.get_layer_painter_brush_color_opacity()"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetBrushColorHardness, terrain, set_layer_painter_brush_color_opacity, "Set the terrain layer painter brush color opacity.", "terrain.set_layer_painter_brush_color_opacity(float opacity)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetBrushDetailHardness, terrain, get_layer_painter_brush_detail_intensity, "Get the terrain layer painter brush detail intensity.", "terrain.get_layer_painter_brush_detail_intensity()"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetBrushDetailHardness, terrain, set_layer_painter_brush_detail_intensity, "Set the terrain layer painter brush detail intensity.", "terrain.set_layer_painter_brush_detail_intensity(float intensity)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetBrushMaskByLayerSettings, terrain, get_layer_painter_brush_mask_by_layer_settings, "Get the terrain layer painter brush setting for masking by layer settings (altitude, slope).", "terrain.get_layer_painter_brush_mask_by_layer_settings()"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetBrushMaskByLayerSettings, terrain, set_layer_painter_brush_mask_by_layer_settings, "Set the terrain layer painter brush setting for masking by layer settings (altitude, slope).", "terrain.set_layer_painter_brush_mask_by_layer_settings(bool enable)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetBrushMaskLayer, terrain, get_layer_painter_brush_mask_layer_name, "Get the terrain layer painter brush 'mask by layer' layer name.", "terrain.get_layer_painter_brush_mask_layer_name()"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetBrushMaskLayer, terrain, set_layer_painter_brush_mask_layer_name, "Set the terrain layer painter brush 'mask by layer' layer name.", "terrain.set_layer_painter_brush_mask_layer_name(string layer)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetLayerBrushColor, terrain, get_layer_brush_color, "Get the specific terrain layer's brush color.", "terrain.get_layer_brush_color(string layer)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetLayerBrushColor, terrain, set_layer_brush_color, "Set the specific terrain layer's brush color.", "terrain.set_layer_brush_color(string layer, float red, float green, float blue)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyGetLayerBrushColorBrightness, terrain, get_layer_brush_color_brightness, "Get the specific terrain layer's brush color brightness setting.", "terrain.get_layer_brush_color_brightness(string layer)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PySetLayerBrushColorBrightness, terrain, set_layer_brush_color_brightness, "Set the specific terrain layer's brush color brightness setting.", "terrain.set_layer_brush_color_brightness(string layer, float brightness)"); REGISTER_PYTHON_COMMAND_WITH_EXAMPLE(CTerrainTexturePainter::PyPaintLayer, terrain, paint_layer, "Paint the terrain using the brush settings from the given layer and the terrain layer painter.", "terrain.paint_layer(string layer, float center_x, float center_y, float center_z, bool flood_fill)"); #include <TerrainTexturePainter.moc>
34.40087
197
0.56945
[ "object", "vector", "3d" ]
e78f4fa25cd7757ab1bbffe941e98ab76c97191f
11,792
cpp
C++
sample/api_physics_effects/6_joint/main.cpp
erwincoumans/test2
cb78f36ae4002d79f21d21c759d07e2e23aabf15
[ "BSD-3-Clause" ]
5
2017-10-08T16:06:35.000Z
2020-10-08T23:30:34.000Z
sample/api_physics_effects/6_joint/main.cpp
erwincoumans/test2
cb78f36ae4002d79f21d21c759d07e2e23aabf15
[ "BSD-3-Clause" ]
null
null
null
sample/api_physics_effects/6_joint/main.cpp
erwincoumans/test2
cb78f36ae4002d79f21d21c759d07e2e23aabf15
[ "BSD-3-Clause" ]
null
null
null
/* Physics Effects Copyright(C) 2010 Sony Computer Entertainment Inc. All rights reserved. Physics Effects is open software; you can redistribute it and/or modify it under the terms of the BSD License. Physics Effects 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 BSD License for more details. A copy of the BSD License is distributed with Physics Effects under the filename: physics_effects_license.txt */ #include "../common/common.h" #include "../common/ctrl_func.h" #include "../common/render_func.h" #include "../common/perf_func.h" #include "physics_func.h" #ifdef _WIN32 #include <gl/gl.h> #include <gl/glu.h> #endif // ARA begin insert new code #ifdef __ANDROID__ #include <EGL/egl.h> #include <GLES/gl.h> #endif // ARA end #define SAMPLE_NAME "api_physics_effects/6_joint" //#define ENABLE_DEBUG_DRAW #ifdef ENABLE_DEBUG_DRAW #define ENABLE_DEBUG_DRAW_CONTACT #define ENABLE_DEBUG_DRAW_AABB #define ENABLE_DEBUG_DRAW_ISLAND #endif static bool s_isRunning = true; int sceneId = 0; bool simulating = false; void render(void) { render_begin(); const PfxVector3 colorWhite(1.0f); const PfxVector3 colorGray(0.7f); for(int i=0;i<physics_get_num_rigidbodies();i++) { const PfxRigidState &state = physics_get_state(i); const PfxCollidable &coll = physics_get_collidable(i); PfxVector3 color = state.isAsleep()?colorGray:colorWhite; PfxTransform3 rbT(state.getOrientation(), state.getPosition()); PfxShapeIterator itrShape(coll); for(int j=0;j<coll.getNumShapes();j++,++itrShape) { const PfxShape &shape = *itrShape; PfxTransform3 offsetT = shape.getOffsetTransform(); PfxTransform3 worldT = rbT * offsetT; switch(shape.getType()) { case kPfxShapeSphere: render_sphere( worldT, color, PfxFloatInVec(shape.getSphere().m_radius)); break; case kPfxShapeBox: render_box( worldT, color, shape.getBox().m_half); break; case kPfxShapeCapsule: render_capsule( worldT, color, PfxFloatInVec(shape.getCapsule().m_radius), PfxFloatInVec(shape.getCapsule().m_halfLen)); break; case kPfxShapeCylinder: render_cylinder( worldT, color, PfxFloatInVec(shape.getCylinder().m_radius), PfxFloatInVec(shape.getCylinder().m_halfLen)); break; default: break; } } } render_debug_begin(); #ifdef ENABLE_DEBUG_DRAW_CONTACT for(int i=0;i<physics_get_num_contacts();i++) { const PfxContactManifold &contact = physics_get_contact(i); const PfxRigidState &stateA = physics_get_state(contact.getRigidBodyIdA()); const PfxRigidState &stateB = physics_get_state(contact.getRigidBodyIdB()); for(int j=0;j<contact.getNumContacts();j++) { const PfxContactPoint &cp = contact.getContactPoint(j); PfxVector3 pA = stateA.getPosition()+rotate(stateA.getOrientation(),pfxReadVector3(cp.m_localPointA)); render_debug_point(pA,PfxVector3(0,0,1)); } } #endif #ifdef ENABLE_DEBUG_DRAW_AABB for(int i=0;i<physics_get_num_rigidbodies();i++) { const PfxRigidState &state = physics_get_state(i); const PfxCollidable &coll = physics_get_collidable(i); PfxVector3 center = state.getPosition() + coll.getCenter(); PfxVector3 half = absPerElem(PfxMatrix3(state.getOrientation())) * coll.getHalf(); render_debug_box(center,half,PfxVector3(1,0,0)); } #endif #ifdef ENABLE_DEBUG_DRAW_ISLAND const PfxIsland *island = physics_get_islands(); if(island) { for(PfxUInt32 i=0;i<pfxGetNumIslands(island);i++) { PfxIslandUnit *islandUnit = pfxGetFirstUnitInIsland(island,i); PfxVector3 aabbMin(SCE_PFX_FLT_MAX); PfxVector3 aabbMax(-SCE_PFX_FLT_MAX); for(;islandUnit!=NULL;islandUnit=pfxGetNextUnitInIsland(islandUnit)) { const PfxRigidState &state = physics_get_state(pfxGetUnitId(islandUnit)); const PfxCollidable &coll = physics_get_collidable(pfxGetUnitId(islandUnit)); PfxVector3 center = state.getPosition() + coll.getCenter(); PfxVector3 half = absPerElem(PfxMatrix3(state.getOrientation())) * coll.getHalf(); aabbMin = minPerElem(aabbMin,center-half); aabbMax = maxPerElem(aabbMax,center+half); } render_debug_box((aabbMax+aabbMin)*0.5f,(aabbMax-aabbMin)*0.5f,PfxVector3(0,1,0)); } } #endif render_debug_end(); render_end(); } int init(void) { perf_init(); ctrl_init(); render_init(); physics_init(); float angX,angY,r; render_get_view_angle(angX,angY,r); r *= 0.5f; render_set_view_angle(angX,angY,r); return 0; } static int shutdown(void) { ctrl_release(); render_release(); physics_release(); perf_release(); return 0; } void update(void) { float angX,angY,r; render_get_view_angle(angX,angY,r); ctrl_update(); if(ctrl_button_pressed(BTN_UP)) { angX -= 0.05f; if(angX < -1.4f) angX = -1.4f; if(angX > -0.01f) angX = -0.01f; } if(ctrl_button_pressed(BTN_DOWN)) { angX += 0.05f; if(angX < -1.4f) angX = -1.4f; if(angX > -0.01f) angX = -0.01f; } if(ctrl_button_pressed(BTN_LEFT)) { angY -= 0.05f; } if(ctrl_button_pressed(BTN_RIGHT)) { angY += 0.05f; } if(ctrl_button_pressed(BTN_ZOOM_OUT)) { r *= 1.1f; if(r > 500.0f) r = 500.0f; } if(ctrl_button_pressed(BTN_ZOOM_IN)) { r *= 0.9f; if(r < 1.0f) r = 1.0f; } if(ctrl_button_pressed(BTN_SCENE_RESET) == BTN_STAT_DOWN) { physics_create_scene(sceneId); } if(ctrl_button_pressed(BTN_SCENE_NEXT) == BTN_STAT_DOWN) { physics_create_scene(++sceneId); } if(ctrl_button_pressed(BTN_SIMULATION) == BTN_STAT_DOWN) { simulating = !simulating; } if(ctrl_button_pressed(BTN_STEP) == BTN_STAT_DOWN) { simulating = true; } else if(ctrl_button_pressed(BTN_STEP) == BTN_STAT_UP || ctrl_button_pressed(BTN_STEP) == BTN_STAT_KEEP) { simulating = false; } int w,h; render_get_screent_size(w,h); ctrl_set_screen_size(w,h); static PfxVector3 pickPos(0.0f); if(ctrl_button_pressed(BTN_PICK) == BTN_STAT_DOWN) { int sx,sy; ctrl_get_cursor_position(sx,sy); PfxVector3 wp1((float)sx,(float)sy,0.0f); PfxVector3 wp2((float)sx,(float)sy,1.0f); wp1 = render_get_world_position(wp1); wp2 = render_get_world_position(wp2); pickPos = physics_pick_start(wp1,wp2); } else if(ctrl_button_pressed(BTN_PICK) == BTN_STAT_KEEP) { int sx,sy; ctrl_get_cursor_position(sx,sy); PfxVector3 sp = render_get_screen_position(pickPos); PfxVector3 wp((float)sx,(float)sy,sp[2]); wp = render_get_world_position(wp); physics_pick_update(wp); } else if(ctrl_button_pressed(BTN_PICK) == BTN_STAT_UP) { physics_pick_end(); } render_set_view_angle(angX,angY,r); } #ifndef _WIN32 // ARA begin insert new code #ifdef __ANDROID__ /////////////////////////////////////////////////////////////////////////////// // sceneChange // /// This function is used to change the physics scene on Android devices /////////////////////////////////////////////////////////////////////////////// void sceneChange() { physics_create_scene(sceneId++); } #else // __ANDROID__ // ARA end /////////////////////////////////////////////////////////////////////////////// // Main int main(void) { init(); physics_create_scene(sceneId); printf("## %s: INIT SUCCEEDED ##\n", SAMPLE_NAME); while (s_isRunning) { update(); if(simulating) physics_simulate(); render(); perf_sync(); } shutdown(); printf("## %s: FINISHED ##\n", SAMPLE_NAME); return 0; } // ARA begin insert new code #endif // __ANDROID__ // ARA end #else // _WIN32 /////////////////////////////////////////////////////////////////////////////// // WinMain extern HDC hDC; extern HGLRC hRC; HWND hWnd; HINSTANCE hInstance; void releaseWindow() { if(hRC) { wglMakeCurrent(0,0); wglDeleteContext(hRC); } if(hDC) ReleaseDC(hWnd,hDC); if(hWnd) DestroyWindow(hWnd); UnregisterClass(SAMPLE_NAME,hInstance); } LRESULT CALLBACK WndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam) { switch(uMsg) { case WM_SYSCOMMAND: { switch (wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; } case WM_CLOSE: PostQuitMessage(0); return 0; case WM_SIZE: render_resize(LOWORD(lParam),HIWORD(lParam)); return 0; } return DefWindowProc(hWnd,uMsg,wParam,lParam); } bool createWindow(char* title, int width, int height) { WNDCLASS wc; RECT rect; rect.left=0; rect.right=width; rect.top=0; rect.bottom=height; hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = SAMPLE_NAME; if(!RegisterClass(&wc)) { return false; } AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); if(!(hWnd=CreateWindowEx(WS_EX_APPWINDOW|WS_EX_WINDOWEDGE,SAMPLE_NAME,title, WS_OVERLAPPEDWINDOW|WS_CLIPSIBLINGS|WS_CLIPCHILDREN, 0,0,rect.right-rect.left,rect.bottom-rect.top, NULL,NULL,hInstance,NULL))) { releaseWindow(); return false; } static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; if(!(hDC=GetDC(hWnd))) { releaseWindow(); OutputDebugString(""); return FALSE; } int pixelformat; if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 ){ OutputDebugString("ChoosePixelFormat Failed...."); return FALSE; } if (SetPixelFormat(hDC, pixelformat, &pfd) == FALSE){ OutputDebugString("SetPixelFormat Failed...."); return FALSE; } if (!(hRC=wglCreateContext(hDC))){ OutputDebugString("Creating HGLRC Failed...."); return FALSE; } // Set Vsync //BOOL (WINAPI *wglSwapIntervalEXT)(int) = NULL; //if(strstr((char*)glGetString( GL_EXTENSIONS ),"WGL_EXT_swap_control")== 0) { //} //else { //wglSwapIntervalEXT = (BOOL (WINAPI*)(int))wglGetProcAddress("wglSwapIntervalEXT"); //if(wglSwapIntervalEXT) wglSwapIntervalEXT(1); //} wglMakeCurrent(hDC,hRC); ShowWindow(hWnd,SW_SHOW); SetForegroundWindow(hWnd); SetFocus(hWnd); render_resize(width, height); glClearColor(0.0f,0.0f,0.0f,0.0f); glClearDepth(1.0f); return TRUE; } int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { if(!createWindow(SAMPLE_NAME,DISPLAY_WIDTH,DISPLAY_HEIGHT)) { MessageBox(NULL,"Can't create gl window.","ERROR",MB_OK|MB_ICONEXCLAMATION); return 0; } init(); physics_create_scene(sceneId); SCE_PFX_PRINTF("## %s: INIT SUCCEEDED ##\n", SAMPLE_NAME); MSG msg; while(s_isRunning) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message==WM_QUIT) { s_isRunning = false; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { update(); if(simulating) physics_simulate(); render(); perf_sync(); } } shutdown(); SCE_PFX_PRINTF("## %s: FINISHED ##\n", SAMPLE_NAME); releaseWindow(); return (msg.wParam); } #endif
22.941634
107
0.655614
[ "render", "shape" ]
e799a6ce7c9cb9947e2cf64cb35afa523698f2ba
5,533
cpp
C++
opencl/source/built_ins/vme_builtin.cpp
Panquesito7/compute-runtime
3357b8b916885a336174ab0e7bbfc7652be4fb88
[ "Intel", "MIT" ]
778
2017-09-29T20:02:43.000Z
2022-03-31T15:35:28.000Z
opencl/source/built_ins/vme_builtin.cpp
Panquesito7/compute-runtime
3357b8b916885a336174ab0e7bbfc7652be4fb88
[ "Intel", "MIT" ]
478
2018-01-26T16:06:45.000Z
2022-03-30T10:19:10.000Z
opencl/source/built_ins/vme_builtin.cpp
Panquesito7/compute-runtime
3357b8b916885a336174ab0e7bbfc7652be4fb88
[ "Intel", "MIT" ]
215
2018-01-30T08:39:32.000Z
2022-03-29T11:08:51.000Z
/* * Copyright (C) 2020-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/source/built_ins/vme_builtin.h" #include "shared/source/built_ins/built_ins.h" #include "shared/source/device/device.h" #include "opencl/source/built_ins/built_in_ops_vme.h" #include "opencl/source/built_ins/builtins_dispatch_builder.h" #include "opencl/source/built_ins/populate_built_ins.inl" #include "opencl/source/built_ins/vme_dispatch_builder.h" #include "opencl/source/execution_environment/cl_execution_environment.h" #include "opencl/source/program/program.h" namespace NEO { static const char *blockMotionEstimateIntelSrc = { #include "kernels/vme_block_motion_estimate_intel_frontend.builtin_kernel" }; static const char *blockAdvancedMotionEstimateCheckIntelSrc = { #include "kernels/vme_block_advanced_motion_estimate_check_intel_frontend.builtin_kernel" }; static const char *blockAdvancedMotionEstimateBidirectionalCheckIntelSrc = { #include "kernels/vme_block_advanced_motion_estimate_bidirectional_check_intel_frontend.builtin_kernel" }; static const std::tuple<const char *, const char *> mediaBuiltIns[] = { {"block_motion_estimate_intel", blockMotionEstimateIntelSrc}, {"block_advanced_motion_estimate_check_intel", blockAdvancedMotionEstimateCheckIntelSrc}, {"block_advanced_motion_estimate_bidirectional_check_intel", blockAdvancedMotionEstimateBidirectionalCheckIntelSrc}}; // Unlike other built-ins media kernels are not stored in BuiltIns object. // Pointer to program with built in kernels is returned to the user through API // call and user is responsible for releasing it by calling clReleaseProgram. Program *Vme::createBuiltInProgram( Context &context, const ClDeviceVector &deviceVector, const char *kernelNames, int &errcodeRet) { std::string programSourceStr = ""; std::istringstream ss(kernelNames); std::string currentKernelName; while (std::getline(ss, currentKernelName, ';')) { bool found = false; for (auto &builtInTuple : mediaBuiltIns) { if (currentKernelName == std::get<0>(builtInTuple)) { programSourceStr += std::get<1>(builtInTuple); found = true; break; } } if (!found) { errcodeRet = CL_INVALID_VALUE; return nullptr; } } if (programSourceStr.empty() == true) { errcodeRet = CL_INVALID_VALUE; return nullptr; } Program *pBuiltInProgram = nullptr; pBuiltInProgram = Program::createBuiltInFromSource(programSourceStr.c_str(), &context, deviceVector, nullptr); auto &device = *deviceVector[0]; if (pBuiltInProgram) { std::unordered_map<std::string, BuiltinDispatchInfoBuilder *> builtinsBuilders; builtinsBuilders["block_motion_estimate_intel"] = &Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockMotionEstimateIntel, device); builtinsBuilders["block_advanced_motion_estimate_check_intel"] = &Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockAdvancedMotionEstimateCheckIntel, device); builtinsBuilders["block_advanced_motion_estimate_bidirectional_check_intel"] = &Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::VmeBlockAdvancedMotionEstimateBidirectionalCheckIntel, device); errcodeRet = pBuiltInProgram->build(deviceVector, mediaKernelsBuildOptions, true, builtinsBuilders); } else { errcodeRet = CL_INVALID_VALUE; } return pBuiltInProgram; } const char *getAdditionalBuiltinAsString(EBuiltInOps::Type builtin) { switch (builtin) { default: return nullptr; case EBuiltInOps::VmeBlockMotionEstimateIntel: return "vme_block_motion_estimate_intel.builtin_kernel"; case EBuiltInOps::VmeBlockAdvancedMotionEstimateCheckIntel: return "vme_block_advanced_motion_estimate_check_intel.builtin_kernel"; case EBuiltInOps::VmeBlockAdvancedMotionEstimateBidirectionalCheckIntel: return "vme_block_advanced_motion_estimate_bidirectional_check_intel"; } } BuiltinDispatchInfoBuilder &Vme::getBuiltinDispatchInfoBuilder(EBuiltInOps::Type operation, ClDevice &device) { auto &builtins = *device.getDevice().getBuiltIns(); uint32_t operationId = static_cast<uint32_t>(operation); auto clExecutionEnvironment = static_cast<ClExecutionEnvironment *>(device.getExecutionEnvironment()); auto &operationBuilder = clExecutionEnvironment->peekBuilders(device.getRootDeviceIndex())[operationId]; switch (operation) { default: return BuiltInDispatchBuilderOp::getBuiltinDispatchInfoBuilder(operation, device); case EBuiltInOps::VmeBlockMotionEstimateIntel: std::call_once(operationBuilder.second, [&] { operationBuilder.first = std::make_unique<BuiltInOp<EBuiltInOps::VmeBlockMotionEstimateIntel>>(builtins, device); }); break; case EBuiltInOps::VmeBlockAdvancedMotionEstimateCheckIntel: std::call_once(operationBuilder.second, [&] { operationBuilder.first = std::make_unique<BuiltInOp<EBuiltInOps::VmeBlockAdvancedMotionEstimateCheckIntel>>(builtins, device); }); break; case EBuiltInOps::VmeBlockAdvancedMotionEstimateBidirectionalCheckIntel: std::call_once(operationBuilder.second, [&] { operationBuilder.first = std::make_unique<BuiltInOp<EBuiltInOps::VmeBlockAdvancedMotionEstimateBidirectionalCheckIntel>>(builtins, device); }); break; } return *operationBuilder.first; } } // namespace NEO
44.264
197
0.756009
[ "object" ]
e79af2bc8f7f2d57267e2148f44a7f6712826724
1,836
cpp
C++
Ch 3 Paradigms/Dynamic Programming/Bottom Up/uva-481-LIS-O(nlgk).cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
Ch 3 Paradigms/Dynamic Programming/Bottom Up/uva-481-LIS-O(nlgk).cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
Ch 3 Paradigms/Dynamic Programming/Bottom Up/uva-481-LIS-O(nlgk).cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
//UVa - 481 - What Goes Up //Longest Increasing Subsequence O(nlgk), k=LISlen, n=i/p len //Bottom up DP(using previous info while filling) + Greedy insertion #include <iostream> #include <algorithm> #include <vector> using namespace std; using vi = vector<int>; vi arr; //Input Array vi parent; //Parent indx of LIS elements in arr[] void backtrack( int id ) //Recurse & print LIS starting @last { if( parent[id] != -1 ) backtrack( parent[id] ); printf( "%d\n", arr[id] ); } int main() { constexpr int INF{ 2147483647 }; //Largest possible int int num; while( scanf("%d", &num) != EOF ) arr.push_back(num); arr.push_back(INF); //Ensure LIS always ends with INF int n{ (int)arr.size() }; //Length of input parent.assign(n, -1); //Parent indx of LIS elements in arr[] vi lis(n); //Array to store LIS vi lisId(n); //Index of LIS elements in arr[] int k{ 0 }; //Length of LIS, initially 0 int pos{ 0 }; //Where in LIS to insert new element? int last{ 0 }; //Hold last element of latest LIS in i/p for( int id{0}; id < n; ++id ) //Loop elements in O(n) { //Find position of element in current LIS in O(lgk) pos = lower_bound( lis.begin(), lis.begin() + k, arr[id] ) - lis.begin(); lis[pos] = arr[id]; //Greedily overwrite that lisId[pos] = id; //Also store its array index (pos == 0) ? parent[id] = -1 //1st element : parent[id] = lisId[pos - 1]; //Parent's index if( pos == k ) //Length has increased by 1 { ++k; last = id; //Index of last element in latest LIS } } //Last element is INF so print till last but 1 element of LIS printf( "%d\n-\n", k - 1 ); backtrack(parent[last]); return 0; }
29.142857
69
0.574619
[ "vector" ]
e79cf6939742c8436796b8973a69e5150205534d
7,530
cpp
C++
2020/day24/p2/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2020/day24/p2/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2020/day24/p2/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
#include <lib/file_util.hpp> #include <chain/chain.hpp> #include <lib/containers.hpp> #include <iostream> #include <iomanip> #include <vector> #include <string> #include <memory> #include <map> using vec3 = containers::vec3<int64_t>; enum class color_t { white, black }; auto operator<<(std::ostream& os, const color_t& c) -> std::ostream& { if(c == color_t::white) { os << "white"; } else { os << "black"; } return os; } enum class direction_t : size_t { east = 0, southeast = 1, southwest = 2, west = 3, northwest = 4, northeast = 5 }; auto to_string(const direction_t& d) -> std::string { switch(d) { case direction_t::east: return "e"; case direction_t::southeast: return "se"; case direction_t::southwest: return "sw"; case direction_t::west: return "w"; case direction_t::northwest: return "nw"; case direction_t::northeast: return "ne"; } throw std::runtime_error{"invalid direction"}; } auto operator<<(std::ostream& os, const direction_t d) -> std::ostream& { os << to_string(d); return os; } auto cube_directions(const direction_t& d) -> vec3 { switch(d) { case direction_t::east: return vec3{1, -1, 0}; case direction_t::southeast: return vec3{0, -1, 1}; case direction_t::southwest: return vec3{-1, 0, 1}; case direction_t::west: return vec3{-1, 1, 0}; case direction_t::northwest: return vec3{0, 1, -1}; case direction_t::northeast: return vec3{1, 0, -1}; } throw std::runtime_error{"invalid direction"}; } struct tile_t { color_t color{color_t::white}; }; auto parse_next(std::string_view& data) -> direction_t { if(data[0] == 'e') { data.remove_prefix(1); return direction_t::east; } else if(data[0] == 'w') { data.remove_prefix(1); return direction_t::west; } else { if(data[0] == 's') { if(data[1] == 'e') { data.remove_prefix(2); return direction_t::southeast; } else if(data[1] == 'w') { data.remove_prefix(2); return direction_t::southwest; } else { throw std::runtime_error{std::string{"invalid next direction from 's' ="} + std::string{data}}; } } else if(data[0] == 'n') { if(data[1] == 'e') { data.remove_prefix(2); return direction_t::northeast; } else if(data[1] == 'w') { data.remove_prefix(2); return direction_t::northwest; } else { throw std::runtime_error{std::string{"invalid next direction from 'n' ="} + std::string{data}}; } } } throw std::runtime_error{std::string{"invalid next direction = "} + std::string{data}}; } using hexgrid = std::map<int64_t, std::map<int64_t, std::map<int64_t, tile_t>>>; static std::array<direction_t, 6> directions{ direction_t::east, direction_t::southeast, direction_t::southwest, direction_t::west, direction_t::northwest, direction_t::northeast }; auto next_day(const hexgrid& input, bool flip_tiles = true) -> hexgrid { auto output = input; for(const auto& [x_idx, x_tiles] : input) { for(const auto& [y_idx, y_tiles] : x_tiles) { for(const auto& [z_idx, i_tile] : y_tiles) { uint64_t bcount{0}; vec3 pos{x_idx, y_idx, z_idx}; for(const auto& d : directions) { auto n_pos = pos + cube_directions(d); const tile_t* i_n_tile{nullptr}; auto x_iter = input.find(n_pos.x); if(x_iter != input.end()) { auto y_iter = x_iter->second.find(n_pos.y); if(y_iter != x_iter->second.end()) { auto z_iter = y_iter->second.find(n_pos.z); if(z_iter != y_iter->second.end()) { i_n_tile = &z_iter->second; } } } if(i_n_tile != nullptr) { if(i_n_tile->color == color_t::black) { bcount++; } } // Grow outwards on the output hexgrid. output[n_pos.x][n_pos.y][n_pos.z]; } if(flip_tiles) { auto& o_tile = output[x_idx][y_idx][z_idx]; if(i_tile.color == color_t::white) { // White tiles with exactly 2 black tiles flips to black. if(bcount == 2) { o_tile.color = color_t::black; } } else // color_t::black { // Black tiles with 'zero' OR more than '2' black tiles flips to white if(bcount == 0 || bcount > 2) { o_tile.color = color_t::white; } } } } } } return output; } auto grid_count_black_tiles(const hexgrid& input) -> size_t { size_t bcount{0}; for(const auto& [x_idx, x_tiles] : input) { for(const auto& [y_idx, y_tiles] : x_tiles) { for(const auto& [z_idx, tile] : y_tiles) { if(tile.color == color_t::black) { ++bcount; } } } } return bcount; } int main(int argc, char* argv[]) { std::vector<std::string> args{argv, argv + argc}; if(args.size() != 2) { std::cout << args[0] << " <input_file>" << std::endl; return 0; } auto contents = file::read(args[1]); std::map<int64_t, std::map<int64_t, std::map<int64_t, tile_t>>> tiles{}; for(auto& directions : chain::str::split(contents, '\n')) { // Every set of directions starts at the center tile. vec3 pos{0, 0, 0}; while(!directions.empty()) { auto d = parse_next(directions); std::cout << d; pos += cube_directions(d); } auto& tile = tiles[pos.x][pos.y][pos.z]; tile.color = (tile.color == color_t::white) ? color_t::black : color_t::white; } std::cout << "\nDay 0:" << grid_count_black_tiles(tiles) << "\n"; // The grid needs to be expanded so the first day can properly count, after that its always // "big enough" around all the tiles to properly count. This call will just make the hexgrid // larger but it won't flip or change any tiles yet. tiles = next_day(tiles, false); for(size_t i = 1; i <= 100; ++i) { tiles = next_day(tiles); std::cout << "Day " << i << ": " << grid_count_black_tiles(tiles) << "\n"; } return 0; }
26.607774
111
0.473174
[ "vector" ]
e79fd66b8c6bfcf16840522073431b58ad21ccb6
4,671
cpp
C++
source/gfx/gfx_utils.cpp
ranoke/gl_renderer
d29eb50f2343668db4e4b4243686e3e27d23a244
[ "MIT" ]
null
null
null
source/gfx/gfx_utils.cpp
ranoke/gl_renderer
d29eb50f2343668db4e4b4243686e3e27d23a244
[ "MIT" ]
null
null
null
source/gfx/gfx_utils.cpp
ranoke/gl_renderer
d29eb50f2343668db4e4b4243686e3e27d23a244
[ "MIT" ]
null
null
null
#include "gfx_utils.h" #include "base/logger.h" #include <iostream> #include <string> namespace gfx_utils { std::string get_filename_from_path(const std::string path) { auto last_slash = path.find_last_of("/\\"); last_slash = last_slash == std::string::npos ? 0 : last_slash + 1; auto last_dot = path.rfind('.'); last_dot = last_dot == std::string::npos ? path.size() - last_slash : last_dot - last_slash; return path.substr(last_slash, last_dot); } template <class T> void library_t<T>::add(const std::string &path) { assert(false && "i dunno what to do with a path"); // do i create a parser for a shader // to make them in one file // so it would be easier to deal with them // or do i assume that .gls for example means to load // everything that named bedore the .gls ??? } //template<class T> //void library_t<T>::add(const std::string& name, library_t<T>::type obj) //{ // assert(!exists(name) && "obj with this name already exists"); // data_[name] = obj; //} template <class T> void library_t<T>::add(const std::string &name, const library_t<T>::type &obj) { assert(!exists(name) && "obj with this name already exists"); data_[name] = obj; } template <class T> void library_t<T>::add(const std::string &name, library_t<T>::type &&obj) { assert(!exists(name) && "obj with this name already exists"); data_[name] = obj; } template <class T> const T &library_t<T>::get(const std::string &name) { return data_[name]; } template <class T> bool library_t<T>::exists(const std::string &name) { return data_.find(name) != data_.end(); } gfx::texture_t texture_load(const std::string &path) { return texture_load(path.c_str()); } gfx::texture_t texture_load_cubemap(const std::vector<const char *> &path) { gfx::texture_desc_t desc = {0, 0, 0, gfx::gl_texture_type::texture_cubemap}; i32 w, h, c; desc.data_ = malloc(6 * sizeof(void *)); void **data = (void **)desc.data_; for (int i = 0; i < 6; i++) { data[i] = stbi_load(path[i], &w, &h, &c, 3); if (data[i] == NULL) { assert(false); gfx::texture_t t; return t; } } desc.width_ = w; desc.height_ = h; const gfx::texture_t t = gfx::texture_ctor(desc, false); for (int i = 0; i < 6; i++) { stbi_image_free(data[i]); } free(desc.data_); return t; } gfx::texture_t texture_load_hdri(const std::string &path) { gfx::texture_desc_t desc = {0, 0, 0, gfx::gl_texture_type::texture_2d, gfx::gl_type::gl_float, gfx::gl_format::rgb, gfx::gl_format::rgb_16f}; stbi_set_flip_vertically_on_load(true); i32 w, h, c; float *data = stbi_loadf(path.c_str(), &w, &h, &c, 0); desc.data_ = data; desc.width_ = w; desc.height_ = h; gfx::texture_t t; if (data) { t = gfx::texture_ctor(desc, false); stbi_image_free(data); } else { logger::warn("Failed to load hdri {0}", path); } stbi_set_flip_vertically_on_load(false); return t; } gfx::texture_t texture_load(const char *path) { int w, h, c; void *data = stbi_load(path, &w, &h, &c, 0); if (data == NULL) { logger::warn("Failed to load texture: {0}", path); return {}; } gfx::texture_desc_t desc = { static_cast<u32>(w), static_cast<u32>(h), data, gfx::gl_texture_type::texture_2d, }; gfx::texture_t t = gfx::texture_ctor(desc, false); stbi_image_free(data); return t; } gfx::program_t program_load(const char *vertex_path, const char *fragment_path) { std::ifstream vertex_file(vertex_path); std::ifstream fragment_file(fragment_path); std::string vertex_src, fragment_src; { std::stringstream ss; std::string line; while (getline(vertex_file, line)) { ss << line << "\n"; } vertex_src = ss.str(); } { std::stringstream ss; std::string line; while (getline(fragment_file, line)) { ss << line << "\n"; } fragment_src = ss.str(); } gfx::program_t p = gfx::program_ctor({gfx::shader_ctor(vertex_src, GL_VERTEX_SHADER), gfx::shader_ctor(fragment_src, GL_FRAGMENT_SHADER)}); return p; } // template implementation for libraries template struct gfx_utils::library_t<gfx::program_t>; template struct gfx_utils::library_t<gfx::texture_t>; } // namespace gfx_utils
25.80663
96
0.589809
[ "vector" ]
e7a42a47b8421e9630bf0333d9c9da31545469be
5,553
cpp
C++
src/qt5gui/ExcitationSignalWidget.cpp
sigurdstorve/OpenBCSim
500025c1b63bc6ff083cbd649771d1b98e3f7314
[ "BSD-3-Clause" ]
17
2016-05-27T13:09:19.000Z
2022-03-21T07:08:47.000Z
src/qt5gui/ExcitationSignalWidget.cpp
rojsc/OpenBCSim
53773172974ad42fc3faceb7b36611573abf1c4c
[ "BSD-3-Clause" ]
63
2015-09-10T11:22:56.000Z
2021-05-21T14:52:39.000Z
src/qt5gui/ExcitationSignalWidget.cpp
rojsc/OpenBCSim
53773172974ad42fc3faceb7b36611573abf1c4c
[ "BSD-3-Clause" ]
15
2016-07-26T14:52:18.000Z
2022-01-02T15:52:28.000Z
/* Copyright (c) 2015, Sigurd Storve All rights reserved. Licensed under the BSD license. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ExcitationSignalWidget.hpp" #include <QDoubleSpinBox> #include <cmath> #include <vector> #include <algorithm> #include <tuple> #include <QVBoxLayout> #include <QGroupBox> #include <QFormLayout> #include <QPushButton> #include <QVector> #ifdef BCSIM_ENABLE_QWT #include <qwt_plot.h> #include <qwt_plot_curve.h> #endif #include "../utils/GaussPulse.hpp" ExcitationSignalWidget::ExcitationSignalWidget(QWidget* parent) : QWidget(parent) { auto main_layout = new QVBoxLayout; auto group_box = new QGroupBox("Gaussian pulse excitiation"); auto form_layout = new QFormLayout; #ifdef BCSIM_ENABLE_QWT m_plot_curve = new QwtPlotCurve("Excitation"); m_plot = new QwtPlot; m_plot->setFixedSize(150, 150); m_plot_curve->attach(m_plot); form_layout->addRow(m_plot); #endif m_sampling_freq_sb = new QDoubleSpinBox; m_sampling_freq_sb->setRange(1, 1000); m_sampling_freq_sb->setSingleStep(10); m_sampling_freq_sb->setValue(50); m_sampling_freq_sb->setSuffix("MHz"); connect(m_sampling_freq_sb, SIGNAL(valueChanged(double)), this, SLOT(onSomethingChanged())); m_center_freq_sb = new QDoubleSpinBox; m_center_freq_sb->setRange(0.0, 100); m_center_freq_sb->setSingleStep(0.1); m_center_freq_sb->setValue(2.5); m_center_freq_sb->setSuffix("MHz"); connect(m_center_freq_sb, SIGNAL(valueChanged(double)), this, SLOT(onSomethingChanged())); m_bandwidth_sb = new QDoubleSpinBox; m_bandwidth_sb->setRange(0.1, 150.0); m_bandwidth_sb->setSingleStep(1.0); m_bandwidth_sb->setValue(10.0); m_bandwidth_sb->setSuffix("%"); connect(m_bandwidth_sb, SIGNAL(valueChanged(double)), this, SLOT(onSomethingChanged())); form_layout->addRow("Sampling freq.", m_sampling_freq_sb); form_layout->addRow("Center freq.", m_center_freq_sb); form_layout->addRow("Bandwidth", m_bandwidth_sb); main_layout->addWidget(group_box); group_box->setLayout(form_layout); setLayout(main_layout); onSomethingChanged(); } void ExcitationSignalWidget::force_emit() { onSomethingChanged(); } bcsim::ExcitationSignal ExcitationSignalWidget::construct(std::vector<float>& /*out*/ excitation_times) const { // construct a new ExcitationSignal bcsim::ExcitationSignal new_excitation; // read values from GUI controls new_excitation.sampling_frequency = static_cast<float>(m_sampling_freq_sb->value()*1e6); auto center_frequency = static_cast<float>(m_center_freq_sb->value()*1e6); auto fractional_bandwidth = static_cast<float>(m_bandwidth_sb->value()*0.01); //std::vector<float> times; bcsim::MakeGaussianExcitation(center_frequency, fractional_bandwidth, new_excitation.sampling_frequency, excitation_times, new_excitation.samples, new_excitation.center_index); new_excitation.demod_freq = center_frequency; return new_excitation; } void ExcitationSignalWidget::onSomethingChanged() { std::vector<float> temp_times; auto new_excitation = construct(temp_times); #ifdef BCSIM_ENABLE_QWT auto num_samples = temp_times.size(); // convert to double for plotting std::vector<double> plot_times(num_samples); std::vector<double> plot_samples(num_samples); for (size_t i = 0; i < num_samples; i++) { plot_times[i] = static_cast<double>(temp_times[i]); plot_samples[i] = static_cast<double>(new_excitation.samples[i]); } m_plot_curve->setSamples(plot_times.data(), plot_samples.data(), static_cast<int>(num_samples)); const auto min_value = *std::min_element(plot_times.begin(), plot_times.end()); const auto max_value = *std::max_element(plot_times.begin(), plot_times.end()); m_plot->setAxisScale(QwtPlot::xBottom, min_value, max_value); m_plot->replot(); #endif emit valueChanged(new_excitation); }
40.23913
111
0.726994
[ "vector" ]
e7a5d14e74368f914e12a2d2ed4c0f6de041ab8b
123,918
cpp
C++
renderdoc/core/sparse_page_table.cpp
yanjifa/renderdoc
308456535f067df15be78de145440c170c2d8c00
[ "MIT" ]
1
2022-02-17T21:18:24.000Z
2022-02-17T21:18:24.000Z
renderdoc/core/sparse_page_table.cpp
superlee1/renderdoc
a51b20369f685b4e57ccd97fe203483c6d5c5d1f
[ "MIT" ]
null
null
null
renderdoc/core/sparse_page_table.cpp
superlee1/renderdoc
a51b20369f685b4e57ccd97fe203483c6d5c5d1f
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2021-2022 Baldur Karlsson * * 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 "sparse_page_table.h" #include "common/globalconfig.h" #include "serialise/serialiser.h" namespace Sparse { static uint32_t calcPageForTileCoord(const Coord &coord, const Coord &subresourcePageDim) { return (((coord.z * subresourcePageDim.y) + coord.y) * subresourcePageDim.x) + coord.x; } void PageRangeMapping::createPages(uint32_t numPages, uint32_t pageSize) { // don't do anything if the pages have already been populated if(!pages.empty()) return; // otherwise allocate them. If we have a single page mapping we can just duplicate and it's easy if(singlePageReused || singleMapping.memory == ResourceId()) { pages.fill(numPages, singleMapping); } else { // otherwise we need to allocate and increment pages.reserve(numPages); pages.clear(); for(uint32_t i = 0; i < numPages; i++) { pages.push_back(singleMapping); singleMapping.offset += pageSize; } } // reset the single mapping to be super clear singleMapping = {}; singlePageReused = false; } void PageTable::Initialise(uint64_t bufferByteSize, uint32_t pageByteSize) { m_PageByteSize = pageByteSize; // set just in case the calling code calls getMipTailByteOffsetForSubresource m_ArraySize = 1; m_MipCount = 1; m_TextureDim = {(uint32_t)bufferByteSize, 1, 1}; m_PageTexelSize = {pageByteSize, 1, 1}; // initialise mip tail with buffer properties m_MipTail.byteStride = 0; m_MipTail.byteOffset = 0; m_MipTail.firstMip = 0; m_MipTail.totalPackedByteSize = bufferByteSize; m_MipTail.mappings.resize(1); m_MipTail.mappings[0].singlePageReused = false; m_MipTail.mappings[0].singleMapping = {}; } void PageTable::Initialise(const Coord &overallTexelDim, uint32_t numMips, uint32_t numArraySlices, uint32_t pageByteSize, const Sparse::Coord &pageTexelDim, uint32_t firstTailMip, uint64_t mipTailOffset, uint64_t mipTailStride, uint64_t mipTailTotalPackedSize) { // sanitise inputs to be safe m_PageByteSize = RDCMAX(1U, pageByteSize); m_ArraySize = RDCMAX(1U, numArraySlices); m_MipCount = RDCMAX(1U, numMips); m_PageTexelSize.x = RDCMAX(1U, pageTexelDim.x); m_PageTexelSize.y = RDCMAX(1U, pageTexelDim.y); m_PageTexelSize.z = RDCMAX(1U, pageTexelDim.z); m_TextureDim.x = RDCMAX(1U, overallTexelDim.x); m_TextureDim.y = RDCMAX(1U, overallTexelDim.y); m_TextureDim.z = RDCMAX(1U, overallTexelDim.z); // initialise the subresources m_Subresources.resize(m_ArraySize * m_MipCount); // initialise mip tail if we have one if(firstTailMip < m_MipCount) { m_MipTail.byteStride = mipTailStride; m_MipTail.byteOffset = mipTailOffset; m_MipTail.firstMip = firstTailMip; m_MipTail.totalPackedByteSize = mipTailTotalPackedSize; if(m_MipTail.byteStride == 0) { m_MipTail.mappings.resize(1); m_MipTail.mappings[0].singlePageReused = false; m_MipTail.mappings[0].singleMapping = {}; } else { m_MipTail.mappings.resize(m_ArraySize); for(size_t i = 0; i < m_MipTail.mappings.size(); i++) { m_MipTail.mappings[i].singlePageReused = false; m_MipTail.mappings[i].singleMapping = {}; } } } else { m_MipTail.byteStride = 0; m_MipTail.byteOffset = 0; m_MipTail.firstMip = m_MipCount; m_MipTail.totalPackedByteSize = 0; } } uint64_t PageTable::setMipTailRange(uint64_t resourceByteOffset, ResourceId memory, uint64_t memoryByteOffset, uint64_t byteSize, bool useSinglePage) { // offsets should be page aligned RDCASSERT((memoryByteOffset % m_PageByteSize) == 0, memoryByteOffset, m_PageByteSize); RDCASSERT((resourceByteOffset % m_PageByteSize) == 0, resourceByteOffset, m_PageByteSize); // size should either be page aligned, or should be the end of the mip tail region (for buffers // that don't have to fill the whole thing) RDCASSERT((byteSize % m_PageByteSize) == 0 || (resourceByteOffset + byteSize == m_MipTail.totalPackedByteSize), resourceByteOffset, byteSize, m_PageByteSize, m_MipTail.totalPackedByteSize); RDCASSERT(m_MipTail.totalPackedByteSize > 0); // if we're setting to NULL, set the offset to 0 if(memory == ResourceId()) memoryByteOffset = 0; // rebase the byte offset from resource-relative to miptail-relative RDCASSERT(resourceByteOffset >= m_MipTail.byteOffset); resourceByteOffset -= m_MipTail.byteOffset; if(m_MipTail.mappings.empty()) { RDCERR("Attempting to set mip tail on image with no mip region"); return m_MipTail.byteOffset + m_MipTail.totalPackedByteSize; } // if we're setting the whole mip tail at once, store it as a single page mapping if(resourceByteOffset == 0 && byteSize == m_MipTail.totalPackedByteSize) { for(size_t i = 0; i < m_MipTail.mappings.size(); i++) { m_MipTail.mappings[i].pages.clear(); m_MipTail.mappings[i].singleMapping.memory = memory; m_MipTail.mappings[i].singleMapping.offset = memoryByteOffset; m_MipTail.mappings[i].singlePageReused = useSinglePage; // if we're not using a single page and we have multiple mip tails separated by a stride, // update the memory offset for each single mapping. This implies wasted memory in between so // I don't think apps will do this, but it may be legal so handle it here. if(!useSinglePage) memoryByteOffset += i * m_MipTail.byteStride; } // we consumed the whole mip tail by definition return m_MipTail.byteOffset + m_MipTail.totalPackedByteSize; } else if(m_MipTail.mappings.size() == 1) { // if we only have one miptail region, this is simple. Create pages as needed and update the // referenced pages PageRangeMapping &mapping = m_MipTail.mappings[0]; mapping.createPages( uint32_t((m_MipTail.totalPackedByteSize + m_PageByteSize - 1) / m_PageByteSize), m_PageByteSize); // iterate through each referenced resource page for(size_t page = size_t(resourceByteOffset / m_PageByteSize), endPage = size_t((resourceByteOffset + byteSize + m_PageByteSize - 1) / m_PageByteSize); page < mapping.pages.size() && page < endPage; page++) { mapping.pages[page].memory = memory; mapping.pages[page].offset = memoryByteOffset; // if we're not mapping all resource pages to a single memory page, advance the offset if(!useSinglePage && memory != ResourceId()) memoryByteOffset += m_PageByteSize; } // return how much of the mip tail we consumed, clamped to the size. Note resourceByteOffset has // been remapped to be mip-tail relative here return m_MipTail.byteOffset + RDCMIN(m_MipTail.totalPackedByteSize, resourceByteOffset + byteSize); } else { // otherwise the hard case - separate mip tails for each subresource. Figure out which // subresource we're starting with RDCASSERTNOTEQUAL(m_MipTail.byteStride, 0); uint32_t sub = uint32_t(resourceByteOffset / m_MipTail.byteStride); resourceByteOffset -= sub * m_MipTail.byteStride; const uint64_t mipTailSubresourceByteSize = m_MipTail.totalPackedByteSize / m_MipTail.mappings.size(); // while we have mapping bytes to consume and the subresource is in range while(byteSize > 0 && sub < m_MipTail.mappings.size()) { PageRangeMapping &mapping = m_MipTail.mappings[sub]; uint64_t consumedBytes = 0; // if we're setting the whole miptail, store that concisely if(resourceByteOffset == 0 && byteSize >= mipTailSubresourceByteSize) { mapping.pages.clear(); mapping.singleMapping.memory = memory; mapping.singleMapping.offset = memoryByteOffset; mapping.singlePageReused = useSinglePage; if(!useSinglePage) memoryByteOffset += m_MipTail.byteStride; consumedBytes = mipTailSubresourceByteSize; } else { mapping.createPages( uint32_t((mipTailSubresourceByteSize + m_PageByteSize - 1) / m_PageByteSize), m_PageByteSize); // iterate through each referenced page in this subresource's mip tail. Note we only iterate // over as many pages as this mapping has, even if the bound region is larger. for(size_t page = size_t(resourceByteOffset / m_PageByteSize), endPage = size_t((resourceByteOffset + byteSize + m_PageByteSize - 1) / m_PageByteSize); page < mapping.pages.size() && page < endPage; page++) { mapping.pages[page].memory = memory; mapping.pages[page].offset = memoryByteOffset; // if we're not mapping all resource pages to a single memory page, advance the offset if(!useSinglePage && memory != ResourceId()) memoryByteOffset += m_PageByteSize; consumedBytes += m_PageByteSize; } memoryByteOffset += m_MipTail.byteStride - mipTailSubresourceByteSize; } // if we have fully set this mip tail, move to the next subresource's mip tail. // note this covers the case where we set exactly all the bytes in the mip tail, where we set // more bytes than exist but don't overlap into the next (based on stride), as well as the // case where we have bytes to set in the next subresource too. In the first two cases we will // just return, but in the last case we 'consume' the stride and get ready to continue if(resourceByteOffset + consumedBytes >= mipTailSubresourceByteSize) { // we start from the first byte in the next miptail resourceByteOffset = 0; // advance over the consumed bytes byteSize -= consumedBytes; // advance over the padding bytes. // if we don't have enough remaining to hit the stride, we just zero-out the number of bytes // remaining byteSize -= RDCMIN(byteSize, m_MipTail.byteStride - mipTailSubresourceByteSize); sub++; } else { // and consume all bytes, even if that is more than we actually used above (consider if the // user specifies more than in the tail, but less than the stride) byteSize = 0; resourceByteOffset += consumedBytes; } } if(byteSize > 0) RDCERR("Unclaimed bytes being assigned to image after iterating over all subresources"); return m_MipTail.byteOffset + sub * m_MipTail.byteStride + resourceByteOffset; } } void PageTable::setImageBoxRange(uint32_t subresource, const Sparse::Coord &coord, const Sparse::Coord &dim, ResourceId memory, uint64_t memoryByteOffset, bool useSinglePage) { const Coord subresourcePageDim = calcSubresourcePageDim(subresource); RDCASSERT((coord.x % m_PageTexelSize.x) == 0); RDCASSERT((coord.y % m_PageTexelSize.y) == 0); RDCASSERT((coord.z % m_PageTexelSize.z) == 0); // dimension may be misaligned if it's referring to part of a page on a non-page-aligned texture // dimension RDCASSERT((dim.x % m_PageTexelSize.x) == 0 || (coord.x + dim.x == m_TextureDim.x), dim.x, coord.x, m_PageTexelSize.x, m_TextureDim.x); RDCASSERT((dim.y % m_PageTexelSize.y) == 0 || (coord.y + dim.y == m_TextureDim.y), dim.y, coord.y, m_PageTexelSize.y, m_TextureDim.y); RDCASSERT((dim.z % m_PageTexelSize.z) == 0 || (coord.z + dim.z == m_TextureDim.z), dim.z, coord.z, m_PageTexelSize.z, m_TextureDim.z); // convert coords and dim to pages for ease of calculation Sparse::Coord curCoord = coord; curCoord.x /= m_PageTexelSize.x; curCoord.y /= m_PageTexelSize.y; curCoord.z /= m_PageTexelSize.z; Sparse::Coord curDim = dim; curDim.x = RDCMAX(1U, (curDim.x + m_PageTexelSize.x - 1) / m_PageTexelSize.x); curDim.y = RDCMAX(1U, (curDim.y + m_PageTexelSize.y - 1) / m_PageTexelSize.y); curDim.z = RDCMAX(1U, (curDim.z + m_PageTexelSize.z - 1) / m_PageTexelSize.z); RDCASSERT(subresource < m_Subresources.size(), subresource, m_Subresources.size()); RDCASSERT(curCoord.x < subresourcePageDim.x && curCoord.y < subresourcePageDim.y && curCoord.z < subresourcePageDim.z); RDCASSERT(curCoord.x + curDim.x <= subresourcePageDim.x && curCoord.y + curDim.y <= subresourcePageDim.y && curCoord.z + curDim.z <= subresourcePageDim.z); // if we're setting to NULL, set the offset to 0 if(memory == ResourceId()) memoryByteOffset = 0; PageRangeMapping &sub = m_Subresources[subresource]; // if we're setting the whole subresource, set it to use the optimal single mapping if(curCoord.x == 0 && curCoord.y == 0 && curCoord.z == 0 && curDim == subresourcePageDim) { sub.pages.clear(); sub.singleMapping.memory = memory; sub.singleMapping.offset = memoryByteOffset; sub.singlePageReused = useSinglePage; } else { // either we're starting at a coord somewhere into the subresource, or we don't cover it all. // Split the subresource into pages if needed and update. const uint32_t numSubresourcePages = subresourcePageDim.x * subresourcePageDim.y * subresourcePageDim.z; sub.createPages(numSubresourcePages, m_PageByteSize); for(uint32_t z = curCoord.z; z < curCoord.z + curDim.z; z++) { for(uint32_t y = curCoord.y; y < curCoord.y + curDim.y; y++) { for(uint32_t x = curCoord.x; x < curCoord.x + curDim.x; x++) { // calculate the page const uint32_t page = calcPageForTileCoord({x, y, z}, subresourcePageDim); sub.pages[page].memory = memory; sub.pages[page].offset = memoryByteOffset; // if we're not mapping all resource pages to a single memory page, advance the offset if(!useSinglePage && memory != ResourceId()) memoryByteOffset += m_PageByteSize; } } } } } rdcpair<uint32_t, Coord> PageTable::setImageWrappedRange(uint32_t subresource, const Sparse::Coord &coord, uint64_t byteSize, ResourceId memory, uint64_t memoryByteOffset, bool useSinglePage, bool updateMappings) { const bool allBytes = (byteSize == ~0U); if(allBytes) byteSize -= byteSize % m_PageByteSize; RDCASSERT((byteSize % m_PageByteSize) == 0, byteSize, m_PageByteSize); RDCASSERT(subresource < m_Subresources.size() || isSubresourceInMipTail(subresource), subresource, m_Subresources.size()); Sparse::Coord curCoord = coord; // if we're setting to NULL, set the offset to 0 if(memory == ResourceId()) memoryByteOffset = 0; // loop while we still have bytes left, to allow wrapping over subresources while(byteSize > 0 && (isSubresourceInMipTail(subresource) || subresource < m_Subresources.size())) { const Coord subresourcePageDim = calcSubresourcePageDim(subresource); const uint32_t numSubresourcePages = isSubresourceInMipTail(subresource) ? uint32_t(m_MipTail.totalPackedByteSize / m_MipTail.mappings.size()) / m_PageByteSize : subresourcePageDim.x * subresourcePageDim.y * subresourcePageDim.z; PageRangeMapping &sub = isSubresourceInMipTail(subresource) ? getMipTailMapping(subresource) : m_Subresources[subresource]; const uint64_t subresourceByteSize = numSubresourcePages * m_PageByteSize; // if we're setting the whole subresource, set it to use the optimal single mapping if(curCoord.x == 0 && curCoord.y == 0 && curCoord.z == 0 && byteSize >= subresourceByteSize) { if(updateMappings) { sub.pages.clear(); sub.singleMapping.memory = memory; sub.singleMapping.offset = memoryByteOffset; sub.singlePageReused = useSinglePage; } // if we're not mapping all resource pages to a single memory page, advance the offset if(!useSinglePage && memory != ResourceId()) memoryByteOffset += numSubresourcePages * m_PageByteSize; byteSize -= subresourceByteSize; // continue on the next subresource at {0,0,0}. If there are bytes remaining we'll loop and // assign them // if we're setting in the miptail right now, continue on at the next mip 0 if(isSubresourceInMipTail(subresource)) { const uint32_t slice = subresource / m_MipCount; subresource = (slice + 1) * m_MipCount; } else { subresource++; curCoord = {0, 0, 0}; } // since we know we consumed a whole subresource above, if we're done then we can return the // correct reference to the next subresource at 0,0,0 here if(byteSize == 0) return {subresource, curCoord}; } else { // either we're starting at a coord somewhere into the subresource, or we don't cover it all. // Split the subresource into pages if needed and update. if(updateMappings) sub.createPages(numSubresourcePages, m_PageByteSize); // note that numPages could be more pages than in the subresource! hence below we check both // that we haven't exhausted the incoming pages and that we haven't exhausted the pages in the // subresource const uint32_t numPages = uint32_t(byteSize / m_PageByteSize); if(isSubresourceInMipTail(subresource)) { curCoord.x /= m_PageTexelSize.x; curCoord.y = 0; curCoord.z = 0; } else { // convert current co-ord to pages for calculation. We don't have to worry about doing this // repeatedly because if we overlap into another subresource we start at 0,0,0 curCoord.x /= m_PageTexelSize.x; curCoord.y /= m_PageTexelSize.y; curCoord.z /= m_PageTexelSize.z; } // calculate the starting page uint32_t startingPage = (((curCoord.z * subresourcePageDim.y) + curCoord.y) * subresourcePageDim.x) + curCoord.x; for(uint32_t page = startingPage; page < startingPage + numPages && page < numSubresourcePages; page++) { if(updateMappings) { sub.pages[page].memory = memory; sub.pages[page].offset = memoryByteOffset; } // if we're not mapping all resource pages to a single memory page, advance the offset if(!useSinglePage && memory != ResourceId()) memoryByteOffset += m_PageByteSize; byteSize -= m_PageByteSize; } // if we consumed all bytes and didn't get to the end of the subresource, calculate where we // ended up if(byteSize == 0 && startingPage + numPages < numSubresourcePages) { if(isSubresourceInMipTail(subresource)) { curCoord.x += numPages * m_PageByteSize; } else { // X we just increment by however many pages, wrapping by the row length in pages curCoord.x = (curCoord.x + numPages) % subresourcePageDim.x; // for Y we increment by however many *rows*, again wrapping curCoord.y = (curCoord.y + numPages / subresourcePageDim.x) % subresourcePageDim.y; // similarly for Z curCoord.z = (curCoord.z + numPages / (subresourcePageDim.x * subresourcePageDim.y)) % subresourcePageDim.z; } return {subresource, curCoord}; } // continue on the next subresource at {0,0,0}. If there are bytes remaining we'll loop and // assign them // if we're setting in the miptail right now, continue on at the next mip 0 if(isSubresourceInMipTail(subresource)) { const uint32_t slice = subresource / m_MipCount; subresource = (slice + 1) * m_MipCount; } else { subresource++; curCoord = {0, 0, 0}; } // if we got here we consumed the whole subresource and ended, so return that if(byteSize == 0) return {subresource, curCoord}; } } if(!allBytes && byteSize > 0) RDCERR("Unclaimed bytes being assigned to image after iterating over all subresources"); return {0, {0, 0, 0}}; } void PageTable::copyImageBoxRange(uint32_t dstSubresource, const Coord &coordInTiles, const Coord &dimInTiles, const PageTable &srcPageTable, uint32_t srcSubresource, const Coord &srcCoordInTiles) { // this can only be used if pages are the same size, which is always true on D3D RDCASSERT(getPageByteSize() == srcPageTable.getPageByteSize()); const bool srcMip = srcPageTable.isSubresourceInMipTail(srcSubresource); const bool dstMip = isSubresourceInMipTail(dstSubresource); // if we're copying between mip tails and the copy is completely contained in the mip tail on // both sides of the copy if(srcMip && dstMip && dimInTiles.x <= srcPageTable.getMipTailSliceSize() / srcPageTable.getPageByteSize() && dimInTiles.x <= getMipTailSliceSize() / getPageByteSize()) { const Sparse::PageRangeMapping &srcMapping = srcPageTable.getMipTailMapping(srcSubresource); // if the source has a single mapping, copy it and allow setMipTailRange to figure out if this // is a single mapping in the destination or not if(srcMapping.hasSingleMapping()) { setMipTailRange( getMipTailByteOffsetForSubresource(dstSubresource) + coordInTiles.x * m_PageByteSize, srcMapping.singleMapping.memory, srcMapping.singleMapping.offset + srcCoordInTiles.x * m_PageByteSize, dimInTiles.x * m_PageByteSize, srcMapping.singlePageReused); } // otherwise we just do a page-by-page copy else { uint32_t dstStartPage = coordInTiles.x; uint32_t srcStartPage = srcCoordInTiles.x; for(uint32_t pageIdx = 0; pageIdx < dimInTiles.x; pageIdx++) { Page srcPageContents = srcMapping.getPage(srcStartPage + pageIdx, m_PageByteSize); setMipTailRange(dstStartPage * m_PageByteSize, srcPageContents.memory, srcPageContents.offset, m_PageByteSize, false); } } return; } Sparse::Coord srcSubSize = srcPageTable.calcSubresourcePageDim(srcSubresource); Sparse::Coord dstSubSize = calcSubresourcePageDim(dstSubresource); // if the region covers the destination subresource we might be able to take a shortcut if(dstSubSize == dimInTiles) { // if the subresources are identical, just copy no matter what if(srcSubSize == dstSubSize) { m_Subresources[dstSubresource] = srcPageTable.getSubresource(srcSubresource); return; } // one more case - if the destination is completely covered by the region and the source is at // least as big AND the source is a single page mapping, we can copy to a single page mapping. // That's because the pages are the same they just wrap differently (e.g. in an original 8x8 // source the pages 0..7 form the first row and in the destination 4x4 those same pages are the // first two rows, but that's exactly what this operation wants to do). if(srcSubSize.x >= dimInTiles.x && srcSubSize.y >= dimInTiles.y && srcSubSize.z >= dimInTiles.z && srcPageTable.getSubresource(srcSubresource).hasSingleMapping()) { m_Subresources[dstSubresource] = srcPageTable.getSubresource(srcSubresource); return; } } // in all other cases we fall back to a page-by-page copy from source to dest. This case means the // box is a subset of the destination or the source isn't a nice single mapping so we need to copy // pages one by one // box regions are by definition constrained within a subresource. We assume it's // constrained within both... RDCASSERT(srcCoordInTiles.x + dimInTiles.x <= srcSubSize.x, srcCoordInTiles.x, dimInTiles.x, srcSubSize.x); RDCASSERT(srcCoordInTiles.y + dimInTiles.y <= srcSubSize.y, srcCoordInTiles.y, dimInTiles.x, srcSubSize.y); RDCASSERT(srcCoordInTiles.z + dimInTiles.z <= srcSubSize.z, srcCoordInTiles.z, dimInTiles.x, srcSubSize.z); RDCASSERT(coordInTiles.x + dimInTiles.x <= dstSubSize.x, coordInTiles.x, dimInTiles.x, dstSubSize.x); RDCASSERT(coordInTiles.y + dimInTiles.y <= dstSubSize.y, coordInTiles.y, dimInTiles.y, dstSubSize.y); RDCASSERT(coordInTiles.z + dimInTiles.z <= dstSubSize.z, coordInTiles.z, dimInTiles.z, dstSubSize.z); Sparse::PageRangeMapping &dstSub = m_Subresources[dstSubresource]; const Sparse::PageRangeMapping &srcSub = srcPageTable.getSubresource(srcSubresource); dstSub.createPages(dstSubSize.x * dstSubSize.y * dstSubSize.z, m_PageByteSize); for(uint32_t z = 0; z < dimInTiles.z; z++) { for(uint32_t y = 0; y < dimInTiles.y; y++) { for(uint32_t x = 0; x < dimInTiles.x; x++) { const uint32_t dstPage = calcPageForTileCoord( {coordInTiles.x + x, coordInTiles.y + y, coordInTiles.z + z}, dstSubSize); const uint32_t srcPage = calcPageForTileCoord( {srcCoordInTiles.x + x, srcCoordInTiles.y + y, srcCoordInTiles.z + z}, srcSubSize); dstSub.pages[dstPage] = srcSub.getPage(srcPage, m_PageByteSize); } } } } void PageTable::copyImageWrappedRange(uint32_t dstSubresource, const Coord &coordInTiles, uint64_t numTiles, const PageTable &srcPageTable, uint32_t srcSubresource, const Coord &srcCoordInTiles) { // this can only be used if pages are the same size, which is always true on D3D RDCASSERT(getPageByteSize() == srcPageTable.getPageByteSize()); const bool srcMip = srcPageTable.isSubresourceInMipTail(srcSubresource); const bool dstMip = isSubresourceInMipTail(dstSubresource); // if we're copying between mip tails and the copy is completely contained in the mip tail on // both sides of the copy if(srcMip && dstMip && numTiles <= srcPageTable.getMipTailSliceSize() / srcPageTable.getPageByteSize() && numTiles <= getMipTailSliceSize() / getPageByteSize()) { const Sparse::PageRangeMapping &srcMapping = srcPageTable.getMipTailMapping(srcSubresource); // if the source has a single mapping, copy it and allow setMipTailRange to figure out if this // is a single mapping in the destination or not if(srcMapping.hasSingleMapping()) { setMipTailRange( getMipTailByteOffsetForSubresource(dstSubresource) + coordInTiles.x * m_PageByteSize, srcMapping.singleMapping.memory, srcMapping.singleMapping.offset + srcCoordInTiles.x * m_PageByteSize, numTiles * m_PageByteSize, srcMapping.singlePageReused); } // otherwise we just do a page-by-page copy else { uint32_t dstStartPage = coordInTiles.x; uint32_t srcStartPage = srcCoordInTiles.x; for(uint32_t pageIdx = 0; pageIdx < numTiles; pageIdx++) { Page srcPageContents = srcMapping.getPage(srcStartPage + pageIdx, m_PageByteSize); setMipTailRange(dstStartPage * m_PageByteSize, srcPageContents.memory, srcPageContents.offset, m_PageByteSize, false); } } return; } // in all other cases we fall back to a page-by-page copy from source to dest, overlapping pages // linearly. Sparse::Coord srcSubSize = srcPageTable.calcSubresourcePageDim(srcSubresource); Sparse::Coord dstSubSize = calcSubresourcePageDim(dstSubresource); const Sparse::PageRangeMapping *srcMapping = &srcPageTable.getSubresource(srcSubresource); Sparse::PageRangeMapping *dstMapping = &m_Subresources[dstSubresource]; uint32_t dstPage = calcPageForTileCoord({coordInTiles.x, coordInTiles.y, coordInTiles.z}, dstSubSize); uint32_t srcPage = calcPageForTileCoord({srcCoordInTiles.x, srcCoordInTiles.y, srcCoordInTiles.z}, srcSubSize); for(uint64_t i = 0; i < numTiles;) { const uint64_t remainingTiles = numTiles - i; const uint32_t dstSubTiles = dstSubSize.x * dstSubSize.y * dstSubSize.z; const uint32_t srcSubTiles = srcSubSize.x * srcSubSize.y * srcSubSize.z; // if we currently have enough tiles remaining to update the whole next resource and we're // pointing at 0,0,0 and our source range is a single mapping, copy that single mapping. if(dstPage == 0 && dstSubTiles <= remainingTiles && srcMapping->hasSingleMapping() && dstSubTiles <= srcSubTiles - srcPage) { // as above, the tiles may wrap differently in the destination mapping but that's how we want // it to be *dstMapping = *srcMapping; // increment by how many tiles we consumed srcPage += dstSubTiles; dstPage += dstSubTiles; i += dstSubTiles; } else { // otherwise just copy the current page dstMapping->createPages(dstSubTiles, m_PageByteSize); dstMapping->pages[dstPage] = srcMapping->getPage(srcPage, m_PageByteSize); dstPage++; srcPage++; i++; } if(i >= numTiles) break; // wrap the destination and source to the next page in the next subresource if we've used all // the ones up if(srcPage >= srcSubTiles) { // start at page 0 in the next subresource srcPage = 0; // if we were in the mip tail, jump all the way to the next mip0, otherwise we just move to // the next subresource if(isSubresourceInMipTail(srcSubresource)) { const uint32_t slice = srcSubresource / srcPageTable.getMipCount(); srcSubresource = (slice + 1) * srcPageTable.getMipCount(); } else { srcSubresource++; } // update subresource properties for the new current subresource srcSubSize = srcPageTable.calcSubresourcePageDim(srcSubresource); srcMapping = &srcPageTable.getSubresource(srcSubresource); } if(dstPage >= dstSubTiles) { // start at page 0 in the next subresource dstPage = 0; // if we were in the mip tail, jump all the way to the next mip0, otherwise we just move to // the next subresource if(isSubresourceInMipTail(dstSubresource)) { const uint32_t slice = dstSubresource / m_MipCount; dstSubresource = (slice + 1) * m_MipCount; } else { dstSubresource++; } dstSubSize = calcSubresourcePageDim(dstSubresource); dstMapping = &m_Subresources[dstSubresource]; } if(srcSubresource >= srcPageTable.getNumSubresources()) { RDCERR( "Number of tiles %u in image wrapped range copy exceeded source page table subresource " "count %u", numTiles, srcPageTable.getNumSubresources()); return; } if(dstSubresource >= getNumSubresources()) { RDCERR( "Number of tiles %u in image wrapped range copy exceeded dest page table subresource " "count %u", numTiles, getNumSubresources()); return; } } } Coord PageTable::calcSubresourcePageDim(uint32_t subresource) const { const uint32_t mipLevel = subresource % m_MipCount; const Sparse::Coord mipDim = { RDCMAX(1U, m_TextureDim.x >> mipLevel), RDCMAX(1U, m_TextureDim.y >> mipLevel), RDCMAX(1U, m_TextureDim.z >> mipLevel), }; // for each page that is fully or partially used return {RDCMAX(1U, (mipDim.x + m_PageTexelSize.x - 1) / m_PageTexelSize.x), RDCMAX(1U, (mipDim.y + m_PageTexelSize.y - 1) / m_PageTexelSize.y), RDCMAX(1U, (mipDim.z + m_PageTexelSize.z - 1) / m_PageTexelSize.z)}; } uint64_t PageTable::GetSerialiseSize() const { uint64_t ret = 0; // size of the pair itself ret += sizeof(*this); // for each mip tail region for(uint32_t s = 0; s < getMipTail().mappings.size(); s++) { ret += sizeof(Sparse::PageRangeMapping); // and the size of each page if the range mapping is expanded if(!getMipTail().mappings[s].hasSingleMapping()) ret += sizeof(Sparse::Page) * getMipTail().mappings[s].pages.size(); } // for each subresource the size of it for(uint32_t s = 0; s < getNumSubresources(); s++) { ret += sizeof(Sparse::PageRangeMapping); // and the size of each page if the range mapping is expanded if(!getSubresource(s).hasSingleMapping()) ret += sizeof(Sparse::Page) * getSubresource(s).pages.size(); } return ret; } }; // namespace Sparse template <typename SerialiserType> void DoSerialise(SerialiserType &ser, Sparse::Coord &el) { SERIALISE_MEMBER(x); SERIALISE_MEMBER(y); SERIALISE_MEMBER(z); } template <typename SerialiserType> void DoSerialise(SerialiserType &ser, Sparse::Page &el) { SERIALISE_MEMBER(memory); SERIALISE_MEMBER(offset); } template <typename SerialiserType> void DoSerialise(SerialiserType &ser, Sparse::PageRangeMapping &el) { SERIALISE_MEMBER(singleMapping); SERIALISE_MEMBER(pages); } template <typename SerialiserType> void DoSerialise(SerialiserType &ser, Sparse::MipTail &el) { SERIALISE_MEMBER(firstMip); SERIALISE_MEMBER(byteOffset); SERIALISE_MEMBER(byteStride); SERIALISE_MEMBER(totalPackedByteSize); SERIALISE_MEMBER(mappings); } template <typename SerialiserType> void DoSerialise(SerialiserType &ser, Sparse::PageTable &el) { SERIALISE_MEMBER(m_TextureDim); SERIALISE_MEMBER(m_MipCount); SERIALISE_MEMBER(m_ArraySize); SERIALISE_MEMBER(m_PageByteSize); SERIALISE_MEMBER(m_PageTexelSize); SERIALISE_MEMBER(m_Subresources); SERIALISE_MEMBER(m_MipTail); } INSTANTIATE_SERIALISE_TYPE(Sparse::Coord); INSTANTIATE_SERIALISE_TYPE(Sparse::Page); INSTANTIATE_SERIALISE_TYPE(Sparse::PageRangeMapping); INSTANTIATE_SERIALISE_TYPE(Sparse::MipTail); INSTANTIATE_SERIALISE_TYPE(Sparse::PageTable); #if ENABLED(ENABLE_UNIT_TESTS) #include "catch/catch.hpp" template <> rdcstr DoStringise(const Sparse::Coord &el) { return StringFormat::Fmt("{%u, %u, %u}", el.x, el.y, el.z); } template <> rdcstr DoStringise(const Sparse::Page &el) { return StringFormat::Fmt("%s:%llu", ToStr(el.memory).c_str(), el.offset); } TEST_CASE("Test sparse page table mapping", "[sparse]") { Sparse::PageTable pageTable; SECTION("normal buffer") { pageTable.Initialise(256, 64); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 256); CHECK(pageTable.getMipTail().firstMip == 0); REQUIRE(pageTable.getMipTail().mappings.size() == 1); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({ResourceId(), 0})); uint64_t nextTailOffset; SECTION("Set all pages") { ResourceId mem = ResourceIDGen::GetNewUniqueID(); nextTailOffset = pageTable.setBufferRange(0, mem, 512, 256, false); CHECK(nextTailOffset == 256); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem, 512})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); }; SECTION("Set repeated page") { ResourceId mem = ResourceIDGen::GetNewUniqueID(); nextTailOffset = pageTable.setBufferRange(0, mem, 512, 256, true); CHECK(nextTailOffset == 256); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem, 512})); CHECK(pageTable.getMipTail().mappings[0].singlePageReused); }; SECTION("Set page subsets") { ResourceId mem = ResourceIDGen::GetNewUniqueID(); nextTailOffset = pageTable.setBufferRange(128, mem, 512, 64, false); CHECK(nextTailOffset == 128 + 64); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 4); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem, 512})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({ResourceId(), 0})); nextTailOffset = pageTable.setBufferRange(0, mem, 1024, 64, false); CHECK(nextTailOffset == 64); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem, 1024})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem, 512})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({ResourceId(), 0})); nextTailOffset = pageTable.setBufferRange(64, mem, 128, 128, false); CHECK(nextTailOffset == 64 + 128); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem, 1024})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem, 128})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem, 128 + 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({ResourceId(), 0})); nextTailOffset = pageTable.setBufferRange(64, mem, 256, 128, true); CHECK(nextTailOffset == 64 + 128); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem, 1024})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem, 256})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem, 256})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({ResourceId(), 0})); nextTailOffset = pageTable.setBufferRange(64, ResourceId(), 256, 64, true); CHECK(nextTailOffset == 64 + 64); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem, 1024})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem, 256})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({ResourceId(), 0})); }; }; SECTION("one-page buffer") { pageTable.Initialise(64, 64); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 64); CHECK(pageTable.getMipTail().firstMip == 0); REQUIRE(pageTable.getMipTail().mappings.size() == 1); ResourceId mem = ResourceIDGen::GetNewUniqueID(); uint64_t nextTailOffset; nextTailOffset = pageTable.setBufferRange(0, mem, 1024, 64, false); CHECK(nextTailOffset == 64); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem, 1024})); nextTailOffset = pageTable.setBufferRange(0, ResourceId(), 1024, 64, false); CHECK(nextTailOffset == 64); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({ResourceId(), 0})); }; SECTION("non-page-aligned buffer") { pageTable.Initialise(100, 64); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 100); CHECK(pageTable.getMipTail().firstMip == 0); REQUIRE(pageTable.getMipTail().mappings.size() == 1); uint64_t nextTailOffset; ResourceId mem = ResourceIDGen::GetNewUniqueID(); nextTailOffset = pageTable.setBufferRange(0, mem, 1024, 100, false); CHECK(nextTailOffset == 100); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem, 1024})); nextTailOffset = pageTable.setBufferRange(0, ResourceId(), 1024, 64, false); CHECK(nextTailOffset == 64); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 2); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem, 1024 + 64})); }; SECTION("sub-page sized buffer") { pageTable.Initialise(10, 64); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 10); CHECK(pageTable.getMipTail().firstMip == 0); REQUIRE(pageTable.getMipTail().mappings.size() == 1); uint64_t nextTailOffset; ResourceId mem = ResourceIDGen::GetNewUniqueID(); nextTailOffset = pageTable.setBufferRange(0, mem, 1024, 10, false); CHECK(nextTailOffset == 10); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem, 1024})); nextTailOffset = pageTable.setBufferRange(0, ResourceId(), 1024, 10, false); CHECK(nextTailOffset == 10); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({ResourceId(), 0})); }; SECTION("2D texture") { // create a 256x256 texture with 32x32 pages, 6 mips (the last two are in the mip tail) pageTable.Initialise({256, 256, 1}, 6, 1, 64, {32, 32, 1}, 4, 0x10000, 0, 256); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getPageTexelSize() == Sparse::Coord({32, 32, 1})); CHECK(pageTable.getMipTail().byteOffset == 0x10000); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 256); CHECK(pageTable.getMipTail().firstMip == 4); // only expect one mapping because we specified stride of 0, so packed mip tail REQUIRE(pageTable.getMipTail().mappings.size() == 1); REQUIRE(pageTable.getNumSubresources() == 6); CHECK_FALSE(pageTable.isSubresourceInMipTail(0)); CHECK_FALSE(pageTable.isSubresourceInMipTail(1)); CHECK_FALSE(pageTable.isSubresourceInMipTail(2)); CHECK_FALSE(pageTable.isSubresourceInMipTail(3)); CHECK(pageTable.isSubresourceInMipTail(4)); CHECK(pageTable.isSubresourceInMipTail(5)); CHECK_FALSE(pageTable.isByteOffsetInResource(0)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x1000)); CHECK(pageTable.isByteOffsetInResource(0x10000)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 32)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 255)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000 + 256)); // they should all be a single mapping to NULL CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(4).hasSingleMapping()); CHECK(pageTable.getSubresource(4).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(5).hasSingleMapping()); CHECK(pageTable.getSubresource(5).singleMapping == Sparse::Page({ResourceId(), 0})); ResourceId mip = ResourceIDGen::GetNewUniqueID(); uint64_t nextTailOffset; // this is tested above more robustly as buffers. Here we just check that setting the mip tail // offset doesn't break anything nextTailOffset = pageTable.setMipTailRange(0x10000, mip, 128, 256, false); CHECK(nextTailOffset == 0x10000 + 256); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mip, 128})); SECTION("whole-subresource bindings") { ResourceId sub0 = ResourceIDGen::GetNewUniqueID(); ResourceId sub1 = ResourceIDGen::GetNewUniqueID(); ResourceId sub2 = ResourceIDGen::GetNewUniqueID(); ResourceId sub3 = ResourceIDGen::GetNewUniqueID(); pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, sub0, 0, false); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({sub0, 0})); CHECK_FALSE(pageTable.getSubresource(0).singlePageReused); pageTable.setImageBoxRange(1, {0, 0, 0}, {128, 128, 1}, sub1, 128, true); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({sub1, 128})); CHECK(pageTable.getSubresource(1).singlePageReused); rdcpair<uint32_t, Sparse::Coord> nextCoord; // this mip 2 is 64x64 which is 2x2 tiles, each tiles is 64 bytes nextCoord = pageTable.setImageWrappedRange(2, {0, 0, 0}, 2 * 2 * 64, sub2, 256, false); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({sub2, 256})); CHECK_FALSE(pageTable.getSubresource(2).singlePageReused); CHECK(nextCoord.first == 3); CHECK(nextCoord.second == Sparse::Coord({0, 0, 0})); nextCoord = pageTable.setImageWrappedRange(3, {0, 0, 0}, 1 * 1 * 64, sub3, 512, true); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({sub3, 512})); // this is redundant because there's only one page, but let's check it anyway CHECK(pageTable.getSubresource(3).singlePageReused); CHECK(nextCoord.first == 4); CHECK(nextCoord.second == Sparse::Coord({0, 0, 0})); }; SECTION("Wrapped bindings into mip tail") { ResourceId whole = ResourceIDGen::GetNewUniqueID(); ResourceId sub = ResourceIDGen::GetNewUniqueID(); rdcpair<uint32_t, Sparse::Coord> nextCoord; // set the entire resource to the same page, that's enough tiles for each subresource plus the // mip tail nextCoord = pageTable.setImageWrappedRange( 0, {0, 0, 0}, (8 * 8 + 4 * 4 + 2 * 2 + 1 * 1) * 64 + 256, whole, 512, true); CHECK(nextCoord.first == 6); CHECK(nextCoord.second == Sparse::Coord({0, 0, 0})); for(uint32_t i = 0; i < 4; i++) { CHECK(pageTable.getSubresource(i).hasSingleMapping()); CHECK(pageTable.getSubresource(i).singleMapping == Sparse::Page({whole, 512})); CHECK(pageTable.getSubresource(i).singlePageReused); } CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({whole, 512})); CHECK(pageTable.getMipTail().mappings[0].singlePageReused); // set it without being the same page, to check offsets nextCoord = pageTable.setImageWrappedRange( 0, {0, 0, 0}, (8 * 8 + 4 * 4 + 2 * 2 + 1 * 1) * 64 + 256, whole, 0, false); CHECK(nextCoord.first == 6); CHECK(nextCoord.second == Sparse::Coord({0, 0, 0})); uint32_t dim = 8, offset = 0; for(uint32_t i = 0; i < 4; i++) { CHECK(pageTable.getSubresource(i).hasSingleMapping()); CHECK(pageTable.getSubresource(i).singleMapping == Sparse::Page({whole, offset})); CHECK_FALSE(pageTable.getSubresource(i).singlePageReused); offset += (dim * dim) * 64; dim >>= 1; } CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({whole, offset})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); // wrap a binding part-way into a mip tail nextCoord = pageTable.setImageWrappedRange(3, {0, 0, 0}, 64 + 128, sub, 0, false); // the 'coord' for mip tail is effectively 1D and 1 texel per tile CHECK(nextCoord.first == 4); CHECK(nextCoord.second == Sparse::Coord({128, 0, 0})); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({sub, 0})); CHECK_FALSE(pageTable.getSubresource(3).singlePageReused); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 4); // first two pages have been updated CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({sub, 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({sub, 128})); // second two pages still point into whole CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({whole, (8 * 8 + 4 * 4 + 2 * 2 + 1 * 1) * 64 + 128})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({whole, (8 * 8 + 4 * 4 + 2 * 2 + 1 * 1) * 64 + 192})); }; SECTION("Partial-subresource bindings") { ResourceId sub0a = ResourceIDGen::GetNewUniqueID(); ResourceId sub0b = ResourceIDGen::GetNewUniqueID(); ResourceId sub0c = ResourceIDGen::GetNewUniqueID(); // make sure that we detect this as a sub-update even though it starts at 0 and has full width pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 192, 1}, sub0a, 0, false); CHECK_FALSE(pageTable.getSubresource(0).hasSingleMapping()); // 8x8 pages in top mip REQUIRE(pageTable.getSubresource(0).pages.size() == 64); #define _idx(x, y) y * 8 + x // don't check every one, spot-check CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({sub0a, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0a, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 2)] == Sparse::Page({sub0a, (2 * 8 + 1) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0a, (2 * 8 + 2) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({ResourceId(), 0})); // update only a sub-box pageTable.setImageBoxRange(0, {64, 0, 0}, {32, 256, 1}, sub0b, 0, false); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({sub0a, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0b, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0b, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({sub0b, 6 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({sub0b, 7 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({ResourceId(), 0})); rdcpair<uint32_t, Sparse::Coord> nextCoord; // update a wrapped region nextCoord = pageTable.setImageWrappedRange(0, {96, 192, 0}, 8 * 64, sub0c, 640, true); CHECK(nextCoord.first == 0); CHECK(nextCoord.second == Sparse::Coord({3, 7, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({sub0a, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0b, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0b, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({sub0b, 6 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({ResourceId(), 0})); nextCoord = pageTable.setImageWrappedRange(0, {64, 224, 0}, 11 * 64, sub0c, 6400, false); CHECK(nextCoord.first == 1); CHECK(nextCoord.second == Sparse::Coord({1, 1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({sub0a, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0b, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0b, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({sub0b, 6 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({sub0c, 6400})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({sub0c, 6464})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({sub0c, 6528})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({sub0c, 6720})); CHECK_FALSE(pageTable.getSubresource(1).hasSingleMapping()); // 4x4 pages in second mip REQUIRE(pageTable.getSubresource(1).pages.size() == 16); CHECK(pageTable.getSubresource(1).pages[0] == Sparse::Page({sub0c, 6784})); nextCoord = pageTable.setImageWrappedRange(0, {32, 0, 0}, 64, ResourceId(), 640, false); CHECK(nextCoord.first == 0); CHECK(nextCoord.second == Sparse::Coord({2, 0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0b, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0b, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({sub0b, 6 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({sub0c, 6400})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({sub0c, 6464})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({sub0c, 6528})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({sub0c, 6720})); pageTable.setImageBoxRange(0, {32, 192, 0}, {64, 64, 1}, ResourceId(), 640, false); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0b, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0b, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({sub0c, 6464})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({sub0c, 6528})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({sub0c, 6720})); nextCoord = pageTable.setImageWrappedRange(0, {128, 224, 0}, 64 * 4, sub0a, 512, true); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({sub0a, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({sub0b, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({sub0b, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 2)] == Sparse::Page({sub0a, (2 * 8 + 3) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({sub0c, 640})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({sub0c, 6464})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 7)] == Sparse::Page({sub0a, 512})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7)] == Sparse::Page({sub0a, 512})); CHECK(pageTable.getSubresource(1).pages[0] == Sparse::Page({sub0c, 6784})); CHECK(nextCoord.first == 1); CHECK(nextCoord.second == Sparse::Coord({0, 0, 0})); }; }; SECTION("2D rectangular texture") { pageTable.Initialise({512, 128, 1}, 6, 1, 64, {32, 32, 1}, 4, 0x10000, 0, 64); ResourceId mem0 = ResourceIDGen::GetNewUniqueID(); ResourceId mem1 = ResourceIDGen::GetNewUniqueID(); ResourceId mem2 = ResourceIDGen::GetNewUniqueID(); pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 64, 1}, mem0, 0, true); CHECK_FALSE(pageTable.getSubresource(0).hasSingleMapping()); // 16x4 pages in top mip REQUIRE(pageTable.getSubresource(0).pages.size() == 64); #undef _idx #define _idx(x, y) y * 16 + x CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 2)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 2)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 2)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 3)] == Sparse::Page({ResourceId(), 0})); pageTable.setImageBoxRange(0, {256, 64, 0}, {256, 64, 1}, mem1, 0, true); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 2)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 2)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 2)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 3)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 3)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 3)] == Sparse::Page({mem1, 0})); rdcpair<uint32_t, Sparse::Coord> nextCoord; // update from 11,2 for 17 tiles, which should overlap correctly to 11,3 and no more nextCoord = pageTable.setImageWrappedRange(0, {11 * 32, 64, 0}, 64 * 17, mem2, 0, true); CHECK(nextCoord.first == 0); CHECK(nextCoord.second == Sparse::Coord({12, 3, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 2)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 2)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 2)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 3)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 3)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 3)] == Sparse::Page({mem1, 0})); }; SECTION("2D non-aligned texture") { pageTable.Initialise({500, 116, 1}, 6, 1, 64, {32, 32, 1}, 4, 0x10000, 0, 64); ResourceId mem0 = ResourceIDGen::GetNewUniqueID(); ResourceId mem1 = ResourceIDGen::GetNewUniqueID(); ResourceId mem2 = ResourceIDGen::GetNewUniqueID(); #undef _idx #define _idx(x, y) y * 16 + x pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 64, 1}, mem0, 0, true); pageTable.setImageBoxRange(0, {256, 64, 0}, {500 - 256, 116 - 64, 1}, mem1, 0, true); pageTable.setImageWrappedRange(0, {11 * 32, 64, 0}, 64 * 17, mem2, 0, true); // still 16x4 pages in top mip REQUIRE(pageTable.getSubresource(0).pages.size() == 64); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 1)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 2)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 2)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 2)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(11, 3)] == Sparse::Page({mem2, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(12, 3)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(13, 3)] == Sparse::Page({mem1, 0})); }; SECTION("2D texture that's all mip tail") { // create a 256x256 texture with 32x32 pages, 6 mips (the last two are in the mip tail) pageTable.Initialise({256, 256, 1}, 6, 1, 64, {32, 32, 1}, 0, 0, 0, 8192); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getPageTexelSize() == Sparse::Coord({32, 32, 1})); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 8192); CHECK(pageTable.getMipTail().firstMip == 0); REQUIRE(pageTable.getMipTail().mappings.size() == 1); REQUIRE(pageTable.getNumSubresources() == 6); CHECK(pageTable.isSubresourceInMipTail(0)); CHECK(pageTable.isSubresourceInMipTail(1)); CHECK(pageTable.isSubresourceInMipTail(2)); CHECK(pageTable.isSubresourceInMipTail(3)); CHECK(pageTable.isSubresourceInMipTail(4)); CHECK(pageTable.isSubresourceInMipTail(5)); ResourceId mip = ResourceIDGen::GetNewUniqueID(); uint64_t nextTailOffset; // this is tested above more robustly as buffers. Here we just check that setting the mip tail // offset doesn't break anything nextTailOffset = pageTable.setMipTailRange(0, mip, 512, 256, false); CHECK(nextTailOffset == 256); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 8192 / 64); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mip, 512})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mip, 576})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mip, 640})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mip, 704})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[5] == Sparse::Page({ResourceId(), 0})); }; SECTION("2D texture being set with unbounded range") { ResourceId whole = ResourceIDGen::GetNewUniqueID(); // create a 256x256 texture with 32x32 pages, 6 mips (the last two are in the mip tail) pageTable.Initialise({256, 256, 1}, 6, 1, 64, {32, 32, 1}, 4, 0, 0, 8192); pageTable.setImageWrappedRange(0, {0, 0, 0}, ~0U, whole, 0, false); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({whole, 0})); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({whole, (8 * 8) * 64})); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({whole, (8 * 8 + 4 * 4) * 64})); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({whole, (8 * 8 + 4 * 4 + 2 * 2) * 64})); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({whole, (8 * 8 + 4 * 4 + 2 * 2 + 1 * 1) * 64})); }; SECTION("3D texture tests") { // create a 256x256x64 texture with 32x32x4 pages, 6 mips (the last two are in the mip tail) pageTable.Initialise({256, 256, 64}, 6, 1, 64, {32, 32, 4}, 4, 0x10000, 0, 64); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getPageTexelSize() == Sparse::Coord({32, 32, 4})); CHECK(pageTable.getMipTail().byteOffset == 0x10000); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 64); CHECK(pageTable.getMipTail().firstMip == 4); REQUIRE(pageTable.getNumSubresources() == 6); CHECK_FALSE(pageTable.isSubresourceInMipTail(0)); CHECK_FALSE(pageTable.isSubresourceInMipTail(1)); CHECK_FALSE(pageTable.isSubresourceInMipTail(2)); CHECK_FALSE(pageTable.isSubresourceInMipTail(3)); CHECK(pageTable.isSubresourceInMipTail(4)); CHECK(pageTable.isSubresourceInMipTail(5)); // they should all be a single mapping to NULL CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(4).hasSingleMapping()); CHECK(pageTable.getSubresource(4).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(5).hasSingleMapping()); CHECK(pageTable.getSubresource(5).singleMapping == Sparse::Page({ResourceId(), 0})); SECTION("whole-subresource bindings") { ResourceId sub0 = ResourceIDGen::GetNewUniqueID(); ResourceId sub1 = ResourceIDGen::GetNewUniqueID(); pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 64}, sub0, 0, false); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({sub0, 0})); CHECK_FALSE(pageTable.getSubresource(0).singlePageReused); pageTable.setImageBoxRange(1, {0, 0, 0}, {128, 128, 32}, sub1, 128, true); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({sub1, 128})); CHECK(pageTable.getSubresource(1).singlePageReused); }; SECTION("Partial-subresource bindings") { ResourceId sub0a = ResourceIDGen::GetNewUniqueID(); ResourceId sub0b = ResourceIDGen::GetNewUniqueID(); ResourceId sub0c = ResourceIDGen::GetNewUniqueID(); // make sure that we detect this as a sub-update even though it covers full width/height pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 16}, sub0a, 0, false); CHECK_FALSE(pageTable.getSubresource(0).hasSingleMapping()); // 8x8x16 pages in top mip REQUIRE(pageTable.getSubresource(0).pages.size() == 8 * 8 * 16); #undef _idx #define _idx(x, y, z) ((z * 8 + y) * 8 + x) // don't check every one, spot-check CHECK(pageTable.getSubresource(0).pages[_idx(0, 0, 0)] == Sparse::Page({sub0a, _idx(0, 0, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 4, 0)] == Sparse::Page({sub0a, _idx(3, 4, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7, 0)] == Sparse::Page({sub0a, _idx(7, 7, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0, 1)] == Sparse::Page({sub0a, _idx(0, 0, 1) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 4, 1)] == Sparse::Page({sub0a, _idx(3, 4, 1) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7, 1)] == Sparse::Page({sub0a, _idx(7, 7, 1) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0, 10)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 4, 10)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7, 10)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0, 11)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 4, 11)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 7, 11)] == Sparse::Page({ResourceId(), 0})); }; }; SECTION("2D texture array tests") { ResourceId mip0 = ResourceIDGen::GetNewUniqueID(); ResourceId mip1 = ResourceIDGen::GetNewUniqueID(); ResourceId mip2 = ResourceIDGen::GetNewUniqueID(); // create a 256x256 texture with 32x32 pages, 6 mips (the last two are in the mip tail), and 5 // array slices. The mip tail in this case we make two pages to better show the effect of the // mip tail SECTION("separate mip tail") { // in the event that we have separate mip tails the stride may be huge as otherwise it's just // a single mip tail storage. In this event we don't want to overallocate and waste pages pageTable.Initialise({256, 256, 1}, 6, 5, 64, {32, 32, 1}, 4, 0x10000, 32768, 128 * 5); SECTION("property accessors") { CHECK(pageTable.getMipCount() == 6); CHECK(pageTable.getArraySize() == 5); CHECK(pageTable.calcSubresource(0, 0) == 0); CHECK(pageTable.calcSubresource(0, 1) == 1); CHECK(pageTable.calcSubresource(0, 2) == 2); CHECK(pageTable.calcSubresource(0, 3) == 3); CHECK(pageTable.calcSubresource(0, 4) == 4); CHECK(pageTable.calcSubresource(0, 5) == 5); CHECK(pageTable.calcSubresource(1, 0) == 6); CHECK(pageTable.calcSubresource(2, 2) == 14); CHECK(pageTable.calcSubresource(4, 5) == 29); // 64 bytes per page, 8x8 pages in top mip CHECK(pageTable.getSubresourceByteSize(0) == 64 * 8 * 8); CHECK(pageTable.getSubresourceByteSize(6) == 64 * 8 * 8); CHECK(pageTable.getSubresourceByteSize(12) == 64 * 8 * 8); CHECK(pageTable.getSubresourceByteSize(1) == 64 * 4 * 4); CHECK(pageTable.getSubresourceByteSize(2) == 64 * 2 * 2); CHECK(pageTable.getSubresourceByteSize(3) == 64 * 1 * 1); } CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getPageTexelSize() == Sparse::Coord({32, 32, 1})); CHECK(pageTable.getMipTail().byteOffset == 0x10000); CHECK(pageTable.getMipTail().byteStride == 32768); CHECK(pageTable.getMipTail().totalPackedByteSize == 128 * 5); CHECK(pageTable.getMipTail().firstMip == 4); REQUIRE(pageTable.getMipTail().mappings.size() == 5); REQUIRE(pageTable.getNumSubresources() == 6 * 5); CHECK_FALSE(pageTable.isByteOffsetInResource(0)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x1000)); CHECK(pageTable.isByteOffsetInResource(0x10000)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 32)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 1280)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 32768)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 128000)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 32768 * 5 - 1)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000 + 32768 * 5)); // all mips in the same array slice should have the same miptail offset CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == pageTable.getMipTailByteOffsetForSubresource(1)); CHECK(pageTable.getMipTailByteOffsetForSubresource(6) == pageTable.getMipTailByteOffsetForSubresource(8)); CHECK(pageTable.getMipTailByteOffsetForSubresource(18) == pageTable.getMipTailByteOffsetForSubresource(20)); // but mips in different slices should have a different one CHECK(pageTable.getMipTailByteOffsetForSubresource(0) != pageTable.getMipTailByteOffsetForSubresource(6)); CHECK(pageTable.getMipTailByteOffsetForSubresource(0) != pageTable.getMipTailByteOffsetForSubresource(20)); // the calculated offset should be relative to the stride, not relative to the packing CHECK(pageTable.getMipTailByteOffsetForSubresource(6) == 0x10000 + 32768); uint64_t nextTailOffset; SECTION("separate whole-mip sets") { nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(0), mip0, 0, 128, false); CHECK(nextTailOffset == pageTable.getMipTailByteOffsetForSubresource(6)); nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(6), mip1, 640, 128, true); CHECK(nextTailOffset == pageTable.getMipTailByteOffsetForSubresource(12)); nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(18), mip2, 6400, 128, false); CHECK(nextTailOffset == pageTable.getMipTailByteOffsetForSubresource(24)); // each of these sets should have been detected as a single page mapping CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mip0, 0})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); CHECK(pageTable.getMipTail().mappings[1].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[1].singleMapping == Sparse::Page({mip1, 640})); CHECK(pageTable.getMipTail().mappings[1].singlePageReused); CHECK(pageTable.getMipTail().mappings[2].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[2].singleMapping == Sparse::Page({ResourceId(), 0})); CHECK_FALSE(pageTable.getMipTail().mappings[2].singlePageReused); CHECK(pageTable.getMipTail().mappings[3].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[3].singleMapping == Sparse::Page({mip2, 6400})); CHECK_FALSE(pageTable.getMipTail().mappings[3].singlePageReused); CHECK(pageTable.getMipTail().mappings[4].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[4].singleMapping == Sparse::Page({ResourceId(), 0})); CHECK_FALSE(pageTable.getMipTail().mappings[4].singlePageReused); }; SECTION("single set large enough for all mips") { nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(0), mip0, 0, 32768 * 4 + 128, false); CHECK(nextTailOffset >= pageTable.getMipTailByteOffsetForSubresource(29) + 128); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mip0, 32768 * 0})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); CHECK(pageTable.getMipTail().mappings[1].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[1].singleMapping == Sparse::Page({mip0, 32768 * 1})); CHECK_FALSE(pageTable.getMipTail().mappings[1].singlePageReused); CHECK(pageTable.getMipTail().mappings[2].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[2].singleMapping == Sparse::Page({mip0, 32768 * 2})); CHECK_FALSE(pageTable.getMipTail().mappings[2].singlePageReused); CHECK(pageTable.getMipTail().mappings[3].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[3].singleMapping == Sparse::Page({mip0, 32768 * 3})); CHECK_FALSE(pageTable.getMipTail().mappings[3].singlePageReused); CHECK(pageTable.getMipTail().mappings[4].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[4].singleMapping == Sparse::Page({mip0, 32768 * 4})); CHECK_FALSE(pageTable.getMipTail().mappings[4].singlePageReused); }; SECTION("Partial and overlapping memory sets") { nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(0), mip0, 0, 64, false); CHECK(nextTailOffset == pageTable.getMipTailByteOffsetForSubresource(0) + 64); nextTailOffset = pageTable.setMipTailRange( pageTable.getMipTailByteOffsetForSubresource(6) + 64, mip1, 256, 64, false); CHECK(nextTailOffset == pageTable.getMipTailByteOffsetForSubresource(12)); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 2); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mip0, 0})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({ResourceId(), 0})); CHECK_FALSE(pageTable.getMipTail().mappings[1].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[1].pages.size() == 2); CHECK(pageTable.getMipTail().mappings[1].pages[0] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[1].pages[1] == Sparse::Page({mip1, 256})); // this set is dubiously legal in client APIs but we ensure it works. We set part of one mip // tail, then the whole stride (which overwrites the real non-tail subresources?) then part // of the mip tail of the next // we set 64 bytes in one, 'set' (skip) the padding bytes (stride - miptail size) then 64 // more bytes nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(0) + 64, mip2, 64, 64 + (32768 - 128) + 64, false); CHECK(nextTailOffset == pageTable.getMipTailByteOffsetForSubresource(6) + 64); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 2); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mip0, 0})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mip2, 64})); CHECK_FALSE(pageTable.getMipTail().mappings[1].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[1].pages.size() == 2); CHECK(pageTable.getMipTail().mappings[1].pages[0] == Sparse::Page({mip2, 32768})); CHECK(pageTable.getMipTail().mappings[1].pages[1] == Sparse::Page({mip1, 256})); nextTailOffset = pageTable.setMipTailRange(pageTable.getMipTailByteOffsetForSubresource(18) + 64, mip2, 0, 64 + (32768 - 128) + 128, false); CHECK(nextTailOffset >= pageTable.getMipTailByteOffsetForSubresource(29) + 128); CHECK_FALSE(pageTable.getMipTail().mappings[3].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[3].pages.size() == 2); CHECK(pageTable.getMipTail().mappings[3].pages[0] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[3].pages[1] == Sparse::Page({mip2, 0})); CHECK(pageTable.getMipTail().mappings[4].hasSingleMapping()); CHECK_FALSE(pageTable.getMipTail().mappings[4].singlePageReused); CHECK(pageTable.getMipTail().mappings[4].singleMapping == Sparse::Page({mip2, 64 + (32768 - 128)})); }; }; SECTION("combined mip tail") { pageTable.Initialise({256, 256, 1}, 6, 5, 64, {32, 32, 1}, 4, 0x10000, 0, 128 * 5); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getPageTexelSize() == Sparse::Coord({32, 32, 1})); CHECK(pageTable.getMipTail().byteOffset == 0x10000); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 128 * 5); CHECK(pageTable.getMipTail().firstMip == 4); REQUIRE(pageTable.getMipTail().mappings.size() == 1); REQUIRE(pageTable.getNumSubresources() == 6 * 5); CHECK_FALSE(pageTable.isByteOffsetInResource(0)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x1000)); CHECK(pageTable.isByteOffsetInResource(0x10000)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 32)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 128)); CHECK(pageTable.isByteOffsetInResource(0x10000 + 128 * 5 - 1)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000 + 128 * 5)); // all mips in all array slices should have the same miptail offset we specified CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == 0x10000); CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == pageTable.getMipTailByteOffsetForSubresource(1)); CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == pageTable.getMipTailByteOffsetForSubresource(6)); CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == pageTable.getMipTailByteOffsetForSubresource(8)); CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == pageTable.getMipTailByteOffsetForSubresource(16)); CHECK(pageTable.getMipTailByteOffsetForSubresource(0) == pageTable.getMipTailByteOffsetForSubresource(20)); uint64_t nextTailOffset; SECTION("whole-tail set") { nextTailOffset = pageTable.setMipTailRange(0x10000, mip0, 0, 128 * 5, false); CHECK(nextTailOffset == 0x10000 + 128 * 5); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mip0, 0})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); }; SECTION("separate mip sets") { // we don't use getMipTailByteOffset.. to calculate the offset because the mip tail is a // single one for all subresources nextTailOffset = pageTable.setMipTailRange(0x10000, mip0, 0, 128, false); CHECK(nextTailOffset == 0x10000 + 128); nextTailOffset = pageTable.setMipTailRange(0x10000 + 128, mip1, 640, 128, false); CHECK(nextTailOffset == 0x10000 + 256); nextTailOffset = pageTable.setMipTailRange(0x10000 + 384, mip2, 6400, 128, false); CHECK(nextTailOffset == 0x10000 + 512); // we should only allocate the minimum number of pages - total size divided by page size CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 5 * 2); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mip0, 0})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mip0, 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mip1, 640})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mip1, 704})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[5] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[6] == Sparse::Page({mip2, 6400})); CHECK(pageTable.getMipTail().mappings[0].pages[7] == Sparse::Page({mip2, 6464})); }; }; SECTION("no mip tail") { pageTable.Initialise({256, 256, 1}, 6, 5, 64, {32, 32, 1}, 8, 0x10000, 0, 128 * 5); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getPageTexelSize() == Sparse::Coord({32, 32, 1})); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 0); CHECK(pageTable.getMipTail().firstMip == 6); REQUIRE(pageTable.getNumSubresources() == 6 * 5); CHECK_FALSE(pageTable.isByteOffsetInResource(0)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x1000)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000 + 32)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000 + 63)); CHECK_FALSE(pageTable.isByteOffsetInResource(0x10000 + 64)); }; if(pageTable.getMipTail().totalPackedByteSize > 0) { for(uint32_t slice = 0; slice < 5; slice++) { for(uint32_t mip = 0; mip < 6; mip++) { uint32_t sub = slice * 6 + mip; if(mip < 4) { CHECK_FALSE(pageTable.isSubresourceInMipTail(sub)); } else { CHECK(pageTable.isSubresourceInMipTail(sub)); } } } } ResourceId sub0 = ResourceIDGen::GetNewUniqueID(); ResourceId sub1_2 = ResourceIDGen::GetNewUniqueID(); ResourceId sub7 = ResourceIDGen::GetNewUniqueID(); ResourceId sub8 = ResourceIDGen::GetNewUniqueID(); ResourceId sub18_19_20 = ResourceIDGen::GetNewUniqueID(); pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, sub0, 0, false); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({sub0, 0})); CHECK_FALSE(pageTable.getSubresource(0).singlePageReused); rdcpair<uint32_t, Sparse::Coord> nextCoord; // this will set all of subresource 1 (4x4 tiles), wrap into subresource 2 (2x2 tiles) and set // all of that nextCoord = pageTable.setImageWrappedRange(1, {0, 0, 0}, (16 + 4) * 64, sub1_2, 0x200000, false); CHECK(nextCoord.first == 3); CHECK(nextCoord.second == Sparse::Coord({0, 0, 0})); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({sub1_2, 0x200000})); CHECK_FALSE(pageTable.getSubresource(1).singlePageReused); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({sub1_2, 0x200000 + 16 * 64})); CHECK_FALSE(pageTable.getSubresource(2).singlePageReused); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({ResourceId(), 0})); pageTable.setImageBoxRange(7, {0, 0, 0}, {128, 128, 1}, sub7, 128, true); CHECK(pageTable.getSubresource(7).hasSingleMapping()); CHECK(pageTable.getSubresource(7).singleMapping == Sparse::Page({sub7, 128})); CHECK(pageTable.getSubresource(7).singlePageReused); #undef _idx #define _idx(x, y) y * 2 + x pageTable.setImageBoxRange(8, {32, 0, 0}, {32, 64, 1}, sub8, 12800, false); CHECK(pageTable.getSubresource(8).pages[_idx(0, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(8).pages[_idx(1, 0)] == Sparse::Page({sub8, 12800})); CHECK(pageTable.getSubresource(8).pages[_idx(0, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(8).pages[_idx(1, 1)] == Sparse::Page({sub8, 12864})); // this sets some of subresource 18 (8x8 tiles), all of subresource 19 (4x4 tiles) and some of // 20 (2x2 tiles) nextCoord = pageTable.setImageWrappedRange(18, {128, 128, 0}, (28 + 16 + 1) * 64, sub18_19_20, 0, false); CHECK(nextCoord.first == 20); CHECK(nextCoord.second == Sparse::Coord({1, 0, 0})); #undef _idx #define _idx(x, y) y * 8 + x CHECK(pageTable.getSubresource(18).pages[_idx(0, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(18).pages[_idx(3, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(18).pages[_idx(4, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(18).pages[_idx(5, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(18).pages[_idx(3, 4)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(18).pages[_idx(4, 4)] == Sparse::Page({sub18_19_20, 0 * 64})); CHECK(pageTable.getSubresource(18).pages[_idx(5, 4)] == Sparse::Page({sub18_19_20, 1 * 64})); CHECK(pageTable.getSubresource(18).pages[_idx(7, 7)] == Sparse::Page({sub18_19_20, 27 * 64})); CHECK(pageTable.getSubresource(19).hasSingleMapping()); CHECK(pageTable.getSubresource(19).singleMapping == Sparse::Page({sub18_19_20, 28 * 64})); CHECK_FALSE(pageTable.getSubresource(19).singlePageReused); #undef _idx #define _idx(x, y) y * 2 + x CHECK(pageTable.getSubresource(20).pages[_idx(0, 0)] == Sparse::Page({sub18_19_20, (28 + 16) * 64})); CHECK(pageTable.getSubresource(20).pages[_idx(1, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(20).pages[_idx(0, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(20).pages[_idx(1, 1)] == Sparse::Page({ResourceId(), 0})); }; SECTION("Updates from whole-subresource to split pages") { ResourceId mem0 = ResourceIDGen::GetNewUniqueID(); ResourceId mem1 = ResourceIDGen::GetNewUniqueID(); ResourceId mem2 = ResourceIDGen::GetNewUniqueID(); SECTION("Buffers/mip-tail") { pageTable.Initialise(320, 64); CHECK(pageTable.getPageByteSize() == 64); CHECK(pageTable.getMipTail().byteOffset == 0); CHECK(pageTable.getMipTail().byteStride == 0); CHECK(pageTable.getMipTail().totalPackedByteSize == 320); CHECK(pageTable.getMipTail().firstMip == 0); REQUIRE(pageTable.getMipTail().mappings.size() == 1); uint64_t nextTailOffset; nextTailOffset = pageTable.setBufferRange(0, mem0, 0, 320, false); CHECK(nextTailOffset == 320); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem0, 0})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); nextTailOffset = pageTable.setBufferRange(128, mem1, 0, 64, false); CHECK(nextTailOffset == 128 + 64); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 5); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem1, 0})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 192})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 256})); nextTailOffset = pageTable.setBufferRange(0, mem2, 1024, 64, false); CHECK(nextTailOffset == 0 + 64); CHECK_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE(pageTable.getMipTail().mappings[0].pages.size() == 5); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem2, 1024})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem1, 0})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 192})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 256})); nextTailOffset = pageTable.setBufferRange(0, mem2, 0, 320, false); CHECK(nextTailOffset == 0 + 320); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem2, 0})); CHECK_FALSE(pageTable.getMipTail().mappings[0].singlePageReused); nextTailOffset = pageTable.setBufferRange(0, mem1, 0, 320, true); CHECK(nextTailOffset == 0 + 320); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == Sparse::Page({mem1, 0})); CHECK(pageTable.getMipTail().mappings[0].singlePageReused); }; SECTION("2D texture") { // create a 256x256 texture with 32x32 pages, 6 mips (the last two are in the mip tail) pageTable.Initialise({256, 256, 1}, 6, 1, 64, {32, 32, 1}, 4, 0x10000, 0, 64); // they should all be a single mapping to NULL CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(3).hasSingleMapping()); CHECK(pageTable.getSubresource(3).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(4).hasSingleMapping()); CHECK(pageTable.getSubresource(4).singleMapping == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(5).hasSingleMapping()); CHECK(pageTable.getSubresource(5).singleMapping == Sparse::Page({ResourceId(), 0})); pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, mem0, 0, false); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({mem0, 0})); CHECK_FALSE(pageTable.getSubresource(0).singlePageReused); pageTable.setImageBoxRange(0, {32, 32, 0}, {64, 64, 1}, mem1, 10240, true); #undef _idx #define _idx(x, y) (y * 8 + x) CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem0, _idx(0, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem0, _idx(1, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem0, _idx(2, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem1, 10240})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem1, 10240})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 2)] == Sparse::Page({mem1, 10240})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({mem1, 10240})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({mem0, _idx(2, 6) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({mem0, _idx(3, 6) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({mem0, _idx(1, 7) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({mem0, _idx(2, 7) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({mem0, _idx(3, 7) * 64})); pageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, mem0, 0, false); pageTable.setImageBoxRange(0, {32, 32, 0}, {64, 64, 1}, mem1, 1024000, false); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem0, _idx(0, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem0, _idx(1, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem0, _idx(2, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem1, 1024000})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem1, 1024064})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 2)] == Sparse::Page({mem1, 1024128})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 2)] == Sparse::Page({mem1, 1024192})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 6)] == Sparse::Page({mem0, _idx(2, 6) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 6)] == Sparse::Page({mem0, _idx(3, 6) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 7)] == Sparse::Page({mem0, _idx(1, 7) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 7)] == Sparse::Page({mem0, _idx(2, 7) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(3, 7)] == Sparse::Page({mem0, _idx(3, 7) * 64})); }; }; SECTION("page table copy operations") { ResourceId mem0 = ResourceIDGen::GetNewUniqueID(); ResourceId mem1 = ResourceIDGen::GetNewUniqueID(); ResourceId mem2 = ResourceIDGen::GetNewUniqueID(); ResourceId mem3 = ResourceIDGen::GetNewUniqueID(); ResourceId mem4 = ResourceIDGen::GetNewUniqueID(); Sparse::PageTable srcPageTable; SECTION("Buffers") { SECTION("Same size") { pageTable.Initialise(320, 64); srcPageTable.Initialise(320, 64); srcPageTable.setBufferRange(0, mem0, 0, 320, false); pageTable.copyImageBoxRange(0, {0, 0, 0}, {5, 1, 1}, srcPageTable, 0, {0, 0, 0}); CHECK(srcPageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == srcPageTable.getMipTail().mappings[0].singleMapping); // copying two separate boxes won't coalesce pageTable.copyImageBoxRange(0, {0, 0, 0}, {4, 1, 1}, srcPageTable, 0, {0, 0, 0}); pageTable.copyImageBoxRange(0, {4, 0, 0}, {1, 1, 1}, srcPageTable, 0, {4, 0, 0}); CHECK(srcPageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 5, srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == srcPageTable.getMipTail().mappings[0].singleMapping); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 4, srcPageTable, 0, {0, 0, 0}); pageTable.copyImageWrappedRange(0, {4, 0, 0}, 1, srcPageTable, 0, {4, 0, 0}); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); }; SECTION("Source larger") { pageTable.Initialise(320, 64); srcPageTable.Initialise(640, 64); srcPageTable.setBufferRange(0, mem0, 0, 640, false); pageTable.copyImageBoxRange(0, {0, 0, 0}, {5, 1, 1}, srcPageTable, 0, {0, 0, 0}); CHECK(srcPageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == srcPageTable.getMipTail().mappings[0].singleMapping); // copying two separate boxes won't coalesce pageTable.copyImageBoxRange(0, {0, 0, 0}, {4, 1, 1}, srcPageTable, 0, {0, 0, 0}); pageTable.copyImageBoxRange(0, {4, 0, 0}, {1, 1, 1}, srcPageTable, 0, {4, 0, 0}); CHECK(srcPageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 5, srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].singleMapping == srcPageTable.getMipTail().mappings[0].singleMapping); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 4, srcPageTable, 0, {0, 0, 0}); pageTable.copyImageWrappedRange(0, {4, 0, 0}, 1, srcPageTable, 0, {4, 0, 0}); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); }; SECTION("Destination larger") { pageTable.Initialise(640, 64); srcPageTable.Initialise(320, 64); srcPageTable.setBufferRange(0, mem0, 0, 320, false); pageTable.copyImageBoxRange(0, {0, 0, 0}, {5, 1, 1}, srcPageTable, 0, {0, 0, 0}); CHECK(srcPageTable.getMipTail().mappings[0].hasSingleMapping()); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[5] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[6] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[7] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[8] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[9] == Sparse::Page({ResourceId(), 0})); // copying two separate boxes won't coalesce pageTable.copyImageBoxRange(0, {0, 0, 0}, {4, 1, 1}, srcPageTable, 0, {0, 0, 0}); pageTable.copyImageBoxRange(0, {4, 0, 0}, {1, 1, 1}, srcPageTable, 0, {4, 0, 0}); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[5] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[6] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[7] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[8] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[9] == Sparse::Page({ResourceId(), 0})); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 5, srcPageTable, 0, {0, 0, 0}); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[5] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[6] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[7] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[8] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[9] == Sparse::Page({ResourceId(), 0})); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 4, srcPageTable, 0, {0, 0, 0}); pageTable.copyImageWrappedRange(0, {4, 0, 0}, 1, srcPageTable, 0, {4, 0, 0}); REQUIRE_FALSE(pageTable.getMipTail().mappings[0].hasSingleMapping()); CHECK(pageTable.getMipTail().mappings[0].pages[0] == Sparse::Page({mem0, 0 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[1] == Sparse::Page({mem0, 1 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[2] == Sparse::Page({mem0, 2 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[3] == Sparse::Page({mem0, 3 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[4] == Sparse::Page({mem0, 4 * 64})); CHECK(pageTable.getMipTail().mappings[0].pages[5] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[6] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[7] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[8] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getMipTail().mappings[0].pages[9] == Sparse::Page({ResourceId(), 0})); }; }; SECTION("2D textures") { pageTable.Initialise({256, 256, 1}, 6, 1, 64, {32, 32, 1}, 4, 0x10000, 0x10000, 256); srcPageTable.Initialise({256, 256, 1}, 6, 1, 64, {32, 32, 1}, 4, 0x10000, 0x10000, 256); SECTION("Box copies") { srcPageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, mem0, 0, false); srcPageTable.setImageBoxRange(1, {0, 0, 0}, {128, 128, 1}, mem1, 0, false); srcPageTable.setImageBoxRange(2, {0, 0, 0}, {64, 64, 1}, mem2, 0, false); pageTable.copyImageBoxRange(0, {0, 0, 0}, {8, 8, 1}, srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({mem0, 0})); pageTable.copyImageBoxRange(1, {0, 0, 0}, {4, 4, 1}, srcPageTable, 1, {0, 0, 0}); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({mem1, 0})); srcPageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, mem3, 0, false); pageTable.copyImageBoxRange(0, {0, 0, 0}, {4, 4, 1}, srcPageTable, 0, {0, 0, 0}); REQUIRE_FALSE(pageTable.getSubresource(0).hasSingleMapping()); #undef _idx #define _idx(x, y) (y * 8 + x) CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem3, _idx(0, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem3, _idx(1, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem3, _idx(2, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 0)] == Sparse::Page({mem0, _idx(5, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 0)] == Sparse::Page({mem0, _idx(6, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 0)] == Sparse::Page({mem0, _idx(7, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 1)] == Sparse::Page({mem3, _idx(0, 1) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem3, _idx(1, 1) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem3, _idx(2, 1) * 64})); pageTable.copyImageBoxRange(0, {0, 0, 0}, {4, 4, 1}, srcPageTable, 1, {0, 0, 0}); REQUIRE_FALSE(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem1, 0 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem1, 1 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem1, 2 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 0)] == Sparse::Page({mem0, _idx(5, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 0)] == Sparse::Page({mem0, _idx(6, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 0)] == Sparse::Page({mem0, _idx(7, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 1)] == Sparse::Page({mem1, 4 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem1, 5 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem1, 6 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 3)] == Sparse::Page({mem1, 12 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 3)] == Sparse::Page({mem1, 13 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 3)] == Sparse::Page({mem1, 14 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 4)] == Sparse::Page({mem0, _idx(4, 4) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 4)] == Sparse::Page({mem0, _idx(5, 4) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 4)] == Sparse::Page({mem0, _idx(6, 4) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 5)] == Sparse::Page({mem0, _idx(4, 5) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 5)] == Sparse::Page({mem0, _idx(5, 5) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 5)] == Sparse::Page({mem0, _idx(6, 5) * 64})); pageTable.copyImageBoxRange(0, {4, 4, 0}, {4, 4, 1}, srcPageTable, 1, {0, 0, 0}); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({mem1, 0 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({mem1, 1 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({mem1, 2 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 0)] == Sparse::Page({mem0, _idx(5, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 0)] == Sparse::Page({mem0, _idx(6, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 0)] == Sparse::Page({mem0, _idx(7, 0) * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 1)] == Sparse::Page({mem1, 4 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({mem1, 5 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({mem1, 6 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 3)] == Sparse::Page({mem1, 12 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 3)] == Sparse::Page({mem1, 13 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 3)] == Sparse::Page({mem1, 14 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 4)] == Sparse::Page({mem1, 0 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 4)] == Sparse::Page({mem1, 1 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 4)] == Sparse::Page({mem1, 2 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(4, 5)] == Sparse::Page({mem1, 4 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 5)] == Sparse::Page({mem1, 5 * 64})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 5)] == Sparse::Page({mem1, 6 * 64})); }; SECTION("Wrapped copies preserving single mapping") { srcPageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, mem0, 0, false); srcPageTable.setImageBoxRange(1, {0, 0, 0}, {128, 128, 1}, mem1, 0, false); srcPageTable.setImageBoxRange(2, {0, 0, 0}, {64, 64, 1}, mem2, 0, false); pageTable.copyImageWrappedRange(0, {0, 0, 0}, 8 * 8, srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({mem0, 0})); pageTable.copyImageWrappedRange(1, {0, 0, 0}, 4 * 4, srcPageTable, 1, {0, 0, 0}); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({mem1, 0})); // copying from a larger mip into a smaller one just copies the tiles literally, even if // the tiles don't wrap the same way in each case pageTable.copyImageWrappedRange(1, {0, 0, 0}, 4 * 4, srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({mem0, 0})); // this copies the top 3 subresources all together pageTable.copyImageWrappedRange(0, {0, 0, 0}, (8 * 8 + 4 * 4 + 2 * 2), srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getSubresource(0).hasSingleMapping()); CHECK(pageTable.getSubresource(0).singleMapping == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(1).hasSingleMapping()); CHECK(pageTable.getSubresource(1).singleMapping == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(2).hasSingleMapping()); CHECK(pageTable.getSubresource(2).singleMapping == Sparse::Page({mem2, 0})); }; SECTION("Wrapped copies splitting pages") { srcPageTable.setImageBoxRange(0, {0, 0, 0}, {256, 256, 1}, mem0, 0, false); srcPageTable.setImageBoxRange(1, {0, 0, 0}, {128, 128, 1}, mem1, 0, false); srcPageTable.setImageBoxRange(2, {0, 0, 0}, {64, 64, 1}, mem2, 0, false); pageTable.copyImageWrappedRange(0, {5, 0, 0}, 2, srcPageTable, 0, {0, 0, 0}); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 0)] == Sparse::Page({mem0, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 3)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 4)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 4)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 4)] == Sparse::Page({ResourceId(), 0})); pageTable.copyImageWrappedRange(0, {0, 3, 0}, 10, srcPageTable, 1, {0, 0, 0}); CHECK(pageTable.getSubresource(0).pages[_idx(0, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 0)] == Sparse::Page({mem0, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 0)] == Sparse::Page({mem0, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 0)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 1)] == Sparse::Page({ResourceId(), 0})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 3)] == Sparse::Page({mem1, 0})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 3)] == Sparse::Page({mem1, 64})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 3)] == Sparse::Page({mem1, 128})); CHECK(pageTable.getSubresource(0).pages[_idx(5, 3)] == Sparse::Page({mem1, 320})); CHECK(pageTable.getSubresource(0).pages[_idx(6, 3)] == Sparse::Page({mem1, 384})); CHECK(pageTable.getSubresource(0).pages[_idx(7, 3)] == Sparse::Page({mem1, 448})); CHECK(pageTable.getSubresource(0).pages[_idx(0, 4)] == Sparse::Page({mem1, 512})); CHECK(pageTable.getSubresource(0).pages[_idx(1, 4)] == Sparse::Page({mem1, 576})); CHECK(pageTable.getSubresource(0).pages[_idx(2, 4)] == Sparse::Page({ResourceId(), 0})); }; }; }; }; #endif // ENABLED(ENABLE_UNIT_TESTS)
47.206857
102
0.65578
[ "3d" ]
e7a9a29519888d863669d7efe29a16e0cf6fd293
41,932
cpp
C++
thirdparty/physx/APEXSDK/module/clothing/src/ModuleClothing.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
thirdparty/physx/APEXSDK/module/clothing/src/ModuleClothing.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
thirdparty/physx/APEXSDK/module/clothing/src/ModuleClothing.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "NxApexDefs.h" #include "MinPhysxSdkVersion.h" #if NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED #include "ApexAuthorableObject.h" #include "ApexIsoMesh.h" #include "ApexSubdivider.h" #include "ApexSharedUtils.h" #include "NiApexRenderMeshAsset.h" #include <limits.h> #include <new> #if NX_SDK_VERSION_MAJOR == 2 #include "NxPhysicsSDK.h" #endif #include "PxCudaContextManager.h" #include "Factory.h" #include "ModuleClothing.h" #include "ClothingAsset.h" #include "ClothingAssetAuthoring.h" #include "ClothingPhysicalMesh.h" #include "ClothingIsoMesh.h" #include "NiApexScene.h" #include "ClothingScene.h" #include "NxFromPx.h" #include "ModulePerfScope.h" #include "CookingPhysX.h" #include "CookingPhysX3.h" #include "SimulationPhysX3.h" #if NX_SDK_VERSION_MAJOR == 2 #include "SimulationNxCloth.h" #include "SimulationNxSoftBody.h" #endif #endif #include "NiApexSDK.h" #include "PsShare.h" #ifdef PX_WINDOWS #include "CuFactory.h" #endif #include "PVDBinding.h" #include "PvdDataStream.h" using namespace clothing; using namespace physx::debugger; #define INIT_PVD_CLASSES_PARAMETERIZED( parameterizedClassName ) { \ pvdStream.createClass(NamespacedName(APEX_PVD_NAMESPACE, #parameterizedClassName)); \ parameterizedClassName* params = DYNAMIC_CAST(parameterizedClassName*)(NiGetApexSDK()->getParameterizedTraits()->createNxParameterized(#parameterizedClassName)); \ pvdBinding->initPvdClasses(*params->rootParameterDefinition(), #parameterizedClassName); \ params->destroy(); } namespace physx { namespace apex { #if defined(_USRDLL) /* Modules don't have to link against the framework, they keep their own */ NiApexSDK* gApexSdk = 0; NxApexSDK* NxGetApexSDK() { return gApexSdk; } NiApexSDK* NiGetApexSDK() { return gApexSdk; } NXAPEX_API NxModule* NX_CALL_CONV createModule( NiApexSDK* inSdk, NiModule** niRef, physx::PxU32 APEXsdkVersion, physx::PxU32 PhysXsdkVersion, NxApexCreateError* errorCode) { using namespace clothing; if (APEXsdkVersion != NX_APEX_SDK_VERSION) { if (errorCode) { *errorCode = APEX_CE_WRONG_VERSION; } return NULL; } if (PhysXsdkVersion != NX_PHYSICS_SDK_VERSION) { if (errorCode) { *errorCode = APEX_CE_WRONG_VERSION; } return NULL; } #if NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED gApexSdk = inSdk; APEX_INIT_FOUNDATION(); initModuleProfiling(inSdk, "Clothing"); clothing::ModuleClothing* impl = PX_NEW(clothing::ModuleClothing)(inSdk); *niRef = (NiModule*) impl; return (NxModule*) impl; #else // NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED if (errorCode != NULL) { *errorCode = APEX_CE_WRONG_VERSION; } PX_UNUSED(niRef); PX_UNUSED(inSdk); return NULL; // Clothing Module can only compile against MIN_PHYSX_SDK_VERSION_REQUIRED or above #endif // NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED } #else // !defined(_USRDLL) /* Statically linking entry function */ void instantiateModuleClothing() { #if NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED using namespace clothing; NiApexSDK* sdk = NiGetApexSDK(); initModuleProfiling(sdk, "Clothing"); clothing::ModuleClothing* impl = PX_NEW(clothing::ModuleClothing)(sdk); sdk->registerExternalModule((NxModule*) impl, (NiModule*) impl); #endif } #endif // !defined(_USRDLL) namespace clothing { #if NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED // This is needed to have an actor assigned to every NxActor, even if they currently don't belong to an NxClothingActor class DummyActor : public NxApexActor, public physx::UserAllocated, public ApexRWLockable { public: APEX_RW_LOCKABLE_BOILERPLATE DummyActor(NxApexAsset* owner) : mOwner(owner) {} void release() { PX_DELETE(this); } NxApexAsset* getOwner() const { return mOwner; } void getPhysicalLodRange(physx::PxF32& min, physx::PxF32& max, bool& intOnly) const { PX_UNUSED(min); PX_UNUSED(max); PX_UNUSED(intOnly); } physx::PxF32 getActivePhysicalLod() const { return -1.0f; } void forcePhysicalLod(physx::PxF32 lod) { PX_UNUSED(lod); } /** \brief Selectively enables/disables debug visualization of a specific APEX actor. Default value it true. */ virtual void setEnableDebugVisualization(bool state) { PX_UNUSED(state); } private: NxApexAsset* mOwner; }; // This is needed to for every dummy actor to point to an asset that in turn has the right object type id. class DummyAsset : public NxApexAsset, public physx::UserAllocated, public ApexRWLockable { public: APEX_RW_LOCKABLE_BOILERPLATE DummyAsset(NxAuthObjTypeID assetTypeID) : mAssetTypeID(assetTypeID) {}; void release() { PX_DELETE(this); } virtual const char* getName() const { return NULL; } virtual NxAuthObjTypeID getObjTypeID() const { return mAssetTypeID; } virtual const char* getObjTypeName() const { return NULL; } virtual PxU32 forceLoadAssets() { return 0; } virtual const NxParameterized::Interface* getAssetNxParameterized() const { return NULL; } NxParameterized::Interface* getDefaultActorDesc() { PX_ALWAYS_ASSERT(); return NULL; }; NxParameterized::Interface* getDefaultAssetPreviewDesc() { PX_ALWAYS_ASSERT(); return NULL; }; virtual NxApexActor* createApexActor(const NxParameterized::Interface& /*parms*/, NxApexScene& /*apexScene*/) { PX_ALWAYS_ASSERT(); return NULL; } virtual NxApexAssetPreview* createApexAssetPreview(const ::NxParameterized::Interface& /*params*/, NxApexAssetPreviewScene* /*previewScene*/) { PX_ALWAYS_ASSERT(); return NULL; } virtual bool isValidForActorCreation(const ::NxParameterized::Interface& /*parms*/, NxApexScene& /*apexScene*/) const { return true; // TODO implement this method } virtual bool isDirty() const { return false; } /** * \brief Releases the ApexAsset but returns the NxParameterized::Interface and *ownership* to the caller. */ virtual NxParameterized::Interface* releaseAndReturnNxParameterizedInterface(void) { return NULL; } private: NxAuthObjTypeID mAssetTypeID; }; ModuleClothing::ModuleClothing(NiApexSDK* inSdk) : mDummyActor(NULL) , mDummyAsset(NULL) , mModuleParams(NULL) , mApexClothingActorParams(NULL) , mApexClothingPreviewParams(NULL) , mCpuFactory(NULL) , mCpuFactoryReferenceCount(0) #ifdef PX_WINDOWS , mGpuDllHandle(NULL) , mPxCreateCuFactoryFunc(NULL) #endif { mInternalModuleParams.maxNumCompartments = 4; mInternalModuleParams.maxUnusedPhysXResources = 5; mInternalModuleParams.allowAsyncCooking = true; mInternalModuleParams.avgSimFrequencyWindow = 60; mInternalModuleParams.allowApexWorkBetweenSubsteps = true; mInternalModuleParams.interCollisionDistance = 0.0f; mInternalModuleParams.interCollisionStiffness = 1.0f; mInternalModuleParams.interCollisionIterations = 1; mInternalModuleParams.sparseSelfCollision = false; mInternalModuleParams.maxTimeRenderProxyInPool = 100; PX_COMPILE_TIME_ASSERT(sizeof(mInternalModuleParams) == 40); // don't forget to init the new param here (and then update this assert) name = "Clothing"; mSdk = inSdk; mApiProxy = this; NxParameterized::Traits* traits = mSdk->getParameterizedTraits(); if (traits) { # define PARAM_CLASS(clas) PARAM_CLASS_REGISTER_FACTORY(traits, clas) # include "ClothingParamClasses.inc" mApexClothingActorParams = traits->createNxParameterized(ClothingActorParam::staticClassName()); mApexClothingPreviewParams = traits->createNxParameterized(ClothingPreviewParam::staticClassName()); } // Set per-platform unit cost. One unit is one cloth vertex times one solver iteration #if defined( PX_WINDOWS ) || defined( PX_XBOXONE ) mLodUnitCost = 0.0001f; #elif defined( PX_PS4 ) mLodUnitCost = 0.0001f; #elif defined( PX_X360 ) mLodUnitCost = 0.001f; #elif defined( PX_PS3 ) mLodUnitCost = 0.001f; #elif defined( PX_ANDROID ) mLodUnitCost = 0.001f; #elif defined( PX_LINUX ) mLodUnitCost = 0.001f; #else // Using default value set in Module class #endif #ifdef PX_WINDOWS // // Since we split out the GPU code, we load the module and create the CuFactory ourselves // ApexSimpleString gpuClothingDllName; // PX_COMPILE_TIME_ASSERT(sizeof(HMODULE) == sizeof(mGpuDllHandle)); // { // ModuleUpdateLoader moduleLoader(UPDATE_LOADER_DLL_NAME); // // #define APEX_CLOTHING_GPU_DLL_PREFIX "APEX_ClothingGPU" // // #ifdef PX_PHYSX_DLL_NAME_POSTFIX // # if defined(PX_X86) // static const char* gpuClothingDllPrefix = APEX_CLOTHING_GPU_DLL_PREFIX PX_STRINGIZE(PX_PHYSX_DLL_NAME_POSTFIX) "_x86"; // # elif defined(PX_X64) // static const char* gpuClothingDllPrefix = APEX_CLOTHING_GPU_DLL_PREFIX PX_STRINGIZE(PX_PHYSX_DLL_NAME_POSTFIX) "_x64"; // # endif // #else // # if defined(PX_X86) // static const char* gpuClothingDllPrefix = APEX_CLOTHING_GPU_DLL_PREFIX "_x86"; // # elif defined(PX_X64) // static const char* gpuClothingDllPrefix = APEX_CLOTHING_GPU_DLL_PREFIX "_x64"; // # endif // #endif // // #undef APEX_CLOTHING_GPU_DLL_PREFIX // // gpuClothingDllName = ApexSimpleString(gpuClothingDllPrefix); // // // applications can append strings to the APEX DLL filenames, support this with getCustomDllNamePostfix() // gpuClothingDllName += ApexSimpleString(NiGetApexSDK()->getCustomDllNamePostfix()); // gpuClothingDllName += ApexSimpleString(".dll"); // // mGpuDllHandle = moduleLoader.loadModule(gpuClothingDllName.c_str(), NiGetApexSDK()->getAppGuid()); // } // // if (mGpuDllHandle) // { // mPxCreateCuFactoryFunc = (PxCreateCuFactory_FUNC*)GetProcAddress((HMODULE)mGpuDllHandle, "PxCreateCuFactory"); // if (mPxCreateCuFactoryFunc == NULL) // { // APEX_DEBUG_WARNING("Failed to find method PxCreateCuFactory in dll \'%s\'", gpuClothingDllName.c_str()); // FreeLibrary((HMODULE)mGpuDllHandle); // mGpuDllHandle = NULL; // } // } // else if (!gpuClothingDllName.empty()) // { // APEX_DEBUG_WARNING("Failed to load the GPU dll \'%s\'", gpuClothingDllName.c_str()); // } #endif } NxAuthObjTypeID ModuleClothing::getModuleID() const { return ClothingAsset::mAssetTypeID; } NxApexRenderableIterator* ModuleClothing::createRenderableIterator(const NxApexScene& apexScene) { ClothingScene* cs = getClothingScene(apexScene); if (cs) { return cs->createRenderableIterator(); } return NULL; } #ifdef WITHOUT_APEX_AUTHORING class ClothingAssetDummyAuthoring : public NxApexAssetAuthoring, public UserAllocated { public: ClothingAssetDummyAuthoring(ModuleClothing* module, NxResourceList& list, NxParameterized::Interface* params, const char* name) { PX_UNUSED(module); PX_UNUSED(list); PX_UNUSED(params); PX_UNUSED(name); } ClothingAssetDummyAuthoring(ModuleClothing* module, NxResourceList& list, const char* name) { PX_UNUSED(module); PX_UNUSED(list); PX_UNUSED(name); } ClothingAssetDummyAuthoring(ModuleClothing* module, NxResourceList& list) { PX_UNUSED(module); PX_UNUSED(list); } virtual ~ClothingAssetDummyAuthoring() {} virtual void setToolString(const char* /*toolName*/, const char* /*toolVersion*/, PxU32 /*toolChangelist*/) { } virtual void release() { destroy(); } // internal void destroy() { PX_DELETE(this); } /** * \brief Returns the name of this APEX authorable object type */ virtual const char* getObjTypeName() const { return NX_CLOTHING_AUTHORING_TYPE_NAME; } /** * \brief Prepares a fully authored Asset Authoring object for a specified platform */ virtual bool prepareForPlatform(physx::apex::NxPlatformTag) { PX_ASSERT(0); return false; } const char* getName(void) const { return NULL; } /** * \brief Save asset's NxParameterized interface, may return NULL */ virtual NxParameterized::Interface* getNxParameterized() const { PX_ASSERT(0); return NULL; //ClothingAsset::getAssetNxParameterized(); } virtual NxParameterized::Interface* releaseAndReturnNxParameterizedInterface(void) { PX_ALWAYS_ASSERT(); return NULL; } }; typedef ApexAuthorableObject<ModuleClothing, ClothingAsset, ClothingAssetDummyAuthoring> ClothingAO; #else typedef ApexAuthorableObject<ModuleClothing, ClothingAsset, ClothingAssetAuthoring> ClothingAO; #endif NxParameterized::Interface* ModuleClothing::getDefaultModuleDesc() { NxParameterized::Traits* traits = mSdk->getParameterizedTraits(); if (!mModuleParams) { mModuleParams = DYNAMIC_CAST(ClothingModuleParameters*) (traits->createNxParameterized("ClothingModuleParameters")); PX_ASSERT(mModuleParams); } else { mModuleParams->initDefaults(); } const NxParameterized::Hint* hint = NULL; NxParameterized::Handle h(mModuleParams); h.getParameter("maxNumCompartments"); PX_ASSERT(h.isValid()); #if defined(PX_WINDOWS) hint = h.parameterDefinition()->hint("defaultValueWindows"); #else hint = h.parameterDefinition()->hint("defaultValueConsoles"); #endif PX_ASSERT(hint); if (hint) { mModuleParams->maxNumCompartments = (physx::PxU32)hint->asUInt(); } return mModuleParams; } void ModuleClothing::init(NxParameterized::Interface& desc) { if (strcmp(desc.className(), ClothingModuleParameters::staticClassName()) == 0) { ClothingModuleParameters* params = DYNAMIC_CAST(ClothingModuleParameters*)(&desc); mInternalModuleParams = *params; } else { APEX_INVALID_PARAMETER("The NxParameterized::Interface object is of the wrong type"); } #if !defined(PX_WINDOWS) && NX_SDK_VERSION_MAJOR == 2 if (mInternalModuleParams.maxNumCompartments > 0) { APEX_DEBUG_WARNING("ModuleClothingDesc::maxNumCompartments > 0! On consoles performance is worse when using compartments for cloth and softbodies"); } #endif ClothingAO* AOClothingAsset = PX_NEW(ClothingAO)(this, mAssetAuthorableObjectFactories, ClothingAssetParameters::staticClassName()); ClothingAsset::mAssetTypeID = AOClothingAsset->getResID(); registerBackendFactory(&mBackendFactory); registerBackendFactory(&mBackendFactoryPhysX3); #ifndef WITHOUT_PVD AOClothingAsset->mAssets.setupForPvd(mApiProxy, "NxClothingAssets", "NxClothingAsset"); // handle case if module is created after pvd connection PVD::PvdBinding* pvdBinding = mSdk->getPvdBinding(); if (pvdBinding != NULL) { if (pvdBinding->getConnectionType() & PvdConnectionType::eDEBUG) { pvdBinding->lock(); physx::debugger::comm::PvdDataStream* pvdStream = pvdBinding->getDataStream(); if (pvdStream != NULL) { NamespacedName pvdModuleName(APEX_PVD_NAMESPACE, getName()); pvdStream->createClass(pvdModuleName); initPvdClasses(*pvdStream); NxModule* nxModule = static_cast<NxModule*>(this); pvdStream->createInstance(pvdModuleName, nxModule); pvdStream->pushBackObjectRef(mSdk, "NxModules", nxModule); initPvdInstances(*pvdStream); } pvdBinding->unlock(); } } #endif } NxClothingPhysicalMesh* ModuleClothing::createEmptyPhysicalMesh() { NX_WRITE_ZONE(); return createPhysicalMeshInternal(NULL); } NxClothingPhysicalMesh* ModuleClothing::createSingleLayeredMesh(NxRenderMeshAssetAuthoring* asset, PxU32 subdivisionSize, bool mergeVertices, bool closeHoles, IProgressListener* progress) { NX_WRITE_ZONE(); return createSingleLayeredMeshInternal(DYNAMIC_CAST(NiApexRenderMeshAssetAuthoring*)(asset), subdivisionSize, mergeVertices, closeHoles, progress); } NxClothingIsoMesh* ModuleClothing::createMultiLayeredMesh(NxRenderMeshAssetAuthoring* asset, PxU32 subdivisionSize, physx::PxU32 keepNBiggestMeshes, bool discardInnerMeshes, IProgressListener* progress) { NX_WRITE_ZONE(); return createMultiLayeredMeshInternal(DYNAMIC_CAST(NiApexRenderMeshAssetAuthoring*)(asset), subdivisionSize, keepNBiggestMeshes, discardInnerMeshes, progress); } void ModuleClothing::destroy() { mClothingSceneList.clear(); if (mApexClothingActorParams != NULL) { mApexClothingActorParams->destroy(); mApexClothingActorParams = NULL; } if (mApexClothingPreviewParams != NULL) { mApexClothingPreviewParams->destroy(); mApexClothingPreviewParams = NULL; } #ifdef PX_WINDOWS for (PxU32 i = 0; i < mGpuFactories.size(); i++) { //APEX_DEBUG_INFO("Release Gpu factory %d", i); PX_DELETE(mGpuFactories[i].factoryGpu); mGpuFactories.replaceWithLast(i); } #endif PX_DELETE(mCpuFactory); mCpuFactory = NULL; #ifndef WITHOUT_PVD destroyPvdInstances(); #endif if (mModuleParams != NULL) { mModuleParams->destroy(); mModuleParams = NULL; } if (mDummyActor != NULL) { mDummyActor->release(); mDummyActor = NULL; } if (mDummyAsset != NULL) { mDummyAsset->release(); mDummyAsset = NULL; } NxParameterized::Traits* traits = mSdk->getParameterizedTraits(); Module::destroy(); releaseModuleProfiling(); mAssetAuthorableObjectFactories.clear(); // needs to be done before destructor! #ifdef PX_WINDOWS if (mGpuDllHandle != NULL) { FreeLibrary((HMODULE)mGpuDllHandle); } #endif PX_DELETE(this); if (traits) { # define PARAM_CLASS(clas) PARAM_CLASS_REMOVE_FACTORY(traits, clas) # include "ClothingParamClasses.inc" } } NiModuleScene* ModuleClothing::createNiModuleScene(NiApexScene& scene, NiApexRenderDebug* renderDebug) { return PX_NEW(ClothingScene)(*this, scene, renderDebug, mClothingSceneList); } void ModuleClothing::releaseNiModuleScene(NiModuleScene& scene) { ClothingScene* clothingScene = DYNAMIC_CAST(ClothingScene*)(&scene); clothingScene->destroy(); } physx::PxU32 ModuleClothing::forceLoadAssets() { physx::PxU32 loadedAssetCount = 0; for (physx::PxU32 i = 0; i < mAssetAuthorableObjectFactories.getSize(); i++) { NiApexAuthorableObject* ao = static_cast<NiApexAuthorableObject*>(mAssetAuthorableObjectFactories.getResource(i)); loadedAssetCount += ao->forceLoadAssets(); } return loadedAssetCount; } #ifndef WITHOUT_PVD void ModuleClothing::initPvdClasses(physx::debugger::comm::PvdDataStream& pvdStream) { NamespacedName objRef = getPvdNamespacedNameForType<ObjectRef>(); // --------------------------------------- // Hierarchy // NxModule holds NxClothingAssets pvdStream.createClass(NamespacedName(APEX_PVD_NAMESPACE, "NxClothingAsset")); pvdStream.createProperty(NamespacedName(APEX_PVD_NAMESPACE, getName()), "NxClothingAssets", "children", objRef, PropertyType::Array); // NxClothingAsset holds NxClothingActors pvdStream.createClass(NamespacedName(APEX_PVD_NAMESPACE, "NxClothingActor")); pvdStream.createProperty(NamespacedName(APEX_PVD_NAMESPACE, "NxClothingAsset"), "NxClothingActors", "children", objRef, PropertyType::Array); // --------------------------------------- // NxParameterized PVD::PvdBinding* pvdBinding = NxGetApexSDK()->getPvdBinding(); PX_ASSERT(pvdBinding != NULL); // Module Params INIT_PVD_CLASSES_PARAMETERIZED(ClothingModuleParameters); pvdStream.createProperty(NamespacedName(APEX_PVD_NAMESPACE, getName()), "ModuleParams", "", objRef, PropertyType::Scalar); // Asset Params INIT_PVD_CLASSES_PARAMETERIZED(ClothingPhysicalMeshParameters); INIT_PVD_CLASSES_PARAMETERIZED(ClothingGraphicalLodParameters); INIT_PVD_CLASSES_PARAMETERIZED(ClothingCookedParam); INIT_PVD_CLASSES_PARAMETERIZED(ClothingCookedPhysX3Param); INIT_PVD_CLASSES_PARAMETERIZED(ClothingMaterialLibraryParameters); INIT_PVD_CLASSES_PARAMETERIZED(ClothingAssetParameters); pvdStream.createProperty(NamespacedName(APEX_PVD_NAMESPACE, "NxClothingAsset"), "AssetParams", "", objRef, PropertyType::Scalar); // Actor Params INIT_PVD_CLASSES_PARAMETERIZED(ClothingActorParam); pvdStream.createProperty(NamespacedName(APEX_PVD_NAMESPACE, "NxClothingActor"), "ActorParams", "", objRef, PropertyType::Scalar); // --------------------------------------- // Additional Properties // --------------------------------------- } void ModuleClothing::initPvdInstances(physx::debugger::comm::PvdDataStream& pvdStream) { // if there's more than one AOFactory we don't know any more for sure that its a clothing asset factory, so we have to adapt the code below PX_ASSERT(mAssetAuthorableObjectFactories.getSize() == 1 && "Adapt the code below"); PVD::PvdBinding* pvdBinding = NxGetApexSDK()->getPvdBinding(); PX_ASSERT(pvdBinding != NULL); // Module Params pvdStream.createInstance(NamespacedName(APEX_PVD_NAMESPACE, "ClothingModuleParameters"), mModuleParams); pvdStream.setPropertyValue(mApiProxy, "ModuleParams", DataRef<const PxU8>((const PxU8*)&mModuleParams, sizeof(ClothingModuleParameters*)), getPvdNamespacedNameForType<ObjectRef>()); // update module properties (should we do this per frame? if so, how?) pvdBinding->updatePvd(mModuleParams, *mModuleParams); // prepare asset list and forward init calls NiApexAuthorableObject* ao = static_cast<NiApexAuthorableObject*>(mAssetAuthorableObjectFactories.getResource(0)); ao->mAssets.initPvdInstances(pvdStream); } void ModuleClothing::destroyPvdInstances() { PVD::PvdBinding* pvdBinding = NxGetApexSDK()->getPvdBinding(); if (pvdBinding != NULL) { if (pvdBinding->getConnectionType() & PvdConnectionType::eDEBUG) { pvdBinding->lock(); physx::debugger::comm::PvdDataStream* pvdStream = pvdBinding->getDataStream(); { if (pvdStream != NULL) { pvdBinding->updatePvd(mModuleParams, *mModuleParams, PVD::PvdAction::DESTROY); pvdStream->destroyInstance(mModuleParams); } } pvdBinding->unlock(); } } } #endif ClothingScene* ModuleClothing::getClothingScene(const NxApexScene& apexScene) { const NiApexScene* niScene = DYNAMIC_CAST(const NiApexScene*)(&apexScene); for (physx::PxU32 i = 0 ; i < mClothingSceneList.getSize() ; i++) { ClothingScene* clothingScene = DYNAMIC_CAST(ClothingScene*)(mClothingSceneList.getResource(i)); if (clothingScene->mApexScene == niScene) { return clothingScene; } } PX_ASSERT(!"Unable to locate an appropriate ClothingScene"); return NULL; } ClothingPhysicalMesh* ModuleClothing::createPhysicalMeshInternal(ClothingPhysicalMeshParameters* mesh) { ClothingPhysicalMesh* result = PX_NEW(ClothingPhysicalMesh)(this, mesh, &mPhysicalMeshes); return result; } void ModuleClothing::releasePhysicalMesh(ClothingPhysicalMesh* physicalMesh) { physicalMesh->destroy(); } void ModuleClothing::releaseIsoMesh(ClothingIsoMesh* isoMesh) { isoMesh->destroy(); } void ModuleClothing::unregisterAssetWithScenes(ClothingAsset* asset) { for (physx::PxU32 i = 0; i < mClothingSceneList.getSize(); i++) { ClothingScene* clothingScene = static_cast<ClothingScene*>(mClothingSceneList.getResource(i)); clothingScene->unregisterAsset(asset); } } void ModuleClothing::notifyReleaseGraphicalData(ClothingAsset* asset) { for (physx::PxU32 i = 0; i < mClothingSceneList.getSize(); i++) { ClothingScene* clothingScene = static_cast<ClothingScene*>(mClothingSceneList.getResource(i)); clothingScene->removeRenderProxies(asset); } } NxApexActor* ModuleClothing::getDummyActor() { mDummyProtector.lock(); if (mDummyActor == NULL) { PX_ASSERT(mDummyAsset == NULL); mDummyAsset = PX_NEW(DummyAsset)(getModuleID()); mDummyActor = PX_NEW(DummyActor)(mDummyAsset); } mDummyProtector.unlock(); return mDummyActor; } void ModuleClothing::registerBackendFactory(BackendFactory* factory) { for (PxU32 i = 0; i < mBackendFactories.size(); i++) { if (strcmp(mBackendFactories[i]->getName(), factory->getName()) == 0) { return; } } mBackendFactories.pushBack(factory); } void ModuleClothing::unregisterBackendFactory(BackendFactory* factory) { PxU32 read = 0, write = 0; while (read < mBackendFactories.size()) { mBackendFactories[write] = mBackendFactories[read]; if (mBackendFactories[read] == factory) { read++; } else { read++, write++; } } while (read < write) { mBackendFactories.popBack(); } } BackendFactory* ModuleClothing::getBackendFactory(const char* simulationBackend) { PX_ASSERT(simulationBackend != NULL); for (PxU32 i = 0; i < mBackendFactories.size(); i++) { if (mBackendFactories[i]->isMatch(simulationBackend)) { return mBackendFactories[i]; } } //APEX_INVALID_OPERATION("Simulation back end \'%s\' not found, using \'PhysX\' instead\n", simulationBackend); PX_ASSERT(mBackendFactories.size() >= 1); PX_ASSERT(strcmp(mBackendFactories[0]->getName(), "Native") == 0); return mBackendFactories[0]; } ClothFactory ModuleClothing::createClothFactory(physx::PxCudaContextManager* contextManager) { shdfnd::Mutex::ScopedLock lock(mFactoryMutex); #ifdef PX_WINDOWS #if NX_SDK_VERSION_MAJOR == 2 if (contextManager != NULL) #elif NX_SDK_VERSION_MAJOR == 3 if (contextManager != NULL && contextManager->supportsArchSM20()) #endif // NX_SDK_VERSION_MAJOR { for (PxU32 i = 0; i < mGpuFactories.size(); i++) { if (mGpuFactories[i].contextManager == contextManager) { mGpuFactories[i].referenceCount++; //APEX_DEBUG_INFO("Found Gpu factory %d (ref = %d)", i, mGpuFactories[i].referenceCount); return ClothFactory(mGpuFactories[i].factoryGpu, &mFactoryMutex); } } // nothing found if (mPxCreateCuFactoryFunc != NULL) { GpuFactoryEntry entry(mPxCreateCuFactoryFunc(contextManager), contextManager); if (entry.factoryGpu != NULL) { //APEX_DEBUG_INFO("Create Gpu factory %d", mGpuFactories.size()); entry.referenceCount = 1; mGpuFactories.pushBack(entry); return ClothFactory(entry.factoryGpu, &mFactoryMutex); } } return ClothFactory(NULL, &mFactoryMutex); } else #else PX_UNUSED(contextManager); #endif { if (mCpuFactory == NULL) { mCpuFactory = cloth::Factory::createFactory(cloth::Factory::CPU); //APEX_DEBUG_INFO("Create Cpu factory"); PX_ASSERT(mCpuFactoryReferenceCount == 0); } mCpuFactoryReferenceCount++; //APEX_DEBUG_INFO("Get Cpu factory (ref = %d)", mCpuFactoryReferenceCount); return ClothFactory(mCpuFactory, &mFactoryMutex); } } void ModuleClothing::releaseClothFactory(physx::PxCudaContextManager* contextManager) { shdfnd::Mutex::ScopedLock lock(mFactoryMutex); #ifdef PX_WINDOWS if (contextManager != NULL) { for (PxU32 i = 0; i < mGpuFactories.size(); i++) { if (mGpuFactories[i].contextManager == contextManager) { PX_ASSERT(mGpuFactories[i].referenceCount > 0); mGpuFactories[i].referenceCount--; //APEX_DEBUG_INFO("Found Gpu factory %d (ref = %d)", i, mGpuFactories[i].referenceCount); if (mGpuFactories[i].referenceCount == 0) { //APEX_DEBUG_INFO("Release Gpu factory %d", i); PX_DELETE(mGpuFactories[i].factoryGpu); mGpuFactories.replaceWithLast(i); } } } } else #else PX_UNUSED(contextManager); #endif { PX_ASSERT(mCpuFactoryReferenceCount > 0); mCpuFactoryReferenceCount--; //APEX_DEBUG_INFO("Release Cpu factory (ref = %d)", mCpuFactoryReferenceCount); if (mCpuFactoryReferenceCount == 0) { PX_DELETE(mCpuFactory); mCpuFactory = NULL; } } } NxClothingPhysicalMesh* ModuleClothing::createSingleLayeredMeshInternal(NiApexRenderMeshAssetAuthoring* renderMeshAsset, PxU32 subdivisionSize, bool mergeVertices, bool closeHoles, IProgressListener* progressListener) { if (renderMeshAsset->getPartCount() > 1) { APEX_INVALID_PARAMETER("NxRenderMeshAssetAuthoring has more than one part (%d)", renderMeshAsset->getPartCount()); return NULL; } if (subdivisionSize > 200) { APEX_INVALID_PARAMETER("subdivisionSize must be smaller or equal to 200 and has been clamped (was %d).", subdivisionSize); subdivisionSize = 200; } HierarchicalProgressListener progress(100, progressListener); PxU32 numGraphicalVertices = 0; for (PxU32 i = 0; i < renderMeshAsset->getSubmeshCount(); i++) { const NiApexRenderSubmesh& submesh = renderMeshAsset->getNiSubmesh(i); numGraphicalVertices += submesh.getVertexBuffer().getVertexCount(); } ClothingPhysicalMesh* physicalMesh = DYNAMIC_CAST(ClothingPhysicalMesh*)(createEmptyPhysicalMesh()); // set time for registration, merge, close and subdivision PxU32 times[4] = { 20, (PxU32)(mergeVertices ? 20 : 0), (PxU32)(closeHoles ? 30 : 0), (PxU32)(subdivisionSize > 0 ? 30 : 0) }; PxU32 sum = times[0] + times[1] + times[2] + times[3]; for (PxU32 i = 0; i < 4; i++) { times[i] = 100 * times[i] / sum; } progress.setSubtaskWork((physx::PxI32)times[0], "Creating single layered mesh"); ApexSubdivider subdivider; Array<PxI32> old2New(numGraphicalVertices, -1); PxU32 nbVertices = 0; PxU32 vertexOffset = 0; for (PxU32 submeshNr = 0; submeshNr < renderMeshAsset->getSubmeshCount(); submeshNr++) { const NiApexRenderSubmesh& submesh = renderMeshAsset->getNiSubmesh(submeshNr); // used for physics? const NxVertexFormat& vf = submesh.getVertexBuffer().getFormat(); PxU32 customIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getID("USED_FOR_PHYSICS")); NxRenderDataFormat::Enum outFormat = vf.getBufferFormat(customIndex); const PxU8* usedForPhysics = NULL; if (outFormat == NxRenderDataFormat::UBYTE1) { usedForPhysics = (const PxU8*)submesh.getVertexBuffer().getBuffer(customIndex); } customIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getID("LATCH_TO_NEAREST_SLAVE")); outFormat = vf.getBufferFormat(customIndex); const PxU32* latchToNearestSlave = outFormat != NxRenderDataFormat::UINT1 ? NULL : (PxU32*)submesh.getVertexBuffer().getBuffer(customIndex); customIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getID("LATCH_TO_NEAREST_MASTER")); outFormat = vf.getBufferFormat(customIndex); const PxU32* latchToNearestMaster = outFormat != NxRenderDataFormat::UINT1 ? NULL : (PxU32*)submesh.getVertexBuffer().getBuffer(customIndex); PX_ASSERT((latchToNearestSlave != NULL) == (latchToNearestMaster != NULL)); // both NULL or not NULL // triangles const PxU32* indices = submesh.getIndexBuffer(0); // only 1 part supported! // vertices NxRenderDataFormat::Enum format; PxU32 bufferIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getSemanticID(NxRenderVertexSemantic::POSITION)); const PxVec3* positions = (const PxVec3*)submesh.getVertexBuffer().getBufferAndFormat(format, bufferIndex); if (format != NxRenderDataFormat::FLOAT3) { PX_ALWAYS_ASSERT(); positions = NULL; } const PxU32 submeshIndices = submesh.getIndexCount(0); for (PxU32 meshIndex = 0; meshIndex < submeshIndices; meshIndex += 3) { if (latchToNearestSlave != NULL) { PxU32 numVerticesOk = 0; for (PxU32 i = 0; i < 3; i++) { const PxU32 index = indices[meshIndex + i]; numVerticesOk += latchToNearestSlave[index] == 0 ? 1u : 0u; } if (numVerticesOk < 3) { continue; // skip this triangle } } else if (usedForPhysics != NULL) { PxU32 numVerticesOk = 0; for (PxU32 i = 0; i < 3; i++) { const PxU32 index = indices[meshIndex + i]; numVerticesOk += usedForPhysics[index] == 0 ? 0u : 1u; } if (numVerticesOk < 3) { continue; // skip this triangle } } // add triangle to subdivider for (PxU32 i = 0; i < 3; i++) { const PxU32 localIndex = indices[meshIndex + i]; const PxU32 index = localIndex + vertexOffset; if (old2New[index] == -1) { old2New[index] = (physx::PxI32)nbVertices++; PxU32 master = latchToNearestMaster != NULL ? latchToNearestMaster[localIndex] : 0xffffffffu; subdivider.registerVertex(positions[localIndex], master); } } const PxU32 i0 = (physx::PxU32)old2New[indices[meshIndex + 0] + vertexOffset]; const PxU32 i1 = (physx::PxU32)old2New[indices[meshIndex + 1] + vertexOffset]; const PxU32 i2 = (physx::PxU32)old2New[indices[meshIndex + 2] + vertexOffset]; subdivider.registerTriangle(i0, i1, i2); } vertexOffset += submesh.getVertexBuffer().getVertexCount(); } subdivider.endRegistration(); progress.completeSubtask(); if (nbVertices == 0) { APEX_INVALID_PARAMETER("Mesh has no active vertices (see Physics on/off channel)"); return NULL; } // use subdivider if (mergeVertices) { progress.setSubtaskWork((physx::PxI32)times[1], "Merging"); subdivider.mergeVertices(&progress); progress.completeSubtask(); } if (closeHoles) { progress.setSubtaskWork((physx::PxI32)times[2], "Closing holes"); subdivider.closeMesh(&progress); progress.completeSubtask(); } if (subdivisionSize > 0) { progress.setSubtaskWork((physx::PxI32)times[3], "Subdividing"); subdivider.subdivide(subdivisionSize, &progress); progress.completeSubtask(); } Array<PxVec3> newVertices(subdivider.getNumVertices()); Array<PxU32> newMasterValues(subdivider.getNumVertices()); for (PxU32 i = 0; i < newVertices.size(); i++) { subdivider.getVertex(i, newVertices[i], newMasterValues[i]); } Array<PxU32> newIndices(subdivider.getNumTriangles() * 3); for (PxU32 i = 0; i < newIndices.size(); i += 3) { subdivider.getTriangle(i / 3, newIndices[i], newIndices[i + 1], newIndices[i + 2]); } physicalMesh->setGeometry(false, newVertices.size(), sizeof(PxVec3), newVertices.begin(), newMasterValues.begin(), newIndices.size(), sizeof(PxU32), &newIndices[0]); return physicalMesh; } NxClothingIsoMesh* ModuleClothing::createMultiLayeredMeshInternal(NiApexRenderMeshAssetAuthoring* renderMeshAsset, PxU32 subdivisionSize, PxU32 keepNBiggestMeshes, bool discardInnerMeshes, IProgressListener* progressListener) { if (renderMeshAsset->getPartCount() != 1) { APEX_INTERNAL_ERROR("Input mesh must have exactly one part (has %d)", renderMeshAsset->getPartCount()); return NULL; } if (subdivisionSize > 200) { APEX_INVALID_PARAMETER("subdivisionSize must be smaller or equal to 200 and has been clamped (was %d).", subdivisionSize); subdivisionSize = 200; } ApexIsoMesh isoMesh(subdivisionSize, keepNBiggestMeshes, discardInnerMeshes); isoMesh.setBound(renderMeshAsset->getBounds(0)); HierarchicalProgressListener progress(100, progressListener); progress.setSubtaskWork(90, "Initializing Iso Mesh"); for (PxU32 submeshNr = 0; submeshNr < renderMeshAsset->getSubmeshCount(); submeshNr++) { const NiApexRenderSubmesh& submesh = renderMeshAsset->getNiSubmesh(submeshNr); NxRenderDataFormat::Enum positionFormat; const NxVertexBuffer& vb = submesh.getVertexBuffer(); const NxVertexFormat& vf = vb.getFormat(); PxU32 bufferIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getSemanticID(NxRenderVertexSemantic::POSITION)); const PxVec3* positions = (const PxVec3*)vb.getBufferAndFormat(positionFormat, bufferIndex); PX_ASSERT(positionFormat == physx::NxRenderDataFormat::FLOAT3); // triangles const PxU32* indices = submesh.getIndexBuffer(0); // used for physics PxU32 customIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getID("USED_FOR_PHYSICS")); NxRenderDataFormat::Enum outFormat = vf.getBufferFormat(customIndex); const PxU8* usedForPhysics = NULL; if (outFormat == NxRenderDataFormat::UBYTE1) { usedForPhysics = (const PxU8*)vb.getBuffer(customIndex); } customIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getID("LATCH_TO_NEAREST_SLAVE")); outFormat = vf.getBufferFormat(customIndex); const PxU32* latchToNearestSlave = outFormat != NxRenderDataFormat::UINT1 ? NULL : (PxU32*)submesh.getVertexBuffer().getBuffer(customIndex); customIndex = (physx::PxU32)vf.getBufferIndexFromID(vf.getID("LATCH_TO_NEAREST_MASTER")); outFormat = vf.getBufferFormat(customIndex); const PxU32* latchToNearestMaster = outFormat != NxRenderDataFormat::UINT1 ? NULL : (PxU32*)submesh.getVertexBuffer().getBuffer(customIndex); PX_ASSERT((latchToNearestSlave != NULL) == (latchToNearestMaster != NULL)); // both NULL or not NULL PX_UNUSED(latchToNearestMaster); const PxU32 submeshIndices = submesh.getIndexCount(0); for (PxU32 meshIndex = 0; meshIndex < submeshIndices; meshIndex += 3) { if (latchToNearestSlave != NULL) { PxU32 numVerticesOk = 0; for (PxU32 i = 0; i < 3; i++) { const PxU32 index = indices[meshIndex + i]; numVerticesOk += latchToNearestSlave[index] == 0 ? 1u : 0u; } if (numVerticesOk < 3) { continue; // skip this triangle } } else if (usedForPhysics != NULL) { PxU32 numVerticesOk = 0; for (PxU32 k = 0; k < 3; k++) { const PxU32 index = indices[meshIndex + k]; numVerticesOk += usedForPhysics[index] == 0 ? 0u : 1u; } if (numVerticesOk < 3) { continue; // skip this triangle } } isoMesh.addTriangle(positions[indices[meshIndex + 0]], positions[indices[meshIndex + 1]], positions[indices[meshIndex + 2]]); } } isoMesh.update(&progress); progress.completeSubtask(); progress.setSubtaskWork(10, "Copying Iso Mesh"); ClothingIsoMesh* clothingIsoMesh = PX_NEW(ClothingIsoMesh)(this, isoMesh, subdivisionSize, &mIsoMeshes); progress.completeSubtask(); return clothingIsoMesh; } bool ModuleClothing::ClothingBackendFactory::isMatch(const char* simulationBackend) { if (strcmp(getName(), simulationBackend) == 0) { return true; } if (strcmp(ClothingCookedParam::staticClassName(), simulationBackend) == 0) { return true; } return false; } const char* ModuleClothing::ClothingBackendFactory::getName() { return "Native"; } /*const char* ModuleClothing::ClothingBackendFactory::getCookingJobType() { return ClothingCookedParam::staticClassName(); }*/ PxU32 ModuleClothing::ClothingBackendFactory::getCookingVersion() { return CookingPhysX::getCookingVersion(); } PxU32 ModuleClothing::ClothingBackendFactory::getCookedDataVersion(const NxParameterized::Interface* cookedData) { if (cookedData != NULL && isMatch(cookedData->className())) { return ((ClothingCookedParam*)cookedData)->cookedDataVersion; } return 0; } CookingAbstract* ModuleClothing::ClothingBackendFactory::createCookingJob() { return PX_NEW(CookingPhysX)(); } void ModuleClothing::ClothingBackendFactory::releaseCookedInstances(NxParameterized::Interface* _cookedData, bool tetraMesh) { if (_cookedData != NULL) { PX_ASSERT(strcmp(_cookedData->className(), ClothingCookedParam::staticClassName()) == 0); ClothingCookedParam* cookedData = static_cast<ClothingCookedParam*>(_cookedData); #if NX_SDK_VERSION_MAJOR == 2 NxPhysicsSDK* pSDK = NiGetApexSDK()->getPhysXSDK(); #endif for (PxI32 i = 0; i < cookedData->convexMeshPointers.arraySizes[0]; i++) { #if NX_SDK_VERSION_MAJOR == 2 NxConvexMesh* convexMesh = reinterpret_cast<NxConvexMesh*>(cookedData->convexMeshPointers.buf[i]); if (convexMesh != NULL) { pSDK->releaseConvexMesh(*convexMesh); } #elif NX_SDK_VERSION_MAJOR == 3 PX_ALWAYS_ASSERT(); #endif cookedData->convexMeshPointers.buf[i] = NULL; } for (PxI32 i = 0; i < cookedData->cookedPhysicalSubmeshes.arraySizes[0]; i++) { if (tetraMesh) { #if NX_SDK_VERSION_MAJOR == 2 NxSoftBodyMesh* mesh = reinterpret_cast<NxSoftBodyMesh*>(cookedData->cookedPhysicalSubmeshes.buf[i].deformableMeshPointer); if (mesh != NULL) { pSDK->releaseSoftBodyMesh(*mesh); } #elif NX_SDK_VERSION_MAJOR == 3 PX_ALWAYS_ASSERT(); #endif } else { #if NX_SDK_VERSION_MAJOR == 2 NxClothMesh* mesh = reinterpret_cast<NxClothMesh*>(cookedData->cookedPhysicalSubmeshes.buf[i].deformableMeshPointer); if (mesh != NULL) { pSDK->releaseClothMesh(*mesh); } #elif NX_SDK_VERSION_MAJOR == 3 PX_ALWAYS_ASSERT(); #endif } cookedData->cookedPhysicalSubmeshes.buf[i].deformableMeshPointer = NULL; PX_ASSERT(cookedData->cookedPhysicalSubmeshes.buf[i].deformableMeshPointer == NULL); } } } SimulationAbstract* ModuleClothing::ClothingBackendFactory::createSimulation(bool tetraMesh, ClothingScene* clothingScene, bool useHW) { if (tetraMesh) { #if NX_SDK_VERSION_MAJOR == 2 return PX_NEW(SimulationNxSoftBody)(clothingScene, useHW); #elif NX_SDK_VERSION_MAJOR == 3 PX_ALWAYS_ASSERT(); PX_UNUSED(clothingScene); PX_UNUSED(useHW); return NULL; #endif } else { #if NX_SDK_VERSION_MAJOR == 2 return PX_NEW(SimulationNxCloth)(clothingScene, useHW); #elif NX_SDK_VERSION_MAJOR == 3 // PH: We only get here when the user specifies 'ForceNative' in the actor desc's 'simulationBackend'. // Since there is no native solver (we ditched 3.2 PxCloth support) we should return NULL return NULL; #endif } } bool ModuleClothing::ClothingPhysX3Backend::isMatch(const char* simulationBackend) { if (strcmp(getName(), simulationBackend) == 0) { return true; } if (strcmp(ClothingCookedPhysX3Param::staticClassName(), simulationBackend) == 0) { return true; } return false; } const char* ModuleClothing::ClothingPhysX3Backend::getName() { return "Embedded"; } PxU32 ModuleClothing::ClothingPhysX3Backend::getCookingVersion() { return CookingPhysX3::getCookingVersion(); } PxU32 ModuleClothing::ClothingPhysX3Backend::getCookedDataVersion(const NxParameterized::Interface* cookedData) { if (cookedData != NULL && isMatch(cookedData->className())) { return static_cast<const ClothingCookedPhysX3Param*>(cookedData)->cookedDataVersion; } return 0; } CookingAbstract* ModuleClothing::ClothingPhysX3Backend::createCookingJob() { bool withFibers = true; return PX_NEW(CookingPhysX3)(withFibers); } void ModuleClothing::ClothingPhysX3Backend::releaseCookedInstances(NxParameterized::Interface* cookedData, bool /*tetraMesh*/) { SimulationPhysX3::releaseFabric(cookedData); } SimulationAbstract* ModuleClothing::ClothingPhysX3Backend::createSimulation(bool tetraMesh, ClothingScene* clothingScene, bool useHW) { if (!tetraMesh) { return PX_NEW(SimulationPhysX3)(clothingScene, useHW); } APEX_INTERNAL_ERROR("PhysX3 does not (yet?) support tetrahedral meshes\n"); return NULL; } #endif // NX_SDK_VERSION_NUMBER >= MIN_PHYSX_SDK_VERSION_REQUIRED } } // namespace apex } // namespace physx
27.532502
202
0.743513
[ "mesh", "object" ]
e7a9eef1eeb4afe2de3f40499a3f302a4a95162d
15,152
cpp
C++
domain-server/src/DomainServerSettingsManager.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
1
2015-03-11T19:49:20.000Z
2015-03-11T19:49:20.000Z
domain-server/src/DomainServerSettingsManager.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
domain-server/src/DomainServerSettingsManager.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // DomainServerSettingsManager.cpp // domain-server/src // // Created by Stephen Birarda on 2014-06-24. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QStandardPaths> #include <QtCore/QUrl> #include <QtCore/QUrlQuery> #include <Assignment.h> #include <HifiConfigVariantMap.h> #include <HTTPConnection.h> #include "DomainServerSettingsManager.h" const QString SETTINGS_DESCRIPTION_RELATIVE_PATH = "/resources/describe-settings.json"; const QString DESCRIPTION_SETTINGS_KEY = "settings"; const QString SETTING_DEFAULT_KEY = "default"; const QString DESCRIPTION_NAME_KEY = "name"; const QString SETTING_DESCRIPTION_TYPE_KEY = "type"; DomainServerSettingsManager::DomainServerSettingsManager() : _descriptionArray(), _configMap() { // load the description object from the settings description QFile descriptionFile(QCoreApplication::applicationDirPath() + SETTINGS_DESCRIPTION_RELATIVE_PATH); descriptionFile.open(QIODevice::ReadOnly); _descriptionArray = QJsonDocument::fromJson(descriptionFile.readAll()).array(); } void DomainServerSettingsManager::setupConfigMap(const QStringList& argumentList) { _configMap.loadMasterAndUserConfig(argumentList); // for now we perform a temporary transition from http-username and http-password to http_username and http_password const QVariant* oldUsername = valueForKeyPath(_configMap.getUserConfig(), "security.http-username"); const QVariant* oldPassword = valueForKeyPath(_configMap.getUserConfig(), "security.http-password"); if (oldUsername || oldPassword) { QVariantMap& settingsMap = *reinterpret_cast<QVariantMap*>(_configMap.getUserConfig()["security"].data()); // remove old keys, move to new format if (oldUsername) { settingsMap["http_username"] = oldUsername->toString(); settingsMap.remove("http-username"); } if (oldPassword) { settingsMap["http_password"] = oldPassword->toString(); settingsMap.remove("http-password"); } // save the updated settings persistToFile(); } } QVariant DomainServerSettingsManager::valueOrDefaultValueForKeyPath(const QString &keyPath) { const QVariant* foundValue = valueForKeyPath(_configMap.getMergedConfig(), keyPath); if (foundValue) { return *foundValue; } else { int dotIndex = keyPath.indexOf('.'); QString groupKey = keyPath.mid(0, dotIndex); QString settingKey = keyPath.mid(dotIndex + 1); foreach(const QVariant& group, _descriptionArray.toVariantList()) { QVariantMap groupMap = group.toMap(); if (groupMap[DESCRIPTION_NAME_KEY].toString() == groupKey) { foreach(const QVariant& setting, groupMap[DESCRIPTION_SETTINGS_KEY].toList()) { QVariantMap settingMap = setting.toMap(); if (settingMap[DESCRIPTION_NAME_KEY].toString() == settingKey) { return settingMap[SETTING_DEFAULT_KEY]; } } return QVariant(); } } } return QVariant(); } const QString SETTINGS_PATH = "/settings.json"; bool DomainServerSettingsManager::handlePublicHTTPRequest(HTTPConnection* connection, const QUrl &url) { if (connection->requestOperation() == QNetworkAccessManager::GetOperation && url.path() == SETTINGS_PATH) { // this is a GET operation for our settings // check if there is a query parameter for settings affecting a particular type of assignment const QString SETTINGS_TYPE_QUERY_KEY = "type"; QUrlQuery settingsQuery(url); QString typeValue = settingsQuery.queryItemValue(SETTINGS_TYPE_QUERY_KEY); if (!typeValue.isEmpty()) { QJsonObject responseObject = responseObjectForType(typeValue); connection->respond(HTTPConnection::StatusCode200, QJsonDocument(responseObject).toJson(), "application/json"); return true; } else { return false; } } return false; } bool DomainServerSettingsManager::handleAuthenticatedHTTPRequest(HTTPConnection *connection, const QUrl &url) { if (connection->requestOperation() == QNetworkAccessManager::PostOperation && url.path() == SETTINGS_PATH) { // this is a POST operation to change one or more settings QJsonDocument postedDocument = QJsonDocument::fromJson(connection->requestContent()); QJsonObject postedObject = postedDocument.object(); // we recurse one level deep below each group for the appropriate setting recurseJSONObjectAndOverwriteSettings(postedObject, _configMap.getUserConfig(), _descriptionArray); // store whatever the current _settingsMap is to file persistToFile(); // return success to the caller QString jsonSuccess = "{\"status\": \"success\"}"; connection->respond(HTTPConnection::StatusCode200, jsonSuccess.toUtf8(), "application/json"); // defer a restart to the domain-server, this gives our HTTPConnection enough time to respond const int DOMAIN_SERVER_RESTART_TIMER_MSECS = 1000; QTimer::singleShot(DOMAIN_SERVER_RESTART_TIMER_MSECS, qApp, SLOT(restart())); return true; } else if (connection->requestOperation() == QNetworkAccessManager::GetOperation && url.path() == SETTINGS_PATH) { // setup a JSON Object with descriptions and non-omitted settings const QString SETTINGS_RESPONSE_DESCRIPTION_KEY = "descriptions"; const QString SETTINGS_RESPONSE_VALUE_KEY = "values"; const QString SETTINGS_RESPONSE_LOCKED_VALUES_KEY = "locked"; QJsonObject rootObject; rootObject[SETTINGS_RESPONSE_DESCRIPTION_KEY] = _descriptionArray; rootObject[SETTINGS_RESPONSE_VALUE_KEY] = responseObjectForType("", true); rootObject[SETTINGS_RESPONSE_LOCKED_VALUES_KEY] = QJsonDocument::fromVariant(_configMap.getMasterConfig()).object(); connection->respond(HTTPConnection::StatusCode200, QJsonDocument(rootObject).toJson(), "application/json"); } return false; } QJsonObject DomainServerSettingsManager::responseObjectForType(const QString& typeValue, bool isAuthenticated) { QJsonObject responseObject; if (!typeValue.isEmpty() || isAuthenticated) { // convert the string type value to a QJsonValue QJsonValue queryType = typeValue.isEmpty() ? QJsonValue() : QJsonValue(typeValue.toInt()); const QString AFFECTED_TYPES_JSON_KEY = "assignment-types"; // enumerate the groups in the description object to find which settings to pass foreach(const QJsonValue& groupValue, _descriptionArray) { QJsonObject groupObject = groupValue.toObject(); QString groupKey = groupObject[DESCRIPTION_NAME_KEY].toString(); QJsonArray groupSettingsArray = groupObject[DESCRIPTION_SETTINGS_KEY].toArray(); QJsonObject groupResponseObject; foreach(const QJsonValue& settingValue, groupSettingsArray) { const QString VALUE_HIDDEN_FLAG_KEY = "value-hidden"; QJsonObject settingObject = settingValue.toObject(); if (!settingObject[VALUE_HIDDEN_FLAG_KEY].toBool()) { QJsonArray affectedTypesArray = settingObject[AFFECTED_TYPES_JSON_KEY].toArray(); if (affectedTypesArray.isEmpty()) { affectedTypesArray = groupObject[AFFECTED_TYPES_JSON_KEY].toArray(); } if (affectedTypesArray.contains(queryType) || (queryType.isNull() && isAuthenticated)) { // this is a setting we should include in the responseObject QString settingName = settingObject[DESCRIPTION_NAME_KEY].toString(); // we need to check if the settings map has a value for this setting QVariant variantValue; QVariant settingsMapGroupValue = _configMap.getMergedConfig() .value(groupObject[DESCRIPTION_NAME_KEY].toString()); if (!settingsMapGroupValue.isNull()) { variantValue = settingsMapGroupValue.toMap().value(settingName); } if (variantValue.isNull()) { // no value for this setting, pass the default if (settingObject.contains(SETTING_DEFAULT_KEY)) { groupResponseObject[settingName] = settingObject[SETTING_DEFAULT_KEY]; } else { // users are allowed not to provide a default for string values // if so we set to the empty string groupResponseObject[settingName] = QString(""); } } else { groupResponseObject[settingName] = QJsonValue::fromVariant(variantValue); } } } } if (!groupResponseObject.isEmpty()) { // set this group's object to the constructed object responseObject[groupKey] = groupResponseObject; } } } return responseObject; } bool DomainServerSettingsManager::settingExists(const QString& groupName, const QString& settingName, const QJsonArray& descriptionArray, QJsonValue& settingDescription) { foreach(const QJsonValue& groupValue, descriptionArray) { QJsonObject groupObject = groupValue.toObject(); if (groupObject[DESCRIPTION_NAME_KEY].toString() == groupName) { foreach(const QJsonValue& settingValue, groupObject[DESCRIPTION_SETTINGS_KEY].toArray()) { QJsonObject settingObject = settingValue.toObject(); if (settingObject[DESCRIPTION_NAME_KEY].toString() == settingName) { settingDescription = settingObject[SETTING_DEFAULT_KEY]; return true; } } } } settingDescription = QJsonValue::Undefined; return false; } void DomainServerSettingsManager::updateSetting(const QString& key, const QJsonValue& newValue, QVariantMap& settingMap, const QJsonValue& settingDescription) { if (newValue.isString()) { if (newValue.toString().isEmpty()) { // this is an empty value, clear it in settings variant so the default is sent settingMap.remove(key); } else { // make sure the resulting json value has the right type const QString settingType = settingDescription.toObject()[SETTING_DESCRIPTION_TYPE_KEY].toString(); const QString INPUT_DOUBLE_TYPE = "double"; const QString INPUT_INTEGER_TYPE = "int"; if (settingType == INPUT_DOUBLE_TYPE) { settingMap[key] = newValue.toString().toDouble(); } else if (settingType == INPUT_INTEGER_TYPE) { settingMap[key] = newValue.toString().toInt(); } else { settingMap[key] = newValue.toString(); } } } else if (newValue.isBool()) { settingMap[key] = newValue.toBool(); } else if (newValue.isObject()) { if (!settingMap.contains(key)) { // we don't have a map below this key yet, so set it up now settingMap[key] = QVariantMap(); } QVariantMap& thisMap = *reinterpret_cast<QVariantMap*>(settingMap[key].data()); foreach(const QString childKey, newValue.toObject().keys()) { updateSetting(childKey, newValue.toObject()[childKey], thisMap, settingDescription.toObject()[key]); } if (settingMap[key].toMap().isEmpty()) { // we've cleared all of the settings below this value, so remove this one too settingMap.remove(key); } } else if (newValue.isArray()) { // we just assume array is replacement settingMap[key] = newValue.toArray().toVariantList(); } } void DomainServerSettingsManager::recurseJSONObjectAndOverwriteSettings(const QJsonObject& postedObject, QVariantMap& settingsVariant, const QJsonArray& descriptionArray) { // Iterate on the setting groups foreach(const QString& groupKey, postedObject.keys()) { QJsonValue groupValue = postedObject[groupKey]; if (!settingsVariant.contains(groupKey)) { // we don't have a map below this key yet, so set it up now settingsVariant[groupKey] = QVariantMap(); } // Iterate on the settings foreach(const QString& settingKey, groupValue.toObject().keys()) { QJsonValue settingValue = groupValue.toObject()[settingKey]; QJsonValue thisDescription; if (settingExists(groupKey, settingKey, descriptionArray, thisDescription)) { QVariantMap& thisMap = *reinterpret_cast<QVariantMap*>(settingsVariant[groupKey].data()); updateSetting(settingKey, settingValue, thisMap, thisDescription); } } if (settingsVariant[groupKey].toMap().empty()) { // we've cleared all of the settings below this value, so remove this one too settingsVariant.remove(groupKey); } } } void DomainServerSettingsManager::persistToFile() { // make sure we have the dir the settings file is supposed to live in QFileInfo settingsFileInfo(_configMap.getUserConfigFilename()); if (!settingsFileInfo.dir().exists()) { settingsFileInfo.dir().mkpath("."); } QFile settingsFile(_configMap.getUserConfigFilename()); if (settingsFile.open(QIODevice::WriteOnly)) { settingsFile.write(QJsonDocument::fromVariant(_configMap.getUserConfig()).toJson()); } else { qCritical("Could not write to JSON settings file. Unable to persist settings."); } }
44.046512
124
0.62038
[ "object" ]
e7aef7961caee7740424c8c70e99fcb42c826acc
4,225
hh
C++
libraries/json/json/utils.hh
BlueSolei/lithium
080b7db72efd6f673103f6a29ddb027cb50f812b
[ "MIT" ]
2
2020-07-21T01:18:11.000Z
2021-07-29T02:55:29.000Z
libraries/json/json/utils.hh
BlueSolei/lithium
080b7db72efd6f673103f6a29ddb027cb50f812b
[ "MIT" ]
null
null
null
libraries/json/json/utils.hh
BlueSolei/lithium
080b7db72efd6f673103f6a29ddb027cb50f812b
[ "MIT" ]
null
null
null
#pragma once #include <optional> #include <li/json/symbols.hh> #include <li/metamap/metamap.hh> #include <li/symbol/ast.hh> #include <tuple> #include <map> #include <unordered_map> namespace li { template <typename T> struct json_object_base; template <typename T> struct json_object_; template <typename T> struct json_vector_; template <typename V> struct json_value_; template <typename V> struct json_map_; template <typename... T> struct json_tuple_; struct json_key; namespace impl { template <typename S, typename... A> auto make_json_object_member(const function_call_exp<S, A...>& e); template <typename S> auto make_json_object_member(const li::symbol<S>&); template <typename S, typename T> auto make_json_object_member(const assign_exp<S, T>& e) { return cat(make_json_object_member(e.left), mmm(s::type = e.right)); } template <typename S> auto make_json_object_member(const li::symbol<S>&) { return mmm(s::name = S{}); } template <typename V> auto to_json_schema(V v) { return json_value_<V>{}; } template <typename... M> auto to_json_schema(const metamap<M...>& m); template <typename V> auto to_json_schema(const std::vector<V>& arr) { auto elt = to_json_schema(decltype(arr[0]){}); return json_vector_<decltype(elt)>{elt}; } template <typename... V> auto to_json_schema(const std::tuple<V...>& arr) { return json_tuple_<decltype(to_json_schema(V{}))...>(to_json_schema(V{})...); } template <typename K, typename V> auto to_json_schema(const std::unordered_map<K, V>& arr) { return json_map_<decltype(to_json_schema(V{}))>(to_json_schema(V{})); } template <typename K, typename V> auto to_json_schema(const std::map<K, V>& arr) { return json_map_<decltype(to_json_schema(V{}))>(to_json_schema(V{})); } template <typename... M> auto to_json_schema(const metamap<M...>& m) { auto tuple_maker = [](auto&&... t) { return std::make_tuple(std::forward<decltype(t)>(t)...); }; auto entities = map_reduce( m, [](auto k, auto v) { return mmm(s::name = k, s::type = to_json_schema(v)); }, tuple_maker); return json_object_<decltype(entities)>(entities); } template <typename... E> auto json_object_to_metamap(const json_object_<std::tuple<E...>>& s) { auto make_kvs = [](auto... elt) { return std::make_tuple((elt.name = elt.type)...); }; auto kvs = std::apply(make_kvs, s.entities); return std::apply(mmm, kvs); } template <typename S, typename... A> auto make_json_object_member(const function_call_exp<S, A...>& e) { auto res = mmm(s::name = e.method, s::json_key = symbol_string(e.method)); auto parse = [&](auto a) { if constexpr (std::is_same<decltype(a), json_key>::value) { res.json_key = a.key; } }; ::li::tuple_map(e.args, parse); return res; } } // namespace impl template <typename T> struct json_object_; template <typename O> struct json_vector_; template <typename E> constexpr auto json_is_vector(json_vector_<E>) -> std::true_type { return {}; } template <typename E> constexpr auto json_is_vector(E) -> std::false_type { return {}; } template <typename... E> constexpr auto json_is_tuple(json_tuple_<E...>) -> std::true_type { return {}; } template <typename E> constexpr auto json_is_tuple(E) -> std::false_type { return {}; } template <typename E> constexpr auto json_is_object(json_object_<E>) -> std::true_type { return {}; } template <typename E> constexpr auto json_is_object(json_map_<E>) -> std::true_type { return {}; } template <typename E> constexpr auto json_is_object(E) -> std::false_type { return {}; } template <typename E> constexpr auto json_is_value(json_object_<E>) -> std::false_type { return {}; } template <typename E> constexpr auto json_is_value(json_vector_<E>) -> std::false_type { return {}; } template <typename... E> constexpr auto json_is_value(json_tuple_<E...>) -> std::false_type { return {}; } template <typename E> constexpr auto json_is_value(json_map_<E>) -> std::false_type { return {}; } template <typename E> constexpr auto json_is_value(E) -> std::true_type { return {}; } template <typename T> constexpr auto is_std_optional(std::optional<T>) -> std::true_type; template <typename T> constexpr auto is_std_optional(T) -> std::false_type; } // namespace li
33.007813
100
0.704615
[ "vector" ]
e7b1c1c147d3ce400f8f8c1adb4400ec006d5c45
746
hpp
C++
libs/utils/include/utils/ArgParse.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
2
2020-02-10T07:58:21.000Z
2022-03-15T19:13:28.000Z
libs/utils/include/utils/ArgParse.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
libs/utils/include/utils/ArgParse.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
#ifndef ARG_PARSE_HPP #define ARG_PARSE_HPP #include <vector> namespace utils { enum class ArgType { Flag, Value, List, }; class ArgOption { public: ArgOption(const char* option, const char* description, ArgType type); const char* mOption; const char* mDescription; ArgType mType; bool mIsSet; std::vector<char*> mValues; }; class ArgParser { public: ArgParser(const char* appInfo); bool parse(int argv, char** argc); void printHelp(); void addOption(ArgOption* option); private: const char* mAppInfo; std::vector<ArgOption*> mOptions; }; } // namespace utils #endif
16.217391
77
0.572386
[ "vector" ]
e7b291af9fd1e846bc3e9297217550101710e59c
3,323
cpp
C++
Competitive Programing Problem Solutions/Graph Theory/Articulation Points and Bridges/796-Critical Links-Uva.cpp
BIJOY-SUST/ACM---ICPC
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
1
2022-02-27T12:07:59.000Z
2022-02-27T12:07:59.000Z
Competitive Programing Problem Solutions/Graph Theory/Articulation Points and Bridges/796-Critical Links-Uva.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
Competitive Programing Problem Solutions/Graph Theory/Articulation Points and Bridges/796-Critical Links-Uva.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> #define mx 100001 //#define mod 1000000007 //#define pi 2*acos(0.0) #define pp pair<int,int> //#define ll long long int #define me printf("BIJOY\n"); //#define one(n) __builtin_popcount(n) //#define ull unsigned long long int //#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c //const int fx[]={+1,-1,+0,+0}; //const int fy[]={+0,+0,+1,-1}; //const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; //const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; //const int fx[]={-2,-2,-1,-1,+1,+1,+2,+2}; //const int fy[]={-1,+1,-2,+2,-2,+2,-1,+1}; //int biton(int n,int pos){return n=n|(1<<pos);} //int bitoff(int n,int pos){return n=n&~(1<<pos);} //bool bitcheck(int n,int pos){return (bool)(n&(1<<pos));} //template< class T > inline T SQR(T a) {return ((a)*(a));} //template< class T > inline T gcd(T a,T b) {a=abs(a);b=abs(b); if(!b) return a; return gcd(b,a%b);} //template< class T > inline T lcm(T a,T b) {a=abs(a);b=abs(b); return (a/_gcd(a,b))*b;} //template<typename T> T POW(T b,T p) {T r=1; while(p){if(p&1)r=(r*b);b=(b*b);p>>=1;}return r;} //template<typename T> T BigMod(T b,T p,T m) {T r=1; while(p){if(p&1)r=(r*b)%m;b=(b*b)%m;p>>=1;}return r;} //template<typename T> T ModInverse(T n,T m) {return BigMod(n,m-2,m);} using namespace std; vector<int>edges[mx]; vector<pp >ans; int parent[mx],low[mx],temp[mx],child[mx]; bool vis[mx],is_cut[mx]; int c; void dfs(int u){ vis[u]=true; low[u]=temp[u]=++c; for(int i=0;i<edges[u].size();i++){ int v=edges[u][i]; if(parent[u]==v) continue; else if(!vis[v]){ child[u]++; parent[v]=u; dfs(v); low[u]=min(low[u],low[v]); if(low[v]>temp[u]){ ans.push_back(make_pair(min(u,v),max(u,v))); } } else{ low[u]=min(low[u],temp[v]); } } } int main(){ // freopen("Input.txt","r",stdin); // freopen("Output.txt","w",stdout); // int t; // scanf("%d",&t); // for(int cs=1;cs<=t;cs++){ int n; while(scanf("%d",&n)==1){ for(int i=1;i<=n;i++){ int u,d; scanf("%d (%d)",&u,&d); while(d--){ int v; scanf("%d",&v); edges[u].push_back(v); edges[v].push_back(u); } } // for(int i=0;i<n;i++){ // for(int j=0;j<edges[i].size();j++){ // printf("%d ",edges[i][j]); // } // cout<<endl; // } memset(vis,false,sizeof(vis)); memset(is_cut,false,sizeof(is_cut)); memset(parent,-1,sizeof(parent)); memset(low,0,sizeof(low)); memset(temp,0,sizeof(temp)); memset(child,0,sizeof(child)); c=0; for(int i=0;i<n;i++){ if(!vis[i]) dfs(i); } sort(ans.begin(),ans.end()); //printf("Case %d:\n",cs); printf("%d critical links\n",ans.size()); for(int i=0;i<ans.size();i++){ printf("%d - %d\n",ans[i].first,ans[i].second); } for(int i=0;i<mx;i++) edges[i].clear(); ans.clear(); printf("\n"); } return 0; } /* */
33.23
107
0.457418
[ "vector" ]
e7b3271171ea47d1af30c759f573cf020a4e787f
3,955
cc
C++
paddle/fluid/distributed/ps/service/server.cc
Shaun2016/Paddle
b963903806c8a6694df79b42aaab6578a0ef6afb
[ "Apache-2.0" ]
null
null
null
paddle/fluid/distributed/ps/service/server.cc
Shaun2016/Paddle
b963903806c8a6694df79b42aaab6578a0ef6afb
[ "Apache-2.0" ]
null
null
null
paddle/fluid/distributed/ps/service/server.cc
Shaun2016/Paddle
b963903806c8a6694df79b42aaab6578a0ef6afb
[ "Apache-2.0" ]
1
2021-12-09T08:59:17.000Z
2021-12-09T08:59:17.000Z
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/distributed/ps/service/server.h" #include "glog/logging.h" #include "paddle/fluid/distributed/ps/service/brpc_ps_server.h" #include "paddle/fluid/distributed/ps/service/graph_brpc_server.h" #include "paddle/fluid/distributed/ps/service/ps_local_server.h" #include "paddle/fluid/distributed/ps/table/table.h" namespace paddle { namespace distributed { REGISTER_PSCORE_CLASS(PSServer, BrpcPsServer); REGISTER_PSCORE_CLASS(PSServer, PsLocalServer); REGISTER_PSCORE_CLASS(PsBaseService, BrpcPsService); REGISTER_PSCORE_CLASS(PSServer, GraphBrpcServer); REGISTER_PSCORE_CLASS(PsBaseService, GraphBrpcService); PSServer *PSServerFactory::Create(const PSParameter &ps_config) { const auto &config = ps_config.server_param(); if (!config.has_downpour_server_param()) { LOG(ERROR) << "miss downpour_server_param in ServerParameter"; return NULL; } if (!config.downpour_server_param().has_service_param()) { LOG(ERROR) << "miss service_param in ServerParameter.downpour_server_param"; return NULL; } if (!config.downpour_server_param().service_param().has_server_class()) { LOG(ERROR) << "miss server_class in " "ServerParameter.downpour_server_param.service_param"; return NULL; } const auto &service_param = config.downpour_server_param().service_param(); PSServer *server = CREATE_PSCORE_CLASS(PSServer, service_param.server_class()); if (server == NULL) { LOG(ERROR) << "server is not registered, server_name:" << service_param.server_class(); return NULL; } TableManager::Instance().Initialize(); return server; } int32_t PSServer::Configure( const PSParameter &config, PSEnvironment &env, size_t server_rank, const std::vector<framework::ProgramDesc> &server_sub_program) { scope_.reset(new framework::Scope()); _config = config.server_param(); _rank = server_rank; _environment = &env; _shuffled_ins = paddle::framework::MakeChannel<std::pair<uint64_t, std::string>>(); size_t shard_num = env.GetPsServers().size(); const auto &downpour_param = _config.downpour_server_param(); uint32_t barrier_table = UINT32_MAX; uint32_t global_step_table = UINT32_MAX; for (int i = 0; i < downpour_param.downpour_table_param_size(); ++i) { auto *table = CREATE_PSCORE_CLASS( Table, downpour_param.downpour_table_param(i).table_class()); if (downpour_param.downpour_table_param(i).table_class() == "BarrierTable") { barrier_table = downpour_param.downpour_table_param(i).table_id(); } if (downpour_param.downpour_table_param(i).table_class() == "GlobalStepTable") { global_step_table = downpour_param.downpour_table_param(i).table_id(); } table->SetProgramEnv(scope_.get(), place_, &server_sub_program); table->SetShard(_rank, shard_num); table->Initialize(downpour_param.downpour_table_param(i), config.fs_client_param()); _table_map[downpour_param.downpour_table_param(i).table_id()].reset(table); } if (barrier_table != UINT32_MAX) { _table_map[barrier_table]->SetTableMap(&_table_map); } if (global_step_table != UINT32_MAX) { _table_map[global_step_table]->SetTableMap(&_table_map); } return Initialize(); } } // namespace distributed } // namespace paddle
35.954545
80
0.733502
[ "vector" ]
e7b81af6edd2707f653c68a61a33cb4d18bcc2fe
1,609
hpp
C++
include/LDtkLoader/Enum.hpp
dontpanic5/LDtkLoader
885a08f428c16c99cffb436c8af1eee0fee493ed
[ "Zlib" ]
null
null
null
include/LDtkLoader/Enum.hpp
dontpanic5/LDtkLoader
885a08f428c16c99cffb436c8af1eee0fee493ed
[ "Zlib" ]
null
null
null
include/LDtkLoader/Enum.hpp
dontpanic5/LDtkLoader
885a08f428c16c99cffb436c8af1eee0fee493ed
[ "Zlib" ]
null
null
null
// Created by Modar Nasser on 13/11/2020. #pragma once #include <string> #include <vector> #include "LDtkLoader/thirdparty/json.hpp" #include "LDtkLoader/DataTypes.hpp" namespace ldtk { class World; class Enum; struct Tileset; struct EnumValue { const std::string name; const Color color; const Enum& type; auto hasIcon() const -> bool; auto getIconTileset() const -> const Tileset&; auto getIconTexturePos() const -> IntPoint; private: friend Enum; friend bool operator==(const EnumValue& l, const EnumValue& r); EnumValue(std::string name, int id, int tile_id, const Color& color, const Enum& enum_type); const int id; const int tile_id; }; bool operator==(const EnumValue& l, const EnumValue& r); bool operator!=(const EnumValue& l, const EnumValue& r); class Enum { friend World; public: Enum(const Enum&) = delete; Enum(Enum&&) = default; auto operator=(const Enum&) -> Enum& = delete; const std::string name; const int uid; auto operator[](const std::string& val_name) const -> const EnumValue&; auto hasIcons() const -> bool; auto getIconsTileset() const -> const Tileset&; Enum(const nlohmann::json& j, const World* w); private: friend World; const int m_tileset_id; const Tileset* m_tileset; std::unordered_map<std::string, EnumValue> m_values; }; } auto operator<<(std::ostream& os, const ldtk::EnumValue& enum_value) -> std::ostream&;
25.951613
100
0.617775
[ "vector" ]
e7bbbea9df1c7227cc1db00933826a72940869dd
10,510
hpp
C++
test-suite/mpiparalleltestrunner.hpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
4
2016-03-28T15:05:23.000Z
2020-02-17T23:05:57.000Z
test-suite/mpiparalleltestrunner.hpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
1
2015-02-02T20:32:43.000Z
2015-02-02T20:32:43.000Z
test-suite/mpiparalleltestrunner.hpp
pcaspers/quantlib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
10
2015-01-26T14:50:24.000Z
2015-10-23T07:41:30.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2015 Klaus Spanderen 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 QuantLib license for more details. */ #ifndef quantlib_test_mpi_parallel_test_runner_hpp #define quantlib_test_mpi_parallel_test_runner_hpp #include <ql/types.hpp> #include <boost/timer.hpp> #include <boost/thread/thread.hpp> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <boost/serialization/utility.hpp> #define BOOST_TEST_NO_MAIN 1 #include <boost/test/results_collector.hpp> #include <boost/test/included/unit_test.hpp> #include <boost/algorithm/string.hpp> #include <boost/mpi.hpp> #include <map> #include <list> #include <sstream> #include <utility> #include <fstream> #include <iostream> #include <string> #include <cstring> #include <cstdlib> #ifdef BOOST_MSVC # error parallel test suite runner is not available on Windows #endif using boost::unit_test::test_results; using namespace boost::unit_test_framework; namespace { class TestCaseCollector : public test_tree_visitor { public: typedef std::map<test_unit_id, std::list<test_unit_id> > id_map_t; const id_map_t& map() const { return idMap_; } test_unit_id testSuiteId() const { return testSuiteId_; } bool visit(test_unit const& tu) { if (tu.p_parent_id == framework::master_test_suite().p_id) { QL_REQUIRE(!tu.p_name.get().compare("QuantLib test suite"), "could not find QuantLib test suite"); testSuiteId_ = tu.p_id; } return test_tree_visitor::visit(tu); } void visit(test_case const& tc) { idMap_[tc.p_parent_id].push_back(tc.p_id); } std::list<test_unit_id>::size_type numberOfTests() { std::list<test_unit_id>::size_type n=0; for (id_map_t::const_iterator p_it = idMap_.begin(); p_it != idMap_.end(); ++p_it) n+=p_it->second.size(); return n; } private: id_map_t idMap_; test_unit_id testSuiteId_; }; struct TestCaseId { friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & id; ar & terminate; } test_unit_id id; bool terminate; }; const char* const namesLogMutexName = "named_log_mutex"; std::ostream& log_message(std::ostream& out, const std::string& msg) { std::vector<std::string> tok; boost::split(tok, msg, boost::is_any_of("\n")); for (std::vector<std::string>::const_iterator iter = tok.begin(); iter != tok.end(); ++iter) { if (iter->length() && iter->compare("Running 1 test case...")) { out << *iter << std::endl; } } return out; } void output_logstream( std::ostream& out, std::streambuf* outBuf, std::stringstream& s) { out.flush(); out.rdbuf(outBuf); log_message(out, s.str()); s.str(std::string()); out.rdbuf(s.rdbuf()); } } test_suite* init_unit_test_suite(int, char* []); int main( int argc, char* argv[] ) { typedef QuantLib::Time Time; const char* const profileFileName = ".unit_test_profile.txt"; typedef std::vector<std::pair<std::string, QuantLib::Time> > run_time_list_type; boost::mpi::environment env; boost::mpi::communicator world; if (!world.rank()) { framework::init(init_unit_test_suite, argc, argv ); framework::finalize_setup_phase(); std::map<std::string, Time> runTimeLog; std::ifstream in(profileFileName); if (in.good()) { for (std::string line; std::getline(in, line);) { std::vector<std::string> tok; boost::split(tok, line, boost::is_any_of(" ")); QL_REQUIRE(tok.size() == 2, "every line should consists of two entries"); runTimeLog[tok[0]] = std::atof(tok[1].c_str()); } } in.close(); TestCaseCollector tcc; traverse_test_tree(framework::master_test_suite(), tcc , true); s_log_impl().stream() << "Total number of test cases: " << tcc.numberOfTests() << std::endl; // run root test cases in master process const std::list<test_unit_id>& qlRoot = tcc.map().find(tcc.testSuiteId())->second; std::multimap<Time, test_unit_id> testsSortedByRunTime; for (TestCaseCollector::id_map_t::const_iterator p_it = tcc.map().begin(); p_it != tcc.map().end(); ++p_it) { if (p_it->first != tcc.testSuiteId()) { for (std::list<test_unit_id>::const_iterator it = p_it->second.begin(); it != p_it->second.end(); ++it) { const std::string& name = framework::get(*it, TUT_ANY).p_name; if (runTimeLog.count(name)) { testsSortedByRunTime.insert( std::make_pair(runTimeLog[name], *it)); } else { testsSortedByRunTime.insert( std::make_pair( std::numeric_limits<Time>::max(), *it)); } } } } std::vector<test_unit_id> ids; for (std::multimap<Time, test_unit_id>::const_iterator iter = testsSortedByRunTime.begin(); iter != testsSortedByRunTime.end(); ++iter) { ids.push_back(iter->second); } QL_REQUIRE(ids.size() + qlRoot.size() == tcc.numberOfTests(), "missing test case in distrubtion list"); testsSortedByRunTime.clear(); test_results results; std::stringstream logBuf; std::streambuf* const oldBuf = s_log_impl().stream().rdbuf(); s_log_impl().stream().rdbuf(logBuf.rdbuf()); for (std::list<test_unit_id>::const_iterator iter = qlRoot.begin(); std::distance(qlRoot.begin(), iter) < int(qlRoot.size())-1; ++iter) { framework::run(*iter); results += boost::unit_test::results_collector.results(*iter); } output_logstream(s_log_impl().stream(), oldBuf, logBuf); s_log_impl().stream().rdbuf(oldBuf); const unsigned nSlaves = std::min(size_t(world.size()-1), ids.size()); for (unsigned i=nSlaves+1; i < world.size(); ++i) { const TestCaseId id = { 0, true }; world.send(i, 0, id); } for (unsigned i=0; i < ids.size() + nSlaves; ++i) { if (i < nSlaves) { const TestCaseId id = { ids[ids.size()-i-1], false }; world.send(i+1, 0, id); } else { std::string msg; // while(!world.iprobe(boost::mpi::any_source, 2)) // boost::this_thread::sleep(boost::posix_time::microsec(1000)); const boost::mpi::status s = world.recv(boost::mpi::any_source, 2, msg); if (i < ids.size()) { const TestCaseId id = { ids[ids.size()-i-1], false }; world.send(s.source(), 0, id); } else { const TestCaseId id = { 0, true }; world.send(s.source(), 0, id); } log_message(std::cout, msg); } } run_time_list_type runTimeLogs; for (unsigned i=0; i < world.size()-1; ++i) { run_time_list_type log; world.recv(boost::mpi::any_source, 3, log); for (run_time_list_type::const_iterator iter = log.begin(); iter != log.end(); ++iter) { runTimeLog[iter->first] = iter->second; } test_results r; world.recv(boost::mpi::any_source, 1, (char*) &r, sizeof(test_results)); results+=r; } if (!qlRoot.empty()) framework::run(qlRoot.back()); results += boost::unit_test::results_collector.results( qlRoot.back()); s_log_impl().stream() << "Test module \"" << framework::master_test_suite().p_name <<"\" has passed with:" << std::endl << " " << results.p_assertions_failed << " assertions failed" << std::endl << " " << results.p_assertions_passed << " assertions passed" << std::endl; std::ofstream out( profileFileName, std::ios::out | std::ios::trunc); out << std::setprecision(6); for (std::map<std::string, QuantLib::Time>::const_iterator iter = runTimeLog.begin(); iter != runTimeLog.end(); ++iter) { out << iter->first << " " << iter->second << std::endl; } out.close(); } else { std::stringstream logBuf; s_log_impl().stream().rdbuf(logBuf.rdbuf()); framework::init(init_unit_test_suite, argc, argv ); framework::finalize_setup_phase(); logBuf.str(std::string()); test_results r; run_time_list_type runTimeLogs; TestCaseId id; world.recv(0, 0, id); while (!id.terminate) { boost::timer t; framework::run(id.id); r += boost::unit_test::results_collector.results(id.id); runTimeLogs.push_back(std::make_pair( framework::get(id.id, TUT_ANY).p_name, t.elapsed())); s_log_impl().stream().flush(); const std::string log = logBuf.str(); logBuf.str(std::string()); world.send(0, 2, log); world.recv(0, 0, id); } world.send(0, 3, runTimeLogs); // boost::mpi::request t = world.send(0, 1, (char*) &r, sizeof(test_results)); // while(!boost::mpi::test_all(&t, &t+1)) // boost::this_thread::sleep(boost::posix_time::microsec(1000)); } framework::shutdown(); } #endif
31.094675
83
0.544148
[ "vector" ]
e7bf5770e3cc0b267afc30689ca3ad96a1b6a890
894
cpp
C++
90.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
90.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
90.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
// // Created by pzz on 2021/12/4. // #include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { private: vector<vector<int>> result; vector<int> path; vector<bool> used; void backtracing(vector<int> &nums, int start) { result.push_back(path); for (int i = start; i < nums.size(); i++) { if (i > 0 && nums[i - 1] == nums[i] && used[i - 1] == false) continue; used[i] = true; path.push_back(nums[i]); backtracing(nums, i + 1); path.pop_back(); used[i] = false; } } public: vector<vector<int>> subsetsWithDup(vector<int> &nums) { used.insert(used.begin(), nums.size(), false); sort(nums.begin(), nums.end()); backtracing(nums, 0); return result; } }; int main() { return 0; }
21.285714
72
0.524609
[ "vector" ]
e7c23f958181338258a3cc3cf977ff3cc88493e6
5,935
hpp
C++
util/utils.hpp
ajoudaki/Project2020-seq-tensor-sketching
20b19ddd19751840d33af97abe314d29b34dc0d4
[ "MIT" ]
7
2020-12-07T11:33:17.000Z
2022-01-02T07:30:52.000Z
util/utils.hpp
ajoudaki/Project2020-seq-tensor-sketching
20b19ddd19751840d33af97abe314d29b34dc0d4
[ "MIT" ]
26
2021-01-13T18:15:23.000Z
2022-02-27T05:52:59.000Z
util/utils.hpp
ajoudaki/Project2020-seq-tensor-sketching
20b19ddd19751840d33af97abe314d29b34dc0d4
[ "MIT" ]
2
2021-01-06T15:03:10.000Z
2022-01-02T07:18:45.000Z
#pragma once #include "util/multivec.hpp" #include "util/timer.hpp" #include <algorithm> #include <cassert> #include <cmath> #include <numeric> #include <vector> namespace ts { // ts = Tensor Sketch /** * Extracts k-mers from a sequence. The k-mer is treated as a number in base alphabet_size and then * converted to decimal, i.e. the sequence s1...sk is converted to s1*S^(k-1) + s2*S^(k-2) + ... + * sk, where k is the k-mer size. * @tparam chr types of elements in the sequence * @tparam kmer type that stores a kmer * @param seq the sequence to extract kmers from * @param kmer_size number of characters in a kmer * @param alphabet_size size of the alphabet * @return the extracted kmers, as integers converted from base #alphabet_size */ template <class chr, class kmer> std::vector<kmer> seq2kmer(const std::vector<chr> &seq, uint8_t kmer_size, uint8_t alphabet_size) { Timer timer("seq2kmer"); if (seq.size() < (size_t)kmer_size) { return std::vector<kmer>(); } std::vector<kmer> result(seq.size() - kmer_size + 1, 0); kmer c = 1; for (uint8_t i = 0; i < kmer_size; i++) { result[0] += c * seq[i]; c *= alphabet_size; } c /= alphabet_size; for (size_t i = 0; i < result.size() - 1; i++) { kmer base = result[i] - seq[i]; assert(base % alphabet_size == 0); result[i + 1] = base / alphabet_size + seq[i + kmer_size] * c; } return result; } template <class T> T l1_dist(const std::vector<T> &a, const std::vector<T> &b) { assert(a.size() == b.size()); T res = 0; for (size_t i = 0; i < a.size(); i++) { auto el = std::abs(a[i] - b[i]); res += el; } return res; } template <class T> T l2_dist(const std::vector<T> &a, const std::vector<T> &b) { assert(a.size() == b.size()); T res = 0; for (size_t i = 0; i < a.size(); i++) { auto el = std::abs(a[i] - b[i]); res += el * el; } return res; } template <class T> T l1_dist2D_minlen(const Vec2D<T> &a, const Vec2D<T> &b) { auto len = std::min(a.size(), b.size()); T val = 0; for (size_t i = 0; i < len; i++) { for (size_t j = 0; j < a[i].size() and j < b[i].size(); j++) { auto el = std::abs(a[i][j] - b[i][j]); val += el; } } return val; } template <class T> T l2_dist2D_minlen(const Vec2D<T> &a, const Vec2D<T> &b) { auto len = std::min(a.size(), b.size()); T val = 0; for (size_t i = 0; i < len; i++) { for (size_t j = 0; j < a[i].size() and j < b[i].size(); j++) { auto el = (a[i][j] - b[i][j]); val += el * el; } } return val; } template <class T> T hamming_dist(const std::vector<T> &a, const std::vector<T> &b) { assert(a.size() == b.size()); T diff = 0; for (size_t i = 0; i < a.size(); i++) { if (a[i] != b[i]) { diff++; } } return diff; } template <class seq_type> int lcs(const std::vector<seq_type> &s1, const std::vector<seq_type> &s2) { size_t m = s1.size(); size_t n = s2.size(); // int L[m + 1][n + 1]; Vec2D<int> L(m + 1, std::vector<int>(n + 1, 0)); for (size_t i = 0; i <= m; i++) { for (size_t j = 0; j <= n; j++) { if (i == 0 || j == 0) { L[i][j] = 0; } else if (s1[i - 1] == s2[j - 1]) { L[i][j] = L[i - 1][j - 1] + 1; } else { L[i][j] = std::max(L[i - 1][j], L[i][j - 1]); } } } return L[m][n]; } template <class seq_type> size_t lcs_distance(const std::vector<seq_type> &s1, const std::vector<seq_type> &s2) { return s1.size() + s2.size() - 2 * lcs(s1, s2); } template <class seq_type> size_t edit_distance(const std::vector<seq_type> &s1, const std::vector<seq_type> &s2) { Timer timer("edit_distance"); const size_t m(s1.size()); const size_t n(s2.size()); if (m == 0) return n; if (n == 0) return m; auto costs = std::vector<size_t>(n + 1); for (size_t k = 0; k <= n; k++) costs[k] = k; size_t i = 0; for (auto it1 = s1.begin(); it1 != s1.end(); ++it1, ++i) { costs[0] = i + 1; size_t corner = i; size_t j = 0; for (auto it2 = s2.begin(); it2 != s2.end(); ++it2, ++j) { size_t upper = costs[j + 1]; if (*it1 == *it2) { costs[j + 1] = corner; } else { size_t t(upper < corner ? upper : corner); costs[j + 1] = (costs[j] < t ? costs[j] : t) + 1; } corner = upper; } } size_t result = costs[n]; return result; } template <class T, class = is_u_integral<T>> T int_pow(T x, T pow) { T result = 1; for (;;) { if (pow & 1) result *= x; pow >>= 1; if (!pow) break; x *= x; } return result; } std::string flag_values(char delimiter = ' ', bool skip_empty = false, bool include_flagfile = true); // If the -o output flag is set, this writes a small shell script <output>.meta containing the // command line used to generate the output. void write_output_meta(); // A simple wrapper around std::apply that applies a given lambda on each element of a tuple. template <typename F, typename T> void apply_tuple(F &&f, T &tuple_t) { std::apply([&](auto &...t) { (f(t), ...); }, tuple_t); } // A simple wrapper around std::apply that applies f on pairs of elements of two tuples. template <typename F, typename T, typename U> void apply_tuple(F &&f, T &tuple_t, U &tuple_u) { std::apply([&](auto &...t) { std::apply([&](auto &...u) { (f(t, u), ...); }, tuple_u); }, tuple_t); } std::pair<double, double> avg_stddev(const std::vector<double> &v); // v must be sorted. double median(const std::vector<double> &v); } // namespace ts
26.977273
99
0.527043
[ "vector" ]
b10ecb8a161aaf6a406491d0d0e22a24a3a31607
2,707
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/function/7.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/function/7.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/function/7.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// { dg-do run { target c++11 } } // 2005-01-15 Douglas Gregor <dgregor@cs.indiana.edu> // // Copyright (C) 2005-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // // 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 // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 20.7.15 polymorphic function object wrapper #include <functional> #include <testsuite_hooks.h> #include <testsuite_tr1.h> template<typename T> const T& as_const(T& t) { return t; } // Check that f's target is a reference_wrapper bound to obj. template<typename Function, typename T> bool wraps(Function& f, T& obj) { using ref_wrapper_type = std::reference_wrapper<T>; auto* p = f.template target<ref_wrapper_type>(); return std::addressof(p->get()) == std::addressof(obj); } // Put reference_wrappers to function pointers into function<> wrappers void test07() { using std::function; using std::ref; using std::cref; using std::reference_wrapper; int (*fptr)(float) = __gnu_test::truncate_float; function<int(float)> f1(ref(fptr)); VERIFY( f1 ); VERIFY( !!f1 ); VERIFY( !(f1 == 0) ); VERIFY( !(0 == f1) ); VERIFY( f1 != 0 ); VERIFY( 0 != f1 ); // Invocation VERIFY( f1(3.1f) == 3 ); // target_type and target() functions const function<int(float)>& f1c = f1; using ref_wrapper_type = reference_wrapper<int(*)(float)>; VERIFY( typeid(ref_wrapper_type) == f1.target_type() ); VERIFY( f1.target<ref_wrapper_type>() != nullptr ); VERIFY( wraps(f1, fptr) ); VERIFY( wraps(f1c, fptr) ); function<int(float)> f2(cref(fptr)); VERIFY( f2 ); VERIFY( !!f2 ); VERIFY( !(f2 == 0) ); VERIFY( !(0 == f2) ); VERIFY( f2 != 0 ); VERIFY( 0 != f2 ); // Invocation VERIFY( f2(3.1f) == 3 ); // target_type and target() functions const function<int(float)>& f2c = f2; using cref_wrapper_type = reference_wrapper<int(* const)(float)>; VERIFY( typeid(cref_wrapper_type) == f2.target_type() ); VERIFY( wraps(f2, as_const(fptr)) ); VERIFY( f2c.target_type() == f2.target_type() ); VERIFY( wraps(f2c, as_const(fptr)) ); } int main() { test07(); return 0; }
28.494737
74
0.670115
[ "object" ]
b1109d9f1ac718e3e328bc880495fd8ffa24be1d
12,955
cc
C++
projects/research/text-processors/to_utf8_trys/data_processor_utf8_autoconv_trys/sampler.cc
zaqwes8811/smart-vocabulary-cards
abeab5c86b1c6f68d8796475cba80c4f2c6055ff
[ "Apache-2.0" ]
null
null
null
projects/research/text-processors/to_utf8_trys/data_processor_utf8_autoconv_trys/sampler.cc
zaqwes8811/smart-vocabulary-cards
abeab5c86b1c6f68d8796475cba80c4f2c6055ff
[ "Apache-2.0" ]
11
2015-01-25T14:22:52.000Z
2015-09-08T09:59:38.000Z
projects/research/text-processors/to_utf8_trys/data_processor_utf8_autoconv_trys/sampler.cc
zaqwes8811/vocabulary-cards
abeab5c86b1c6f68d8796475cba80c4f2c6055ff
[ "Apache-2.0" ]
null
null
null
// encoding : utf8 // "Copyright [year] <Copyright Owner>" [legal/copyright] #include <app-server-code/data_processor/sampler_uni_header.h> // где должна проходить граница простр. имен? namespace tmitter_web_service { //} // namespace tmitter_web_service using std::string; using std::vector; using std::size_t; using simple_type_processors::int2str; using simple_type_processors::hl; using simple_type_processors::uint8; //int НачальнаяОбрабокаПолучДанных() // AA 55 позоже убраны int Sampler::ProcessAnswer( uchar* input_buffer, int buffer_length, int &currentTransmitterIndex_, uint type_protocol) { uchar *localCopyBuffer = new uchar[buffer_length]; if (type_protocol == 0) { // Danger!!! bad loop!! for (int i = 0, k = 0; i < buffer_length; i++, k++) { localCopyBuffer[k] = input_buffer[i]; if (input_buffer[i] == 0xAA) { i++; } } } else if (type_protocol == 1) { for (int i = 0, k = 0; i < buffer_length; i++, k++) localCopyBuffer[k] = input_buffer[i]; } int ret = 0; uint iLen = (((uint)localCopyBuffer[0]) << 8) | ((uint)localCopyBuffer[1]); if ((iLen > buffer_length) || (iLen < 2)) { delete [] localCopyBuffer; ret = -3; return ret; // incorrect tag len or len buf } int typeTransmitter; // не соответсвует названию!! Danger!! int codeTransmitter; if (type_protocol == 0) { currentTransmitterIndex_ = static_cast<int>(localCopyBuffer[2]); typeTransmitter = static_cast<int>(localCopyBuffer[3]); codeTransmitter = static_cast<int>(localCopyBuffer[4]); } else if (type_protocol == 1) { currentTransmitterIndex_ = 1; typeTransmitter = 0xC1; codeTransmitter = (kRequestAllParameters); nominalPower___ = 2000; excitersTotal_ = 2; PABTotal_ = 10; preampPerPAB___ = 2; BCNTotal_ = 0; sizeBlockModParams_ = 0; sizeBlockTerminalAmpParams_ = 0; sizeBlockPreampParams_ = 0; sizeBlockBCNParams_ = 0; sizeEventsString_ = 0; sizeFailsString_ = 0; DBTotal_ = 0; sizeBlockDBParams_ = 0; transmitterID___ = 77; exciterType_ = 0; } else { // no use } // check control sum uchar control_sum = 0; if (type_protocol == 0) { for (int i = 0; i < (iLen-1); i++) control_sum += localCopyBuffer[i]; } else if (type_protocol == 1) { control_sum = 0xA1; for (int i = 0; i < (iLen-1); i++) { if (((uint)control_sum+(uint)localCopyBuffer[i]) >= 0x100) { control_sum += localCopyBuffer[i]; control_sum += 1; } else { control_sum += localCopyBuffer[i]; } } } if (control_sum != localCopyBuffer[iLen-1]) { delete [] localCopyBuffer; ret = -1; return ret; // cs error } // @TODO: <igor.a.lugansky@gmail.com> ^ выделить бы в один метод-инициализатор // распределение по типу запроса? switch (typeTransmitter) { // 41 Transmitter case 0xC1: switch (codeTransmitter) { case kRequestMainParameters: { uchar *ptrSourceArray = &localCopyBuffer[5]; ParseMainStateTmitter(ptrSourceArray); } break; // запрашивались все параметры? case kRequestAllParameters: { // Mayby Error!! uchar *ptrSourceArray = &localCopyBuffer[0]; // Danger!! LOG_ARRAY(first, length, buffer_name, marker) // marker=5 для type_proto = 0 //LOG_ARRAY(0, buffer_length, localCopyBuffer, 5) //int current_buffer_ptr_ = 0; ProcessAllParamsResponse(ptrSourceArray, type_protocol, buffer_length); } break; // еще запрос case kRequestProtocolEvent: { uchar *ptrSourceArray = &localCopyBuffer[5]; ptrSourceArray = ParseTransmitterEventsProto(ptrSourceArray); } break; // default: break; } break; // 44 - case 0xC4: switch (codeTransmitter) { case kRequestCfgTransmitter:{ uchar *ptrSourceArray = &localCopyBuffer[0]; ParseCfgSystem(ptrSourceArray); } break; default: break; } break; // code type is undefined default: ret = -2; } delete [] localCopyBuffer; return ret; } void Sampler::ParseCfgSystem(uchar* localCopyBuffer) { // первые 5 наверное заголовок // Danger!! LOG_ARRAY(first, length, buffer_name, marker) string name = "cfg system"; //LOG_ARRAY(0, 22, localCopyBuffer, 5, name) // мощность номинальная int current_nominal_power = localCopyBuffer[5]; current_nominal_power |= (((uint)(localCopyBuffer[6])) << 8); nominalPower___ = (current_nominal_power & 0x0f); nominalPower___ += ((current_nominal_power & 0xf0) >> 4)*10; nominalPower___ += ((current_nominal_power & 0xf00) >> 8)*100; nominalPower___ += ((current_nominal_power & 0xf000) >> 12)*1000; // число возбудителей numExcitersPack_ = localCopyBuffer[7]; excitersTotal_ = (numExcitersPack_ & 0x0f); excitersTotal_ += ((numExcitersPack_ & 0xf0) >> 4)*10; // число усилительных блоков ibNumPAB = localCopyBuffer[8]; PABTotal_ = (ibNumPAB & 0x0f); PABTotal_ += ((ibNumPAB & 0xf0) >> 4)*10; // число УП в Бумах ibNumPAinPAB = localCopyBuffer[9]; preampPerPAB___ = (ibNumPAinPAB & 0x0f); preampPerPAB___ += ((ibNumPAinPAB & 0xf0) >> 4)*10; // число комплексных нагрузок ibNumBCV = localCopyBuffer[10]; BCNTotal_ = (ibNumBCV & 0x0f); BCNTotal_ += ((ibNumBCV & 0xf0) >> 4)*10; // // вот что это? размены информационных блоков ibSizeIBMod = localCopyBuffer[11]; sizeBlockModParams_ = (ibSizeIBMod & 0x0f); sizeBlockModParams_ += ((ibSizeIBMod & 0xf0) >> 4)*10; // размер блока параметров предварителього усилителя ibSizeIBPAPAB = localCopyBuffer[12]; sizeBlockTerminalAmpParams_ = (ibSizeIBPAPAB & 0x0f); sizeBlockTerminalAmpParams_ += ((ibSizeIBPAPAB & 0xf0) >> 4)*10; ibSizeIBPrAPAB = localCopyBuffer[13]; sizeBlockPreampParams_ = (ibSizeIBPrAPAB & 0x0f); sizeBlockPreampParams_ += ((ibSizeIBPrAPAB & 0xf0) >> 4)*10; ibSizeIBBCV = localCopyBuffer[14]; sizeBlockBCNParams_ = (ibSizeIBBCV & 0x0f); sizeBlockBCNParams_ += ((ibSizeIBBCV & 0xf0) >> 4)*10; ibEventStringSize = localCopyBuffer[15]; sizeEventsString_ = (ibEventStringSize & 0x0f); sizeEventsString_ += ((ibEventStringSize & 0xf0) >> 4)*10; ibFailStringSize = localCopyBuffer[16]; sizeFailsString_ = (ibFailStringSize & 0x0f); sizeFailsString_ += ((ibFailStringSize & 0xf0) >> 4)*10; // // // детектора ibNUMDB = localCopyBuffer[17]; DBTotal_ = (ibNUMDB & 0x0f); DBTotal_ += ((ibNUMDB & 0xf0) >> 4)*10; ibSizeDB = localCopyBuffer[18]; sizeBlockDBParams_ = (ibSizeDB & 0x0f); sizeBlockDBParams_ += ((ibSizeDB & 0xf0) >> 4)*10; // остальное transmitterID___ = localCopyBuffer[19]; exciterType_ = localCopyBuffer[20]; countReservedTransmitters_ = localCopyBuffer[21]; } uchar* Sampler::ParseTransmitterEventsProto(uchar *ptrSourceArray) { uchar* repeater_ptr = NULL; return repeater_ptr; } void Sampler::ApplyMaxTemperature() { iMaxTemre = new_max_temperature_; iMaxStatus = iNewMaxStatus; int low = (currentBounds___.iTemLow); int hig = (currentBounds___.iTemMax); if (tmitterOnTgr___.D == 1) { // SNMP_CM11 if ((iMaxTemre<low) || (iMaxTemre > hig)) { if ((temperatureWasOk_) && TimoutIsOver()) { temperatureWasOk_ = false; //TickQueryPosition(); WriteCurrentMsg("Внимание, максимальная температура "+int2str(iMaxTemre)+" C", SNMP_CM11); AppendToCurrentRecord("", kSnmpWarning); } } else { if (!temperatureWasOk_) { temperatureWasOk_ = true; //TickQueryPosition(); WriteCurrentMsg("Максимальная температура норма", SNMP_CM11); AppendToCurrentRecord("", kSnmpOk); currentMWFCode_ |= kSnmpOk; } } } } // Похоже тут происходит перекачка буфера из rs в меструю базу данных // // void Sampler::ProcessAllParamsResponse(uchar* localCopyBuffer, uchar type_protocol, int bufferLength) { // настроим состояние Preprocess(); // установка состояния ParsePkgAndChangeState(localCopyBuffer, type_protocol, bufferLength); // обработка ListLines msgSet = Rpt( localCopyBuffer, type_protocol, bufferLength); // To log journal.PutSetRecords(msgSet); // Отправляем накопленное в журнал, жмем на спусковой крючок. const int kSNMPEventSend_ = 1; #ifndef _CROSS_GCC SetEvent(externalEventsArray_[kSNMPEventSend_]); #endif // _CROSS_GCC // доработка - завершающий этап Postprocess(); } void Sampler::Preprocess() { new_max_temperature_ = -200; hasMsgForSnmp_ = false; currentMWFCode_ = 0; counterFailsAndWarns_ = currentQueryIndex_; //newFailOccure_ = false; statusRecordIndex_ = 0; // Очистка очередей для SNMP, нужно бы сделать копию stringMsgsQuerySTL_.clear(); HLTypeCodesQuerySTL_.clear(); LLTypeCodesQuerySTL_.clear(); } void Sampler::Postprocess() { // прочая обработка ApplyMaxTemperature(); // if (hasMsgForSnmp_) { // спусковой крючок - обновит границы? чего? //SetEvent(externalEventsArray_[kBoundUpdate_]); //} // Если в(ы)ключен, то нужно сбросить FSM if (tmitterOnTgr___.IsChange()) { if (tmitterOnTgr___.D == 0) { RstSamplerFSM(); } } // пока просто очищаем msgsSetFromOnIteration_.clear(); } string Sampler::GetJournalContent(int& err) { err = 0; vector<string> content = journal.GetContent(); string result; result.reserve(4096); if (!content.empty()) { foreach_r_(string at, content) { result += at+kNewLineLog; } } return result; } } // namespace tmitter_web_service // Обобщенная обработка ответа? // Ведет запись в буффер журнала, но только во вложенных вызовах // #define ERRORED_PICE #ifndef ERRORED_PICE int Sampler::ProcessAnswer( uchar* input_buffer, // есть еще какой-то заголовок int buffer_length, int &currentTransmitterIndex_, uint type_protocol) { uchar *localCopyBuffer = new uchar[buffer_length]; int typeTransmitter; // не соотв. название, кажется! int codeTransmitter; int ret = 0; uint iLen = (((uint)localCopyBuffer[0]) << 8) | ((uint)localCopyBuffer[1]); uchar control_sum = 0; // разделение по протоколам if (type_protocol == 0) { // Danger!!! bad loop!! for (int i = 0, k = 0; i < buffer_length; i++, k++) { localCopyBuffer[k] = input_buffer[i]; if (input_buffer[i] == 0xAA) { i++; } } if ((iLen > buffer_length) || (iLen < 2)) { delete [] localCopyBuffer; ret = -3; return ret; // incorrect tag len or len buf } currentTransmitterIndex_ = static_cast<int>(localCopyBuffer[2]); typeTransmitter = static_cast<int>(localCopyBuffer[3]); codeTransmitter = static_cast<int>(localCopyBuffer[4]); // check control sum for (int i = 0; i < (iLen-1); i++) control_sum += localCopyBuffer[i]; if (control_sum != localCopyBuffer[iLen-1]) { delete [] localCopyBuffer; ret = -1; return ret; // cs error } // другой протокол } else if (type_protocol == 1) { for (int i = 0, k = 0; i < buffer_length; i++, k++) localCopyBuffer[k] = input_buffer[i]; if ((iLen > buffer_length) || (iLen < 2)) { delete [] localCopyBuffer; ret = -3; return ret; // incorrect tag len or len buf } currentTransmitterIndex_ = 1; typeTransmitter = 0xC1; codeTransmitter = (kRequestAllParameters); nominalPower___ = 2000; excitersTotal_ = 2; PABTotal_ = 10; preampPerPAB___ = 2; BCNTotal_ = 0; sizeBlockModParams_ = 0; sizeBlockTerminalAmpParams_ = 0; sizeBlockPreampParams_ = 0; sizeBlockBCNParams_ = 0; sizeEventsString_ = 0; sizeFailsString_ = 0; DBTotal_ = 0; sizeBlockDBParams_ = 0; transmitterID___ = 77; exciterType_ = 0; // check control sum control_sum = 0xA1; for (int i = 0; i < (iLen-1); i++) { if (((uint)control_sum+(uint)localCopyBuffer[i]) >= 0x100) { control_sum += localCopyBuffer[i]; control_sum += 1; } else { control_sum += localCopyBuffer[i]; } } if (control_sum != localCopyBuffer[iLen-1]) { delete [] localCopyBuffer; ret = -1; return ret; // cs error } } else { LOG_I("Protocol no supported"); return -4; } #endif // ERRORED_PICE
29.309955
95
0.624624
[ "vector" ]
b110a774cedc3c86e5c3b72b3382b8c9b8cdc9b6
3,533
hpp
C++
include/LIEF/ELF/Segment.hpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
2
2021-12-31T07:25:05.000Z
2022-03-05T15:03:00.000Z
include/LIEF/ELF/Segment.hpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
null
null
null
include/LIEF/ELF/Segment.hpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2021 R. Thomas * Copyright 2017 - 2021 Quarkslab * * 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. */ #ifndef LIEF_ELF_SEGMENT_H_ #define LIEF_ELF_SEGMENT_H_ #include <string> #include <vector> #include <iostream> #include <memory> #include "LIEF/Object.hpp" #include "LIEF/visibility.h" #include "LIEF/ELF/type_traits.hpp" #include "LIEF/ELF/enums.hpp" namespace LIEF { namespace ELF { namespace DataHandler { class Handler; } class Parser; class Binary; class Section; struct Elf64_Phdr; struct Elf32_Phdr; //! @brief Class which represent segments class LIEF_API Segment : public Object { friend class Parser; friend class Section; friend class Binary; public: Segment(); Segment(const std::vector<uint8_t>& header, ELF_CLASS type); Segment(const std::vector<uint8_t>& header); Segment(const Elf64_Phdr* header); Segment(const Elf32_Phdr* header); virtual ~Segment(); Segment& operator=(Segment other); Segment(const Segment& other); void swap(Segment& other); SEGMENT_TYPES type() const; ELF_SEGMENT_FLAGS flags() const; uint64_t file_offset() const; uint64_t virtual_address() const; uint64_t physical_address() const; uint64_t physical_size() const; uint64_t virtual_size() const; uint64_t alignment() const; std::vector<uint8_t> content() const; bool has(ELF_SEGMENT_FLAGS flag) const; bool has(const Section& section) const; bool has(const std::string& section_name) const; void add(ELF_SEGMENT_FLAGS c); void remove(ELF_SEGMENT_FLAGS c); void type(SEGMENT_TYPES type); void flags(ELF_SEGMENT_FLAGS flags); void clear_flags(); void file_offset(uint64_t fileOffset); void virtual_address(uint64_t virtualAddress); void physical_address(uint64_t physicalAddress); void physical_size(uint64_t physicalSize); void virtual_size(uint64_t virtualSize); void alignment(uint64_t alignment); void content(const std::vector<uint8_t>& content); void content(std::vector<uint8_t>&& content); template<typename T> T get_content_value(size_t offset) const; template<typename T> void set_content_value(size_t offset, T value); size_t get_content_size() const; it_sections sections(); it_const_sections sections() const; virtual void accept(Visitor& visitor) const override; Segment& operator+=(ELF_SEGMENT_FLAGS c); Segment& operator-=(ELF_SEGMENT_FLAGS c); bool operator==(const Segment& rhs) const; bool operator!=(const Segment& rhs) const; LIEF_API friend std::ostream& operator<<(std::ostream& os, const Segment& segment); private: SEGMENT_TYPES type_; ELF_SEGMENT_FLAGS flags_; uint64_t file_offset_; uint64_t virtual_address_; uint64_t physical_address_; uint64_t size_; uint64_t virtual_size_; uint64_t alignment_; sections_t sections_; DataHandler::Handler* datahandler_{nullptr}; std::vector<uint8_t> content_c_; }; } } #endif /* _ELF_SEGMENT_H_ */
28.264
85
0.729408
[ "object", "vector" ]
b1111a383e6faae280c2918c20ba0e2f50cd317f
7,507
cpp
C++
main/extensions/test/ole/unoTocomCalls/Test/Test.cpp
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/extensions/test/ole/unoTocomCalls/Test/Test.cpp
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/extensions/test/ole/unoTocomCalls/Test/Test.cpp
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // Test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "../XCallback_Impl/XCallback_Impl.h" #include "../XCallback_Impl/XCallback_Impl_i.c" CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() HRESULT doTest(); int main(int argc, char* argv[]) { HRESULT hr; if( FAILED( hr=CoInitialize(NULL))) { _tprintf(_T("CoInitialize failed \n")); return -1; } _Module.Init( ObjectMap, GetModuleHandle( NULL)); if( FAILED(hr=doTest())) { _com_error err( hr); const TCHAR * errMsg= err.ErrorMessage(); MessageBox( NULL, errMsg, "Test failed", MB_ICONERROR); } _Module.Term(); CoUninitialize(); return 0; } HRESULT doTest() { HRESULT hr= S_OK; CComPtr<IUnknown> spUnk; hr= spUnk.CoCreateInstance(L"com.sun.star.ServiceManager"); if( FAILED( hr)) return hr; CComDispatchDriver manager( spUnk); CComVariant param( L"oletest.OleTest"); CComVariant retVal; hr= manager.Invoke1((LPCOLESTR)L"createInstance", &param, &retVal ); CComDispatchDriver oletest( retVal.punkVal); spUnk.Release(); hr= spUnk.CoCreateInstance(L"XCallback_Impl.Callback"); if( FAILED( hr)) return hr; CComQIPtr<IDispatch> paramDisp(spUnk); //###################################################################### // out parameters //###################################################################### CComVariant param1( paramDisp); CComVariant param2(1); // oletest calls XCallback::func1 hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::returnInterface param2= 2; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outInterface param2= 3; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outStruct param2= 4; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outEnum param2= 5; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outSeqAny param2= 6; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outAny param2= 7; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outBool param2= 8; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outChar param2= 9; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outString param2= 10; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outFloat param2= 11; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outDouble param2= 12; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outByte param2= 13; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outShort param2= 14; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outLong param2= 15; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outValuesMixed param2= 30; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outValuesAll param2= 31; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::outSeqByte // Does not work currently because Sequences are always converted to // SAFEARRAY( VARIANT) // param2= 32; // hr= oletest.Invoke2(L"testInterface", &param1, &param2); //###################################################################### // in / out parameters //###################################################################### // XCallback::inoutInterface param2= 100; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutStruct param2= 101; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutEnum param2= 102; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutSeqAny param2= 103; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutAny param2= 104; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutBool param2= 105; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutChar param2= 106; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutString param2= 107; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutFloat param2= 108; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutDouble param2= 109; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutByte param2= 110; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutShort param2= 111; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutLong param2= 112; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutValuesAll param2=120; hr= oletest.Invoke2(L"testInterface", &param1, &param2); //###################################################################### // in parameters //###################################################################### // XCallback::inValues param2= 200; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inSeqByte // SAFEARRAY( VARIANT) param2= 201; hr= oletest.Invoke2(L"testInterface", &param1, &param2); //XCallback::inSeqXEventListener param2= 202; hr= oletest.Invoke2(L"testInterface", &param1, &param2); //###################################################################### // The UNO test component OleTest calls on XCallback_Impl.Callback directly // that is the COM object has not been past a parameter but rather OleTest // creates the COM object itself //###################################################################### // XCallback::outValuesAll // does not work currently param2= 300; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutValuesAll param2= 301; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inoutValues param2= 302; hr= oletest.Invoke2(L"testInterface", &param1, &param2); // XCallback::inValues param2= 303; hr= oletest.Invoke2(L"testInterface", &param1, &param2); //###################################################################### // Test a COM object which implements several interfaces. //###################################################################### CComQIPtr<IDispatch> dispSimple; hr= dispSimple.CoCreateInstance(L"XCallback_Impl.Simple"); CComVariant varSimple( dispSimple); param2= 0; hr= oletest.Invoke2(L"testInterface2", &varSimple, &param2); return hr; } // VARIANT CComVariant VT_UNKNOWN VT_DISPATCH V_UI1 CComDispatchDriver WINAPI
30.893004
77
0.638737
[ "object" ]
b115c7220db8c0c8672a758041f969d9693f0008
2,548
hpp
C++
psrdada_cpp/effelsberg/edd/test/SKTestVector.hpp
MPIfR-BDG/psrdada_cpp
aa9436e59eeb6ee597173caeba8a9e15db8d7d46
[ "MIT" ]
null
null
null
psrdada_cpp/effelsberg/edd/test/SKTestVector.hpp
MPIfR-BDG/psrdada_cpp
aa9436e59eeb6ee597173caeba8a9e15db8d7d46
[ "MIT" ]
3
2020-02-15T12:57:36.000Z
2020-04-08T14:48:57.000Z
psrdada_cpp/effelsberg/edd/test/SKTestVector.hpp
MPIfR-BDG/psrdada_cpp
aa9436e59eeb6ee597173caeba8a9e15db8d7d46
[ "MIT" ]
5
2020-01-09T14:34:54.000Z
2022-03-14T07:15:39.000Z
#ifndef PSRDADA_CPP_EFFELSBERG_EDD_SKTESTVECTOR_HPP #define PSRDADA_CPP_EFFELSBERG_EDD_SKTESTVECTOR_HPP #include "psrdada_cpp/common.hpp" #include <complex> #include <vector> #include <functional> #include <numeric> #include <random> #include <algorithm> namespace psrdada_cpp { namespace effelsberg { namespace edd { namespace test { #define DEFAULT_MEAN 0 //default mean for normal ditribution test vector #define DEFAULT_STD 0.5 //default standard deviation for normal ditribution test vector class SKTestVector{ public: /** * @param sample_size size of test vector * window_size number of samples in a window * with_rfi Flag to include RFI in test vector * rfi_frequency frequency of RFI * rfi_amplitude amplitude of RFI * mean mean for normal distribution test vector * std standard deviation for normal distribution test vector */ SKTestVector(std::size_t sample_size, std::size_t window_size, bool with_rfi, float rfi_frequency, float rfi_amplitude, float mean = DEFAULT_MEAN, float std = DEFAULT_STD); ~SKTestVector(); /** * @brief generates test vector * * @detail The test vector is a normal distribution vector and contains RFI if the flag with_rfi is set to true. * * @param rfi_windows vector of window indices on which the RFI has to be added. * test_samples output test vector */ void generate_test_vector(std::vector<int> const& rfi_windows, std::vector<std::complex<float>> &test_samples); private: /** * @brief generates a normal distribution vector for the default or given mean and standard deviation. * * @param samples output normal distribution test vector * */ void generate_normal_distribution_vector(std::vector<std::complex<float>> &samples); /** * @brief generates rfi signal of frequency = _rfi_frequency and size = _window_size * * @param rfi_samples output RFI vector * */ void generate_rfi_vector(std::vector<std::complex<float>> &rfi_samples); std::size_t _sample_size; std::size_t _window_size; bool _with_rfi; float _rfi_frequency; float _rfi_amplitude; float _mean; float _std; }; } //test } //edd } //effelsberg } //psrdada_cpp #endif //PSRDADA_CPP_EFFELSBERG_EDD_SKTESTVECTOR_HPP
34.432432
118
0.655808
[ "vector" ]
b11a51a358f349a4d23c0825869ecef6e21b4dba
434
cpp
C++
Array/Intersection of Two Arrays/IntersectionOfTwoArrays.cpp
steveLauwh/Algorithms
e8ce0c5cc2a54fbe9700ed8c02acf0f758243eaa
[ "Apache-2.0" ]
39
2018-09-19T06:57:33.000Z
2022-01-29T09:11:20.000Z
Array/Intersection of Two Arrays/IntersectionOfTwoArrays.cpp
steveLauwh/Data-Structures-And-Algorithms
e8ce0c5cc2a54fbe9700ed8c02acf0f758243eaa
[ "Apache-2.0" ]
null
null
null
Array/Intersection of Two Arrays/IntersectionOfTwoArrays.cpp
steveLauwh/Data-Structures-And-Algorithms
e8ce0c5cc2a54fbe9700ed8c02acf0f758243eaa
[ "Apache-2.0" ]
17
2018-07-09T08:33:14.000Z
2021-12-08T09:30:01.000Z
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> s(nums1.begin(), nums1.end()); set<int> ret; for (int i = 0; i < nums2.size(); i++) { if (s.find(nums2[i]) != s.end()) { ret.insert(nums2[i]); } } return vector<int>(ret.begin(), ret.end()); } };
22.842105
70
0.419355
[ "vector" ]
b11f26edabbf56ea62101834bc69775a9e863905
11,451
cpp
C++
Plugins/ProceduralMeshes/Source/ProceduralMeshes/Private/SimpleCylinderActor.cpp
AsifulHaque/ProceduralMeshDemos
585425ba563670b83c4d3c8834d0d2fa9ffaa4d7
[ "MIT" ]
289
2016-05-22T10:12:39.000Z
2022-03-25T19:36:37.000Z
Plugins/ProceduralMeshes/Source/ProceduralMeshes/Private/SimpleCylinderActor.cpp
TriAxis-Games/ProceduralMeshDemos
d033e0e6a6103f0406b6b9b2757d069663d9a3d1
[ "MIT" ]
9
2016-05-22T12:40:24.000Z
2022-02-20T20:58:31.000Z
Plugins/ProceduralMeshes/Source/ProceduralMeshes/Private/SimpleCylinderActor.cpp
TriAxis-Games/ProceduralMeshDemos
d033e0e6a6103f0406b6b9b2757d069663d9a3d1
[ "MIT" ]
63
2016-06-14T08:39:07.000Z
2022-03-26T13:20:01.000Z
// Copyright Sigurdur Gunnarsson. All Rights Reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // Example cylinder mesh #include "SimpleCylinderActor.h" #include "Providers/RuntimeMeshProviderStatic.h" ASimpleCylinderActor::ASimpleCylinderActor() { PrimaryActorTick.bCanEverTick = false; StaticProvider = CreateDefaultSubobject<URuntimeMeshProviderStatic>(TEXT("RuntimeMeshProvider-Static")); StaticProvider->SetShouldSerializeMeshData(false); } void ASimpleCylinderActor::OnConstruction(const FTransform& Transform) { Super::OnConstruction(Transform); GenerateMesh(); } // This is called when actor is already in level and map is opened void ASimpleCylinderActor::PostLoad() { Super::PostLoad(); GenerateMesh(); } void ASimpleCylinderActor::SetupMeshBuffers() { int32 VertexCount = RadialSegmentCount * 4; // 4 verts per face int32 TriangleCount = RadialSegmentCount * 2 * 3; // 2 triangles per face // Count extra vertices if double sided if (bDoubleSided) { VertexCount = VertexCount * 2; TriangleCount = TriangleCount * 2; } // Count vertices for caps if set if (bCapEnds) { // Each cap adds as many verts as there are verts in a circle // 2x Number of vertices x3 VertexCount += 2 * (RadialSegmentCount - 2) * 3; TriangleCount += 2 * (RadialSegmentCount - 2) * 3; } if (VertexCount != Positions.Num()) { Positions.Empty(); Positions.AddUninitialized(VertexCount); Normals.Empty(); Normals.AddUninitialized(VertexCount); Tangents.Empty(); Tangents.AddUninitialized(VertexCount); TexCoords.Empty(); TexCoords.AddUninitialized(VertexCount); } if (TriangleCount != Triangles.Num()) { Triangles.Empty(); Triangles.AddUninitialized(TriangleCount); } } void ASimpleCylinderActor::GenerateMesh() { GetRuntimeMeshComponent()->Initialize(StaticProvider); StaticProvider->ClearSection(0, 0); if (Height <= 0) { return; } SetupMeshBuffers(); GenerateCylinder(Positions, Triangles, Normals, Tangents, TexCoords, Height, Radius, RadialSegmentCount, bCapEnds, bDoubleSided, bSmoothNormals); const TArray<FColor> EmptyColors{}; StaticProvider->CreateSectionFromComponents(0, 0, 0, Positions, Triangles, Normals, TexCoords, EmptyColors, Tangents, ERuntimeMeshUpdateFrequency::Infrequent, false); StaticProvider->SetupMaterialSlot(0, TEXT("CylinderMaterial"), Material); } void ASimpleCylinderActor::GenerateCylinder(TArray<FVector>& InVertices, TArray<int32>& InTriangles, TArray<FVector>& InNormals, TArray<FRuntimeMeshTangent>& InTangents, TArray<FVector2D>& InTexCoords, const float InHeight, const float InWidth, const int32 InCrossSectionCount, const bool bInCapEnds, const bool bInDoubleSided, const bool bInSmoothNormals/* = true*/) { // ------------------------------------------------------- // Basic setup int32 VertexIndex = 0; int32 TriangleIndex = 0; // ------------------------------------------------------- // Make a cylinder section const float AngleBetweenQuads = (2.0f / static_cast<float>(InCrossSectionCount)) * PI; const float VMapPerQuad = 1.0f / static_cast<float>(InCrossSectionCount); const FVector Offset = FVector(0, 0, InHeight); // Start by building up vertices that make up the cylinder sides for (int32 QuadIndex = 0; QuadIndex < InCrossSectionCount; QuadIndex++) { const float Angle = static_cast<float>(QuadIndex) * AngleBetweenQuads; const float NextAngle = static_cast<float>(QuadIndex + 1) * AngleBetweenQuads; // Set up the vertices const FVector P0 = FVector(FMath::Cos(Angle) * InWidth, FMath::Sin(Angle) * InWidth, 0.f); const FVector P1 = FVector(FMath::Cos(NextAngle) * InWidth, FMath::Sin(NextAngle) * InWidth, 0.f); const FVector P2 = P1 + Offset; const FVector P3 = P0 + Offset; // Set up the quad triangles int32 VertIndex1 = VertexIndex++; int32 VertIndex2 = VertexIndex++; int32 VertIndex3 = VertexIndex++; int32 VertIndex4 = VertexIndex++; InVertices[VertIndex1] = P0; InVertices[VertIndex2] = P1; InVertices[VertIndex3] = P2; InVertices[VertIndex4] = P3; // Now create two triangles from those four vertices // The order of these (clockwise/counter-clockwise) dictates which way the normal will face. InTriangles[TriangleIndex++] = VertIndex4; InTriangles[TriangleIndex++] = VertIndex3; InTriangles[TriangleIndex++] = VertIndex1; InTriangles[TriangleIndex++] = VertIndex3; InTriangles[TriangleIndex++] = VertIndex2; InTriangles[TriangleIndex++] = VertIndex1; // UVs. Note that Unreal UV origin (0,0) is top left InTexCoords[VertIndex1] = FVector2D(1.0f - (VMapPerQuad * QuadIndex), 1.0f); InTexCoords[VertIndex2] = FVector2D(1.0f - (VMapPerQuad * (QuadIndex + 1)), 1.0f); InTexCoords[VertIndex3] = FVector2D(1.0f - (VMapPerQuad * (QuadIndex + 1)), 0.0f); InTexCoords[VertIndex4] = FVector2D(1.0f - (VMapPerQuad * QuadIndex), 0.0f); // Normals const FVector NormalCurrent = FVector::CrossProduct(InVertices[VertIndex1] - InVertices[VertIndex3], InVertices[VertIndex2] - InVertices[VertIndex3]).GetSafeNormal(); if (bInSmoothNormals) { // To smooth normals we give the vertices different values than the polygon they belong to. // GPUs know how to interpolate between those. // I do this here as an average between normals of two adjacent polygons const float NextNextAngle = static_cast<float>(QuadIndex + 2) * AngleBetweenQuads; const FVector P4 = FVector(FMath::Cos(NextNextAngle) * InWidth, FMath::Sin(NextNextAngle) * InWidth, 0.f); // p1 to p4 to p2 const FVector NormalNext = FVector::CrossProduct(P1 - P2, P4 - P2).GetSafeNormal(); const FVector AverageNormalRight = ((NormalCurrent + NormalNext) / 2).GetSafeNormal(); const float PreviousAngle = static_cast<float>(QuadIndex - 1) * AngleBetweenQuads; const FVector PMinus1 = FVector(FMath::Cos(PreviousAngle) * InWidth, FMath::Sin(PreviousAngle) * InWidth, 0.f); // p0 to p3 to pMinus1 const FVector NormalPrevious = FVector::CrossProduct(P0 - PMinus1, P3 - PMinus1).GetSafeNormal(); const FVector AverageNormalLeft = ((NormalCurrent + NormalPrevious) / 2).GetSafeNormal(); InNormals[VertIndex1] = AverageNormalLeft; InNormals[VertIndex2] = AverageNormalRight; InNormals[VertIndex3] = AverageNormalRight; InNormals[VertIndex4] = AverageNormalLeft; } else { // If not smoothing we just set the vertex normal to the same normal as the polygon they belong to InNormals[VertIndex1] = InNormals[VertIndex2] = InNormals[VertIndex3] = InNormals[VertIndex4] = NormalCurrent; } // Tangents (perpendicular to the surface) const FVector SurfaceTangent = (P0 - P1).GetSafeNormal(); InTangents[VertIndex1] = InTangents[VertIndex2] = InTangents[VertIndex3] = InTangents[VertIndex4] = SurfaceTangent; // ------------------------------------------------------- // If double sided, create extra polygons but face the normals the other way. if (bInDoubleSided) { VertIndex1 = VertexIndex++; VertIndex2 = VertexIndex++; VertIndex3 = VertexIndex++; VertIndex4 = VertexIndex++; InVertices[VertIndex1] = P0; InVertices[VertIndex2] = P1; InVertices[VertIndex3] = P2; InVertices[VertIndex4] = P3; // Reverse the poly order to face them the other way InTriangles[TriangleIndex++] = VertIndex4; InTriangles[TriangleIndex++] = VertIndex1; InTriangles[TriangleIndex++] = VertIndex3; InTriangles[TriangleIndex++] = VertIndex3; InTriangles[TriangleIndex++] = VertIndex1; InTriangles[TriangleIndex++] = VertIndex2; // UVs (Unreal 1,1 is top left) InTexCoords[VertIndex1] = FVector2D(1.0f - (VMapPerQuad * QuadIndex), 1.0f); InTexCoords[VertIndex2] = FVector2D(1.0f - (VMapPerQuad * (QuadIndex + 1)), 1.0f); InTexCoords[VertIndex3] = FVector2D(1.0f - (VMapPerQuad * (QuadIndex + 1)), 0.0f); InTexCoords[VertIndex4] = FVector2D(1.0f - (VMapPerQuad * QuadIndex), 0.0f); // Just simple (unsmoothed) normal for these InNormals[VertIndex1] = InNormals[VertIndex2] = InNormals[VertIndex3] = InNormals[VertIndex4] = NormalCurrent; // Tangents (perpendicular to the surface) const FVector SurfaceTangentDbl = (P0 - P1).GetSafeNormal(); InTangents[VertIndex1] = InTangents[VertIndex2] = InTangents[VertIndex3] = InTangents[VertIndex4] = SurfaceTangentDbl; } // ------------------------------------------------------- // Caps are closed here by triangles that start at 0, then use the points along the circle for the other two corners. // A better looking method uses a vertex in the center of the circle, but uses two more polygons. We will demonstrate that in a different sample. if (QuadIndex != 0 && QuadIndex != InCrossSectionCount - 1 && bInCapEnds) { // Bottom cap FVector CapVertex0 = FVector(FMath::Cos(0) * InWidth, FMath::Sin(0) * InWidth, 0.f); FVector CapVertex1 = FVector(FMath::Cos(Angle) * InWidth, FMath::Sin(Angle) * InWidth, 0.f); FVector CapVertex2 = FVector(FMath::Cos(NextAngle) * InWidth, FMath::Sin(NextAngle) * InWidth, 0.f); VertIndex1 = VertexIndex++; VertIndex2 = VertexIndex++; VertIndex3 = VertexIndex++; InVertices[VertIndex1] = CapVertex0; InVertices[VertIndex2] = CapVertex1; InVertices[VertIndex3] = CapVertex2; InTriangles[TriangleIndex++] = VertIndex1; InTriangles[TriangleIndex++] = VertIndex2; InTriangles[TriangleIndex++] = VertIndex3; InTexCoords[VertIndex1] = FVector2D(0.5f - (FMath::Cos(0) / 2.0f), 0.5f - (FMath::Sin(0) / 2.0f)); InTexCoords[VertIndex2] = FVector2D(0.5f - (FMath::Cos(-Angle) / 2.0f), 0.5f - (FMath::Sin(-Angle) / 2.0f)); InTexCoords[VertIndex3] = FVector2D(0.5f - (FMath::Cos(-NextAngle) / 2.0f), 0.5f - (FMath::Sin(-NextAngle) / 2.0f)); FVector CapNormalCurrent = FVector::CrossProduct(InVertices[VertIndex1] - InVertices[VertIndex3], InVertices[VertIndex2] - InVertices[VertIndex3]).GetSafeNormal(); InNormals[VertIndex1] = InNormals[VertIndex2] = InNormals[VertIndex3] = CapNormalCurrent; // Tangents (perpendicular to the surface) FVector SurfaceTangentCap = (P0 - P1).GetSafeNormal(); InTangents[VertIndex1] = InTangents[VertIndex2] = InTangents[VertIndex3] = SurfaceTangentCap; // Top cap CapVertex0 = CapVertex0 + Offset; CapVertex1 = CapVertex1 + Offset; CapVertex2 = CapVertex2 + Offset; VertIndex1 = VertexIndex++; VertIndex2 = VertexIndex++; VertIndex3 = VertexIndex++; InVertices[VertIndex1] = CapVertex0; InVertices[VertIndex2] = CapVertex1; InVertices[VertIndex3] = CapVertex2; InTriangles[TriangleIndex++] = VertIndex3; InTriangles[TriangleIndex++] = VertIndex2; InTriangles[TriangleIndex++] = VertIndex1; InTexCoords[VertIndex1] = FVector2D(0.5f - (FMath::Cos(0) / 2.0f), 0.5f - (FMath::Sin(0) / 2.0f)); InTexCoords[VertIndex2] = FVector2D(0.5f - (FMath::Cos(Angle) / 2.0f), 0.5f - (FMath::Sin(Angle) / 2.0f)); InTexCoords[VertIndex3] = FVector2D(0.5f - (FMath::Cos(NextAngle) / 2.0f), 0.5f - (FMath::Sin(NextAngle) / 2.0f)); CapNormalCurrent = FVector::CrossProduct(InVertices[VertIndex1] - InVertices[VertIndex3], InVertices[VertIndex2] - InVertices[VertIndex3]).GetSafeNormal(); InNormals[VertIndex1] = InNormals[VertIndex2] = InNormals[VertIndex3] = CapNormalCurrent; // Tangents (perpendicular to the surface) SurfaceTangentCap = (P0 - P1).GetSafeNormal(); InTangents[VertIndex1] = InTangents[VertIndex2] = InTangents[VertIndex3] = SurfaceTangentCap; } } }
41.945055
367
0.714697
[ "mesh", "transform" ]
b124bc44c83eade476e88ef6a569dcf55ecb22d6
5,255
cpp
C++
src/data/mzp.cpp
TheEZIC/mangetsu
808b57765617c7e7805472330db77bf6d05bcd74
[ "MIT" ]
2
2022-02-21T07:38:52.000Z
2022-03-02T17:04:52.000Z
src/data/mzp.cpp
TheEZIC/mangetsu
808b57765617c7e7805472330db77bf6d05bcd74
[ "MIT" ]
null
null
null
src/data/mzp.cpp
TheEZIC/mangetsu
808b57765617c7e7805472330db77bf6d05bcd74
[ "MIT" ]
1
2022-01-09T19:06:44.000Z
2022-01-09T19:06:44.000Z
#include <string.h> #include <mg/data/mzp.hpp> #include <mg/util/endian.hpp> namespace mg::data { void Mzp::MzpArchiveHeader::to_host_order() { archive_entry_count = le_to_host_u16(archive_entry_count); } void Mzp::MzpArchiveHeader::to_file_order() { archive_entry_count = host_to_le_u16(archive_entry_count); } void Mzp::MzpArchiveEntry::to_host_order() { sector_offset = le_to_host_u16(sector_offset); byte_offset = le_to_host_u16(byte_offset); size_sectors = le_to_host_u16(size_sectors); size_bytes = le_to_host_u16(size_bytes); } void Mzp::MzpArchiveEntry::to_file_order() { sector_offset = host_to_le_u16(sector_offset); byte_offset = host_to_le_u16(byte_offset); size_sectors = host_to_le_u16(size_sectors); size_bytes = host_to_le_u16(size_bytes); } void Mzp::MzpArchiveEntry::print() { fprintf(stderr, "MzpArchiveEntry:\n" " Sector offset: %08x\n" " Byte offset: %08x\n" " Size sectors: %08x\n" " Size lowbytes: %08x\n" " True offset: %08x\n" " True size: %08x\n", sector_offset, byte_offset, size_sectors, size_bytes, (sector_offset * SECTOR_SIZE) + byte_offset, entry_data_size()); } void Mzp::MzpArchiveEntry::set_offsets(uint32_t offset) { sector_offset = offset / SECTOR_SIZE; byte_offset = offset % SECTOR_SIZE; } void Mzp::MzpArchiveEntry::set_data_size(uint32_t size) { // Calculate the number of sectors our data crosses (rounding up) const bool crosses_sector = !!(size % SECTOR_SIZE); const unsigned sector_bound = crosses_sector ? (size / SECTOR_SIZE) + 1 : (size / SECTOR_SIZE); size_sectors = sector_bound; size_bytes = size & 0xFFFF; } void mzp_write(const Mzp &mzp, std::string &out) { // Clear output out.clear(); // Write header Mzp::MzpArchiveHeader header; memcpy(header.magic, Mzp::FILE_MAGIC, sizeof(Mzp::MzpArchiveHeader::magic)); header.archive_entry_count = mzp.entry_headers.size(); header.to_file_order(); out.resize(sizeof(header)); memcpy(&out[0], &header, sizeof(header)); // Calculate the data segment start std::string::size_type data_segment_start = sizeof(Mzp::MzpArchiveHeader) + sizeof(Mzp::MzpArchiveEntry) * mzp.entry_headers.size(); // Clone the header data so that we can recalculate it std::vector<Mzp::MzpArchiveEntry> entry_headers = mzp.entry_headers; std::string::size_type current_data_offset = 0; for (unsigned i = 0; i < mzp.entry_headers.size(); i++) { Mzp::MzpArchiveEntry &entry_header = entry_headers[i]; auto &entry_data = mzp.entry_data[i]; const std::string::size_type entry_size = entry_data.size(); entry_header.set_offsets(current_data_offset); entry_header.set_data_size(entry_size); current_data_offset += entry_size; // Pad current data offset to 16 byte boundary // const std::string::size_type real_data_end_addr = // data_segment_start + current_data_offset; // current_data_offset += 16 - (real_data_end_addr % 16); } // Calculate total file size const std::string::size_type output_size = data_segment_start + current_data_offset; out.resize(output_size, 0xFF); // Write out each datum pair, since we need to use the header to get the // correct data offset for (unsigned i = 0; i < mzp.entry_headers.size(); i++) { // Convert header to file order and emit auto &entry_header = entry_headers[i]; entry_header.to_file_order(); const std::string::size_type header_output_offset = sizeof(Mzp::MzpArchiveHeader) + sizeof(Mzp::MzpArchiveEntry) * i; memcpy(&out[header_output_offset], &entry_header, sizeof(entry_header)); // Insert data at data start + data offset auto &entry_data = mzp.entry_data[i]; memcpy(&out[data_segment_start + entry_header.data_offset_relative()], entry_data.data(), entry_data.size()); } } bool mzp_read(const std::string &data, Mzp &out) { // Is file large enough to have a header if (data.size() < sizeof(Mzp::MzpArchiveHeader)) { return false; } // Read off header out.header = *reinterpret_cast<const Mzp::MzpArchiveHeader *>(&data[0]); out.header.to_host_order(); // Valid magic? if (memcmp(out.header.magic, Mzp::FILE_MAGIC, sizeof(Mzp::MzpArchiveHeader::magic)) != 0) { return false; } // Clear output vecs out.entry_headers.clear(); out.entry_data.clear(); // Iterate the archive entries for (uint16_t i = 0; i < out.header.archive_entry_count; i++) { // Calculate start offset of header record std::string::size_type archive_header_offset = sizeof(Mzp::MzpArchiveHeader) + sizeof(Mzp::MzpArchiveEntry) * i; // Clone data Mzp::MzpArchiveEntry entry = *reinterpret_cast<const Mzp::MzpArchiveEntry *>( &data[archive_header_offset]); entry.to_host_order(); // Add to header out.entry_headers.emplace_back(entry); } // Scan through and extract the actual archive data for (auto &entry : out.entry_headers) { out.entry_data.emplace_back(&data[out.archive_entry_start_offset(entry)], entry.entry_data_size()); } return true; } } // namespace mg::data
33.685897
78
0.69039
[ "vector" ]
b128e032b837604dbd355adb2866ae2811ae719c
9,086
cpp
C++
wxWidgets-3.1.0/samples/ipc/baseclient.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
2
2016-10-15T05:12:16.000Z
2016-11-06T16:19:53.000Z
wxWidgets-3.1.0/samples/ipc/baseclient.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
14
2016-09-21T21:24:46.000Z
2016-11-15T07:54:21.000Z
wxWidgets-3.1.0/samples/ipc/baseclient.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Name: samples/ipc/baseclient.cpp // Purpose: IPC sample: console client // Author: Anders Larsen // Most of the code was stolen from: samples/ipc/client.cpp // (c) Julian Smart, Jurgen Doornik // Created: 2007-11-08 // Copyright: (c) 2007 Anders Larsen // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif // Settings common to both executables: determines whether // we're using TCP/IP or real DDE. #include "ipcsetup.h" #include "connection.h" #include "wx/timer.h" #include "wx/datetime.h" #include "wx/vector.h" class MyClient; // ---------------------------------------------------------------------------- // classes // ---------------------------------------------------------------------------- class MyApp : public wxApp { public: MyApp() { Connect(wxEVT_IDLE, wxIdleEventHandler(MyApp::OnIdle)); } virtual bool OnInit() wxOVERRIDE; virtual int OnExit() wxOVERRIDE; private: void OnIdle(wxIdleEvent& event); MyClient *m_client; }; class MyConnection : public MyConnectionBase { public: virtual bool DoExecute(const void *data, size_t size, wxIPCFormat format) wxOVERRIDE; virtual const void *Request(const wxString& item, size_t *size = NULL, wxIPCFormat format = wxIPC_TEXT) wxOVERRIDE; virtual bool DoPoke(const wxString& item, const void* data, size_t size, wxIPCFormat format) wxOVERRIDE; virtual bool OnAdvise(const wxString& topic, const wxString& item, const void *data, size_t size, wxIPCFormat format) wxOVERRIDE; virtual bool OnDisconnect() wxOVERRIDE; }; class MyClient : public wxClient, private wxTimer { public: MyClient(); virtual ~MyClient(); bool Connect(const wxString& sHost, const wxString& sService, const wxString& sTopic); void Disconnect(); wxConnectionBase *OnMakeConnection() wxOVERRIDE; bool IsConnected() { return m_connection != NULL; }; virtual void Notify() wxOVERRIDE; void StartNextTestIfNecessary(); private: void TestRequest(); void TestPoke(); void TestExecute(); void TestStartAdvise(); void TestStopAdvise(); void TestDisconnect(); MyConnection *m_connection; // the test functions to be executed by StartNextTestIfNecessary() typedef void (MyClient::*MyClientTestFunc)(); wxVector<MyClientTestFunc> m_tests; // number of seconds since the start of the test int m_step; }; // ============================================================================ // implementation // ============================================================================ wxIMPLEMENT_APP_CONSOLE(MyApp); // ---------------------------------------------------------------------------- // MyApp // ---------------------------------------------------------------------------- // The `main program' equivalent, creating the windows and returning the // main frame bool MyApp::OnInit() { if ( !wxApp::OnInit() ) return false; // Create a new client m_client = new MyClient; bool retval = m_client->Connect("localhost", "4242", "IPC TEST"); wxLogMessage("Client host=\"localhost\" port=\"4242\" topic=\"IPC TEST\" %s", retval ? "connected" : "failed to connect"); return retval; } int MyApp::OnExit() { delete m_client; return 0; } void MyApp::OnIdle(wxIdleEvent& event) { if ( m_client ) m_client->StartNextTestIfNecessary(); event.Skip(); } // ---------------------------------------------------------------------------- // MyClient // ---------------------------------------------------------------------------- MyClient::MyClient() : wxClient() { m_connection = NULL; m_step = 0; } bool MyClient::Connect(const wxString& sHost, const wxString& sService, const wxString& sTopic) { // suppress the log messages from MakeConnection() wxLogNull nolog; m_connection = (MyConnection *)MakeConnection(sHost, sService, sTopic); if ( !m_connection ) return false; Start(1000); return true; } wxConnectionBase *MyClient::OnMakeConnection() { return new MyConnection; } void MyClient::Disconnect() { if (m_connection) { m_connection->Disconnect(); wxDELETE(m_connection); wxLogMessage("Client disconnected from server"); } wxGetApp().ExitMainLoop(); } MyClient::~MyClient() { Disconnect(); } void MyClient::Notify() { // we shouldn't call wxIPC methods from here directly as we may be called // from inside an IPC call when using TCP/IP as the sockets are used in // non-blocking code and so can dispatch events, including the timer ones, // while waiting for IO and so starting another IPC call would result in // fatal reentrancies -- instead, just set a flag and perform the test // indicated by it later from our idle event handler MyClientTestFunc testfunc = NULL; switch ( m_step++ ) { case 0: testfunc = &MyClient::TestRequest; break; case 1: testfunc = &MyClient::TestPoke; break; case 2: testfunc = &MyClient::TestExecute; break; case 3: testfunc = &MyClient::TestStartAdvise; break; case 10: testfunc = &MyClient::TestStopAdvise; break; case 15: testfunc = &MyClient::TestDisconnect; // We don't need the timer any more, we're going to exit soon. Stop(); break; default: // No need to wake up idle handling. return; } m_tests.push_back(testfunc); wxWakeUpIdle(); } void MyClient::StartNextTestIfNecessary() { while ( !m_tests.empty() ) { MyClientTestFunc testfunc = m_tests.front(); m_tests.erase(m_tests.begin()); (this->*testfunc)(); } } void MyClient::TestRequest() { size_t size; m_connection->Request("Date"); m_connection->Request("Date+len", &size); m_connection->Request("bytes[3]", &size, wxIPC_PRIVATE); } void MyClient::TestPoke() { wxString s = wxDateTime::Now().Format(); m_connection->Poke("Date", s); s = wxDateTime::Now().FormatTime() + " " + wxDateTime::Now().FormatDate(); m_connection->Poke("Date", (const char *)s.c_str(), s.length() + 1); char bytes[3]; bytes[0] = '1'; bytes[1] = '2'; bytes[2] = '3'; m_connection->Poke("bytes[3]", bytes, 3, wxIPC_PRIVATE); } void MyClient::TestExecute() { wxString s = "Date"; m_connection->Execute(s); m_connection->Execute((const char *)s.c_str(), s.length() + 1); char bytes[3]; bytes[0] = '1'; bytes[1] = '2'; bytes[2] = '3'; m_connection->Execute(bytes, WXSIZEOF(bytes)); } void MyClient::TestStartAdvise() { wxLogMessage("StartAdvise(\"something\")"); m_connection->StartAdvise("something"); } void MyClient::TestStopAdvise() { wxLogMessage("StopAdvise(\"something\")"); m_connection->StopAdvise("something"); } void MyClient::TestDisconnect() { Disconnect(); } // ---------------------------------------------------------------------------- // MyConnection // ---------------------------------------------------------------------------- bool MyConnection::OnAdvise(const wxString& topic, const wxString& item, const void *data, size_t size, wxIPCFormat format) { Log("OnAdvise", topic, item, data, size, format); return true; } bool MyConnection::OnDisconnect() { wxLogMessage("OnDisconnect()"); wxGetApp().ExitMainLoop(); return true; } bool MyConnection::DoExecute(const void *data, size_t size, wxIPCFormat format) { Log("Execute", wxEmptyString, wxEmptyString, data, size, format); bool retval = wxConnection::DoExecute(data, size, format); if (!retval) { wxLogMessage("Execute failed!"); } return retval; } const void *MyConnection::Request(const wxString& item, size_t *size, wxIPCFormat format) { const void *data = wxConnection::Request(item, size, format); Log("Request", wxEmptyString, item, data, size ? *size : wxNO_LEN, format); return data; } bool MyConnection::DoPoke(const wxString& item, const void *data, size_t size, wxIPCFormat format) { Log("Poke", wxEmptyString, item, data, size, format); return wxConnection::DoPoke(item, data, size, format); }
26.489796
133
0.55635
[ "vector" ]
b12de0ffd85429ebc1bf6e95a990b49c3cba716e
8,690
cpp
C++
src/crl_contact.cpp
inesc-tec-robotics/carlos_controller
ffcc45f24dd534bb953d5bd4a47badd3d3d5223d
[ "BSD-3-Clause" ]
null
null
null
src/crl_contact.cpp
inesc-tec-robotics/carlos_controller
ffcc45f24dd534bb953d5bd4a47badd3d3d5223d
[ "BSD-3-Clause" ]
null
null
null
src/crl_contact.cpp
inesc-tec-robotics/carlos_controller
ffcc45f24dd534bb953d5bd4a47badd3d3d5223d
[ "BSD-3-Clause" ]
null
null
null
#include "carlos_controller/crl_contact.h" #include "carlos_controller/crl_defines.h" #include <amn_common/amn_mnl_defines.h> #include <amn_common/amn_ik_lib.h> #include <amn_common/amn_lico_lib.h> #include <std_msgs/UInt8.h> #include <brics_actuator/JointVelocities.h> #include <ftm_msgs/ftm_defines.h> #include <std_srvs/Empty.h> using namespace carlos; ContactController::ContactController(ros::NodeHandle node, double sensor_offset, double period) { this->node = node; this->offset = sensor_offset; this->period = period; this->mode = CONTACT_MODE_STOPPED; ContactController::register_messages(); ContactController::register_services(); ContactController::install_params(); this->timer = node.createTimer(ros::Duration(period), &ContactController::timerCallback, this); this->timer.stop(); } /* timer callback */ void ContactController::timerCallback(const ros::TimerEvent& event) { //double torques[DOF]; //double velocities[DOF]; brics_actuator::JointVelocities msg; if(!ft_received || !arm_received) return; switch(this->mode){ case CONTACT_MODE_STOPPED: break; case CONTACT_MODE_AUTO: //get_joints_torque(&this->ft_readings, this->joints, torques, this->offset); //d_velocities_friction(this->joints, torques, velocities, period, DOF); msg.velocities = std::vector<brics_actuator::JointValue>(DOF); for(int i=0; i<DOF; i++){ msg.velocities[i].joint_uri = std::string(this->joints[i].name); msg.velocities[i].unit = "rad"; msg.velocities[i].value = this->velocities[i]*(1.0 - this->factor); } this->velPub.publish(msg); break; } } /* Communication funtions */ void ContactController::install_params(void) { XmlRpc::XmlRpcValue joint_names; this->node.getParam(JOINTS_NAMES, joint_names); ROS_ASSERT(joint_names.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<joint_names.size(); i++){ ROS_ASSERT(joint_names[i].getType() == XmlRpc::XmlRpcValue::TypeString); this->joints[i].name = static_cast<std::string>(joint_names[i]).c_str(); } XmlRpc::XmlRpcValue max_acc; this->node.getParam(JOINTS_MAX_ACC, max_acc); ROS_ASSERT(max_acc.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<max_acc.size(); i++){ ROS_ASSERT(max_acc[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].max_acc = max_acc[i]; } XmlRpc::XmlRpcValue max_vel; this->node.getParam(JOINTS_MAX_VEL, max_vel); ROS_ASSERT(max_vel.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<max_vel.size(); i++){ ROS_ASSERT(max_vel[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].max_vel = max_vel[i]; } XmlRpc::XmlRpcValue inertias; this->node.getParam(JOINTS_INERTIAS, inertias); ROS_ASSERT(inertias.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<inertias.size(); i++){ ROS_ASSERT(inertias[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].inertia = inertias[i]; } XmlRpc::XmlRpcValue frictions; this->node.getParam(JOINTS_FRICTIONS, frictions); ROS_ASSERT(frictions.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<frictions.size(); i++){ ROS_ASSERT(frictions[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].friction = frictions[i]; } XmlRpc::XmlRpcValue min_pos; this->node.getParam(JOINTS_MIN_POS, min_pos); ROS_ASSERT(min_pos.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<min_pos.size(); i++){ ROS_ASSERT(min_pos[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].min_pos = min_pos[i]; } XmlRpc::XmlRpcValue links_list; this->node.getParam(JOINTS_LINKS, links_list); ROS_ASSERT(links_list.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<links_list.size(); i++){ ROS_ASSERT(links_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].link = links_list[i]; } XmlRpc::XmlRpcValue max_pos; this->node.getParam(JOINTS_MAX_POS, max_pos); ROS_ASSERT(max_pos.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int32_t i=0; i<max_pos.size(); i++){ ROS_ASSERT(max_pos[i].getType() == XmlRpc::XmlRpcValue::TypeDouble); this->joints[i].max_pos = max_pos[i]; } /* XmlRpc::XmlRpcValue press; this->node.getParam(PARAM_STUD_PRESS, press); ROS_ASSERT(press.getType() == XmlRpc::XmlRpcValue::TypeDouble); this->stud_press = press; */ } void ContactController::register_messages(void) { this->velPub = this->node.advertise<brics_actuator::JointVelocities>(COMMAND_VEL_TOPIC, 10); } void ContactController::subscribe_messages(void) { fprintf(stdout, "Arm state name %s\n", ARM_CONTROLLER_STATE_TOPIC); this->armSubs = this->node.subscribe(ARM_CONTROLLER_STATE_TOPIC, 1, &ContactController::armStateHnd, this); fprintf(stdout, "ftm data topic --> %s\n", FTM_DATA_TOPIC); this->ftSubs = this->node.subscribe("/ftm75/measurement", 1, &ContactController::ftHnd, this); } void ContactController::unsubscribe_messages(void) { this->armSubs.shutdown(); this->ftSubs.shutdown(); } void ContactController::register_services(void) { this->resetSrv = this->node.serviceClient<std_srvs::Empty>(FTM_CALIBRATE_SRV); } /* Class functions */ contact_mode_t ContactController::set_mode(contact_mode_t mode) { fprintf(stdout, "Contact controller -> set mode hnd: %d\n", this->mode); switch(this->mode){ case CONTACT_MODE_STOPPED: this->mode = mode; if(this->mode == CONTACT_MODE_AUTO){ this->ft_received = 0; this->arm_received = 0; subscribe_messages(); this->timer.start(); } break; case CONTACT_MODE_AUTO: if(mode == CONTACT_MODE_STOPPED){ unsubscribe_messages(); this->mode = CONTACT_MODE_STOPPED; this->timer.stop(); this->stop_arm(); } break; } return this->mode; } contact_mode_t ContactController::get_mode(void) { return this->mode; } void ContactController::set_joint_velocities(double* vel, double press) { for(int i=0; i<DOF; i++) this->velocities[i] = vel[i]; this->stud_press = press; } void ContactController::set_joint_limits(double* min, double* max) { for(int i=0; i<DOF; i++){ this->joints[i].min_pos = min[i]; this->joints[i].max_pos = max[i]; } return; } void ContactController::stop_arm(void) { brics_actuator::JointVelocities msg; msg.velocities = std::vector<brics_actuator::JointValue>(DOF); for(int i=0; i<DOF; i++){ msg.velocities[i].joint_uri = std::string(this->joints[i].name); msg.velocities[i].unit = "rad"; msg.velocities[i].value = 0.0; } this->velPub.publish(msg); } /* message handlers */ void ContactController::armStateHnd(const pr2_controllers_msgs::JointTrajectoryControllerState::ConstPtr& msg) { if(arm_received == 0) arm_received = 1; for(int i=0; i<DOF; i++){ this->joints[i].position = msg->actual.positions[i]; this->joints[i].velocity = msg->actual.velocities[i]; } } void ContactController::ftHnd(const geometry_msgs::WrenchStamped::ConstPtr& msg) { double goal[DOF]; switch(this->mode){ case CONTACT_MODE_STOPPED:CONTACT_MODE_REACHED: break; case CONTACT_MODE_AUTO: if(!this->ft_received){ this->ft_readings.fx = msg->wrench.force.x; this->ft_readings.fy = msg->wrench.force.y; this->ft_readings.fz = msg->wrench.force.z; this->ft_readings.mx = msg->wrench.torque.x; this->ft_readings.my = msg->wrench.torque.y; this->ft_readings.mz = msg->wrench.torque.z; this->ft_received = 1; }else{ this->ft_readings.fx = (this->ft_readings.fx + msg->wrench.force.x) / 2.0; this->ft_readings.fy = (this->ft_readings.fy + msg->wrench.force.y) / 2.0; this->ft_readings.fz = (this->ft_readings.fz + msg->wrench.force.z) / 2.0; this->ft_readings.mx = (this->ft_readings.mx + msg->wrench.torque.x) / 2.0; this->ft_readings.my = (this->ft_readings.my + msg->wrench.torque.y) / 2.0; this->ft_readings.mz = (this->ft_readings.mz + msg->wrench.torque.z) / 2.0; } if((this->stud_press + this->ft_readings.fz) < 0.0){ fprintf(stdout, "Contact controller mode changed to STOPPED\n"); unsubscribe_messages(); this->mode = CONTACT_MODE_STOPPED; this->timer.stop(); stop_arm(); }else{ this->factor = fabs(this->ft_readings.fz / this->stud_press); if(this->factor > 1.0){ fprintf(stdout, "Contact controller mode changed to STOPPED\n"); unsubscribe_messages(); this->mode = CONTACT_MODE_STOPPED; this->timer.stop(); stop_arm(); } } break; } }
30.173611
110
0.687227
[ "vector" ]
b1361534962c703060d66b2b826cd3911d6fc833
24,808
cpp
C++
rviz_default_plugins/src/rviz_default_plugins/robot/robot_link.cpp
nbbrooks/rviz
e6a4c36a22cab690d97774d3afc8ffaae758e2d9
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/robot/robot_link.cpp
nbbrooks/rviz
e6a4c36a22cab690d97774d3afc8ffaae758e2d9
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/robot/robot_link.cpp
nbbrooks/rviz
e6a4c36a22cab690d97774d3afc8ffaae758e2d9
[ "BSD-3-Clause-Clear" ]
null
null
null
/* * Copyright (c) 2008, Willow Garage, Inc. * Copyright (c) 2018, Bosch Software Innovations GmbH. * 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 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. */ #include "rviz_default_plugins/robot/robot_link.hpp" #include <map> #include <memory> #include <string> #include <vector> #include <OgreEntity.h> #include <OgreMaterial.h> #include <OgreMaterialManager.h> #include <OgreRibbonTrail.h> #include <OgreSceneManager.h> #include <OgreSceneNode.h> #include <OgreSubEntity.h> #include <OgreTextureManager.h> #include <OgreSharedPtr.h> #include <OgreTechnique.h> #include <QFileInfo> // NOLINT cpplint cannot handle include order here #include "resource_retriever/retriever.h" #include "rviz_default_plugins/robot/robot_joint.hpp" #include "rviz_default_plugins/robot/robot.hpp" #include "rviz_rendering/material_manager.hpp" #include "rviz_rendering/mesh_loader.hpp" #include "rviz_rendering/objects/axes.hpp" #include "rviz_rendering/objects/object.hpp" #include "rviz_rendering/objects/shape.hpp" #include "rviz_common/display_context.hpp" #include "rviz_common/load_resource.hpp" #include "rviz_common/logging.hpp" #include "rviz_common/properties/bool_property.hpp" #include "rviz_common/properties/float_property.hpp" #include "rviz_common/properties/property.hpp" #include "rviz_common/properties/quaternion_property.hpp" #include "rviz_common/properties/vector_property.hpp" #include "rviz_common/interaction/selection_manager.hpp" #define RVIZ_RESOURCE_GROUP "rviz_rendering" using rviz_rendering::Axes; using rviz_rendering::Shape; namespace rviz_default_plugins { namespace robot { using rviz_common::properties::Property; using rviz_common::properties::FloatProperty; using rviz_common::properties::QuaternionProperty; using rviz_common::properties::VectorProperty; class RobotLinkSelectionHandler : public rviz_common::interaction::SelectionHandler { public: RobotLinkSelectionHandler(RobotLink * link, rviz_common::DisplayContext * context); ~RobotLinkSelectionHandler() override; void createProperties( const rviz_common::interaction::Picked & obj, Property * parent_property) override; void updateProperties() override; void preRenderPass(uint32_t pass) override; void postRenderPass(uint32_t pass) override; private: RobotLink * link_; rviz_common::properties::VectorProperty * position_property_; rviz_common::properties::QuaternionProperty * orientation_property_; template<typename T, typename ... Args> friend typename std::shared_ptr<T> rviz_common::interaction::createSelectionHandler( Args ... arguments); }; RobotLinkSelectionHandler::RobotLinkSelectionHandler( RobotLink * link, rviz_common::DisplayContext * context) : SelectionHandler(context), link_(link), position_property_(nullptr), orientation_property_(nullptr) {} RobotLinkSelectionHandler::~RobotLinkSelectionHandler() = default; void RobotLinkSelectionHandler::createProperties( const rviz_common::interaction::Picked & obj, rviz_common::properties::Property * parent_property) { (void) obj; Property * group = new Property("Link " + QString::fromStdString(link_->getName()), QVariant(), "", parent_property); properties_.push_back(group); position_property_ = new VectorProperty("Position", Ogre::Vector3::ZERO, "", group); position_property_->setReadOnly(true); orientation_property_ = new QuaternionProperty("Orientation", Ogre::Quaternion::IDENTITY, "", group); orientation_property_->setReadOnly(true); group->expand(); } void RobotLinkSelectionHandler::updateProperties() { position_property_->setVector(link_->getPosition()); orientation_property_->setQuaternion(link_->getOrientation()); } void RobotLinkSelectionHandler::preRenderPass(uint32_t pass) { (void) pass; if (!link_->is_selectable_) { if (link_->visual_node_) { link_->visual_node_->setVisible(false); } if (link_->collision_node_) { link_->collision_node_->setVisible(false); } if (link_->trail_) { link_->trail_->setVisible(false); } if (link_->axes_) { link_->axes_->getSceneNode()->setVisible(false); } } } void RobotLinkSelectionHandler::postRenderPass(uint32_t pass) { (void) pass; if (!link_->is_selectable_) { link_->updateVisibility(); } } RobotLink::RobotLink( Robot * robot, const urdf::LinkConstSharedPtr & link, const std::string & parent_joint_name, bool visual, bool collision) : RobotElementBaseClass(robot, link->name), scene_manager_(robot->getDisplayContext()->getSceneManager()), context_(robot->getDisplayContext()), parent_joint_name_(parent_joint_name), visual_node_(nullptr), collision_node_(nullptr), trail_(nullptr), material_alpha_(1.0), robot_alpha_(1.0), only_render_depth_(false), is_selectable_(true), using_color_(false) { setProperties(link); visual_node_ = robot_->getVisualNode()->createChildSceneNode(); collision_node_ = robot_->getCollisionNode()->createChildSceneNode(); // create material for coloring links static int count = 1; std::string color_material_name = "robot link color material " + std::to_string(count++); color_material_ = rviz_rendering::MaterialManager::createMaterialWithLighting(color_material_name); // create the ogre objects to display if (visual) { createVisual(link); } if (collision) { createCollision(link); } if (collision || visual) { createSelection(); } createDescription(link); if (!hasGeometry()) { robot_element_property_->setIcon(rviz_common::loadPixmap( "package://rviz_default_plugins/icons/classes/RobotLinkNoGeom.png")); alpha_property_->hide(); robot_element_property_->setValue(QVariant()); } } void RobotLink::setProperties(const urdf::LinkConstSharedPtr & link) { robot_element_property_ = new Property( link->name.c_str(), true, "", nullptr, SLOT(updateVisibility()), this); robot_element_property_->setIcon(rviz_common::loadPixmap( "package://rviz_default_plugins/icons/classes/RobotLink.png")); details_ = new Property("Details", QVariant(), "", nullptr); alpha_property_ = new FloatProperty("Alpha", 1, "Amount of transparency to apply to this link.", robot_element_property_, SLOT(updateAlpha()), this); trail_property_ = new Property("Show Trail", false, "Enable/disable a 2 meter \"ribbon\" which follows this link.", robot_element_property_, SLOT(updateTrail()), this); axes_property_ = new Property("Show Axes", false, "Enable/disable showing the axes of this link.", robot_element_property_, SLOT(updateAxes()), this); position_property_ = new VectorProperty("Position", Ogre::Vector3::ZERO, "Position of this link, in the current Fixed Frame. (Not editable)", robot_element_property_); position_property_->setReadOnly(true); orientation_property_ = new QuaternionProperty("Orientation", Ogre::Quaternion::IDENTITY, "Orientation of this link, in the current Fixed Frame. (Not editable)", robot_element_property_); orientation_property_->setReadOnly(true); robot_element_property_->collapse(); } void RobotLink::createDescription(const urdf::LinkConstSharedPtr & link) { std::stringstream desc; if (parent_joint_name_.empty()) { desc << "Root Link <b>" << name_ << "</b>"; } else { desc << "Link <b>" << name_ << "</b>"; desc << " with parent joint <b>" << parent_joint_name_ << "</b>"; } if (link->child_joints.empty()) { desc << " has no children."; } else { desc << " has " << link->child_joints.size(); if (link->child_joints.size() > 1) { desc << " child joints: "; } else { desc << " child joint: "; } auto child_it = link->child_joints.begin(); auto child_end = link->child_joints.end(); for (; child_it != child_end; ++child_it) { urdf::Joint * child_joint = child_it->get(); if (child_joint && !child_joint->name.empty()) { child_joint_names_.push_back(child_joint->name); desc << "<b>" << child_joint->name << "</b>" << ((child_it + 1 == child_end) ? "." : ", "); } } } if (hasGeometry()) { desc << " Check/uncheck to show/hide this link in the display."; if (visual_meshes_.empty()) { desc << " This link has collision geometry but no visible geometry."; } else if (collision_meshes_.empty()) { desc << " This link has visible geometry but no collision geometry."; } } else { desc << " This link has NO geometry."; } robot_element_property_->setDescription(desc.str().c_str()); } RobotLink::~RobotLink() { for (auto & visual_mesh : visual_meshes_) { scene_manager_->destroyEntity(visual_mesh); } for (auto & collision_mesh : collision_meshes_) { scene_manager_->destroyEntity(collision_mesh); } scene_manager_->destroySceneNode(visual_node_); scene_manager_->destroySceneNode(collision_node_); if (trail_) { scene_manager_->destroyRibbonTrail(trail_); } delete details_; delete robot_element_property_; } void RobotLink::setRobotAlpha(float a) { robot_alpha_ = a; updateAlpha(); } void RobotLink::setTransforms( const Ogre::Vector3 & visual_position, const Ogre::Quaternion & visual_orientation, const Ogre::Vector3 & collision_position, const Ogre::Quaternion & collision_orientation) { if (visual_node_) { visual_node_->setPosition(visual_position); visual_node_->setOrientation(visual_orientation); } if (collision_node_) { collision_node_->setPosition(collision_position); collision_node_->setOrientation(collision_orientation); } position_property_->setVector(visual_position); orientation_property_->setQuaternion(visual_orientation); if (axes_) { axes_->setPosition(visual_position); axes_->setOrientation(visual_orientation); } } void RobotLink::setToErrorMaterial() { for (auto & visual_mesh : visual_meshes_) { visual_mesh->setMaterialName("BaseWhiteNoLighting"); } for (auto & collision_mesh : collision_meshes_) { collision_mesh->setMaterialName("BaseWhiteNoLighting"); } } void RobotLink::setToNormalMaterial() { if (using_color_) { for (auto & visual_mesh : visual_meshes_) { visual_mesh->setMaterial(color_material_); } for (auto & collision_mesh : collision_meshes_) { collision_mesh->setMaterial(color_material_); } } else { for (const auto & material_entry : materials_) { material_entry.first->setMaterial(material_entry.second); } } } void RobotLink::setColor(float red, float green, float blue) { Ogre::ColourValue color = color_material_->getTechnique(0)->getPass(0)->getDiffuse(); color.r = red; color.g = green; color.b = blue; color_material_->getTechnique(0)->setAmbient(0.5f * color); color_material_->getTechnique(0)->setDiffuse(color); using_color_ = true; setToNormalMaterial(); } void RobotLink::unsetColor() { using_color_ = false; setToNormalMaterial(); } bool RobotLink::setSelectable(bool selectable) { bool old = is_selectable_; is_selectable_ = selectable; return old; } bool RobotLink::getSelectable() { return is_selectable_; } bool RobotLink::hasGeometry() const { return visual_meshes_.size() + collision_meshes_.size() > 0; } void RobotLink::setOnlyRenderDepth(bool onlyRenderDepth) { setRenderQueueGroup(onlyRenderDepth ? Ogre::RENDER_QUEUE_BACKGROUND : Ogre::RENDER_QUEUE_MAIN); only_render_depth_ = onlyRenderDepth; updateAlpha(); } void RobotLink::updateVisibility() { bool enabled = getEnabled(); robot_->calculateJointCheckboxes(); if (visual_node_) { visual_node_->setVisible(enabled && robot_->isVisible() && robot_->isVisualVisible()); } if (collision_node_) { collision_node_->setVisible(enabled && robot_->isVisible() && robot_->isCollisionVisible()); } if (trail_) { trail_->setVisible(enabled && robot_->isVisible()); } if (axes_) { axes_->getSceneNode()->setVisible(enabled && robot_->isVisible()); } } void RobotLink::updateAlpha() { float link_alpha = alpha_property_->getFloat(); for (const auto & material_entry : materials_) { const Ogre::MaterialPtr & material = material_entry.second; if (only_render_depth_) { material->setColourWriteEnabled(false); material->setDepthWriteEnabled(true); } else { Ogre::ColourValue color = material->getTechnique(0)->getPass(0)->getDiffuse(); color.a = robot_alpha_ * material_alpha_ * link_alpha; material->setDiffuse(color); rviz_rendering::MaterialManager::enableAlphaBlending(material, color.a); } } Ogre::ColourValue color = color_material_->getTechnique(0)->getPass(0)->getDiffuse(); color.a = robot_alpha_ * link_alpha; color_material_->setDiffuse(color); rviz_rendering::MaterialManager::enableAlphaBlending(color_material_, color.a); } void RobotLink::updateTrail() { if (trail_property_->getValue().toBool()) { if (!trail_) { if (visual_node_) { static int count = 0; std::string link_name = "Trail for link " + name_ + std::to_string(count++); trail_ = scene_manager_->createRibbonTrail(link_name); trail_->setMaxChainElements(100); trail_->setInitialWidth(0, 0.01f); trail_->setInitialColour(0, 0.0f, 0.5f, 0.5f); trail_->addNode(visual_node_); trail_->setTrailLength(2.0f); trail_->setVisible(getEnabled()); robot_->getOtherNode()->attachObject(trail_); } else { RVIZ_COMMON_LOG_ERROR_STREAM( "No visual node for link '" << name_ << "', cannot create a trail"); } } } else { if (trail_) { scene_manager_->destroyRibbonTrail(trail_); trail_ = nullptr; } } } void RobotLink::setRenderQueueGroup(Ogre::uint8 group) { for (auto child_node : visual_node_->getChildren()) { auto child = dynamic_cast<Ogre::SceneNode *>(child_node); if (child) { auto attached_objects = child->getAttachedObjects(); for (const auto & object : attached_objects) { object->setRenderQueueGroup(group); } } } } bool RobotLink::getEnabled() const { if (!hasGeometry()) { return true; } return robot_element_property_->getValue().toBool(); } Ogre::Entity * RobotLink::createEntityForGeometryElement( const urdf::LinkConstSharedPtr & link, const urdf::Geometry & geom, const urdf::Pose & origin, const std::string material_name, Ogre::SceneNode * scene_node) { Ogre::Entity * entity = nullptr; // default in case nothing works. Ogre::SceneNode * offset_node = scene_node->createChildSceneNode(); static int count = 0; std::string entity_name = "Robot Link" + std::to_string(count++); Ogre::Vector3 scale(Ogre::Vector3::UNIT_SCALE); Ogre::Vector3 offset_position( static_cast<float>(origin.position.x), static_cast<float>(origin.position.y), static_cast<float>(origin.position.z)); Ogre::Quaternion offset_orientation = Ogre::Quaternion( static_cast<float>(origin.rotation.w), static_cast<float>(origin.rotation.x), static_cast<float>(origin.rotation.y), static_cast<float>(origin.rotation.z)); switch (geom.type) { case urdf::Geometry::SPHERE: { auto sphere = dynamic_cast<const urdf::Sphere &>(geom); entity = Shape::createEntity(entity_name, Shape::Sphere, scene_manager_); scale = Ogre::Vector3( static_cast<float>(sphere.radius * 2), static_cast<float>(sphere.radius * 2), static_cast<float>(sphere.radius * 2)); break; } case urdf::Geometry::BOX: { auto box = dynamic_cast<const urdf::Box &>(geom); entity = Shape::createEntity(entity_name, Shape::Cube, scene_manager_); scale = Ogre::Vector3( static_cast<float>(box.dim.x), static_cast<float>(box.dim.y), static_cast<float>(box.dim.z)); break; } case urdf::Geometry::CYLINDER: { auto cylinder = dynamic_cast<const urdf::Cylinder &>(geom); Ogre::Quaternion rotX; rotX.FromAngleAxis(Ogre::Degree(90), Ogre::Vector3::UNIT_X); offset_orientation = offset_orientation * rotX; entity = Shape::createEntity(entity_name, Shape::Cylinder, scene_manager_); scale = Ogre::Vector3( static_cast<float>(cylinder.radius * 2), static_cast<float>(cylinder.length), static_cast<float>(cylinder.radius * 2)); break; } case urdf::Geometry::MESH: { auto mesh = dynamic_cast<const urdf::Mesh &>(geom); if (mesh.filename.empty()) { return nullptr; } scale = Ogre::Vector3( static_cast<float>(mesh.scale.x), static_cast<float>(mesh.scale.y), static_cast<float>(mesh.scale.z)); std::string model_name = mesh.filename; try { rviz_rendering::loadMeshFromResource(model_name); entity = scene_manager_->createEntity(entity_name, model_name); } catch (Ogre::InvalidParametersException & e) { RVIZ_COMMON_LOG_ERROR_STREAM( "Could not convert mesh resource '" << model_name << "' for link '" << link->name << "'. It may be an empty mesh: " << e.what()); } catch (Ogre::Exception & e) { RVIZ_COMMON_LOG_ERROR_STREAM( "could not load model '" << model_name << "' for link '" << link->name + "': " << e.what()); } break; } default: RVIZ_COMMON_LOG_ERROR_STREAM("Unsupported geometry type for element: " << geom.type); break; } if (entity) { offset_node->attachObject(entity); offset_node->setScale(scale); offset_node->setPosition(offset_position); offset_node->setOrientation(offset_orientation); assignMaterialsToEntities(link, material_name, entity); } return entity; } void RobotLink::assignMaterialsToEntities( const urdf::LinkConstSharedPtr & link, const std::string & material_name, const Ogre::Entity * entity) { static int material_count = 0; if (default_material_name_.empty()) { default_material_ = getMaterialForLink(link); std::string cloned_name = default_material_->getName() + std::to_string(material_count++) + "Robot"; default_material_ = default_material_->clone(cloned_name); default_material_name_ = default_material_->getName(); } for (uint32_t i = 0; i < entity->getNumSubEntities(); ++i) { default_material_ = getMaterialForLink(link, material_name); std::string cloned_name = default_material_->getName() + std::to_string(material_count++) + "Robot"; default_material_ = default_material_->clone(cloned_name); default_material_name_ = default_material_->getName(); // Assign materials only if the submesh does not have one already Ogre::SubEntity * sub = entity->getSubEntity(i); const std::string & sub_material_name = sub->getMaterialName(); if (sub_material_name == "BaseWhite" || sub_material_name == "BaseWhiteNoLighting") { sub->setMaterialName(default_material_name_); } else { // Need to clone here due to how selection works. // Once selection id is done per object and not per material, // this can go away std::string sub_cloned_name = sub_material_name + std::to_string(material_count++) + "Robot"; sub->getMaterial()->clone(sub_cloned_name); sub->setMaterialName(sub_cloned_name); } materials_[sub] = sub->getMaterial(); } } Ogre::MaterialPtr RobotLink::getMaterialForLink( const urdf::LinkConstSharedPtr & link, const std::string material_name) { if (!link->visual || !link->visual->material) { return Ogre::MaterialManager::getSingleton().getByName("RVIZ/ShadedRed"); } static int count = 0; std::string link_material_name = "Robot Link Material" + std::to_string(count++); auto material_for_link = rviz_rendering::MaterialManager::createMaterialWithShadowsAndLighting(link_material_name); urdf::VisualSharedPtr visual = getVisualWithMaterial(link, material_name); if (visual->material->texture_filename.empty()) { const urdf::Color & color = visual->material->color; material_for_link->getTechnique(0)->setAmbient(color.r * 0.5f, color.g * 0.5f, color.b * 0.5f); material_for_link->getTechnique(0)->setDiffuse(color.r, color.g, color.b, color.a); material_alpha_ = color.a; } else { loadMaterialFromTexture(material_for_link, visual); } return material_for_link; } urdf::VisualSharedPtr RobotLink::getVisualWithMaterial( const urdf::LinkConstSharedPtr & link, const std::string & material_name) const { urdf::VisualSharedPtr visual = link->visual; for (const auto & visual_array_element : link->visual_array) { if (visual_array_element && !material_name.empty() && visual_array_element->material_name == material_name) { visual = visual_array_element; break; } } return visual; } void RobotLink::loadMaterialFromTexture( Ogre::MaterialPtr & material_for_link, const urdf::VisualSharedPtr & visual) const { std::string filename = visual->material->texture_filename; if (!Ogre::TextureManager::getSingleton().resourceExists(filename, RVIZ_RESOURCE_GROUP)) { resource_retriever::Retriever retriever; resource_retriever::MemoryResource res; try { res = retriever.get(filename); } catch (resource_retriever::Exception & e) { RVIZ_COMMON_LOG_ERROR(e.what()); } if (res.size != 0) { Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream(res.data.get(), res.size)); Ogre::Image image; std::string extension = QFileInfo(QString::fromStdString(filename)).completeSuffix().toStdString(); if (extension[0] == '.') { extension = extension.substr(1, extension.size() - 1); } try { image.load(stream, extension); Ogre::TextureManager::getSingleton().loadImage(filename, RVIZ_RESOURCE_GROUP, image); } catch (Ogre::Exception & e) { RVIZ_COMMON_LOG_ERROR_STREAM("Could not load texture [" << filename << "]: " << e.what()); } } } Ogre::Pass * pass = material_for_link->getTechnique(0)->getPass(0); Ogre::TextureUnitState * tex_unit = pass->createTextureUnitState(); tex_unit->setTextureName(filename); } void RobotLink::createCollision(const urdf::LinkConstSharedPtr & link) { createVisualizable<urdf::CollisionSharedPtr>( link, collision_meshes_, link->collision_array, link->collision, collision_node_); collision_node_->setVisible(getEnabled()); } void RobotLink::createVisual(const urdf::LinkConstSharedPtr & link) { createVisualizable<urdf::VisualSharedPtr>( link, visual_meshes_, link->visual_array, link->visual, visual_node_); visual_node_->setVisible(getEnabled()); } void RobotLink::createSelection() { selection_handler_ = rviz_common::interaction::createSelectionHandler<RobotLinkSelectionHandler>( this, context_); for (auto & visual_mesh : visual_meshes_) { selection_handler_->addTrackedObject(visual_mesh); } for (auto & collision_mesh : collision_meshes_) { selection_handler_->addTrackedObject(collision_mesh); } } } // namespace robot } // namespace rviz_default_plugins
31.522236
99
0.702233
[ "mesh", "geometry", "object", "shape", "vector", "model" ]
b139caa5d2a0e16f49ef0d2e0084c9bbced67226
885
hpp
C++
lab/mpllibs/metaparse/v1/util/digit_to_int.hpp
sabel83/metaparse_tutorial
819fddf6bf06736861adbeabeb30967f56b7e8d0
[ "BSL-1.0" ]
24
2015-07-14T01:56:03.000Z
2021-09-16T07:48:46.000Z
lab/mpllibs/metaparse/v1/util/digit_to_int.hpp
sabel83/metaparse_tutorial
819fddf6bf06736861adbeabeb30967f56b7e8d0
[ "BSL-1.0" ]
1
2017-10-01T12:31:25.000Z
2017-10-04T12:16:47.000Z
lab/mpllibs/metaparse/v1/util/digit_to_int.hpp
sabel83/metaparse_tutorial
819fddf6bf06736861adbeabeb30967f56b7e8d0
[ "BSL-1.0" ]
2
2017-08-22T20:31:11.000Z
2019-02-23T07:32:29.000Z
#ifndef MPLLIBS_METAPARSE_V1_UTIL_DIGIT_TO_INT_HPP #define MPLLIBS_METAPARSE_V1_UTIL_DIGIT_TO_INT_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2009 - 2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <mpllibs/metaparse/v1/util/digit_to_int_c.hpp> #include <boost/mpl/vector.hpp> namespace mpllibs { namespace metaparse { namespace v1 { namespace util { template <class D = boost::mpl::na> struct digit_to_int : digit_to_int_c<D::type::value> {}; template <> struct digit_to_int<boost::mpl::na> { typedef digit_to_int type; template <class D = boost::mpl::na> struct apply : digit_to_int<D> {}; }; } } } } #endif
22.692308
64
0.638418
[ "vector" ]
b13ae28242a842340e2917832b885cd31d212a59
1,598
cpp
C++
LeetCode/07/LeetCode728-SelfDividingNumbers.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
LeetCode/07/LeetCode728-SelfDividingNumbers.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
LeetCode/07/LeetCode728-SelfDividingNumbers.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
// LeetCode728-selfDividingNumbers.cpp // Ad147 // Init: 19Jan02 /* ----------------------------------------------------------------------------- A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. Example 1: ``` Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] ``` Note: - The boundaries of each input argument are 1 <= left <= right <= 10000. ----------------------------------------------------------------------------- */ #include <vector> // solution -------------------------------------------------------------------- // Runtime: 4 ms, faster than 65.11% of C++ online submissions for Self Dividing Numbers. // `final`: Many 0 ms submissions have similar code with this. class Solution { public: std::vector<int> selfDividingNumbers(int left, int right) { std::vector<int> ret; for (int i = left; i <= right; ++i) { bool flag = true; for (int temp = i, d = temp % 10; temp != 0; temp /= 10, d = temp % 10) { if (d == 0 || i % d) { flag = false; break; } } if (flag) ret.push_back(i); } return ret; } };
26.633333
125
0.475594
[ "vector" ]
b13b1dd103609fd8aec78b8c049c4817bdeec96f
1,236
cpp
C++
aws-cpp-sdk-identitystore/source/model/Group.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-identitystore/source/model/Group.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-identitystore/source/model/Group.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/identitystore/model/Group.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace IdentityStore { namespace Model { Group::Group() : m_groupIdHasBeenSet(false), m_displayNameHasBeenSet(false) { } Group::Group(JsonView jsonValue) : m_groupIdHasBeenSet(false), m_displayNameHasBeenSet(false) { *this = jsonValue; } Group& Group::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("GroupId")) { m_groupId = jsonValue.GetString("GroupId"); m_groupIdHasBeenSet = true; } if(jsonValue.ValueExists("DisplayName")) { m_displayName = jsonValue.GetString("DisplayName"); m_displayNameHasBeenSet = true; } return *this; } JsonValue Group::Jsonize() const { JsonValue payload; if(m_groupIdHasBeenSet) { payload.WithString("GroupId", m_groupId); } if(m_displayNameHasBeenSet) { payload.WithString("DisplayName", m_displayName); } return payload; } } // namespace Model } // namespace IdentityStore } // namespace Aws
16.48
69
0.70712
[ "model" ]
b13b8b8f0e7a130defe4a6e362e3ad9af92585a6
6,510
cpp
C++
src/Samples/src/samples/materials/shadermaterial/shader_material_skybox_clouds_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/Samples/src/samples/materials/shadermaterial/shader_material_skybox_clouds_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/Samples/src/samples/materials/shadermaterial/shader_material_skybox_clouds_scene.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/cameras/free_camera.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/lights/hemispheric_light.h> #include <babylon/materials/effect.h> #include <babylon/materials/effect_shaders_store.h> #include <babylon/materials/shader_material.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/mesh_builder.h> #include <babylon/samples/babylon_register_sample.h> namespace BABYLON { namespace Samples { class ShaderMaterialSkyboxCloudsScene : public IRenderableScene { public: /** Vertex Shader **/ static constexpr const char* customVertexShader = R"ShaderCode( #ifdef GL_ES precision highp float; #endif // Attributes attribute vec3 position; attribute vec2 uv; // Uniforms uniform mat4 worldViewProjection; // Varying varying vec2 vUV; void main(void) { gl_Position = worldViewProjection * vec4(position, 1.0); vUV = uv; } )ShaderCode"; /** Pixel (Fragment) Shader **/ // 2D Clouds ( https://www.shadertoy.com/view/4tdSWr ) static constexpr const char* customFragmentShader = R"ShaderCode( #ifdef GL_ES precision highp float; #endif // Varying varying vec3 vPosition; varying vec3 vNormal; varying vec2 vUV; // Uniforms uniform mat4 worldViewProjection; uniform float time; const float cloudscale = 1.1; const float speed = 0.03; const float clouddark = 0.5; const float cloudlight = 0.3; const float cloudcover = 0.2; const float cloudalpha = 8.0; const float skytint = 0.5; const vec3 skycolour1 = vec3(0.2, 0.4, 0.6); const vec3 skycolour2 = vec3(0.4, 0.7, 1.0); const mat2 m = mat2(1.6, 1.2, -1.2, 1.6); vec2 hash(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return -1.0 + 2.0 * fract(sin(p) * 43758.5453123); } float noise(in vec2 p) { const float K1 = 0.366025404; // (sqrt(3)-1)/2; const float K2 = 0.211324865; // (3-sqrt(3))/6; vec2 i = floor(p + (p.x + p.y) * K1); vec2 a = p - i + (i.x + i.y) * K2; vec2 o = (a.x > a.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); vec2 b = a - o + K2; vec2 c = a - 1.0 + 2.0 * K2; vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0); vec3 n = h * h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0))); return dot(n, vec3(70.0)); } float fbm(vec2 n) { float total = 0.0, amplitude = 0.1; for (int i = 0; i < 7; i++) { total += noise(n) * amplitude; n = m * n; amplitude *= 0.4; } return total; } // ------------------------------------------------------------------- void main(void) { vec2 p = -1.0 + 2.0 * vUV.xy; vec2 uv = vUV.xy; float iTime = time * speed; float q = fbm(uv * cloudscale * 0.5); // ridged noise shape float r = 0.0; uv *= cloudscale; uv -= q - iTime; float weight = 0.8; for (int i = 0; i < 8; i++) { r += abs(weight * noise(uv)); uv = m * uv + iTime; weight *= 0.7; } // noise shape float f = 0.0; uv = vUV.xy; uv *= cloudscale; uv -= q - iTime; weight = 0.7; for (int i = 0; i < 8; i++) { f += weight * noise(uv); uv = m * uv + iTime; weight *= 0.6; } f *= r + f; // noise colour float c = 0.0; iTime = time * speed * 2.0; uv = vUV.xy; uv *= cloudscale * 2.0; uv -= q - iTime; weight = 0.4; for (int i = 0; i < 7; i++) { c += weight * noise(uv); uv = m * uv + iTime; weight *= 0.6; } // noise ridge colour float c1 = 0.0; iTime = time * speed * 3.0; uv = vUV.xy; uv *= cloudscale * 3.0; uv -= q - iTime; weight = 0.4; for (int i = 0; i < 7; i++) { c1 += abs(weight * noise(uv)); uv = m * uv + iTime; weight *= 0.6; } c += c1; vec3 skycolour = mix(skycolour2, skycolour1, p.y); vec3 cloudcolour = vec3(1.1, 1.1, 0.9) * clamp((clouddark + cloudlight * c), 0.0, 1.0); f = cloudcover + cloudalpha * f * r; vec3 result = mix(skycolour, clamp(skytint * skycolour + cloudcolour, 0.0, 1.0), clamp(f + c, 0.0, 1.0)); gl_FragColor = vec4(result, 1.0); } )ShaderCode"; public: ShaderMaterialSkyboxCloudsScene(ICanvas* iCanvas) : IRenderableScene(iCanvas), _time{0.f}, _shaderMaterial{nullptr} { // Vertex shader Effect::ShadersStore()["customVertexShader"] = customVertexShader; // Fragment shader Effect::ShadersStore()["customFragmentShader"] = customFragmentShader; } ~ShaderMaterialSkyboxCloudsScene() override = default; const char* getName() override { return "Shader Material Skybox Clouds Scene"; } void initializeScene(ICanvas* canvas, Scene* scene) override { // Create a FreeCamera, and set its position to (x:0, y:0, z:-8) auto camera = FreeCamera::New("camera1", Vector3(0.f, 0.f, -8.f), scene); // Target the camera to scene origin camera->setTarget(Vector3::Zero()); // Attach the camera to the canvas camera->attachControl(canvas, true); // Create a basic light, aiming 0,1,0 - meaning, to the sky HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene); // Create a built-in "box" shape const float ratio = static_cast<float>(getEngine()->getRenderWidth()) / static_cast<float>(getEngine()->getRenderHeight()); BoxOptions options; options.size = 5.f; options.sideOrientation = Mesh::DEFAULTSIDE; options.updatable = false; options.width = *options.size * ratio; auto skybox = MeshBuilder::CreateBox("skybox", options, scene); // Create shader material IShaderMaterialOptions shaderMaterialOptions; shaderMaterialOptions.attributes = {"position", "uv"}; shaderMaterialOptions.uniforms = {"worldViewProjection", "time"}; _shaderMaterial = ShaderMaterial::New("boxShader", scene, "custom", shaderMaterialOptions); // box + sky = skybox ! skybox->material = _shaderMaterial; // Animation scene->onAfterCameraRenderObservable.add([this](Camera*, EventState&) { _shaderMaterial->setFloat("time", _time); _time += 0.01f * getScene()->getAnimationRatio(); }); } private: float _time; ShaderMaterialPtr _shaderMaterial; }; // end of class ShaderMaterialSkyboxCloudsScene BABYLON_REGISTER_SAMPLE("Shader Material", ShaderMaterialSkyboxCloudsScene) } // end of namespace Samples } // end of namespace BABYLON
26.356275
95
0.616129
[ "mesh", "shape" ]
b13c9753aa94f709e7b5eda98cb48cedefecaf2a
15,498
cpp
C++
android/jni/SearchResultPoi/View/SearchResultPoiView.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
69
2017-06-07T10:47:03.000Z
2022-03-24T08:33:33.000Z
android/jni/SearchResultPoi/View/SearchResultPoiView.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
23
2017-06-07T10:47:00.000Z
2020-07-09T10:31:17.000Z
android/jni/SearchResultPoi/View/SearchResultPoiView.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
31
2017-08-12T13:19:32.000Z
2022-01-04T20:33:40.000Z
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchResultPoiView.h" #include "AndroidAppThreadAssertionMacros.h" #include "SearchVendorNames.h" #include "YelpSearchResultModel.h" #include "YelpParsingHelpers.h" #include "EegeoJsonParser.h" #include "EegeoSearchResultModel.h" namespace ExampleApp { namespace SearchResultPoi { namespace View { SearchResultPoiView::SearchResultPoiView(AndroidNativeState& nativeState, bool showDirectionsButton,std::string javascriptWhitlistURL) : m_nativeState(nativeState) , m_uiViewClass(NULL) , m_uiView(NULL) , m_showDirectionsButton(showDirectionsButton) , m_javascriptWhitelistHelper(javascriptWhitlistURL) { ASSERT_UI_THREAD } SearchResultPoiView::~SearchResultPoiView() { ASSERT_UI_THREAD } void SearchResultPoiView::Show(const Search::SdkModel::SearchResultModel& model, bool isPinned) { ASSERT_UI_THREAD m_model = model; const std::string& vendor = m_model.GetVendor(); if(vendor == Search::YelpVendorName) { CreateAndShowYelpPoiView(model, isPinned); } else if(vendor == Search::GeoNamesVendorName) { CreateAndShowGeoNamesPoiView(model, isPinned); } else if (vendor == Search::EegeoVendorName) { CreateAndShowEegeoPoiView(model, isPinned); } else { Eegeo_ASSERT(false, "Unknown POI vendor %s, cannot create view instance.\n", vendor.c_str()); } } void SearchResultPoiView::Hide() { ASSERT_UI_THREAD AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jmethodID dismissPoiInfo = env->GetMethodID(m_uiViewClass, "dismissPoiInfo", "()V"); env->CallVoidMethod(m_uiView, dismissPoiInfo); jmethodID removeHudMethod = env->GetMethodID(m_uiViewClass, "destroy", "()V"); env->CallVoidMethod(m_uiView, removeHudMethod); env->DeleteGlobalRef(m_uiView); env->DeleteGlobalRef(m_uiViewClass); m_uiViewClass = NULL; m_uiView = NULL; } void SearchResultPoiView::UpdateImage(const std::string& url, bool hasImage, const std::vector<Byte>* pImageBytes) { ASSERT_UI_THREAD AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; unsigned int imgSize = hasImage ? pImageBytes->size() : 0; jbyteArray imgArr = env->NewByteArray(imgSize); if(imgSize) { env->SetByteArrayRegion(imgArr,0,imgSize, (jbyte*)(&(pImageBytes->at(0)))); } jstring urlStr = env->NewStringUTF(url.c_str()); jmethodID updateImageData = env->GetMethodID(m_uiViewClass, "updateImageData", "(Ljava/lang/String;Z[B)V"); env->CallVoidMethod(m_uiView, updateImageData, urlStr, hasImage, imgArr); env->DeleteLocalRef(urlStr); env->DeleteLocalRef(imgArr); } void SearchResultPoiView::InsertAvailabilityChangedCallback(Eegeo::Helpers::ICallback2<const Search::SdkModel::SearchResultModel&, const std::string&>& callback) { // TJ: Stubbed for Droid implementation } void SearchResultPoiView::RemoveAvailabilityChangedCallback(Eegeo::Helpers::ICallback2<const Search::SdkModel::SearchResultModel&, const std::string&>& callback) { // TJ: Stubbed for Droid implementation } void SearchResultPoiView::InsertClosedCallback(Eegeo::Helpers::ICallback0& callback) { ASSERT_UI_THREAD m_closedCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveClosedCallback(Eegeo::Helpers::ICallback0& callback) { ASSERT_UI_THREAD m_closedCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandleCloseClicked() { ASSERT_UI_THREAD m_closedCallbacks.ExecuteCallbacks(); } void SearchResultPoiView::InsertTogglePinnedCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_togglePinClickedCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveTogglePinnedCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_togglePinClickedCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandlePinToggleClicked() { ASSERT_UI_THREAD m_togglePinClickedCallbacks.ExecuteCallbacks(m_model); } void SearchResultPoiView::InsertDirectionsCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_directionsCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveDirectionsCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_directionsCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandleDirectionsClicked() { ASSERT_UI_THREAD m_directionsCallbacks.ExecuteCallbacks(m_model); } bool SearchResultPoiView::IsJavascriptWhitelisted(std::string url){ ASSERT_UI_THREAD return m_javascriptWhitelistHelper.IsWhitelistedUrl(url); } void SearchResultPoiView::CreateAndShowYelpPoiView(const Search::SdkModel::SearchResultModel& model, bool isPinned) { const std::string viewClass = "com/eegeo/searchresultpoiview/YelpSearchResultPoiView"; m_uiViewClass = CreateJavaClass(viewClass); m_uiView = CreateJavaObject(m_uiViewClass); Search::Yelp::SdkModel::YelpSearchResultModel yelpModel; yelpModel = Search::Yelp::SdkModel::Helpers::TransformToYelpSearchResult(model); AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jobjectArray humanReadableTagsArray = CreateJavaArray(model.GetHumanReadableTags()); jobjectArray reviewsArray = CreateJavaArray(yelpModel.GetReviews()); jstring titleStr = env->NewStringUTF(model.GetTitle().c_str()); jstring addressStr = env->NewStringUTF(model.GetSubtitle().c_str()); jstring phoneStr = env->NewStringUTF(yelpModel.GetPhone().c_str()); jstring urlStr = env->NewStringUTF(yelpModel.GetWebUrl().c_str()); jstring iconKeyStr = env->NewStringUTF(model.GetIconKey().c_str()); jstring imageUrlStr = env->NewStringUTF(yelpModel.GetImageUrl().c_str()); jstring ratingImageUrlStr = env->NewStringUTF(yelpModel.GetRatingImageUrl().c_str()); jstring vendorStr = env->NewStringUTF(model.GetVendor().c_str()); jmethodID displayPoiInfoMethod = env->GetMethodID(m_uiViewClass, "displayPoiInfo", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;IZ)V"); env->CallVoidMethod( m_uiView, displayPoiInfoMethod, titleStr, addressStr, phoneStr, urlStr, iconKeyStr, humanReadableTagsArray, imageUrlStr, ratingImageUrlStr, vendorStr, reviewsArray, yelpModel.GetReviewCount(), isPinned ); env->DeleteLocalRef(vendorStr); env->DeleteLocalRef(ratingImageUrlStr); env->DeleteLocalRef(imageUrlStr); env->DeleteLocalRef(iconKeyStr); env->DeleteLocalRef(urlStr); env->DeleteLocalRef(phoneStr); env->DeleteLocalRef(addressStr); env->DeleteLocalRef(titleStr); env->DeleteLocalRef(reviewsArray); env->DeleteLocalRef(humanReadableTagsArray); } void SearchResultPoiView::CreateAndShowGeoNamesPoiView(const Search::SdkModel::SearchResultModel& model, bool isPinned) { const std::string viewClass = "com/eegeo/searchresultpoiview/GeoNamesSearchResultPoiView"; m_uiViewClass = CreateJavaClass(viewClass); m_uiView = CreateJavaObject(m_uiViewClass); AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jstring titleStr = env->NewStringUTF(model.GetTitle().c_str()); jstring addressStr = env->NewStringUTF(model.GetSubtitle().c_str()); jstring iconKeyStr = env->NewStringUTF(model.GetIconKey().c_str()); jmethodID displayPoiInfoMethod = env->GetMethodID(m_uiViewClass, "displayPoiInfo", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V"); env->CallVoidMethod( m_uiView, displayPoiInfoMethod, titleStr, addressStr, iconKeyStr, isPinned ); env->DeleteLocalRef(iconKeyStr); env->DeleteLocalRef(addressStr); env->DeleteLocalRef(titleStr); } void SearchResultPoiView::CreateAndShowEegeoPoiView(const Search::SdkModel::SearchResultModel& model, bool isPinned) { const std::string viewClass = "com/eegeo/searchresultpoiview/EegeoSearchResultPoiView"; m_uiViewClass = CreateJavaClass(viewClass); Eegeo_ASSERT(m_uiViewClass != NULL, "failed to create viewClass EegeoSearchResultPoiView"); m_uiView = CreateJavaObject(m_uiViewClass); Eegeo_ASSERT(m_uiView != NULL, "failed to create view EegeoSearchResultPoiView"); const Search::EegeoPois::SdkModel::EegeoSearchResultModel& eegeoSearchResultModel = Search::EegeoPois::SdkModel::TransformToEegeoSearchResult(model); AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jobjectArray humanReadableTagsArray = CreateJavaArray(model.GetHumanReadableTags()); jstring titleStr = env->NewStringUTF(model.GetTitle().c_str()); jstring subtitleStr = env->NewStringUTF(model.GetSubtitle().c_str()); jstring addressStr = env->NewStringUTF(eegeoSearchResultModel.GetAddress().c_str()); jstring descriptionStr = env->NewStringUTF(eegeoSearchResultModel.GetDescription().c_str()); jstring phoneStr = env->NewStringUTF(eegeoSearchResultModel.GetPhone().c_str()); jstring urlStr = env->NewStringUTF(eegeoSearchResultModel.GetWebUrl().c_str()); jstring iconKeyStr = env->NewStringUTF(model.GetIconKey().c_str()); jstring imageUrlStr = env->NewStringUTF(eegeoSearchResultModel.GetImageUrl().c_str()); jstring vendorStr = env->NewStringUTF(model.GetVendor().c_str()); jstring facebookStr = env->NewStringUTF(eegeoSearchResultModel.GetFacebookUrl().c_str()); jstring twitterStr = env->NewStringUTF(eegeoSearchResultModel.GetTwitterUrl().c_str()); jstring emailStr = env->NewStringUTF(eegeoSearchResultModel.GetEmail().c_str()); jstring customViewStr = env->NewStringUTF(eegeoSearchResultModel.GetCustomViewUrl().c_str()); int customViewHeight = eegeoSearchResultModel.GetCustomViewHeight(); jmethodID displayPoiInfoMethod = env->GetMethodID(m_uiViewClass, "displayPoiInfo", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)V"); env->CallVoidMethod( m_uiView, displayPoiInfoMethod, titleStr, subtitleStr, addressStr, descriptionStr, phoneStr, urlStr, iconKeyStr, humanReadableTagsArray, imageUrlStr, vendorStr, isPinned, facebookStr, twitterStr, emailStr, customViewStr, customViewHeight, m_showDirectionsButton ); env->DeleteLocalRef(vendorStr); env->DeleteLocalRef(imageUrlStr); env->DeleteLocalRef(iconKeyStr); env->DeleteLocalRef(urlStr); env->DeleteLocalRef(phoneStr); env->DeleteLocalRef(addressStr); env->DeleteLocalRef(descriptionStr); env->DeleteLocalRef(titleStr); env->DeleteLocalRef(subtitleStr); env->DeleteLocalRef(humanReadableTagsArray); env->DeleteLocalRef(facebookStr); env->DeleteLocalRef(twitterStr); env->DeleteLocalRef(emailStr); env->DeleteLocalRef(customViewStr); } jclass SearchResultPoiView::CreateJavaClass(const std::string& viewClass) { AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jstring strClassName = env->NewStringUTF(viewClass.c_str()); jclass uiClass = m_nativeState.LoadClass(env, strClassName); env->DeleteLocalRef(strClassName); return static_cast<jclass>(env->NewGlobalRef(uiClass)); } jobject SearchResultPoiView::CreateJavaObject(jclass uiViewClass) { AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jmethodID uiViewCtor = env->GetMethodID(uiViewClass, "<init>", "(Lcom/eegeo/entrypointinfrastructure/MainActivity;J)V"); jobject instance = env->NewObject( uiViewClass, uiViewCtor, m_nativeState.activity, (jlong)(this) ); return env->NewGlobalRef(instance); } jobjectArray SearchResultPoiView::CreateJavaArray(const std::vector<std::string>& stringVector) { AndroidSafeNativeThreadAttachment attached(m_nativeState); JNIEnv* env = attached.envForThread; jobjectArray jniStringArray = env->NewObjectArray( stringVector.size(), env->FindClass("java/lang/String"), 0 ); for(size_t i = 0; i < stringVector.size(); ++ i) { jstring jniString = env->NewStringUTF(stringVector[i].c_str()); env->SetObjectArrayElement(jniStringArray, i, jniString); env->DeleteLocalRef(jniString); } return jniStringArray; } } } }
40.464752
359
0.631178
[ "vector", "model" ]
b13ec7624e93599d121cb4fc23be22a927436749
2,513
cpp
C++
src/TBase.cpp
Lai0n/TXTMenu
271c8b26b9b54ac5219127e69b1d20f1e19ff2ec
[ "Apache-2.0" ]
null
null
null
src/TBase.cpp
Lai0n/TXTMenu
271c8b26b9b54ac5219127e69b1d20f1e19ff2ec
[ "Apache-2.0" ]
null
null
null
src/TBase.cpp
Lai0n/TXTMenu
271c8b26b9b54ac5219127e69b1d20f1e19ff2ec
[ "Apache-2.0" ]
null
null
null
/* * TBase.cpp * * Created: 11/22/2018 * Author: Peter Karaba */ #include "TBase.hpp" #include "../config.hpp" #include "redirect.hpp" #include <stdio.h> namespace TBase { static TBase::container* navDepthArr[MAXDEPTH]; static uint8_t currentContainerIndex=0; bool item::forward(){ return false; } container::container(){ } void container::render(uint8_t index, uint8_t* currentLanguage){ array[index]->render(currentLanguage); } bool container::forward(uint8_t& index){ return array[index]->forward(); } void container::callFunction(uint8_t& index){ array[index]->callFunction(); } void container::setSize(uint8_t newSize){ } uint8_t container::getSize(){ } void container::setArr(item** newPtr){ } menuCtrl::menuCtrl(arrCreator<item*>& __iarrc){ arrSize = __iarrc.getOC(); array = __iarrc.getArr(); navDepthArr[0] = this; // Set root container for navigation } void navForward(TBase::container* nextContainer){ if (currentContainerIndex < 255) navDepthArr[++currentContainerIndex] = nextContainer; } void navBackward(){ if (currentContainerIndex > 0) currentContainerIndex--; } TBase::container* getCurrentContainer(){ return navDepthArr[currentContainerIndex]; } char* varEdit(){ output_enterEditMode(); char key; // pressed key char* retValue = NULL; char* newValueStr = (char*)malloc(sizeof(char)); // Typed string newValueStr[0] = '\0'; uint8_t digitCount = 0; // Counter for typed digits while(1){ output_clear(); fprintf(ios, ":%s", newValueStr); key = input_getc(); if (!( (key >= 'a' && key <= 'z') || (key >= 'A' && key <= 'Z') || (key - 48 >= 0 && key - 48 <= 9) || key == '.' || key == Key_DEL || key == Key_OK || key == Key_UP || key == Key_DOWN || key == Key_LEFT || key == Key_RIGHT )) // if character is forbidden, then skip continue; switch(key){ case Key_LEFT: { free(newValueStr); goto escape; } case Key_DEL: //Delete one digit if (digitCount == 0) break; newValueStr[--digitCount] = '\0'; break; case Key_OK: // Exit & save retValue = newValueStr; goto escape; case Key_RIGHT: case Key_UP: case Key_DOWN: break; default: newValueStr = (char*)realloc(newValueStr,sizeof(char)*(digitCount+2)); newValueStr[digitCount] = key; //Copy key to string newValueStr[++digitCount] = '\0'; break; } delay_ms(NAVDELAY); } escape: output_exitEditMode(); return retValue; } }
21.117647
171
0.641862
[ "render" ]
b146e16022cef2ddd701c519f61b498b90e6cc72
6,145
hpp
C++
src/libraries/core/meshTools/edgeFaceCirculator/edgeFaceCirculator.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/meshTools/edgeFaceCirculator/edgeFaceCirculator.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/meshTools/edgeFaceCirculator/edgeFaceCirculator.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2017 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::edgeFaceCirculator Description Walks from starting face around edge. Implicit description of edge: - face - index in face. edge is always between f[index] and f[index+1] - direction (cell to walk into) -# Use in-place: \n \code edgeFaceCirculator circ(..); // Optionally rotate to beginning: circ.setCanonical(); // Walk do { Info<< "face:" << circ.face() << endl; ++circ; } while (circ != circ.end()); \endcode -# Use like STL iterator: \n \code edgeFaceCirculator circ(..); for ( edgeFaceCirculator iter = circ.begin(); iter != circ.end(); ++iter ) { Info<< "face:" << iter.face() << endl; } \endcode SourceFiles edgeFaceCirculator.cpp \*---------------------------------------------------------------------------*/ #ifndef edgeFaceCirculator_H #define edgeFaceCirculator_H #include "face.hpp" #include "ListOps.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of classes class primitiveMesh; /*---------------------------------------------------------------------------*\ Class edgeFaceCirculator Declaration \*---------------------------------------------------------------------------*/ class edgeFaceCirculator { // Static data members //- End iterator primitiveMesh nullptr static const primitiveMesh* const endConstIterMeshPtr; //- end iterator static const edgeFaceCirculator endConstIter; // Private data //- Mesh const primitiveMesh& mesh_; //- Current face label faceLabel_; //- Current side of face bool ownerSide_; //- Edge (between index and index+1 on faces[faceLabel_] label index_; //- Is boundary edge? bool isBoundaryEdge_; //- Starting face so we know when to stop. Used when circulating over // internal edges. label startFaceLabel_; // Private Member Functions //- Set to end() iterator inline void setEnd(); //- Check and set faceLabel_ and ownerSide_ inline void setFace(const label faceI, const label cellI); //- Set faceLabel_ to be the other face on the cell that uses the // edge. inline void otherFace(const label cellI); public: // Constructors //- Construct from components inline edgeFaceCirculator ( const primitiveMesh& mesh, const label faceLabel, const bool ownerSide, const label index, const bool isBoundaryEdge ); //- Construct as copy inline edgeFaceCirculator(const edgeFaceCirculator&); // Member Functions //- Helper: find index in face of edge or -1. Index is such that edge is // between f[index] and f[index+1] inline static label getMinIndex ( const face& f, const label v0, const label v1 ); inline label faceLabel() const; inline bool ownerSide() const; inline label index() const; //- Helper: get the neighbouring cell according to the ownerSide. // Returns -1 if on neighbourside of boundary face. inline label cellLabel() const; //- Helper: return true if normal of generated face points along // edge from v0 to v1. (v0 and v1 have to be on edge) inline bool sameOrder(const label v0, const label v1) const; //- Set edge to a unique state so different ones can be compared. // Internal edge: minimum face index. // Boundary edge: walk back until boundary face. inline void setCanonical(); // Member Operators inline void operator=(const edgeFaceCirculator& iter); inline bool operator==(const edgeFaceCirculator& iter) const; inline bool operator!=(const edgeFaceCirculator& iter) const; //- Step to next face. Uses no edge addressing! inline edgeFaceCirculator& operator++(); //- iterator set to the beginning face. For internal edges this is // the current face. For boundary edges this is the first boundary face // reached from walking back (i.e. in opposite direction to ++) inline edgeFaceCirculator begin() const; inline edgeFaceCirculator cbegin() const; //- iterator set to beyond the end of the walk. inline const edgeFaceCirculator& end() const; inline const edgeFaceCirculator& cend() const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "edgeFaceCirculatorI.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
28.714953
80
0.529862
[ "mesh" ]
b147cc9fbc0f26433de72667ce5e3e0c55164c05
1,334
cpp
C++
src/core/tests/visitors/op/shape_of.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/core/tests/visitors/op/shape_of.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/core/tests/visitors/op/shape_of.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "ngraph/op/util/attr_types.hpp" #include "ngraph/opsets/opset1.hpp" #include "ngraph/opsets/opset3.hpp" #include "ngraph/opsets/opset5.hpp" #include "util/visitor.hpp" using namespace std; using namespace ngraph; using ngraph::test::NodeBuilder; using ngraph::test::ValueMap; TEST(attributes, shapeof_op1) { NodeBuilder::get_ops().register_factory<op::v0::ShapeOf>(); auto data = make_shared<op::Parameter>(element::i32, Shape{2, 3, 4}); auto shapeof = make_shared<op::v0::ShapeOf>(data); NodeBuilder builder(shapeof); auto g_shapeof = ov::as_type_ptr<op::v0::ShapeOf>(builder.create()); const auto expected_attr_count = 0; EXPECT_EQ(builder.get_value_map_size(), expected_attr_count); } TEST(attributes, shapeof_op3) { NodeBuilder::get_ops().register_factory<op::v3::ShapeOf>(); auto data = make_shared<op::Parameter>(element::i32, Shape{2, 3, 4}); auto shapeof = make_shared<op::v3::ShapeOf>(data, element::Type_t::i64); NodeBuilder builder(shapeof); auto g_shapeof = ov::as_type_ptr<op::v3::ShapeOf>(builder.create()); const auto expected_attr_count = 1; EXPECT_EQ(builder.get_value_map_size(), expected_attr_count); }
34.205128
76
0.724138
[ "shape" ]
b14bae4c56f865796c2dee7a3a2cb8c6280c3385
2,285
cpp
C++
Pipes/pipePacket.cpp
wilseypa/lhf
d686862445eccd3c1bd1d681cff818bb41ed9241
[ "MIT" ]
3
2018-03-28T00:20:47.000Z
2022-01-19T03:00:20.000Z
Pipes/pipePacket.cpp
wilseypa/lhf
d686862445eccd3c1bd1d681cff818bb41ed9241
[ "MIT" ]
23
2020-02-12T18:28:40.000Z
2020-09-29T15:50:39.000Z
Pipes/pipePacket.cpp
wilseypa/lhf
d686862445eccd3c1bd1d681cff818bb41ed9241
[ "MIT" ]
7
2019-12-05T19:52:56.000Z
2021-03-15T07:57:35.000Z
#include <string> #include <vector> #include <typeinfo> #include <iostream> #include "pipePacket.hpp" // pipePacket constructor, currently no needed information for the class constructor template<typename nodeType> pipePacket<nodeType>::pipePacket(const std::string& simplexType, const double epsilon, const int maxDim){ std::map<std::string,std::string> blankConfig; blankConfig["dimensions"] = std::to_string(maxDim); blankConfig["epsilon"] = std::to_string(epsilon); if(complex != nullptr) delete complex; complex = simplexBase<nodeType>::newSimplex(simplexType, blankConfig); } template<typename nodeType> pipePacket<nodeType>::pipePacket(std::map<std::string, std::string> configMap, const std::string& simplexType){ if(complex != nullptr) delete complex; complex = simplexBase<nodeType>::newSimplex(simplexType, configMap); } template<typename nodeType> std::string pipePacket<nodeType>::getStats(){ std::string ret; ret += std::to_string(inputData.size()) + ","; ret += std::to_string(complex->simplexCount()); return ret; } template<typename nodeType> double pipePacket<nodeType>::getSize(){ size_t size = 0; //1. Calculate size of original data for(auto row : workData){ size += row.size() * sizeof(row[0]); } //2. Calculate size of input data for(auto row : inputData){ size += row.size() * sizeof(row[0]); } //3. Calculate size of centroid labels size += centroidLabels.size() * sizeof(centroidLabels[0]); //4. Calculate size of the distance matrix for(auto row : distMatrix){ size += row.size() * sizeof(row[0]); } //5. Calculate size of complex storage size += complex->getSize(); //6. Calculate size of the boundaries for(auto row : boundaries){ size += row.size() * sizeof(row.begin()); } //7. Calculate size of weights size += weights.size() * sizeof(weights.begin()); //8. Calculate size of bettiTable for(auto betti : bettiTable){ size += betti.getSize(); } //9. Calculate size of stats size += stats.size() * sizeof(std::string); //10. Calculate size of runLog size += runLog.size() * sizeof(std::string); return size; } //Explicit Template Class Instantiation template class pipePacket<simplexNode>; template class pipePacket<alphaNode>; template class pipePacket<witnessNode>;
25.965909
111
0.710284
[ "vector" ]
b14c9dd678cd788c564b5336fce1747074551a5a
36,636
cpp
C++
GL3Plus/src/GLSL/src/OgreGLSLProgramManagerCommon.cpp
spetz911/ogre3d
98e74672d77a201ebd4f62cb61fb4d069cd45830
[ "MIT" ]
null
null
null
GL3Plus/src/GLSL/src/OgreGLSLProgramManagerCommon.cpp
spetz911/ogre3d
98e74672d77a201ebd4f62cb61fb4d069cd45830
[ "MIT" ]
null
null
null
GL3Plus/src/GLSL/src/OgreGLSLProgramManagerCommon.cpp
spetz911/ogre3d
98e74672d77a201ebd4f62cb61fb4d069cd45830
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreGLSLProgramManagerCommon.h" #include "OgreGLSLGpuProgram.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreGLSLProgram.h" #include "OgreGpuProgramManager.h" #include "OgreHardwareBufferManager.h" #include "OgreRoot.h" namespace Ogre { //----------------------------------------------------------------------- GLSLProgramManagerCommon::GLSLProgramManagerCommon(void) : mActiveVertexGpuProgram(NULL), mActiveGeometryGpuProgram(NULL), mActiveFragmentGpuProgram(NULL), mActiveHullGpuProgram(NULL), mActiveDomainGpuProgram(NULL), mActiveComputeGpuProgram(NULL) { // Fill in the relationship between type names and enums mTypeEnumMap.insert(StringToEnumMap::value_type("float", GL_FLOAT)); mTypeEnumMap.insert(StringToEnumMap::value_type("vec2", GL_FLOAT_VEC2)); mTypeEnumMap.insert(StringToEnumMap::value_type("vec3", GL_FLOAT_VEC3)); mTypeEnumMap.insert(StringToEnumMap::value_type("vec4", GL_FLOAT_VEC4)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler1D", GL_SAMPLER_1D)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2D", GL_SAMPLER_2D)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler3D", GL_SAMPLER_3D)); mTypeEnumMap.insert(StringToEnumMap::value_type("samplerCube", GL_SAMPLER_CUBE)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler1DShadow", GL_SAMPLER_1D_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DShadow", GL_SAMPLER_2D_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("int", GL_INT)); mTypeEnumMap.insert(StringToEnumMap::value_type("ivec2", GL_INT_VEC2)); mTypeEnumMap.insert(StringToEnumMap::value_type("ivec3", GL_INT_VEC3)); mTypeEnumMap.insert(StringToEnumMap::value_type("ivec4", GL_INT_VEC4)); mTypeEnumMap.insert(StringToEnumMap::value_type("bvec2", GL_BOOL_VEC2)); mTypeEnumMap.insert(StringToEnumMap::value_type("bvec3", GL_BOOL_VEC3)); mTypeEnumMap.insert(StringToEnumMap::value_type("bvec4", GL_BOOL_VEC4)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat2", GL_FLOAT_MAT2)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat3", GL_FLOAT_MAT3)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat4", GL_FLOAT_MAT4)); // GL 2.1 mTypeEnumMap.insert(StringToEnumMap::value_type("mat2x2", GL_FLOAT_MAT2)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat3x3", GL_FLOAT_MAT3)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat4x4", GL_FLOAT_MAT4)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat2x3", GL_FLOAT_MAT2x3)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat3x2", GL_FLOAT_MAT3x2)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat3x4", GL_FLOAT_MAT3x4)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat4x3", GL_FLOAT_MAT4x3)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat2x4", GL_FLOAT_MAT2x4)); mTypeEnumMap.insert(StringToEnumMap::value_type("mat4x2", GL_FLOAT_MAT4x2)); // GL 3.0 mTypeEnumMap.insert(StringToEnumMap::value_type("uint", GL_UNSIGNED_INT)); mTypeEnumMap.insert(StringToEnumMap::value_type("uvec2", GL_UNSIGNED_INT_VEC2)); mTypeEnumMap.insert(StringToEnumMap::value_type("uvec3", GL_UNSIGNED_INT_VEC3)); mTypeEnumMap.insert(StringToEnumMap::value_type("uvec4", GL_UNSIGNED_INT_VEC4)); mTypeEnumMap.insert(StringToEnumMap::value_type("samplerCubeShadow", GL_SAMPLER_CUBE_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler1DArray", GL_SAMPLER_1D_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DArray", GL_SAMPLER_2D_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler1DArrayShadow", GL_SAMPLER_1D_ARRAY_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DArrayShadow", GL_SAMPLER_2D_ARRAY_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler1D", GL_INT_SAMPLER_1D)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler2D", GL_INT_SAMPLER_2D)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler3D", GL_INT_SAMPLER_3D)); mTypeEnumMap.insert(StringToEnumMap::value_type("isamplerCube", GL_INT_SAMPLER_CUBE)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler1DArray", GL_INT_SAMPLER_1D_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler2DArray", GL_INT_SAMPLER_2D_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler1D", GL_UNSIGNED_INT_SAMPLER_1D)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler2D", GL_UNSIGNED_INT_SAMPLER_2D)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler3D", GL_UNSIGNED_INT_SAMPLER_3D)); mTypeEnumMap.insert(StringToEnumMap::value_type("usamplerCube", GL_UNSIGNED_INT_SAMPLER_CUBE)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler1DArray", GL_UNSIGNED_INT_SAMPLER_1D_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler2DArray", GL_UNSIGNED_INT_SAMPLER_2D_ARRAY)); // GL 3.1 mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DRect", GL_SAMPLER_2D_RECT)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DRectShadow", GL_SAMPLER_2D_RECT_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler2DRect", GL_INT_SAMPLER_2D_RECT)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler2DRect", GL_UNSIGNED_INT_SAMPLER_2D_RECT)); mTypeEnumMap.insert(StringToEnumMap::value_type("samplerBuffer", GL_SAMPLER_BUFFER)); mTypeEnumMap.insert(StringToEnumMap::value_type("isamplerBuffer", GL_INT_SAMPLER_BUFFER)); mTypeEnumMap.insert(StringToEnumMap::value_type("usamplerBuffer", GL_UNSIGNED_INT_SAMPLER_BUFFER)); // GL 3.2 mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DMS", GL_SAMPLER_2D_MULTISAMPLE)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler2DMS", GL_INT_SAMPLER_2D_MULTISAMPLE)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler2DMS", GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE)); mTypeEnumMap.insert(StringToEnumMap::value_type("sampler2DMSArray", GL_SAMPLER_2D_MULTISAMPLE_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("isampler2DMSArray", GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("usampler2DMSArray", GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY)); // GL 4.0 mTypeEnumMap.insert(StringToEnumMap::value_type("double", GL_DOUBLE)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat2", GL_DOUBLE_MAT2)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat3", GL_DOUBLE_MAT3)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat4", GL_DOUBLE_MAT4)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat2x2", GL_DOUBLE_MAT2)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat3x3", GL_DOUBLE_MAT3)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat4x4", GL_DOUBLE_MAT4)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat2x3", GL_DOUBLE_MAT2x3)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat3x2", GL_DOUBLE_MAT3x2)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat3x4", GL_DOUBLE_MAT3x4)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat4x3", GL_DOUBLE_MAT4x3)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat2x4", GL_DOUBLE_MAT2x4)); mTypeEnumMap.insert(StringToEnumMap::value_type("dmat4x2", GL_DOUBLE_MAT4x2)); mTypeEnumMap.insert(StringToEnumMap::value_type("dvec2", GL_DOUBLE_VEC2)); mTypeEnumMap.insert(StringToEnumMap::value_type("dvec3", GL_DOUBLE_VEC3)); mTypeEnumMap.insert(StringToEnumMap::value_type("dvec4", GL_DOUBLE_VEC4)); mTypeEnumMap.insert(StringToEnumMap::value_type("samplerCubeArray", GL_SAMPLER_CUBE_MAP_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("samplerCubeArrayShadow", GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW)); mTypeEnumMap.insert(StringToEnumMap::value_type("isamplerCubeArray", GL_INT_SAMPLER_CUBE_MAP_ARRAY)); mTypeEnumMap.insert(StringToEnumMap::value_type("usamplerCubeArray", GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY)); // FIXME OpenGL 4 // mTypeEnumMap.insert(StringToEnumMap::value_type("image1D", GL_IMAGE_1D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage1D", GL_INT_IMAGE_1D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage1D", GL_UNSIGNED_INT_IMAGE_1D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image2D", GL_IMAGE_2D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage2D", GL_INT_IMAGE_2D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage2D", GL_UNSIGNED_INT_IMAGE_2D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image3D", GL_IMAGE_3D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage3D", GL_INT_IMAGE_3D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage3D", GL_UNSIGNED_INT_IMAGE_3D)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image2DRect", GL_IMAGE_2D_RECT)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage2DRect", GL_INT_IMAGE_2D_RECT)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage2DRect", GL_UNSIGNED_INT_IMAGE_2D_RECT)); // mTypeEnumMap.insert(StringToEnumMap::value_type("imageCube", GL_IMAGE_CUBE)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimageCube", GL_INT_IMAGE_CUBE)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimageCube", GL_UNSIGNED_INT_IMAGE_CUBE)); // mTypeEnumMap.insert(StringToEnumMap::value_type("imageBuffer", GL_IMAGE_BUFFER)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimageBuffer", GL_INT_IMAGE_BUFFER)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimageBuffer", GL_UNSIGNED_INT_IMAGE_BUFFER)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image1DArray", GL_IMAGE_1D_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage1DArray", GL_INT_IMAGE_1D_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage1DArray", GL_UNSIGNED_INT_IMAGE_1D_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image2DArray", GL_IMAGE_2D_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage2DArray", GL_INT_IMAGE_2D_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage2DArray", GL_UNSIGNED_INT_IMAGE_2D_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("imageCubeArray", GL_IMAGE_CUBE_MAP_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimageCubeArray", GL_INT_IMAGE_CUBE_MAP_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimageCubeArray", GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image2DMS", GL_IMAGE_2D_MULTISAMPLE)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage2DMS", GL_INT_IMAGE_2D_MULTISAMPLE)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage2DMS", GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE)); // mTypeEnumMap.insert(StringToEnumMap::value_type("image2DMSArray", GL_IMAGE_2D_MULTISAMPLE_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("iimage2DMSArray", GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY)); // mTypeEnumMap.insert(StringToEnumMap::value_type("uimage2DMSArray", GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY)); } //----------------------------------------------------------------------- GLSLProgramManagerCommon::~GLSLProgramManagerCommon(void) { } //--------------------------------------------------------------------- void GLSLProgramManagerCommon::completeDefInfo(GLenum gltype, GpuConstantDefinition& defToUpdate) { // Decode uniform size and type // Note GLSL never packs rows into float4's(from an API perspective anyway) // therefore all values are tight in the buffer switch (gltype) { case GL_FLOAT: defToUpdate.constType = GCT_FLOAT1; break; case GL_FLOAT_VEC2: defToUpdate.constType = GCT_FLOAT2; break; case GL_FLOAT_VEC3: defToUpdate.constType = GCT_FLOAT3; break; case GL_FLOAT_VEC4: defToUpdate.constType = GCT_FLOAT4; break; case GL_SAMPLER_1D: case GL_SAMPLER_1D_ARRAY: case GL_INT_SAMPLER_1D: case GL_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: // need to record samplers for GLSL defToUpdate.constType = GCT_SAMPLER1D; break; case GL_SAMPLER_2D: case GL_SAMPLER_2D_RECT: // TODO: Move these to a new type?? case GL_INT_SAMPLER_2D_RECT: case GL_UNSIGNED_INT_SAMPLER_2D_RECT: case GL_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: defToUpdate.constType = GCT_SAMPLER2D; break; case GL_SAMPLER_3D: case GL_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_3D: defToUpdate.constType = GCT_SAMPLER3D; break; case GL_SAMPLER_CUBE: case GL_SAMPLER_CUBE_SHADOW: case GL_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE: defToUpdate.constType = GCT_SAMPLERCUBE; break; case GL_SAMPLER_1D_SHADOW: case GL_SAMPLER_1D_ARRAY_SHADOW: defToUpdate.constType = GCT_SAMPLER1DSHADOW; break; case GL_SAMPLER_2D_SHADOW: case GL_SAMPLER_2D_RECT_SHADOW: case GL_SAMPLER_2D_ARRAY_SHADOW: defToUpdate.constType = GCT_SAMPLER2DSHADOW; break; case GL_INT: defToUpdate.constType = GCT_INT1; break; case GL_INT_VEC2: defToUpdate.constType = GCT_INT2; break; case GL_INT_VEC3: defToUpdate.constType = GCT_INT3; break; case GL_INT_VEC4: defToUpdate.constType = GCT_INT4; break; case GL_FLOAT_MAT2: defToUpdate.constType = GCT_MATRIX_2X2; break; case GL_FLOAT_MAT3: defToUpdate.constType = GCT_MATRIX_3X3; break; case GL_FLOAT_MAT4: defToUpdate.constType = GCT_MATRIX_4X4; break; case GL_FLOAT_MAT2x3: defToUpdate.constType = GCT_MATRIX_2X3; break; case GL_FLOAT_MAT3x2: defToUpdate.constType = GCT_MATRIX_3X2; break; case GL_FLOAT_MAT2x4: defToUpdate.constType = GCT_MATRIX_2X4; break; case GL_FLOAT_MAT4x2: defToUpdate.constType = GCT_MATRIX_4X2; break; case GL_FLOAT_MAT3x4: defToUpdate.constType = GCT_MATRIX_3X4; break; case GL_FLOAT_MAT4x3: defToUpdate.constType = GCT_MATRIX_4X3; break; case GL_DOUBLE: defToUpdate.constType = GCT_DOUBLE1; break; case GL_DOUBLE_VEC2: defToUpdate.constType = GCT_DOUBLE2; break; case GL_DOUBLE_VEC3: defToUpdate.constType = GCT_DOUBLE3; break; case GL_DOUBLE_VEC4: defToUpdate.constType = GCT_DOUBLE4; break; case GL_DOUBLE_MAT2: defToUpdate.constType = GCT_MATRIX_DOUBLE_2X2; break; case GL_DOUBLE_MAT3: defToUpdate.constType = GCT_MATRIX_DOUBLE_3X3; break; case GL_DOUBLE_MAT4: defToUpdate.constType = GCT_MATRIX_DOUBLE_4X4; break; case GL_DOUBLE_MAT2x3: defToUpdate.constType = GCT_MATRIX_DOUBLE_2X3; break; case GL_DOUBLE_MAT3x2: defToUpdate.constType = GCT_MATRIX_DOUBLE_3X2; break; case GL_DOUBLE_MAT2x4: defToUpdate.constType = GCT_MATRIX_DOUBLE_2X4; break; case GL_DOUBLE_MAT4x2: defToUpdate.constType = GCT_MATRIX_DOUBLE_4X2; break; case GL_DOUBLE_MAT3x4: defToUpdate.constType = GCT_MATRIX_DOUBLE_3X4; break; case GL_DOUBLE_MAT4x3: defToUpdate.constType = GCT_MATRIX_DOUBLE_4X3; break; default: defToUpdate.constType = GCT_UNKNOWN; break; } // GL doesn't pad defToUpdate.elementSize = GpuConstantDefinition::getElementSize(defToUpdate.constType, false); } //--------------------------------------------------------------------- bool GLSLProgramManagerCommon::completeParamSource( const String& paramName, const GpuConstantDefinitionMap* vertexConstantDefs, const GpuConstantDefinitionMap* geometryConstantDefs, const GpuConstantDefinitionMap* fragmentConstantDefs, const GpuConstantDefinitionMap* hullConstantDefs, const GpuConstantDefinitionMap* domainConstantDefs, const GpuConstantDefinitionMap* computeConstantDefs, GLUniformReference& refToUpdate) { if (vertexConstantDefs) { GpuConstantDefinitionMap::const_iterator parami = vertexConstantDefs->find(paramName); if (parami != vertexConstantDefs->end()) { refToUpdate.mSourceProgType = GPT_VERTEX_PROGRAM; refToUpdate.mConstantDef = &(parami->second); return true; } } if (geometryConstantDefs) { GpuConstantDefinitionMap::const_iterator parami = geometryConstantDefs->find(paramName); if (parami != geometryConstantDefs->end()) { refToUpdate.mSourceProgType = GPT_GEOMETRY_PROGRAM; refToUpdate.mConstantDef = &(parami->second); return true; } } if (fragmentConstantDefs) { GpuConstantDefinitionMap::const_iterator parami = fragmentConstantDefs->find(paramName); if (parami != fragmentConstantDefs->end()) { refToUpdate.mSourceProgType = GPT_FRAGMENT_PROGRAM; refToUpdate.mConstantDef = &(parami->second); return true; } } if (hullConstantDefs) { GpuConstantDefinitionMap::const_iterator parami = hullConstantDefs->find(paramName); if (parami != hullConstantDefs->end()) { refToUpdate.mSourceProgType = GPT_HULL_PROGRAM; refToUpdate.mConstantDef = &(parami->second); return true; } } if (domainConstantDefs) { GpuConstantDefinitionMap::const_iterator parami = domainConstantDefs->find(paramName); if (parami != domainConstantDefs->end()) { refToUpdate.mSourceProgType = GPT_DOMAIN_PROGRAM; refToUpdate.mConstantDef = &(parami->second); return true; } } // FIXME // if (computeConstantDefs) // { // GpuConstantDefinitionMap::const_iterator parami = // computeConstantDefs->find(paramName); // if (parami != computeConstantDefs->end()) // { // refToUpdate.mSourceProgType = GPT_COMPUTE_PROGRAM; // refToUpdate.mConstantDef = &(parami->second); // return true; // } // } return false; } //--------------------------------------------------------------------- void GLSLProgramManagerCommon::extractUniforms(GLuint programObject, const GpuConstantDefinitionMap* vertexConstantDefs, const GpuConstantDefinitionMap* geometryConstantDefs, const GpuConstantDefinitionMap* fragmentConstantDefs, const GpuConstantDefinitionMap* hullConstantDefs, const GpuConstantDefinitionMap* domainConstantDefs, const GpuConstantDefinitionMap* computeConstantDefs, GLUniformReferenceList& list, GLUniformBufferList& sharedList) { // Scan through the active uniforms and add them to the reference list GLint uniformCount = 0; #define uniformLength 200 // GLint uniformLength = 0; // glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformLength); char uniformName[uniformLength]; GLUniformReference newGLUniformReference; // Get the number of active uniforms OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORMS, &uniformCount)); // Loop over each of the active uniforms, and add them to the reference container // only do this for user defined uniforms, ignore built in gl state uniforms for (int index = 0; index < uniformCount; index++) { GLint arraySize; GLenum glType; OGRE_CHECK_GL_ERROR(glGetActiveUniform(programObject, index, uniformLength, NULL, &arraySize, &glType, uniformName)); // Don't add built in uniforms OGRE_CHECK_GL_ERROR(newGLUniformReference.mLocation = glGetUniformLocation(programObject, uniformName)); if (newGLUniformReference.mLocation >= 0) { // User defined uniform found, add it to the reference list String paramName = String( uniformName ); // Current ATI drivers (Catalyst 7.2 and earlier) and older NVidia drivers will include all array elements as uniforms but we only want the root array name and location // Also note that ATI Catalyst 6.8 to 7.2 there is a bug with glUniform that does not allow you to update a uniform array past the first uniform array element // ie you can't start updating an array starting at element 1, must always be element 0. // If the uniform name has a "[" in it then its an array element uniform. String::size_type arrayStart = paramName.find("["); if (arrayStart != String::npos) { // if not the first array element then skip it and continue to the next uniform if (paramName.compare(arrayStart, paramName.size() - 1, "[0]") != 0) continue; paramName = paramName.substr(0, arrayStart); } // Find out which params object this comes from bool foundSource = completeParamSource(paramName, vertexConstantDefs, geometryConstantDefs, fragmentConstantDefs, hullConstantDefs, domainConstantDefs, computeConstantDefs, newGLUniformReference); // Only add this parameter if we found the source if (foundSource) { assert(size_t (arraySize) == newGLUniformReference.mConstantDef->arraySize && "GL doesn't agree with our array size!"); list.push_back(newGLUniformReference); } // Don't bother adding individual array params, they will be // picked up in the 'parent' parameter can copied all at once // anyway, individual indexes are only needed for lookup from // user params } // end if } // end for // Now deal with uniform blocks GLint blockCount = 0; OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_BLOCKS, &blockCount)); for (int index = 0; index < blockCount; index++) { OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockName(programObject, index, uniformLength, NULL, uniformName)); GpuSharedParametersPtr blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(uniformName); GLint blockSize, blockBinding; OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize)); OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_BINDING, &blockBinding)); HardwareUniformBufferSharedPtr newUniformBuffer = HardwareBufferManager::getSingleton().createUniformBuffer(blockSize, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, false, uniformName); GL3PlusHardwareUniformBuffer* hwGlBuffer = static_cast<GL3PlusHardwareUniformBuffer*>(newUniformBuffer.get()); hwGlBuffer->setGLBufferBinding(blockBinding); sharedList.push_back(newUniformBuffer); } } //--------------------------------------------------------------------- void GLSLProgramManagerCommon::extractConstantDefs(const String& src, GpuNamedConstants& defs, const String& filename) { // Parse the output string and collect all uniforms // NOTE this relies on the source already having been preprocessed // which is done in GLSLProgram::loadFromSource String line; String::size_type currPos = src.find("uniform"); while (currPos != String::npos) { // Now check for using the word 'uniform' in a larger string & ignore bool inLargerString = false; if (currPos != 0) { char prev = src.at(currPos - 1); if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n' && prev != ';') inLargerString = true; } if (!inLargerString && currPos + 7 < src.size()) { char next = src.at(currPos + 7); if (next != ' ' && next != '\t' && next != '\r' && next != '\n') inLargerString = true; } // skip 'uniform' currPos += 7; if (!inLargerString) { String::size_type endPos; GpuSharedParametersPtr blockSharedParams; // Check for a type. If there is one, then the semicolon is missing // otherwise treat as if it is a uniform block String::size_type lineEndPos = src.find_first_of("\n\r", currPos); line = src.substr(currPos, lineEndPos - currPos); StringVector parts = StringUtil::split(line, " \t"); StringToEnumMap::iterator typei = mTypeEnumMap.find(parts.front()); if (typei == mTypeEnumMap.end()) { // Gobble up the external name String externalName = parts.front(); // Now there should be an opening brace String::size_type openBracePos = src.find("{", currPos); if (openBracePos != String::npos) { currPos = openBracePos + 1; } else { LogManager::getSingleton().logMessage("Missing opening brace in GLSL Uniform Block in file " + filename, LML_CRITICAL); break; } // First we need to find the internal name for the uniform block String::size_type endBracePos = src.find("}", currPos); // Find terminating semicolon currPos = endBracePos + 1; endPos = src.find(";", currPos); if (endPos == String::npos) { // problem, missing semicolon, abort break; } // TODO: We don't need the internal name. Just skip over to the end of the block // But we do need to know if this is an array of blocks. Is that legal? // Find the internal name. // This can be an array. // line = src.substr(currPos, endPos - currPos); // StringVector internalParts = StringUtil::split(line, ", \t\r\n"); // String internalName = ""; // uint16 arraySize = 0; // for (StringVector::iterator i = internalParts.begin(); i != internalParts.end(); ++i) // { // StringUtil::trim(*i); // String::size_type arrayStart = i->find("[", 0); // if (arrayStart != String::npos) // { // // potential name (if butted up to array) // String name = i->substr(0, arrayStart); // StringUtil::trim(name); // if (!name.empty()) // internalName = name; // // String::size_type arrayEnd = i->find("]", arrayStart); // String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1); // StringUtil::trim(arrayDimTerm); // arraySize = StringConverter::parseUnsignedInt(arrayDimTerm); // } // else // { // internalName = *i; // } // } // // // Ok, now rewind and parse the individual uniforms in this block // currPos = openBracePos + 1; // blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(externalName); // if(blockSharedParams.isNull()) // blockSharedParams = GpuProgramManager::getSingleton().createSharedParameters(externalName); // do // { // lineEndPos = src.find_first_of("\n\r", currPos); // endPos = src.find(";", currPos); // line = src.substr(currPos, endPos - currPos); // // // TODO: Give some sort of block id // // Parse the normally structured uniform // parseIndividualConstant(src, defs, currPos, filename, blockSharedParams); // currPos = lineEndPos + 1; // } while (endBracePos > currPos); } else { // find terminating semicolon endPos = src.find(";", currPos); if (endPos == String::npos) { // problem, missing semicolon, abort break; } parseIndividualConstant(src, defs, currPos, filename, blockSharedParams); } line = src.substr(currPos, endPos - currPos); } // not commented or a larger symbol // Find next one currPos = src.find("uniform", currPos); } } //--------------------------------------------------------------------- void GLSLProgramManagerCommon::parseIndividualConstant(const String& src, GpuNamedConstants& defs, String::size_type currPos, const String& filename, GpuSharedParametersPtr sharedParams) { GpuConstantDefinition def; String paramName = ""; String::size_type endPos = src.find(";", currPos); String line = src.substr(currPos, endPos - currPos); // Remove spaces before opening square braces, otherwise // the following split() can split the line at inappropriate // places (e.g. "vec3 something [3]" won't work). for (String::size_type sqp = line.find (" ["); sqp != String::npos; sqp = line.find (" [")) line.erase (sqp, 1); // Split into tokens StringVector parts = StringUtil::split(line, ", \t\r\n"); for (StringVector::iterator i = parts.begin(); i != parts.end(); ++i) { // Is this a type? StringToEnumMap::iterator typei = mTypeEnumMap.find(*i); if (typei != mTypeEnumMap.end()) { completeDefInfo(typei->second, def); } else { // if this is not a type, and not empty, it should be a name StringUtil::trim(*i); if (i->empty()) continue; // Skip over precision keywords if(StringUtil::match((*i), "lowp") || StringUtil::match((*i), "mediump") || StringUtil::match((*i), "highp")) continue; String::size_type arrayStart = i->find("[", 0); if (arrayStart != String::npos) { // potential name (if butted up to array) String name = i->substr(0, arrayStart); StringUtil::trim(name); if (!name.empty()) paramName = name; String::size_type arrayEnd = i->find("]", arrayStart); String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1); StringUtil::trim(arrayDimTerm); // the array term might be a simple number or it might be // an expression (e.g. 24*3) or refer to a constant expression // we'd have to evaluate the expression which could get nasty // TODO def.arraySize = StringConverter::parseInt(arrayDimTerm); } else { paramName = *i; def.arraySize = 1; } // Name should be after the type, so complete def and add // We do this now so that comma-separated params will do // this part once for each name mentioned if (def.constType == GCT_UNKNOWN) { LogManager::getSingleton().logMessage("Problem parsing the following GLSL Uniform: '" + line + "' in file " + filename, LML_CRITICAL); // next uniform break; } // Special handling for shared parameters if(sharedParams.isNull()) { // Complete def and add // increment physical buffer location def.logicalIndex = 0; // not valid in GLSL if (def.isFloat()) { def.physicalIndex = defs.floatBufferSize; defs.floatBufferSize += def.arraySize * def.elementSize; } else { def.physicalIndex = defs.intBufferSize; defs.intBufferSize += def.arraySize * def.elementSize; } defs.map.insert(GpuConstantDefinitionMap::value_type(paramName, def)); // Generate array accessors defs.generateConstantDefinitionArrayEntries(paramName, def); } else { try { const GpuConstantDefinition &sharedDef = sharedParams->getConstantDefinition(paramName); (void)sharedDef; // Silence warning } catch (Exception& e) { // This constant doesn't exist so we'll create a new one sharedParams->addConstantDefinition(paramName, def.constType); } } } } } }
48.268775
203
0.631155
[ "object" ]
b14d4584e5286eb33c7391add827d3f094373e36
1,797
cc
C++
thrift/compiler/generate/t_android_generator.cc
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
thrift/compiler/generate/t_android_generator.cc
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
1
2022-03-03T09:40:25.000Z
2022-03-03T09:40:25.000Z
thrift/compiler/generate/t_android_generator.cc
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/compiler/generate/t_android_generator.h> #include <cctype> #include <fstream> #include <sstream> #include <string> #include <vector> #include <stdexcept> #include <boost/filesystem.hpp> using namespace std; namespace apache { namespace thrift { namespace compiler { /** * Prepares for file generation by opening up the necessary file output * streams. * * @param tprogram The program to generate */ void t_android_generator::init_generator() { // Make output directory boost::filesystem::create_directory(get_out_dir()); namespace_key_ = "android"; package_name_ = program_->get_namespace(namespace_key_); string dir = package_name_; string subdir = get_out_dir(); string::size_type loc; while ((loc = dir.find('.')) != string::npos) { subdir = subdir + "/" + dir.substr(0, loc); boost::filesystem::create_directory(subdir); dir = dir.substr(loc + 1); } if (dir.size() > 0) { subdir = subdir + "/" + dir; boost::filesystem::create_directory(subdir); } package_dir_ = subdir; } THRIFT_REGISTER_GENERATOR(android, "Android Java", ""); } // namespace compiler } // namespace thrift } // namespace apache
26.426471
75
0.710629
[ "vector" ]
b14e7ee3d7b0a8f1d6fb323d712287a18c5c6e79
3,062
cpp
C++
MOM-Glove/MOM-Glove.cpp
Make-O-Matic/MOM-Glove
2157c13bc51eb3e09378383aef68ccdb6237d5ce
[ "MIT" ]
null
null
null
MOM-Glove/MOM-Glove.cpp
Make-O-Matic/MOM-Glove
2157c13bc51eb3e09378383aef68ccdb6237d5ce
[ "MIT" ]
null
null
null
MOM-Glove/MOM-Glove.cpp
Make-O-Matic/MOM-Glove
2157c13bc51eb3e09378383aef68ccdb6237d5ce
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <SoftwareSerial.h> #include "PacketSerial.h" #include "Adafruit_BNO055.h" #include "Adafruit_DRV2605.h" extern "C" { //#include "pfleury/uart.h" }; FUSES = { .low = 0xFF, //0xFF .high = FUSE_SPIEN & FUSE_BOOTSZ0 & FUSE_BOOTRST, //0xDC .extended = FUSE_BODLEVEL1 //0xFD }; LOCKBITS = LB_MODE_3; //0xFC #define UART_BAUD_RATE 115200 Adafruit_BNO055 bno = Adafruit_BNO055(55); Adafruit_DRV2605 drv = Adafruit_DRV2605(); PacketSerial PSerial; SoftwareSerial RFID_1(2, 3); SoftwareSerial RFID_2(4, 5); uint8_t switchcnt; uint8_t rfidcnt = 0; #define RFID_CNT 4; uint8_t ledcnt = 0; #define VIB_BIB 1 #define VIB_NR 14 uint8_t vibr[] = {14, 15, 16, 47, 48, 54, 64, 70, 73, 74}; #define KEY 6 #define BEEP 7 uint8_t beepcnt = 0; #define BEEP_CNT 10 #define WEAR 8 #define GRASP_A A0 #define GRASP_B A1 #define GRASP_C A2 #include "Packet.h" Packet pkg; void process_rfid(uint8_t c) { static uint8_t buffer[64]; static int count = 0; if (c == 0x02) { count = 0; } else if (c == 0x03) { ledcnt = 0; memcpy(pkg.rfid, buffer, sizeof(pkg.rfid)); rfidcnt = RFID_CNT; } else if(count < 64) { buffer[count++] = c; } } inline void set_led(void) { if (ledcnt < 10) { if (ledcnt == 0) { digitalWrite(LED_BUILTIN, HIGH); } ledcnt++; } else { digitalWrite(LED_BUILTIN, LOW); } } inline void process_cmd(uint8_t cmd) { if (cmd >= '0' && cmd <= '9' && cmd - '0' < (uint8_t) sizeof(vibr)) { drv.setWaveform(VIB_BIB, vibr[cmd - '0']); drv.go(); } if (cmd == '*') { beepcnt = BEEP_CNT; digitalWrite(BEEP, HIGH); } } inline void read_bno(void) { sensors_event_t event; bno.getEvent(&event); pkg.ex = event.orientation.x; pkg.ey = event.orientation.y; pkg.ez = event.orientation.z; imu::Vector<3> vec = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL); pkg.ax = vec.x(); pkg.ay = vec.y(); pkg.az = vec.z(); } inline void read_inputs(void) { pkg.key = digitalRead(KEY) ^ 1; pkg.wear = digitalRead(WEAR) ^ 1; pkg.graspa = analogRead(GRASP_A); pkg.graspb = analogRead(GRASP_B); pkg.graspc = analogRead(GRASP_C); } void setup() { pinMode(LED_BUILTIN, OUTPUT); pinMode(BEEP, OUTPUT); pinMode(KEY, INPUT_PULLUP); pinMode(WEAR, INPUT_PULLUP); PSerial.begin(115200); RFID_1.begin(9600); RFID_2.begin(9600); bno.begin(); delay(1000); bno.setExtCrystalUse(true); drv.begin(); drv.useERM(); drv.selectLibrary(2); drv.setWaveform(VIB_BIB, VIB_NR); sei(); } void loop() { read_bno(); read_inputs(); PSerial.send((uint8_t*) &pkg, sizeof(pkg)); if (rfidcnt) { rfidcnt--; } else { memset(pkg.rfid, 0, sizeof(pkg.rfid)); } set_led(); if (beepcnt) { beepcnt--; } else { digitalWrite(BEEP, LOW); } delay(20); //if (switchcnt++ % 10 < 5) /*{ RFID_1.listen(); while(RFID_1.available() > 0) { pkg.lastnr = 0; process_rfid(RFID_1.read()); } } else { */ RFID_2.listen(); while(RFID_2.available() > 0) { pkg.lastnr = 1; process_rfid(RFID_2.read()); } //} if (Serial.available()) { process_cmd(Serial.read()); } }
16.287234
73
0.650555
[ "vector" ]
b14f18cf1560bdb3fd672badbdd37868d71d202a
3,911
cpp
C++
mahbubul-hassan/3-e-treap.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
mahbubul-hassan/3-e-treap.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
mahbubul-hassan/3-e-treap.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
#include <bits/stdc++.h> using namespace std; #define PI 2*acos(0) #define ll long long int bool myAssert(bool b); void testDrivenDevelopment(); int start(int argc=0, char const *argv[] = NULL); int n,m; vector<int> *g; bool *isvisited; #define TN TreapNode class TreapNode{ public: int key, priority; TN *l, *r; TreapNode(int key = 0){ this->key = key; priority = rand()%100; l = NULL; r = NULL; } }; TN *rotateRight(TN *y){ TN *x = y->l, *T2 = x->r; // perform rotation x->r = y; y->l = T2; return x; } TN *rotateLeft(TN *x){ TN *y=x->r, *T2 = y->l; // perform rotation y->l = x; x->r = T2; return y; } TN *search(TN *root, int key){ //just like binary search if( (root == NULL) || (root->key == key) ){ return root; } // left if(key < root->key){ return search(root->l, key); }else{ return search(root->r, key); } return NULL; } TN *insert(TN *root, int key){ // if no root, create a new node and return if(!root){ root = new TN(key); return root; } if(key <=root->key){ // insert in the left branch root->l = insert(root->l, key); // fix priority issue if(root->l->priority > root->priority){ root = rotateRight(root); } }else{ root->r = insert(root->r, key); // fix priority if(root->r->priority > root->priority){ root = rotateLeft(root); } } return root; } TN *deleteNode(TN *root, int key){ if(root == NULL){ return root; } if(key < root->key){ root = deleteNode(root->l, key); } else if (key > root->key){ root = deleteNode(root->r, key); } // if key is at root // if left = NULL else if(root->l == NULL){ TN *temp = root->r; root->r = NULL; delete(root); root = temp; temp = NULL; } // if right == NULL else if(root->r == NULL){ TN *temp = root->l; root->l = NULL; delete(root); root = temp; temp = NULL; }else if(root->l->priority < root->r->priority){ root = rotateLeft(root); root->r = deleteNode(root->l, key); }else{ root = rotateRight(root); root->r = deleteNode(root->r, key); } return root; } void inorder(TN *root){ if(root){ inorder(root->l); cout << "key: "<< root->key << " | priority: %d " << root->priority; if (root->l) cout << " | left child: " << root->l->key; if (root->r) cout << " | right child: " << root->r->key; cout << endl; inorder(root->r); } } int main(int argc, char const *argv[]) { /* code */ /* Soln soln */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* cout << setprecision(8); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); srand(time(NULL)); TN *root(NULL); root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); cout << "Inorder traversal of the given tree \n"; inorder(root); cout << "\nDelete 20\n"; root = deleteNode(root, 20); cout << "Inorder traversal of the modified tree \n"; inorder(root); cout << "\nDelete 30\n"; root = deleteNode(root, 30); cout << "Inorder traversal of the modified tree \n"; inorder(root); cout << "\nDelete 50\n"; root = deleteNode(root, 50); cout << "Inorder traversal of the modified tree \n"; inorder(root); TreapNode *res = search(root, 50); (res == NULL)? cout << "\n50 Not Found ": cout << "\n50 found"; return 0; }
21.727778
68
0.510867
[ "vector" ]
b151373e01791e90127b01d9ddff8e77162d6ca1
2,973
cpp
C++
libs/core/thread_support/tests/unit/range.cpp
msimberg/hpx-local
18a15d139d52969994b306dffc00af9a56e1e04f
[ "BSL-1.0" ]
6
2021-12-17T15:00:57.000Z
2022-01-13T17:50:22.000Z
libs/core/thread_support/tests/unit/range.cpp
msimberg/hpx-local
18a15d139d52969994b306dffc00af9a56e1e04f
[ "BSL-1.0" ]
20
2021-11-03T10:16:49.000Z
2022-01-20T02:05:19.000Z
libs/core/thread_support/tests/unit/range.cpp
msimberg/hpx-local
18a15d139d52969994b306dffc00af9a56e1e04f
[ "BSL-1.0" ]
2
2021-12-17T15:35:33.000Z
2022-01-11T12:26:20.000Z
// Copyright (c) 2016 Agustin Berge // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpx/local/config.hpp> #include <hpx/iterator_support/range.hpp> #include <hpx/modules/testing.hpp> #include <vector> /////////////////////////////////////////////////////////////////////////////// void array_range() { int r[3] = {0, 1, 2}; HPX_TEST_EQ(hpx::util::begin(r), &r[0]); HPX_TEST_EQ(hpx::util::end(r), &r[3]); int const cr[3] = {0, 1, 2}; HPX_TEST_EQ(hpx::util::begin(cr), &cr[0]); HPX_TEST_EQ(hpx::util::end(cr), &cr[3]); HPX_TEST_EQ(hpx::util::size(cr), 3u); HPX_TEST_EQ(hpx::util::empty(cr), false); } /////////////////////////////////////////////////////////////////////////////// struct member { int x; int* begin() { return &x; } int const* begin() const { return &x; } int* end() { return &x + 1; } int const* end() const { return &x + 1; } }; void member_range() { member r = member(); HPX_TEST_EQ(hpx::util::begin(r), &r.x); HPX_TEST_EQ(hpx::util::end(r), &r.x + 1); member const cr = member(); HPX_TEST_EQ(hpx::util::begin(cr), &cr.x); HPX_TEST_EQ(hpx::util::end(cr), &cr.x + 1); HPX_TEST_EQ(hpx::util::size(cr), 1u); HPX_TEST_EQ(hpx::util::empty(cr), false); } /////////////////////////////////////////////////////////////////////////////// namespace adl { struct free { int x; }; int* begin(free& r) { return &r.x; } int const* begin(free const& r) { return &r.x; } int* end(free& r) { return &r.x + 1; } int const* end(free const& r) { return &r.x + 1; } } // namespace adl void adl_range() { adl::free r = adl::free(); HPX_TEST_EQ(hpx::util::begin(r), &r.x); HPX_TEST_EQ(hpx::util::end(r), &r.x + 1); adl::free const cr = adl::free(); HPX_TEST_EQ(hpx::util::begin(cr), &cr.x); HPX_TEST_EQ(hpx::util::end(cr), &cr.x + 1); HPX_TEST_EQ(hpx::util::size(cr), 1u); HPX_TEST_EQ(hpx::util::empty(cr), false); } /////////////////////////////////////////////////////////////////////////////// void vector_range() { std::vector<int> r(3); HPX_TEST_EQ(hpx::util::begin(r), r.begin()); HPX_TEST_EQ(hpx::util::end(r), r.end()); std::vector<int> cr(3); HPX_TEST_EQ(hpx::util::begin(cr), cr.begin()); HPX_TEST_EQ(hpx::util::end(cr), cr.end()); HPX_TEST_EQ(hpx::util::size(cr), 3u); HPX_TEST_EQ(hpx::util::empty(cr), false); } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { { array_range(); member_range(); adl_range(); vector_range(); } return hpx::util::report_errors(); }
22.353383
80
0.480659
[ "vector" ]
b152dc062596bfb2585aecf81dd6c7dd1a991321
20,729
cpp
C++
GamingAnywhere/core/ga-conf.cpp
Kaleem2255/Cloud-Gaming-Windows-Sample
09473271aafdb0eabad29a7d9c61753b66172d15
[ "BSD-3-Clause" ]
37
2019-08-08T19:02:09.000Z
2022-01-16T17:35:47.000Z
GamingAnywhere/core/ga-conf.cpp
Kaleem2255/Cloud-Gaming-Windows-Sample
09473271aafdb0eabad29a7d9c61753b66172d15
[ "BSD-3-Clause" ]
1
2019-08-29T09:57:13.000Z
2019-08-29T10:11:31.000Z
GamingAnywhere/core/ga-conf.cpp
Kaleem2255/Cloud-Gaming-Windows-Sample
09473271aafdb0eabad29a7d9c61753b66172d15
[ "BSD-3-Clause" ]
17
2019-08-29T09:58:13.000Z
2022-01-30T14:05:53.000Z
/* * Copyright (c) 2013 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA 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. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * @file * GamingAnywhere configuration file loader: implementations */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <map> #include <vector> #include <string> #ifdef WIN32 #else #include <libgen.h> #endif #include "ga-common.h" #include "ga-conf.h" #include "ga-confvar.h" using namespace std; /** Global variables used to store loaded configurations */ static map<string,gaConfVar> ga_vars; static map<string,gaConfVar>::iterator ga_vmi = ga_vars.begin(); /** * Trim a configuration string. This is an internal function. * * @param buf [in] Pointer to a loaded string from the configuration file. * @return Pointer to the trimmed string. * * Note that this function does not preserve the content of the input string. * This function pre-process a loaded string based on the following logics: * - Remove heading space characters * - Remove section header '[': * Section headers is only for improving configuration file's readability. * - Remove comment char from head: '#', ';', and '//' * - Remove comment char from tail: '#' * - Remove space characters and the end */ static char * ga_conf_trim(char *buf) { char *ptr; // remove head spaces while(*buf && isspace(*buf)) buf++; // remove section if(buf[0] == '[') { buf[0] = '\0'; return buf; } // remove comments if((ptr = strchr(buf, '#')) != NULL) *ptr = '\0'; if((ptr = strchr(buf, ';')) != NULL) *ptr = '\0'; if((ptr = strchr(buf, '/')) != NULL) { if(*(ptr+1) == '/') *ptr = '\0'; } // move ptr to the end, again for(ptr = buf; *ptr; ptr++) ; --ptr; // remove comments while(ptr >= buf) { if(*ptr == '#') *ptr = '\0'; ptr--; } // move ptr to the end, again for(ptr = buf; *ptr; ptr++) ; --ptr; // remove tail spaces while(ptr >= buf && isspace(*ptr)) *ptr-- = '\0'; // return buf; } /** * Parse a single configuration string. This is an internal function. * * @param filename [in] The current configuration file name. * @param lineno [in] The current line number of the string. * @param buf [in] The content of the current configuration string. * @return 0 on success, or -1 on error. */ static int ga_conf_parse(const char *filename, int lineno, char *buf) { char *option, *token; //, *saveptr; char *leftbracket, *rightbracket; gaConfVar gcv; // option = buf; if((token = strchr(buf, '=')) == NULL) { return 0; } if(*(token+1) == '\0') { return 0; } *token++ = '\0'; // option = ga_conf_trim(option); if(*option == '\0') return 0; // token = ga_conf_trim(token); if(token[0] == '\0') return 0; // check if its a include if(strcmp(option, "include") == 0) { #ifdef WIN32 char incfile[_MAX_PATH]; char tmpdn[_MAX_DIR]; char drive[_MAX_DRIVE], tmpfn[_MAX_FNAME]; char *ptr = incfile; if(token[0] == '/' || token[0] == '\\' || token[1] == ':') { strncpy(incfile, token, sizeof(incfile)); } else { _splitpath(filename, drive, tmpdn, tmpfn, NULL); _makepath(incfile, drive, tmpdn, token, NULL); } // replace '/' with '\\' while(*ptr) { if(*ptr == '/') *ptr = '\\'; ptr++; } #else char incfile[PATH_MAX]; char tmpdn[PATH_MAX]; // strncpy(tmpdn, filename, sizeof(tmpdn)); if(token[0]=='/') { strncpy(incfile, token, sizeof(incfile)); } else { snprintf(incfile, sizeof(incfile), "%s/%s", dirname(tmpdn), token); } #endif //ga_error("# include: %s\n", incfile); return ga_conf_load(incfile); } // check if its a map if((leftbracket = strchr(option, '[')) != NULL) { rightbracket = strchr(leftbracket+1, ']'); if(rightbracket == NULL) { ga_error("# %s:%d: malformed option (%s without right bracket).\n", filename, lineno, option); return -1; } // no key specified if(leftbracket + 1 == rightbracket) { ga_error("# %s:%d: malformed option (%s without a key).\n", filename, lineno, option); return -1; } // garbage after rightbracket? if(*(rightbracket+1) != '\0') { ga_error("# %s:%d: malformed option (%s?).\n", filename, lineno, option); return -1; } *leftbracket = '\0'; leftbracket++; *rightbracket = '\0'; } // its a map if(leftbracket != NULL) { //ga_error("%s[%s] = %s\n", option, leftbracket, token); ga_vars[option][leftbracket] = token; } else { //ga_error("%s = %s\n", option, token); ga_vars[option] = token; } return 0; } /** * Load a configuration file. * * @param filename [in] The configuration pathname * @return 0 on success, or -1 on error. * * The given configuration file is parsed and loaded into the system. * Other system components can then read the loaded parameters using * functions exported from this file. */ int ga_conf_load(const char *filename) { FILE *fp; char buf[8192]; int lineno = 0; // if(filename == NULL) return -1; if((fp = fopen(filename, "rt")) == NULL) { return -1; } while(fgets(buf, sizeof(buf), fp) != NULL) { lineno++; if(ga_conf_parse(filename, lineno, buf) < 0) { fclose(fp); return -1; } } fclose(fp); return lineno; } /** * Clear all loaded configuration. */ void ga_conf_clear() { ga_vars.clear(); ga_vmi = ga_vars.begin(); return; } /** * Load the value of a parameter in string format. * * @param key [in] The parameter to be loaded. * @param store [in,out] Buffer to store the loaded value. * @param slen[in] Length of buffers pointed by \a store. * @return A pointer to the loaded value on success, or NULL on error. * * Note that if \a store is NULL, this function automatically allocates * spaces to store the result. You may need to release the memory by * calling \em free(). */ char * ga_conf_readv(const char *key, char *store, int slen) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(key)) == ga_vars.end()) return NULL; if(mi->second.value().c_str() == NULL) return NULL; if(store == NULL) return strdup(mi->second.value().c_str()); strncpy(store, mi->second.value().c_str(), slen); return store; } /** * Load the value of a parameter as an integer. * * @param key [in] The parameter to be loaded. * @return The integer value of the parameter. * * Note that when the given parameter is not defined, * this function returns zero. */ int ga_conf_readint(const char *key) { char buf[64]; char *ptr = ga_conf_readv(key, buf, sizeof(buf)); if(ptr == NULL) return 0; return strtol(ptr, NULL, 0); } /** * Load the value of a parameter as an double float number. * * @param key [in] The parameter to be loaded. * @return The double float value of the parameter. * * Note that when the given parameter is not defined, * this function returns 0.0. */ double ga_conf_readdouble(const char *key) { char buf[64]; char *ptr = ga_conf_readv(key, buf, sizeof(buf)); if(ptr == NULL) return 0.0; return strtod(ptr, NULL); } /** * Load multiple integer values specified in a parameter. * This is an internal function. * * @param key [in] The parameter to be loaded. * @param val [out] An integer array used to store loaded integers. * @param n [in] The expected number of integers to be loaded. * @return The exact number of integers loaded into \a val. * This number can be less than or equal to \a n. * * This function attempts to loads \a n numbers from the parameter and * store the loaded number in \a val in the order. * * A sample configuration line is: param = 1 2 3. */ static int ga_conf_multiple_int(char *buf, int *val, int n) { int reads = 0; char *endptr, *ptr = buf; while(reads < n) { val[reads] = strtol(ptr, &endptr, 0); if(ptr == endptr) break; ptr = endptr; reads++; } return reads; } /** * Load multiple integer values specified in a parameter. * * @param key [in] The parameter to be loaded. * @param val [out] An integer array used to store loaded integers. * @param n [in] The expected number of integers to be loaded. * @return The exact number of integers loaded into \a val. * This number can be less than or equal to \a n. * * This function attempts to loads \a n numbers from the parameter and * store the loaded number in \a val in the order. * * A sample configuration line is: param = 1 2 3. */ int ga_conf_readints(const char *key, int *val, int n) { char buf[1024]; char *ptr = ga_conf_readv(key, buf, sizeof(buf)); if(ptr == NULL) return 0; return ga_conf_multiple_int(buf, val, n); } /** * Determine whether a string represents TRUE or FALSE. * * @param ptr [in] The string to be determined. * @param defval [in] The default value if the string cannot be determined. * @return 0 for FALSE, or 1 for TRUE. * * - The following string values are treated as TRUE: true, 1, y, yes, enabled, enable. * - The following string values are treated as FALSE: false, 0, n, no, disabled, disable. */ int ga_conf_boolval(const char *ptr, int defval) { if(strcasecmp(ptr, "true") == 0 || strcasecmp(ptr, "1") ==0 || strcasecmp(ptr, "y") ==0 || strcasecmp(ptr, "yes") == 0 || strcasecmp(ptr, "enabled") == 0 || strcasecmp(ptr, "enable") == 0) return 1; if(strcasecmp(ptr, "false") == 0 || strcasecmp(ptr, "0") ==0 || strcasecmp(ptr, "n") ==0 || strcasecmp(ptr, "no") == 0 || strcasecmp(ptr, "disabled") == 0 || strcasecmp(ptr, "disable") == 0) return 0; return defval; } /** * Load the value of a parameter as boolean. * * @param ptr [in] The parameter to be loaded. * @param defval [in] The returned value if the parameter * is not defined in the configuration file. * @return 0 for FALSE, or 1 for TRUE. * * See the definitions defined in \em ga_conf_boolval function: * - The following string values are treated as TRUE: true, 1, y, yes, enabled, enable. * - The following string values are treated as FALSE: false, 0, n, no, disabled, disable. */ int ga_conf_readbool(const char *key, int defval) { char buf[64]; char *ptr = ga_conf_readv(key, buf, sizeof(buf)); if(ptr == NULL) return defval; return ga_conf_boolval(ptr, defval); } /** * Add a parameter value into system runtime configuration. * * @param key [in] The parameter name. * @param value [in] The parameter value. * * Note again, this function DOES NOT MODIFY the configuration file. * It only adds/changes the parameters in the runtime configuration. */ int ga_conf_writev(const char *key, const char *value) { ga_vars[key] = value; return 0; } /** * Delete a parameter value from system runtime configuration. * * @param key [in] The parameter to be deleted. * * Note again, this function DOES NOT MODIFY the configuration file. * It only deletes the parameters in the runtime configuration. */ void ga_conf_erase(const char *key) { ga_vars.erase(key); return; } /** * Test if a given parameter is defined as a 'parameter map'. * * @param key [in] The parameter to be tested. * @return 1 if the parameter is defined as a map, or 0 if not. * * A 'parameter map' is defined like: param[key] = value.\n * in the configuration file. */ int ga_conf_ismap(const char *key) { return ga_conf_mapsize(key) > 0 ? 1 : 0; } /** * Determine if a 'parameter map' contains a given \a key. * * @param mapname [in] The name of the parameter map. * @param key [in] The key to be tested. * @return 0 if the key is not found, or non-zero if found. */ int ga_conf_haskey(const char *mapname, const char *key) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return 0; return mi->second.haskey(key); } /** * Get the number of keys defined in a parameter map * * @param mapname [in] The name of the parameter map. * @return The number of keys defined in the parameter map. */ int ga_conf_mapsize(const char *mapname) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return 0; return mi->second.msize(); } /** * Read a string value from a key of a parameter map. * * @param mapname [in] The name of the parameter map. * @param key [in] The key to be retrieved. * @param store [out] Buffer to store the loaded value. * @param slen [in] Length of buffers pointed by \a store. * @return Pointer to the loaded value on success, or NULL on error. * * Note that if \a store is NULL, this function automatically allocates * spaces to store the result. You may need to release the memory by * calling \em free(). */ char * ga_conf_mapreadv(const char *mapname, const char *key, char *store, int slen) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return NULL; if((mi->second)[key] == "") return NULL; if(store == NULL) return strdup((mi->second)[key].c_str()); strncpy(store, (mi->second)[key].c_str(), slen); return store; } /** * Read an integer value from a key of a parameter map. * * @param mapname [in] The name of the parameter map. * @param key [in] The key to be retrieved. * @return The loaded integer value. * * Note that when the given key is not defined, * this function returns zero. */ int ga_conf_mapreadint(const char *mapname, const char *key) { char buf[64]; char *ptr = ga_conf_mapreadv(mapname, key, buf, sizeof(buf)); if(ptr == NULL) return 0; return strtol(ptr, NULL, 0); } /** * Read multiple integer values from a key of a parameter map. * * @param mapname [in] The name of the parameter map. * @param key [in] The key to be retrieved. * @param val [out] The array used to store loaded integers. * @param n [in] The expected number of integers to be loaded. * @return The exact number of integers loaded into \a val. * This number can be less than or equal to \a n. * * This function attempts to loads \a n numbers from * the key of the parameter map and store the loaded number in * \a val in the order. * * A sample configuration line is: param[key] = 1 2 3. */ int ga_conf_mapreadints(const char *mapname, const char *key, int *val, int n) { char buf[1024]; char *ptr = ga_conf_mapreadv(mapname, key, buf, sizeof(buf)); if(ptr == NULL) return 0; return ga_conf_multiple_int(buf, val, n); } /** * Read a double float value from a key of a parameter map. * * @param mapname [in] The name of the parameter map. * @param key [in] The key to be retrieved. * @return The loaded double float value. * * Note that when the given key is not defined, * this function returns 0.0. */ double ga_conf_mapreaddouble(const char *mapname, const char *key) { char buf[64]; char *ptr = ga_conf_mapreadv(mapname, key, buf, sizeof(buf)); if(ptr == NULL) return 0.0; return strtod(ptr, NULL); } /** * Read a boolean value from a key of a parameter map. * * @param mapname [in] The name of the parameter map. * @param key [in] The key to be retrieved. * @param defval [in] The returned default value if \a key is not defined. * @return 0 for FALSE, or 1 for TRUE. * * See the definitions defined in \em ga_conf_boolval function: * - The following string values are treated as TRUE: true, 1, y, yes, enabled, enable. * - The following string values are treated as FALSE: false, 0, n, no, disabled, disable. */ int ga_conf_mapreadbool(const char *mapname, const char *key, int defval) { char buf[64]; char *ptr = ga_conf_mapreadv(mapname, key, buf, sizeof(buf)); if(ptr == NULL) return defval; return ga_conf_boolval(ptr, defval); } /** * Add a parameter map key's value into system runtime configuration. * * @param mapname [in] The parameter map name. * @param key [in] The key name. * @param value [in] The parameter value. * @return This function always returns zero. * * Note again, this function DOES NOT MODIFY the configuration file. * It only adds/changes the parameters in the runtime configuration. */ int ga_conf_mapwritev(const char *mapname, const char *key, const char *value) { ga_vars[mapname][key] = value; return 0; } /** * Delete a parameter map key's value into system runtime configuration. * * @param mapname [in] The parameter map name. * @param key [in] The key name. * * Note again, this function DOES NOT MODIFY the configuration file. * It only deletes the parameters in the runtime configuration. */ void ga_conf_maperase(const char *mapname, const char *key) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return; ga_vars.erase(mi); return; } /** * Reset the iteration pointer of a parameter map. * * @param mapname [in] The name of the parameter map. * * This function is usually called before you attempt to enumerate * key/values in a parameter map. */ void ga_conf_mapreset(const char *mapname) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return; mi->second.mreset(); return; } /** * Get the current key from a parameter map. * * @param mapname [in] The name of the parameter map. * @param keystore [out] The buffer used to stora the current key. * @param klen [in] The buffer lenfgth of \a keystore. * @return Pointer to the key string, or NULL on error. * * Note that if \a keystore is NULL, this function automatically allocates * spaces to store the key. You may need to release the memory by * calling \em free(). */ char * ga_conf_mapkey(const char *mapname, char *keystore, int klen) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return NULL; if(mi->second.mkey() == "") return NULL; if(keystore == NULL) return strdup(mi->second.mkey().c_str()); strncpy(keystore, mi->second.mkey().c_str(), klen); return keystore; } /** * Get the current value from a parameter map. * * @param mapname [in] The name of the parameter map. * @param valstore [out] The buffer used to stora the current key. * @param vlen [in] The buffer lenfgth of \a valstore. * @return Pointer to the value string, or NULL on error. * * Note that if \a valstore is NULL, this function automatically allocates * spaces to store the key. You may need to release the memory by * calling \em free(). */ char * ga_conf_mapvalue(const char *mapname, char *valstore, int vlen) { map<string,gaConfVar>::iterator mi; if((mi = ga_vars.find(mapname)) == ga_vars.end()) return NULL; if(mi->second.mkey() == "") return NULL; if(valstore == NULL) return strdup(mi->second.mvalue().c_str()); strncpy(valstore, mi->second.mvalue().c_str(), vlen); return valstore; } /** * Advance the iteration pointer of a parameter map and get its key value. * * @param mapname [in] The name of the parameter map. * @param keystore [out] The buffer used to stora the next key. * @param klen [in] The buffer lenfgth of \a keystore. * * This function is uaually called during an enumeration process. * Note that if \a keystore is NULL, this function automatically allocates * spaces to store the key. You may need to release the memory by * calling \em free(). */ char * ga_conf_mapnextkey(const char *mapname, char *keystore, int klen) { map<string,gaConfVar>::iterator mi; string k = ""; // if((mi = ga_vars.find(mapname)) == ga_vars.end()) return NULL; k = mi->second.mnextkey(); if(k == "") return NULL; if(keystore == NULL) return strdup(k.c_str()); strncpy(keystore, k.c_str(), klen); return keystore; } /** * Reset the global runtime configuration iteration pointer. * * This function is used to enumerate all runtime configurations. */ void ga_conf_reset() { ga_vmi = ga_vars.begin(); } /** * Get the current key of the gloabl runtime configuration. * * @return The current key value. * * This function is used to enumerate all runtime configurations. */ const char *ga_conf_key() { if(ga_vmi == ga_vars.end()) return NULL; return ga_vmi->first.c_str(); } /** * Advance and get the key of the global runtime configuratin. * * @return The next key value, or NULL if it reaches the end. * * This function is used to enumerate all runtime configurations. */ const char *ga_conf_nextkey() { if(ga_vmi == ga_vars.end()) return NULL; // move forward ga_vmi++; // if(ga_vmi == ga_vars.end()) return NULL; return ga_vmi->first.c_str(); }
27.346966
91
0.672729
[ "vector" ]
b1625274b2c22195346ef5475805b1f4af3d1e94
1,506
cpp
C++
solutions/LeetCode/C++/946.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/946.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/946.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission class Solution { public: bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { stack<int> temp; int j = 0; ios::sync_with_stdio(false); cin.tie(nullptr); for(int i = 0; i < pushed.size() ; ++i) { temp.push(pushed[i]); while(!temp.empty() and temp.top() == popped[j]) { temp.pop(); ++j; } } return temp.empty() ; } }; __________________________________________________________________________________________________ sample 9044 kb submission static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { public: bool validateStackSequences(std::vector<int>& pushed, std::vector<int>& popped) { int pu = 0; int po = 0; std::stack<int> s; while (true) { if (!s.empty() && po < popped.size() && s.top() == popped[po]) { s.pop(); ++po; } else if (pu < pushed.size()) { s.push(pushed[pu++]); } else if (po == popped.size()) { return true; } else { return false; } } } }; __________________________________________________________________________________________________
31.375
98
0.557769
[ "vector" ]
b163dcfa410f6224c76e5d2f1d419f25525b2c66
3,260
cpp
C++
examples/distributed-map/index/main.cpp
enozcan/hazelcast-cpp-client
672ea72811d6281329bd84070e798af711d5cbfb
[ "Apache-2.0" ]
null
null
null
examples/distributed-map/index/main.cpp
enozcan/hazelcast-cpp-client
672ea72811d6281329bd84070e798af711d5cbfb
[ "Apache-2.0" ]
null
null
null
examples/distributed-map/index/main.cpp
enozcan/hazelcast-cpp-client
672ea72811d6281329bd84070e798af711d5cbfb
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Created by İhsan Demir on 21/12/15. // #include <hazelcast/client/HazelcastClient.h> #include <hazelcast/client/query/SqlPredicate.h> class Person : public hazelcast::client::serialization::IdentifiedDataSerializable { public: Person() { } Person(const Person &p) : male(p.male), age(p.age) { if (NULL != p.name.get()) { name = std::unique_ptr<std::string>(new std::string(*p.name)); } } Person &operator=(const Person &p) { if (NULL != p.name.get()) { name = std::unique_ptr<std::string>(new std::string(*p.name)); } male = p.male; age = p.age; return *this; } Person(const char *n, bool male, int age) : name(std::unique_ptr<std::string>(new std::string(n))), male(male), age(age) { } int getFactoryId() const { return 1; } int getClassId() const { return 3; } void writeData(hazelcast::client::serialization::ObjectDataOutput &out) const { out.writeUTF(name.get()); out.writeBoolean(male); out.writeInt(age); } void readData(hazelcast::client::serialization::ObjectDataInput &in) { name = in.readUTF(); male = in.readBoolean(); age = in.readInt(); } const std::string *getName() const { return name.get(); } bool isMale() const { return male; } int getAge() const { return age; } private: std::unique_ptr<std::string> name; bool male; int age; }; int main() { hazelcast::client::HazelcastClient hz; hazelcast::client::IMap<std::string, Person> map = hz.getMap<std::string, Person>("personsWithIndex"); map.addIndex("name", true); const int mapSize = 200000; char buf[30]; char name[30]; time_t start = time(NULL); for (int i = 0; i < mapSize; ++i) { hazelcast::util::hz_snprintf(buf, 30, "person-%d", i); hazelcast::util::hz_snprintf(name, 50, "myname-%d", i % 1000); Person p(name, (i % 2 == 0), (i % 100)); map.put(buf, p); } time_t end = time(NULL); std::cout << "Put " << mapSize << " entries into the map in " << end - start << " seconds" << std::endl; start = time(NULL); hazelcast::client::query::SqlPredicate predicate("name == 'myname-30'"); std::vector<std::pair<std::string, Person> > entries = map.entrySet(predicate); end = time(NULL); std::cout << "The query resulted in " << entries.size() << " entries in " << end - start << " seconds" << std::endl; std::cout << "Finished" << std::endl; return 0; }
28.347826
120
0.600613
[ "vector" ]
b16d3f4841a571266e36b4c48bc9a946b406cec7
1,067
cxx
C++
dreco-engine/src/game_objects/game_world.cxx
GloryOfNight/dreco-engine
1d29b747dc9277cbc5952b31833403a65a4d9c71
[ "MIT" ]
1
2020-02-27T13:29:15.000Z
2020-02-27T13:29:15.000Z
dreco-engine/src/game_objects/game_world.cxx
GloryOfNight/dreco-engine
1d29b747dc9277cbc5952b31833403a65a4d9c71
[ "MIT" ]
null
null
null
dreco-engine/src/game_objects/game_world.cxx
GloryOfNight/dreco-engine
1d29b747dc9277cbc5952b31833403a65a4d9c71
[ "MIT" ]
null
null
null
#include "game_world.hxx" #include "game_object.hxx" #include "camera_base.hxx" using namespace dreco; game_world::game_world(game_base* _gi) : gi_owner(_gi) { player_camera = new camera_base(this); RegisterObject("camera", *player_camera); } game_world::~game_world() { for (auto obj : world_objects) { delete obj.second; } } void game_world::Tick(const float& DeltaTime) { for (auto object : world_objects) { if (!object.second->GetIsBegined()) { object.second->Begin(); } object.second->Tick(DeltaTime); } } game_base* game_world::GetGameInstance() const { return gi_owner; } game_object* game_world::GetObject(const char* _name) const { return world_objects.at(_name); } camera_base* game_world::GetPlayerCamera() const { return player_camera; } const world_objects_map& game_world::GetWorldObjectsRef() const { return world_objects; } void game_world::RegisterObject(const char* _name, game_object& _obj) { world_objects.emplace(_name, &_obj); }
18.719298
70
0.679475
[ "object" ]
b17226d444762a593eb152083ee5a1b48b4bda1d
25,276
cpp
C++
groups/bbl/bbldc/bbldc_perioddaterangedaycountadapter.t.cpp
AlisdairM/bde
bc65db208c32513aa545080f57090cc39c608be0
[ "Apache-2.0" ]
1
2022-01-23T11:31:12.000Z
2022-01-23T11:31:12.000Z
groups/bbl/bbldc/bbldc_perioddaterangedaycountadapter.t.cpp
AlisdairM/bde
bc65db208c32513aa545080f57090cc39c608be0
[ "Apache-2.0" ]
null
null
null
groups/bbl/bbldc/bbldc_perioddaterangedaycountadapter.t.cpp
AlisdairM/bde
bc65db208c32513aa545080f57090cc39c608be0
[ "Apache-2.0" ]
null
null
null
// bbldc_perioddaterangedaycountadapter.t.cpp -*-C++-*- #include <bbldc_perioddaterangedaycountadapter.h> #include <bbldc_periodicmaactualactual.h> #include <bdlt_date.h> #include <bslim_testutil.h> #include <bslma_default.h> #include <bslma_testallocator.h> #include <bsls_assert.h> #include <bsls_asserttest.h> #include <bsl_cstdlib.h> // 'atoi' #include <bsl_iostream.h> using namespace BloombergLP; using namespace bsl; // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The component under test consists of two forwarding methods that forward to // static member function implementations within the template parameter class // that compute the day count and year fraction between two dates and two // methods to complete the protocol implementation. The general plan is that // the methods are tested with two different template parameters to ensure the // forwarding methods forward correctly and the other methods return the // expected value. // ---------------------------------------------------------------------------- // [ 1] PeriodDateRangeDayCountAdapter(pD, pYD, bA); // [ 1] ~PeriodDateRangeDayCountAdapter(); // [ 1] int daysDiff(beginDate, endDate) const; // [ 1] const bdlt::Date& firstDate() const; // [ 1] const bdlt::Date& lastDate() const; // [ 1] double yearsDiff(beginDate, endDate) const; // [ 1] bslma::Allocator *allocator() const; // ---------------------------------------------------------------------------- // [ 2] USAGE EXAMPLE // ---------------------------------------------------------------------------- // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; bool verbose = argc > 2; bool veryVerbose = argc > 3; cout << "TEST " << __FILE__ << " CASE " << test << endl; // CONCERN: 'BSLS_REVIEW' failures should lead to test failures. bsls::ReviewFailureHandlerGuard reviewGuard(&bsls::Review::failByAbort); // CONCERN: In no case does memory come from the global allocator. bslma::TestAllocator globalAllocator("global", veryVerbose); bslma::Default::setGlobalAllocator(&globalAllocator); bslma::TestAllocator defaultAllocator("default", veryVerbose); ASSERT(0 == bslma::Default::setDefaultAllocator(&defaultAllocator)); switch (test) { case 0: case 2: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from component header file. // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << endl << "USAGE EXAMPLE" << endl << "=============" << endl; ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Adapting 'bbldc::PeriodIcmaActualActual' ///- - - - - - - - - - - - - - - - - - - - - - - - - - // This example shows the procedure for using // 'bbldc::PeriodDateRangeDayCountAdapter' to adapt the // 'bbldc::PeriodIcmaActualActual' day-count convention to the // 'bbldc::DateRangeDayCount' protocol, and then the use of the day-count // methods. First, we create a schedule of period dates, 'sched', // corresponding to a quarterly payment ('periodYearDiff == 0.25'): //.. bsl::vector<bdlt::Date> sched; sched.push_back(bdlt::Date(2003, 10, 1)); sched.push_back(bdlt::Date(2004, 1, 1)); //.. // Then, we define an instance of the adapted day-count convention and obtain a // reference to the 'bbldc::DateRangeDayCount': //.. const bbldc::PeriodDateRangeDayCountAdapter<bbldc::PeriodIcmaActualActual> myDcc(sched, 0.25); const bbldc::DateRangeDayCount& dcc = myDcc; //.. // Next, create two 'bdlt::Date' variables, 'd1' and 'd2', with which to use // the day-count convention methods: //.. const bdlt::Date d1(2003, 10, 19); const bdlt::Date d2(2003, 12, 31); //.. // Now, use the base-class reference to compute the day count between the two // dates: //.. const int daysDiff = dcc.daysDiff(d1, d2); ASSERT(73 == daysDiff); //.. // Finally, use the base-class reference to compute the year fraction between // the two dates: //.. const double yearsDiff = dcc.yearsDiff(d1, d2); // Need fuzzy comparison since 'yearsDiff' is a 'double'. ASSERT(yearsDiff > 0.1983 && yearsDiff < 0.1985); //.. } break; case 1: { // -------------------------------------------------------------------- // INHERITANCE MECHANISM // Verify the inheritance mechanism works as expected. // // Concerns: //: 1 The adaptation of a day-count convention class compiles and links //: (all virtual functions are defined). //: //: 2 The functions are in fact virtual and accessible from the //: 'bbldc::DateRangeDayCount' base class. //: //: 3 The values bound at construction are correctly forwarded to the //: methods. //: //: 4 The destructor works as expected. //: //: 5 The constructor has the internal memory management system hooked //: up properly so that *all* internally allocated memory draws from //: the same user-supplied allocator whenever one is specified and //: the 'allocator' accessor return value is as expected. //: //: 6 QoI: Asserted precondition violations are detected when enabled. // // Plan: //: 1 Construct an adapted object of a class (which is derived from //: 'bbldc::DateRangeDayCount') and bind a 'bbldc::DateRangeDayCount' //: reference to the object. Using the base class reference, invoke //: the 'daysDiff', 'firstDate', 'lastDate', and 'yearsDiff' methods. //: Verify that the correct implementations of the methods are called. //: (C-1..3) //: //: 2 The destructor is empty so the concern is trivially satisfied. //: (C-4) //: //: 3 Create an object using the constructor with and without passing //: in an allocator and verify the allocator is stored using the //: 'allocator' accessor. //: //: 4 Verify defensive checks are triggered for invalid values. (C-6) // // Testing: // PeriodDateRangeDayCountAdapter(pD, pYD, bA); // ~PeriodDateRangeDayCountAdapter(); // int daysDiff(beginDate, endDate) const; // const bdlt::Date& firstDate() const; // const bdlt::Date& lastDate() const; // double yearsDiff(beginDate, endDate) const; // bslma::Allocator *allocator() const; // -------------------------------------------------------------------- if (verbose) cout << endl << "INHERITANCE MECHANISM" << endl << "=====================" << endl; bsl::vector<bdlt::Date> mSchedule; const bsl::vector<bdlt::Date>& SCHEDULE = mSchedule; { for (unsigned year = 1990; year <= 2006; ++year) { mSchedule.push_back(bdlt::Date(year, 1, 1)); } } const std::vector<bdlt::Date> SCHEDULE_STD(SCHEDULE.begin(), SCHEDULE.end()); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR const std::pmr::vector<bdlt::Date> SCHEDULE_PMR(SCHEDULE.begin(), SCHEDULE.end()); #endif bdlt::Date DATE1(1992, 2, 1); bdlt::Date DATE2(1993, 3, 1); bdlt::Date DATE3(1993, 2, 1); bdlt::Date DATE4(1996, 2, 1); if (verbose) cout << "\nTesting 'daysDiff'" << endl; { { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT( 394 == protocol.daysDiff(DATE1, DATE2)); ASSERT(1095 == protocol.daysDiff(DATE3, DATE4)); } { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_STD, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT( 394 == protocol.daysDiff(DATE1, DATE2)); ASSERT(1095 == protocol.daysDiff(DATE3, DATE4)); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_PMR, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT( 394 == protocol.daysDiff(DATE1, DATE2)); ASSERT(1095 == protocol.daysDiff(DATE3, DATE4)); } #endif } if (verbose) cout << "\nTesting 'firstDate' and 'lastDate'" << endl; { { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT(SCHEDULE.front() == protocol.firstDate()); ASSERT(SCHEDULE.back() == protocol.lastDate()); } { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_STD, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT(SCHEDULE.front() == protocol.firstDate()); ASSERT(SCHEDULE.back() == protocol.lastDate()); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_PMR, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT(SCHEDULE.front() == protocol.firstDate()); ASSERT(SCHEDULE.back() == protocol.lastDate()); } #endif } if (verbose) cout << "\nTesting 'yearsDiff'" << endl; { { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE, 1.0); const bbldc::DateRangeDayCount& protocol = mX; double diff1 = 1.0769 - protocol.yearsDiff(DATE1, DATE2); ASSERT(-0.00005 <= diff1 && diff1 <= 0.00005); double diff2 = 2.9998 - protocol.yearsDiff(DATE3, DATE4); ASSERT(-0.00005 <= diff2 && diff2 <= 0.00005); } { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_STD, 1.0); const bbldc::DateRangeDayCount& protocol = mX; double diff1 = 1.0769 - protocol.yearsDiff(DATE1, DATE2); ASSERT(-0.00005 <= diff1 && diff1 <= 0.00005); double diff2 = 2.9998 - protocol.yearsDiff(DATE3, DATE4); ASSERT(-0.00005 <= diff2 && diff2 <= 0.00005); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_PMR, 1.0); const bbldc::DateRangeDayCount& protocol = mX; double diff1 = 1.0769 - protocol.yearsDiff(DATE1, DATE2); ASSERT(-0.00005 <= diff1 && diff1 <= 0.00005); double diff2 = 2.9998 - protocol.yearsDiff(DATE3, DATE4); ASSERT(-0.00005 <= diff2 && diff2 <= 0.00005); } #endif } if (verbose) cout << "\nTesting 'allocator'" << endl; { { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE, 1.0); const bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>& X = mX; ASSERT(&defaultAllocator == X.allocator()); } { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_STD, 1.0); const bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>& X = mX; ASSERT(&defaultAllocator == X.allocator()); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR { bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_PMR, 1.0); const bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>& X = mX; ASSERT(&defaultAllocator == X.allocator()); } #endif { bslma::TestAllocator sa("supplied", veryVerbose); bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE, 1.0, &sa); const bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>& X = mX; ASSERT(&sa == X.allocator()); } { bslma::TestAllocator sa("supplied", veryVerbose); bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_STD, 1.0, &sa); const bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>& X = mX; ASSERT(&sa == X.allocator()); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR { bslma::TestAllocator sa("supplied", veryVerbose); bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(SCHEDULE_PMR, 1.0, &sa); const bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>& X = mX; ASSERT(&sa == X.allocator()); } #endif } { // negative testing bsls::AssertTestHandlerGuard hG; typedef std::vector<bdlt::Date> StdVector; #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR typedef std::pmr::vector<bdlt::Date> PmrVector; #endif // 'periodDate' with no errors bsl::vector<bdlt::Date> mA; const bsl::vector<bdlt::Date>& A = mA; { mA.push_back(bdlt::Date(2015, 1, 5)); mA.push_back(bdlt::Date(2015, 2, 5)); mA.push_back(bdlt::Date(2015, 3, 5)); mA.push_back(bdlt::Date(2015, 4, 5)); mA.push_back(bdlt::Date(2015, 5, 5)); } const StdVector AS(A.begin(), A.end()); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR const PmrVector AP(A.begin(), A.end()); #endif // 'periodDate' with non-sorted values bsl::vector<bdlt::Date> mE1; const bsl::vector<bdlt::Date>& E1 = mE1; (void)E1; { mE1.push_back(bdlt::Date(2015, 1, 5)); mE1.push_back(bdlt::Date(2015, 3, 5)); mE1.push_back(bdlt::Date(2015, 2, 5)); mE1.push_back(bdlt::Date(2015, 4, 5)); mE1.push_back(bdlt::Date(2015, 5, 5)); } const StdVector E1S(E1.begin(), E1.end()); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR const PmrVector E1P(E1.begin(), E1.end()); #endif // 'periodDate' with non-unique values bsl::vector<bdlt::Date> mE2; const bsl::vector<bdlt::Date>& E2 = mE2; (void)E2; { mE2.push_back(bdlt::Date(2015, 1, 5)); mE2.push_back(bdlt::Date(2015, 2, 5)); mE2.push_back(bdlt::Date(2015, 3, 5)); mE2.push_back(bdlt::Date(2015, 3, 5)); mE2.push_back(bdlt::Date(2015, 4, 5)); mE2.push_back(bdlt::Date(2015, 5, 5)); } const StdVector E2S(E2.begin(), E2.end()); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR const PmrVector E2P(E2.begin(), E2.end()); #endif // 'periodDate' with only one value bsl::vector<bdlt::Date> mE3; const bsl::vector<bdlt::Date>& E3 = mE3; (void)E3; { mE3.push_back(bdlt::Date(2015, 1, 5)); } const StdVector E3S(E3.begin(), E3.end()); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR const PmrVector E3P(E3.begin(), E3.end()); #endif // 'periodDate' with no values bsl::vector<bdlt::Date> mE4; const bsl::vector<bdlt::Date>& E4 = mE4; (void)E4; const StdVector E4S; #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR const PmrVector E4P; #endif ASSERT_PASS(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(A, 1.0)); ASSERT_PASS(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(AS, 1.0)); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR ASSERT_PASS(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(AP, 1.0)); #endif ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E1, 1.0)); ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E1S, 1.0)); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E1P, 1.0)); #endif ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E2, 1.0)); ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E2S, 1.0)); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E2P, 1.0)); #endif ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E3, 1.0)); ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E3S, 1.0)); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E3P, 1.0)); #endif ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E4, 1.0)); ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E4S, 1.0)); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR ASSERT_SAFE_FAIL(bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual>(E4P, 1.0)); #endif // verify out of range bsl::vector<bdlt::Date> mL; const bsl::vector<bdlt::Date>& L = mL; { mL.push_back(bdlt::Date(1750, 1, 5)); mL.push_back(bdlt::Date(1760, 2, 5)); } bbldc::PeriodDateRangeDayCountAdapter< bbldc::PeriodIcmaActualActual> mX(L, 1.0); const bbldc::DateRangeDayCount& protocol = mX; ASSERT_SAFE_PASS(protocol.yearsDiff(bdlt::Date(1751, 1, 1), bdlt::Date(1753, 1, 1))); ASSERT_SAFE_FAIL(protocol.yearsDiff(bdlt::Date(1740, 1, 1), bdlt::Date(1753, 1, 1))); ASSERT_SAFE_FAIL(protocol.yearsDiff(bdlt::Date(1753, 1, 1), bdlt::Date(1740, 1, 1))); ASSERT_SAFE_FAIL(protocol.yearsDiff(bdlt::Date(1753, 1, 1), bdlt::Date(1780, 1, 1))); ASSERT_SAFE_FAIL(protocol.yearsDiff(bdlt::Date(1780, 1, 1), bdlt::Date(1753, 1, 1))); } } break; default: { cerr << "WARNING: CASE `" << test << "' NOT == FOUND." << endl; testStatus = -1; } } // CONCERN: In no case does memory come from the global allocator. LOOP_ASSERT(globalAllocator.numBlocksTotal(), 0 == globalAllocator.numBlocksTotal()); if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
39.93049
79
0.528565
[ "object", "vector" ]
b178180ca65f8ac5c7894e14609957ecdfca9cc7
4,011
cpp
C++
Code/Framework/AzToolsFramework/AzToolsFramework/Debug/TraceContextLogFormatter.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Framework/AzToolsFramework/AzToolsFramework/Debug/TraceContextLogFormatter.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Framework/AzToolsFramework/AzToolsFramework/Debug/TraceContextLogFormatter.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzToolsFramework/Debug/TraceContext.h> #include <AzToolsFramework/Debug/TraceContextLogFormatter.h> #ifdef AZ_ENABLE_TRACE_CONTEXT #include <AzToolsFramework/Debug/TraceContextStackInterface.h> #endif // AZ_ENABLE_TRACE_CONTEXT #include <cinttypes> namespace AzToolsFramework { namespace Debug { #ifdef AZ_ENABLE_TRACE_CONTEXT void TraceContextLogFormatter::Print(AZStd::string& out, const TraceContextStackInterface& stack, bool printUuids) { size_t stackSize = stack.GetStackCount(); for (size_t i = 0; i < stackSize; ++i) { if (!printUuids && stack.GetType(i) == TraceContextStackInterface::ContentType::UuidType) { continue; } PrintLine(out, stack, i); out += '\n'; } } void TraceContextLogFormatter::PrintLine(AZStd::string& out, const TraceContextStackInterface& stack, size_t index) { // Don't assert on this as it could cause an infinite loop of asserts that trigger trace context reporting. if (index >= stack.GetStackCount()) { return; } out += AZStd::string::format("[%s] = ", stack.GetKey(index)); PrintValue(out, stack, index); } void TraceContextLogFormatter::PrintValue(AZStd::string& out, const TraceContextStackInterface& stack, size_t index) { // Don't assert on this as it could cause an infinite loop of asserts that trigger trace context reporting. if (index >= stack.GetStackCount()) { return; } switch (stack.GetType(index)) { case TraceContextStackInterface::ContentType::StringType: out += stack.GetStringValue(index); break; case TraceContextStackInterface::ContentType::BoolType: out += stack.GetBoolValue(index) ? "true" : "false"; break; case TraceContextStackInterface::ContentType::IntType: out += AZStd::string::format("%" PRId64, stack.GetIntValue(index)); break; case TraceContextStackInterface::ContentType::UintType: out += AZStd::string::format("%" PRIu64, stack.GetUIntValue(index)); break; case TraceContextStackInterface::ContentType::FloatType: out += AZStd::string::format("%f", stack.GetFloatValue(index)); break; case TraceContextStackInterface::ContentType::DoubleType: out += AZStd::string::format("%f", stack.GetDoubleValue(index)); break; case TraceContextStackInterface::ContentType::UuidType: out += stack.GetUuidValue(index).ToString<AZStd::string>(false).c_str(); break; case TraceContextStackInterface::ContentType::Undefined: out += "<undefined value type>"; break; default: out += "<unknown value type>"; break; } } #else // AZ_ENABLE_TRACE_CONTEXT void TraceContextLogFormatter::Print(AZStd::string& /*out*/, const TraceContextStackInterface& /*stack*/, bool /*printUuids*/) { } void TraceContextLogFormatter::PrintLine(AZStd::string& /*out*/, const TraceContextStackInterface& /*stack*/, size_t /*index*/) { } void TraceContextLogFormatter::PrintValue(AZStd::string& /*out*/, const TraceContextStackInterface& /*stack*/, size_t /*index*/) { } #endif // AZ_ENABLE_TRACE_CONTEXT } // Debug } // AzToolsFramework
36.463636
136
0.591124
[ "3d" ]
b178e3b5ae9a38a103ce7bf608408a34371847a4
9,629
cpp
C++
Source/modules/webcl/WebCLKernelArgInfoProvider.cpp
crosswalk-project/blink-crosswalk
16d1b69626699e9ca703e0c24c829e96d07fcd3e
[ "BSD-3-Clause" ]
18
2015-04-16T09:57:11.000Z
2020-12-09T15:58:55.000Z
Source/modules/webcl/WebCLKernelArgInfoProvider.cpp
crosswalk-project/blink-crosswalk
16d1b69626699e9ca703e0c24c829e96d07fcd3e
[ "BSD-3-Clause" ]
58
2015-01-02T14:37:31.000Z
2015-11-30T04:58:51.000Z
Source/modules/webcl/WebCLKernelArgInfoProvider.cpp
crosswalk-project/blink-crosswalk
16d1b69626699e9ca703e0c24c829e96d07fcd3e
[ "BSD-3-Clause" ]
35
2015-01-14T00:10:29.000Z
2022-01-20T10:28:15.000Z
// Copyright (C) 2013 Samsung Electronics Corporation. All rights reserved. // Copyright (C) 2015 Intel Corporation All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #if ENABLE(WEBCL) #include "core/webcl/WebCLException.h" #include "modules/webcl/WebCLKernel.h" #include "modules/webcl/WebCLKernelArgInfoProvider.h" #include "modules/webcl/WebCLProgram.h" namespace blink { const size_t notFound = static_cast<size_t>(-1); static bool isASCIILineBreakCharacter(UChar c) { return c == '\r' || c == '\n'; } inline bool isEmptySpace(UChar c) { return c <= ' ' && (c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\f'); } inline bool isStarCharacter(UChar c) { return c == '*'; } inline bool isPrecededByUnderscores(const String& string, size_t index) { size_t start = index - 2; return (start >= 0 && string[start + 1] == '_' && string[start] == '_'); } WebCLKernelArgInfoProvider::WebCLKernelArgInfoProvider(WebCLKernel* kernel) : m_kernel(kernel) { ASSERT(kernel); ensureInfo(); } void WebCLKernelArgInfoProvider::ensureInfo() { if (m_argumentInfoVector.size()) return; const String& source = m_kernel->program()->sourceWithCommentsStripped(); // 0) find "kernel" string. // 1) Check if it is a valid kernel declaration. // 2) find the first open braces past "kernel". // 3) reverseFind the given kernel name string. // 4) if not found go back to (1) // 5) if found, parse its argument list. size_t kernelNameIndex = 0; size_t kernelDeclarationIndex = 0; for (size_t startIndex = 0; ; startIndex = kernelDeclarationIndex + 6) { kernelDeclarationIndex = source.find("kernel", startIndex); if (kernelDeclarationIndex == notFound) { return; } // Check if "kernel" is not a substring of a valid token, // e.g. "akernel" or "__kernel_": // 1) After "kernel" there has to be an empty space. // 2) Before "kernel" there has to be either: // 2.1) two underscore characters or // 2.2) none, i.e. "kernel" is the first string in the program source or // 2.3) an empty space. if (!isEmptySpace(source[kernelDeclarationIndex + 6])) continue; // If the kernel declaration is not at the beginning of the program. bool hasTwoUnderscores = isPrecededByUnderscores(source, kernelDeclarationIndex); bool isKernelDeclarationAtBeginning = hasTwoUnderscores ? (kernelDeclarationIndex == 2) : (kernelDeclarationIndex == 0); if (!isKernelDeclarationAtBeginning) { size_t firstPrecedingIndex = kernelDeclarationIndex - (hasTwoUnderscores ? 3 : 1); if (!isEmptySpace(source[firstPrecedingIndex])) continue; } size_t openBrace = source.find("{", kernelDeclarationIndex + 6); kernelNameIndex = source.reverseFind(m_kernel->kernelName(), openBrace); if (kernelNameIndex < kernelDeclarationIndex) continue; if (kernelNameIndex != notFound) break; } ASSERT(kernelNameIndex); size_t requiredIndex = source.reverseFind("required_work_group_size", kernelNameIndex); if (requiredIndex != notFound) { size_t requiredOpenBracket = source.find("(", requiredIndex); size_t requiredCloseBracket = source.find(")", requiredOpenBracket); const String& requiredArgumentListStr = source.substring(requiredOpenBracket + 1, requiredCloseBracket - requiredOpenBracket - 1); Vector<String> requiredArgumentStrVector; requiredArgumentListStr.split(",", requiredArgumentStrVector); for (auto requiredArgument : requiredArgumentStrVector) { requiredArgument = requiredArgument.removeCharacters(isASCIILineBreakCharacter); requiredArgument = requiredArgument.stripWhiteSpace(); m_requiredArgumentVector.append(requiredArgument.toUInt()); } } size_t openBracket = source.find("(", kernelNameIndex); size_t closeBracket = source.find(")", openBracket); const String& argumentListStr = source.substring(openBracket + 1, closeBracket - openBracket - 1); Vector<String> argumentStrVector; argumentListStr.split(",", argumentStrVector); for (auto argument : argumentStrVector) { argument = argument.removeCharacters(isASCIILineBreakCharacter); argument = argument.stripWhiteSpace(); parseAndAppendDeclaration(argument); } } static void prependUnsignedIfNeeded(Vector<String>& declarationStrVector, String& type) { for (size_t i = 0; i < declarationStrVector.size(); i++) { static AtomicString& Unsigned = *new AtomicString("unsigned", AtomicString::ConstructFromLiteral); if (declarationStrVector[i] == Unsigned) { type = "u" + type; declarationStrVector.remove(i); return; } } } void WebCLKernelArgInfoProvider::parseAndAppendDeclaration(const String& argumentDeclaration) { // "*" is used to indicate pointer data type, setting isPointerType flag if "*" is present in argumentDeclaration. // Since we parse only valid & buildable OpenCL kernels, * in argumentDeclaration must be associated with type only. bool isPointerType = false; if (argumentDeclaration.contains("*")) isPointerType = true; Vector<String> declarationStrVector; argumentDeclaration.removeCharacters(isStarCharacter).split(" ", declarationStrVector); const String& name = extractName(declarationStrVector); const String& addressQualifier = extractAddressQualifier(declarationStrVector); String type = extractType(declarationStrVector); static AtomicString& image2d_t = *new AtomicString("image2d_t", AtomicString::ConstructFromLiteral); const String& accessQualifier = (type == image2d_t) ? extractAccessQualifier(declarationStrVector) : "none"; prependUnsignedIfNeeded(declarationStrVector, type); m_argumentInfoVector.append(WebCLKernelArgInfo::create(addressQualifier, accessQualifier, type, name, isPointerType)); } String WebCLKernelArgInfoProvider::extractAddressQualifier(Vector<String>& declarationStrVector) { static AtomicString* __Private = new AtomicString("__private", AtomicString::ConstructFromLiteral); static AtomicString* Private = new AtomicString("private", AtomicString::ConstructFromLiteral); static AtomicString* __Global = new AtomicString("__global", AtomicString::ConstructFromLiteral); static AtomicString* Global = new AtomicString("global", AtomicString::ConstructFromLiteral); static AtomicString* __Constant = new AtomicString("__constant", AtomicString::ConstructFromLiteral); static AtomicString* Constant = new AtomicString("constant", AtomicString::ConstructFromLiteral); static AtomicString* __Local = new AtomicString("__local", AtomicString::ConstructFromLiteral); static AtomicString* Local = new AtomicString("local", AtomicString::ConstructFromLiteral); String address = *Private; size_t i = 0; for (; i < declarationStrVector.size(); i++) { const String& candidate = declarationStrVector[i]; if (candidate == *__Private || candidate == *Private) { break; } else if (candidate == *__Global || candidate == *Global) { address = *Global; break; } else if (candidate == *__Constant || candidate == *Constant) { address = *Constant; break; } else if (candidate == *__Local || candidate == *Local) { address = *Local; break; } } if (i < declarationStrVector.size()) declarationStrVector.remove(i); return address; } String WebCLKernelArgInfoProvider::extractAccessQualifier(Vector<String>& declarationStrVector) { static AtomicString* __read_only = new AtomicString("__read_only", AtomicString::ConstructFromLiteral); static AtomicString* read_only = new AtomicString("read_only", AtomicString::ConstructFromLiteral); static AtomicString* __write_only = new AtomicString("__read_only", AtomicString::ConstructFromLiteral); static AtomicString* write_only = new AtomicString("write_only", AtomicString::ConstructFromLiteral); static AtomicString* __read_write = new AtomicString("__read_write", AtomicString::ConstructFromLiteral); static AtomicString* read_write = new AtomicString("read_write", AtomicString::ConstructFromLiteral); String access = *read_only; size_t i = 0; for (; i < declarationStrVector.size(); i++) { const String& candidate = declarationStrVector[i]; if (candidate == *__read_only || candidate == *read_only) { break; } else if (candidate == *__write_only || candidate == *write_only) { access = *write_only; break; } else if (candidate == *__read_write || candidate == *read_write) { access = *read_write; break; } } if (i < declarationStrVector.size()) declarationStrVector.remove(i); return access; } String WebCLKernelArgInfoProvider::extractName(Vector<String>& declarationStrVector) { String last = declarationStrVector.last(); declarationStrVector.removeLast(); return last; } String WebCLKernelArgInfoProvider::extractType(Vector<String>& declarationStrVector) { String type = declarationStrVector.last(); declarationStrVector.removeLast(); return type; } } // namespace blink #endif // ENABLE(WEBCL)
38.983806
138
0.689687
[ "vector" ]
b1799992aa64178a74b0f43fbd9dbc7d5c1a4454
19,681
cpp
C++
src/Battle.cpp
DevelopersGuild/C-RPG
92d33bf5ab14d8c41478d75aa7068f83890a5ea0
[ "MIT" ]
4
2018-04-15T06:01:06.000Z
2022-02-26T02:08:59.000Z
src/Battle.cpp
DevelopersGuild/C-RPG
92d33bf5ab14d8c41478d75aa7068f83890a5ea0
[ "MIT" ]
6
2016-02-02T07:46:03.000Z
2016-06-10T18:41:15.000Z
src/Battle.cpp
DevelopersGuild/C-RPG
92d33bf5ab14d8c41478d75aa7068f83890a5ea0
[ "MIT" ]
5
2016-03-15T01:12:26.000Z
2019-02-28T18:51:14.000Z
#include "Battle.h" #include <fstream> #include <sstream> #include <stdlib.h> #include <time.h> /* The constructor */ Gameplay::BattleCharacter::BattleCharacter() { direction = DIRECTION::right; facing_right = true; status = active; } /* BattleChar(base) loadSprite function Assume the picture is 320 height */ void Gameplay::BattleCharacter::loadSprite(sf::Texture &texture) { //1.find the number of frame. 1 frame is 320 x 320, 2 frame is 640 x 320... sf::Vector2u textureSize = texture.getSize(); int num_frame = textureSize.x / 320; //2.add each frame into the spriteList for(int i = 0; i < num_frame; i++) { spriteList.add(sf::IntRect(i * 320, 0, 320, 320)); } //3.set texture to sprite sprite.setTexture(texture); //4.set the origin of the sprite sprite.setOrigin(160, 160); //5.set the texture at the first frame sprite.setTextureRect(spriteList.getNext()); } /* BattleChar(base) moving function add 0.5 speed only */ void Gameplay::BattleCharacter::move(Gameplay::BattleCharacter::DIRECTION newDirection) { if(direction != newDirection) { sprite.scale(-1, 1); facing_right = !facing_right; } if(direction == DIRECTION::right && !facing_right) { sprite.scale(-1,1); facing_right = !facing_right; } else if(direction == DIRECTION::left && facing_right) { sprite.scale(-1, 1); facing_right = !facing_right; } //if speed is already at max speed, do nothing if(speed < max_speed && speed > -max_speed) { switch(newDirection) { case DIRECTION::right: speed += 0.5; direction = right; break; case DIRECTION::left: speed -= 0.5; direction = left; break; } } } /* BattleChar(base) animation Update function decrease the speed, update sprite.... */ void Gameplay::BattleCharacter::animeUpdate() { if(moveTimer.getElapsedTime() > sf::seconds(0.01)) { //move the character sprite.move(speed, 0); //decrease the speed if(speed > 0) speed -= 0.1; else if(speed < 0) speed += 0.1; moveTimer.restart(); } //if speed is too small, just set it to 0 if(speed < 0.2 && speed > -0.2) speed = 0; //if 0.8s has passed since the last sprite, go to the next sprite if(spriteTimer.getElapsedTime() > sf::seconds(0.4)) { sprite.setTextureRect(spriteList.getNext()); spriteTimer.restart(); } } /* BattleChar(base) draw draw the sprite of character */ void Gameplay::BattleCharacter::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(sprite); } /* BattleChar flyOut move to the right-top corner or left-top corner of the screen and keep rotating! */ void Gameplay::BattleCharacter::flyOut() { if(direction == right) { sprite.move(-10, -16); sprite.rotate(20); } else if(direction == left) { sprite.move(10, -16); sprite.rotate(-20); } } /* BattlePlayer constructor constructor of BattlePlayer class, need a character pointer */ Gameplay::BattlePlayer::BattlePlayer(Character& newCharacter) : character(newCharacter) { speed = 0; max_speed = 4; //TBD type = player; name = newCharacter.getName(); max_speed = newCharacter.getBattleSpeed(); } /* BattlePlayer animeUpdate move the player right */ void Gameplay::BattlePlayer::animeUpdate() { if(status == STATUS::non_active) { this->flyOut(); } BattleCharacter::animeUpdate(); } /* BattlePlayer escapeBattle try to escape (or "be escaped") the battle. Failed if the number of continuous battle escaped is greater than 3. */ bool Gameplay::BattlePlayer::escapeBattle() { if(character.getBattleEscaped() >= 3) { return false; } else { character.incBattleEscaped(); return true; } } /* BattlePlayer leaveBattle leave the battle normally. */ void Gameplay::BattlePlayer::leaveBattle() { //nothing happen... } /* BattlePlayer takeDamage take the damage...if hp is below 0. The player is defeated and flys out the battle. */ void Gameplay::BattlePlayer::takeDamage(int value) { character.setCurrentHp(character.getCurrentHp() - value); if(character.getCurrentHp() <= 0) { status = STATUS::non_active; } } /* BattleMonster constructor default constructor of monster. */ Gameplay::BattleMonster::BattleMonster() { max_speed = 2; max_hp = 20; current_hp = max_hp; atk = 5; def = 5; direction = left; facing_right = false; type = monster; status = active; exp = 1; money = 0; } /* BattleMonster constructor with attributes initiate attributes of monster */ Gameplay::BattleMonster::BattleMonster(float newMaxSpeed, int newAtk, int newDef, int newMaxHP) { max_speed = newMaxSpeed; speed = 0; atk = newAtk; def = newDef; max_hp = newMaxHP; current_hp = max_hp; direction = left; facing_right = false; type = monster; status = active; exp = 1; money = 0; } /* BattleMonster copy constructor copy constructor */ Gameplay::BattleMonster::BattleMonster(const BattleMonster& newMonster) { max_speed = newMonster.max_speed; speed = 0; atk = newMonster.atk; def = newMonster.def; max_hp = newMonster.max_hp; current_hp = newMonster.current_hp; direction = newMonster.direction; facing_right = newMonster.facing_right; type = monster; status = newMonster.status; exp = newMonster.exp; money = newMonster.money; const sf::Texture* texture = newMonster.sprite.getTexture(); sf::Vector2u textureSize = texture->getSize(); int num_frame = textureSize.x / 320; for(int i = 0; i < num_frame; i++) spriteList.add(sf::IntRect(i * 320, 0, 320, 320)); sprite.setTexture(*texture); sprite.setOrigin(160, 160); sprite.setTextureRect(spriteList.getNext()); } /* BattleMonster assign constructor assign constructor */ Gameplay::BattleMonster& Gameplay::BattleMonster::operator=(const BattleMonster& newMonster) { max_speed = newMonster.max_speed; speed = 0; atk = newMonster.atk; def = newMonster.def; max_hp = newMonster.max_hp; current_hp = newMonster.current_hp; direction = newMonster.direction; facing_right = newMonster.facing_right; type = monster; status = newMonster.status; exp = newMonster.exp; money = newMonster.money; const sf::Texture* texture = newMonster.sprite.getTexture(); sf::Vector2u textureSize = texture->getSize(); int num_frame = textureSize.x / 320; for(int i = 0; i < num_frame; i++) spriteList.add(sf::IntRect(i * 320, 0, 320, 320)); sprite.setTexture(*texture); sprite.setOrigin(160, 160); sprite.setTextureRect(spriteList.getNext()); return *this; } /* BattleMonster animeUpdate the monster moves left. */ void Gameplay::BattleMonster::animeUpdate() { if(status == BattleCharacter::STATUS::active) { this->move(left); } else if(status == BattleCharacter::STATUS::non_active) { this->flyOut(); } BattleCharacter::animeUpdate(); } /* BattleMonster takeDamage take Damage. Flys out when hp is below 0. */ void Gameplay::BattleMonster::takeDamage(int value) { current_hp = current_hp - value; if(current_hp <= 0) { status = STATUS::non_active; } } /* Battle constructor constructor of battle */ Gameplay::Battle::Battle(Configuration& newConfig) : config(newConfig), camera(config.window.getDefaultView()) { //the background is as big as the window background.setSize(sf::Vector2f(config.window.getSize())); state = started; } /* Battle setBackGround set the background of the battle */ void Gameplay::Battle::setBackGround(sf::Texture* texture) { background.setTexture(texture); } /* Battle addCharacter add the character to the character Tree, if the playerName is already in the tree, rename the character with additional number. */ void Gameplay::Battle::addCharacter(std::unique_ptr<BattleCharacter> charPtr) { std::string searchStr; for(int i = 0; ; i++) { searchStr = charPtr->getName(); if(i) searchStr += i; //search for the name in the character Tree auto it = characterTree.find(searchStr); //if not found, then add the character to the tree if(it == characterTree.end()) { charPtr->setName(searchStr); characterTree.emplace(searchStr, std::move(charPtr)); return; } } } /* Battle setCharPosition set the position of the character. Since the battle is on x-axis only, so only one value is needed. if the name is not found, do nothing. */ void Gameplay::Battle::setCharPosition(const std::string& charName, int value) { auto it = characterTree.find(charName); if(it != characterTree.end()) it->second->setPosition(sf::Vector2f(value, 500)); else std::cout << "Error: char not found." << std::endl; return; } /* Battle moveCharacter move the character in certain direction if the name is not found, do nothing. */ void Gameplay::Battle::moveCharacter(const std::string &charName, BattleCharacter::DIRECTION direction) { auto it = characterTree.find(charName); if(it->second->getStatus() == BattleCharacter::STATUS::active) it->second->move(direction); } /* Battle damage number constructor set the text with font and number. */ Gameplay::BattleDamage::BattleDamage(const sf::Font& font, const std::string& str) { text.setFont(font); text.setString(str); text.setCharacterSize(32); done = false; } /* Battle damage number update update the position of the number(flys up) after 0.3s, set the boolean done to true. */ void Gameplay::BattleDamage::update() { if(clock.getElapsedTime() < sf::seconds(0.8f)) { if(updateClock.getElapsedTime() > sf::seconds(0.015f)) { text.move(0,-2); updateClock.restart(); } } else { done = true; } } /* Battle damage number draw draw the number on screen */ void Gameplay::BattleDamage::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(text); } /* Battle draw draw the battle in window */ void Gameplay::Battle::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(background); for(auto& pair : characterTree) { target.draw(*pair.second); } for(const std::unique_ptr<BattleDamage>& obj : damageRenderList) { target.draw(*obj); } } /* Battle update perform animation update and collision test(thus dealing damage) for battle. Must called in every frame. */ void Gameplay::Battle::update() { //do nothing if battle is already over if (state == overed) return; for(auto& pair : characterTree) { pair.second->animeUpdate(); _hitWallTest(pair.second); } _collisionTest(); //update the drawList for(auto it = damageRenderList.begin(); it != damageRenderList.end(); it++) { if((*it)->isDone()) { damageRenderList.erase(it); if (damageRenderList.empty()) break; else it = damageRenderList.begin(); } } for(auto it = damageRenderList.begin(); it != damageRenderList.end(); it++) { (*it)->update(); } } /* Battle hitWallTest check if the character hits the edge of the battle. */ void Gameplay::Battle::_hitWallTest(std::unique_ptr<BattleCharacter>& character) { //if the target is hitting the invisible wall.... //right wall if(character->getPosition().x >= background.getSize().x) { //if it is active monster, stop the monster if(character->getType() == BattleCharacter::TYPE::monster && character->getStatus() == BattleCharacter::STATUS::active) character->setPosition(sf::Vector2f(background.getSize().x, 500)); //if it is player, the player leaves the battle if(character->getType() == BattleCharacter::TYPE::player) { character->resetEscapeBattle(); character->leaveBattle(); this->state = STATE::overed; } } else if(character->getPosition().x <= 0)//left wall { //if it is player and the player has not won the battle yet, escape the battle if it is the first 3 times if(character->getType() == BattleCharacter::TYPE::player) { if (haswon()) { character->resetEscapeBattle(); this->state = STATE::overed; } else if(character->getStatus() == BattleCharacter::STATUS::non_active) { //if the player has lost the battle... this->state = STATE::overed;//TBD } else if( character->escapeBattle()) { this->state = STATE::overed; } else { character->setPosition(sf::Vector2f(1, 500)); //stop the player } } //the monster reaches the left wall?... } } /* Battle collisionTest test if any two character intersect in the battle and then call deal damage function. */ void Gameplay::Battle::_collisionTest() { for(auto& pair : characterTree) { if(pair.second->getStatus() == BattleCharacter::STATUS::active && pair.second->getType() == BattleCharacter::TYPE::player) { for(auto& otherPair : characterTree) { if(otherPair.second->getStatus() == BattleCharacter::STATUS::active && otherPair.second->getType() == BattleCharacter::TYPE::monster && pair.first != otherPair.first && pair.second->getAABB().intersects(otherPair.second->getAABB())) { _dealDamage(pair.second, otherPair.second); return; } } } } } /* Battle dealDamage determine the damage taken. Put the damage number to the rendering list, and set the speed of player and monster */ void Gameplay::Battle::_dealDamage(std::unique_ptr<BattleCharacter>& player, std::unique_ptr<BattleCharacter>& monster) { //calculate damage int damage_playerToMonster = player->getAtk() - monster->getDef(); int damage_monsterToPlayer = monster->getAtk() - player->getDef(); //set the damage to 1 if the damage is 0 or negative if(damage_playerToMonster <= 0) damage_playerToMonster = 1; if(damage_monsterToPlayer <= 0) damage_monsterToPlayer = 1; //calculate ratio float damage_ratio = (static_cast<float>(damage_monsterToPlayer) / damage_playerToMonster); //if damage_ratio is greater than 1.2, set it as 1.2 if(damage_ratio >= 1.2f) damage_ratio = 1.2f; //if damage_ratio is less than 0.8 set it as 0.8 if(damage_ratio <= 0.8f) damage_ratio = 0.8f; //characters take damage player->takeDamage(damage_monsterToPlayer); monster->takeDamage(damage_playerToMonster); //player may gain exp and money if the monster is defeated if(monster->getStatus() == BattleCharacter::STATUS::non_active) { player->setExp(monster->getExp()); std::unique_ptr<BattleDamage> expgain(new BattleDamage(config.fontMan.get("PressStart2P.ttf"), "exp +" + std::to_string(monster->getExp()))); expgain->setTextColor(sf::Color::Yellow); expgain->setPosition(player->getPosition() - sf::Vector2f(0, 170)); damageRenderList.push_back(std::move(expgain)); int newMoney = player->getMoney() + monster->getMoney(); player->setMoney(newMoney); } //put the damage number to render list std::unique_ptr<BattleDamage> playerDamageToken(new BattleDamage(config.fontMan.get("PressStart2P.ttf"), std::to_string(damage_monsterToPlayer))); playerDamageToken->setPosition(player->getPosition() - sf::Vector2f(0, 170)); playerDamageToken->setTextColor(sf::Color::Red); std::unique_ptr<BattleDamage> monsterDamageToken(new BattleDamage(config.fontMan.get("PressStart2P.ttf"), std::to_string(damage_playerToMonster))); monsterDamageToken->setPosition(monster->getPosition() - sf::Vector2f(0, 170)); monsterDamageToken->setTextColor(sf::Color::Black); damageRenderList.push_back(std::move(playerDamageToken)); damageRenderList.push_back(std::move(monsterDamageToken)); //generate two random numbers between 0 to 2 int r1 = rand() % 4; int r2 = rand() % 4; //set the speed player->setSpeed((-4 * damage_ratio) - r1); monster->setSpeed((4 * (1.f / damage_ratio)) + r2); //player sound sf::Sound& sound = config.soundMan.get("Blow1.ogg"); sound.play(); } /* Battle haswon has the player won the battle?(i.e. no monster are active) */ bool Gameplay::Battle::haswon() { for (auto& pair : characterTree) { if (pair.second->getType() == BattleCharacter::TYPE::monster && pair.second->getStatus() == BattleCharacter::STATUS::active) return false; } return true; } /* BattleFactory constructor load all monster's name and their data into the tree. */ Gameplay::BattleFactory::BattleFactory(Configuration& newConfig) : config(newConfig) { //load all monster name and texture filename here. std::ifstream input; input.open(resourcePath() + "maps/monsterData.txt"); if (!input.is_open()) { std::cout << "Error: maps/monsterData.txt not found!" << std::endl; exit(1); } //load the data to a new BattleMonster while (!input.eof()) { std::string name, spriteName, line; int max_speed, atk, def, max_hp, exp, money; std::getline(input, line); std::stringstream ss(line); ss >> name >> max_speed >> atk >> def >> max_hp >> exp >> money >>spriteName; BattleMonster newMonster(max_speed, atk, def, max_hp); newMonster.setExp(exp); newMonster.setMoney(money); newMonster.loadSprite(config.texMan.get(spriteName)); monsterTree.emplace(name, newMonster); } input.close(); } /* BattleFactory generateBattle generate a battle based on the battleObject and player who started the battle */ std::shared_ptr<Gameplay::Battle> Gameplay::BattleFactory::generateBattle(tmx::MapObject* battleObject) { //create empty battle std::shared_ptr<Gameplay::Battle> battle(new Battle(config)); //load the background std::string background = battleObject->GetPropertyString("background"); battle->setBackGround(&config.texMan.get(background)); //get the possible monster set std::string monster_set = battleObject->GetPropertyString("monster_set"); std::stringstream ss(monster_set); std::vector<std::string> monsterList; std::string hold; while(ss >> hold) monsterList.push_back(hold); int random = rand() % 100; int min = 0, max = 0, temp = 0; std::string result; for(auto it = monsterList.begin(); it != monsterList.end(); it++) { std::stringstream numss(battleObject->GetPropertyString(*it)); numss >> temp; max += temp; if(random >= min && random < max) { result = *it; break; } min = max; } //create a monster from the tree std::unique_ptr<BattleMonster> monster(new BattleMonster(monsterTree.at(result))); std::string monsterName = monster->getName(); battle->addCharacter(std::move(monster)); battle->setCharPosition(monsterName, 800); return battle; }
26.849932
248
0.644835
[ "render", "vector" ]
b17de05dea319131d2bfb0c70d1c50325297e9f9
3,383
hpp
C++
include/te/display.hpp
a1exwang/te
49732e489e84d93b26ecfd93476267c9e46bc965
[ "MIT" ]
null
null
null
include/te/display.hpp
a1exwang/te
49732e489e84d93b26ecfd93476267c9e46bc965
[ "MIT" ]
null
null
null
include/te/display.hpp
a1exwang/te
49732e489e84d93b26ecfd93476267c9e46bc965
[ "MIT" ]
null
null
null
#pragma once #include <bitset> #include <fstream> #include <iostream> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <vector> #include <te/basic.hpp> #include <te/subprocess.hpp> #include <te/tty_input.hpp> struct SDL_Window; struct SDL_Texture; struct SDL_Renderer; struct _TTF_Font; typedef _TTF_Font TTF_Font; namespace te { class Screen; class FontCache; class Display { public: Display(std::ostream &log_stream, const std::vector<std::string> &args, const std::string &term_env, const std::string &font_file_path, int font_size, const std::string &background_image_path, const std::vector<std::string> &environment_variables, bool use_accleration); ~Display(); void loop(); // child process bool check_child_process(); void process_input(); void write_pending_input_data(std::vector<uint8_t> &input_buffer); void write_to_tty(std::string_view s) const; // screen void resize(int w, int h); // clipboard void clear_selection(); std::string clipboard_copy(); void clipboard_paste(std::string_view clipboard_text) const; // rendering void render_chars(); void render_background_image(); Color map_color(Color color) const; // utility functions void got_character(std::string c); bool less_than(std::tuple<int, int> lhs, std::tuple<int, int> rhs) const { int n_lhs = std::get<0>(lhs) * max_cols_ + std::get<1>(lhs); int n_rhs = std::get<0>(rhs) * max_cols_ + std::get<1>(rhs); return n_lhs < n_rhs; } // is target in [start, end] bool in_range(std::tuple<int, int> start, std::tuple<int, int> end, std::tuple<int, int> target) const { int n_target = std::get<0>(target) * max_cols_ + std::get<1>(target); int n_start = std::get<0>(start) * max_cols_ + std::get<1>(start); int n_end = std::get<0>(end) * max_cols_ + std::get<1>(end); return (n_start <= n_target && n_target <= n_end) || (n_end <= n_target && n_target <= n_start); } // x, y -> row, col std::tuple<int, int> window_to_console(int x, int y) const { return {y / glyph_height_, x / glyph_width_}; } void log_verbose_input_char(uint32_t c, bool has_color); void switch_screen(bool alternate_screen); // private: // screens Screen *current_screen_; std::unique_ptr<Screen> default_screen_, alternate_screen_; // rendering SDL_Window *window_ = nullptr; SDL_Renderer *renderer_ = nullptr; TTF_Font *font_ = nullptr; std::unique_ptr<FontCache> font_cache_; // child process TTYInput tty_input_; std::unique_ptr<Subprocess> subprocess_; // window title std::string window_title_ = "alex's te"; std::vector<std::string> xterm_title_stack_; // background image SDL_Texture *background_image_texture = nullptr; int background_image_width = 0, background_image_height = 0; // 0 - 255 int background_image_opaque = 128; // display sizes int glyph_height_, glyph_width_; int resolution_w_, resolution_h_; int max_rows_, max_cols_; // clipboard bool has_selection = false; bool mouse_left_button_down = false; int selection_start_row = 0, selection_start_col = 0; int selection_end_row = 0, selection_end_col = 0; Color selection_bg_color = Color{0xff666666}, selection_fg_color = Color{0xff111111}; // misc std::ostream &log_stream_; }; }
26.429688
106
0.695241
[ "vector" ]
b18d40f6f2a00feb654f29b0ff70393047352b02
3,178
cc
C++
ivision/src/model/DescribeTrainDatasByIdsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
ivision/src/model/DescribeTrainDatasByIdsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
ivision/src/model/DescribeTrainDatasByIdsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ivision/model/DescribeTrainDatasByIdsResult.h> #include <json/json.h> using namespace AlibabaCloud::Ivision; using namespace AlibabaCloud::Ivision::Model; DescribeTrainDatasByIdsResult::DescribeTrainDatasByIdsResult() : ServiceResult() {} DescribeTrainDatasByIdsResult::DescribeTrainDatasByIdsResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeTrainDatasByIdsResult::~DescribeTrainDatasByIdsResult() {} void DescribeTrainDatasByIdsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allTrainDatas = value["TrainDatas"]["TrainData"]; for (auto value : allTrainDatas) { TrainData trainDatasObject; if(!value["ProjectId"].isNull()) trainDatasObject.projectId = value["ProjectId"].asString(); if(!value["IterationId"].isNull()) trainDatasObject.iterationId = value["IterationId"].asString(); if(!value["DataId"].isNull()) trainDatasObject.dataId = value["DataId"].asString(); if(!value["DataName"].isNull()) trainDatasObject.dataName = value["DataName"].asString(); if(!value["DataUrl"].isNull()) trainDatasObject.dataUrl = value["DataUrl"].asString(); if(!value["CreationTime"].isNull()) trainDatasObject.creationTime = value["CreationTime"].asString(); if(!value["Status"].isNull()) trainDatasObject.status = value["Status"].asString(); if(!value["TagStatus"].isNull()) trainDatasObject.tagStatus = value["TagStatus"].asString(); auto allTagItems = value["TagItems"]["TagItem"]; for (auto value : allTagItems) { TrainData::TagItem tagItemsObject; if(!value["TagId"].isNull()) tagItemsObject.tagId = value["TagId"].asString(); if(!value["RegionType"].isNull()) tagItemsObject.regionType = value["RegionType"].asString(); auto regionNode = value["Region"]; if(!regionNode["Left"].isNull()) tagItemsObject.region.left = regionNode["Left"].asString(); if(!regionNode["Top"].isNull()) tagItemsObject.region.top = regionNode["Top"].asString(); if(!regionNode["Width"].isNull()) tagItemsObject.region.width = regionNode["Width"].asString(); if(!regionNode["Height"].isNull()) tagItemsObject.region.height = regionNode["Height"].asString(); trainDatasObject.tagItems.push_back(tagItemsObject); } trainDatas_.push_back(trainDatasObject); } } std::vector<DescribeTrainDatasByIdsResult::TrainData> DescribeTrainDatasByIdsResult::getTrainDatas()const { return trainDatas_; }
34.543478
105
0.733166
[ "vector", "model" ]
b18e5e6d82593c8a7fa80659804e2d864efdc85c
1,459
cpp
C++
LeetCode/5359.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
7
2019-02-25T13:15:00.000Z
2021-12-21T22:08:39.000Z
LeetCode/5359.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
null
null
null
LeetCode/5359.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
1
2019-04-03T06:12:46.000Z
2019-04-03T06:12:46.000Z
class Solution { private: static const int mod = 1e9 + 7; // 按efficiency从大到小排序 static bool cmp(const pair<int,int>& a, const pair<int,int>& b) { // if(a.second==b.second) // return a.first < b.first; // 效率一样时,不用考虑速度的顺序,随便什么顺序放,插入堆时再检查就行了 return a.second > b.second; } public: int maxPerformance(int n, vector<int>& sp, vector<int>& ef, int k) { vector<pair<int,int>> vp(n); for(int i=0;i<n;i++) { vp[i] = make_pair(sp[i], ef[i]); } sort(vp.begin(), vp.end(), cmp); long long ans = INT_MIN; // 升序队列即最小堆,里面放的是速度 priority_queue<int,vector<int>,greater<int> > q; // 记录到当前为止堆中几个工程师的速度和 long long sum = 0; // 正序遍历时,每次遇到的都是当前遇到过"效率最低"的一个,尝试将其作为最低效的 for(int i=0;i<n;i++) { int nowEf = vp[i].second; int nowSp = vp[i].first; // 堆满了,要和堆顶检查一下,当前的会不会速度更大 // 如果是速度相等没必要换,因为当前的效率不会更高 if(k==q.size() && q.top()<nowSp) { sum -= q.top(); q.pop(); q.push(nowSp); sum += nowSp; } // 堆没满直接插入 else if (k>q.size()) { q.push(nowSp); sum += nowSp; } else { continue; } if (sum*nowEf > ans) ans = sum*nowEf; } return ans % mod; } };
28.057692
72
0.452365
[ "vector" ]
b1929557ac7d095fe9320189cfc3858b2a4d987c
16,379
cpp
C++
src/test/btree_multiset_test.cpp
ohamel-softwaresecure/souffle
d4b9fe641f0c51d2a25408af45416a7e5123f866
[ "UPL-1.0" ]
2
2021-04-29T16:34:06.000Z
2021-12-04T08:31:30.000Z
src/test/btree_multiset_test.cpp
ohamel-softwaresecure/souffle
d4b9fe641f0c51d2a25408af45416a7e5123f866
[ "UPL-1.0" ]
1
2019-11-20T22:48:09.000Z
2019-11-20T22:48:09.000Z
src/test/btree_multiset_test.cpp
ohamel-softwaresecure/souffle
d4b9fe641f0c51d2a25408af45416a7e5123f866
[ "UPL-1.0" ]
1
2021-07-27T07:49:45.000Z
2021-07-27T07:49:45.000Z
/* * Souffle - A Datalog Compiler * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file btree_multiset_test.h * * A test case testing the B-trees utilization as multisets. * ***********************************************************************/ #include "BTree.h" #include "test.h" #include <algorithm> #include <chrono> #include <cstdlib> #include <iomanip> #include <iostream> #include <random> #include <set> #include <tuple> #include <unordered_set> #include <vector> namespace std { template <typename A, typename B> struct hash<tuple<A, B>> { std::size_t operator()(const tuple<A, B>& t) const { auto a = std::hash<A>()(get<0>(t)); auto b = std::hash<B>()(get<1>(t)); // from http://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2)); } }; template <typename A, typename B> std::ostream& operator<<(std::ostream& out, const tuple<A, B>& t) { return out << "[" << get<0>(t) << "," << get<1>(t) << "]"; } } // namespace std namespace souffle { namespace test { TEST(BTreeMultiSet, Basic) { const bool DEBUG = false; using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; EXPECT_EQ(3, test_set::max_keys_per_node); // check initial conditions EXPECT_EQ(0u, t.size()); EXPECT_FALSE(t.contains(10)); EXPECT_FALSE(t.contains(12)); EXPECT_FALSE(t.contains(14)); EXPECT_EQ(0, t.getDepth()); EXPECT_EQ(0, t.getNumNodes()); if (DEBUG) t.printTree(); // add an element t.insert(12); if (DEBUG) { t.printTree(); std::cout << "\n"; } EXPECT_EQ(1u, t.size()); EXPECT_FALSE(t.contains(10)); EXPECT_TRUE(t.contains(12)); EXPECT_FALSE(t.contains(14)); EXPECT_EQ(1, t.getDepth()); EXPECT_EQ(1, t.getNumNodes()); // add a larger element t.insert(14); if (DEBUG) { t.printTree(); std::cout << "\n"; } EXPECT_EQ(2u, t.size()); EXPECT_FALSE(t.contains(10)); EXPECT_TRUE(t.contains(12)); EXPECT_TRUE(t.contains(14)); EXPECT_EQ(1, t.getDepth()); EXPECT_EQ(1, t.getNumNodes()); // add a smaller element t.insert(10); if (DEBUG) { t.printTree(); std::cout << "\n"; } EXPECT_EQ(3u, t.size()); EXPECT_TRUE(t.contains(10)); EXPECT_TRUE(t.contains(12)); EXPECT_TRUE(t.contains(14)); EXPECT_EQ(1, t.getDepth()); EXPECT_EQ(1, t.getNumNodes()); // cause a split t.insert(11); if (DEBUG) { t.printTree(); std::cout << "\n"; } EXPECT_EQ(4u, t.size()); EXPECT_TRUE(t.contains(10)); EXPECT_TRUE(t.contains(11)); EXPECT_TRUE(t.contains(12)); EXPECT_TRUE(t.contains(14)); if (DEBUG) { t.printTree(); std::cout << "\n"; } t.insert(12); EXPECT_EQ(5u, t.size()); t.insert(12); EXPECT_EQ(6u, t.size()); if (DEBUG) { t.printTree(); std::cout << "\n"; } t.insert(15); if (DEBUG) { t.printTree(); std::cout << "\n"; } t.insert(16); if (DEBUG) { t.printTree(); std::cout << "\n"; } } TEST(BTreeMultiSet, Duplicates) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; for (int i = 0; i < 10; i++) { t.insert(0); } EXPECT_EQ(10, t.size()); std::vector<int> data(t.begin(), t.end()); EXPECT_EQ(10, data.size()); for (int i = 0; i < 10; i++) { EXPECT_EQ(0, data[i]); } } TEST(BTreeMultiSet, Incremental) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; int N = 1000; for (int i = 0; i < N; i++) { t.insert(i); for (int j = 0; j < N; j++) { EXPECT_EQ(j <= i, t.contains(j)) << "i=" << i << ", j=" << j; } } } TEST(BTreeMultiSet, Decremental) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; int N = 1000; for (int i = N; i >= 0; i--) { t.insert(i); for (int j = 0; j < N; j++) { EXPECT_EQ(j >= i, t.contains(j)) << "i=" << i << ", j=" << j; } } } TEST(BTreeMultiSet, Shuffled) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; int N = 10000; std::vector<int> data; for (int i = 0; i < N; i++) { data.push_back(i); } std::random_device rd; std::mt19937 generator(rd()); shuffle(data.begin(), data.end(), generator); for (int i = 0; i < N; i++) { t.insert(data[i]); } for (int i = 0; i < N; i++) { EXPECT_TRUE(t.contains(i)) << "i=" << i; } } TEST(BTreeMultiSet, IteratorEmpty) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; EXPECT_EQ(t.begin(), t.end()); } TEST(BTreeMultiSet, IteratorBasic) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; for (int i = 0; i < 10; i++) { t.insert(i); } // t.printTree(); auto it = t.begin(); auto e = t.end(); EXPECT_NE(it, e); int last = -1; for (int i : t) { EXPECT_EQ(last + 1, i); last = i; } EXPECT_EQ(last, 9); } TEST(BTreeMultiSet, IteratorStress) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; int N = 1000; std::vector<int> data; for (int i = 0; i < N; i++) { data.push_back(i); } std::random_device rd; std::mt19937 generator(rd()); shuffle(data.begin(), data.end(), generator); for (int i = 0; i < N; i++) { EXPECT_EQ((size_t)i, t.size()); int last = -1; for (int i : t) { EXPECT_LT(last, i); last = i; } t.insert(data[i]); } } TEST(BTreeMultiSet, BoundaryTest) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; for (int i = 0; i < 10; i++) { t.insert(i); } // t.printTree(); auto a = t.lower_bound(5); EXPECT_EQ(5, *a); auto b = t.upper_bound(5); EXPECT_EQ(6, *b); // add duplicates t.insert(5); t.insert(5); t.insert(5); // t.printTree(); std::cout << "\n"; // test again .. a = t.lower_bound(5); EXPECT_EQ(5, *a); b = t.upper_bound(5); EXPECT_EQ(6, *b); // check the distance EXPECT_EQ(5, *a); ++a; EXPECT_EQ(5, *a); ++a; EXPECT_EQ(5, *a); ++a; EXPECT_EQ(5, *a); ++a; EXPECT_EQ(6, *a); } TEST(BTreeMultiSet, BoundaryEmpty) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; EXPECT_EQ(t.end(), t.lower_bound(5)); EXPECT_EQ(t.end(), t.upper_bound(5)); t.insert(4); EXPECT_EQ(t.lower_bound(3), t.upper_bound(3)); EXPECT_EQ(t.lower_bound(5), t.upper_bound(5)); t.insert(6); EXPECT_EQ(t.lower_bound(3), t.upper_bound(3)); EXPECT_EQ(t.lower_bound(5), t.upper_bound(5)); t.insert(5); EXPECT_EQ(t.lower_bound(3), t.upper_bound(3)); EXPECT_NE(t.lower_bound(5), t.upper_bound(5)); } TEST(BTreeMultiSet, Load) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; for (int N = 0; N < 100; N++) { // generate some ordered data std::vector<int> data; for (int i = 0; i < N; i++) { data.push_back(i); } auto t = test_set::load(data.begin(), data.end()); EXPECT_EQ(data.size(), t.size()); EXPECT_TRUE(t.check()); int last = -1; for (int c : t) { EXPECT_EQ(last + 1, c); last = c; } EXPECT_EQ(last, N - 1); } } TEST(BTreeMultiSet, Clear) { using test_set = btree_multiset<int, detail::comparator<int>, std::allocator<int>, 16>; test_set t; EXPECT_TRUE(t.empty()); t.insert(5); EXPECT_FALSE(t.empty()); t.clear(); EXPECT_TRUE(t.empty()); t.clear(); EXPECT_TRUE(t.empty()); } using Entry = std::tuple<int, int>; std::vector<Entry> getData(unsigned numEntries) { std::vector<Entry> res(numEntries); int k = 0; for (unsigned i = 0; i < numEntries; i++) { res[k++] = Entry(i / 100, i % 100); } std::random_device rd; std::mt19937 generator(rd()); shuffle(res.begin(), res.end(), generator); return res; } using time_point = std::chrono::high_resolution_clock::time_point; time_point now() { return std::chrono::high_resolution_clock::now(); } long duration(const time_point& start, const time_point& end) { return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); } template <typename Op> long time(const std::string& name, const Op& operation) { std::cout << "\t" << std::setw(30) << std::setiosflags(std::ios::left) << name << std::resetiosflags(std::ios::left) << " ... " << std::flush; auto a = now(); operation(); auto b = now(); auto time = duration(a, b); std::cout << " done [" << std::setw(5) << time << "ms]\n"; return time; } template <typename C> struct reserver { void operator()(C&, unsigned) const { // default: no action } }; template <typename A, typename B, typename C, typename D> struct reserver<std::unordered_set<A, B, C, D>> { void operator()(std::unordered_set<A, B, C, D>& set, unsigned size) const { set.reserve(size); } }; #define checkPerformance(set_type, name, in, out) \ { \ std::cout << "Testing: " << name << " ..\n"; \ set_type set; \ time("filling set", [&]() { \ reserver<set_type>()(set, in.size()); \ for (const auto& cur : in) { \ set.insert(cur); \ } \ }); \ int counter = 0; \ time("full scan", [&]() { \ for (auto it = set.begin(); it != set.end(); ++it) { \ counter++; \ } \ }); \ EXPECT_EQ((size_t)counter, set.size()); \ bool allPresent = true; \ time("membership in", [&]() { \ for (const auto& cur : in) { \ allPresent = (set.find(cur) != set.end()) && allPresent; \ } \ }); \ EXPECT_TRUE(allPresent); \ bool allMissing = true; \ time("membership out", [&]() { \ for (const auto& cur : out) { \ allMissing = (set.find(cur) == set.end()) && allMissing; \ } \ }); \ EXPECT_TRUE(allMissing); \ bool allFound = true; \ time("lower_boundaries", [&]() { \ for (const auto& cur : in) { \ allFound = (set.lower_bound(cur) == set.find(cur)) && allFound; \ } \ }); \ EXPECT_TRUE(allFound); \ allFound = true; \ time("upper_boundaries", [&]() { \ for (const auto& cur : in) { \ allFound = (set.upper_bound(cur) == (++set.find(cur))) && allFound; \ } \ }); \ EXPECT_TRUE(allFound); \ allFound = true; \ time("boundaries on missing elements", [&]() { \ for (const auto& cur : out) { \ allFound = (set.lower_bound(cur) == set.upper_bound(cur)) && allFound; \ } \ }); \ EXPECT_TRUE(allFound); \ set_type a(in.begin(), in.end()); \ set_type b(out.begin(), out.end()); \ time("merge two sets", [&]() { a.insert(b.begin(), b.end()); }); \ std::cout << "\tDone!\n\n"; \ } TEST(Performance, Basic) { int N = 1 << 18; // get list of tuples to be inserted std::cout << "Generating Test-Data ...\n"; std::vector<Entry> in; std::vector<Entry> out; time("generating data", [&]() { auto data = getData(2 * N); for (std::size_t i = 0; i < data.size(); i += 2) { in.push_back(data[i]); out.push_back(data[i + 1]); } }); using t1 = std::set<Entry>; checkPerformance(t1, " -- warm up -- ", in, out); using t2 = btree_multiset<Entry, detail::comparator<Entry>, std::allocator<Entry>, 256, detail::linear_search>; checkPerformance(t2, "souffle btree_multiset - 256 - linear", in, out); using t3 = btree_multiset<Entry, detail::comparator<Entry>, std::allocator<Entry>, 256, detail::binary_search>; checkPerformance(t3, "souffle btree_multiset - 256 - binary", in, out); } TEST(Performance, Load) { int N = 1 << 20; std::vector<int> data; for (int i = 0; i < N; i++) { data.push_back(i); } // take time for conventional load time("conventional load", [&]() { btree_multiset<int> t(data.begin(), data.end()); }); // take time for structured load time("bulk-load", [&]() { auto t = btree_multiset<int>::load(data.begin(), data.end()); }); } } // namespace test } // end namespace souffle
30.787594
95
0.43916
[ "vector" ]
b1954ea7ff44b38b67eee7f31cfa81ea12cbc891
722
cpp
C++
C++/0616-Add-Bold-Tag-in-String/soln-1.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0616-Add-Bold-Tag-in-String/soln-1.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0616-Add-Bold-Tag-in-String/soln-1.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: string addBoldTag(string S, vector<string>& words) { int n = S.length(); vector<bool> tags(n, false); for(string & word : words) { int m = word.length(); for(int i = 0; i < n - m + 1; ++i) { if (S.substr(i, m) == word) { for(int j = i; j < i + m; ++j) tags[j] = true; } } } string ans = ""; for(int i = 0; i < n; ++i) { char ch = S[i]; if (tags[i] && (i == 0 || !tags[i - 1])) ans += "<b>"; ans += ch; if (tags[i] && (i == n - 1 || !tags[i + 1])) ans += "</b>"; } return ans; } };
30.083333
71
0.34903
[ "vector" ]
b19737d11a4153423a4774aecf87ccf2253bd821
20,922
cc
C++
PYTHIA8/pythia8243/src/MiniStringFragmentation.cc
mpoghos/AliRoot
e81490f640ad6f2a6189f679de96b07a94304b58
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PYTHIA8/pythia8243/src/MiniStringFragmentation.cc
mpoghos/AliRoot
e81490f640ad6f2a6189f679de96b07a94304b58
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PYTHIA8/pythia8243/src/MiniStringFragmentation.cc
mpoghos/AliRoot
e81490f640ad6f2a6189f679de96b07a94304b58
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
// MiniStringFragmentation.cc is a part of the PYTHIA event generator. // Copyright (C) 2019 Torbjorn Sjostrand. // PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details. // Please respect the MCnet Guidelines, see GUIDELINES for details. // Function definitions (not found in the header) for the . // MiniStringFragmentation class #include "Pythia8/MiniStringFragmentation.h" namespace Pythia8 { //========================================================================== // The MiniStringFragmentation class. //-------------------------------------------------------------------------- // Constants: could be changed here if desired, but normally should not. // These are of technical nature, as described for each. // Since diffractive by definition is > 1 particle, try hard. const int MiniStringFragmentation::NTRYDIFFRACTIVE = 200; // After one-body fragmentation failed, try two-body once more. const int MiniStringFragmentation::NTRYLASTRESORT = 100; // Loop try to combine available endquarks to valid hadron. const int MiniStringFragmentation::NTRYFLAV = 10; //-------------------------------------------------------------------------- // Initialize and save pointers. void MiniStringFragmentation::init(Info* infoPtrIn, Settings& settings, ParticleData* particleDataPtrIn, Rndm* rndmPtrIn, StringFlav* flavSelPtrIn, StringPT* pTSelPtrIn, StringZ* zSelPtrIn) { // Save pointers. infoPtr = infoPtrIn; particleDataPtr = particleDataPtrIn; rndmPtr = rndmPtrIn; flavSelPtr = flavSelPtrIn; pTSelPtr = pTSelPtrIn; zSelPtr = zSelPtrIn; // Calculation and definition of hadron space-time production vertices. hadronVertex = settings.mode("HadronVertex:mode"); setVertices = settings.flag("Fragmentation:setVertices"); kappaVtx = settings.parm("HadronVertex:kappa"); smearOn = settings.flag("HadronVertex:smearOn"); xySmear = settings.parm("HadronVertex:xySmear"); constantTau = settings.flag("HadronVertex:constantTau"); // Charm and bottom quark masses used for space-time offset. mc = particleDataPtr->m0(4); mb = particleDataPtr->m0(5); // Initialize the MiniStringFragmentation class proper. nTryMass = settings.mode("MiniStringFragmentation:nTry"); // Initialize the b parameter of the z spectrum, used when joining jets. bLund = zSelPtr->bAreaLund(); } //-------------------------------------------------------------------------- // Do the fragmentation: driver routine. bool MiniStringFragmentation::fragment(int iSub, ColConfig& colConfig, Event& event, bool isDiff) { // Junction topologies not yet considered - is very rare. iParton = colConfig[iSub].iParton; if (iParton.front() < 0) { infoPtr->errorMsg("Error in MiniStringFragmentation::fragment: " "very low-mass junction topologies not yet handled"); return false; } // Read in info on system to be treated. flav1 = FlavContainer( event[ iParton.front() ].id() ); flav2 = FlavContainer( event[ iParton.back() ].id() ); pSum = colConfig[iSub].pSum; mSum = colConfig[iSub].mass; m2Sum = mSum*mSum; isClosed = colConfig[iSub].isClosed; // Do not want diffractive systems to easily collapse to one particle. int nTryFirst = (isDiff) ? NTRYDIFFRACTIVE : nTryMass; // First try to produce two particles from the system. if (ministring2two( nTryFirst, event)) return true; // If this fails, then form one hadron and shuffle momentum. if (ministring2one( iSub, colConfig, event)) return true; // If also this fails, then try harder to produce two particles. if (ministring2two( NTRYLASTRESORT, event)) return true; // Else complete failure. infoPtr->errorMsg("Error in MiniStringFragmentation::fragment: " "no 1- or 2-body state found above mass threshold"); return false; } //-------------------------------------------------------------------------- // Attempt to produce two particles from the ministring. bool MiniStringFragmentation::ministring2two( int nTry, Event& event) { // Properties of the produced hadrons. int idHad1 = 0; int idHad2 = 0; double mHad1 = 0.; double mHad2 = 0.; double mHadSum = 0.; // Allow a few attempts to find a particle pair with low enough masses. for (int iTry = 0; iTry < nTry; ++iTry) { // For closed gluon loop need to pick an initial flavour. if (isClosed) do { int idStart = flavSelPtr->pickLightQ(); FlavContainer flavStart(idStart, 1); flavStart = flavSelPtr->pick( flavStart); flav1 = flavSelPtr->pick( flavStart); flav2.anti(flav1); } while (flav1.id == 0 || flav1.nPop > 0); // Create a new q qbar flavour to form two hadrons. // Start from a diquark, if any. do { FlavContainer flav3 = (flav1.isDiquark() || (!flav2.isDiquark() && rndmPtr->flat() < 0.5) ) ? flavSelPtr->pick( flav1) : flavSelPtr->pick( flav2).anti(); idHad1 = flavSelPtr->combine( flav1, flav3); idHad2 = flavSelPtr->combine( flav2, flav3.anti()); } while (idHad1 == 0 || idHad2 == 0); // Check whether the mass sum fits inside the available phase space. mHad1 = particleDataPtr->mSel(idHad1); mHad2 = particleDataPtr->mSel(idHad2); mHadSum = mHad1 + mHad2; if (mHadSum < mSum) break; } if (mHadSum >= mSum) return false; // Define an effective two-parton string, by splitting intermediate // gluon momenta in proportion to their closeness to either endpoint. Vec4 pSum1 = event[ iParton.front() ].p(); Vec4 pSum2 = event[ iParton.back() ].p(); if (iParton.size() > 2) { Vec4 pEnd1 = pSum1; Vec4 pEnd2 = pSum2; Vec4 pEndSum = pEnd1 + pEnd2; for (int i = 1; i < int(iParton.size()) - 1 ; ++i) { Vec4 pNow = event[ iParton[i] ].p(); double ratio = (pEnd2 * pNow) / (pEndSum * pNow); pSum1 += ratio * pNow; pSum2 += (1. - ratio) * pNow; } } // If split did not provide an axis then pick random axis to break tie. // (Needed for low-mass q-g-qbar with q-qbar perfectly parallel.) if (pSum1.mCalc() + pSum2.mCalc() > 0.999999 * mSum) { double cthe = 2. * rndmPtr->flat() - 1.; double sthe = sqrtpos(1. - cthe * cthe); double phi = 2. * M_PI * rndmPtr->flat(); Vec4 delta = 0.5 * min( pSum1.e(), pSum2.e()) * Vec4( sthe * sin(phi), sthe * cos(phi), cthe, 0.); pSum1 += delta; pSum2 -= delta; infoPtr->errorMsg("Warning in MiniStringFragmentation::ministring2two: " "random axis needed to break tie"); } // Set up a string region based on the two effective endpoints. StringRegion region; region.setUp( pSum1, pSum2, 0, 0); // Generate an isotropic decay in the ministring rest frame, // suppressed at large pT by a fragmentation pT Gaussian. double pAbs2 = 0.25 * ( pow2(m2Sum - mHad1*mHad1 - mHad2*mHad2) - pow2(2. * mHad1 * mHad2) ) / m2Sum; double pT2 = 0.; do { double cosTheta = rndmPtr->flat(); pT2 = (1. - pow2(cosTheta)) * pAbs2; } while (pTSelPtr->suppressPT2(pT2) < rndmPtr->flat() ); // Construct the forward-backward asymmetry of the two particles. double mT21 = mHad1*mHad1 + pT2; double mT22 = mHad2*mHad2 + pT2; double lambda = sqrtpos( pow2(m2Sum - mT21 - mT22) - 4. * mT21 * mT22 ); double probReverse = 1. / (1. + exp( min( 50., bLund * lambda) ) ); // Construct kinematics, as viewed in the transverse rest frame. double xpz1 = 0.5 * lambda/ m2Sum; if (probReverse > rndmPtr->flat()) xpz1 = -xpz1; double xmDiff = (mT21 - mT22) / m2Sum; double xe1 = 0.5 * (1. + xmDiff); double xe2 = 0.5 * (1. - xmDiff ); // Distribute pT isotropically in angle. double phi = 2. * M_PI * rndmPtr->flat(); double pT = sqrt(pT2); double px = pT * cos(phi); double py = pT * sin(phi); // Translate this into kinematics in the string frame. Vec4 pHad1 = region.pHad( xe1 + xpz1, xe1 - xpz1, px, py); Vec4 pHad2 = region.pHad( xe2 - xpz1, xe2 + xpz1, -px, -py); // Mark hadrons from junction fragmentation with different status. int statusHadPos = 82, statusHadNeg = 82; if (abs(idHad1) > 1000 && abs(idHad1) < 10000 && abs(idHad2) > 1000 && abs(idHad2) < 10000) { if (event[ iParton.front() ].statusAbs() == 74) statusHadPos = 89; if (event[ iParton.back() ].statusAbs() == 74) statusHadNeg = 89; } else if (abs(idHad1) > 1000 && abs(idHad1) < 10000) { if (event[ iParton.front() ].statusAbs() == 74 || event[ iParton.back() ].statusAbs() == 74) statusHadPos = 89; } else if (abs(idHad2) > 1000 && abs(idHad2) < 10000) { if (event[ iParton.front() ].statusAbs() == 74 || event[ iParton.back() ].statusAbs() == 74) statusHadNeg = 89; } // Add produced particles to the event record. int iFirst = event.append( idHad1, statusHadPos, iParton.front(), iParton.back(), 0, 0, 0, 0, pHad1, mHad1); int iLast = event.append( idHad2, statusHadNeg, iParton.front(), iParton.back(), 0, 0, 0, 0, pHad2, mHad2); // Set decay vertex when this is displaced. if (event[iParton.front()].hasVertex()) { Vec4 vDec = event[iParton.front()].vDec(); event[iFirst].vProd( vDec ); event[iLast].vProd( vDec ); } // Set lifetime of hadrons. event[iFirst].tau( event[iFirst].tau0() * rndmPtr->exp() ); event[iLast].tau( event[iLast].tau0() * rndmPtr->exp() ); // Mark original partons as hadronized and set their daughter range. for (int i = 0; i < int(iParton.size()); ++i) { event[ iParton[i] ].statusNeg(); event[ iParton[i] ].daughters(iFirst, iLast); } // Store breakup vertex information from the fragmentation process. if (setVertices) { ministringVertices.clear(); ministringVertices.push_back( StringVertex(true, 0, 0, 1., 0.) ); ministringVertices.push_back( StringVertex(true, 0, 0, 1. - (xe1 + xpz1), xe1 - xpz1) ); ministringVertices.push_back( StringVertex(true, 0, 0, 0., 1.) ); // Store hadron production space-time vertices. setHadronVertices( event, region, iFirst, iLast); } // Successfully done. return true; } //-------------------------------------------------------------------------- // Attempt to produce one particle from a ministring. // Current algorithm: find the system with largest invariant mass // relative to the existing one, and boost that system appropriately. // Try more sophisticated alternatives later?? (Z0 mass shifted??) // Also, if problems, attempt several times to obtain closer mass match?? bool MiniStringFragmentation::ministring2one( int iSub, ColConfig& colConfig, Event& event) { // Cannot handle qq + qbarqbar system. if (abs(flav1.id) > 100 && abs(flav2.id) > 100) return false; // For closed gluon loop need to pick an initial flavour. if (isClosed) do { int idStart = flavSelPtr->pickLightQ(); FlavContainer flavStart(idStart, 1); flav1 = flavSelPtr->pick( flavStart); flav2 = flav1.anti(); } while (abs(flav1.id) > 100); // Select hadron flavour from available quark flavours. int idHad = 0; for (int iTryFlav = 0; iTryFlav < NTRYFLAV; ++iTryFlav) { idHad = flavSelPtr->combine( flav1, flav2); if (idHad != 0) break; } if (idHad == 0) return false; // Find mass. double mHad = particleDataPtr->mSel(idHad); // Find the untreated parton system which combines to the largest // squared mass above mimimum required. int iMax = -1; double deltaM2 = mHad*mHad - mSum*mSum; double delta2Max = 0.; for (int iRec = iSub + 1; iRec < colConfig.size(); ++iRec) { double delta2Rec = 2. * (pSum * colConfig[iRec].pSum) - deltaM2 - 2. * mHad * colConfig[iRec].mass; if (delta2Rec > delta2Max) { iMax = iRec; delta2Max = delta2Rec;} } if (iMax == -1) return false; // Construct kinematics of the hadron and recoiling system. Vec4& pRec = colConfig[iMax].pSum; double mRec = colConfig[iMax].mass; double vecProd = pSum * pRec; double coefOld = mSum*mSum + vecProd; double coefNew = mHad*mHad + vecProd; double coefRec = mRec*mRec + vecProd; double coefSum = coefOld + coefNew; double sHat = coefOld + coefRec; double root = sqrtpos( (pow2(coefSum) - 4. * sHat * mHad*mHad) / (pow2(vecProd) - pow2(mSum * mRec)) ); double k2 = 0.5 * (coefOld * root - coefSum) / sHat; double k1 = (coefRec * k2 + 0.5 * deltaM2) / coefOld; Vec4 pHad = (1. + k1) * pSum - k2 * pRec; Vec4 pRecNew = (1. + k2) * pRec - k1 * pSum; // Mark hadrons from junction split off with status 89. int statusHad = 81; if (abs(idHad) > 1000 && abs(idHad) < 10000 && (event[ iParton.front() ].statusAbs() == 74 || event[ iParton.back() ].statusAbs() == 74)) statusHad = 89; // Add the produced particle to the event record. int iHad = event.append( idHad, statusHad, iParton.front(), iParton.back(), 0, 0, 0, 0, pHad, mHad); // Set decay vertex when this is displaced. if (event[iParton.front()].hasVertex()) { Vec4 vDec = event[iParton.front()].vDec(); event[iHad].vProd( vDec ); } // Set lifetime of hadron. event[iHad].tau( event[iHad].tau0() * rndmPtr->exp() ); // Mark original partons as hadronized and set their daughter range. for (int i = 0; i < int(iParton.size()); ++i) { event[ iParton[i] ].statusNeg(); event[ iParton[i] ].daughters(iHad, iHad); } // Copy down recoiling system, with boosted momentum. Update current partons. RotBstMatrix M; M.bst(pRec, pRecNew); for (int i = 0; i < colConfig[iMax].size(); ++i) { int iOld = colConfig[iMax].iParton[i]; // Do not touch negative iOld = beginning of new junction leg. if (iOld >= 0) { int iNew; // Keep track of 74 throughout the event. if (event[iOld].status() == 74) iNew = event.copy(iOld, 74); else iNew = event.copy(iOld, 72); event[iNew].rotbst(M); colConfig[iMax].iParton[i] = iNew; } } colConfig[iMax].pSum = pRecNew; colConfig[iMax].isCollected = true; // Calculate hadron production points from breakup vertices // using one of the three definitions. if (setVertices) { Vec4 prodPoint = Vec4( 0., 0., 0., 0.); Vec4 pHadron = event[iHad].p(); // Smearing in transverse space. if (smearOn) { // Find two spacelike transverse four-vector directions. Vec4 eX = Vec4( 1., 0., 0., 0.); Vec4 eY = Vec4( 0., 1., 0., 0.); // Introduce smearing in transverse space. double transX = rndmPtr -> gauss(); double transY = rndmPtr -> gauss(); prodPoint = xySmear * (transX * eX + transY * eY) / sqrt(2.); // Keep proper or actual time constant when including the smearing. // Latter case to be done better when introducing MPI vertices. if (constantTau) prodPoint.e( prodPoint.pAbs() ); else prodPoint = Vec4( 0., 0., 0., 0.); } // Reduced oscillation period if hadron contains massive quarks. int id1 = event[ iParton.front() ].idAbs(); int id2 = event[ iParton.back() ].idAbs(); double redOsc = 1.; if (id1 == 4 || id1 == 5 || id2 == 4 || id2 == 5) { double posMass = (id1 == 4 || id1 == 5) ? particleDataPtr->m0(id1) : 0.; double negMass = (id2 == 4 || id2 == 5) ? particleDataPtr->m0(id2) : 0.; redOsc = sqrtpos( pow2(pow2(mHad) - pow2(posMass) - pow2(negMass)) - 4. * pow2(posMass * negMass) ) / pow2(mHad); } // Find hadron production points according to chosen definition. if (hadronVertex == 0) prodPoint += 0.5 * redOsc * pHadron / kappaVtx; else if (hadronVertex == 1) prodPoint += redOsc * pHadron / kappaVtx; event[iHad].vProd( prodPoint * FM2MM ); } // Successfully done. return true; } //-------------------------------------------------------------------------- // Store two hadron production points in the event record. void MiniStringFragmentation::setHadronVertices(Event& event, StringRegion& region, int iFirst, int iLast) { // Initial values. vector<Vec4> longitudinal; int id1 = event[ iParton.front() ].idAbs(); int id2 = event[ iParton.back() ].idAbs(); // Longitudinal space-time location of breakup points. for (int i = 0; i < 3; ++i) { double xPosIn = ministringVertices[i].xRegPos; double xNegIn = ministringVertices[i].xRegNeg; Vec4 noOffset = (xPosIn * region.pPos + xNegIn * region.pNeg) / kappaVtx; longitudinal.push_back( noOffset ); } // Longitudinal offset of breakup points for massive quarks. if (region.massiveOffset( 0, 0, 0, id1, id2, mc, mb)) { for (int i = 0; i < 3; ++i) { // Endpoint correction separately for each end. if (i == 0 && (id1 == 4 || id1 == 5)) { Vec4 v1 = longitudinal[i]; Vec4 v2 = longitudinal[i + 1]; double mHad = event[event.size() - 2].m(); double pPosMass = particleDataPtr->m0(id1); longitudinal[i] = v1 + (pPosMass / mHad) * (v2 - v1); } if (i == 2 && (id2 == 4 || id2== 5)) { Vec4 v1 = longitudinal[i]; Vec4 v2 = longitudinal[i-1] + region.massOffset / kappaVtx; double mHad = event[i - 1 + event.size() - 2].m(); double pNegMass = particleDataPtr->m0(id2); longitudinal[i] = v1 + (pNegMass / mHad) * (v2 - v1); if (longitudinal[i].m2Calc() < -1e-8 * max(1., pow2(longitudinal[i].e()))) infoPtr->errorMsg("Warning in MiniStringFragmentation::setVertices:" " negative tau^2 for endpoint massive correction"); } // Add mass offset for all breakup points. Vec4 massOffset = region.massOffset / kappaVtx; Vec4 position = longitudinal[i] - massOffset; // Correction for non-physical situations. if (position.m2Calc() < 0.) { double cMinus = 0.; if (position.m2Calc() > -1e-8 * max(1., pow2(position.e()))) position.e( position.pAbs() ); else { if(massOffset.m2Calc() > 1e-6) cMinus = (longitudinal[i] * massOffset - sqrt(pow2(longitudinal[i] * massOffset) - longitudinal[i].m2Calc() * massOffset.m2Calc())) / massOffset.m2Calc(); else cMinus = 0.5 * longitudinal[i].m2Calc() / (longitudinal[i] * massOffset); position = longitudinal[i] - cMinus * massOffset; } } longitudinal[i] = position; } } // Smearing in transverse space. vector<Vec4> spaceTime; for (int i = 0; i < 3; ++i) { Vec4 positionTot = longitudinal[i]; if (smearOn) { if (!isClosed && (i == 0 || i == 2)) { spaceTime.push_back(positionTot); continue; } Vec4 eX = region.eX; Vec4 eY = region.eY; // Smearing calculated randomly following a gaussian. for (int iTry = 0; ; ++iTry) { double transX = rndmPtr->gauss(); double transY = rndmPtr->gauss(); Vec4 transversePos = xySmear * (transX * eX + transY * eY) / sqrt(2.); positionTot = transversePos + longitudinal[i]; // Keep proper or actual time constant when including the smearing. // Latter case to be done better when introducing MPI vertices. if (constantTau) { double newtime = sqrt(longitudinal[i].m2Calc() + positionTot.pAbs2()); positionTot.e(newtime); break; } else { if (positionTot.m2Calc() >= 0.) break; if (iTry == 100) { positionTot = longitudinal[i]; break; } } } } spaceTime.push_back(positionTot); } // Find hadron production points according to chosen definition. vector<Vec4> prodPoints(2); for(int i = 0; i < 2; ++i) { Vec4 middlePoint = 0.5 * (spaceTime[i] + spaceTime[i+1]); int iHad = (i == 0) ? iFirst : iLast; Vec4 pHad = event[iHad].p(); // Reduced oscillation period if hadron contains massive quarks. double mHad = event[iHad].m(); int idQ = (i == 0) ? id1 : id2; double redOsc = (idQ == 4 || idQ == 5) ? 1. - pow2(particleDataPtr->m0(idQ) / mHad) : 0.; // Set production point according to chosen definition. if (hadronVertex == 0) prodPoints[i] = middlePoint; else if (hadronVertex == 1) prodPoints[i] = middlePoint + 0.5 * redOsc * pHad / kappaVtx; else { prodPoints[i] = middlePoint - 0.5 * redOsc * pHad / kappaVtx; if (prodPoints[i].m2Calc() < 0. || prodPoints[i].e() < 0.) { double tau0fac = 2. * (redOsc * middlePoint * pHad - sqrt(pow2(middlePoint * redOsc * pHad) - middlePoint.m2Calc() * pow2(redOsc * mHad))) / pow2(redOsc * mHad); prodPoints[i] = middlePoint - 0.5 * tau0fac * redOsc * pHad / kappaVtx; } } event[iHad].vProd( prodPoints[i] * FM2MM ); } } //========================================================================== } // end namespace Pythia8
37.095745
79
0.610984
[ "vector" ]
b19cbda0ecce4f4082e32ce894a7d64a1e779949
9,087
cpp
C++
NextEngineEditor/src/displayComponents.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
1
2021-09-10T18:19:16.000Z
2021-09-10T18:19:16.000Z
NextEngineEditor/src/displayComponents.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
null
null
null
NextEngineEditor/src/displayComponents.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
2
2020-04-02T06:46:56.000Z
2021-06-17T16:47:57.000Z
#include "displayComponents.h" #include <imgui/imgui.h> #include "editor.h" #include "ecs/system.h" #include "ecs/ecs.h" #include "core/io/logger.h" #include "core/container/hash_map.h" #include "core/container/string_view.h" #include "graphics/assets/assets.h" hash_map<sstring, OnInspectGUICallback, 103> override_inspect; OnInspectGUICallback get_on_inspect_gui(string_view on_type) { return override_inspect[on_type]; } void register_on_inspect_gui(string_view on_type, OnInspectGUICallback func) { override_inspect[on_type.data] = func; } bool render_fields_primitive(int* ptr, string_view prefix) { ImGui::PushID((long long)ptr); ImGui::InputInt(prefix.c_str(), ptr); ImGui::PopID(); return true; } bool render_fields_primitive(unsigned int* ptr, string_view prefix) { int as_int = *ptr; ImGui::PushID((long long)ptr); ImGui::InputInt(prefix.c_str(), &as_int); ImGui::PopID(); *ptr = as_int; return true; } bool render_fields_primitive(float* ptr, string_view prefix) { ImGui::PushID((long long)ptr); ImGui::InputFloat(prefix.c_str(), ptr); ImGui::PopID(); return true; } bool render_fields_primitive(string_buffer* str, string_view prefix) { ImGui::PushID((long long)str); ImGui::InputText(prefix.c_str(), *str); ImGui::PopID(); return true; } bool render_fields_primitive(bool* ptr, string_view prefix) { ImGui::PushID((long long)ptr); ImGui::Checkbox(prefix.c_str(), ptr); ImGui::PopID(); return true; } #include <imgui/imgui_internal.h> namespace ImGui { bool ImageButton(texture_handle handle, glm::vec2 size, glm::vec2 uv0, glm::vec2 uv1) { if (handle.id == INVALID_HANDLE) handle = default_textures.white; return ImageButton((ImTextureID)handle.id, size, uv0, uv1); } void Image(texture_handle handle, glm::vec2 size, glm::vec2 uv0, glm::vec2 uv1) { if (handle.id == INVALID_HANDLE) handle = default_textures.white; Image( (ImTextureID)handle.id, size, uv0, uv1); } } const char* destroy_component_popup_name(refl::Struct* type) { return tformat("DestroyComponent", type->name).c_str(); } bool render_fields_struct(refl::Struct* self, void* data, string_view prefix, Editor& editor) { if (override_inspect.index(self->name) != -1) { return override_inspect[self->name](data, prefix, editor); } auto name = tformat(prefix, " : ", self->name); auto id = ImGui::GetID(name.c_str()); if (self->fields.length == 1 && prefix != "Component") { auto& field = self->fields[0]; render_fields(field.type, (char*)data + field.offset, field.name, editor); return true; } bool open; if (prefix == "Component") { open = ImGui::CollapsingHeader(self->name.c_str(), ImGuiTreeNodeFlags_Framed); if (ImGui::IsItemHovered() && ImGui::GetIO().MouseClicked[1]) { ImGui::OpenPopup(destroy_component_popup_name(self)); } ImGui::PushID(self->name.c_str()); //ImGui::CloseButton(ImGui::GetActiveID(), ImVec2(ImGui::GetCurrentWindow()->DC.CursorPos.x + ImGui::GetWindowWidth() - 35, ImGui::GetCurrentWindow()->DC.CursorPos.y - 23.0f), 15.0f); ImGui::PopID(); } else { open = ImGui::TreeNode(name.c_str()); } if (open) { for (auto field : self->fields) { auto offset_ptr = (char*)data + field.offset; if (field.flags == refl::HIDE_IN_EDITOR_TAG) {} else { render_fields(field.type, offset_ptr, field.name, editor); } } if (prefix != "Component") ImGui::TreePop(); } return open; } /* bool render_fields_union(reflect::TypeDescriptor_Union* self, void* data, string_view prefix, Editor& editor) { int tag = *((char*)data + self->tag_offset); auto name = tformat(prefix, " : ", self->name); if (ImGui::TreeNode(name.c_str())) { int i = 0; for (auto& member : self->cases) { if (i > 0) ImGui::SameLine(); ImGui::RadioButton(member.name, tag == i); i++; } for (auto field : self->members) { render_fields(field.type, (char*)data + field.offset, field.name, editor); } auto& union_case = self->cases[tag]; render_fields(union_case.type, (char*)data + union_case.offset, "", editor); ImGui::TreePop(); return true; } return false; }*/ bool render_fields_enum(refl::Enum* self, void* data, string_view prefix, Editor& world) { int tag = *((int*)data); int i = 0; for (auto& value : self->values) { if (i > 0) ImGui::SameLine(); ImGui::RadioButton(value.name.c_str(), value.value == tag); i++; } ImGui::SameLine(); ImGui::Text(prefix.c_str()); return true; } string_view type_to_string(refl::Type* type) { switch (type->type) { case refl::Type::UInt: return "uint"; case refl::Type::Int: return "int"; case refl::Type::Bool: return "bool"; case refl::Type::Float: return "float"; } } bool render_fields_ptr(refl::Ptr* self, void* data, string_view prefix, Editor& world) { if (*(void**)data == NULL) { ImGui::LabelText(prefix.c_str(), "NULL"); return false; } return render_fields(self->element, *(void**)data, prefix, world); } bool render_fields_vector(refl::Array* self, void* data, string_view prefix, Editor& world) { auto ptr = (vector<char>*)data; data = ptr->data; auto name = tformat(prefix, " : ", self->element->name); if (ImGui::TreeNode(name.c_str())) { for (unsigned int i = 0; i < ptr->length; i++) { auto name = "[" + std::to_string(i) + "]"; render_fields(self->element, (char*)data + (i * self->element->size), name.c_str(), world); } ImGui::TreePop(); return true; } return false; } bool render_fields(refl::Type* type, void* data, string_view prefix, Editor& editor) { if (override_inspect.index(type->name) != -1) return override_inspect[type->name](data, prefix, editor); if (type->type == refl::Type::Struct) return render_fields_struct((refl::Struct*)type, data, prefix, editor); //else if (type->kind == refl::Union_Kind) return render_fields_union((reflect::TypeDescriptor_Union*)type, data, prefix, editor); else if (type->type == refl::Type::Array) return render_fields_vector((refl::Array*)type, data, prefix, editor); else if (type->type == refl::Type::Enum) return render_fields_enum((refl::Enum*)type, data, prefix, editor); else if (type->type == refl::Type::Float) return render_fields_primitive((float*)data, prefix); else if (type->type == refl::Type::Int) return render_fields_primitive((int*)data, prefix); else if (type->type == refl::Type::Bool) return render_fields_primitive((bool*)data, prefix); else if (type->type == refl::Type::UInt) return render_fields_primitive((unsigned int*)data, prefix); else if (type->type == refl::Type::StringBuffer) return render_fields_primitive((string_buffer*)data, prefix); } void DisplayComponents::update(World& world, UpdateCtx& params) {} //todo bug when custom ui for component, as it does not respect prefix! void DisplayComponents::render(World& world, RenderPass& params, Editor& editor) { //ImGui::SetNextWindowSize(ImVec2(params.width * editor.editor_tab_width, params.height)); //ImGui::SetNextWindowPos(ImVec2(0, 0)); if (ImGui::Begin("Properties", NULL)) { int selected_id = editor.selected_id; if (selected_id >= 0) { auto name_and_id = tformat("Entity #", selected_id); EntityNode* node = editor.lister.by_id[selected_id]; if (node) { ImGui::InputText(name_and_id.c_str(), node->name); } else { ImGui::Text(name_and_id.c_str()); } Archetype arch = world.arch_of_id(selected_id); bool uncollapse = ImGui::Button("uncollapse all"); for (uint component_id = 0; component_id < MAX_COMPONENTS; component_id++) { if (!has_component(arch, component_id)) continue; ComponentKind kind = world.component_kind[component_id]; refl::Struct* type = world.component_type[component_id]; if (kind != REGULAR_COMPONENT || !type) continue; //todo add editor support for component flags void* data = world.id_to_ptr[component_id][selected_id]; ImGui::BeginGroup(); if (uncollapse) ImGui::SetNextTreeNodeOpen(true); DiffUtil diff_util; begin_e_tdiff(diff_util, world, component_id, selected_id); bool open = render_fields(type, data, "Component", editor); if (open) { ImGui::Dummy(ImVec2(10, 20)); } if (ImGui::BeginPopup(destroy_component_popup_name(type))) { if (ImGui::Button("Delete")) { entity_destroy_component_action(editor.actions, component_id, selected_id); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } else { end_diff(editor.actions, diff_util, "Edited Property"); } ImGui::EndGroup(); } if (ImGui::Button("Add Component")) { ImGui::OpenPopup("createComponent"); } if (ImGui::BeginPopup("createComponent")) { ImGui::InputText("filter", filter); for (uint i = 0; i < MAX_COMPONENTS; i++) { refl::Struct* type = world.component_type[i]; if (!type || (1ull << i) & arch) continue; if (!((string_view)type->name).starts_with_ignore_case(filter)) continue; if (ImGui::Button(type->name.c_str())) { entity_create_component_action(editor.actions, i, selected_id); ImGui::CloseCurrentPopup(); } } ImGui::EndPopup(); } } } ImGui::End(); }
29.990099
185
0.685815
[ "render", "vector" ]
b19cd8b4d8281d0d925525e3bf873d6cc756eb39
2,481
cc
C++
mysql-server/plugin/x/tests/driver/processor/compress_single_message_block_processor.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/plugin/x/tests/driver/processor/compress_single_message_block_processor.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/plugin/x/tests/driver/processor/compress_single_message_block_processor.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, * as designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plugin/x/tests/driver/processor/compress_single_message_block_processor.h" #include <string> #include <vector> #include "my_dbug.h" #include "plugin/x/tests/driver/common/utils_string_parsing.h" Block_processor::Result Compress_single_message_block_processor::feed( std::istream &input, const char *linebuf) { std::string helper_buffer; const char *line_to_process = linebuf; if (!is_eating()) { std::vector<std::string> args; const char *command_dump = "-->compress_and_send"; aux::split(args, linebuf, " ", true); if (3 != args.size()) return Result::Not_hungry; if (args[0] != command_dump || args[2] != "{") return Result::Not_hungry; helper_buffer = args[1] + " {"; line_to_process = helper_buffer.c_str(); } return Send_message_block_processor::feed(input, line_to_process); } int Compress_single_message_block_processor::process( const xcl::XProtocol::Client_message_type_id msg_id, const xcl::XProtocol::Message &message) { DBUG_TRACE; auto error = m_context->m_connection->active_xprotocol()->send_compressed_frame( msg_id, message); if (error) { if (!m_context->m_expected_error.check_error(error)) return 1; } else { if (!m_context->m_expected_error.check_ok()) return 1; } return 0; }
34.458333
84
0.731157
[ "vector" ]
b19f613d4c93b9d8fe3705dd21a03579383d84fd
179,860
cpp
C++
Eudora71/EuImap/src/ImapMailbox.cpp
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
1
2019-06-15T17:46:11.000Z
2019-06-15T17:46:11.000Z
Eudora71/EuImap/src/ImapMailbox.cpp
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
null
null
null
Eudora71/EuImap/src/ImapMailbox.cpp
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
null
null
null
// imapfol.cpp: implementation of the CImapMailbox class. // // Functions to add IMAP mailboxes to Mailboxes and Transfer menus. // For WIN32, mailboxes are also added to the tree control. // // Copyright (c) 1997-2000 by QUALCOMM, Incorporated /* Copyright (c) 2016, Computer History Museum All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) 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 Computer History Museum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // #include "stdafx.h" #ifdef IMAP4 // Only for IMAP. #include <fcntl.h> #include "rs.h" #include "address.h" #include "summary.h" #include "doc.h" #include "fileutil.h" #include "resource.h" #include "tocdoc.h" #include "tocview.h" #include "tocframe.h" #include "msgdoc.h" #include "cursor.h" #include "progress.h" #include "font.h" #include "station.h" #include "utils.h" #include "header.h" #include "mime.h" #include "msgutils.h" #include "guiutils.h" #include "filtersd.h" #include "persona.h" #include "QCWorkerThreadMT.h" #ifdef WIN32 #include "mainfrm.h" #endif #include "eudora.h" #include "QCMailboxDirector.h" #include "QCMailboxCommand.h" #include "QCImapMailboxCommand.h" #include "imap.h" #include "ImapTypes.h" #include "ImapSum.h" #include "ImapSettings.h" #include "imapgets.h" #include "imapjournal.h" #include "ImapResyncer.h" #include "ImapMailbox.h" #include "ImapAccount.h" #include "ImapAccountMgr.h" #include "ImapMlistMgr.h" #include "ImapAppend.h" #include "imapmime.h" #include "pop.h" #include "ImapDownload.h" #include "ImapFiltersd.h" #include "ImapMailMgr.h" #include "ImapChecker.h" #include "ImapConnectionMgr.h" #include "SearchCriteria.h" #include "searchutil.h" #include "StatMng.h" // #include "DebugNewHelpers.h" // We need to extern this - yuck!! extern QCMailboxDirector g_theMailboxDirector; #ifdef EXPIRING // The Evaluation Time Stamp object #include "timestmp.h" extern CTimeStamp g_TimeStamp; #endif // =============== Internal function declarations ===============// BOOL DoingMinimalDownload (CImapMailbox *pImapMailbox); BOOL CopyTextFromTmpMbx (CTocDoc* pTocDoc, CSummary* pSum); void TerminateProgress (BOOL bWePutProgressUp, BOOL bWasInProgress); LPCSTR GetNextUidChunk (LPCSTR pStart, CString& szChunk); TCHAR FigureOutDelimiter(CImapAccount *pAccount); // ===============================================================// // Internal data // constants: const unsigned long ImapMboxVersion = 0x0100; // Version 1.00. const long InfMboxPathSize = 256; const long InfColumnSize = 48; const long InfImapNameSize = 256; const long InfDelimiterFieldSize = 4; const char comma = ','; const int MAX_UIDS_PER_COMMAND = 60; // backed down from 100 to cooperate with worldmail -jdboyd // char *pImapShortHeaderFields = "Date,Subject,From,Sender,Reply-to,To,Priority, Content-Type, Mime-Version"; char *pImapShortHeaderFields = "Date,Subject,Reply-to,From,X-Priority,Importance,Content-Type"; //char *pImapShortHeaderFields = "Date,Subject,Reply-to,From,X-Priority,Importance,Content-Type,Mime-Version,Content-Disposition"; //We will probably never need the Mime-Version and/or Content-Disposition . This was added fot the plugin sake. // Macros #define PARTIAL 0x8000 #define HAS_UNREAD 0x4000 #define NO_INFERIORS 0x2000 #define NO_SELECT 0x1000 #define MARKED 0x0800 #define UNMARKED 0x0400 // Local buffer size. #ifdef MAXBUF #undef MAXBUF #endif #define MAXBUF 2048 // Re-entrancy class to prevent multiple attempts at logging into the same server. // Note: Al this is done in the main thread so we don't need to a synchronization // object. However, we may have re-entrancy problems so we need to guard // against this. // class CLoginLock { public: CLoginLock(CImapMailbox* pImapMailbox); ~CLoginLock(); BOOL WeGotTheLock() { return m_bWeGotTheLock; } private: CImapMailbox* m_pImapMailbox; BOOL m_bWeGotTheLock; }; CLoginLock::CLoginLock(CImapMailbox* pImapMailbox) : m_pImapMailbox (pImapMailbox) { m_bWeGotTheLock = FALSE; // m_PrevPreviewState = TRUE; if (pImapMailbox) { #if 0 // Not necessary. // Disable (another?) preview while we're doing this: // m_PrevPreviewState = pImapMailbox->PreviewAllowed(); pImapMailbox->SetPreviewAllowed (FALSE); #endif // if ( !pImapMailbox->IsLoginBusy() ) { pImapMailbox->SetLoginBusy(TRUE); m_bWeGotTheLock = TRUE; } } } CLoginLock::~CLoginLock() { if (m_pImapMailbox) { #if 0 // Not necessary m_pImapMailbox->SetPreviewAllowed (m_PrevPreviewState); #endif if (m_bWeGotTheLock) { m_pImapMailbox->SetLoginBusy(FALSE); } } } //=================================================================================// //============================== CImapMailbox =====================================// CImapMailbox::CImapMailbox() : m_AccountID(0), m_pImap(NULL), m_pTocDoc(NULL) { InitAttributes(); } CImapMailbox::CImapMailbox(ACCOUNT_ID AccountID) : m_AccountID(AccountID), m_pImap(NULL), m_pTocDoc(NULL) { InitAttributes(); // Grab settings for this account: GrabSettings(); } // InitAttributes [PRIVATE] // // Single method called from both constructors to initialize attributes. This way, // we don't have to duplicate. // void CImapMailbox::InitAttributes() { m_Delimiter = 0; // For this folder hierarchy. m_bHasUnread = FALSE; // If has unread mesages. m_bPartial = FALSE; m_bNoInferiors = TRUE; // If can never contain other folders. m_bNoSelect = FALSE; // If cannot be selected. m_bMarked = FALSE; m_bUnMarked = FALSE; // Don't know mailbox type just yet. // m_Type = IMAP_MAILBOX; // Default. m_Uidvalidity = 0; m_NumberOfMessages = 0; m_UIDHighest = 0; // Set the context of the contained journal and resyncer classes. m_Journaler.SetMailbox(this); m_Resyncer.SetMailbox(this); m_bModified = FALSE; m_bNeedsUpdateFromTemp = FALSE; m_bReadOnly = FALSE; m_bExpunged = FALSE; m_bJustCheckedMail = FALSE; // Allow preview unless we say no. // m_bPreviewAllowed = TRUE; m_bAlreadyCheckingMail = FALSE; m_bForceResync = FALSE; m_bTocWasJustRebuilt = FALSE; m_bUidValidityChanged = FALSE; m_pImapSettings = NULL; // m_bLoginBusy = FALSE; m_pTocDoc = NULL; } // The CImapConnection will close the stream. // Important: Don't call "Close" at this point!! // CImapMailbox::~CImapMailbox () { // Close the CImapConnection if there's one. // if (m_pImap) { Close(); m_pImap = NULL; } if (m_pImapSettings) delete m_pImapSettings; } // ResetAttributes [PUBLIC] // FUNCTION // Reset all attributes to what they would be at instantiation time. // NOTE: Leave the account context intact. // END FUNCTION void CImapMailbox::ResetAttributes() { m_Type = IMAP_MAILBOX; // Default. m_Uidvalidity = 0; // Invalid. m_NumberOfMessages = 0; m_UIDHighest = 0; m_ImapName.Empty(); m_Dirname.Empty(); // m_AccountID = 0; // Leave account ID as is. m_Delimiter = 0; // For this folder hierarchy. m_bHasUnread = FALSE; // If has unread mesages. m_bPartial = FALSE; m_bNoInferiors = TRUE; // If can never contain other folders. m_bNoSelect = FALSE; // If cannot be selected. m_bMarked = FALSE; m_bUnMarked = FALSE; // Set the context of the contained journal and resyncer classes. m_Journaler.SetMailbox(this); m_Resyncer.SetMailbox(this); m_bModified = FALSE; m_bNeedsUpdateFromTemp = FALSE; m_bReadOnly = FALSE; m_bUidValidityChanged = FALSE; // Leave the contained CImapConnection's attributes as-is. } // Copy [public] // FUNCTION // Copy stuff from the given CImapMailbox. // END FUNCTION void CImapMailbox::Copy (CImapMailbox *pImapMailbox) { if (!pImapMailbox) return; m_Uidvalidity = pImapMailbox->GetUidvalidity (); m_NumberOfMessages = pImapMailbox->GetNumberOfMessages (); m_UIDHighest = pImapMailbox->GetUIDHighest (); SetImapType ( pImapMailbox->GetImapType() ); SetImapName ( pImapMailbox->GetImapName() ); SetDirname ( pImapMailbox->GetDirname() ); SetAccountID ( pImapMailbox->GetAccountID() ); SetDelimiter ( pImapMailbox->GetDelimiter() ); SetHasUnread ( pImapMailbox->HasUnread() ); SetNoInferiors ( pImapMailbox->IsNoInferiors() ); SetNoSelect ( pImapMailbox->IsNoSelect() ); SetMarked ( pImapMailbox->IsMarked() ); SetUnMarked ( pImapMailbox->IsUnMarked() ); SetAutoSync ( pImapMailbox->IsAutoSync() ); SetModifiedFlag ( pImapMailbox->IsModified() ); m_bUidValidityChanged = pImapMailbox->m_bUidValidityChanged; } // InitializeLocalStorage // FUNCTION // Make sure the mailbox directory exists and contains at least stubs of the necessary files. // If "Clean", delete messages from the MBX file, etc. // END FUNCTION BOOL CImapMailbox::InitializeLocalStorage(BOOL Clean) { // Create the directory housing the mailbox. if ( CreateMailboxDirectory (GetDirname()) ) { // Create the MBX file if it doesn't exist. CreateMbxFile (GetDirname()); // Create the attachment directory. CreateAttachDir (GetDirname()); // Write imap info. WriteImapInfo (Clean == TRUE); // Initialize the journal database. m_Journaler.SetMailbox(this); m_Journaler.InitializeDatabase (TRUE); // And the resyncer too. m_Resyncer.SetMailbox(this); m_Resyncer.InitializeDatabase (TRUE); return TRUE; } return FALSE; } // // FUNCTION // Reads the IMAP mailbox's info file and fill in ImapName, UIDVALIDITY, etc. // END FUNCTION // NOTES // m_AccountID and m_Dirname MUST have already been set. // END NOTES BOOL CImapMailbox::ReadImapInfo () { JJFileMT in; CString InfFilePath; unsigned long ulValue; char buf[1024]; BOOL bResult = FALSE; if (m_AccountID == 0 || m_Dirname.IsEmpty()) return FALSE; // Format the info filename: GetInfFilePath (m_Dirname, InfFilePath); // Make sure the file exists. if ( !SUCCEEDED ( in.Open(InfFilePath, O_RDONLY) ) ) return FALSE; // Get the version. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // Make sure it's correct. if (ulValue != ImapMboxVersion) goto end; // infModTime (4 bytes) - leave blank. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // Full path to local mailbox directory (256 bytes) // BUG: Don't use this info here because m_Dirname is alread set. if ( !SUCCEEDED (in.Read(buf, InfMboxPathSize) ) ) goto end; // m_Dirname = buf; // infFlags ( 4 bytes) if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // Set object attributes. m_bHasUnread = (ulValue & HAS_UNREAD) > 0; m_bPartial = (ulValue & PARTIAL) > 0; m_bNoInferiors = (ulValue & NO_INFERIORS) > 0; m_bNoSelect = (ulValue & NO_SELECT) > 0; m_bMarked = (ulValue & MARKED) > 0; m_bUnMarked = (ulValue & UNMARKED) > 0; // infColumns (48 bytes) - ignore; if ( !SUCCEEDED (in.Read(buf, InfColumnSize) ) ) goto end; // infType2SelColumn ( 4 bytes) - ignore. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // infLastOpened 4 bytes) - ignore. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // UIDVALIDITY (4 bytes); if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; m_Uidvalidity = ulValue; // infNumberOfMessages 4 bytes. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; m_NumberOfMessages = ulValue; // infUIDHighest 4 bytes. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; m_UIDHighest = ulValue; // infI4Server 4 bytes - ignore. if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // Mailbox ID 4 bytes - ignore if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // infI4MailboxName, 256 bytes. if (! SUCCEEDED (in.Read(buf, InfImapNameSize) ) ) goto end; m_ImapName = buf; // infLastResynced 4 bytes - ignore if (!SUCCEEDED ( in.Get(&ulValue) ) ) goto end; // Delimiter char 4 bytes. if (! SUCCEEDED (in.Read(buf, InfDelimiterFieldSize) ) ) goto end; m_Delimiter = buf[0]; SetModifiedFlag(FALSE); bResult = TRUE; end: in.Close(); return bResult; } // // FUNCTION // Writes the IMAP mailbox's info to the info file // If Overwrite is FALSE and the file exists, leave it as is. // END FUNCTION // NOTES // Must at least have a valid account ID and mailbox dir, AND the mailbox must exist. // END NOTES BOOL CImapMailbox::WriteImapInfo (BOOL Overwrite) { JJFileMT out; CString InfFilePath; unsigned long ulValue; char buf[1024]; const char *p; if (m_AccountID == 0 || m_Dirname.IsEmpty()) return FALSE; // Format the info filename: GetInfFilePath (m_Dirname, InfFilePath); if (FileExistsMT(InfFilePath) && !Overwrite) return TRUE; // Try to open: if ( !SUCCEEDED (out.Open(InfFilePath, O_CREAT | O_TRUNC | O_WRONLY) ) ) return (FALSE); // Write version (4 bytes) ulValue = ImapMboxVersion; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infModTime (4 bytes) - leave blank. ulValue = 0; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // Full path to local mailbox directory (256 bytes) memset(buf, 0, InfMboxPathSize); p = GetDirname(); if (p) strcpy(buf, p); if (!SUCCEEDED (out.Put(buf, InfMboxPathSize) ) ) return (FALSE); // infFlags ( 4 bytes) ulValue = 0; if (m_bHasUnread) ulValue |= HAS_UNREAD; if (m_bPartial) ulValue |= PARTIAL; if (m_bNoInferiors) ulValue |= NO_INFERIORS; if (m_bNoSelect) ulValue |= NO_SELECT; if (m_bMarked) ulValue |= MARKED; if (m_bUnMarked) ulValue |= UNMARKED; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infColumns (48 bytes) - ignore; memset(buf, 0, InfColumnSize); if (!SUCCEEDED (out.Put(buf, InfColumnSize) ) ) return (FALSE); // infType2SelColumn ( 4 bytes) - ignore. ulValue = 0; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infLastOpened 4 bytes) - ignore. ulValue = 0; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // UIDVALIDITY (4 bytes); ulValue = m_Uidvalidity; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infNumberOfMessages 4 bytes. ulValue = m_NumberOfMessages; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infUIDHighest 4 bytes. ulValue = m_UIDHighest; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infI4Server 4 bytes ulValue = 0; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // Mailbox ID 4 bytes ulValue = 0; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // infI4MailboxName, 256 bytes. memset(buf, 0, InfImapNameSize); p = GetImapName(); if (p) strcpy(buf, GetImapName()); if (!SUCCEEDED (out.Put(buf, InfImapNameSize) ) ) return (FALSE); // infLastResynced 4 bytes. ulValue = 0; if ( !SUCCEEDED (out.Put(ulValue) ) ) return (FALSE); // Delimiter char 4 bytes. memset (buf, 0, InfDelimiterFieldSize); buf[0] = m_Delimiter; if (SUCCEEDED (out.Put(buf, InfDelimiterFieldSize) ) ) return (FALSE); SetModifiedFlag(FALSE); return (TRUE); } // GetSettingsShort [PUBLIC] // // Interface to internal settings object. // short CImapMailbox::GetSettingsShort (UINT StringNum) { if (!m_pImapSettings) return 0; return m_pImapSettings->GetSettingsShort (StringNum); } // GetSettingsLong [PUBLIC] // // Interface to internal settings object. // long CImapMailbox::GetSettingsLong (UINT StringNum) { if (!m_pImapSettings) return 0; return m_pImapSettings->GetSettingsLong (StringNum); } // GetSettingsString [PUBLIC] // // Interface to internal settings object. // Note: Returns a const pointer. // LPCSTR CImapMailbox::GetSettingsString (UINT StringNum, char *Buffer /* = NULL */, int len /* = -1 */) { if (!m_pImapSettings) return NULL; return m_pImapSettings->GetSettingsString (StringNum, Buffer, len); } // GetLogin [PUBLIC] // // Does the initial setup before we attempt to open the mailbox. // This MUST be performed in the main thread. // HRESULT CImapMailbox::GetLogin () { HRESULT hResult = S_OK; // This MUST be called in the main thread!! // ASSERT ( ::IsMainThreadMT() ); // Don't allow this if eudora isn't fully initialized: // if ( !CImapMailMgr::AppIsInitialized () ) { return E_FAIL; } // Check re-entrancy flag: // CLoginLock lock (this); if ( !lock.WeGotTheLock() ) { return HRESULT_MAKE_BUSY; } #ifdef EXPIRING // this is the first line of defense if ( g_TimeStamp.IsExpired0() ) { AfxGetMainWnd()->PostMessage(WM_USER_EVAL_EXPIRED); return HRESULT_MAKE_CANCEL; } #endif // Get info from the ACCOUNT if (m_AccountID == 0) return E_FAIL; // Set the friendly name:. QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); return E_FAIL; } m_FriendlyName = pImapCommand->GetName(); // If m_pImap is NULL, we must create or acquire one. // if (!m_pImap) { // Note: this lock the connection so we're the only one that can use it. // hResult = AcquireNetworkConnection (); } if (!m_pImap) { hResult = E_FAIL; ASSERT (0); return E_FAIL; } // If already selected, no need to continue. // if ( m_pImap->IsSelected() ) return S_OK; // If the connection object is too busy to deal with our request, we must fail. // if (m_pImap->IsTooBusy()) { return E_FAIL; } // If the connection is not conencted, we need to go get new password/login. // // If the CImapConnection is not connected, we may need to get (possibly) // new login and password. // CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) return E_FAIL; // Get a login and password for this account. // CString szLogin, szPassword; if ( !pAccount->Login (szLogin, szPassword) ) { return HRESULT_MAKE_CANCEL; } m_pImap->SetLogin (szLogin); m_pImap->SetPassword (szPassword); // Success. Note: we haven't logged into the IMAP server! We've only done // some main-thread initializations. // return S_OK; } // OpenMailbox [PUBLIC] // NOTES // Sometimes we want to open the connection to the server mailbox without // updating it. // It "bSilent" is TRUE, don't put up any progress stuff. // END NOTES HRESULT CImapMailbox::OpenMailbox (BOOL bSilent /* = FALSE */) { HRESULT hResult = S_OK; if ( ::IsMainThreadMT() ) { // Did user cancel login?? // if ( !SUCCEEDED (GetLogin()) ) return HRESULT_MAKE_CANCEL; } // Check re-entrancy flag: // CLoginLock lock (this); if ( !lock.WeGotTheLock() ) { return HRESULT_MAKE_BUSY; } // Must have one of these: // if (!m_pImap) { hResult = E_FAIL; ASSERT (0); return E_FAIL; } // If already selected, no need to continue. // if ( m_pImap->IsSelected() ) return S_OK; // If the connection object is too busy to deal with our request, we must fail. // if (m_pImap->IsTooBusy()) { return E_FAIL; } // We need our account below. // CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) return E_FAIL; // The following can be performed in a background thread. // // We can put up a progress window here! // BOOL bWasInProgress = FALSE; if ( ::IsMainThreadMT() && !bSilent ) { CString buf; if (InProgress) { bWasInProgress = TRUE; PushProgress(); } buf.Format (CRString(IDS_IMAP_OPENING_MAILBOX), m_FriendlyName); MainProgress(buf); } // Open the connection in the main thread. If the connection is already open, // CImapConnection::OpenMailbox is smart enough not to re-open it. // hResult = m_pImap->OpenMailbox (m_ImapName); // If we're doing this in the main thread, update saved info here. // if ( ::IsMainThreadMT() ) { if ( SUCCEEDED (hResult) ) WriteImapInfo (TRUE); // Close progress window if we had one. Close it before we put up // any error message. // if ( !bSilent) { if (bWasInProgress) PopProgress (); else CloseProgress(); } } return hResult; } // FUNCTION // CLose the connection to the IMAP server. // This calls Release on the connection object. // // NOTE: After this, the m_pImap object is no longer valid. We // MUST call AcquireNetworkConnection() again if we want another connection. //. // END FUNCTION HRESULT CImapMailbox::Close() { HRESULT hResult = S_OK; // NOTE: Don't update the imap info file at this time!! // if (m_pImap) { // We no longer own the connection. // hResult = GetImapConnectionMgr()->Release (m_pImap); m_pImap = NULL; } return hResult; } ///////////////////////////////////////////////////////////////////////// // OpenOnDisplay [PUBLIC] // // This method is called only when the mailbox is first opened!!! // See CTocDoc::Display() ///////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::OpenOnDisplay (CTocDoc *pTocDoc) { HRESULT hResult = S_OK; // Sanity: if (!pTocDoc) return E_INVALIDARG; // // Set the frame's name to <name (<Account>)> // SetFrameName (pTocDoc); // Put up cursor while we're doing this. // CCursor cur; // If the application hasn't yet initialized, don't continue. // if ( !CImapMailMgr::AppIsInitialized() ) { return S_OK; } // If we're offline, don't initiate a connection. // if ( !IsSelected() && GetIniShort(IDS_INI_CONNECT_OFFLINE) ) { return HRESULT_MAKE_OFFLINE; } // Don't allow preview at this time. // SetPreviewAllowed (FALSE); #if 0 // // Open the connection before we go any further. // hResult = OpenMailbox (FALSE); #endif // Don't open the mailbox here. Just do the initializations. // hResult = GetLogin(); if ( !SUCCEEDED (hResult) ) { SetPreviewAllowed (TRUE); // Attempt to do a preview in case the summary is already downloaded. pTocDoc->InvalidateCachedPreviewSummary(NULL, true); return hResult; } if (::EscapePressed()) { SetPreviewAllowed (TRUE); return HRESULT_MAKE_CANCEL; } bool bCheckMail = true; CImapAccount *pAccount = g_ImapAccountMgr.FindAccount(m_AccountID); if (pAccount) { bCheckMail = !pAccount->ActionsQueuedForMailbox(this); } if (bCheckMail) { // If we didn't just do a checkmail, do one as we open. if ( !JustCheckedMail () ) { // Don't allow re-entrant check mail on the same mailbox. // SetJustCheckedMail (TRUE); // Set a time to do the check mail. // // If this is Inbox, set the ForceResync instance flag and // call the global GetMail routine out in pop.cpp. // CString szName = GetImapName (); szName.TrimLeft (); szName.TrimRight (); if ( IsInbox (szName) ) { m_bForceResync = TRUE; // Get this personality's name. // CString szPersona; pAccount->GetName (szPersona); LPSTR pszPersonaName = DEBUG_NEW_NOTHROW char[ szPersona.GetLength() + 4 ]; if (pszPersonaName) { // Note: Must terminate this string with double nuls. strcpy (pszPersonaName, (LPCSTR)szPersona); pszPersonaName[szPersona.GetLength() + 1] = '\0'; GetMail (kManualMailCheckBits, pszPersonaName, FALSE/*bFullMailCheck*/); // Unset this: m_bForceResync = FALSE; hResult = S_OK; // Free it: delete[] pszPersonaName; } } else { // // Just force a resync: // // hResult = CheckMail ( pTocDoc, FALSE, TRUE); // hResult = ResyncMailbox (pTocDoc, FALSE, 0xFFFFFFFF, FALSE); hResult = GetImapMailMgr()->DoManualResync (pTocDoc, FALSE, // BOOL bCheckMail /* = FALSE */, FALSE, // BOOL bDownloadedOnly /* = TRUE */, TRUE); // BOOL bInBackground /* = FALSE */) } } } // Reset so we catch it next time. SetJustCheckedMail (FALSE); // Make sure!! // SetPreviewAllowed (TRUE); pTocDoc->InvalidateCachedPreviewSummary(NULL, true); return hResult; } // DoManualResync [PUBLIC] // // External interface to a manual resync. operation. // // Resync what we currently have then do a check mail. // // HISTORY: // JOK - 1/21/98. Added "bCheckMail" parameter. // HRESULT CImapMailbox::DoManualResync (CTocDoc *pTocDoc, BOOL bCheckMail /* = FALSE */, BOOL bDownloadedOnly /* = TRUE */, BOOL bInForeGround /* = FALSE */, BOOL bDoSubMailboxes /* = FALSE */) { HRESULT hResult; if (bInForeGround) { // OFFLINE$$$ // if "Offline mode is set", must ASK if to attempt connection. // // hResult = DoForegroundResync (pTocDoc, bDownloadedOnly); } else { hResult = DoBackgroundResync (pTocDoc, bCheckMail, bDownloadedOnly, bDoSubMailboxes); } // This may have been disabled during startup: // SetPreviewAllowed (TRUE); pTocDoc->InvalidateCachedPreviewSummary(NULL, true); // If still in offline mode, clse connection behind us. // if ( GetIniShort(IDS_INI_CONNECT_OFFLINE) ) Close(); return hResult; } /////////////////////////////////////////////////////////////// // CheckNewMail [PUBLIC] // // External interface to checking for new mail. /////////////////////////////////////////////////////////////// HRESULT CImapMailbox::CheckNewMail (CTocDoc *pTocDoc, BOOL bSilent /* = FALSE */) { HRESULT hResult = S_OK; BOOL bWeOpenedConnection = FALSE; // Sanity: if (!pTocDoc) return E_INVALIDARG; // Open the connection if the connection is not already open, // If we dropped the connection for whatever reason, try to re-connect. // Note: Keep tab of if we opened the connection because we may have to // close it if there's no view. // if (!IsSelected()) { hResult = OpenMailbox (FALSE); if (! SUCCEEDED (hResult) ) { return hResult; } // Flag the we opened the connection. // bWeOpenedConnection = TRUE; } // Call the internal routine. Note" Don't do a re-sync!! hResult = CheckMail ( pTocDoc, bSilent, FALSE); // If no window and we opened the connection, close it. // CTocView *pView = pTocDoc->GetView (); // If we're offline, close the connection again. // if ( GetIniShort(IDS_INI_CONNECT_OFFLINE) ) { Close(); } else if (bWeOpenedConnection && !pView) { Close(); } // Redraw the complete TOC: // if (pView) pView->Invalidate(); return hResult; } // DownloadSingleMessage [PUBLIC] // // External interface to downloading a new message. // Accepts a CSummary object. Since we deal only with CImapSum objects internally, // we need to instantiate a new CImapSum object, copy info from the CSummary into // it, do the download, then copy back stuff that may have changed. // HRESULT CImapMailbox::DownloadSingleMessage (CTocDoc *pTocDoc, CSummary *pSum, BOOL bDownloadAttachments, BOOL bToTmpMbx /* = FALSE */) { HRESULT hResult = S_OK; // Sanity: if (! (pTocDoc && pSum) ) return E_INVALIDARG; // If we're offline and not connected, don't continue. // // if ( !IsSelected() && GetIniShort(IDS_INI_CONNECT_OFFLINE) ) // { // return HRESULT_MAKE_OFFLINE; // } // INstantiate a CImapSum and copy. // CImapSum *pImapSum = DEBUG_NEW_MFCOBJ_NOTHROW CImapSum; if (!pImapSum) return E_FAIL; // Copy stuff: // pImapSum->CopyFromCSummary (pSum); // DO this manually: // pImapSum->m_SummaryDate = pSum->m_Date; // Do the download: // hResult = DownloadSingleMessage (pTocDoc, pImapSum, bDownloadAttachments, bToTmpMbx); if ( SUCCEEDED (hResult) ) { // If we had a date in the original summary, preserve that. // long Seconds = pSum->m_Seconds; pImapSum->CopyToCSummary (pSum); if (Seconds) pSum->m_Seconds = Seconds; } // No longer need pImapSum. delete pImapSum; return hResult; } // DoForegroundResync [PRIVATE] // // Force a full resync of the mailbox, and do it in the foreground. // If it's INBOX, don't do any filtering. // HRESULT CImapMailbox::DoForegroundResync (CTocDoc *pTocDoc, BOOL bDownloadedOnly /* = TRUE */) { HRESULT hResult = S_OK; BOOL bWeOpenedConnection = FALSE; // Sanity: if (!pTocDoc) return E_INVALIDARG; // Open the connection if the connection is not already open, // If we dropped the connection for whatever reason, try to re-connect. // Note: Keep tab of if we opened the connection because we may have to // close it if there's no view. // if (!IsSelected()) { hResult = OpenMailbox (FALSE); if (!SUCCEEDED (hResult) ) { return hResult; } // Flag the we opened the connection. // bWeOpenedConnection = TRUE; } // If this is set to TRUE, only resync what we've already downloaded. if (bDownloadedOnly) { // Do a resync of what we have already seen. // hResult = ResyncMailbox (pTocDoc, FALSE, 0, TRUE); } else { // Do a resync of everything. // hResult = ResyncMailbox (pTocDoc, FALSE, 0xFFFFFFFF, FALSE); } // If no window and we opened the connection, close it. // CTocView *pView = pTocDoc->GetView (); if (bWeOpenedConnection && !pView) { Close(); } else { // Make sure tell the IMAP agent to update it's // // RecreateMessageMap(); } // Redraw the complete TOC: // if (pView) pView->Invalidate(); return hResult; } // DoBackgroundResync [PRIVATE] // // Initiate a background resync. // HRESULT CImapMailbox::DoBackgroundResync (CTocDoc *pTocDoc, BOOL bCheckMail /* = FALSE */, BOOL bDownloadedOnly /* = TRUE */, BOOL bDoSubMailboxes /* = FALSE */) { HRESULT hResult = S_OK; // BOOL bWeOpenedConnection = FALSE; // Sanity: if (!pTocDoc) return E_INVALIDARG; // Open the connection if the connection is not already open, // If we dropped the connection for whatever reason, try to re-connect. // Note: Keep tab of if we opened the connection because we may have to // close it if there's no view. // if (!IsSelected()) { // Just get login info. hResult = GetLogin(); // hResult = OpenMailbox (FALSE); if (!SUCCEEDED (hResult) ) { return hResult; } // Flag the we opened the connection. // // bWeOpenedConnection = TRUE; } // If this is Inbox and the "bCheckMail" flag is set, // set the ForceResync instance flag and // call the global GetMail routine out in pop.cpp. // CString szName = GetImapName (); szName.TrimLeft (); szName.TrimRight (); BOOL bIsInbox = IsInbox (szName); if ( bIsInbox && bCheckMail) { m_bForceResync = TRUE; CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (pAccount) { // Get this personality's name. // CString szPersona; pAccount->GetName (szPersona); LPSTR pszPersonaName = DEBUG_NEW_NOTHROW char[ szPersona.GetLength() + 4 ]; if (pszPersonaName) { // Note: Must terminate this string with double nuls. strcpy (pszPersonaName, (LPCSTR)szPersona); pszPersonaName[szPersona.GetLength() + 1] = '\0'; GetMail(kManualMailCheckBits, pszPersonaName, FALSE/*bFullMailCheck*/); // Unset this: m_bForceResync = FALSE; hResult = S_OK; // Free it: delete[] pszPersonaName; } } } // If this is set to TRUE, only resync what we've already downloaded. else if (bDownloadedOnly) { // Do a resync of what we have already seen. // hResult = GetImapMailMgr()->DoManualResync (pTocDoc, FALSE, // BOOL bCheckMail /* = FALSE */, bDownloadedOnly, // BOOL bDownloadedOnly /* = TRUE */, TRUE, // BOOL bInBackground /* = FALSE */, bDoSubMailboxes); // BOOL bDoSubMailboxes /* = FALSE */) } // else if (!bIsInbox) { // Resync of a non-INBOX mailbox - we want to retrieve everything! // hResult = GetImapMailMgr()->DoManualResync (pTocDoc, FALSE, // BOOL bCheckMail /* = FALSE */, FALSE, // BOOL bDownloadedOnly /* = TRUE */, TRUE, // BOOL bInBackground /* = FALSE */, bDoSubMailboxes); // BOOL bDoSubMailboxes /* = FALSE */) } else { // Do a resync of everything. // hResult = GetImapMailMgr()->DoManualResync (pTocDoc, FALSE, // BOOL bCheckMail /* = FALSE */, FALSE, // BOOL bDownloadedOnly /* = TRUE */, TRUE, // BOOL bInBackground /* = FALSE */, bDoSubMailboxes); // BOOL bDoSubMailboxes /* = FALSE */) } // If no window and we opened the connection, close it. // CTocView *pView = pTocDoc->GetView (); #if 0 // The background task may still be in progress. // if (bWeOpenedConnection && !pView) Close(); #endif // JOK // Redraw the complete TOC: // if (pView) pView->Invalidate(); return hResult; } ////////////////////////////////////////////////////////////////////////////// // CheckMail [PRIVATE] // // NOTES // Checks first for a changed UIDVALIDITY. If it has changed, re-download // all messages up to m_UIDHighest without filtering. // // // If UIDVALIDITY hasn't changed, then use m_UIDHighest to determine if there are // new messages. Download and filter any new messages. If an EXPUNGE occured // as a result of filtering, we have to do a resync, otherwise, do a re-sync // only if "bForceResync" is TRUE. // // NOTE: Must have a TOC!! // // // END NOTES ////////////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::CheckMail (CTocDoc *pTocDoc, BOOL bSilent /* = FALSE */, BOOL bForceResync /* = FALSE */) { HRESULT hResult = S_OK; CString buf; // Scratch buffer. BOOL bWasInProgress = FALSE; BOOL bWeOpenedConnection = FALSE; CTocView *pView = NULL; unsigned long NewUidvalidity; BOOL bWePutProgressUp = FALSE; // Must have a TOC. if (!pTocDoc) { ASSERT (0); return E_INVALIDARG; } // Try to thwart a preview. // pTocDoc->SetPreviewableSummary (NULL); // Get info from the ACCOUNT if (m_AccountID == 0) return E_FAIL; // Get the account's name. CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) { ASSERT (0); return E_FAIL; } // Prevent re-entrance problems!! if ( AlreadyCheckingMail () ) { return S_OK; } // !! Otherewise, we're the one and only. Make sure un-set it before we leave!!! // SetAlreadyCheckingMail (TRUE); CString szPersona; pAccount->GetName (szPersona); // // See if the mailbox is open: // pView = pTocDoc->GetView (); // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); // We can put up a progress window here! if ( ::IsMainThreadMT() && !bSilent ) { if (InProgress) { bWasInProgress = TRUE; PushProgress(); } buf.Format (CRString(IDS_IMAP_UPDATING_MAILBOX), pTocDoc->Name()); MainProgress(buf); bWePutProgressUp = TRUE; } // Open the connection if the connection is already open, // If we dropped the connection for whatever reason, try to re-connect. // if (!IsSelected()) { hResult = OpenMailbox (bSilent); if (! SUCCEEDED (hResult) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); // MAKE SURE TO DO THIS!!! SetAlreadyCheckingMail (FALSE); return hResult; } // Flag that we opened the connection. We might want to close it when we leave. bWeOpenedConnection = TRUE; } // Must have a m_pImap now. // if (!m_pImap) { TerminateProgress (bWePutProgressUp, bWasInProgress); return E_FAIL; } // Change the progress message back. if ( bWePutProgressUp ) { buf.Format (CRString(IDS_IMAP_UPDATING_MAILBOX), pTocDoc->Name()); MainProgress(buf); } // // Reset hResult back to E_FAIL so we can detect success below. // hResult = E_FAIL; // Update the READ/WRITE state. BOOL bIsReadOnly = m_pImap->IsReadOnly(); // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); TerminateProgress (bWePutProgressUp, bWasInProgress); // Close connection? if (bWeOpenedConnection && !pView) { Close(); } // MAKE SURE TO DO THIS!!! SetAlreadyCheckingMail (FALSE); return E_FAIL; } // If the R/W status has changed, reflect this. if (bIsReadOnly != IsReadOnly()) { SetReadOnly (bIsReadOnly); pImapCommand->SetReadOnly (bIsReadOnly); // Update mailbox display. g_theMailboxDirector.ImapNotifyClients (pImapCommand, CA_IMAP_PROPERTIES, NULL); } // Make sure the local mailbox directory exists. "CreateMailboxDirectory()" will return TRUE // if the directory already exists as a direcotry. if ( ! VerifyCache (bSilent) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); // Close connection? if (bWeOpenedConnection && !pView) { Close(); } // MAKE SURE TO DO THIS!!! SetAlreadyCheckingMail (FALSE); return E_FAIL; } // Set this here to prevent a recursive check mail if the TOC hasn't yet been opened // in a view. SetJustCheckedMail (TRUE); // Reset this: m_bUidValidityChanged = FALSE; // Send a Noop so we get any pending EXISTS messages. m_pImap->Noop (); // How many messages do we now think we have? // Update m_NumberOfMessages only if we succeed. // unsigned long nMsgs = 0; hResult = m_pImap->GetMessageCount(nMsgs); if ( !SUCCEEDED (hResult) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); return hResult; } // Ok so far. m_NumberOfMessages = nMsgs; // Get the server's highest UID to see if it's zero. If zero, we need to // close the conection and restart it. // unsigned long ServerUidHighest = 0; hResult = m_pImap->UIDFetchLastUid(ServerUidHighest); if (::EscapePressed()) { TerminateProgress (bWePutProgressUp, bWasInProgress); return HRESULT_MAKE_CANCEL; } if ( !SUCCEEDED (hResult) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); return hResult; } if ( (m_NumberOfMessages > 0) && (ServerUidHighest == 0) ) { Close(); hResult = OpenMailbox (bSilent); if (! SUCCEEDED (hResult) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); return hResult; } // How many messages do we now think we have? // unsigned long nMsgs = 0; hResult = m_pImap->GetMessageCount(nMsgs); if ( !SUCCEEDED (hResult) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); return hResult; } // Ok so far. m_NumberOfMessages = nMsgs; } // Now that we have opened the mailbox successfully, get the UIDValidity, // hResult = m_pImap->GetUidValidity(NewUidvalidity); if ( !SUCCEEDED (hResult) ) { TerminateProgress (bWePutProgressUp, bWasInProgress); return hResult; } // Allow zero UIDVALIDITY?? // If no messages in remote mailbox, just delete our local cached. if (m_NumberOfMessages == 0) { pTocDoc->ImapRemoveAllSummaries (); } // If the UIDVALIDITY changed, we have to download everything. if (m_Uidvalidity != NewUidvalidity) { pTocDoc->ImapRemoveAllSummaries (); m_bUidValidityChanged = TRUE; // We have to redownload stuff, and we can't do filtering during // this redownload because our local "m_UIDHighest" is no longer valid. // We don't know what we previously filtered. // m_UIDHighest = 0; // Tell this to the user if it's inbox. // #if 0 // What about during a timed check mail?? // if ( IsInbox (GetImapName()) ) ErrorDialog (IDS_NOTE_IMAP_UIDVALIDITY_CHANGED, GetImapName()); #endif } // Ok. Get and filter new messages. Set the m_bExpunged flag if filtering // caused an expunge. // m_bExpunged = FALSE; BOOL bWasResynced = FALSE; hResult = GetAndFilterNewMessages (pTocDoc, bWasResynced, TRUE, bSilent); // If we were asked to force a re-sync, or if messages // were removed as part of a filter, do a re-sync of // what we got. Don't fetch any new messages at this time. // Note: "GetAndFilterNewMessages" would have updated "m_UIDHighest" // to include any new messages we already received. // // Note that a client may also force a resync by setting the member // flag "m_bForceResync". // bForceResync = bForceResync | m_bForceResync; // Remember, attempt a re-sync only if user didn't cancel. // if ( SUCCEEDED (hResult) && ( bForceResync || (m_bExpunged && !bWasResynced) ) ) { // This forces a resync only of messages we already received. // hResult = ResyncMailbox (pTocDoc, bSilent, m_UIDHighest, TRUE); } // Update stuff if we succeeded. // if ( SUCCEEDED (hResult) ) { // // Update mailbox info. // m_Uidvalidity = NewUidvalidity; // Reset this: m_bUidValidityChanged = FALSE; } // Update saved info, whether we succeeded or not. // WriteImapInfo (TRUE); // Close connection? if (bWeOpenedConnection && !pView) { Close(); } TerminateProgress (bWePutProgressUp, bWasInProgress); // MAKE SURE TO DO THIS!!! SetAlreadyCheckingMail (FALSE); return hResult; } /////////////////////////////////////////////////////////////////////////////////////////// // GetAndFilterNewMessages [PRIVATE] // // Use m_UIDHighest to get messages with a UID higher than it and filter those messages. // // On OUTPUT: Set the m_Expunged flag if filtering caused an EXPUNGE of the mailbox. // // Assume the mailbox is connected. // // NOTE: This may still cause a full resync. If it did, convey this info back to // caller by seeting "bWasResynced" to TRUE. // //////////////////////////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::GetAndFilterNewMessages (CTocDoc *pTocDoc, BOOL& bWasResynced, BOOL bDoFiltering /* = TRUE */, BOOL bSilent /* = FALSE */) { HRESULT hResult = S_OK; unsigned long NextUid = 0; // Make sure. bWasResynced = FALSE; // Sanity: if (!pTocDoc) { ASSERT (0); return E_INVALIDARG; } if (!m_pImap) { ASSERT (0); return E_FAIL; } // Get our current list of uid's from the summary. CUidMap CurrentUidMap; GetCurrentUids (pTocDoc, CurrentUidMap); // Get the highest one we have locally. unsigned long LocalUidHighest = CurrentUidMap.GetHighestUid(); unsigned long ServerUidHighest = 0; hResult = m_pImap->UIDFetchLastUid(ServerUidHighest); if ( !SUCCEEDED (hResult) ) { return hResult; } // If there are messages in the mailbox, ServerUidHighest MUST be // non-zero. // if ( (m_NumberOfMessages > 0) && (ServerUidHighest == 0) ) { ASSERT (0); return E_FAIL; } // If UIDVALIDITY was hanged, we have to redownload everything, regardless. // if (m_bUidValidityChanged) { if (ServerUidHighest > 0) { // Do a complete re-sync only of what we already have. hResult = ResyncMailbox (pTocDoc, bSilent, ServerUidHighest, FALSE); // Tell caller that we did. bWasResynced = TRUE; m_UIDHighest = ServerUidHighest; } } // Resync if user deleted local cache. else { // If the toc was rebuilt or the user deleted the local cache, resync first. // if ( m_bTocWasJustRebuilt || (m_UIDHighest != 0 && LocalUidHighest == 0) ) { // Do a complete re-sync only of what we already have. hResult = ResyncMailbox (pTocDoc, bSilent, m_UIDHighest, FALSE); if (!SUCCEEDED (hResult)) return E_FAIL; // Tell caller that we did. bWasResynced = TRUE; // Reset our flag. m_bTocWasJustRebuilt = FALSE; } // If all goes well, download the next after this. // NextUid = max (LocalUidHighest, m_UIDHighest); // We may have removed messages at the tail end of the mailbox: // NextUid = min(ServerUidHighest, NextUid); // Did user abort?? // if (EscapePressed()) { return HRESULT_MAKE_CANCEL; } // Now, Fetch only if server has higher UID. // if ( (ServerUidHighest > 0) && (ServerUidHighest > NextUid) ) { CString szSeq; CUidMap NewUidMap; szSeq.Format ("%lu:%lu", NextUid + 1, ServerUidHighest); m_pImap->FetchFlags (szSeq, &NewUidMap); // Did user cancel?? if (EscapePressed()) { hResult = HRESULT_MAKE_CANCEL; } else if (NewUidMap.GetCount() > 0) { // We need to know if filtering caused an expunge. m_bExpunged = FALSE; // Note: THis does the filtering (if it's INBOX)!! // Also: This MUST set the new m_UIDHighest. hResult = DoFetchNewMessages (pTocDoc, NewUidMap, bDoFiltering); // Note!! m_UIDHighest would have been updated in "DoFetchMessages". // Don't update it here!! } // Make sure: NewUidMap.DeleteAll (); } // Did user abort?? // if (EscapePressed()) { hResult = HRESULT_MAKE_CANCEL; } } return hResult; } // ResyncMailbox [PRIVATE] // FUNCTION // Do the dirty work of fetching the flags from the server and updating // the local mailbox cache. // // NOTE: This can NOT be called directly. // // END FUNCTION // NOTES // Assume that the connection is open. // // NOTE: This now re-sync's only up to the given "ulMaxUid". // If "ulMaxUid" is 0xFFFFFFFF, we re-sync ALL messages, unless the "bDownloadedOnly" // flag is set, in which case we only resync what was already downloaded. // Note: If "bDownloadedOnly" is set, we ignore "ulMaxUid". // // END NOTES HRESULT CImapMailbox::ResyncMailbox (CTocDoc *pTocDoc, BOOL bSilent /* = FALSE */, IMAPUID ulMaxUid /* = 0xFFFFFFFF */, BOOL bDownloadedOnly /* = TRUE */) { HRESULT hResult = S_OK; BOOL bWasInProgress = FALSE; unsigned long NewUidvalidity = m_Uidvalidity; // Must be part of a valid account. if (m_AccountID == 0) return E_FAIL; // Must have a toc. if (!pTocDoc) return E_INVALIDARG; // Get the account's name. CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) { ASSERT (0); return E_FAIL; } // Must have one of these: // if (!m_pImap) { ASSERT (0); return E_FAIL; } CString szPersona; pAccount->GetName (szPersona); // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); // Send a Noop so we get any pending EXISTS messages. m_pImap->Noop (); // Make these checks again because things may have changed. // // How many messages do we now think we have? // unsigned long nMsgs = 0; hResult = m_pImap->GetMessageCount(nMsgs); if ( !SUCCEEDED (hResult) ) { return hResult; } // Ok so far. m_NumberOfMessages = nMsgs; // Get the server's highest UID to see if it's zero. If zero, we need to // close the conection and restart it. // unsigned long ServerUidHighest = 0; hResult = m_pImap->UIDFetchLastUid(ServerUidHighest); if ( !SUCCEEDED (hResult) ) { return hResult; } // We can put up a progress window here! if ( ::IsMainThreadMT() && !bSilent ) { if (InProgress) { bWasInProgress = TRUE; PushProgress(); } CString buf; buf.Format (CRString(IDS_IMAP_RESYNCING_MAILBOX), pTocDoc->Name()); MainProgress(buf); } if ( (m_NumberOfMessages > 0) && (ServerUidHighest == 0) ) { Close(); hResult = OpenMailbox (bSilent); if (! SUCCEEDED (hResult) ) { if ( ::IsMainThreadMT() && !bSilent ) { if (bWasInProgress) PopProgress(); else CloseProgress(); } return hResult; } // How many messages do we now think we have? unsigned long nMsgs = 0; hResult = m_pImap->GetMessageCount(nMsgs); if ( SUCCEEDED (hResult) ) { m_NumberOfMessages = nMsgs; // Now that we have opened the mailbox successfully, get the UIDValidity, // hResult = m_pImap->GetUidValidity(NewUidvalidity); if ( SUCCEEDED(hResult) ) { hResult = m_pImap->UIDFetchLastUid(ServerUidHighest); } } if (! SUCCEEDED (hResult) ) { if ( ::IsMainThreadMT() && !bSilent ) { if (bWasInProgress) PopProgress(); else CloseProgress(); } return hResult; } } /// Note: Ignore UIDVALIDITY here, // If no messages in remote mailbox, just delete our local cached. if (m_NumberOfMessages == 0) { pTocDoc->ImapRemoveAllSummaries (); hResult = S_OK; } // If the UIDVALIDITY changed, we have to download everything. if (m_Uidvalidity != NewUidvalidity) { pTocDoc->ImapRemoveAllSummaries (); m_bUidValidityChanged = TRUE; // We have to redownload stuff, and we can't do filtering during // this redownload because our local "m_UIDHighest" is no longer valid. // We don't know what we previously filtered. // m_UIDHighest = 0; } if (m_NumberOfMessages > 0) { // If we get here, do the resync. CUidMap NewUidMap; CUidMap StaleUidMap; // Get the curent list into "StaleUidMap" GetCurrentUids (pTocDoc, StaleUidMap); // If bDownloadedOnly is TRUE, resync only to what we already know // about. // IMAPUID MaxUidToFetch; if (bDownloadedOnly) { // Get the highest one we have locally. unsigned long LocalUidHighest = StaleUidMap.GetHighestUid(); MaxUidToFetch = max (LocalUidHighest, m_UIDHighest); } else { // Fetch UID's up to ulMaxUid from the server into the other list. // MaxUidToFetch = min (ulMaxUid, ServerUidHighest); } if (MaxUidToFetch > 0) { CString szSeq; szSeq.Format ("1:%lu", MaxUidToFetch); hResult = m_pImap->FetchFlags (szSeq, &NewUidMap); } if (EscapePressed() || !SUCCEEDED (hResult) ) { NewUidMap.DeleteAll(); if ( ::IsMainThreadMT() && !bSilent ) { if (bWasInProgress) PopProgress(); else CloseProgress(); } if (EscapePressed()) { return HRESULT_MAKE_CANCEL; } else return E_FAIL; } // Update "MaxUidToFetch" to reflect the highest UID we ACTUALLY fetched. // MaxUidToFetch = NewUidMap.GetHighestUid(); // Merge the two lists. // When done, the two lists will be in the following states: // 1. StaleUidMap contains only uid's no longer on the server. // 2. NewUidMap contains only new uid's // 3. NewOldUidMap contains uid's still on the server, but // m_Imflags have new values. CUidMap NewOldUidMap; MergeUidMapsMT (StaleUidMap, NewUidMap, NewOldUidMap); // // Go update the flags of old summaries. // Note: UpdateOldSummaries removes entries from NewOldUidMap!!! // UpdateOldSummaries (pTocDoc, NewOldUidMap); // Now, remove any stale summaries. // Now, remove summaries in StaleUidMap. if (StaleUidMap.GetCount() > 0 ) { int HighlightIndex; pTocDoc->ImapRemoveListedTocs (&StaleUidMap, HighlightIndex, TRUE, TRUE); } // If there are messages, download them but don't do any filtering. // Filtering at this point can again leave the mailboxes out of sync. // if (NewUidMap.GetCount() > 0) { hResult = DoFetchNewMessages (pTocDoc, NewUidMap, FALSE); /// If we fetched a higher UID than we already knew about, update // our stored m_UIDHighest. // if ( SUCCEEDED (hResult) && (MaxUidToFetch > m_UIDHighest) ) { m_UIDHighest = MaxUidToFetch; } } // Make sure. NewUidMap.DeleteAll(); NewOldUidMap.DeleteAll (); StaleUidMap.DeleteAll (); } // Cleanup. if ( ::IsMainThreadMT() && !bSilent ) { if (bWasInProgress) PopProgress(); else CloseProgress(); } return hResult; } ///////////////////////////////////////////////////////////////////////////////////// // DoFetchNewMessages [private] // FUNCTION // Do the details of Fetching new messages. // New summaries are created and added to "pSumList". // END FUNCTION // NOTES // This also does a crude "resync" in that it checks to see if any messages // have been deleted from the server or if message flags have changed. // Note: NewUidMap now contains ONLY new messages. Downloaded messages are removed // from the list. // Note:Return FALSE only if a grievous error ocurred. // // NOTE: If bDoFiltering is FALSE, don't filter inbox. // END NOTES. ///////////////////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::DoFetchNewMessages (CTocDoc *pTocDoc, CUidMap& NewUidMap, BOOL bDoFiltering) { BOOL bMustCloseProgress = FALSE; HRESULT hResult = S_OK; CImapSumList SumList; // Must have a summary list object. if (! pTocDoc ) return E_INVALIDARG; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); // // First find out how many we have to download. Note: NewUidMap contains // only new messgages!! // int nCountBeforeFiltering = NewUidMap.GetCount (); // If we don't have any, don't continue. if (nCountBeforeFiltering <= 0) { return S_OK; } // If progress window is NOT already up, put one up. if ( ::IsMainThreadMT() ) { if (!InProgress) { CString buf; buf.Format (CRString(IDS_IMAP_UPDATING_MAILBOX), pTocDoc->Name()); MainProgress(buf); bMustCloseProgress = TRUE; } } // If this is "Inbox", do "transfer" filtering at this point. // This will transfer matching messages to mailboxes // on the same server, or download messages into local mailboxes. // When this returns, NewUidMap will contain only messages that should be downloaded // into this mailbox. // // NOTE: This is the first stage in the filtering process.!! // CString szName = GetImapName (); szName.TrimLeft (); szName.TrimRight (); BOOL bFiltering = FALSE; // At this point, we know we've got new messages. If this is the // INBOX, we need to do a few things. // if (IsInbox (szName)) { // Tell our parent account that we've got mail. CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (pAccount) pAccount->SetGotNewMail (TRUE); // Set to TRUE if this is a mailbox that we'er filtering. bFiltering = bDoFiltering; } // In case we're filtering. CImapFilterActions FilterActions; // NOTE: Always set filename of mailbox. FilterActions.SetMBFilename (pTocDoc->GetMBFileName ()); // Make sure reset these. FilterActions.m_bPreFilterXferred = FALSE; FilterActions.m_bPostFilterXferred = FALSE; // Clear our own as well. m_bExpunged = FALSE; if (bFiltering) { // Flag if filtering cause an expunge. // // Change the progress message string. if ( InProgress ) { MainProgress( CRString(IDS_IMAP_DOING_SAMESERVER_FILTERING) ); } // // NOTE: If StartFiltering succeeds, we MUST call EndFiltering // before we leave this method!!! // if (FilterActions.StartFiltering()) { // Update highest UID so far. // IMAPUID ulHighestUidSeen = FilterActions.GetHighestUidSeen (); if (ulHighestUidSeen > m_UIDHighest) m_UIDHighest = ulHighestUidSeen; } else bFiltering = FALSE; } if (EscapePressed()) { // // Downloaded messages that remain after pre-filtering. // NOTE: Accumulate new summaries in SumList. // NOTE: This also updates "m_UIDHighest". // DownloadRemainingMessages (pTocDoc, NewUidMap, &SumList); } // Add the summaries to the TOC now. // NOTE: ImapAppendSumList() adds then to the TOC BUT also adds each new summary // to the CSumList that's passed in. This is so we can do the // post filtering below. Note that "RefSumList" contains the same CSummaries that // are in the TOC, so they MUST NET BE freed when RefSumList is deleted!! // CTempSumList RefSumList; ImapAppendSumList (pTocDoc, &SumList, &RefSumList); // NOTE: If we started the filtering process, we must end it. if (bFiltering) { // Do post filtering on pSumList. Ignore "same server xfers". if (!EscapePressed()) { // Note: Bool Flags are: bDoSameServerXfers, bDoIncoming, bDoManual. // FilterActions.DoFiltering(pTocDoc, RefSumList, NULL/*pstrTransUIDs*/, FALSE/*bDoSameServerXfers*/, TRUE/*bDoIncoming*/, FALSE/*bDoManual*/); } // If we need to do an expunge, do it here. if ( FilterActions.m_bPreFilterXferred || (FilterActions.m_bPostFilterXferred && ExpungeAfterDelete (pTocDoc) ) ) { Expunge (); m_bExpunged = TRUE; } // Do terminating things. FilterActions.EndFiltering(); } // Must free RefSumList's internal memory. Note: Not the data. Just the list. // RefSumList.RemoveAll(); // For the CImapSumList, we must free the object memory as well. // SumList.DeleteAll(); // Close progres if we started it.. if ( ::IsMainThreadMT() ) { if (bMustCloseProgress) CloseProgress(); } if (EscapePressed()) { hResult = HRESULT_MAKE_CANCEL; } return hResult; } ///////////////////////////////////////////////////////////////////// // DownloadRemainingMessages [PRIVATE] // // Called after prefiltering to download the remaining messages. // ///////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::DownloadRemainingMessages (CTocDoc *pTocDoc, CUidMap& NewUidMap, CImapSumList *pSumList, BOOL bToTmpMbx /* = FALSE */, CTaskInfoMT* pTaskInfo /* = NULL */ ) { HRESULT hResult = S_OK; IMAPUID uid = 0; CString strMainText; // Must have a summary list object. if (! (pTocDoc && pSumList) ) return E_INVALIDARG; // // Get new value of count. Note that NewUidMap contains new messages only. // int nCountAfterFiltering = NewUidMap.GetCount (); strMainText.Format(CRString(IDS_POP_MESSAGES_LEFT), nCountAfterFiltering); // Now go download remaining messages. if (InProgress && ::IsMainThreadMT() && (nCountAfterFiltering > 0) ) { MainProgress(strMainText); } // Initialize for background progress. // else if (pTaskInfo && !IsMainThreadMT() && (nCountAfterFiltering > 0) ) { pTaskInfo->SetMainText(strMainText); pTaskInfo->SetTotal(nCountAfterFiltering); } // Figure out what kind of download we'd be doing. BOOL bMinimalDownload = DoingMinimalDownload (this); // // Keep tab of how many we download.. // int count = 0; // If error mid-way, stop the transfer. hResult = S_OK; // Loop through all messages. CImapFlags *pF; // // Download what's left after filtering into the mailbox. // for( UidIteratorType ci = NewUidMap.begin(); ci != NewUidMap.end(); ci++ ) { // Does user want to quit?? if (::EscapePressed()) { hResult = HRESULT_MAKE_CANCEL; break; } pF = ( CImapFlags * ) (*ci).second; if (!pF) continue; uid = pF->m_Uid; if (uid == 0 || !pF->m_IsNew) continue; // count++; // Count only new messages. if ( ::IsMainThreadMT() ) Progress(count); // Set the flags for this message: m_bHasUnread = m_bHasUnread || !(pF->m_Imflags & IMFLAGS_SEEN); // If success, this will be non-NULL: CImapSum *pImapSum; pImapSum = NULL; // If this message was not filtered, go download to the mailbox. // Check to see if to download all or just minimal download. if ( bMinimalDownload ) { // Return a partially filled-in new CSummary object. hResult = DoMinimalDownload (pTocDoc, uid, &pImapSum); // If this our highest UID so far? // if ( pImapSum ) { if ( uid > m_UIDHighest ) m_UIDHighest = uid; // Indicate that this is a minimal download. pImapSum->m_Imflags |= IMFLAGS_NOT_DOWNLOADED; } } else { pImapSum = DEBUG_NEW_MFCOBJ_NOTHROW CImapSum; if (pImapSum) { // At lease these must be filled in: // pImapSum->SetHash (uid); // Fetch message, probably including all attachments. hResult = DownloadSingleMessage (pTocDoc, pImapSum, FALSE, bToTmpMbx); if ( SUCCEEDED (hResult) ) { // Indicate that this was more than a minimal download.. pImapSum->m_Imflags &= ~IMFLAGS_NOT_DOWNLOADED; // If this our highest UID so far? // if ( uid > m_UIDHighest ) m_UIDHighest = uid; } else { // We created pImapSum. Delete it. delete pImapSum; pImapSum = NULL; } } } // Did we get a summary?? if (pImapSum) { // Set Sum->m_Imflags flags based on pF->m_Imflags. // Note: Set selected flags. Don't do a blanket copy. // // // First, clear the bits we're interested in. pImapSum->m_Imflags &= ~( IMFLAGS_SEEN | IMFLAGS_ANSWERED | IMFLAGS_FLAGGED | IMFLAGS_DELETED | IMFLAGS_DRAFT | IMFLAGS_RECENT ); // pImapSum->m_Imflags |= (pF->m_Imflags & IMFLAGS_SEEN); pImapSum->m_Imflags |= (pF->m_Imflags & IMFLAGS_ANSWERED); pImapSum->m_Imflags |= (pF->m_Imflags & IMFLAGS_FLAGGED); pImapSum->m_Imflags |= (pF->m_Imflags & IMFLAGS_DELETED); pImapSum->m_Imflags |= (pF->m_Imflags & IMFLAGS_DRAFT); pImapSum->m_Imflags |= (pF->m_Imflags & IMFLAGS_RECENT); // We must set some of Eudora's flags too. if (pF->m_Imflags & IMFLAGS_SEEN) pImapSum->SetState (MS_READ); else pImapSum->SetState (MS_UNREAD); if (pF->m_Imflags & IMFLAGS_ANSWERED) pImapSum->SetState (MS_REPLIED); // Add the CImapSum now. pSumList->AddTail (pImapSum); } strMainText.Format(CRString(IDS_POP_MESSAGES_LEFT), nCountAfterFiltering - count); // Update progress bar. if (InProgress && ::IsMainThreadMT() && SUCCEEDED (hResult) ) { MainProgress(strMainText); } // If in background, use the task-status' progress. else if (!::IsMainThreadMT() && pTaskInfo) { pTaskInfo->SetMainText(strMainText); pTaskInfo->ProgressAdd(1); } // Does user want to quit?? if (EscapePressed()) { hResult = HRESULT_MAKE_CANCEL; break; } } // For. return hResult; } ///////////////////////////////////////////////////////////////////////////////////////////////// // DoMinimalDownload [PRIVATE] // // FUNCTION // Do a minimal download just to get the message's attributes, fill in a new CSummary // and return it. // Mark the new CSummary with the flag to indicate that the message is only partially downloaded. // The new CSummary is returned, or NULL. // END FUNCTION //////////////////////////////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::DoMinimalDownload (CTocDoc *pTocDoc, IMAPUID Uid, CImapSum **ppSum) { BOOL bWeOpenedOurConnection = FALSE; CImapSum* pSum = NULL; HRESULT hResult = S_OK; // Sanity. Must have a valid TocDoc and Uid. if ( NULL == pTocDoc || Uid == 0 || NULL == ppSum) { ASSERT (0); return E_INVALIDARG; } // Intialize output parms: *ppSum = NULL; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); // Make sure we can open the remote connection to our mailbox. if ( !IsSelected() ) { hResult = OpenMailbox (FALSE); if (! SUCCEEDED (hResult) ) return hResult; bWeOpenedOurConnection = TRUE; } // Must have one of these now!! // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Instantiate a CImapDownloader object to do the actual downloading. CImapDownloader ImapDownloader (GetAccountID(), m_pImap, NULL); pSum = NULL; hResult = ImapDownloader.DoMinimalDownload (Uid, &pSum); // Should we close the stream? CTocView *View = pTocDoc->GetView (); if (bWeOpenedOurConnection && !View) Close(); // Set output parm: *ppSum = pSum; return hResult; } ////////////////////////////////////////////////////////////////////////////////////// // DownloadSingleMessage [PUBLIC] - CImapSum version!!! // FUNCTION // This is a public wrapper around the corresponding CImapDownloader's // method of the same name. // "pSum" is a stub pointing to an as yet undownloaded message. Go out and // append the message to the TOC's MBX file. // Use the INI options to determine if to download attachments. // Create stub files as place-holders for un-downloaded attachments. // Additional possible return codes: // ERROR_CANCELLED : user cancelled. // // END FUNCTION. // HISTORY // Created 9/15/97 by JOK. // END HISTORY. ////////////////////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::DownloadSingleMessage (CTocDoc *pTocDoc, CImapSum *pSum, BOOL bDownloadAttachments, BOOL bToTmpMbx /* = FALSE */) { HRESULT hResult = S_OK; // Sanity: if (! (pTocDoc && pSum) ) return E_INVALIDARG; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); // // Also, don't accept any mouse or keyboard input during this. // Note: Re-enable before we leave. // CTocFrame* pTocFrame = NULL; CTocView *pView = pTocDoc->GetView (); if (pView) { // Disable the whole darn frame!! pTocFrame = (CTocFrame *) pView->GetParentFrame(); } // If we're offline, write a stub to the MBX file and return OK. // if ( !IsSelected() && GetIniShort(IDS_INI_CONNECT_OFFLINE) ) { return WriteOfflineMessage (pTocDoc, pSum, bToTmpMbx); } // // If this is the TOC m_pImapMailbox object, make sure it's still connected // to the server, If not, re-open the connection. // // Try to re-open if, for some reason, the connection was dropped. if ( !IsSelected() ) { hResult = OpenMailbox (FALSE); if ( !SUCCEEDED (hResult) ) return hResult; } // Must have one of these now. // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Open the MBX file for appending. This can be either the real // MBX file or the temporary one. // CString szMbxFilePath; if (bToTmpMbx) { GetTmpMbxFilePath (GetDirname(), szMbxFilePath); } else { szMbxFilePath = pTocDoc->GetMBFileName(); } // Instantiate an ImapDownloader object to do the downloading. CImapDownloader MbxDownloader (GetAccountID(), m_pImap, (LPCSTR) szMbxFilePath); // Make sure the file exists. Open it for appending. Don't truncate!! if (!MbxDownloader.OpenMbxFile (FALSE)) { ErrorDialog ( IDS_ERR_FILE_OPEN, szMbxFilePath, CRString (IDS_ERR_FILE_OPEN_WRITING) ); return E_FAIL; } // Go download it. hResult = MbxDownloader.DownloadSingleMessage (pSum, bDownloadAttachments); // // Note: Only the CImapDownloader can set IMFLAGS_NOT_DOWNLOADED into the summary. // Don't do it here because bResult can be TRUE if we wrote a dummy message to the MBX file. // // CLose the file back. MbxDownloader.CloseMbxFile (); return hResult; } // // CImapMailbox::DownloadFullHeaders() // // Download the entire set of headers for the message specified in pSum and place the results in strHeaders. // HRESULT CImapMailbox::DownloadFullHeaders(CTocDoc *pTocDoc, CSummary *pSum, CString &strHeaders) { HRESULT hResult = S_OK; // Sanity: if (!pTocDoc || !pSum) { return E_INVALIDARG; } // If this is the TOC m_pImapMailbox object, make sure it's still connected // to the server, If not, re-open the connection. if (!IsSelected()) { hResult = OpenMailbox(FALSE); if (!SUCCEEDED(hResult)) { return hResult; } } // Bail if we don't have a connection. if (!m_pImap) { ASSERT(0); return E_FAIL; } // Instantiate an ImapDownloader object to do the downloading. CImapDownloader imapdownloader(GetAccountID(), m_pImap, NULL); hResult = imapdownloader.DownloadFullHeaderToString(pSum->GetHash()); strHeaders = imapdownloader.m_strFullHeader; return hResult; } ////////////////////////////////////////////////////////////////////////////////////// // OnPreviewSingleMessage [PUBLIC] // FUNCTION // This is the method that should be called from a preview. // It tests to see if the user just cancelled an attempt to open the remote mailbox // and don't re-attempt until after a certain time has elapsed. // // Additional possible return codes: // ERROR_CANCELLED : user cancelled. // END FUNCTION. // HISTORY // Created 9/15/97 by JOK. // END HISTORY. ////////////////////////////////////////////////////////////////////////////////////// HRESULT CImapMailbox::OnPreviewSingleMessage(CSummary *pSum, BOOL bDownloadAttachments) { HRESULT hResult = S_OK; // Must be in main thread. // ASSERT (IsMainThreadMT()); // Is preview not allowed at this time? if (!PreviewAllowed()) { return HRESULT_MAKE_CANCEL; } int iConnectionState = GetConnectionState(bDoAllowOffline); if (iConnectionState == iStateStayOfflineDisallow) { hResult = HRESULT_MAKE_CANCEL; } else if (iConnectionState == iStateStayOfflineAllow) { CString strUidList; strUidList.Format("%lu", pSum->GetHash()); if (!m_pTocDoc->QueueImapFetch(strUidList, bDownloadAttachments, TRUE/*bOnlyIfNotDownloaded*/, FALSE/*bClearCacheOnly*/, FALSE/*bInvalidateCachedPreviewSums*/)) { hResult = E_FAIL; } } else { hResult = DownloadSingleMessage(m_pTocDoc, pSum, bDownloadAttachments); } return hResult; } // // CImapMailbox::FetchHeaderString() // // Download the headers for the message associated with pSum. Downloading // will fill in the summary's m_strRawFrom field (which is not preserved) and // we fill strFrom with that value. // HRESULT CImapMailbox::FetchFromHeaderString(CTocDoc *pTocDoc, CSummary *pSum, CString &strFrom) { HRESULT hResult = S_OK; // Must be in main thread. ASSERT (IsMainThreadMT()); // Must have one of these now. if (!m_pImap) { ASSERT (0); return E_FAIL; } // Instantiate a CImapDownloader object to do the actual downloading. CImapDownloader ImapDownloader(m_AccountID, m_pImap, NULL); CImapSum *pImapSum = DEBUG_NEW CImapSum(); hResult = ImapDownloader.DoMinimalDownload(pSum->GetHash(), &pImapSum); strFrom = pImapSum->m_strRawFrom; delete pImapSum; return hResult; } // DidUserCancel [PUBLUC] // // Since we're the one who constructed the HRESULT, we're the one to // determine if it contains a USER CANCELLED. // A caller will pass us an HRESULT that we previously returned to him. // We return TRUE is it contains a flag that we set, indicating that the // user did cancel. // BOOL CImapMailbox::DidUserCancel (HRESULT hResult) { return HRESULT_CONTAINS_CANCEL (hResult); } // XferMessagesOnServer [PUBLIC] // FUNCTION // Given a comma-separated array of message UID's, send a single UID COPY command // to the IMAP server. pDestination is the IMAP name of the destination mailbox. // If !Copy, flag them for deletion. // Return a BOOL for now but later, we should return an ALLOCATED CString // containing the uid's of successfully moved messages, // END FUNCTION // NOTES // In order to optimize the COPY, somewhere along the line we should format // uid's corresponding to consecutive messages using the ":". // END NOTES. HRESULT CImapMailbox::XferMessagesOnServer (LPCSTR pUidlist, CDWordArray *pdwaNewUIDs, LPCSTR pDestination, BOOL Copy, BOOL bSilent/*=FALSE*/) { HRESULT hResult = S_OK; // Sanity. if (!(pUidlist && pDestination)) return E_INVALIDARG; // There was code commented out here to check our online status before proceeding. This code is reached // by four different operations: normal transfers, trashing and junking (which all perform the online // status check before this point) and old style filtering. Old style filtering does its matching by // searching the messages on the server so if we get here by that route we know we are online. The // bottom line is that if we get this far we know we are online so no checking is needed here. -dwiggins // Make sure the stream is connected and alive. if ( !IsSelected() ) { hResult = OpenMailbox ( bSilent ); if (! SUCCEEDED ( hResult ) ) return hResult; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Update the READ/WRITE state now that we have opened the mailbox. BOOL bIsReadOnly = m_pImap->IsReadOnly(); // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); hResult = E_FAIL; } else { // If the R/W status has changed, reflect this. if (bIsReadOnly != IsReadOnly()) { SetReadOnly (bIsReadOnly); pImapCommand->SetReadOnly (bIsReadOnly); // Update mailbox display. g_theMailboxDirector.ImapNotifyClients (pImapCommand, CA_IMAP_PROPERTIES, NULL); } // If this is a MOVE, flag an error if the source mailbox is read-only. // If it's read-only, put up message. if ( !bSilent && IsReadOnly ()) { CString err; err.Format ( CRString (IDS_ERR_IMAP_MBOX_RDONLY), pImapCommand->GetName () ); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, err); hResult = E_FAIL; } } if ( SUCCEEDED (hResult) ) { // Ok, Send the command. hResult = m_pImap->CopyMessages (pUidlist, pDestination, pdwaNewUIDs); } // If no UIDPLUS data was returned tell our account object about it. if (SUCCEEDED(hResult) && pdwaNewUIDs) { CImapAccount *pAccount = g_ImapAccountMgr.FindAccount(GetAccountID()); if (pAccount) { pAccount->SetSupportsUIDPLUS(pdwaNewUIDs->GetSize() > 0); } } // If we failed here, display the server's message. if ( ( !SUCCEEDED (hResult) ) && !bSilent) { ShowLastImapError (); } else { if ( (SUCCEEDED (hResult)) && !Copy) { // NOTE: DOn't expunge them. Just flag them for deletion!! CUidMap mapUidsRemoved; hResult = m_pImap->UIDDeleteMessages (pUidlist, mapUidsRemoved, FALSE); // If we failed here, display the server's message. if ( (!SUCCEEDED(hResult)) && !bSilent) { ShowLastImapError (); } } } return hResult; } // UseFancyTrash [PUBLIC] // // Fancy trash is set on a per-account basis - ask the account for this info. // BOOL CImapMailbox::UseFancyTrash() { BOOL bUseFancyTrash = FALSE; CImapAccount *pAccount = g_ImapAccountMgr.FindAccount ( GetAccountID() ); if (pAccount) bUseFancyTrash = pAccount->UseFancyTrash(); return bUseFancyTrash; } // GetTrashMailboxMbxName // FUNCTION // Call the account of which this mailbox is a member to get the imapname // of the one and only account's Trash mailbox. // Return the MBX filename housing thye mailbox. // END FUNCTION. // NOTES // If "CreateRemote" is TRUE, make sure the remote trash mailbox exists and that there // is a local cache representation. // END NOTES BOOL CImapMailbox::GetTrashMailboxMbxName (CString& MbxFilePath, BOOL CreateRemote, BOOL bSilent /* = FALSE */) { CImapAccount *pAccount; BOOL bResult = FALSE; CString path; // If errorn return an empty string. MbxFilePath.Empty(); // Must have an accountID if (!m_AccountID) return FALSE; pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) return FALSE; // Get the MBX filepath: bResult = pAccount->GetTrashLocalMailboxPath(path, CreateRemote, bSilent); // Copy path to outgoing if we succeeded. if (bResult) MbxFilePath = path; return bResult; } // FUNCTION // Determine if this is the account's trash mailbox. // END FUNCTION BOOL CImapMailbox::IsImapTrashMailbox (LPCSTR pPathname) { CImapAccount *pAccount; BOOL bResult = FALSE; CString path; // Sanity if (!pPathname) return FALSE; // Must have an accountID if (!m_AccountID) return FALSE; pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) return FALSE; // Get the MBX filepath: bResult = pAccount->GetTrashLocalMailboxPath(path, FALSE); // If we found a name, compare.. if (bResult) { bResult = (path.CompareNoCase (pPathname) == 0); } return bResult; } // MoveMsgsToTrash [PUBLIC] // HRESULT CImapMailbox::MoveMsgsToTrash(LPCSTR pUidlist, CDWordArray *pdwaNewUIDs, CUidMap& mapUidsActuallyRemoved, CTocDoc **pTrashToc) { // Sanity: // if (! (pUidlist && *pUidlist) ) return S_OK; if (!m_pImap) { ASSERT(0); return E_FAIL; } // If we're offline, don't initiate a connection. // if ( !IsSelected() && GetIniShort(IDS_INI_CONNECT_OFFLINE) ) { return HRESULT_MAKE_OFFLINE; } // HRESULT hResult = S_OK; if (!IsSelected()) { hResult = OpenMailbox (FALSE); if (! SUCCEEDED (hResult) ) { return hResult; } } // Get trash mailbox for this account. // CImapAccount* pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (!pAccount) return E_FAIL; TCHAR pImapDelimiter = GetDelimiter (); CString strName; CString strFullName; pAccount->GetTrashMailboxName(strName, strFullName, &pImapDelimiter); // If no mailbox name, must ask user. // QCImapMailboxCommand *pTrashCommand = NULL; if (pImapDelimiter=='\0' || pImapDelimiter==' ') // Make sure we have a delimiter of some kind -jdboyd { // the current mailbox doesn't have a delimiter. Use the top level delimiter. // Unfortunately, the top level delimiter isn't kept up to date. It's only set when // a refresh or some such thing happens. I'm too scared to change this, so instead, // scan the existing mailboxes in this account, and return the first instance of a delimiter. pImapDelimiter = FigureOutDelimiter(pAccount); } if ( !strFullName.IsEmpty() ) { // Find the mailbox in our local mailbox tree. // pTrashCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), strFullName, pImapDelimiter); } #if 0 // if (!pTrashCommand) { // Try to create it on the server. // if ( !GetImapAccountMgr()->MailboxExistsOnServer (GetAccountID(), szImapTrashName) ) { ACCOUNT_ID AccountId, LPCSTR pImapName) // Ask. // } #endif // Still no trash command, give up. // if (!pTrashCommand) { CRString fmt (IDS_ERR_IMAP_INVALID_MBOXNAME); CString szText; szText.Format (fmt, strFullName); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, szText); return E_FAIL; } // Are source and destination the same? // BOOL bSameAsDest = strFullName.Compare (GetImapName()) == 0; // Do the transfer. // BOOL bXferSucceeded = FALSE; // If source and destination are the same, don't do the xfer part. // if ( !bSameAsDest ) { hResult = XferMessagesOnServer (pUidlist, pdwaNewUIDs, strFullName, TRUE/*Copy*/, TRUE/*bSilent*/); } else { bXferSucceeded = TRUE; hResult = S_OK; } // if ( SUCCEEDED (hResult) ) { bXferSucceeded = TRUE; // First mark the messages to be deleted as seen. hResult = m_pImap->UIDAddFlaglist(pUidlist, "\\Seen", TRUE/*Silent*/); // Do a UID expunge. This will expunge only the messages in the uid list, // either using the UIDPLUS command (if server supports it), or by // unflagging currently \\DELETED ones first. // // Since UIDExpunge() currently just does an EXPUNGE and acts on all deleted messages // (not just those deleted by trashing). The long term solution is better deletion // handling, but for now we just don't do the EXPUNGE if fancy trash mode is off. -dwiggins hResult = m_pImap->UIDDeleteMessages(pUidlist, mapUidsActuallyRemoved, FALSE/*Expunge*/); // If we didn't succeed, we must copy back xferred messages!!! $$$$$$ // } // If we did the transfer, go update the destination mailbox if it's open. // if (!bSameAsDest && bXferSucceeded) { // See if the TOC open on the desktop. // *pTrashToc = GetToc(pTrashCommand->GetPathname(), NULL, TRUE, TRUE); if (*pTrashToc && (*pTrashToc)->GetView()) { BOOL ViewNeedsUpdate = FALSE; pTrashCommand->Execute (CA_IMAP_RESYNC, &ViewNeedsUpdate); } } if (m_pTocDoc) { DoManualResync(m_pTocDoc); } // We just did a COPY so see if our UIDPLUS status has changed. pAccount->WarnIfUIDPLUSStatusChanged(); return hResult; } // // CImapMailbox::MoveMsgsToOrFromJunk() [PUBLIC] // // Moves the specified messages to the IMAP account's Junk mailbox. // HRESULT CImapMailbox::MoveMsgsToOrFromJunk(bool bToJunk, LPCSTR pUidlist, CDWordArray *pdwaNewUIDs, CUidMap &mapUidsActuallyRemoved, CTocDoc **pTargetToc) { if (!pUidlist || !*pUidlist) { return S_OK; } if (!m_pImap) { ASSERT(0); return E_FAIL; } // If we're offline, don't initiate a connection. if (!IsSelected() && GetIniShort(IDS_INI_CONNECT_OFFLINE)) { return HRESULT_MAKE_OFFLINE; } HRESULT hResult = S_OK; // Open the source mailbox. if (!IsSelected()) { hResult = OpenMailbox(FALSE); if (!SUCCEEDED(hResult)) { return hResult; } } CImapAccount *pAccount = g_ImapAccountMgr.FindAccount(m_AccountID); if (!pAccount) { return E_FAIL; } CString strImapName; QCImapMailboxCommand *pCommand = NULL; if (bToJunk) { // Destination is Junk mailbox for this account. pCommand = pAccount->GetJunkMailbox(strImapName); } else { // Destination is Inbox for this account. pCommand = pAccount->GetInMailbox(strImapName); } if (!pCommand) { return E_FAIL; } // Should we move the message? Don't move if we are junking and this is the junk mailbox or // if we are not junking and this isn't the junk mailbox. BOOL bShouldMove = TRUE; BOOL bIsJunk = IsJunk(GetImapName()); if ((bToJunk && bIsJunk) || (!bToJunk && !bIsJunk)) { bShouldMove = FALSE; } // Do the transfer. BOOL bXferSucceeded = FALSE; // If source and destination are the same, don't do the xfer part. if (bShouldMove) { hResult = XferMessagesOnServer(pUidlist, pdwaNewUIDs, strImapName, TRUE, // Do a COPY only. TRUE); // bSilent. } else { bXferSucceeded = TRUE; hResult = S_OK; } // if (bShouldMove && SUCCEEDED(hResult)) { bXferSucceeded = TRUE; // Do a UID expunge. This will expunge only the messages in the uid list, // either using the UIDPLUS command (if server supports it), or by // unflagging currently \\DELETED ones first. // Since UIDExpunge() currently just does an EXPUNGE and acts on all deleted messages // (not just those deleted by junking). The long term solution is better deletion // handling, but for now we just don't do the EXPUNGE if fancy trash mode is off. -dwiggins hResult = m_pImap->UIDDeleteMessages(pUidlist, mapUidsActuallyRemoved, FALSE/*Expunge*/); // If the delete succeeded mark the messages as seen. This is an option on the Mac but for // now we always mark deleted messages as seen. if (hResult == S_OK) { m_pImap->UIDAddFlaglist(pUidlist, "(\\Seen)"); } // Get the TOC. Note that we need to open the TOC to complete the transfer // process with the UIDPLUS data so open it if it isn't already open. *pTargetToc = GetToc(pCommand->GetPathname(), NULL/*Name*/, TRUE/*HeaderOnly*/, FALSE/*OnlyIfLoaded*/); if (*pTargetToc && (*pTargetToc)->GetView()) { // If the TOC is open update it. BOOL bViewNeedsUpdate = FALSE; pCommand->Execute(CA_IMAP_RESYNC, &bViewNeedsUpdate); } } if (m_pTocDoc) { DoManualResync(m_pTocDoc); } // We just did a COPY so see if our UIDPLUS status has changed. pAccount->WarnIfUIDPLUSStatusChanged(); return hResult; } // // CImapMailbox::ReadyToAutoExpunge() // // Returns TRUE if conditions are right to auto expunge, FALSE otherwise. // BOOL CImapMailbox::ReadyToAutoExpunge() { int iPercent = -1; int iSetting = -1; CImapAccount *pAccount = g_ImapAccountMgr.FindAccount(m_AccountID); if (!pAccount) { return FALSE; } iSetting = pAccount->GetAutoExpungeSetting(&iPercent); if (iSetting == IDS_INI_IMAP_AUTO_EXPUNGE_ALWAYS) { return TRUE; } else if (iSetting == IDS_INI_IMAP_AUTO_EXPUNGE_ON_PCT) { if (iPercent < 0) { // This really shouldn't happen but if we can't determine a valid percent don't go on. return FALSE; } if (m_pTocDoc) { unsigned int iTotalSummaries = m_pTocDoc->NumSums(); unsigned int iDeletedSummaries = 0; CSumList & listSums = m_pTocDoc->GetSumList(); POSITION pos = listSums.GetHeadPosition(); POSITION posNext = NULL; CSummary *pSum = NULL; for (posNext = pos; pos; pos = posNext) { pSum = listSums.GetNext(posNext); if (pSum && pSum->IsIMAPDeleted()) { ++iDeletedSummaries; if (((iDeletedSummaries * 100) / iTotalSummaries) >= (unsigned int)iPercent) { return TRUE; } } } } } return FALSE; } // DeleteMessagesFromServer [PUBLIC] // FUNCTION // Set the delete flags and (optionally) expunge the mailbox. // END FUNCTION HRESULT CImapMailbox::DeleteMessagesFromServer (LPCSTR pUidList, BOOL Expunge, BOOL bSilent /* = FALSE */) { HRESULT hResult = S_OK; // Sanity. if (!pUidList) return E_INVALIDARG; // Make sure the stream is connected and alive. if ( !IsSelected() ) { hResult = OpenMailbox ( bSilent ); if (! SUCCEEDED (hResult) ) return hResult; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Update the READ/WRITE state now that we have opened the mailbox. BOOL bIsReadOnly = m_pImap->IsReadOnly(); // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); return E_FAIL; } // If the R/W status has changed, reflect this. if (bIsReadOnly != IsReadOnly()) { SetReadOnly (bIsReadOnly); pImapCommand->SetReadOnly (bIsReadOnly); // Update mailbox display. g_theMailboxDirector.ImapNotifyClients (pImapCommand, CA_IMAP_PROPERTIES, NULL); } // If it's read-only, put up message. if (!bSilent && IsReadOnly ()) { CString err; err.Format ( CRString (IDS_ERR_IMAP_MBOX_RDONLY), pImapCommand->GetName () ); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, err); hResult = E_FAIL; } else { // Ok, Send the command. // First mark the messages to be deleted as seen. hResult = m_pImap->UIDAddFlaglist(pUidList, "\\Seen", TRUE/*Silent*/); // Now do the delete. CUidMap mapUidsRemoved; hResult = m_pImap->UIDDeleteMessages (pUidList, mapUidsRemoved, Expunge); } // If we failed here, display the server's message. if (!SUCCEEDED(hResult)) { if (!bSilent) { ShowLastImapError (); } } return hResult; } // UnDeleteMessagesFromServer [PUBLIC] // FUNCTION // Remove the delete flags from the messages. // END FUNCTION HRESULT CImapMailbox::UnDeleteMessagesFromServer (LPCSTR pUidList, BOOL bSilent /* = FALSE */) { HRESULT hResult = E_FAIL; // Sanity. if (!pUidList) return E_INVALIDARG; // Make sure the stream is connected and alive. if ( !IsSelected() ) { hResult = OpenMailbox ( bSilent ); if ( !SUCCEEDED (hResult) ) return hResult; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Update the READ/WRITE state now that we have opened the mailbox. BOOL bIsReadOnly = m_pImap->IsReadOnly(); // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); return E_FAIL; } // If the R/W status has changed, reflect this. if (bIsReadOnly != IsReadOnly()) { SetReadOnly (bIsReadOnly); pImapCommand->SetReadOnly (bIsReadOnly); // Update mailbox display. g_theMailboxDirector.ImapNotifyClients (pImapCommand, CA_IMAP_PROPERTIES, NULL); } // If it's read-only, put up message. if (!bSilent && IsReadOnly ()) { CString err; err.Format ( CRString (IDS_ERR_IMAP_MBOX_RDONLY), pImapCommand->GetName () ); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, err); return E_FAIL; } // Ok, Send the command. hResult = m_pImap->UIDUnDeleteMessages (pUidList); // If we failed here, display the server's message. if ( !SUCCEEDED(hResult) ) { if (!bSilent) { ShowLastImapError (); } } return hResult; } // Expunge [PUBLIC] // FUNCTION // Wrapper around CImapConnection's expunge. // END FUNCTION HRESULT CImapMailbox::Expunge () { HRESULT hResult = E_FAIL; // Make sure the stream is connected and alive. if ( !IsSelected() ) { hResult = OpenMailbox ( FALSE ); if (! SUCCEEDED (hResult) ) return hResult; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } CUidMap mapUidsRemoved; return m_pImap->Expunge(mapUidsRemoved); } // UIDExpunge [PUBLIC] // FUNCTION // Wrapper around CImapConnection's expunge. // END FUNCTION HRESULT CImapMailbox::UIDExpunge (LPCSTR pUidList, CUidMap& mapUidsActuallyRemoved) { HRESULT hResult = E_FAIL; // Make sure the stream is connected and alive. if ( !IsSelected() ) { hResult = OpenMailbox ( FALSE ); if (! SUCCEEDED (hResult) ) return hResult; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } return m_pImap->UIDExpunge (pUidList, mapUidsActuallyRemoved); } // // CImapMailbox::SetRemoteState() // // Calls the appropriate function to set/unset the specified flag for the specified messages // on the server. // BOOL CImapMailbox::SetRemoteState(CString& szUidList, char State, BOOL bUnset) { if (!IsSelected()) { return FALSE; } // Set the state. Note: Do it silently. if (State == MS_READ) { if (bUnset) return SUCCEEDED(ImapUnsetSeenFlag(szUidList, TRUE)); else return SUCCEEDED(ImapSetSeenFlag(szUidList, TRUE)); } else if (State == MS_UNREAD) { if (bUnset) return SUCCEEDED(ImapSetSeenFlag(szUidList, TRUE)); else return SUCCEEDED(ImapUnsetSeenFlag(szUidList, TRUE)); } else if (State == MS_REPLIED) { if (bUnset) return SUCCEEDED(ImapUnsetAnsweredFlag(szUidList, TRUE)); else return SUCCEEDED(ImapSetAnsweredFlag(szUidList, TRUE)); } // If we get here, it's not a state IMAP can set. That's OK. return TRUE; } // ImapSetSeenFlag [PUBLIC] // // Set seen flag // HRESULT CImapMailbox::ImapSetSeenFlag (LPCSTR pUidList, BOOL bSilent /* = FALSE */) { return ModifyRemoteFlags (pUidList, IMFLAGS_SEEN, TRUE, bSilent); } // ImapUnsetSeenFlag [PUBLIC] // // Remove seen flag // HRESULT CImapMailbox::ImapUnsetSeenFlag (LPCSTR pUidList, BOOL bSilent /* = FALSE */) { return ModifyRemoteFlags (pUidList, IMFLAGS_SEEN, FALSE, bSilent); } // ImapSetAnsweredFlag [PUBLIC] // // Set Answered flag // HRESULT CImapMailbox::ImapSetAnsweredFlag (LPCSTR pUidList, BOOL bSilent /* = FALSE */) { return ModifyRemoteFlags (pUidList, IMFLAGS_ANSWERED, TRUE, bSilent); } // ImapUnsetAnsweredFlag [PUBLIC] // // Remove answered flag. // HRESULT CImapMailbox::ImapUnsetAnsweredFlag (LPCSTR pUidList, BOOL bSilent /* = FALSE */) { return ModifyRemoteFlags (pUidList, IMFLAGS_ANSWERED, FALSE, bSilent); } // ModifyRemoteFlags [PUBLIC] // FUNCTION // Does the real work of setting message (IMAP system) flags. // The flags are bitflag-combinations of the IMFLAGS_* bitflags defined in summary.h. // Can set multiple flags in a single call. // //If "bSet" is FALSE, the flags are REMOVED instead of being set. // // END FUNCTION HRESULT CImapMailbox::ModifyRemoteFlags (LPCSTR pUidList, unsigned ulFlags, BOOL bSet, BOOL bSilent /* = FALSE */) { HRESULT hResult = E_FAIL; BOOL bWeOpenedOurConnection = FALSE; // Sanity. if (!(pUidList && ulFlags)) return E_INVALIDARG; #if 0 // JOK // If we're offline, don't initiate a connection. // if ( !IsSelected() && GetIniShort(IDS_INI_CONNECT_OFFLINE) ) { return HRESULT_MAKE_OFFLINE; } #endif // JOK // Make sure the stream is connected and alive. // if ( !IsSelected() ) { hResult = OpenMailbox (bSilent); if (! SUCCEEDED (hResult) ) return E_FAIL; bWeOpenedOurConnection = TRUE; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); return E_FAIL; } // If the mailbox is read-only, put up message. if (!bSilent && IsReadOnly ()) { CString err; err.Format ( CRString (IDS_ERR_IMAP_MBOX_RDONLY), pImapCommand->GetName () ); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, err); return E_FAIL; } // Format the IMAP char-format flaglist. CString szFlaglist; ImapBitflagsToFlaglist (ulFlags, szFlaglist); if (szFlaglist.IsEmpty()) { ASSERT (0); return E_FAIL; } // Send the IMAP command now: if (bSet) hResult = m_pImap->UIDAddFlaglist (pUidList, szFlaglist, bSilent); else hResult = m_pImap->UIDRemoveFlaglist (pUidList, szFlaglist, bSilent); // If we failed here, display the server's message. if ( !SUCCEEDED(hResult) ) { if (!bSilent) { ShowLastImapError (); } } return hResult; } // // FUNCTION // Send a message from a local mailbox up to a remote IMAP mailbox. // We are the target mailbox. // Format attachments into a valid RFC822/MIME message. // END FUNCTION // NOTES // Assume that all members of "this" are valid. Typically we are being called from // within a CTocDoc and this object is the CTocDoc's contained imap object. // NOTE: Do NOT delete target message or components. // NOTE: If the server supports Optimize-1 and we can get a destination UID, // return the new UID in "*pNewUid". // END NOTES HRESULT CImapMailbox::AppendMessageFromLocal (CSummary *pSum, unsigned long *pNewUid, BOOL bSilent) { HRESULT hResult = E_FAIL; CMessageDoc* pMsgDoc = NULL; BOOL MustCloseMsgDoc = FALSE; CTocDoc *pSrcToc; // Sanity if ( !(pSum && pNewUid) ) return E_INVALIDARG; // Initialize *pNewUid = 0; // Get the source TOC. pSrcToc = pSum->m_TheToc; if (pSrcToc == NULL) { ASSERT (0); return E_INVALIDARG; } // Disable preview. // pSrcToc->SetPreviewableSummary (NULL); // If the source toc is an IMAP mailbox. verify it's contained IMPA maibox object. if (pSrcToc->IsImapToc()) { if (!pSrcToc->m_pImapMailbox) { ASSERT ( 0 ); return E_FAIL; } } // Make sure we can open the remote connection first. // if ( !IsSelected() ) { hResult = OpenMailbox ( bSilent ); if (! SUCCEEDED (hResult) ) return hResult; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Update the READ/WRITE state now that we have opened the mailbox. BOOL bIsReadOnly = m_pImap->IsReadOnly(); // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); return E_FAIL; } // If the R/W status has changed, reflect this. if (bIsReadOnly != IsReadOnly()) { SetReadOnly (bIsReadOnly); pImapCommand->SetReadOnly (bIsReadOnly); // Update mailbox display. g_theMailboxDirector.ImapNotifyClients (pImapCommand, CA_IMAP_PROPERTIES, NULL); } // If it's read-only, put up message. if (!bSilent && IsReadOnly ()) { CString err; err.Format ( CRString (IDS_ERR_IMAP_MBOX_RDONLY), pImapCommand->GetName () ); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, err); return E_FAIL; } // Instantiate an append object to do the grunge work. CDWordArray dwaNewUIDs; CImapAppend Append(m_pImap, NULL, pSum, 0, &dwaNewUIDs); // Map local summary flags to IMAP flags. // If the summary is from the local outbox, set SEEN flag. // int State = pSum->m_State; unsigned long Imflags = 0; if (pSum->m_TheToc && pSum->m_TheToc->m_Type == MBT_OUT) { Imflags |= IMFLAGS_SEEN; } else if (State == MS_READ) { Imflags |= IMFLAGS_SEEN; } else if (State == MS_REPLIED || State == MS_FORWARDED || State == MS_REDIRECT) { Imflags |= IMFLAGS_ANSWERED; } Append.SetFlags (Imflags); // With the new IMAP local/cache/online model the summary is actually in the destination // (IMAP) TOC at this point, but the attachment is in the POP attachment directory. The // previous code actually checked to see if the summary was in a POP TOC and used the // attachment directory for the IMAP mailbox if it wasn't. The cold, hard truth is that we // would probably be in trouble if we got here and the source message was originally in an // IMAP mailbox so I have taken that check out. -dwiggins char DirName[_MAX_PATH+1]; GetIniString(IDS_INI_AUTO_RECEIVE_DIR, DirName, sizeof(DirName)); if( strcmp(DirName, "") != 0) Append.SetSrcAttachDir ( DirName ); else Append.SetSrcAttachDir ( (LPCSTR) ( EudoraDir + CRString(IDS_ATTACH_FOLDER) ) ); // Tell the append object to use the target's mailbox directory if it need to spool stuff. Append.SetSpoolDir (m_Dirname); // Get the MBX file stub. MustCloseMsgDoc = FALSE; pMsgDoc = pSum->FindMessageDoc(); if (!pMsgDoc) { pMsgDoc = pSum->GetMessageDoc(); MustCloseMsgDoc = TRUE; } hResult = S_OK; if (pMsgDoc) { // Copy this to the Append object. // Note: GetFullMessage returns allocated text that must be freed!! LPTSTR pText = pMsgDoc->GetFullMessage (); if (!pText) { ASSERT (0); hResult = E_FAIL; } else { // This copies the text, so we can safeky free pText. Append.SetMbxStub (pText); delete[] pText; pText = NULL; } // Did we create the message doc? if (MustCloseMsgDoc) { pSum->NukeMessageDocIfUnused(); pMsgDoc = NULL; } } // Make sure. pMsgDoc = NULL; // Call over to append.cpp to do the dirty work of appending. This may // involve spooling the mesage to a temporary file first, for example if we are doing this // in the background. // For now, spool and do in foreground. if ( SUCCEEDED (hResult) ) { // // Copy the summary's m_Seconds in case the message doesn't have a date field. // Append.m_Seconds = pSum->m_Seconds ;/*+ 60*pSum->m_TimeZoneMinutes;*/ hResult = Append.AppendMessage (TRUE, FALSE); if (dwaNewUIDs.GetCount() == 1) { *pNewUid = dwaNewUIDs.GetAt(0); } } return hResult; } // // FUNCTION // Download message text directly from a remote mailbox and append it up to a destination // remote IMAP mailbox on a different server. // END FUNCTION // NOTES // Assume that all members of "this" are valid. Typically we are being called from // within a CTocDoc and this object is the CTocDoc's contained imap object. // Note: We are the TARGET mailbox!!! // NOTE: If the server supports Optimize-1 and we can get a destination UID, // return the new UID in "*pNewUid". // END NOTES HRESULT CImapMailbox::AppendMessageAcrossRemotes (CSummary *pSum, unsigned long *pNewUid, BOOL bSilent) { HRESULT hResult = E_FAIL; CTocDoc *pSrcToc; BOOL bWeOpenedSrcConnection = FALSE, bWeOpenedOurConnection = FALSE; // Sanity if ( !(pSum && pNewUid) ) return E_INVALIDARG; // Initialize *pNewUid = 0; // Get the source TOC. pSrcToc = pSum->m_TheToc; if (pSrcToc == NULL) { ASSERT (0); return E_INVALIDARG; } // Disable preview. // pSrcToc->SetPreviewableSummary (NULL); // The source TOC is also an IMAP mailbox. Verify it's contained IMAP maibox object. if (!pSrcToc->m_pImapMailbox) { ASSERT ( 0 ); return E_FAIL; } // hResult = S_OK; // Make sure we can open the remote connection to our mailbox. if ( !IsSelected() ) { hResult = OpenMailbox (TRUE); if (! SUCCEEDED (hResult) ) return E_FAIL; bWeOpenedOurConnection = TRUE; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Open to source mailbox as well. if ( !pSrcToc->m_pImapMailbox->IsSelected() ) { hResult = pSrcToc->m_pImapMailbox->OpenMailbox (TRUE); if (!SUCCEEDED (hResult) ) return hResult; bWeOpenedSrcConnection = TRUE; } // Source toc MUST have an IMAP agent as well. // if ( !pSrcToc->m_pImapMailbox->GetImapAgent() ) { ASSERT (0); return E_FAIL; } // Update out READ/WRITE state now that we have opened it. BOOL bIsReadOnly = IsReadOnly(); // We need this a couple of times below: QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (!pImapCommand) { ASSERT (0); return E_FAIL; } // If the R/W status has changed, reflect this. if (bIsReadOnly != IsReadOnly()) { SetReadOnly (bIsReadOnly); pImapCommand->SetReadOnly (bIsReadOnly); // Update mailbox display. g_theMailboxDirector.ImapNotifyClients (pImapCommand, CA_IMAP_PROPERTIES, NULL); } // If it's read-only, put up message. if (!bSilent && IsReadOnly ()) { CString err; err.Format ( CRString (IDS_ERR_IMAP_MBOX_RDONLY), pImapCommand->GetName () ); ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, err); return E_FAIL; } // Call over to append.cpp to do the dirty work of appending. This may // involve spooling the mesage to a temporary file first, for example if we are doing this // in the background. // For now, spool and do in foreground. CDWordArray dwaNewUIDs; CImapAppend Append(m_pImap, pSrcToc->m_pImapMailbox->m_pImap, pSum, pSum->GetHash(), &dwaNewUIDs); Append.m_Seconds = pSum->m_Seconds; hResult = Append.AppendMessageAcrossRemotes (); if (dwaNewUIDs.GetCount() == 1) { *pNewUid = dwaNewUIDs.GetAt(0); } return hResult; } // FindAll [PUBLIC] // FUNCTION // Do a server search of all messages for a match of the given string. // Search the entire text. // END FUNCTION // HRESULT CImapMailbox::FindAll (LPCSTR pSearchString, CString& szImapUidMatches) { HRESULT hResult = E_FAIL; BOOL bWeOpenedOurConnection = FALSE; // Do this first. szImapUidMatches.Empty(); // Must have a search string. if (! (pSearchString && *pSearchString) ) return E_INVALIDARG; // Make sure we can open the remote connection to our mailbox. if ( !IsSelected() ) { hResult = OpenMailbox (TRUE); if (!SUCCEEDED (hResult) ) return hResult; bWeOpenedOurConnection = TRUE; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Call CImap to do the work. hResult = m_pImap->UIDFindText (pSearchString, 1, 0xFFFFFFFF, szImapUidMatches); // If user cancelled, return that to caller in the HRESULT: // if (EscapePressed()) { hResult = HRESULT_MAKE_CANCEL; } // If we opened the connection, close it back. if (bWeOpenedOurConnection) Close(); return hResult; } // // Wrapper around CImapConnection:UIDFind. // HRESULT CImapMailbox::UIDFind (LPCSTR pHeaderList, BOOL bBody, BOOL bNot, LPCSTR pSearchString, LPCSTR pUidStr, CString& szResults) { HRESULT hResult = E_FAIL; BOOL bWeOpenedOurConnection = FALSE; // Do this first. szResults.Empty(); // Must have a search string. if (! (pSearchString && *pSearchString) ) return E_INVALIDARG; // Make sure we can open the remote connection to our mailbox. if ( !IsSelected() ) { hResult = OpenMailbox (TRUE); if (!SUCCEEDED (hResult) ) return hResult; bWeOpenedOurConnection = TRUE; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Call CImap to do the work. hResult = m_pImap->UIDFind (pHeaderList, bBody, bNot, pSearchString, pUidStr, szResults); // If we opened the connection, close it back. if (bWeOpenedOurConnection) Close(); return hResult; } // DoOnServerSearch [PUBLIC] // // Pass to the CImapConnection. // Note: If "pUidRange" is NULL, all messages on the server are searched. // // NOTE: 12/23/98 - Modified to do search in chunks. // HRESULT CImapMailbox::DoOnServerSearch (MultSearchCriteria* pMultiSearchCriteria, CString& szResults, LPCSTR pUidRange /* = NULL */) { HRESULT hResult = E_FAIL; BOOL bMustCloseConnection = FALSE; // Do this first. szResults.Empty(); // Must have a search string. if (! pMultiSearchCriteria ) return E_INVALIDARG; // Make sure we can open the remote connection to our mailbox. if (!IsSelected()) { int iConnectionState = GetConnectionState(bDontAllowOffline); if (iConnectionState == iStateGoOnlineForThis) { // The connection is being allowed for this action only: note that we must close the connection // when we are done. bMustCloseConnection = TRUE; } else if (iConnectionState == iStateStayOfflineDisallow) { // No connection is being created and this action cannot be done offline: bail out. return HRESULT_MAKE_OFFLINE; } hResult = OpenMailbox (TRUE); if (!SUCCEEDED(hResult)) { // Close the connection if it was opened just for us. if (bMustCloseConnection) { Close(); } return hResult; } } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } // Do it in chunks. // hResult = DoOnServerSearchInChunks_ (pMultiSearchCriteria, szResults, pUidRange); // Close the connection if it was opened just for us. if (bMustCloseConnection) { Close(); } return hResult; } // DoOnServerSearchKnown [PUBLIC] // BOOL CImapMailbox::DoOnServerSearchKnown (MultSearchCriteria* pMultiSearchCriteria, CString& szResults) { // If this is an as yet un-opened mailbox, then no matches found. // if (m_UIDHighest == 0) { return TRUE; } // Search up to what summary we've got. // CString szRange; szRange.Format ("1:%lu", m_UIDHighest); return DoOnServerSearch (pMultiSearchCriteria, szResults, szRange); } // Is this a criterion that IMAP can handle?? // // STATIC BOOL CImapMailbox::ImapServerCanSearch (SearchCriteria *pCurSearchCriteria) { // Ask CSeasrchUtil: // return CSearchUtil::ImapServerCanSearch (pCurSearchCriteria); } // DoOnServerSearchInChunks_ [PRIVATE] // // NOTE: 12/23/98 - Modified to do search in chunks. // Assume all sanity checks have already been made. // HRESULT CImapMailbox::DoOnServerSearchInChunks_ (MultSearchCriteria* pMultiSearchCriteria, CString& szResults, LPCSTR pUidRange /* = NULL */) { if (!m_pImap) { ASSERT(0); return E_FAIL; } // Do this first. szResults.Empty(); // Make sure we have messages on the server. // Ping(); if (m_NumberOfMessages == 0) return S_OK; // If in main thread, put up progress bar. // BOOL bWasInProgress = FALSE; BOOL bWePutProgressUp = FALSE; if ( IsMainThreadMT() ) { if (InProgress) { bWasInProgress = TRUE; PushProgress(); } CString buf; buf.Format ("Searching mailbox %s", m_FriendlyName); MainProgress(buf); Progress(0, buf, m_NumberOfMessages); bWePutProgressUp = TRUE; } // Estimate how many search iterations we'd have. // int dm = m_NumberOfMessages / MAX_UIDS_PER_COMMAND + 1; // Expand the given uid range into a comma-separated list. // If pUidRange is NULL, then we expand it to ALL uid's. // Note: ExpandUidRange return an allocated array - MUST FREE IT. // LPSTR pszRange = ExpandUidRange (pUidRange); BOOL bResult = FALSE; // Succeed if we did at least one a search. LPCSTR pNext = pszRange; CString szChunk; CString szCurrentResults; while (pNext) { szChunk.Empty(); szCurrentResults.Empty(); pNext = GetNextUidChunk (pNext, szChunk); if ( !szChunk.IsEmpty() && ( SUCCEEDED(m_pImap->DoOnServerSearch (pMultiSearchCriteria, szCurrentResults, szChunk)) ) ) { // Found any this trip? if ( !szCurrentResults.IsEmpty() ) { if ( !szResults.IsEmpty() ) szResults += comma; szResults += szCurrentResults; } bResult = TRUE; } else { break; } ProgressAdd(dm); } if (pszRange) delete[] pszRange; if ( IsMainThreadMT() ) TerminateProgress (bWePutProgressUp, bWasInProgress); return bResult ? S_OK : E_FAIL; } // // Search a comma-separated list of UID's for one matching "ulUid". // #define BSIZE 1024 BOOL CImapMailbox::Matched (CString& theList, unsigned long ulUid) { BOOL bResult = FALSE; CString str; CString buf; int nc; unsigned long Uid; // Must have a non-zero UID. if (ulUid == 0) return FALSE; // Copy: str = theList; while (!str.IsEmpty()) { nc = str.Find (comma); if (nc < 0) { // May still have a match Uid = atol (str); if (Uid == ulUid) { bResult = TRUE; } // In any case, get out.. break; } else if (nc == 0) { // Skip; str = str.Mid (1); } else { // Test. buf = str.Left (nc); str = str.Mid (nc + 1); // Do we have a match?? buf.TrimRight (); buf.TrimLeft (); Uid = atol (buf); if (Uid == ulUid) { bResult = TRUE; break; } } } return bResult; } // FUNCTION // Wrapper around CImapConnection's FetchAttachmentContentsToFile. // This will check to see if we are connected and selected and if not, // open the mailbox first. // END FUNCION HRESULT CImapMailbox::FetchAttachmentContentsToFile (IMAPUID uid, char *sequence, const char *Filename, short encoding, LPCSTR pSubtype /* = NULL */) { HRESULT hResult = S_OK; BOOL bSilent; // If we are in main thread, put up a progress bar. bSilent = ! ::IsMainThreadMT(); // Make sure we can open the remote connection to our mailbox. // BOOL bWeOpenedConnection = FALSE; if ( !IsSelected() ) { hResult = OpenMailbox (bSilent); if ( !SUCCEEDED (hResult) ) return hResult; bWeOpenedConnection = TRUE; } // Must have one of these now: // if (!m_pImap) { ASSERT (0); return E_FAIL; } hResult = m_pImap->FetchAttachmentContentsToFile (uid, sequence, Filename, encoding, pSubtype); // WE're getting closer to downloading all attachments. // if (SUCCEEDED (hResult) && m_pTocDoc) { CSumList & listSums = m_pTocDoc->GetSumList(); CSummary * pSum = listSums.GetByUid(uid); if (pSum) { ASSERT (pSum->m_nUndownloadedAttachments > 0); // If the TOC has to be rebuilt, it's possible to get an incorrect value for // the number of undownloaded attachments. There's nothing we can do about that. // if (pSum->m_nUndownloadedAttachments > 0) { pSum->m_nUndownloadedAttachments--; // Usage Statistics Support STARTS here BOOL bUpdateStats = FALSE; // Check if Stats need to accounted only for INBOX or not if (m_pImap && m_pImap->IsImapStatisticsForInboxOnly()) { // Tracking IMAP stats only for INBOX if(m_pImap->GetImapName() && !CRString(IDS_IMAP_RAW_INBOX_NAME).CompareNoCase(m_pImap->GetImapName())) bUpdateStats = TRUE; } else { // Tracking stats for all the IMAP mailboxes .. bUpdateStats = TRUE; } if (bUpdateStats) { // Update the Usage Statistics for Attachment received UpdateNumStat(US_STATRECEIVEDATTACH,1,pSum->m_Seconds + (pSum->m_TimeZoneMinutes * 60)); } // Usage Statistics Support ENDS here if (pSum->m_nUndownloadedAttachments == 0) pSum->RedisplayField (FW_SERVER); } } } if (bWeOpenedConnection) Close(); return hResult; } // FUNCTION // So it can be called from imaptoc // END FUNCION HRESULT CImapMailbox::DownloadAttachment ( LPCSTR pFilePath) { return ImapDownloaderFetchAttachment (pFilePath); } // ============== Public Interfacs to JOURNAL object methods =================/ // Public interfaces to journal and resyncer object methods. BOOL CImapMailbox::QueueRemoteXfer (IMAPUID sourceUID, ACCOUNT_ID DestAccountID, LPCSTR pDestImapMboxName, BOOL Copy) { return m_Journaler.QueueRemoteXfer (sourceUID, DestAccountID, pDestImapMboxName, Copy); } // ImapAppendSumList [PRIVATE] // // FUNCTION // For each CImapSum object in "pImapSumList", create a CSummary and add it to the summaries currently in the TOC, // updating any appropriate TOC attributes. // // NOTE: Also add it to pRefSumList BUT, only as a reference. Caller MUST NOT delete the object memory // when deleting the list itself!!! // // END SUMMARY // // HISTORY // (5/14/98 - JOK: Added bFromTmpMbx. If TRUE, then any summaries that // have pointers to an offset in an MBX file point to the temporary // MBX file. The data must be copied to the main MBX file. // (5/14/98 (JOK)) - Added pRefSumList. // // END HISTORY // // NOTE: This is NOT thread safe!!! This is done in the main thread. // // NOTE: This DOES NOT remove entries from the (in-parameter) pImapSumList. // BOOL CImapMailbox::ImapAppendSumList (CTocDoc* pTocDoc, CImapSumList* pImapSumList, CSumList* pRefSumList, BOOL bFromTmpMbx) { POSITION pos, next; BOOL bResult = TRUE; // Sanity. Must have a TOC if (!pTocDoc) return FALSE; // If no CImapSum summary list, then nothing to do. // Note: pRefSumList can be NULL. // if ( !(pImapSumList) ) return TRUE; // If none to add: // if (pImapSumList->GetCount() == 0) return TRUE; // Must create a new summary for each. // pos = pImapSumList->GetHeadPosition (); BOOL bRes; for (next = pos; pos; pos = next) { CImapSum *pImapSum = (CImapSum *) pImapSumList->GetNext (next); if (pImapSum) { CSummary *pSum = NULL; // First see if a summary with a matching UID already exists // this will happen when a previous operation using UIDPLUS // tries to preserve data associated with a summary after a // message has been transferred. pSum = pTocDoc->GetSummaryFromUID(pImapSum->GetHash()); if (!pSum) { pSum = DEBUG_NEW_MFCOBJ_NOTHROW CSummary; if (pSum) { // Turn off notifying search manager (don't need to save // previous value because the summary was just created). pSum->SetNotifySearchManager(false); pSum->m_TheToc = pTocDoc; pImapSum->CopyToCSummary (pSum); // Copy any text from teemporary to main MBX file (if bfromTmpMbx). // bRes = TRUE; if (bFromTmpMbx) { bRes = CopyTextFromTmpMbx (pTocDoc, pSum); } // Now go add the summary. // if (bRes) { // Note: Must format date here. // if ( pImapSum->m_RawDateString.IsEmpty() ) pSum->FormatDate(); else pSum->FormatDate(pImapSum->m_RawDateString); // Restore notifying search manager. Don't need to notify // search manager of the above changes, because we haven't // added it yet. Adding the summary below will notify the // search manager. pSum->SetNotifySearchManager(true); pTocDoc->AddSum(pSum); // Add to pRefSumList as well. // if (pRefSumList) pRefSumList->AddTail (pSum); } else { delete pSum; } } } } // Give back time to op-sys. // if (::EscapePressed()) break; } // Whether we succeeded or not, force a save of the TOC when we're exiting. // We don't want the MBX file to have an earlier timespamp than the TOC file. pTocDoc->SetModifiedFlag(); pTocDoc->SaveModified(); return bResult; } ///////////////////////////////////////////////////////////// // UpdateOldSummaries // FUNCTION // Loop through old summaries and update status flags. // NOTE: This function removes entries from NewUidList!!! // END FUNCTION ///////////////////////////////////////////////////////////// void CImapMailbox::UpdateOldSummaries (CTocDoc *pTocDoc, CPtrUidList& CurrentUidList) { // Sanity. if (!pTocDoc) return; if (CurrentUidList.GetCount() == 0) return; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); CSumList & listSums = pTocDoc->GetSumList(); POSITION pos = listSums.GetHeadPosition(); POSITION NextPos; for (NextPos = pos; pos; pos = NextPos) { CSummary* Sum = listSums.GetNext(NextPos); // If this is in CurrentUidList, we've found one. // Note: This is an inefficient search procedure because we may have to // loop through all of "CurrentUidList" to find the match!!! // POSITION UidPos = CurrentUidList.GetHeadPosition(); POSITION UidNext; for (UidNext = UidPos; UidPos; UidPos = UidNext) { CImapFlags *pF = (CImapFlags *) CurrentUidList.GetNext (UidNext); if ( pF && (pF->m_Uid == Sum->GetHash()) && !pF->m_IsNew) { // Copy selected Imap Flags from old messages. // NOTE: Important. Don't erase any other flag from Sum->m_Imflags, // especially the flag indicating the download status!! // // // First, clear the bits we'er interested in. Sum->m_Imflags &= ~(IMFLAGS_SEEN | IMFLAGS_ANSWERED | IMFLAGS_FLAGGED | IMFLAGS_DELETED | IMFLAGS_DRAFT ); // // Now set them if they're set. Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_ANSWERED); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_FLAGGED); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_DELETED); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_DRAFT); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_SEEN); // // Set the summary's READ, UNREAD and Answered flags. // If current state is one of the other flags, leave as-is. // int State = Sum->m_State; if (State == MS_READ || State == MS_UNREAD || State == MS_REPLIED) { if (Sum->m_Imflags & IMFLAGS_SEEN) Sum->SetState (MS_READ); else Sum->SetState (MS_UNREAD); if (Sum->m_Imflags & IMFLAGS_ANSWERED) Sum->SetState (MS_REPLIED); } // Now get rid of it. delete pF; CurrentUidList.RemoveAt (UidPos); break; } } // Give back time to op-sys. // if (::EscapePressed()) break; } } ///////////////////////////////////////////////////////////// // UpdateOldSummaries - MAP version // FUNCTION // Loop through old summaries and update status flags. // NOTE: This function removes entries from ModifiedUidMap!!! // NOTE: ModifiedUidMap will typically contain only UID's whose flags have actually // changed. // END FUNCTION ///////////////////////////////////////////////////////////// void CImapMailbox::UpdateOldSummaries (CTocDoc *pTocDoc, CUidMap& ModifiedUidMap) { // Sanity. if (!pTocDoc) return; if ( ModifiedUidMap.GetCount() == 0 ) return; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); CSumList & listSums = pTocDoc->GetSumList(); POSITION pos = listSums.GetHeadPosition(); POSITION NextPos; for (NextPos = pos; pos; pos = NextPos) { // Since we remove stuff from ModifiedUidMap, it may becose empty: if ( ModifiedUidMap.GetCount() == 0 ) break; CSummary* Sum = listSums.GetNext(NextPos); // If this is the Inbox and this message is junk then junk that message now. if (IsInbox(GetImapName()) && ((Sum->m_Imflags & IMFLAGS_DELETED) == 0) && (Sum->GetJunkScore() >= (unsigned char)GetIniShort(IDS_INI_MIN_SCORE_TO_JUNK)) && UsingFullFeatureSet() && GetIniShort(IDS_INI_USE_JUNK_MAILBOX)) { // Junk the message. pTocDoc->ImapChangeMsgsJunkStatus(Sum, true); } else { // If this is in ModifiedUidMap, we've found one. // UidIteratorType ci = ModifiedUidMap.find ( Sum->GetHash() ); if ( ci != ModifiedUidMap.end() ) { CImapFlags *pF = (CImapFlags *) (*ci).second; if ( pF && (pF->m_Uid == Sum->GetHash()) && !pF->m_IsNew) { // Copy selected Imap Flags from old messages. // NOTE: Important. Don't erase any other flag from Sum->m_Imflags, // especially the flag indicating the download status!! // // // First, clear the bits we'er interested in. Sum->m_Imflags &= ~(IMFLAGS_SEEN | IMFLAGS_ANSWERED | IMFLAGS_FLAGGED | IMFLAGS_DELETED | IMFLAGS_DRAFT ); // // Now set them if they're set. Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_ANSWERED); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_FLAGGED); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_DELETED); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_DRAFT); Sum->m_Imflags |= (pF->m_Imflags & IMFLAGS_SEEN); // // Set the summary's READ, UNREAD and Answered flags. // If current state is one of the other flags, leave as-is. // int State = Sum->m_State; if (State == MS_READ || State == MS_UNREAD || State == MS_REPLIED) { if (Sum->m_Imflags & IMFLAGS_SEEN) Sum->SetState (MS_READ); else Sum->SetState (MS_UNREAD); if (Sum->m_Imflags & IMFLAGS_ANSWERED) Sum->SetState (MS_REPLIED); } // Now get rid of it. ModifiedUidMap.erase (ci); delete pF; } } } // Give back time to op-sys. // if (::EscapePressed()) break; } } // // Set the TocDoc's frame name to <Account::Name> // void CImapMailbox::SetFrameName (CTocDoc *pTocDoc) { // Sanity: if (!pTocDoc) return; // Get acount. CImapAccount *pAccount = g_ImapAccountMgr.FindAccount (m_AccountID); if (pAccount) { CString szPersona; pAccount->GetName (szPersona); // Get the command object and the friendly name. QCImapMailboxCommand *pImapCommand = g_theMailboxDirector.ImapFindByImapName( GetAccountID(), GetImapName (), GetDelimiter () ); if (pImapCommand) { CString szFullName; szFullName.Format ("%s (%s)", pImapCommand->GetName(), szPersona); pTocDoc->ReallySetTitle (szFullName); } } } // // Internal error display method. Just call the external function. // void CImapMailbox::ShowLastImapError () { ::ShowLastImapError (m_pImap); } // ResetUnseenFlags [PUBLIC] // All messages in NewUidList that do not have the \seen flags set, unset it // on tyhe server. // void CImapMailbox::ResetUnseenFlags (CPtrUidList& NewUidList) { POSITION pos, nextPos; CImapFlags *pF; CString sUidlist, sUid; // Must have one of these now: // if (!m_pImap) { ASSERT (0); return; } pos = NewUidList.GetHeadPosition (); for (nextPos = pos; pos; pos = nextPos) { pF = ( CImapFlags * ) NewUidList.GetNext( nextPos ); if (! (pF && pF->m_Uid)) continue; if (pF->m_Imflags & IMFLAGS_SEEN) continue; // Ok. This is not seen. Add to list. if (sUidlist.IsEmpty()) sUidlist.Format("%lu", pF->m_Uid); else { sUid.Format (",%lu", pF->m_Uid); sUidlist += sUid; } } if (sUidlist.IsEmpty()) return; // Go remove the seen flag. m_pImap->UIDRemoveFlaglist (sUidlist, "(\\SEEN)"); } // // Perform Manual filtering action. This is called when the "Filter Messages" // menu is selected. // void CImapMailbox::FilterMessages (CTocDoc *pTocDoc, CSummary *SingleSum /* = NULL */) { // Sanity: if (!pTocDoc) return; HRESULT hResult = E_FAIL; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); CImapFilterActions FilterActions; // NOTE: Always set filename of mailbox. FilterActions.SetMBFilename (pTocDoc->GetMBFileName ()); // In the case of manual filtering forcing us to always be online might sometimes be overly harsh. // For example, if all filters do things like labelling that need no connection then we shouldn't // force the user online. This is a first pass and allowing offline manual filtering is a feature for // much further down the road. We'll deal with this properly then. In the meantime, don't allow // manual filtering when offline. -dwiggins BOOL bMustCloseConnection = FALSE; int iConnectionState = GetConnectionState(bDontAllowOffline); if (iConnectionState == iStateGoOnlineForThis) { // The connection is being allowed for this action only: note that we must close the connection // when we are done. bMustCloseConnection = TRUE; } else if (iConnectionState == iStateStayOfflineDisallow) { // No connection is being created and this action cannot be done offline: bail out. return; } hResult = OpenMailbox (TRUE); if (!SUCCEEDED(hResult)) { // Close the connection if it was opened just for us. if (bMustCloseConnection) { Close(); } return; } if (FilterActions.StartFiltering()) { FilterActions.DoManualFiltering (pTocDoc, SingleSum); FilterActions.EndFiltering(); } // This should update |deleted flage, etc!!. CTocView *pView = pTocDoc->GetView (); if (pView ) pView->m_SumListBox.SetRedraw(TRUE); // Close the connection if it was opened just for us. if (bMustCloseConnection) { Close(); } } // VerifyCache [PUBLIC] // Make sure the local mailbox directory exists. "CreateMailboxDirectory()" will return TRUE // if the directory already exists as a direcotry. // BOOL CImapMailbox::VerifyCache (BOOL bSilent /* = FALSE */) { CString buf; // Scratch buffer. if (!CreateMailboxDirectory (m_Dirname)) { if ( ::IsMainThreadMT() && !bSilent ) { ErrorDialog( IDS_ERR_DIR_CREATE, m_Dirname); } return FALSE; } // Create the local "Attach" directory for this mailbox. CString AttachDir; if (!CreateAttachDir (m_Dirname)) { if ( ::IsMainThreadMT() && !bSilent) { GetAttachDirPath (m_Dirname, buf); ErrorDialog( IDS_ERR_DIR_CREATE, buf); } return FALSE; } // Make sure the MBX file exists. CString MbxFilePath; GetMbxFilePath (m_Dirname, MbxFilePath); if (!CreateLocalFile (MbxFilePath, FALSE)) { if ( ::IsMainThreadMT() && !bSilent) { ErrorDialog( IDS_ERR_IMAP_FILE_CREATE, MbxFilePath); } return FALSE; } return TRUE; } // Create the contained CImapSettings object and fill it with user preferences. // // Note: Leave this as a separate method so we can always re-get the // settings. // void CImapMailbox::GrabSettings() { // Fill it: // if (!m_pImapSettings) { m_pImapSettings = DEBUG_NEW_NOTHROW CImapSettings (); } if (m_pImapSettings) m_pImapSettings->GrabSettings(m_AccountID); // Force the CImapConnection to update it's network settings: // if (m_pImap) m_pImap->UpdateNetworkSettings(); } HRESULT CImapMailbox::GetLastImapError (LPSTR pBuffer, short nBufferSize) { if (!pBuffer) { ASSERT (0); return E_FAIL; } // Initialize. *pBuffer = 0; if (m_pImap) { return m_pImap->GetLastImapError (pBuffer, nBufferSize); } return E_FAIL; } HRESULT CImapMailbox::GetLastServerMessage (LPSTR pBuffer, short nBufferSize) { if (!pBuffer) { ASSERT (0); return E_FAIL; } // Initialize. *pBuffer = 0; if (m_pImap) { return m_pImap->GetLastServerMessage (pBuffer, nBufferSize); } return E_FAIL; } HRESULT CImapMailbox::GetLastImapErrorAndType (LPSTR pBuffer, short nBufferSize, int *pType) { if (!pBuffer) { ASSERT (0); return E_FAIL; } // Initialize. *pBuffer = 0; if (m_pImap) { return m_pImap->GetLastImapErrorAndType (pBuffer, nBufferSize, pType); } return E_FAIL; } BOOL CImapMailbox::IsSelected () { return m_pImap ? m_pImap->IsSelected() : FALSE; } // RecreateMessageMap [PUBLIC] // void CImapMailbox::RecreateMessageMap () { if (m_pImap) m_pImap->RecreateMessageMap(); } // AcquireNetworkConnection [PUBLIC] // // Negotiate with the connection manager for a CImapConnection object. // HRESULT CImapMailbox::AcquireNetworkConnection () { CImapConnection *pImap = NULL; HRESULT hResult = GetImapConnectionMgr()->CreateConnection (m_AccountID, m_ImapName, &pImap, TRUE); if ( pImap && SUCCEEDED (hResult) ) { // Set internal pointer. // m_pImap = pImap; } return hResult; } // DownloadAttachmentsBeforeCompose [PUBLIC] // // If we had to ask, and the user said NOT to download, we then // clear "szAttach" and return HRESULT_MAKE_CANCEL; // If we need to download attachments, we do thaht here. // HRESULT CImapMailbox::DownloadAttachmentsBeforeCompose (CString& szAttach, UINT Optype) { HRESULT hResult = S_OK; if ( szAttach.IsEmpty() ) return S_OK; BOOL bDownloadAttachments = GetIniShort(IDS_INI_ALWAYS_DNLOAD_BEFORE_FWD); BOOL bWarn = GetIniShort(IDS_INI_WARN_DNLOAD_BEFORE_FWD); if (bWarn) { // Use out internal copy of string: // CString szOurAttach = szAttach; // Need to determine if any attachment is un-downloaded: // BOOL bFoundUndownloaded = FALSE; CString szOneAttach; szOneAttach.Empty(); int ns = 0; BOOL bDone = FALSE; while (!bDone && !bFoundUndownloaded) { ns = szOurAttach.Find (';'); if (ns > 0) { szOneAttach = szOurAttach.Mid (0, ns); // don't include the ';' szOurAttach = szOurAttach.Mid (ns + 2); // don't include the ';' or the space in the next filename -jdboyd } else { szOneAttach = szOurAttach; bDone = TRUE; } if (szOneAttach.GetLength()) bFoundUndownloaded = !IsImapDownloaded (szOneAttach); } if (!bFoundUndownloaded) { return S_OK; } // OK, We have to ask: // bDownloadAttachments = (YesNoDialog(IDS_INI_WARN_DNLOAD_BEFORE_FWD, IDS_INI_ALWAYS_DNLOAD_BEFORE_FWD, IDS_WARN_DNLOAD_BEFORE_FWD, Optype == MS_FORWARDED ? CRString (IDS_FIO_FORWARD) : CRString (IDS_FIO_REDIRECT) ) == IDOK); if (!bDownloadAttachments) hResult = HRESULT_MAKE_CANCEL; } if (!bDownloadAttachments) { szAttach.Empty(); return hResult; } // Otherwise, download all attachments. // // Use out internal copy of string: // CString szOurAttach = szAttach; CString szOneAttach; szOneAttach.Empty(); int ns = 0; BOOL bDone = FALSE; while (!bDone) { ns = szOurAttach.Find (';'); if (ns > 0) { szOneAttach = szOurAttach.Mid (0, ns); // don't include the ';' szOurAttach = szOurAttach.Mid (ns + 2); // don't include the ';' or the space in the next filename -jdboyd } else { szOneAttach = szOurAttach; bDone = TRUE; } if (szOneAttach.GetLength()) ImapDownloaderFetchAttachment (szOneAttach); } return S_OK; } // WriteOfflineMessage [PRIVATE] // // Call the downloaded to write a dummy "offline" message if we're attempting to download a message // and we;re offline. // HRESULT CImapMailbox::WriteOfflineMessage (CTocDoc* pTocDoc, CImapSum* pSum, BOOL bToTmpMbx /* = FALSE */) { HRESULT hResult = S_OK; // Sanity: // if (! (pTocDoc && pSum) ) return E_FAIL; // Open the MBX file for appending. This can be either the real // MBX file or the temporary one. // CString szMbxFilePath; if (bToTmpMbx) { GetTmpMbxFilePath (GetDirname(), szMbxFilePath); } else { szMbxFilePath = pTocDoc->GetMBFileName(); } // Instantiate an ImapDownloader object to do the downloading. CImapDownloader MbxDownloader (GetAccountID(), m_pImap, (LPCSTR) szMbxFilePath); // Make sure the file exists. Open it for appending. Don't truncate!! if (!MbxDownloader.OpenMbxFile (FALSE)) { ErrorDialog ( IDS_ERR_FILE_OPEN, szMbxFilePath, CRString (IDS_ERR_FILE_OPEN_WRITING) ); return E_FAIL; } // Go write dummy message to file. // hResult = MbxDownloader.WriteOfflineMessage (pSum); // // Note: Only the CImapDownloader can set IMFLAGS_NOT_DOWNLOADED into the summary. // Don't do it here because bResult can be TRUE if we wrote a dummy message to the MBX file. // // CLose the file back. MbxDownloader.CloseMbxFile (); return hResult; } // Ping [PUBLIC] // // Send a NOOP to the IMAP mailbox so we update our idea of the number of // messages on the server. // // NOTE: This can be called from outside. In that case, the connection is made // if it's not already. // void CImapMailbox::Ping() { // If we're offline, ignore it. // if ( GetIniShort(IDS_INI_CONNECT_OFFLINE) ) return; if (!IsSelected()) { HRESULT hResult = OpenMailbox (TRUE); if (! SUCCEEDED (hResult) ) { return; } } if ( IsSelected() && m_pImap) { m_pImap->Noop(); unsigned long nMsgs = 0; if ( SUCCEEDED(m_pImap->GetMessageCount(nMsgs)) ) m_NumberOfMessages = nMsgs; } } // ExpandUidRange [PRIVATE] // // NOTE: This returns an allocate array - MUST FREE IT. // // UNFINISHED: We just return a comma0list of ALL UID's. We need to // handle mixes of commas and colons, etc. // LPSTR CImapMailbox::ExpandUidRange (LPCSTR pUidRange) { // If range is a pure comma-separated list, just resturn that. // if ( pUidRange && (strchr (pUidRange, ':') == NULL) ) return SafeStrdupMT(pUidRange); if (!m_pImap) { ASSERT(0); return NULL; } // Get these in any case. // unsigned long uidHigh = 0; unsigned long uidLow = 0; if ( !SUCCEEDED(m_pImap->UIDFetchLastUid (uidHigh)) ) return NULL; if ( !SUCCEEDED(m_pImap->UIDFetchFirstUid (uidLow)) ) return NULL; // Note: uidHigh can be same as uidLow. // if (uidHigh == 0 || uidLow == 0 || uidHigh < uidLow) return NULL; // Estimate how much of a buffer we need. // #digits per UID * #uid's // int nDigits = 2; // Includes one for the comma. unsigned long max = uidHigh; while (max = max/10) nDigits++; // Include the first and last! // size_t totlen = (nDigits * (uidHigh - uidLow + 1)) + 1; LPSTR pStr = DEBUG_NEW_NOTHROW char[totlen]; LPSTR szUid = DEBUG_NEW_NOTHROW char [nDigits + 2]; int len; if (pStr && szUid) { *pStr = 0; LPSTR p = pStr; for (unsigned long uid = uidLow; uid <= uidHigh; uid++) { if (p == pStr) sprintf (szUid, "%lu", uid); else sprintf (szUid, ",%lu", uid); len = strlen(szUid); if ((pStr + totlen) > (p + len)) { sprintf (p, "%s", szUid); p += len; } else { // If we run out of room we obviously botched the size calculation above. // In the past we just overran the buffer, now we stop adding items if we // didn't allocate enough space. If this ASSERT() ever fires re-evaluate // the above size calculation. ASSERT(0); break; } } } delete[] szUid; return pStr; } //================ ImapMailboxMode functions ========================/ // NewImapMailboxNode () // Create a new ImapMailboxNode structure and initialize fields. // NOTES // END NOTES ImapMailboxNode *NewImapMailboxNode() { ImapMailboxNode *pNode = DEBUG_NEW_NOTHROW ImapMailboxNode; if (pNode) { memset ((void *)pNode, 0, sizeof (ImapMailboxNode)); } return pNode; } // SetImapAttributesFromImapNode // FUNCTION // Copy attributes from pMboxNode to the CImapMailbox object; // END FUNCTION void SetImapAttributesFromImapNode (CImapMailbox* pImapMbox, ImapMailboxNode *pNode) { if (!(pImapMbox && pNode)) return; // Set current mailbox state. pImapMbox->SetImapName (pNode->pImapName); pImapMbox->SetDirname (pNode->pDirname); pImapMbox->SetDelimiter (pNode->Delimiter); pImapMbox->SetNoInferiors (pNode->NoInferiors); pImapMbox->SetMarked (pNode->Marked); pImapMbox->SetUnMarked (pNode->UnMarked); pImapMbox->SetAutoSync (pNode->AutoSync); pImapMbox->SetImapType (pNode->Type); } // Free memory for a folders. Assumes that child list already deleted. void DeleteMailboxNode (ImapMailboxNode* pFolder) { if (pFolder) { if (pFolder->pDirname) delete[] pFolder->pDirname; if (pFolder->pImapName) delete[] pFolder->pImapName; delete pFolder; } } // Delete a child folder list from a folder. // Note: Don't delete the parent folder itself. void DeleteChildList (ImapMailboxNode *pParentFolder) { ImapMailboxNode *pFolder, *pNextFolder; if (!pParentFolder) return; pFolder = pParentFolder->ChildList; while (pFolder) { // Make sure. pNextFolder = pFolder->SiblingList; // Delete it's child list before deleting it. DeleteChildList (pFolder); // Delete it now. DeleteMailboxNode (pFolder); // Loop through siblings. pFolder = pNextFolder; } // Make sure to do this. pParentFolder->ChildList = NULL; } // Delete a sibling folder list from a folder. // Note: Don't delete the given folder itself. void DeleteSiblingList (ImapMailboxNode *pGivenFolder) { ImapMailboxNode *pFolder, *pNextFolder; if (!pGivenFolder) return; pFolder = pGivenFolder->SiblingList; while (pFolder) { // Make sure. pNextFolder = pFolder->SiblingList; // Delete it's child list before deleting it. DeleteChildList (pFolder); // Delete it now. DeleteMailboxNode (pFolder); // Loop through siblings. pFolder = pNextFolder; } // Make sure to do this. pGivenFolder->SiblingList = NULL; } // Delete a complete folder subtree, INCLUDING the starting folder. // Note: It is up to the calling function to take note of the fact that // this memory is no longer available and that the passed-in pointer is no longer valid! void DeleteFolderSubtree (ImapMailboxNode *pStartingFolder) { // Sanity. if (!pStartingFolder) return; // Delete child list. DeleteChildList (pStartingFolder); pStartingFolder->ChildList = NULL; // Delete sibling list. DeleteSiblingList (pStartingFolder); pStartingFolder->SiblingList = NULL; // Now, delete me. DeleteMailboxNode (pStartingFolder); } // =================== Global Routines ==============================// // ================= exported Utility Functions ===========================// // ExpungeAfterDelete [EXPORTED] // // Return TRUE if the IDS_INI_IMAP_REMOVE_ON_DELETE flag is set for the personality that // pTocDoc is a member of. // BOOL ExpungeAfterDelete (CTocDoc *pTocDoc) { if (! (pTocDoc && pTocDoc->m_pImapMailbox) ) return FALSE; // Just return the value in m_Settings. // return pTocDoc->m_pImapMailbox->GetSettingsShort (IDS_INI_IMAP_REMOVE_ON_DELETE); } // FUNCTION // Wade through NewUidList and any entries that are also in CurrentUidList, move to NewOldUidList // with the new flags. // If there is any entry in NewUidList that has Uid == 0, remove it. // AT the end, we should have the New Uid list containing truly new messages and // "CurrentUidList" containing only messages that are no longer on the server. // "NewOldUidList" will contain messages that should remain in the local cache, // but probably with new flags (e.g, someone may have set the \Deleted flags. // END FUNCTION // // NOTE: // The assumption is that these lists are ordered in ascending order of UID!!! // END NOTE // // void MergeUidListsMT (CPtrUidList& CurrentUidList, CPtrUidList& NewUidList, CPtrUidList& NewOldUidList) { POSITION oldPos, oldNext; POSITION newPos, newNext; CImapFlags *pOldF, *pNewF; unsigned long curUid; // // Clear NewOldUidList // NewOldUidList.DeleteAll (); oldPos = CurrentUidList.GetHeadPosition(); newPos = NewUidList.GetHeadPosition(); // Loop through oldPos. for (oldNext = oldPos; oldPos; oldPos = oldNext) { pOldF = ( CImapFlags * ) CurrentUidList.GetNext( oldNext ); if (pOldF) { curUid = pOldF->m_Uid; // Loop through pNewF until we get to the same or next higher UID. // while (newPos) { newNext = newPos; pNewF = ( CImapFlags * ) NewUidList.GetNext ( newNext ); if (pNewF) { // Delete any zero-uid entries. if (pNewF->m_Uid == 0) { // Delete NewUidList.RemoveAt (newPos); delete pNewF; // Loop to the next entry. newPos = newNext; } else if (pNewF->m_Uid == curUid) { // This gets deleted both from NewUidList and from CurrentUidList, // and added to NewOldUidList; // Note: The resulting "NewOldUidList" will be in ascending UID-order. // CurrentUidList.RemoveAt (oldPos); NewOldUidList.AddTail ( pOldF); // // Merge flags. Set the Seen flag from our value but copy the rest from remote. // // First, clear the bits we'er interested in. pOldF->m_Imflags &= ~( IMFLAGS_SEEN | IMFLAGS_ANSWERED | IMFLAGS_FLAGGED | IMFLAGS_DELETED | IMFLAGS_DRAFT | IMFLAGS_RECENT ); // pOldF->m_Imflags |= (pNewF->m_Imflags & IMFLAGS_DELETED); pOldF->m_Imflags |= (pNewF->m_Imflags & IMFLAGS_RECENT); pOldF->m_Imflags |= (pNewF->m_Imflags & IMFLAGS_SEEN); pOldF->m_Imflags |= (pNewF->m_Imflags & IMFLAGS_ANSWERED); pOldF->m_Imflags |= (pNewF->m_Imflags & IMFLAGS_FLAGGED); pOldF->m_Imflags |= (pNewF->m_Imflags & IMFLAGS_DRAFT); // Delete pOldF from list. NewUidList.RemoveAt (newPos); delete pNewF; pNewF = NULL; // Do next on current list. newPos = newNext; break; } else if (pNewF->m_Uid > curUid) { // // Next time we start with this pNewF again. // Don't update newPos. // break; } else // pNewF->m_Uid < curUid. { // Haven't got to a UID that is equal or greater. Keep looping. newPos = newNext; } } else { // Invalid entry. Remove. // NewUidList.RemoveAt (newPos); // Keep looping. newPos = newNext; } } // while new list } else { // Remove any empty node. CurrentUidList.RemoveAt (oldPos); } } // for current list. } // Allocate memory and copy buf to it. LPSTR CopyString (LPCSTR buf) { LPSTR p = NULL; if (!buf) return NULL; p = DEBUG_NEW_NOTHROW char [strlen (buf) + 2]; if (p) { strcpy (p, buf); } return p; } // CreateLocalFile // FUNCTION // Given the full path to a file, if it doesn't exist, create it read/write. // If "Truncate", delete its contents. // END FUNCTION BOOL CreateLocalFile (LPCSTR pFilepath, BOOL Truncate) { DWORD Attributes; BOOL bResult = FALSE; if (pFilepath) { // If file exists, truncate it. Attributes = GetFileAttributes (pFilepath); if (Attributes != 0xFFFFFFFF) { // Make sure it's a file. if (! (Attributes & FILE_ATTRIBUTE_DIRECTORY) ) { // Its a file. Truncate? if (Truncate) { bResult = ChangeFileSize (pFilepath, 0); } else bResult = TRUE; } else { return FALSE; } } else { // Doesnt exist. Create it. JJFileMT jFile; if (SUCCEEDED (jFile.Open (pFilepath, O_RDWR | O_CREAT) ) ) { bResult = TRUE; jFile.Close(); } } } return bResult; } // If the file exists, remove it. void DeleteLocalFile (LPCSTR pPathname) { if (!pPathname) return; if (FileExistsMT (pPathname)) { _chmod (pPathname, _S_IREAD | _S_IWRITE); _unlink (pPathname); } } // Given a parent directory name and a child name, create a full pathname. void MakePath (LPCSTR pParent, LPCSTR pName, CString &Path) { if (!(pParent && pName)) return; Path = pParent; if (Path.Right ( 1 ) != DirectoryDelimiter) Path += DirectoryDelimiter; Path += pName; } // DirectoryExists // Return TRUE if a directory with the given pathname exists. // The name must be a full path. BOOL DirectoryExists (LPCSTR pPath) { DWORD Attributes; // If the directory exists, OK. Attributes = GetFileAttributes ((LPCSTR)pPath); if (Attributes == 0xFFFFFFFF) return FALSE; else { // Make sure it's a directory. if (Attributes & FILE_ATTRIBUTE_DIRECTORY) return TRUE; else return FALSE; } } // FormatBasePath // Given a directory name, make sure it has a trailing directory // delimiter character. // NOTES // Write the result into BasePath. // END NOTES void FormatBasePath (LPCSTR pPath, CString &BasePath) { int i; if (!pPath) return; BasePath = pPath; i = BasePath.GetLength(); if (i <= 0) return; if (BasePath.GetAt (i - 1) != DirectoryDelimiter) BasePath += CString (DirectoryDelimiter); } // void StripTrailingDelimiter (CString &myName) { int length; length = myName.GetLength(); while ((length > 0) && (myName.Right ( 1 ) == DirectoryDelimiter)) { length--; myName = myName.Left ( length ); } } // ChangeFileSize. BOOL ChangeFileSize (LPCSTR pFilepath, long length) { JJFileMT jFile; BOOL bResult = FALSE; if (pFilepath) { if (SUCCEEDED(jFile.Open (pFilepath, O_RDWR) ) ) { bResult = SUCCEEDED (jFile.ChangeSize ( length ) ); jFile.Close(); } } return bResult; } // BOOL CreateMailboxDirectory (LPCSTR pDirname) // FUNCTION // Create the directory housing a mailbox. // END FUNCTION. BOOL CreateMailboxDirectory (LPCSTR pDirname) { if (!pDirname) return FALSE; // If the dirname exists as a file, delete it. DWORD Attributes = GetFileAttributes (pDirname); if ( (Attributes != 0xFFFFFFFF) && // Exists ! (Attributes & FILE_ATTRIBUTE_DIRECTORY) ) // Is a file. { DeleteLocalFile (pDirname); } // If the directory doesn't exist, try now to create it. if ( !DirectoryExists (pDirname) ) { // Try to create. if (!CreateDirectory (pDirname, NULL)) { return FALSE; } } // If it doesn't exist now, we really can't create it. if (!DirectoryExists (pDirname)) { return FALSE; } else return TRUE; } // CreateMbxFile // NOTES // If the file already exists, don't truncate. // END NOTES BOOL CreateMbxFile (LPCSTR pMailboxDir) { CString MbxFilePath; if (pMailboxDir) { if (GetMbxFilePath (pMailboxDir, MbxFilePath)) { return CreateLocalFile (MbxFilePath, FALSE); } } return FALSE; } // CreateAttachDir // FUNCTION // Given the name of a directory housing a mailbox, create a subdirectory named "Attach" // for storing attachments. // END FUNCTION // NOTES // Return FALSE if we couldn't create the directory. // END NOTES BOOL CreateAttachDir (LPCSTR pPathname) { CString AttachDir; GetAttachDirPath (pPathname, AttachDir); // If it exists, OK DWORD Attributes = GetFileAttributes (AttachDir); // Exists? if (Attributes != 0xFFFFFFFF) // Yes. It exists. { if (Attributes & FILE_ATTRIBUTE_DIRECTORY) { return TRUE; } else { // It's a file, remove it. DeleteLocalFile (AttachDir); } } // Ok Try to create it. return CreateDirectory (AttachDir, NULL); } // GetAttachDirPath // FUNCTION // Given the name of a directory housing a mailbox, format a full path to // its "Attach" subdirectory. // END FUNCTION // NOTES // END NOTES void GetAttachDirPath (LPCSTR pPathname, CString& FullPath) { if (!pPathname) return; FullPath = pPathname; if (FullPath.Right ( 1 ) != DirectoryDelimiter) { FullPath += DirectoryDelimiter; } FullPath += CRString (IDS_IMAP_ATTACH_DIRNAME); } // GetMbxFilePath // FUNCTION // Given the mailbox directory (pMailboxDir), create a full pathname to // the contained MBX file. // Return the MBX filepath in MbxFilePath. // END FUNCTION BOOL GetMbxFilePath (LPCSTR pMailboxDir, CString& MbxFilePath) { int length, i; CString path; if (!pMailboxDir) return FALSE; // pMailboxDir MUST have at least a directory delimiter AND another char in the name. // i.e., at least "\a". path = pMailboxDir; length = path.GetLength(); if (length < 2) return FALSE; // Remove any trailing delimiter. if (path[length - 1] == DirectoryDelimiter) { path = path.Left (length - 1); length--; } // Add the last name. i = path.ReverseFind (DirectoryDelimiter); if ((i >= 0) && (i < (length - 1)) ) { MbxFilePath = path + DirectoryDelimiter + path.Mid (i + 1) + CRString (IDS_MAILBOX_EXTENSION); return TRUE; } return FALSE; } // GetTmpMbxFilePath // FUNCTION // Given the mailbox directory (pMailboxDir), create a full pathname to // the contained temporary MBX file. // Return the MBX filepath in MbxFilePath. // END FUNCTION BOOL GetTmpMbxFilePath (LPCSTR pMailboxDir, CString& TmpMbxFilePath) { int length, i; CString path; if (!pMailboxDir) return FALSE; // pMailboxDir MUST have at least a directory delimiter AND another char in the name. // i.e., at least "\a". path = pMailboxDir; length = path.GetLength(); if (length < 2) return FALSE; // Remove any trailing delimiter. if (path[length - 1] == DirectoryDelimiter) { path = path.Left (length - 1); length--; } // Change name to tmp_Name.tbx.. i = path.ReverseFind (DirectoryDelimiter); if ((i >= 0) && (i < (length - 1)) ) { CString Name = "tmp_" + path.Mid (i + 1); TmpMbxFilePath = path + DirectoryDelimiter + Name + CRString (IDS_IMAP_TMPMBX_EXTENSION); return TRUE; } return FALSE; } // GetInfFilePath // FUNCTION // Given the mailbox directory (pMailboxDir), create a full pathname to // the contained INF file. // Return the INF filepath in InfFilePath. // END FUNCTION BOOL GetInfFilePath (LPCSTR pMailboxDir, CString& InfFilePath) { int length, i; CString path; if (!pMailboxDir) return FALSE; // pMailboxDir MUST have at least a directory delimiter AND another char in the name. // i.e., at least "\a". path = pMailboxDir; length = path.GetLength(); if (length < 2) return FALSE; // Remove any trailing delimiter. if (path[length - 1] == DirectoryDelimiter) { path = path.Left (length - 1); length--; } // Add the last name. i = path.ReverseFind (DirectoryDelimiter); if ((i >= 0) && (i < (length - 1)) ) { InfFilePath = path + DirectoryDelimiter + path.Mid (i + 1) + CRString (IDS_IMAP_INFO_FILE_EXTENSION); return TRUE; } return FALSE; } // MbxFilePathToMailboxDir // FUNCTION // Given the full path to a mailbox directory, extract the name of the containing directory into // "MailboxDir". // END FUNCTION BOOL MbxFilePathToMailboxDir (LPCSTR pMbxFilepath, CString& MailboxDir) { int i; CString path; BOOL bResult = FALSE; if (!pMbxFilepath) return FALSE; // Make sure this is an mbx file path. path = pMbxFilepath; path.TrimRight(); i = path.ReverseFind ('.'); if (i > 0) { path = path.Mid (i); // .mbx (includes dot) if (path.CompareNoCase (CRString (IDS_MAILBOX_EXTENSION)) == 0) { bResult = TRUE; } } if (bResult) { bResult = FALSE; path = pMbxFilepath; i = path.ReverseFind (DirectoryDelimiter); if (i == 0) // \name.mbx???? { path = path.Left (1); bResult = TRUE; } else { path = path.Left (i); bResult = TRUE; } if (bResult) MailboxDir = path; } return bResult; } // ImapIsTmpMbx // FUNCTION // Return TRUE if the given filename ends in ".tbx". // END FUNCTION BOOL ImapIsTmpMbx (LPCSTR pFilename) { if (!pFilename) return FALSE; CString ext = pFilename; int i = ext.ReverseFind ('.'); if (i > 0) { ext = ext.Mid (i); if (ext.CompareNoCase (CRString (IDS_IMAP_TMPMBX_EXTENSION)) == 0) return TRUE; } return FALSE; } // CopyAttachmentFile // FUNCTION // Copy an attachment file between attachment directories. // END FUNCTION // NOTES // "pFilename" may be a full pathname, in which case, strip tha path off. Get a unique // filename in the destination directory. Return the full pathname of the destination // file in "NewPathName". // END NOTES BOOL ImapCopyAttachmentFile (LPCSTR pSourceAttachmentDir, LPCSTR pTargetMailboxDir, LPCSTR pFilename, CString& NewPathname) { char buf [MAXBUF + 4]; char Name [MAXBUF + 4]; CString str; JJFileMT* AttachFile = NULL; BOOL bResult = FALSE; if (!(pSourceAttachmentDir && pTargetMailboxDir && pFilename)) return FALSE; // Strip path, if any. str = pFilename; int i = str.ReverseFind (DirectoryDelimiter); if (i >= 0) str = str.Mid (i + 1); // Copy to Name. if (str.GetLength() > MAXBUF) return FALSE; strcpy (Name, (LPCSTR) str); // Get unique filename in the "Attach" subdirectory of pTargetMailboxDir. str = pTargetMailboxDir; // Need to do this for "OpenLocalAttachFile()!!!" if (str.Right ( 1 ) != DirectoryDelimiter) { str += DirectoryDelimiter;; } // We need to put stuff into a char array for OpenLocalAttachFile(). if (str.GetLength() > MAXBUF) return FALSE; strcpy (buf, (LPCSTR)str); AttachFile = OpenLocalAttachFile(buf, Name, false); if (AttachFile) { BSTR pAllocStr = NULL; // Put the filename into "NewPathname". if (SUCCEEDED ( AttachFile->GetFName(&pAllocStr) ) && pAllocStr != NULL) { NewPathname = pAllocStr; SysFreeString (pAllocStr); pAllocStr = NULL; } AttachFile->Close(); if (!NewPathname.IsEmpty()) { // Full path to source file. str = pSourceAttachmentDir; if (str.Right ( 1 ) != DirectoryDelimiter) { str += DirectoryDelimiter; } str += Name; // Do the copy. Overwrite existing file. bResult = CopyFile (str, NewPathname, FALSE); } delete AttachFile; } if (!bResult) NewPathname.Empty(); return bResult; } // // NOTES // This returns a complete path in "Newpath" // END NOTES BOOL GetUniqueTempFilepath (LPCSTR pParentDir, LPCSTR pBaseName, CString &Newpath) { CString Name, BaseName; int i, trial; const int MaxTrial = 1000; BOOL bResult = FALSE; CString DirectoryPrefix; // pTopNode can be NULL. if (!(pParentDir && pBaseName)) return FALSE; // Use pCurNode->pImapName as the suggested name. // If name begins with a dot, keep it a part of the name, // otherwise use only the chars before the dot. // Make sure it's at most MaxNameLength characters long. Name = pBaseName; // Delete any ".extension" in filename. i = Name.Find('.'); while (i >= 0) { if (i == 0) { // If name is something like ".xxx", use "xxx". Name = Name.Mid ( 1 ); // Make sure we don't have any more. i = Name.Find ('.'); } else if (i > 0) { // Use basename; Name = Name.Left (i); i = -1; // Stop here. } else { // else use as is. i = -1; } } // Do we have anything left? if (Name.IsEmpty()) Name = '0'; // Extract basename if contains directory delimiters. i = Name.ReverseFind (DirectoryDelimiter); if (i >= 0) { Name = Name.Mid (i + 1); } // Do we have anything left? if (Name.IsEmpty()) Name = '0'; // See if we already have that name (Case insensitive compare, since the name become // files in a possibly FAT file system). Add a uniquifier digit. // Format the containing directory name with a trailing directory delimiter. DirectoryPrefix = pParentDir; if (DirectoryPrefix.Right ( 1 ) != DirectoryDelimiter) DirectoryPrefix += DirectoryDelimiter; // Now go make sure there's no duplicate file or directory name. BaseName = Name; bResult = FALSE; for (trial = 0; trial <= MaxTrial; trial++) { if (FileExistsMT (DirectoryPrefix + Name)) { // Found an existing file or directory. Add a uniquifier. Name.Format ("%s%d", (LPCSTR)BaseName, trial); } // if else { // Found a unique name. bResult = TRUE; break; } } // Did we get a unique name?? if (trial > MaxTrial || Name.IsEmpty()) return FALSE; // Ok. Found one at last. bResult = TRUE; // Found a unique name. // Make sure copy Name to NewName. if (bResult) { Newpath = DirectoryPrefix + Name; } return bResult; } // FUNCTION // Delete a filesystem directory. If "DeleteChildren" is TRUE, delete all // contained files and subdirectories. // END FUNCTION BOOL RemoveLocalDirectory (LPCSTR pPathname, BOOL RemoveChildren) { BOOL bResult = TRUE; CString Path; CString Name; if (!pPathname) return FALSE; // If this is a simple file, just delete it. DWORD Attributes = GetFileAttributes (pPathname); // Does it even exist? If not, still return TRUE. if (Attributes == 0xFFFFFFFF) return TRUE; // Is it a directory. if (Attributes & FILE_ATTRIBUTE_DIRECTORY) { if (RemoveChildren) { CFileFind finder; Path = pPathname; Path += "\\*.*"; BOOL bWorking = finder.FindFile(Path); while (bWorking) { bWorking = finder.FindNextFile(); // Ignore "." and ".." Path = finder.GetFilePath(); Name = finder.GetFileName(); if ( !( (Name.Compare (".") == 0) || (Name.Compare ("..") == 0) ) ) { if (finder.IsDirectory()) { bResult = RemoveLocalDirectory( Path, TRUE) && bResult; } else DeleteLocalFile (Path); } } } // Remove the directory itselt. // BUG: Should do the foll: // 1. If the directory is the current working directory, set the cwd up one level. bResult = RemoveDirectory (pPathname) && bResult; #ifdef _MYDEBUG if (!bResult) { // For debugging: int error = GetLastError(); } #endif } else { DeleteLocalFile (pPathname); } return bResult; } // FUNCTION // Formulate a friendly name for a mailbox. // Write the result into FriendlyName. // END FUNCTION void FormulateFriendlyImapName (LPCSTR pImapName, TCHAR DelimiterChar, CString& FriendlyName) { if (!pImapName) return; // At the very least, return pImapName. FriendlyName = pImapName; // Is this INBOX?? CRString INBOX (IDS_IMAP_RAW_INBOX_NAME); if (INBOX.CompareNoCase (pImapName) == 0) { FriendlyName = CRString (IDS_IMAP_FRIENDLY_INBOX_NAME); } else { // User the basename. if (DelimiterChar) { int i = FriendlyName.ReverseFind (DelimiterChar); if (i >= 0) FriendlyName = FriendlyName.Mid (i + 1); } } } // DoingMinimalDownload [INTERNAL] // FUNCTION // DETERMINE if the user wants us to do minimal download for the given mailbox. // END FUNCTION BOOL DoingMinimalDownload (CImapMailbox *pImapMailbox) { // Must have a mailbox. if (!pImapMailbox) return TRUE; // Just do a GetIniShort for now. return pImapMailbox->GetSettingsShort (IDS_INI_IMAP_MINDNLOAD); } /////////////////////////////////////////////////////////////////////////////////// // RenameMboxDirAndContents // // Given the name of a local directory housing a mailbox, and an ImapMailboxNode // representing a renamed mailbox, go find a new unique name for the mailbox // within it's parent directory, rename it and it's contents. // Return the new name (just the relative name) in szNewDirname. /////////////////////////////////////////////////////////////////////////////////// BOOL RenameMboxDirAndContents (LPCSTR pOldDirpath, ImapMailboxNode *pNode, CString& szNewDirname, LPCSTR pNewParentDir /* = NULL */) { CString szPathname; BOOL bResult = FALSE; // Sanity: if ( ! (pOldDirpath && pNode) ) { ASSERT (0); return FALSE; } // Clear this in case... szNewDirname.Empty(); // If a parent directory is given, use that, otherwise use // the same parent directory as pOldDirpath. // if (pNewParentDir) { szPathname = pNewParentDir; } else { char szDrive[ _MAX_DRIVE ]; char szDir[ 1024 ]; char szFname[ 256 ]; char szExt[ _MAX_EXT ]; // // Find the parent directory. MUST have one!! // _splitpath( pOldDirpath, szDrive, szDir, szFname, szExt ); // This is the parent directory. szPathname = szDrive; szPathname += szDir; } // remove trailing directory delimiter if any. if( szPathname.Right(1) == '\\' ) { szPathname = szPathname.Left( szPathname.GetLength() - 1 ); } // // Get a new unique directory name. // CString szBasename; if ( MakeSuitableMailboxName (szPathname, NULL, pNode, szBasename, 64) ) { // Format a full path. szPathname += DirectoryDelimiter + szBasename; // Now rename the directory. If we couldn't rename directory, // create new one. // BOOL bSuccess = SUCCEEDED ( ::FileRenameMT( pOldDirpath, szPathname ) ); if (!bSuccess) { bSuccess = CreateMailboxDirectory (szPathname); } // Rename all the internal files RenameInternalMailboxFiles (pOldDirpath, szPathname); // Copy basename to szNewDirname to be returned. szNewDirname = szBasename; // Succeeded. bResult = bSuccess; } return bResult; } // // RenameInternalMailboxFiles // Alter a mailbox directory has been renamed, rename the internal // MBX, TOC, inf, act, opt files. // // // NOTES // This may be a non-selectable mailbox, in which case the MBX and TOC files may not exist. // END NOTES // BOOL RenameInternalMailboxFiles (LPCSTR pOldDirPathname, LPCSTR pNewDirPathname) { CString szOldDirname; CString szNewDirname; CString szOldFilepath, szNewFilepath; // Sanity if (! (pOldDirPathname && pNewDirPathname) ) { ASSERT (0); return FALSE; } // Extract the old directory name. szOldDirname = pOldDirPathname; int nc = szOldDirname.ReverseFind (DirectoryDelimiter); if (nc >= 0) szOldDirname = szOldDirname.Mid (nc + 1); // Extract the new directory name. szNewDirname = pNewDirPathname; nc = szNewDirname.ReverseFind (DirectoryDelimiter); if (nc >= 0) szNewDirname = szNewDirname.Mid (nc + 1); // Rename the MBX file szOldFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szOldDirname, CRString (IDS_MAILBOX_EXTENSION) ); szNewFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szNewDirname, CRString (IDS_MAILBOX_EXTENSION) ); // // Make sure no file exists with the new name. If a sub-directory exists with this name, // "RemoveLocalDirectory" will remove it. It will also remove it if it's a file. // RemoveLocalDirectory (szNewFilepath, TRUE); // BUG: We should check for success here!! FileRenameMT (szOldFilepath, szNewFilepath); // Rename the TOC file szOldFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szOldDirname, CRString (IDS_TOC_EXTENSION) ); szNewFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szNewDirname, CRString (IDS_TOC_EXTENSION) ); // // Make sure no file exists with the new name. If a sub-directory exists with this name, // "RemoveLocalDirectory" will remove it. It will also remove it if it's a file. // RemoveLocalDirectory (szNewFilepath, TRUE); FileRenameMT (szOldFilepath, szNewFilepath); // Rename the INF file szOldFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szOldDirname, CRString (IDS_IMAP_INFO_FILE_EXTENSION) ); szNewFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szNewDirname, CRString (IDS_IMAP_INFO_FILE_EXTENSION) ); // // Make sure no file exists with the new name. If a sub-directory exists with this name, // "RemoveLocalDirectory" will remove it. It will also remove it if it's a file. // RemoveLocalDirectory (szNewFilepath, TRUE); FileRenameMT (szOldFilepath, szNewFilepath); // Rename the ACT file szOldFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szOldDirname, CRString (IDS_IMAP_JRNL_FILE_EXTENSION) ); szNewFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szNewDirname, CRString (IDS_IMAP_JRNL_FILE_EXTENSION) ); // // Make sure no file exists with the new name. If a sub-directory exists with this name, // "RemoveLocalDirectory" will remove it. It will also remove it if it's a file. // RemoveLocalDirectory (szNewFilepath, TRUE); FileRenameMT (szOldFilepath, szNewFilepath); // Rename the OPT file szOldFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szOldDirname, CRString (IDS_IMAP_RESYNCOPT_FILE_EXTENSION) ); szNewFilepath.Format ("%s%c%s%s", pNewDirPathname, DirectoryDelimiter, szNewDirname, CRString (IDS_IMAP_RESYNCOPT_FILE_EXTENSION) ); // // Make sure no file exists with the new name. If a sub-directory exists with this name, // "RemoveLocalDirectory" will remove it. It will also remove it if it's a file. // RemoveLocalDirectory (szNewFilepath, TRUE); FileRenameMT (szOldFilepath, szNewFilepath); return TRUE; } ////////////////////////////////////////////////////////////////////////////////////////////// // CreateDirectoryForMailbox // // Get a unique directory within "pParentDir" and create it. Set the full pathname into // pImapNode->pDirname; // "pImapNode" contains all the info needed. ////////////////////////////////////////////////////////////////////////////////////////////// BOOL CreateDirectoryForMailbox (LPCSTR pParentDir, ImapMailboxNode *pImapNode, CString& szNewDirname) { BOOL bResult = FALSE; // Sanity: if (! (pParentDir && pImapNode) ) return FALSE; // Get a unique directory name and create it NOW!.We will create the // files within the directory later. CString szBasename; bResult = MakeSuitableMailboxName (pParentDir, NULL, pImapNode, szBasename, 64); if (bResult) { // Format a path to DirName and copy it to pCurNode->pPathname. CString Path = pParentDir; if (Path.Right (1) != DirectoryDelimiter) Path += DirectoryDelimiter; Path += szBasename; // Set it into the node. if (pImapNode->pDirname) delete[] (pImapNode->pDirname); pImapNode->pDirname = CopyString (Path); // Make sure the directory exists or that we can create it. bResult = CreateMailboxDirectory (Path); // Set output parameters. if (bResult) szNewDirname = szBasename; } return bResult; } ///////////////////////////////////////////////////////////////////////////////// // ServerHasHigherUid // // Look at the last element in the list and return it's UID. // that any UID in CurrentUidList. // ///////////////////////////////////////////////////////////////////////////////// unsigned long GetLocalHighestUid (CPtrUidList& CurrentUidList) { POSITION pos; unsigned long Uid = 0; // // Note: We can simply compare UidServerHighest with the tail position in the // list because CurrentUidList is ordered!! // pos = CurrentUidList.GetTailPosition (); if (pos) { CImapFlags *pF = (CImapFlags *) CurrentUidList.GetPrev( pos ); if( pF ) { Uid = pF->m_Uid; } } return Uid; } //////////////////////////////////////////////////////////////////////// // GetCurrentUidList // // Accumulate current uid's and flags in "CurrentUidList" // //////////////////////////////////////////////////////////////////////// void GetCurrentUidList (CTocDoc *pTocDoc, CPtrUidList& CurrentUidList) { unsigned long uid; // Clear list first. CurrentUidList.DeleteAll (); // Sanity: if (! pTocDoc ) return; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); CSumList & listSums = pTocDoc->GetSumList(); POSITION pos = listSums.GetHeadPosition(); CSummary * pSum; while (pos) { pSum = listSums.GetNext(pos); if (pSum) { uid = pSum->GetHash(); if (uid != 0) { CurrentUidList.OrderedInsert (uid, pSum->m_Imflags, FALSE); } } } } //////////////////////////////////////////////////////////////////////// // GetCurrentUids - STL "MAP" version. // // Accumulate current uid's and flags in "CurrentUidMap" // //////////////////////////////////////////////////////////////////////// void GetCurrentUids (CTocDoc *pTocDoc, CUidMap& UidMap) { unsigned long uid; // Clear list first. UidMap.DeleteAll (); // Sanity: if (! pTocDoc ) return; // Disable preview. // pTocDoc->SetPreviewableSummary (NULL); CSumList & listSums = pTocDoc->GetSumList(); POSITION pos = listSums.GetHeadPosition(); CSummary * pSum; while (pos) { pSum = listSums.GetNext(pos); if (pSum) { uid = pSum->GetHash(); #if 0 // JOK - 7/8/98 - Include sums with uid of 0 also so they could get deleted during a resync. if (uid != 0) #endif { UidMap.OrderedInsert (uid, pSum->m_Imflags, FALSE); } } } } // // SHow that last IMAP error logged in the CImapConnection object specified by // "pImap". // void ShowLastImapError (CImapConnection *pImap) { TCHAR buf [512]; int iType = IMAPERR_BAD_CODE; if (!pImap) return; buf[0] = '\0'; pImap->GetLastImapErrorAndType (buf, 510, &iType); ::TrimWhitespaceMT (buf); // If we didn't get a message, just put up a plain error message. if (!buf[0]) { ErrorDialog (IDS_ERR_IMAP_COMMAND_FAILED); return; } // See what type of message it was. switch (iType) { case IMAPERR_USER_CANCELLED: case IMAPERR_LOCAL_ERROR: ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, buf); break; case IMAPERR_COMMAND_FAILED: case IMAPERR_CONNECTION_CLOSED: ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_SRVMSG, buf); break; // All other types: default: // If "buf" is non-empty, display that: // if (*buf) { ErrorDialog (IDS_ERR_IMAP_CMD_FAILED_REASON, buf); } else { ErrorDialog (IDS_ERR_IMAP_COMMAND_FAILED); } break; } } // ImapBitflagsToFlaglist [EXPORTED] // // Create a parenthesized, comma-separated IMAP flaglist given IMFLAGS_* // bitflags. Write the result in szFlaglist. // If ulBitflags don't contain proper bitflags, return an empty // string, otherwise format a proper comma-separated string of flags. // void ImapBitflagsToFlaglist (unsigned ulBitflags, CString& szFlaglist) { // In case of error: szFlaglist.Empty(); // \\SEEN: if (ulBitflags & IMFLAGS_SEEN) { if ( szFlaglist.IsEmpty() ) szFlaglist = "(\\SEEN"; else szFlaglist += ", \\SEEN"; } // \\ANSWERED: if (ulBitflags & IMFLAGS_ANSWERED) { if ( szFlaglist.IsEmpty() ) szFlaglist = "(\\ANSWERED"; else szFlaglist += ", \\ANSWERED"; } // \\DELETED: if (ulBitflags & IMFLAGS_DELETED) { if ( szFlaglist.IsEmpty() ) szFlaglist = "(\\DELETED"; else szFlaglist += ", \\DELETED"; } // \\FLAGGED: if (ulBitflags & IMFLAGS_FLAGGED) { if ( szFlaglist.IsEmpty() ) szFlaglist = "(\\FLAGGED"; else szFlaglist += ", \\FLAGGED"; } // \\DRAFT: if (ulBitflags & IMFLAGS_DRAFT) { if ( szFlaglist.IsEmpty() ) szFlaglist = "(\\DRAFT"; else szFlaglist += ", \\DRAFT"; } // Terminate parenthesis? if (!szFlaglist.IsEmpty()) szFlaglist += ")"; } // Return TRUE if the given name is INBOX: // BOOL IsInbox (LPCSTR pName) { BOOL bRet = FALSE; if (pName) { bRet = ( stricmp (pName, "INBOX") == 0 ); } return bRet; } // Return TRUE if the given name is Junk: // BOOL IsJunk (LPCSTR pName) { BOOL bRet = FALSE; if (pName) { bRet = ( stricmp (pName, "Junk") == 0 ); if (!bRet) { bRet = ( stricmp (pName, "INBOX.Junk") == 0 ); } } return bRet; } // Return TRUE if the given name is Trash: // BOOL IsTrash (LPCSTR pName) { BOOL bRet = FALSE; if (pName) { bRet = ( stricmp (pName, "Trash") == 0 ); } return bRet; } // CopyTextFromTmpMbx [INTERNAL] // // If the summary has an offset into an MBX file, then it must be the // temporary MBX file. Go copy the text into the main MBX file. // BOOL CopyTextFromTmpMbx (CTocDoc* pTocDoc, CSummary* pSum) { // Sanity: if (! (pTocDoc && pSum) ) return FALSE; // Does the summary have am offset?? // if ( pSum->IsNotIMAPDownloadedAtAll() ) { return TRUE; } if (!pSum->m_Length) { return TRUE; } CImapMailbox* pImapMailbox = pTocDoc->m_pImapMailbox; if (!pImapMailbox) { ASSERT (0); return FALSE; } // Look for temporary MBX file. // CString szTmpMbxFilePath; GetTmpMbxFilePath (pImapMailbox->GetDirname(), szTmpMbxFilePath); if ( !FileExistsMT(szTmpMbxFilePath) ) { // File sould have been here!! // ASSERT (0); return FALSE; } // Ok. Open both files. // CString szMainMbxFilePath = pTocDoc->GetMBFileName(); JJFile TargetMBox; JJFile SrcMBox; if (FAILED(TargetMBox.Open(szMainMbxFilePath, O_RDWR | O_CREAT | O_APPEND)) || FAILED(SrcMBox.Open(szTmpMbxFilePath, O_RDONLY))) { return FALSE; } // Get current offset into target file because we may need to truncate it if // failed. // long lOffset = -1; TargetMBox.Tell(&lOffset); if (FAILED(SrcMBox.JJBlockMove(pSum->m_Offset, pSum->m_Length, &TargetMBox))) { TargetMBox.ChangeSize(lOffset); return FALSE; } return TRUE; } // Utility function for closing or popping the progress. // void TerminateProgress (BOOL bWePutProgressUp, BOOL bWasInProgress) { if ( bWePutProgressUp ) { if (bWasInProgress) PopProgress(); else CloseProgress(); } } // GetNextUidChunk // // Iterate through a comma-separated list of UID's. // Parameters: // "pStart - pointer to the current start of the list. // "szChunk - next comma-separated UID's // // Return: Pointer to where next to start, or NULL if list exhausted. // LPCSTR GetNextUidChunk (LPCSTR pStart, CString& szChunk) { if (!pStart) return NULL; LPCSTR pNext = NULL; int nUids; for (pNext = pStart, nUids = 0; pNext && nUids < MAX_UIDS_PER_COMMAND; nUids++) { pNext = strchr (pNext + 1, comma); } // Copy to szChunk. if (pNext && pNext > pStart) { szChunk = CString (pStart, pNext - pStart); } else { // Last chunk. szChunk = pStart; pNext = NULL; } return pNext; } // // FigureOutDelimiter // jdboyd 5/24/99 // // Return the first delimiter character found in the mailboxes belonging // to this account. First, check the top level delimiter. If no valid // delimiter character is found, scan the top level mailboxes for a delimiter. // Return it. // TCHAR FigureOutDelimiter(CImapAccount *pAccount) { TCHAR d = '\0'; d = pAccount->GetTopDelimiter(); if ( d=='\0' || d==' ' ) { // iterate through the top level of mailboxes looking for a delimiter QCMailboxCommand *pC; QCImapMailboxCommand *pIC; CString strDirectory; // find the mailboxes that belong to this account pAccount->GetDirectory (strDirectory); pC = g_theMailboxDirector.FindByPathname( strDirectory ); // only makes sense to do this if they're IMAP mailboxes if (pC->GetType() == MBT_IMAP_ACCOUNT) { // find the first IMAP mailbox CPtrList& ChildList = pC->GetChildList (); POSITION pos = ChildList.GetHeadPosition(); // iterate through the mailboxes, stop when we find a valid delimiter while( pos && !d ) { pIC = ( QCImapMailboxCommand* ) ChildList.GetNext( pos ); if (pIC) { d = pIC->GetDelimiter(); if (d == ' ') d = '\0'; // space is an invalid delimiter character } } } } return (d); } #endif
23.192779
150
0.641149
[ "object", "model" ]
b1a15f7a30f85d7306c006f0c23088e777ab8e34
633
cc
C++
other/lower_bound.cc
gnosis23/algorithms
99fd4509b82876c09fb958888c9a454845ba2c32
[ "MIT" ]
1
2020-09-07T15:41:12.000Z
2020-09-07T15:41:12.000Z
other/lower_bound.cc
gnosis23/algorithms
99fd4509b82876c09fb958888c9a454845ba2c32
[ "MIT" ]
null
null
null
other/lower_bound.cc
gnosis23/algorithms
99fd4509b82876c09fb958888c9a454845ba2c32
[ "MIT" ]
null
null
null
/** * 寻找下界(如果没有会返回最大的小于目标数加一) * 参考:https://en.cppreference.com/w/cpp/algorithm/lower_bound * * 1) 如果目标不重复,可以在里面加个相等的分支,直接返回;剩下的就是下界 * 2) 用前闭后开的方式实现“二分法”,可以避开一些 bug,如 [2,3] */ #include <vector> using std::vector; int lower_bound(vector<int>& nums, int val) { int last = nums.size(); int first = 0; int count = last; while (count > 0) { int it = first; int step = count / 2; it += step; bool comp = nums[it] < val; if (comp) { first = ++it; count -= step + 1; } else { count = step; } } return first; }
21.1
61
0.515008
[ "vector" ]
b1a1d4e1d07e9dbe3093c674de6a9efee58ac456
8,654
cpp
C++
src/osgEarthBuildings/TerrainClamper.cpp
VTMAK/osgearth-buildings-pprabhu
b18c78ee5c8c0876a76ee8897070f1dbb55ccb7b
[ "MIT" ]
null
null
null
src/osgEarthBuildings/TerrainClamper.cpp
VTMAK/osgearth-buildings-pprabhu
b18c78ee5c8c0876a76ee8897070f1dbb55ccb7b
[ "MIT" ]
null
null
null
src/osgEarthBuildings/TerrainClamper.cpp
VTMAK/osgearth-buildings-pprabhu
b18c78ee5c8c0876a76ee8897070f1dbb55ccb7b
[ "MIT" ]
null
null
null
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2016 Pelican Mapping * http://osgearth.org * * osgEarth 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 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "TerrainClamper" #include <osgEarth/Version> using namespace osgEarth; using namespace osgEarth::Features; using namespace osgEarth::Buildings; #define LC "[TerrainClamper] " TerrainClamper::TerrainClamper() : _maxEntries( 200000u ) { //nop } void TerrainClamper::setSession(Session* session) { _session = session; } bool TerrainClamper::fetchTileFromMap(const TileKey& key, MapFrame& frame, Tile* tile) { const int tileSize = 33; tile->_loadTime = osg::Timer::instance()->tick(); osg::ref_ptr<osg::HeightField> hf = new osg::HeightField(); hf->allocate( tileSize, tileSize ); // Initialize the heightfield to nodata hf->getFloatArray()->assign( hf->getFloatArray()->size(), NO_DATA_VALUE ); TileKey keyToUse = key; while( !tile->_hf.valid() && keyToUse.valid() ) { if (frame.populateHeightField(hf, keyToUse, false /*heightsAsHAE*/, 0L)) { tile->_hf = GeoHeightField( hf.get(), keyToUse.getExtent() ); tile->_bounds = keyToUse.getExtent().bounds(); } else { keyToUse = keyToUse.createParentKey(); } } return tile->_hf.valid(); } bool TerrainClamper::getTile(const TileKey& key, MapFrame& frame, osg::ref_ptr<Tile>& out) { // first see whether the tile is available _tilesMutex.lock(); osg::ref_ptr<Tile>& tile = _tiles[key]; if ( !tile.valid() ) { // a new tile; status -> EMPTY tile = new Tile(); tile->_key = key; // update the LRU: _lru.push_front( key ); ++_entries; if ( _entries > _maxEntries ) { _lru.pop_back(); --_entries; } } if ( tile->_status == STATUS_EMPTY ) { //OE_INFO << " getTile(" << key.str() << ") -> fetch from map\n"; tile->_status.exchange(STATUS_IN_PROGRESS); _tilesMutex.unlock(); bool ok = fetchTileFromMap(key, frame, tile.get()); tile->_status.exchange( ok ? STATUS_AVAILABLE : STATUS_FAIL ); out = ok ? tile.get() : 0L; return ok; } else if ( tile->_status == STATUS_AVAILABLE ) { //OE_INFO << " getTile(" << key.str() << ") -> available\n"; out = tile.get(); // update the LRU: KeyLRU::iterator i = std::find(_lru.begin(), _lru.end(), key); if ( i != _lru.end() && i != _lru.begin() ) { _lru.erase( i ); _lru.push_front( key ); } _tilesMutex.unlock(); return true; } else if ( tile->_status == STATUS_FAIL ) { //OE_INFO << " getTile(" << key.str() << ") -> fail\n"; _tilesMutex.unlock(); out = 0L; return false; } else //if ( tile->_status == STATUS_IN_PROGRESS ) { //OE_INFO << " getTile(" << key.str() << ") -> in progress...waiting\n"; _tilesMutex.unlock(); return true; // out:NULL => check back later please. } } bool TerrainClamper::buildQuerySet(const GeoExtent& extent, MapFrame& frame, unsigned lod, QuerySet& output) { output.clear(); //Dont' need this since the Frame is used once per enveloper -gw //if ( frame.needsSync() ) //{ // if (frame.sync()) // { // _tilesMutex.lock(); // _tiles.clear(); // _tilesMutex.unlock(); // } //} if (frame.getProfile() == 0L || !frame.getProfile()->isOK()) { OE_INFO << LC << "Frame profile is not available; buildQuerySet failed.\n"; return false; } // find the minimal collection of tiles (in the map frame's profile) that cover // the requested extent (which might be in a different profile). std::vector<TileKey> keys; frame.getProfile()->getIntersectingTiles(extent, lod, keys); // for each coverage key, fetch the corresponding elevation tile and add it to // the output list. for(int i=0; i<keys.size(); ++i) { OE_START_TIMER(get); const double timeout = 30.0; osg::ref_ptr<Tile> tile; while( getTile(keys[i], frame, tile) && !tile.valid() && OE_GET_TIMER(get) < timeout) { // condition: another thread is working on fetching the tile from the map, // so wait and try again later. Do this until we succeed or time out. OpenThreads::Thread::YieldCurrentThread(); } if ( !tile.valid() && OE_GET_TIMER(get) >= timeout ) { // this means we timed out trying to fetch the map tile. OE_WARN << LC << "Timout fetching tile " << keys[i].str() << std::endl; } if ( tile.valid() ) { if ( tile->_hf.valid() ) { // got a valid tile, so push it to the query set. output.insert( tile.get() ); } else { OE_WARN << LC << "Got a tile with an invalid HF (" << keys[i].str() << ")\n"; } } } return true; } TerrainEnvelope* TerrainClamper::createEnvelope(const GeoExtent& extent, unsigned lod) { osg::ref_ptr<TerrainEnvelope> e = new TerrainEnvelope(); #if OSGEARTH_VERSION_GREATER_OR_EQUAL(2,9,0) e->_frame = _session->createMapFrame(); #else e->_frame.setMap(_session->getMap()); #endif if (!e->_frame.isValid()) { // frame synchronization failed, which means the Map went away. return 0L; } if (buildQuerySet( extent, e->_frame, lod, e->_tiles )) return e.release(); else return 0L; } //................................... bool TerrainEnvelope::getElevationExtrema(const Feature* feature, float& min, float& max) const { if ( !feature || !feature->getGeometry() ) return false; min = FLT_MAX, max = -FLT_MAX; unsigned count = 0; ConstGeometryIterator gi(feature->getGeometry(), false); while(gi.hasMore()) { const Geometry* part = gi.next(); for(Geometry::const_iterator v = part->begin(); v != part->end(); ++v) { // TODO: consider speed of this vs. Profile::createTileKey + std::map lookup // NB, tiles are pre-sorted from high to low resolution. for(TerrainClamper::QuerySet::const_iterator q = _tiles.begin(); q != _tiles.end(); ++q) { TerrainClamper::Tile* tile = q->get(); if ( tile->_bounds.contains(v->x(), v->y()) ) { ++count; float elevation; if ( tile->_hf.getElevation(0L, v->x(), v->y(), INTERP_BILINEAR, 0L, elevation) ) { if ( elevation < min ) min = elevation; if ( elevation > max ) max = elevation; } break; } } } } // If none of the feature points clamped, try the feature centroid. // It's possible (but improbable) that the feature encloses the envelope if (min > max) { osg::Vec2d v = feature->getGeometry()->getBounds().center2d(); // TODO: consider speed of this vs. Profile::createTileKey + std::map lookup for (TerrainClamper::QuerySet::const_iterator q = _tiles.begin(); q != _tiles.end(); ++q) { TerrainClamper::Tile* tile = q->get(); if (tile->_bounds.contains(v.x(), v.y())) { float elevation; if (tile->_hf.getElevation(0L, v.x(), v.y(), INTERP_BILINEAR, 0L, elevation)) { if (elevation < min) min = elevation; if (elevation > max) max = elevation; } break; } } } return (min <= max); }
29.841379
103
0.556159
[ "geometry", "vector" ]
b1a447506ea81ce1d90ee037a1914112ac8253b1
6,779
cpp
C++
SCSL/Rein/Rein/rein.cpp
shiwanghua/matching-algorithm
a09714b76d8722a7891b72f4740948814369b40e
[ "MIT" ]
14
2019-01-18T12:56:27.000Z
2020-12-09T12:31:21.000Z
SCSL/Rein/Rein/rein.cpp
shiwanghua/matching-algorithm
a09714b76d8722a7891b72f4740948814369b40e
[ "MIT" ]
null
null
null
SCSL/Rein/Rein/rein.cpp
shiwanghua/matching-algorithm
a09714b76d8722a7891b72f4740948814369b40e
[ "MIT" ]
8
2019-03-11T13:22:32.000Z
2021-04-27T04:18:57.000Z
#include "rein.h" void Rein::insert(IntervalSub &sub, int64_t &origintime) { Timer t; double poss = 1; int level; for(int j = 0; j < sub.size; ++j){ IntervalCnt &cnt = sub.constraints[j]; poss *= (cnt.highValue-cnt.lowValue)*1.0/valDom; } level = (int) floor(log(poss)/log(0.1)/Dom*newlevel); if(level<0)level=0; else if(level>=newlevel)level=newlevel-1; int indexId=LvSize[level].size(),buckStep=LvBuckStep[level]; subtolevel[sub.id] = level; originlevel[sub.id] = level; for (int j = 0; j < sub.size; ++j){ IntervalCnt &cnt = sub.constraints[j]; kCombo c; c.val = cnt.lowValue; c.subID = sub.id; c.indexId = indexId; data[level][cnt.att][0][c.val / buckStep].push_back(c); c.val = cnt.highValue; data[level][cnt.att][1][c.val / buckStep].push_back(c); } LvSize[level].push_back(sub.id); ++subnum; origintime=t.elapsed_nano(); //} } void Rein::match(const Pub &pub, int &matchSubs, vector<double> &matchDetailPub) { Timer t; for (int siIndex=0; siIndex<newlevel; ++siIndex) { vector<bool> bits(LvSize[siIndex].size(), false); int bucks=LvBuck[siIndex],buckStep=LvBuckStep[siIndex]; for (int i = 0; i < pub.size; i++) { int value = pub.pairs[i].value, att = pub.pairs[i].att, buck = value / buckStep; vector<kCombo> &data_0 = data[siIndex][att][0][buck]; int data_0_size = data_0.size(); for (int k = 0; k < data_0_size; k++) if (data_0[k].val > value) bits[data_0[k].indexId] = true; for (int j = buck + 1; j < bucks; j++){ vector<kCombo> &data_1 = data[siIndex][att][0][j]; int data_1_size = data_1.size(); for (int k = 0; k < data_1_size; k++) bits[data_1[k].indexId] = true; } vector<kCombo> &data_2 = data[siIndex][att][1][buck]; int data_2_size = data_2.size(); for (int k = 0; k < data_2_size; k++) if (data_2[k].val < value) bits[data_2[k].indexId] = true; for (int j = buck - 1; j >= 0; j--){ vector<kCombo> &data_3 = data[siIndex][att][1][j]; //if (data_3.empty()) break; int data_3_size = data_3.size(); for (int k = 0; k < data_3_size; k++) bits[data_3[k].indexId] = true; } } //Timer t5; vector<int> &_Lv = LvSize[siIndex]; int b = _Lv.size(); for (int i=0; i<b; ++i) if (!bits[i] && _Lv[i]!=-1) { matchDetailPub.push_back(t.elapsed_nano() / 1000000.0); ++matchSubs; ++countlist[_Lv[i]]; } } } int Rein::change(const vector<IntervalSub> &subList,int cstep, double matchingtime, string &windowcontent){ int changenum=0,totalshouldchange=0,limitnum=subnum/100;//maxcount=0; bool stopflag=false; if(!firstchange){ limitnum = (int) (matchingtime * cstep * limitscale / adjustcost); } Timer t; /*for(int i=0;i<subnum;++i){ if(countlist[i]>maxcount){ maxcount=countlist[i]; } }*/ //int zerocount=0,ninecount=0; for(int i=0;i<subnum;++i){ //int level=newlevel-1-(int)floor((double)countlist[i]/(maxcount+1e-6)*newlevel); //int level=originlevel[i]-(int)round((double)countlist[i]/cstep*originlevel[i]); int level=(int)round(pow(1-(double)countlist[i]/cstep,2)*originlevel[i]); int oldlevel=subtolevel[i]; /*if(countlist[i]==0){ level=oldlevel+1; if(level>=newlevel) level=oldlevel; }*/ //if(level == oldlevel) continue; int distancelevel = abs(level-oldlevel); if(distancelevel==0) continue; if(distancelevel==1 && changelist[1].size()>=limitnum) continue; changeaction tmp; tmp.id = i; tmp.oldlevel = oldlevel; tmp.newlevel = level; changelist[distancelevel].push_back(tmp); ++totalshouldchange; } /*vector<int> &_Lv = LvSize[0]; int l=_Lv.size(); int num=0; for(int j=0;j<l;++j) if(_Lv[j]!=-1) ++num; cout<<"level zero: "<<l<<' '<<num<<endl;*/ //cout<<"maxcount: "<<maxcount<<endl; cout<<"totalshouldchange: "<<totalshouldchange<<endl; //windowcontent += to_string(totalshouldchange) +"\t"; for(int i=newlevel-1;i>0;--i){ //cout<<i<<' '; int l=changelist[i].size(); //cout<<l<<endl; for(int ii=0;ii<l;++ii){ changeaction &action = changelist[i][ii]; int id=action.id,oldlevel=action.oldlevel,level=action.newlevel; int indexId; if(emptymark[level].empty()){ indexId=LvSize[level].size(); LvSize[level].push_back(id); } else{ indexId=emptymark[level].back(); emptymark[level].pop_back(); LvSize[level][indexId]=id; } int oldindexId=-1,buckStep=LvBuckStep[level],oldbuckStep=LvBuckStep[oldlevel]; subtolevel[id]=level; IntervalSub sub=subList[id]; for(int j=0;j<sub.size;++j){ IntervalCnt cnt = sub.constraints[j]; vector<kCombo>::iterator ed=data[oldlevel][cnt.att][0][cnt.lowValue/oldbuckStep].end(); //bool fl=false; for(vector<kCombo>::iterator it=data[oldlevel][cnt.att][0][cnt.lowValue/oldbuckStep].begin();it!=ed;++it) if(it->subID==id){ oldindexId = it->indexId; data[oldlevel][cnt.att][0][cnt.lowValue/oldbuckStep].erase(it); //fl=true; break; } //if(!fl)cout<<"error!not found lowValue"<<endl; //fl=false; ed=data[oldlevel][cnt.att][1][cnt.highValue/oldbuckStep].end(); for(vector<kCombo>::iterator it=data[oldlevel][cnt.att][1][cnt.highValue/oldbuckStep].begin();it!=ed;++it) if(it->subID==id){ data[oldlevel][cnt.att][1][cnt.highValue/oldbuckStep].erase(it); //fl=true; break; } //if(!fl)cout<<"error!not found highValue"<<endl; kCombo c; c.val = cnt.lowValue; c.subID = id; c.indexId = indexId; data[level][cnt.att][0][c.val / buckStep].push_back(c); c.val = cnt.highValue; data[level][cnt.att][1][c.val / buckStep].push_back(c); } LvSize[oldlevel][oldindexId]=-1; emptymark[oldlevel].push_back(oldindexId); ++changenum; if(changenum>=limitnum){ stopflag=true; break; } } if(stopflag)break; } if(changenum){ adjustcost = (double)t.elapsed_nano() / 1000000 / changenum; firstchange = false; } for(int i=newlevel-1;i>0;--i) changelist[i].clear(); memset(countlist, 0, sizeof(countlist)); //windowcontent += to_string(changenum) +"\n"; //cout<<zerocount<<" "<<ninecount<<endl; return changenum; } void Rein::check(){ for(int i=0;i<newlevel;++i){ vector<int> &_Lv = LvSize[i]; int l=_Lv.size(); int num=0; for(int j=0;j<l;++j) if(_Lv[j]!=-1) ++num; cout<<i<<' '<<l<<' '<<num<<endl; } }
28.603376
110
0.587845
[ "vector" ]
b1ab4951fefabcde3d0f3e0f77e853036dbfa19a
9,011
hpp
C++
src/mlpack/core/tree/address.hpp
NaxAlpha/mlpack-build
1f0c1454d4b35eb97ff115669919c205cee5bd1c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2018-05-21T11:08:36.000Z
2022-03-12T07:52:14.000Z
src/mlpack/core/tree/address.hpp
okmegy/Mlpack
ac9abef3c1353f483ed1af42ba5a7432f291ca1a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/core/tree/address.hpp
okmegy/Mlpack
ac9abef3c1353f483ed1af42ba5a7432f291ca1a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file address.hpp * @author Mikhail Lozhnikov * * This file contains a series of functions for translating points to addresses * and back and functions for comparing addresses. * * The notion of addresses is described in the following paper. * @code * @inproceedings{bayer1997, * author = {Bayer, Rudolf}, * title = {The Universal B-Tree for Multidimensional Indexing: General * Concepts}, * booktitle = {Proceedings of the International Conference on Worldwide * Computing and Its Applications}, * series = {WWCA '97}, * year = {1997}, * isbn = {3-540-63343-X}, * pages = {198--209}, * numpages = {12}, * publisher = {Springer-Verlag}, * address = {London, UK, UK}, * } * @endcode */ #ifndef MLPACK_CORE_TREE_ADDRESS_HPP #define MLPACK_CORE_TREE_ADDRESS_HPP namespace mlpack { namespace bound { namespace addr { /** * Calculate the address of a point. Be careful, the point and the address * variables should be equal-sized and the type of the address should correspond * to the type of the vector. * * The function maps each floating point coordinate to an equal-sized unsigned * integer datatype in such a way that the transform preserves the ordering * (i.e. lower floating point values correspond to lower integers). Thus, * the mapping saves the exponent and the mantissa of each floating point value * consequently, furthermore the exponent is stored before the mantissa. In the * case of negative numbers the resulting integer value should be inverted. * In the multi-dimensional case, after we transform the representation, we * have to interleave the bits of the new representation across all the elements * in the address vector. * * @param address The resulting address. * @param point The point that is being translated to the address. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ template<typename AddressType, typename VecType> void PointToAddress(AddressType& address, const VecType& point) { typedef typename VecType::elem_type VecElemType; // Check that the arguments are compatible. typedef typename std::conditional<sizeof(VecElemType) * CHAR_BIT <= 32, uint32_t, uint64_t>::type AddressElemType; static_assert(std::is_same<typename AddressType::elem_type, AddressElemType>::value == true, "The vector element type does not " "correspond to the address element type."); arma::Col<AddressElemType> result(point.n_elem); constexpr size_t order = sizeof(AddressElemType) * CHAR_BIT; // Calculate the number of bits for the exponent. const int numExpBits = std::ceil(std::log2( std::numeric_limits<VecElemType>::max_exponent - std::numeric_limits<VecElemType>::min_exponent + 1.0)); // Calculate the number of bits for the mantissa. const int numMantBits = order - numExpBits - 1; assert(point.n_elem == address.n_elem); assert(address.n_elem > 0); for (size_t i = 0; i < point.n_elem; i++) { int e; VecElemType normalizedVal = std::frexp(point(i),&e); bool sgn = std::signbit(normalizedVal); if (point(i) == 0) e = std::numeric_limits<VecElemType>::min_exponent; if (sgn) normalizedVal = -normalizedVal; if (e < std::numeric_limits<VecElemType>::min_exponent) { AddressElemType tmp = (AddressElemType) 1 << (std::numeric_limits<VecElemType>::min_exponent - e); e = std::numeric_limits<VecElemType>::min_exponent; normalizedVal /= tmp; } // Extract the mantissa. AddressElemType tmp = (AddressElemType) 1 << numMantBits; result(i) = std::floor(normalizedVal * tmp); // Add the exponent. assert(result(i) < ((AddressElemType) 1 << numMantBits)); result(i) |= ((AddressElemType) (e - std::numeric_limits<VecElemType>::min_exponent)) << numMantBits; assert(result(i) < ((AddressElemType) 1 << (order - 1)) - 1); // Negative values should be inverted. if (sgn) { result(i) = ((AddressElemType) 1 << (order - 1)) - 1 - result(i); assert((result(i) >> (order - 1)) == 0); } else { result(i) |= (AddressElemType) 1 << (order - 1); assert((result(i) >> (order - 1)) == 1); } } address.zeros(point.n_elem); // Interleave the bits of the new representation across all the elements // in the address vector. for (size_t i = 0; i < order; i++) for (size_t j = 0; j < point.n_elem; j++) { size_t bit = (i * point.n_elem + j) % order; size_t row = (i * point.n_elem + j) / order; address(row) |= (((result(j) >> (order - 1 - i)) & 1) << (order - 1 - bit)); } } /** * Translate the address to the point. Be careful, the point and the address * variables should be equal-sized and the type of the address should correspond * to the type of the vector. * * The function makes the backward transform to the function above. * * @param address An address to translate. * @param point The point that corresponds to the address. */ template<typename AddressType, typename VecType> void AddressToPoint(VecType& point, const AddressType& address) { typedef typename VecType::elem_type VecElemType; // Check that the arguments are compatible. typedef typename std::conditional<sizeof(VecElemType) * CHAR_BIT <= 32, uint32_t, uint64_t>::type AddressElemType; static_assert(std::is_same<typename AddressType::elem_type, AddressElemType>::value == true, "The vector element type does not " "correspond to the address element type."); constexpr size_t order = sizeof(AddressElemType) * CHAR_BIT; // Calculate the number of bits for the exponent. const int numExpBits = std::ceil(std::log2( std::numeric_limits<VecElemType>::max_exponent - std::numeric_limits<VecElemType>::min_exponent + 1.0)); assert(point.n_elem == address.n_elem); assert(address.n_elem > 0); arma::Col<AddressElemType> rearrangedAddress(address.n_elem, arma::fill::zeros); // Calculate the number of bits for the mantissa. const int numMantBits = order - numExpBits - 1; for (size_t i = 0; i < order; i++) for (size_t j = 0; j < address.n_elem; j++) { size_t bit = (i * address.n_elem + j) % order; size_t row = (i * address.n_elem + j) / order; rearrangedAddress(j) |= (((address(row) >> (order - 1 - bit)) & 1) << (order - 1 - i)); } for (size_t i = 0; i < rearrangedAddress.n_elem; i++) { bool sgn = rearrangedAddress(i) & ((AddressElemType) 1 << (order - 1)); if (!sgn) { rearrangedAddress(i) = ((AddressElemType) 1 << (order - 1)) - 1 - rearrangedAddress(i); } // Extract the mantissa. AddressElemType tmp = (AddressElemType) 1 << numMantBits; AddressElemType mantissa = rearrangedAddress(i) & (tmp - 1); if (mantissa == 0) mantissa = 1; VecElemType normalizedVal = (VecElemType) mantissa / tmp; if (!sgn) normalizedVal = -normalizedVal; // Extract the exponent tmp = (AddressElemType) 1 << numExpBits; AddressElemType e = (rearrangedAddress(i) >> numMantBits) & (tmp - 1); e += std::numeric_limits<VecElemType>::min_exponent; point(i) = std::ldexp(normalizedVal, e); if (std::isinf(point(i))) { if (point(i) > 0) point(i) = std::numeric_limits<VecElemType>::max(); else point(i) = std::numeric_limits<VecElemType>::lowest(); } } } /** * Compare two addresses. The function returns 1 if the first address is greater * than the second one, -1 if the first address is less than the second one, * otherwise the function returns 0. */ template<typename AddressType1, typename AddressType2> int CompareAddresses(const AddressType1& addr1, const AddressType2& addr2) { static_assert(std::is_same<typename AddressType1::elem_type, typename AddressType2::elem_type>::value == true, "Can't compare " "addresses of distinct types"); assert(addr1.n_elem == addr2.n_elem); for (size_t i = 0; i < addr1.n_elem; i++) { if (addr1[i] < addr2[i]) return -1; else if (addr2[i] < addr1[i]) return 1; } return 0; } /** * Returns true if an address is contained between two other addresses. */ template<typename AddressType1, typename AddressType2, typename AddressType3> bool Contains(const AddressType1& address, const AddressType2& loBound, const AddressType3& hiBound) { return ((CompareAddresses(loBound, address) <= 0) && (CompareAddresses(hiBound, address) >= 0)); } } // namespace addr } // namespace bound } // namespave mlpack #endif // MLPACK_CORE_TREE_ADDRESS_HPP
33.623134
80
0.661969
[ "vector", "transform" ]
b1aea4ecbc3828699def47553febc9c41a23a1b3
7,798
cc
C++
src/developer/system_monitor/bin/harvester/task_tree.cc
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/developer/system_monitor/bin/harvester/task_tree.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
null
null
null
src/developer/system_monitor/bin/harvester/task_tree.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
2
2020-10-25T01:13:49.000Z
2020-10-26T02:32:13.000Z
// Copyright 2019 The Fuchsia 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 "task_tree.h" #include <fuchsia/kernel/c/fidl.h> #include <inttypes.h> #include <lib/fdio/directory.h> #include <lib/fdio/fdio.h> #include <lib/syslog/cpp/macros.h> #include <lib/zx/channel.h> #include <zircon/status.h> #include <cstdio> namespace harvester { const size_t kNumInitialKoids = 128; const size_t kNumExtraKoids = 10; zx_status_t TaskTree::GatherChildKoids(zx_handle_t parent, zx_koid_t parent_koid, int children_kind, const char* kind_name, std::vector<zx_koid_t>& child_koids) { size_t actual = 0; size_t available = 0; zx_status_t status; int count = 0; // This is inherently racy. Retry once with a bit of slop to try to // get a complete list. do { status = zx_object_get_info(parent, children_kind, child_koids.data(), child_koids.size() * sizeof(zx_koid_t), &actual, &available); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx_object_get_info(" << parent_koid << ", " << kind_name << ", ...) failed: " << zx_status_get_string(status) << " (" << status << ")"; // On error, empty child_koids so we don't pass through invalid // information. child_koids.clear(); return status; } if (actual < available) { child_koids.resize(available + kNumExtraKoids); } } while (actual < available && count++ < 2); // If we're still too small at least warn the user. if (actual < available) { FX_LOGS(WARNING) << "zx_object_get_info(" << parent_koid << ", " << kind_name << ", ...) truncated " << (available - actual) << "/" << available << " results"; } child_koids.resize(actual); return ZX_OK; } zx_status_t TaskTree::GetHandleForChildKoid(zx_koid_t child_koid, zx_handle_t parent, zx_koid_t parent_koid, zx_handle_t* child_handle) { auto it = koids_to_handles_.find(child_koid); if (it != koids_to_handles_.end()) { *child_handle = it->second; stale_koids_to_handles_.erase(child_koid); return ZX_OK; } zx_status_t status = zx_object_get_child(parent, child_koid, ZX_RIGHT_SAME_RIGHTS, child_handle); if (status != ZX_OK) { FX_LOGS(WARNING) << "zx_object_get_child(" << parent_koid << ", (job)" << child_koid << ", ...) failed: " << zx_status_get_string(status) << " (" << status << ")"; } else { koids_to_handles_.insert( std::pair<zx_koid_t, zx_handle_t>(child_koid, *child_handle)); stale_koids_to_handles_.erase(child_koid); } return status; } void TaskTree::GatherThreadsForProcess(zx_handle_t parent_process, zx_koid_t parent_process_koid) { zx_status_t status; // Get the koids for the threads belonging to this process. std::vector<zx_koid_t> koids(kNumInitialKoids); status = GatherChildKoids(parent_process, parent_process_koid, ZX_INFO_PROCESS_THREADS, "ZX_INFO_PROCESS_THREADS", koids); if (status != ZX_OK) { return; } for (zx_koid_t koid : koids) { zx_handle_t next_thread_handle; status = GetHandleForChildKoid(koid, parent_process, parent_process_koid, &next_thread_handle); if (status == ZX_OK) { // Store the thread / koid / parent process triple. threads_.emplace_back(next_thread_handle, koid, parent_process_koid); } } } void TaskTree::GatherProcessesForJob(zx_handle_t parent_job, zx_koid_t parent_job_koid) { zx_status_t status; // Get the koids for the processes under this job. std::vector<zx_koid_t> koids(kNumInitialKoids); status = GatherChildKoids(parent_job, parent_job_koid, ZX_INFO_JOB_PROCESSES, "ZX_INFO_JOB_PROCESSES", koids); if (status != ZX_OK) { return; } for (zx_koid_t koid : koids) { zx_handle_t next_process_handle; status = GetHandleForChildKoid(koid, parent_job, parent_job_koid, &next_process_handle); if (status == ZX_OK) { // Store the process / koid / parent job triple. processes_.emplace_back(next_process_handle, koid, parent_job_koid); // Gather the process's threads. GatherThreadsForProcess(next_process_handle, koid); } } } void TaskTree::GatherProcessesAndJobsForJob(zx_handle_t parent_job, zx_koid_t parent_job_koid) { zx_status_t status; // Gather the job's processes. GatherProcessesForJob(parent_job, parent_job_koid); // Get the koids for the child jobs under this job. std::vector<zx_koid_t> koids(kNumInitialKoids); status = GatherChildKoids(parent_job, parent_job_koid, ZX_INFO_JOB_CHILDREN, "ZX_INFO_JOB_CHILDREN", koids); if (status != ZX_OK) { return; } for (zx_koid_t koid : koids) { zx_handle_t child_job_handle; status = GetHandleForChildKoid(koid, parent_job, parent_job_koid, &child_job_handle); if (status == ZX_OK) { // Store the child job / koid / parent job triple. jobs_.emplace_back(child_job_handle, koid, parent_job_koid); // Gather the job's processes and child jobs. GatherProcessesAndJobsForJob(child_job_handle, koid); } } } void TaskTree::GatherJobs() { zx::channel local, remote; zx_status_t status = zx::channel::create(0, &local, &remote); if (status != ZX_OK) { FX_LOGS(ERROR) << "Could not create channel"; return; } status = fdio_service_connect("/svc/fuchsia.kernel.RootJob", remote.release()); if (status != ZX_OK) { FX_LOGS(ERROR) << "Cannot open fuchsia.kernel.RootJob: " << zx_status_get_string(status); return; } zx_handle_t root_job; zx_koid_t root_job_koid = 0; auto it = koids_to_handles_.find(root_job_koid); if (it != koids_to_handles_.end()) { root_job = it->second; } else { zx_status_t fidl_status = fuchsia_kernel_RootJobGet(local.get(), &root_job); if (fidl_status != ZX_OK) { FX_LOGS(ERROR) << "Cannot obtain root job"; return; } koids_to_handles_.insert( std::pair<zx_koid_t, zx_handle_t>(root_job_koid, root_job)); } // We will rebuild these data structures as we walk the job tree. jobs_.clear(); processes_.clear(); threads_.clear(); stale_koids_to_handles_.insert(koids_to_handles_.begin(), koids_to_handles_.end()); stale_koids_to_handles_.erase(root_job_koid); // Store the root job node. jobs_.emplace_back(root_job, root_job_koid, root_job_koid); // Gather the root job's processes and jobs. GatherProcessesAndJobsForJob(root_job, root_job_koid); for (auto& [koid, handle] : stale_koids_to_handles_) { koids_to_handles_.erase(koid); zx_handle_close(handle); } stale_koids_to_handles_.clear(); } void TaskTree::Gather() { GatherJobs(); } void TaskTree::Clear() { // Close all open handles. for (auto& koid_handle_pair : koids_to_handles_) { zx_handle_close(koid_handle_pair.second); } koids_to_handles_.clear(); jobs_.clear(); processes_.clear(); threads_.clear(); } } // namespace harvester
31.067729
80
0.622467
[ "vector" ]
b1ba88df56595199425c0ca2aa81fd9015aee822
15,996
cpp
C++
src/model/ScheduleWeek.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
354
2015-01-10T17:46:11.000Z
2022-03-29T10:00:00.000Z
src/model/ScheduleWeek.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
3,243
2015-01-02T04:54:45.000Z
2022-03-31T17:22:22.000Z
src/model/ScheduleWeek.cpp
jmarrec/OpenStudio
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
[ "blessing" ]
157
2015-01-07T15:59:55.000Z
2022-03-30T07:46:09.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "ScheduleWeek.hpp" #include "ScheduleWeek_Impl.hpp" #include "ScheduleDay.hpp" #include "ScheduleDay_Impl.hpp" #include "Model.hpp" #include <utilities/idd/OS_Schedule_Week_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { ScheduleWeek_Impl::ScheduleWeek_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(idfObject, model, keepHandle) { OS_ASSERT(idfObject.iddObject().type() == ScheduleWeek::iddObjectType()); } ScheduleWeek_Impl::ScheduleWeek_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(other, model, keepHandle) { OS_ASSERT(other.iddObject().type() == ScheduleWeek::iddObjectType()); } ScheduleWeek_Impl::ScheduleWeek_Impl(const ScheduleWeek_Impl& other, Model_Impl* model, bool keepHandle) : ResourceObject_Impl(other, model, keepHandle) {} const std::vector<std::string>& ScheduleWeek_Impl::outputVariableNames() const { static const std::vector<std::string> result; return result; } IddObjectType ScheduleWeek_Impl::iddObjectType() const { return ScheduleWeek::iddObjectType(); } boost::optional<ScheduleDay> ScheduleWeek_Impl::sundaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::SundaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::mondaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::MondaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::tuesdaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::TuesdaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::wednesdaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::WednesdaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::thursdaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::ThursdaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::fridaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::FridaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::saturdaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::SaturdaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::holidaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::HolidaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::summerDesignDaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::SummerDesignDaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::winterDesignDaySchedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::WinterDesignDaySchedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::customDay1Schedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::CustomDay1Schedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } boost::optional<ScheduleDay> ScheduleWeek_Impl::customDay2Schedule() const { boost::optional<ScheduleDay> result; OptionalWorkspaceObject schedule = getTarget(OS_Schedule_WeekFields::CustomDay2Schedule_DayName); if (schedule) { result = schedule->optionalCast<ScheduleDay>(); } return result; } bool ScheduleWeek_Impl::setSundaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::SundaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setMondaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::MondaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setTuesdaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::TuesdaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setWednesdaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::WednesdaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setThursdaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::ThursdaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setFridaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::FridaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setSaturdaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::SaturdaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setHolidaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::HolidaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setSummerDesignDaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::SummerDesignDaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setWinterDesignDaySchedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::WinterDesignDaySchedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setCustomDay1Schedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::CustomDay1Schedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setCustomDay2Schedule(const ScheduleDay& schedule) { return setPointer(OS_Schedule_WeekFields::CustomDay2Schedule_DayName, schedule.handle()); } bool ScheduleWeek_Impl::setAllSchedules(const ScheduleDay& schedule) { bool result = true; result = result && setSundaySchedule(schedule); result = result && setMondaySchedule(schedule); result = result && setTuesdaySchedule(schedule); result = result && setWednesdaySchedule(schedule); result = result && setThursdaySchedule(schedule); result = result && setFridaySchedule(schedule); result = result && setSaturdaySchedule(schedule); result = result && setHolidaySchedule(schedule); result = result && setSummerDesignDaySchedule(schedule); result = result && setWinterDesignDaySchedule(schedule); result = result && setCustomDay1Schedule(schedule); result = result && setCustomDay2Schedule(schedule); return result; } bool ScheduleWeek_Impl::setWeekdaySchedule(const ScheduleDay& schedule) { bool result = true; result = result && setMondaySchedule(schedule); result = result && setTuesdaySchedule(schedule); result = result && setWednesdaySchedule(schedule); result = result && setThursdaySchedule(schedule); result = result && setFridaySchedule(schedule); return result; } bool ScheduleWeek_Impl::setWeekendSchedule(const ScheduleDay& schedule) { bool result = true; result = result && setSundaySchedule(schedule); result = result && setSaturdaySchedule(schedule); return result; } } // namespace detail ScheduleWeek::ScheduleWeek(const Model& model) : ResourceObject(ScheduleWeek::iddObjectType(), model) { OS_ASSERT(getImpl<detail::ScheduleWeek_Impl>()); } IddObjectType ScheduleWeek::iddObjectType() { IddObjectType result(IddObjectType::OS_Schedule_Week); return result; } /// @cond ScheduleWeek::ScheduleWeek(std::shared_ptr<detail::ScheduleWeek_Impl> impl) : ResourceObject(std::move(impl)) {} /// @endcond boost::optional<ScheduleDay> ScheduleWeek::sundaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->sundaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::mondaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->mondaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::tuesdaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->tuesdaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::wednesdaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->wednesdaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::thursdaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->thursdaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::fridaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->fridaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::saturdaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->saturdaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::holidaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->holidaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::summerDesignDaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->summerDesignDaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::winterDesignDaySchedule() const { return getImpl<detail::ScheduleWeek_Impl>()->winterDesignDaySchedule(); } boost::optional<ScheduleDay> ScheduleWeek::customDay1Schedule() const { return getImpl<detail::ScheduleWeek_Impl>()->customDay1Schedule(); } boost::optional<ScheduleDay> ScheduleWeek::customDay2Schedule() const { return getImpl<detail::ScheduleWeek_Impl>()->customDay2Schedule(); } bool ScheduleWeek::setSundaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setSundaySchedule(schedule); } bool ScheduleWeek::setMondaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setMondaySchedule(schedule); } bool ScheduleWeek::setTuesdaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setTuesdaySchedule(schedule); } bool ScheduleWeek::setWednesdaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setWednesdaySchedule(schedule); } bool ScheduleWeek::setThursdaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setThursdaySchedule(schedule); } bool ScheduleWeek::setFridaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setFridaySchedule(schedule); } bool ScheduleWeek::setSaturdaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setSaturdaySchedule(schedule); } bool ScheduleWeek::setHolidaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setHolidaySchedule(schedule); } bool ScheduleWeek::setSummerDesignDaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setSummerDesignDaySchedule(schedule); } bool ScheduleWeek::setWinterDesignDaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setWinterDesignDaySchedule(schedule); } bool ScheduleWeek::setCustomDay1Schedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setCustomDay1Schedule(schedule); } bool ScheduleWeek::setCustomDay2Schedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setCustomDay2Schedule(schedule); } bool ScheduleWeek::setAllSchedules(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setAllSchedules(schedule); } bool ScheduleWeek::setWeekdaySchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setWeekdaySchedule(schedule); } bool ScheduleWeek::setWeekendSchedule(const ScheduleDay& schedule) { return getImpl<detail::ScheduleWeek_Impl>()->setWeekendSchedule(schedule); } } // namespace model } // namespace openstudio
41.120823
131
0.731558
[ "vector", "model" ]
b1bb4f08dcb992725fd97f41bf0b50c5c7a03f9b
2,745
cpp
C++
3dEngine/src/scene/ui/widget/container/Container.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
18
2020-06-12T00:04:46.000Z
2022-01-11T14:56:19.000Z
3dEngine/src/scene/ui/widget/container/Container.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
null
null
null
3dEngine/src/scene/ui/widget/container/Container.cpp
petitg1987/urchinEngine
a14a57ac49a19237d748d2eafc7c2a38a45b95d6
[ "BSL-1.0" ]
6
2020-08-16T15:58:41.000Z
2022-03-05T13:17:50.000Z
#include <scene/ui/widget/container/Container.h> #include <scene/ui/widget/container/LazyWidget.h> namespace urchin { Container::Container(Position position, Size size, std::string skinName) : Widget(position, size), skinName(std::move(skinName)) { scrollbar = std::make_unique<Scrollbar>(*this, this->skinName); } std::shared_ptr<Container> Container::create(Widget* parent, Position position, Size size, std::string skinName) { return Widget::create<Container>(new Container(position, size, std::move(skinName)), parent); } void Container::onResize(unsigned int sceneWidth, unsigned int sceneHeight) { Widget::onResize(sceneWidth, sceneHeight); scrollbar->onScrollableWidgetsUpdated(); } void Container::addChild(const std::shared_ptr<Widget>& child) { Widget::addChild(child); scrollbar->onScrollableWidgetsUpdated(); } void Container::detachChild(Widget* child){ Widget::detachChild(child); scrollbar->onScrollableWidgetsUpdated(); } void Container::detachChildren() { Widget::detachChildren(); scrollbar->onScrollableWidgetsUpdated(); } void Container::resetChildren() { std::vector<std::shared_ptr<Widget>> copyChildren = getChildren(); for(const auto& child : copyChildren) { if (!scrollbar->isScrollbarWidget(child.get())) { Widget::detachChild(child.get()); } } scrollbar->onScrollableWidgetsUpdated(); } int Container::getScrollShiftY() const { return scrollbar->getScrollShiftY(); } void Container::onScrollableContentUpdated() const { Rectangle<int> containerRectangle = widgetRectangle(); for (const auto& child : getChildren()) { auto* lazyWidget = dynamic_cast<LazyWidget*>(child.get()); if (lazyWidget) { if (containerRectangle.collideWithRectangle(child->widgetRectangle())) { lazyWidget->loadChildren(); } else { lazyWidget->unloadChildren(); } } } } void Container::createOrUpdateWidget() { scrollbar->initializeOrUpdate(); } bool Container::onKeyPressEvent(unsigned int key) { return scrollbar->onKeyPressEvent(key); } bool Container::onKeyReleaseEvent(unsigned int key) { return scrollbar->onKeyReleaseEvent(key); } bool Container::onMouseMoveEvent(int mouseX, int mouseY) { return scrollbar->onMouseMoveEvent(mouseX, mouseY); } bool Container::onScrollEvent(double offsetY) { return scrollbar->onScrollEvent(offsetY); } }
31.918605
118
0.634244
[ "vector" ]
04db087c161c80ff6d51f40e439f9c043d111d93
1,981
cpp
C++
PAT-Advanced/PAT1027-ColorsInMars.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
PAT-Advanced/PAT1027-ColorsInMars.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
PAT-Advanced/PAT1027-ColorsInMars.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
// PAT1027-ColorsInMars.cpp // Ad // Init: 19Apr24 // Score: 20/20. // Spent time: 13 min. // Runtime: 3 ms. /* ----------------------------------------------------------------------------- 1027 Colors in Mars (20 分) People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values. ### Input Specification: Each input file contains one test case which occupies a line containing the three decimal color values. ### Output Specification: For each test case you should output the Mars RGB value in the following format: first output #, then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a 0 to its left. ---------------------------------------- Sample Input: 15 43 71 Sample Output: #123456 ---------------------------------------- ----------------------------------------------------------------------------- */ #include <iostream> #include <string> #include <vector> using namespace std; const vector<string> strDigits{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"}; string transRadix(int num); // Main ------------------------------------------------------------------------ int main() { int r = 0, g = 0, b = 0; cin >> r >> g >> b; cout << '#' << transRadix(r) << transRadix(g) << transRadix(b) << endl; system("pause"); return 0; } // Functions ------------------------------------------------------------------- string transRadix(int num) { int digit1 = num / 13; int digit2 = num % 13; return strDigits[digit1] + strDigits[digit2]; }
29.567164
154
0.547198
[ "vector" ]
04e41f0ece7e417a7ccff9dc6b5a0b5d20c416bc
3,838
hpp
C++
src/libraries/core/fields/DimensionedFields/DimensionedField/SubDimensionedField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fields/DimensionedFields/DimensionedField/SubDimensionedField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/fields/DimensionedFields/DimensionedField/SubDimensionedField.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::SubDimensionedField Description SubDimensionedField is a DimensionedField obtained as a section of another DimensionedField. Thus it is itself unallocated so that no storage is allocated or deallocated during its use. To achieve this behaviour, SubDimensionedField is derived from SubField rather than Field. SourceFiles SubDimensionedFieldI.hpp \*---------------------------------------------------------------------------*/ #ifndef SubDimensionedField_H #define SubDimensionedField_H #include "Field.hpp" #include "SubField.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class SubDimensionedField Declaration \*---------------------------------------------------------------------------*/ template<class Type, class GeoMesh> class SubDimensionedField : public regIOobject, public SubField<Type> { public: // Public typedefs typedef typename GeoMesh::Mesh Mesh; typedef typename Field<Type>::cmptType cmptType; // Constructors //- Construct from a SubField inline SubDimensionedField ( const SubField<Type>& slist ); //- Construct from a UList and size inline SubDimensionedField ( const UList<Type>& list, const label subSize ); //- Construct from a UList start and end indices inline SubDimensionedField ( const UList<Type>& list, const label subSize, const label startIndex ); //- Construct as copy inline SubDimensionedField ( const SubDimensionedField<cmptType, GeoMesh>& sfield ); // Member functions //- Return a null SubDimensionedField static inline const SubDimensionedField<Type, GeoMesh>& null(); //- Return a component field of the field inline tmp<DimensionedField<cmptType, GeoMesh> > component ( const direction ) const; //- Return the field transpose (only defined for second rank tensors) tmp<DimensionedField<Type, GeoMesh> > T() const; // Member operators //- Assignment inline void operator=(const SubDimensionedField<Type, GeoMesh>&); //- Allow cast to a const DimensionedField<Type, GeoMesh>& inline operator const DimensionedField<Type, GeoMesh>&() const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "SubDimensionedFieldI.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
28.641791
79
0.52814
[ "mesh" ]
04eb9ee8cce7bc0b053d1f40fe1bd5c08c2c7c2a
14,827
cpp
C++
ShearParaWorker.cpp
EricAlex/structrock
754d8c481d22a48ea7eb4e055eb16c64c44055ab
[ "BSD-3-Clause" ]
11
2016-05-10T07:07:35.000Z
2022-03-23T02:57:14.000Z
ShearParaWorker.cpp
liuxinren456852/structrock
1a5e660bdbb5f80fb2ab479b7398c072e2573fd1
[ "BSD-3-Clause" ]
null
null
null
ShearParaWorker.cpp
liuxinren456852/structrock
1a5e660bdbb5f80fb2ab479b7398c072e2573fd1
[ "BSD-3-Clause" ]
11
2016-03-25T01:24:59.000Z
2020-06-04T23:40:06.000Z
/* * Software License Agreement (BSD License) * * Xin Wang * * 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 copyright holder(s) 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 : Xin Wang * Email : ericrussell@zju.edu.cn * */ #include <string> #include <sstream> #include <algorithm> #include <cmath> #include <pcl/search/search.h> #include <pcl/search/kdtree.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> #include <pcl/surface/concave_hull.h> #include <pcl/surface/convex_hull.h> #include <pcl/features/normal_3d.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/ModelCoefficients.h> #include <pcl/filters/project_inliers.h> #include <Eigen/src/Core/Matrix.h> #include "omp.h" #include "globaldef.h" #include "dataLibrary.h" #include "ShearParaWorker.h" using namespace std; bool ShearParaWorker::is_para_satisfying(QString &message) { if(dataLibrary::Fracture_Triangles.size() == 0) { message = QString("shearpara: You Haven't Performed Fracture Triangulation Yet!"); return false; } else { this->setParaSize(1); if(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters.size()>=this->getParaSize()) { this->setFileName(QString::fromUtf8(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[0].c_str())); this->setParaIndex(this->getParaSize()); return true; } else { message = QString("shearpara: No Saving Path Given."); return false; } } } void ShearParaWorker::prepare() { this->setSaveScreenMode(false); if((dataLibrary::Workflow[dataLibrary::current_workline_index].parameters.size()>this->getParaIndex())&&(dataLibrary::Workflow[dataLibrary::current_workline_index].parameters[this->getParaIndex()] == "savescreen")) { this->setSaveScreenMode(true); this->setParaIndex(this->getParaIndex()+1); } this->setUnmute(); this->setWriteLog(); this->check_mute_nolog(); } Eigen::Vector3f PolygonNormal(const pcl::PointCloud<pcl::PointXYZ> &polygon) { Eigen::Vector3f vec01(polygon.at(0).x-polygon.at(1).x,polygon.at(0).y-polygon.at(1).y,polygon.at(0).z-polygon.at(1).z); Eigen::Vector3f vec21(polygon.at(2).x-polygon.at(1).x,polygon.at(2).y-polygon.at(1).y,polygon.at(2).z-polygon.at(1).z); Eigen::Vector3f normal = vec01.cross(vec21); normal.normalize(); return normal; } float PolygonArea(const pcl::PointCloud<pcl::PointXYZ> &polygon, Eigen::Vector3f normal) { int num_points = polygon.size(); int j = 0; Eigen::Vector3f va, vb, res; res(0) = res(1) = res(2) = 0.0f; for(int i = 0; i < num_points; i++) { j = (i+1) % num_points; va = polygon.at(i).getVector3fMap(); vb = polygon.at(j).getVector3fMap(); res += va.cross(vb); } return fabs(res.dot(normal) * 0.5); } float ApparentDipAngle(const pcl::PointCloud<pcl::PointXYZ> &polygon, Eigen::Vector3f shearnorm, Eigen::Vector3f sheardir) { Eigen::Vector3f polynormal = PolygonNormal(polygon); float theta = acos(fabs(shearnorm.dot(polynormal))/(shearnorm.norm()*polynormal.norm())); Eigen::Vector3f proj_norm = polynormal - (polynormal.dot(shearnorm)/shearnorm.norm())*shearnorm; float det = shearnorm.dot(sheardir.cross(proj_norm)); float alpha = atan2(det, sheardir.dot(proj_norm)); return atan(-tan(theta)*cos(alpha)); } void ShearParaWorker::doWork() { bool is_success(false); QByteArray ba = this->getFileName().toLocal8Bit(); string* strfilename = new string(ba.data()); dataLibrary::Status = STATUS_SHEARPARA; this->timer_start(); //begin of processing if(this->getSaveScreenMode()) { emit prepare_2_s_f(); for(int i=0; i<dataLibrary::Fracture_Triangles.size(); i++) { std::ostringstream strs; strs << i; string screen_png = *strfilename + "_" + strs.str() +"_.png"; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ptr(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(dataLibrary::Fracture_Triangles[i]->cloud, *cloud_ptr); dataLibrary::fracture_patches.push_back(cloud_ptr); emit show_f_save_screen(QString::fromUtf8(screen_png.c_str())); this->Sleep(1000); } } vector<float> dip_arr, dip_dir_arr; vector<int> is_large_enough_arr; dip_arr.resize(dataLibrary::Fracture_Triangles.size(), 0.0); dip_dir_arr.resize(dataLibrary::Fracture_Triangles.size(), 0.0); is_large_enough_arr.resize(dataLibrary::Fracture_Triangles.size(), 0); for(int i=0; i<dataLibrary::Fracture_Triangles.size(); i++){ pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ptr(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(dataLibrary::Fracture_Triangles[i]->cloud, *cloud_ptr); // determine the shear plane, P /*float nx, ny, nz, curvature; Eigen::Matrix3f convariance_matrix; Eigen::Vector4f xyz_centroid; pcl::compute3DCentroid(*cloud_ptr, xyz_centroid); pcl::computeCovarianceMatrix(*cloud_ptr, xyz_centroid, convariance_matrix); pcl::solvePlaneParameters(convariance_matrix, nx, ny, nz, curvature); Eigen::Vector3f plane_normal; plane_normal(0)=nx/sqrt(nx*nx+ny*ny+nz*nz); plane_normal(1)=ny/sqrt(nx*nx+ny*ny+nz*nz); plane_normal(2)=nz/sqrt(nx*nx+ny*ny+nz*nz);*/ float nx, ny, nz; Eigen::Vector4f plane_normal_param = dataLibrary::fitPlaneManually(*cloud_ptr); nx = plane_normal_param(0); ny = plane_normal_param(1); nz = plane_normal_param(2); Eigen::Vector3f plane_normal; plane_normal << nx, ny, nz; is_large_enough_arr[i] = cloud_ptr->points.size(); float dip_direction, dip; //Dip Direction if(nx == 0.0) { if((ny > 0.0)||(ny == 0.0)) dip_direction = 0.0; else dip_direction = 180.0; } else if(nx > 0.0) { dip_direction = 90.0 - atan(ny/nx)*180/M_PI; } else { dip_direction = 270.0 - atan(ny/nx)*180/M_PI; } //dip if((nx*nx + ny*ny) == 0.0) { dip = 0.0; } else { dip = 90.0 - atan(fabs(nz)/sqrt((nx*nx + ny*ny)))*180/M_PI; } dip_arr[i] = dip; dip_dir_arr[i] = dip_direction; // shear directions parallel to P std::vector<Eigen::Vector3f> sdirections; Eigen::Vector3f original; if((nx==0)&&(ny==0)) { original(0)=1.0; original(1)=0.0; original(2)=0.0; } else { original(0)=-plane_normal(1); original(1)=plane_normal(0); original(2)=0.0; } for(float j=-TWOPI/2; j<-0.001; j+=TWOPI/72) { float x = plane_normal(0); float y = plane_normal(1); float z = plane_normal(2); float c = std::cos(j); float s = std::sqrt(1-c*c); float C = 1-c; Eigen::Matrix3f rmat; rmat<<x*x*C+c,x*y*C-z*s,x*z*C+y*s,y*x*C+z*s,y*y*C+c,y*z*C-x*s,z*x*C-y*s,z*y*C+x*s,z*z*C+c; Eigen::Vector3f rotated=rmat*original; rotated.normalize(); sdirections.push_back(rotated); } int halfsize = sdirections.size(); for(int j=0; j<halfsize; j++) { Eigen::Vector3f temp_new; temp_new(0) = -sdirections[j](0); temp_new(1) = -sdirections[j](1); temp_new(2) = -sdirections[j](2); sdirections.push_back(temp_new); } vector<float> SP_arr, reci_big_c_arr, theta_max_arr; SP_arr.resize(sdirections.size(), 0.0); reci_big_c_arr.resize(sdirections.size(), 0.0); theta_max_arr.resize(sdirections.size(), 0.0); #pragma omp parallel for for(int j=0; j<sdirections.size(); j++){ float A_0, theta_max; A_0 = 0.0; std::vector< std::pair<float, float> > ADAs_As; std::vector<float> theta_cr, A_theta_cr, Big_Y, Big_X; for(int k=0; k<dataLibrary::Fracture_Triangles[i]->polygons.size(); k++) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_polygon(new pcl::PointCloud<pcl::PointXYZ>); for(int r=0; r<dataLibrary::Fracture_Triangles[i]->polygons[k].vertices.size(); r++) { cloud_polygon->push_back(cloud_ptr->at(dataLibrary::Fracture_Triangles[i]->polygons[k].vertices[r])); } float apparentDA = ApparentDipAngle(*cloud_polygon, plane_normal, sdirections[j]); if(apparentDA>0) { Eigen::Vector3f trinormal = PolygonNormal(*cloud_polygon); float temp_area = PolygonArea(*cloud_polygon, trinormal); ADAs_As.push_back(make_pair(apparentDA, temp_area)); A_0 += temp_area; } } std::sort(ADAs_As.begin(), ADAs_As.end()); theta_max = ADAs_As.back().first; float temp_cr[18] = {0.0, 1.2, 2.5, 3.9, 5.32, 6.82, 8.41, 10.0, 12.5, 15.0, 17.5, 20.0, 23.0, 26.3, 30.0, 34.0, 40.0, 50.0}; for(int k=0; k<18; k++) { if((temp_cr[k]/360*TWOPI)<theta_max) theta_cr.push_back(temp_cr[k]/360*TWOPI); } float sum_X = 0.0; float sum_Y = 0.0; for(int k=0; k<theta_cr.size(); k++) { float temp_X = log((theta_max-theta_cr[k])/theta_max); Big_X.push_back(temp_X); sum_X += temp_X; float temp_A_theta_cr = 0.0; int r=ADAs_As.size()-1; while((r>=0)&&(ADAs_As[r].first>=theta_cr[k])) { temp_A_theta_cr += ADAs_As[r].second; r--; } A_theta_cr.push_back(temp_A_theta_cr); float temp_Y = log(temp_A_theta_cr); Big_Y.push_back(temp_Y); sum_Y += temp_Y; } float mean_X = sum_X/Big_X.size(); float mean_Y = sum_Y/Big_Y.size(); float S_xy = 0.0; float S_x = 0.0; for(int k=0; k<Big_X.size(); k++) { S_x += (Big_X[k] - mean_X)*(Big_X[k] - mean_X); S_xy += (Big_X[k] - mean_X)*(Big_Y[k] - mean_Y); } float SP = (theta_max*S_x/S_xy)*360/TWOPI; float reci_big_c = S_x/S_xy; SP_arr[j] = SP; reci_big_c_arr[j] = reci_big_c; theta_max_arr[j] = theta_max; } std::ostringstream strs; strs << i; string textfilename = *strfilename + "_" + strs.str() +"_.txt"; string reci_big_c_filename = *strfilename + "_" + strs.str() +"_reciprocal_C_.txt"; string theta_max_filename = *strfilename + "_" + strs.str() +"_theta_max_.txt"; ofstream fout(textfilename.c_str()); ofstream reci_big_c_fout(reci_big_c_filename.c_str()); ofstream theta_max_fout(theta_max_filename.c_str()); for(int j=0; j<sdirections.size(); j++){ fout<<SP_arr[j]*sdirections[j](0)<<"\t"<<SP_arr[j]*sdirections[j](1)<<"\t"<<SP_arr[j]*sdirections[j](2)<<"\t"<<SP_arr[j]<<"\n"; reci_big_c_fout<<reci_big_c_arr[j]*sdirections[j](0)<<"\t"<<reci_big_c_arr[j]*sdirections[j](1)<<"\t"<<reci_big_c_arr[j]*sdirections[j](2)<<"\t"<<reci_big_c_arr[j]<<"\n"; theta_max_fout<<theta_max_arr[j]*sdirections[j](0)<<"\t"<<theta_max_arr[j]*sdirections[j](1)<<"\t"<<theta_max_arr[j]*sdirections[j](2)<<"\t"<<theta_max_arr[j]<<"\n"; } fout<<flush; fout.close(); reci_big_c_fout<<flush; reci_big_c_fout.close(); theta_max_fout<<flush; theta_max_fout.close(); } string dip_dipdir_file = *strfilename + "_dip_dipdir.txt"; ofstream dip_dipdir_out(dip_dipdir_file.c_str()); string is_large_enough = *strfilename + "_is_large_enough.txt"; ofstream is_large_enough_out(is_large_enough.c_str()); for(int i=0; i<dataLibrary::Fracture_Triangles.size(); i++){ dip_dipdir_out<<dip_arr[i]<<'\t'<<dip_dir_arr[i]<<'\n'; is_large_enough_out<<is_large_enough_arr[i]<<'\n'; } dip_dipdir_out<<flush; dip_dipdir_out.close(); is_large_enough_out<<flush; is_large_enough_out.close(); is_success = true; //end of processing this->timer_stop(); if(this->getWriteLogMode()&&is_success) { std::string log_text = "\tFracture Shear Parameter Estimation costs: "; std::ostringstream strs; strs << this->getTimer_sec(); log_text += (strs.str() +" seconds."); dataLibrary::write_text_to_log_file(log_text); } if(!this->getMuteMode()&&is_success) { emit show(); } dataLibrary::Status = STATUS_READY; emit showReadyStatus(); if(this->getWorkFlowMode()&&is_success) { this->Sleep(1000); emit GoWorkFlow(); } }
37.63198
218
0.610575
[ "vector" ]
04ec8f201632a89a4f9e3ad61a78d1e279405d59
1,503
cpp
C++
Chapter06/Palindrome/Palindrome.cpp
Vaibhav-Kashyap/CPPDataStructures-Algorithmspackt
8fa5ecbcdc836321e63a8361fd8be4b7df392961
[ "MIT" ]
207
2018-04-24T22:39:37.000Z
2022-03-28T12:16:16.000Z
Chapter06/Palindrome/Palindrome.cpp
Vaibhav-Kashyap/CPPDataStructures-Algorithmspackt
8fa5ecbcdc836321e63a8361fd8be4b7df392961
[ "MIT" ]
1
2020-06-24T23:47:28.000Z
2020-07-17T12:56:41.000Z
Chapter06/Palindrome/Palindrome.cpp
Vaibhav-Kashyap/CPPDataStructures-Algorithmspackt
8fa5ecbcdc836321e63a8361fd8be4b7df392961
[ "MIT" ]
98
2018-04-28T15:03:48.000Z
2022-01-03T12:16:07.000Z
// Project: Palindrome.cbp // File : Palindrome.cpp #include <iostream> #include <algorithm> using namespace std; bool IsPalindrome( string str) { // Palindrome is not case sensitive // so we convert all characters // to uppercase transform( str.begin(), str.end(), str.begin(), ::toupper); // Palindrome does not care about space // so we remove all spaces if any str.erase( remove( str.begin(), str.end(), ' '), str.end()); // --- Palindrome detector --- // Starting from leftmost and rightmost elements // of the str int left = 0; int right = str.length() - 1; // Comparing the current leftmost // and rightmost elements // until all elements are checked or // until unmatched characters are found while(right > left) { if(str[left++] != str[right--]) { return false; } } // If all characters which are compared // are same, it must be palindrome return true; // --- End of palindrome detector --- } int main() { cout << "Palindrome" << endl; // Input string string str; cout << "Input string -> "; getline(cin, str); // Check if it is palindrome cout << "'" << str << "' is "; if(IsPalindrome(str)) { cout << "a palindrome"; } else { cout << "NOT a palindrome"; } cout << endl; return 0; }
19.519481
52
0.533599
[ "transform" ]
04f03f65da0eba7cbddf2da3a32882304aeba607
5,734
cpp
C++
Section22/UnsocpedEnums/main.cpp
Himanshu40/Learn-Cpp
f0854f7c88bf31857c0c6216af80245666ca9b54
[ "CC-BY-4.0" ]
2
2021-07-18T18:12:10.000Z
2021-07-19T15:40:25.000Z
Section22/UnsocpedEnums/main.cpp
Himanshu40/Learn-Cpp
f0854f7c88bf31857c0c6216af80245666ca9b54
[ "CC-BY-4.0" ]
null
null
null
Section22/UnsocpedEnums/main.cpp
Himanshu40/Learn-Cpp
f0854f7c88bf31857c0c6216af80245666ca9b54
[ "CC-BY-4.0" ]
null
null
null
#include <iostream> #include <vector> #include <string> // Used for test1 enum Direction {North, South, East, West}; // Used for test2 // Unscoped enumeration representing items for a grocery shopping list enum GroceryItem {Milk, Bread, Apple, Orange}; // Used for test3 // Unscoped enumerations holding the possible states // and sequences of a rocket launch. enum State {EngineFailure, InclementWeather, Nominal, Unknown}; enum Sequence {Abort, Hold, Launch}; // enum Street {Main, North, Elm}; // Error, can't use North again // Used for test1 // This function expects a Direction parameter // and returns its string representation std::string directionToString(Direction direction) { std::string result; switch (direction) { case North: result = "North"; break; case South: result = "South"; break; case East: result = "East"; break; case West: result = "West"; break; default: result = "Unknown direction"; } return result; } // Overloading the stream insertion operator to insert // the string representation of the provided GroceryItem // parameter into the output stream std::ostream &operator<<(std::ostream &os, GroceryItem groceryItem) { switch (groceryItem) { case Milk: os << "Milk"; break; case Bread: os << "Bread"; break; case Apple: os << "Apple"; break; case Orange: os << "Orange"; break; default: os << "Invalid item"; } return os; } // Used for test2 // Returns a boolean depending on whether the GroceryItem // parameter is a valid enumerator or not bool isValidGroceryItem(GroceryItem groceryItem) { switch (groceryItem) { case Milk: case Bread: case Apple: case Orange: return true; default: return false; } } // Used for test3 std::istream &operator>>(std::istream &is, State &state) { std::underlying_type_t<State> userInput; is >> userInput; switch (userInput) { case EngineFailure: case InclementWeather: case Nominal: case Unknown: state = State(userInput); break; default: state = Unknown; } return is; } // It shows the use of an uscoped enumeration void test1() { std::cout << "===TEST1===" << std::endl; Direction x; std::cout << x << std::endl; // Gives random number everytime it run Direction direction {North}; std::cout << "\nDirection " << direction << std::endl; std::cout << directionToString(direction) << std::endl; direction = West; std::cout << "\nDirection " << direction << std::endl; std::cout << directionToString(direction) << std::endl; // direction = 5; // Compiler Error direction = Direction(100); std::cout << "\nDirection " << direction << std::endl; std::cout << directionToString(direction) << std::endl; direction = static_cast<Direction>(100); std::cout << "\nDirection " << direction << std::endl; std::cout << directionToString(direction) << std::endl; } void displayGroceryItem(const std::vector<GroceryItem> &groceryList) { std::cout << "Grocery List" << "\n=========================" << std::endl; int invalidItemCount {0}; int validItemCount {0}; for (GroceryItem groceryItem : groceryList) { std::cout << groceryItem << std::endl; if (isValidGroceryItem(groceryItem)) { validItemCount++; } else { invalidItemCount++; } } std::cout << "=========================" << std::endl; std::cout << "Valid items: " << validItemCount << std::endl; std::cout << "Invalid items: " << invalidItemCount << std::endl; std::cout << "Total items: " << validItemCount + invalidItemCount << std::endl; } // Using an unscoped enumeration to model grocery items void test2() { std::cout << "===TEST2===" << std::endl; std::vector<GroceryItem> shoppingList; shoppingList.push_back(Apple); shoppingList.push_back(Apple); shoppingList.push_back(Milk); shoppingList.push_back(Orange); // GroceryItem item = 100; // Compiler Error // Careful when casting int helicopter {1000}; shoppingList.push_back(GroceryItem(helicopter)); // Invalid item shoppingList.push_back(GroceryItem(0)); // Will add Milk again displayGroceryItem(shoppingList); } // Used for test3 std::ostream &operator<<(std::ostream &os, const Sequence sequence) { switch (sequence) { case Abort: os << "Abort"; break; case Hold: os << "Hold"; break; case Launch: os << "Launch"; break; } return os; } // Used for test3 // Displays an informtion message given the sequence parameter void initiate(Sequence sequence) { std::cout << "Initiate " << sequence << " sequence!" << std::endl; } // Using unscoped enums to control a rocket launch void test3() { std::cout << "===TEST3===" << std::endl; State state; std::cout << "Launch state: "; std::cin >> state; switch (state) { case EngineFailure: case Unknown: initiate(Abort); break; case InclementWeather: initiate(Hold); break; case Nominal: initiate(Launch); break; } } int main() { test1(); test2(); test3(); return 0; }
25.259912
83
0.574294
[ "vector", "model" ]
04f1b4c227edc6696378d71e9b7a7b1a99487867
31,172
cpp
C++
movie/win32/dsmixer.cpp
3c1u/krkrz
3655de95a45cc72e22f04ac9fa10cfbff320f53f
[ "BSD-3-Clause" ]
null
null
null
movie/win32/dsmixer.cpp
3c1u/krkrz
3655de95a45cc72e22f04ac9fa10cfbff320f53f
[ "BSD-3-Clause" ]
null
null
null
movie/win32/dsmixer.cpp
3c1u/krkrz
3655de95a45cc72e22f04ac9fa10cfbff320f53f
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************/ /*! @file @brief VMR9を使うオーバーレイクラス 実行にはDirectX9以降が必要 ----------------------------------------------------------------------------- Copyright (C) 2005 T.Imoto ----------------------------------------------------------------------------- @author T.Imoto @date 2005/09/25 @note 2005/09/25 T.Imoto 作成 *****************************************************************************/ #include "tjsCommHead.h" #include "MsgIntf.h" #include "SysInitIntf.h" #include "PluginImpl.h" //#define _WIN32_WINNT 0x0400 //#define _WIN32_DCOM // DCOM #include "dsmixer.h" #include "CIStream.h" #include "DShowException.h" #include "OptionInfo.h" #include <dvdmedia.h> #include <windowsx.h> #include <objbase.h> #include "CVMRCustomAllocatorPresenter9.h" #include "TVPVideoOverlay.h" //---------------------------------------------------------------------------- //! @brief 初期化 //---------------------------------------------------------------------------- tTVPDSMixerVideoOverlay::tTVPDSMixerVideoOverlay() { m_AvgTimePerFrame = 0; m_OwnerInst = 0; m_Width = 0; m_Height = 0; m_AllocatorPresenter = NULL; m_hMessageDrainWnd = NULL; } //---------------------------------------------------------------------------- //! @brief インターフェイスを解放する //---------------------------------------------------------------------------- tTVPDSMixerVideoOverlay::~tTVPDSMixerVideoOverlay() { Shutdown = true; ReleaseAll(); m_hMessageDrainWnd = NULL; } //---------------------------------------------------------------------------- //! @brief インターフェイスを解放する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::ReleaseAll() { if( m_MediaControl.p != NULL ) { m_MediaControl->Stop(); } if( m_AllocatorPresenter != NULL ) { // delete m_AllocatorPresenter; m_AllocatorPresenter->Release(); m_AllocatorPresenter = NULL; } if( m_VMR9SurfAllocNotify.p ) m_VMR9SurfAllocNotify.Release(); if( m_VMR9MixerCtrl.p ) m_VMR9MixerCtrl.Release(); if( m_VMR9MixerBmp.p ) m_VMR9MixerBmp.Release(); // if( m_VMR9WinLessCtrl.p ) // m_VMR9WinLessCtrl.Release(); tTVPDSMovie::ReleaseAll(); } //---------------------------------------------------------------------------- //! @brief フィルタグラフの構築 //! @param callbackwin : メッセージを送信するウィンドウ //! @param stream : 読み込み元ストリーム //! @param streamname : ストリームの名前 //! @param type : メディアタイプ(拡張子) //! @param size : メディアサイズ //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::BuildGraph( HWND callbackwin, IStream *stream, const tjs_char * streamname, const tjs_char *type, unsigned __int64 size ) { HRESULT hr; //CoInitialize(NULL); // detect CMediaType from stream's extension ('type') try { if( FAILED(hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)) ) ThrowDShowException(TJS_W("Failed to call CoInitializeEx."), hr); // create IFilterGraph instance if( FAILED(hr = m_GraphBuilder.CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC)) ) ThrowDShowException(TJS_W("Failed to create FilterGraph."), hr); // Register to ROT if(GetShouldRegisterToROT()) { AddToROT(m_dwROTReg); } { CAutoLock Lock(&m_VMRLock); OwnerWindow = callbackwin; // copy window handle for D3D m_OwnerInst = GetModuleHandle(NULL); } m_AllocatorPresenter = new CVMRCustomAllocatorPresenter9(this,m_VMRLock); m_AllocatorPresenter->AddRef(); m_AllocatorPresenter->Initialize(); if( IsWindowsMediaFile(type) ) { CComPtr<IBaseFilter> pVMR9; AddVMR9Filer( pVMR9 ); BuildWMVGraph( pVMR9, stream ); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerCtrl ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerControl9."), hr); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerBmp ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerBitmap9."), hr); } else { CMediaType mt; mt.majortype = MEDIATYPE_Stream; ParseVideoType( mt, type ); // may throw an exception // create proxy filter m_Proxy = new CIStreamProxy( stream, size ); hr = S_OK; m_Reader = new CIStreamReader( m_Proxy, &mt, &hr ); if( FAILED(hr) || m_Reader == NULL ) ThrowDShowException(TJS_W("Failed to create proxy filter object."), hr); m_Reader->AddRef(); // add fliter if( FAILED(hr = GraphBuilder()->AddFilter( m_Reader, TJS_W("Stream Reader"))) ) ThrowDShowException(TJS_W("Failed to call IFilterGraph::AddFilter."), hr); // AddFilterしたのでRelease m_Reader->Release(); if( mt.subtype == MEDIASUBTYPE_Avi || mt.subtype == MEDIASUBTYPE_QTMovie ) { // render output pin if( FAILED(hr = GraphBuilder()->Render(m_Reader->GetPin(0))) ) ThrowDShowException(TJS_W("Failed to call IGraphBuilder::Render."), hr); CComPtr<IBaseFilter> pRender; if( FAILED(hr = FindVideoRenderer( &pRender ) ) ) ThrowDShowException(TJS_W("Failed to call FindVideoRenderer( &pRender )."), hr); CComPtr<IPin> pRenderPin; pRenderPin = GetInPin(pRender, 0); // get decoder output pin CComPtr<IPin> pDecoderPinOut; if( FAILED(hr = pRenderPin->ConnectedTo( &pDecoderPinOut )) ) ThrowDShowException(TJS_W("Failed to call pRenderPin->ConnectedTo( &pDecoderPinOut )."), hr); // dissconnect pins if( FAILED(hr = pDecoderPinOut->Disconnect()) ) ThrowDShowException(TJS_W("Failed to call pDecoderPinOut->Disconnect()."), hr); if( FAILED(hr = pRenderPin->Disconnect()) ) ThrowDShowException(TJS_W("Failed to call pRenderPin->Disconnect()."), hr); // remove default render if( FAILED(hr = GraphBuilder()->RemoveFilter( pRender ) ) ) ThrowDShowException(TJS_W("Failed to call GraphBuilder->RemoveFilter(pRenderPin)."), hr); CComPtr<IBaseFilter> pVMR9; AddVMR9Filer( pVMR9 ); CComPtr<IPin> pRdrPinIn; pRdrPinIn = GetInPin(pVMR9, 0); if( FAILED(hr = GraphBuilder()->ConnectDirect( pDecoderPinOut, pRdrPinIn, NULL )) ) ThrowDShowException(TJS_W("Failed to call GraphBuilder()->ConnectDirect( pDecoderPinOut, pRdrPinIn, NULL )."), hr); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerCtrl ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerControl9."), hr); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerBmp ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerBitmap9."), hr); } #ifdef ENABLE_THEORA else if( mt.subtype == MEDIASUBTYPE_Ogg ) { CComPtr<IBaseFilter> pVMR9; AddVMR9Filer( pVMR9 ); BuildTheoraGraph( pVMR9, m_Reader); // may throw an exception if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerCtrl ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerControl9."), hr); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerBmp ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerBitmap9."), hr); } #endif else { tTVPDSFilterHandlerType* handler = TVPGetDSFilterHandler( mt.subtype ); if( handler ) { CComPtr<IBaseFilter> pVMR9; AddVMR9Filer( pVMR9 ); BuildPluginGraph( handler, pVMR9, m_Reader ); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerCtrl ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerControl9."), hr); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerBmp ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerBitmap9."), hr); } else { CComPtr<IBaseFilter> pVMR9; AddVMR9Filer( pVMR9 ); BuildMPEGGraph( pVMR9, m_Reader); // may throw an exception if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerCtrl ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerControl9."), hr); if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9MixerBmp ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRMixerBitmap9."), hr); } } } #if 1 { // 平均フレーム表示時間を取得する CComPtr<IBaseFilter> pRender; if( FAILED(hr = FindVideoRenderer( &pRender ) ) ) ThrowDShowException(TJS_W("Failed to call FindVideoRenderer( &pRender )."), hr); CComPtr<IPin> pRenderPin; pRenderPin = GetInPin(pRender, 0); AM_MEDIA_TYPE mt; if( FAILED(hr = pRenderPin->ConnectionMediaType(&mt)) ) ThrowDShowException(TJS_W("Failed to call IPin::ConnectionMediaType(pmt)."), hr); if( mt.formattype == FORMAT_VideoInfo && mt.cbFormat != 0 ) { VIDEOINFOHEADER *vih = reinterpret_cast<VIDEOINFOHEADER*>(mt.pbFormat); m_AvgTimePerFrame = vih->AvgTimePerFrame; m_Width = vih->bmiHeader.biWidth; m_Height = vih->bmiHeader.biHeight; } else if( mt.formattype == FORMAT_VideoInfo2 && mt.cbFormat != 0 ) { VIDEOINFOHEADER2 *vih = reinterpret_cast<VIDEOINFOHEADER2*>(mt.pbFormat); m_AvgTimePerFrame = vih->AvgTimePerFrame; m_Width = vih->bmiHeader.biWidth; m_Height = vih->bmiHeader.biHeight; } FreeMediaType(mt); } #endif // query each interfaces if( FAILED(hr = m_GraphBuilder.QueryInterface( &m_MediaControl )) ) ThrowDShowException(TJS_W("Failed to query IMediaControl"), hr); if( FAILED(hr = m_GraphBuilder.QueryInterface( &m_MediaPosition )) ) ThrowDShowException(TJS_W("Failed to query IMediaPosition"), hr); if( FAILED(hr = m_GraphBuilder.QueryInterface( &m_MediaSeeking )) ) ThrowDShowException(TJS_W("Failed to query IMediaSeeking"), hr); if( FAILED(hr = m_GraphBuilder.QueryInterface( &m_MediaEventEx )) ) ThrowDShowException(TJS_W("Failed to query IMediaEventEx"), hr); if( FAILED(hr = m_GraphBuilder.QueryInterface( &m_BasicAudio )) ) ThrowDShowException(TJS_W("Failed to query IBasicAudio"), hr); // set notify event if(callbackwin) { if(FAILED(hr = Event()->SetNotifyWindow((OAHWND)callbackwin, WM_GRAPHNOTIFY, (long)(this)))) ThrowDShowException(TJS_W("Failed to set IMediaEventEx::SetNotifyWindow."), hr); } } catch(const tjs_char *msg) { MakeAPause(true); ReleaseAll(); CoUninitialize(); TVPThrowExceptionMessage(msg); } catch(...) { MakeAPause(true); ReleaseAll(); CoUninitialize(); throw; } MakeAPause(false); CoUninitialize(); } //---------------------------------------------------------------------------- //! @brief VMR9フィルタをフィルタグラフへ追加する //! @param pVMR9 : VMR9フィルタ //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::AddVMR9Filer( CComPtr<IBaseFilter> &pVMR9 ) { HRESULT hr = S_OK; if( FAILED(hr = pVMR9.CoCreateInstance(CLSID_VideoMixingRenderer9, NULL, CLSCTX_INPROC) ) ) ThrowDShowException(TJS_W("Failed to create VMR9 Filter. This component requires DirectX9."), hr); if( FAILED(hr = GraphBuilder()->AddFilter( pVMR9, TJS_W("Video Mixing Render 9"))) ) ThrowDShowException(TJS_W("Failed to call GraphBuilder()->AddFilter( pVMR9, L\"Video Mixing Render 9\")."), hr); { CComPtr<IVMRFilterConfig9> pConfig; if( FAILED(hr = pVMR9.QueryInterface(&pConfig) ) ) ThrowDShowException(TJS_W("Failed to query IVMRFilterConfig9."), hr); if( FAILED(hr = pConfig->SetNumberOfStreams(1) ) ) ThrowDShowException(TJS_W("Failed to call IVMRFilterConfig9::SetNumberOfStreams(1)."), hr); if( FAILED(hr = pConfig->SetRenderingMode(VMR9Mode_Renderless ) ) ) ThrowDShowException(TJS_W("Failed to call IVMRFilterConfig9::SetRenderingMode(VMR9Mode_Renderless)."), hr); // Negotiate Renderless mode if( FAILED(hr = pVMR9.QueryInterface( &m_VMR9SurfAllocNotify ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRSurfaceAllocatorNotify9."), hr); CComPtr<IVMRSurfaceAllocator9> alloc; if( FAILED(hr = AllocatorPresenter()->QueryInterface( IID_IVMRSurfaceAllocator9, reinterpret_cast<void**>(&alloc.p) ) ) ) ThrowDShowException(TJS_W("Failed to query IVMRSurfaceAllocator9."), hr); if( FAILED(hr = AllocatorNotify()->AdviseSurfaceAllocator( reinterpret_cast<DWORD_PTR>(this), alloc ) ) ) ThrowDShowException(TJS_W("Failed to call IVMRSurfaceAllocatorNotify9::AdviseSurfaceAllocator()."), hr); if( FAILED(hr = Allocator()->AdviseNotify( AllocatorNotify() ) ) ) ThrowDShowException(TJS_W("Failed to call IVMRSurfaceAllocator9::AdviseNotify()."), hr); // query monitor config // if( FAILED(hr = pVMR9.QueryInterface(&m_VMR9MonitorConfig)) ) // ThrowDShowException(TJS_W("Failed to query IVMRMonitorConfig9."), hr); } } //---------------------------------------------------------------------------- //! @brief ミキシングするビットマップを設定する //! @param hdc : 設定しているビットマップを保持しているデバイスコンテキスト //! @param dest : 転送先位置 //! @param alpha : アルファ値 (0.0 - 1.0で指定) //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetMixingBitmap( HDC hdc, RECT *dest, float alpha ) { HRESULT hr; VMR9AlphaBitmap bmpInfo; ZeroMemory(&bmpInfo, sizeof(bmpInfo)); bmpInfo.dwFlags = VMR9AlphaBitmap_hDC | VMR9AlphaBitmap_FilterMode; bmpInfo.hdc = hdc; bmpInfo.rSrc.left = 0; bmpInfo.rSrc.top = 0; bmpInfo.rSrc.right = dest->right - dest->left; bmpInfo.rSrc.bottom = dest->bottom - dest->top; long width; long height; // GetVideoSize( &width, &height ); // ビデオサイズではなく、最終出力画像のサイズで位置を計算する width = Rect.right - Rect.left; height = Rect.bottom - Rect.top; // 0割り回避 if( width <= 0 ) width = 1; if( height <= 0 ) height = 1; if( dest ) { bmpInfo.rDest.left = (static_cast<float>(dest->left)+0.5f)/static_cast<float>(width); bmpInfo.rDest.top = (static_cast<float>(dest->top)+0.5f)/static_cast<float>(height); bmpInfo.rDest.right = (static_cast<float>(dest->right)+0.5f)/static_cast<float>(width); bmpInfo.rDest.bottom = (static_cast<float>(dest->bottom)+0.5f)/static_cast<float>(height); } else { // NULLの時は、全体にブレンドするようにする bmpInfo.rDest.left = 0.0f; bmpInfo.rDest.top = 0.0f; bmpInfo.rDest.right = 1.0f; bmpInfo.rDest.bottom = 1.0f; } bmpInfo.fAlpha = alpha; bmpInfo.dwFilterMode = MixerPref_PointFiltering; if(FAILED(hr = MixerBmp()->SetAlphaBitmap( &bmpInfo )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerBitmap9::SetAlphaBitmap."), hr); } //---------------------------------------------------------------------------- //! @brief ミキシングしているビットマップの設定を解除する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::ResetMixingBitmap() { HRESULT hr; VMR9AlphaBitmap bmpInfo; if(FAILED(hr = m_VMR9MixerBmp->GetAlphaBitmapParameters(&bmpInfo)) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerBitmap9::GetAlphaBitmapParameters."), hr); if( bmpInfo.hdc == NULL ) // 設定されていないのでリターン return; ZeroMemory(&bmpInfo, sizeof(bmpInfo)); // 設定せずにこのメソッドをコールすると、ビットマップを解除するという仕様らしい。 if(FAILED(hr = MixerBmp()->UpdateAlphaBitmapParameters( &bmpInfo )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerBitmap9::UpdateAlphaBitmapParameters."), hr); } //---------------------------------------------------------------------------- //! @brief ミキシングするビデオストリームのアルファ値を設定する //! @param a : 設定するアルファ値 //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetMixingMovieAlpha( float a ) { HRESULT hr; if(FAILED(hr = MixerControl()->SetAlpha( 0, a )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::SetAlpha."), hr); } //---------------------------------------------------------------------------- //! @brief ミキシングするビデオストリームのアルファ値を取得する //! @param a : アルファ値を受け取るポインタ //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetMixingMovieAlpha( float *a ) { HRESULT hr; if(FAILED(hr = MixerControl()->GetAlpha( 0, a )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetAlpha."), hr); } //---------------------------------------------------------------------------- //! @brief ミキシングするビデオストリームの背景色を設定する //! @param col : 設定する背景色 //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetMixingMovieBGColor( unsigned long col ) { HRESULT hr; COLORREF cr = ChangeEndian32(col<<8); if(FAILED(hr = MixerControl()->SetBackgroundClr( cr )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::SetBackgroundClr."), hr); } //---------------------------------------------------------------------------- //! @brief ミキシングするビデオストリームの背景色を取得する //! @param col : 背景色を受け取るポインタ //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetMixingMovieBGColor( unsigned long *col ) { HRESULT hr; COLORREF cr; if(FAILED(hr = MixerControl()->GetBackgroundClr( &cr )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetBackgroundClr."), hr); *col = ChangeEndian32(cr); *col >>= 8; } //---------------------------------------------------------------------------- //! @brief ウィンドウハンドルを設定する //! @param window : ウィンドウハンドル //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetWindow(HWND window) { if(Shutdown) return; if( OwnerWindow != window ) { CAutoLock Lock(&m_VMRLock); OwnerWindow = window; AllocatorPresenter()->Reset(); } } //---------------------------------------------------------------------------- //! @brief ビデオの表示矩形を設定する //! @param rect : 表示矩形 //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetRect(RECT *rect) { if(Shutdown) return; Rect = *rect; AllocatorPresenter()->SetRect(rect); } //---------------------------------------------------------------------------- //! @brief ビデオの表示/非表示を設定する //! @param b : 表示/非表示 //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetVisible(bool b) { AllocatorPresenter()->SetVisible(b); } //---------------------------------------------------------------------------- //! @brief ビデオのサイズを取得する //! @param width : 幅 //! @param height : 高さ //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetVideoSize( long *width, long *height ) { if( width == NULL || height == NULL ) TVPThrowExceptionMessage(TJS_W("Pointer is NULL.(tTVPDSMixerVideoOverlay::GetVideoSize)")); *width = m_Width; *height = m_Height; } //---------------------------------------------------------------------------- //! @brief 各フレームの平均表示時間を取得する //! @param pAvgTimePerFrame : 各フレームの平均表示時間 //! @return エラーコード //---------------------------------------------------------------------------- HRESULT __stdcall tTVPDSMixerVideoOverlay::GetAvgTimePerFrame( REFTIME *pAvgTimePerFrame ) { *pAvgTimePerFrame = (double)m_AvgTimePerFrame / 10000000.0; return S_OK; } //---------------------------------------------------------------------------- //! @brief ビデオ画像を画面へ反映する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::PresentVideoImage() { AllocatorPresenter()->PresentVideoImage(); } //---------------------------------------------------------------------------- //! @brief メッセージを送るウィンドウを設定する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetMessageDrainWindow(HWND window) { m_hMessageDrainWnd = window; } //---------------------------------------------------------------------------- //! @brief 最小値を得る //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::GetAmpControlRangeMin( float *v, int flag ) { if(Shutdown) return; VMR9ProcAmpControlRange proc = { sizeof(VMR9ProcAmpControlRange) }; proc.dwProperty = static_cast<VMR9ProcAmpControlFlags>(flag); HRESULT hr; if(FAILED(hr = MixerControl()->GetProcAmpControlRange( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetProcAmpControlRange."), hr); *v = proc.MinValue; } //---------------------------------------------------------------------------- //! @brief 最大値を得る //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::GetAmpControlRangeMax( float *v, int flag ) { if(Shutdown) return; VMR9ProcAmpControlRange proc = { sizeof(VMR9ProcAmpControlRange) }; proc.dwProperty = static_cast<VMR9ProcAmpControlFlags>(flag); HRESULT hr; if(FAILED(hr = MixerControl()->GetProcAmpControlRange( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetProcAmpControlRange."), hr); *v = proc.MaxValue; } //---------------------------------------------------------------------------- //! @brief デフォルト値を得る //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::GetAmpControlDefaultValue( float *v, int flag ) { if(Shutdown) return; VMR9ProcAmpControlRange proc = { sizeof(VMR9ProcAmpControlRange) }; proc.dwProperty = static_cast<VMR9ProcAmpControlFlags>(flag); HRESULT hr; if(FAILED(hr = MixerControl()->GetProcAmpControlRange( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetProcAmpControlRange."), hr); *v = proc.DefaultValue; } //---------------------------------------------------------------------------- //! @brief ステップサイズを得る //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::GetAmpControlStepSize( float *v, int flag ) { if(Shutdown) return; VMR9ProcAmpControlRange proc = { sizeof(VMR9ProcAmpControlRange) }; proc.dwProperty = static_cast<VMR9ProcAmpControlFlags>(flag); HRESULT hr; if(FAILED(hr = MixerControl()->GetProcAmpControlRange( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetProcAmpControlRange."), hr); *v = proc.StepSize; } //---------------------------------------------------------------------------- //! @brief 値を得る //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::GetAmpControl( float *v, int flag ) { if(Shutdown) return; VMR9ProcAmpControl proc = { sizeof(VMR9ProcAmpControl) }; proc.dwFlags = flag; HRESULT hr; if(FAILED(hr = MixerControl()->GetProcAmpControl( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetProcAmpControl."), hr); switch( flag ) { case ProcAmpControl9_Contrast: *v = proc.Contrast; break; case ProcAmpControl9_Brightness: *v = proc.Brightness; break; case ProcAmpControl9_Hue: *v = proc.Hue; break; case ProcAmpControl9_Saturation: *v = proc.Saturation; break; } } //---------------------------------------------------------------------------- //! @brief 値を設定する //---------------------------------------------------------------------------- void tTVPDSMixerVideoOverlay::SetAmpControl( float v, int flag ) { if(Shutdown) return; VMR9ProcAmpControl proc = { sizeof(VMR9ProcAmpControl) }; HRESULT hr; if(FAILED(hr = MixerControl()->GetProcAmpControl( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::GetProcAmpControl."), hr); if( proc.dwFlags & flag ) { proc.dwFlags = flag; switch( flag ) { case ProcAmpControl9_Contrast: proc.Contrast = v; break; case ProcAmpControl9_Brightness: proc.Brightness = v; break; case ProcAmpControl9_Hue: proc.Hue = v; break; case ProcAmpControl9_Saturation: proc.Saturation = v; break; } if(FAILED(hr = MixerControl()->SetProcAmpControl( 0, &proc )) ) ThrowDShowException(TJS_W("Failed to set IVMRMixerControl9::SetProcAmpControl."), hr); } else { ThrowDShowException(TJS_W("Not supported parameter. IVMRMixerControl9::SetProcAmpControl."), hr); } } //---------------------------------------------------------------------------- //! @brief コントラストの幅の最小値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetContrastRangeMin( float *v ) { GetAmpControlRangeMin( v, ProcAmpControl9_Contrast ); } //---------------------------------------------------------------------------- //! @brief コントラストの幅の最大値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetContrastRangeMax( float *v ) { GetAmpControlRangeMax( v, ProcAmpControl9_Contrast ); } //---------------------------------------------------------------------------- //! @brief コントラストのデフォルト値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetContrastDefaultValue( float *v ) { GetAmpControlDefaultValue( v, ProcAmpControl9_Contrast ); } //---------------------------------------------------------------------------- //! @brief コントラストのステップサイズを得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetContrastStepSize( float *v ) { GetAmpControlStepSize( v, ProcAmpControl9_Contrast ); } //---------------------------------------------------------------------------- //! @brief コントラストを得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetContrast( float *v ) { GetAmpControl( v, ProcAmpControl9_Contrast ); } //---------------------------------------------------------------------------- //! @brief コントラストを設定する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetContrast( float v ) { SetAmpControl( v, ProcAmpControl9_Contrast ); } //---------------------------------------------------------------------------- //! @brief 輝度の幅の最小値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetBrightnessRangeMin( float *v ) { GetAmpControlRangeMin( v, ProcAmpControl9_Brightness ); } //---------------------------------------------------------------------------- //! @brief 輝度の幅の最大値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetBrightnessRangeMax( float *v ) { GetAmpControlRangeMax( v, ProcAmpControl9_Brightness ); } //---------------------------------------------------------------------------- //! @brief 輝度のデフォルト値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetBrightnessDefaultValue( float *v ) { GetAmpControlDefaultValue( v, ProcAmpControl9_Brightness ); } //---------------------------------------------------------------------------- //! @brief 輝度のステップサイズを得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetBrightnessStepSize( float *v ) { GetAmpControlStepSize( v, ProcAmpControl9_Brightness ); } //---------------------------------------------------------------------------- //! @brief 輝度を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetBrightness( float *v ) { GetAmpControl( v, ProcAmpControl9_Brightness ); } //---------------------------------------------------------------------------- //! @brief 輝度を設定する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetBrightness( float v ) { SetAmpControl( v, ProcAmpControl9_Brightness ); } //---------------------------------------------------------------------------- //! @brief 色相の幅の最小値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetHueRangeMin( float *v ) { GetAmpControlRangeMin( v, ProcAmpControl9_Hue ); } //---------------------------------------------------------------------------- //! @brief 色相の幅の最大値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetHueRangeMax( float *v ) { GetAmpControlRangeMax( v, ProcAmpControl9_Hue ); } //---------------------------------------------------------------------------- //! @brief 色相のデフォルト値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetHueDefaultValue( float *v ) { GetAmpControlDefaultValue( v, ProcAmpControl9_Hue ); } //---------------------------------------------------------------------------- //! @brief 色相のステップサイズを得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetHueStepSize( float *v ) { GetAmpControlStepSize( v, ProcAmpControl9_Hue ); } //---------------------------------------------------------------------------- //! @brief 色相を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetHue( float *v ) { GetAmpControl( v, ProcAmpControl9_Hue ); } //---------------------------------------------------------------------------- //! @brief 色相を設定する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetHue( float v ) { SetAmpControl( v, ProcAmpControl9_Hue ); } //---------------------------------------------------------------------------- //! @brief 彩度の幅の最小値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetSaturationRangeMin( float *v ) { GetAmpControlRangeMin( v, ProcAmpControl9_Saturation ); } //---------------------------------------------------------------------------- //! @brief 彩度の幅の最大値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetSaturationRangeMax( float *v ) { GetAmpControlRangeMax( v, ProcAmpControl9_Saturation ); } //---------------------------------------------------------------------------- //! @brief 彩度のデフォルト値を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetSaturationDefaultValue( float *v ) { GetAmpControlDefaultValue( v, ProcAmpControl9_Saturation ); } //---------------------------------------------------------------------------- //! @brief 彩度のステップサイズを得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetSaturationStepSize( float *v ) { GetAmpControlStepSize( v, ProcAmpControl9_Saturation ); } //---------------------------------------------------------------------------- //! @brief 彩度を得る //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::GetSaturation( float *v ) { GetAmpControl( v, ProcAmpControl9_Saturation ); } //---------------------------------------------------------------------------- //! @brief 彩度を設定する //---------------------------------------------------------------------------- void __stdcall tTVPDSMixerVideoOverlay::SetSaturation( float v ) { SetAmpControl( v, ProcAmpControl9_Saturation ); }
37.830097
161
0.543244
[ "render", "object" ]
04f503a81ff04d6aa5bb3342a7b1c4a3a240f4be
10,199
cpp
C++
bftengine/src/bftengine/IncomingMsgsStorage.cpp
MaggieQi/concord-bft
8db0cfbec988e691ce592901124bee6617d64be4
[ "Apache-2.0" ]
null
null
null
bftengine/src/bftengine/IncomingMsgsStorage.cpp
MaggieQi/concord-bft
8db0cfbec988e691ce592901124bee6617d64be4
[ "Apache-2.0" ]
null
null
null
bftengine/src/bftengine/IncomingMsgsStorage.cpp
MaggieQi/concord-bft
8db0cfbec988e691ce592901124bee6617d64be4
[ "Apache-2.0" ]
1
2021-05-18T02:12:33.000Z
2021-05-18T02:12:33.000Z
//Concord // //Copyright (c) 2018 VMware, Inc. All Rights Reserved. // //This product is licensed to you under the Apache 2.0 license (the "License"). You may not use this product except in compliance with the Apache 2.0 License. // //This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. #include "IncomingMsgsStorage.hpp" #include "MessageBase.hpp" #include "Logger.hpp" using std::queue; namespace bftEngine { namespace impl { IncomingMsgsStorage::IncomingMsgsStorage(uint16_t maxNumOfPendingExternalMsgs) : maxNumberOfPendingExternalMsgs{ maxNumOfPendingExternalMsgs } { ptrProtectedQueueForExternalMessages = new queue<MessageBase*>(); ptrProtectedQueueForInternalMessages = new queue<InternalMessage*>(); lastOverflowWarning = MinTime; ptrThreadLocalQueueForExternalMessages = new queue<MessageBase*>(); ptrThreadLocalQueueForInternalMessages = new queue<InternalMessage*>(); } IncomingMsgsStorage::~IncomingMsgsStorage() { delete ptrProtectedQueueForExternalMessages; delete ptrProtectedQueueForInternalMessages; delete ptrThreadLocalQueueForExternalMessages; delete ptrThreadLocalQueueForInternalMessages; } void IncomingMsgsStorage::pushExternalMsg(MessageBase* m) // can be called by any thread { std::unique_lock<std::mutex> mlock(lock); { if (ptrProtectedQueueForExternalMessages->size() >= maxNumberOfPendingExternalMsgs && m->type() == MsgCode::Request) { Time n = getMonotonicTime(); if (subtract(n, lastOverflowWarning) > ((TimeDeltaMirco)minTimeBetweenOverflowWarningsMilli * 1000)) { LOG_WARN_F(GL, "More than %d pending messages in consensus queue - may ignore some of the messages!", (int)maxNumberOfPendingExternalMsgs); lastOverflowWarning = n; } delete m; // ignore message } else { ptrProtectedQueueForExternalMessages->push(m); condVar.notify_one(); } } } void IncomingMsgsStorage::pushExternalOrderingMsg(MessageBase* m) // can be called by any thread { std::unique_lock<std::mutex> mlock(lock); { if (ptrProtectedQueueForExternalMessages->size() >= (maxNumberOfPendingExternalMsgs >> 1) && m->type() == MsgCode::ClientGetTimeStamp) { Time n = getMonotonicTime(); if (subtract(n, lastOverflowWarning) > ((TimeDeltaMirco)minTimeBetweenOverflowWarningsMilli * 1000)) { LOG_WARN_F(GL, "More than %d pending messages in ordering queue - may ignore some of the messages!", (int)maxNumberOfPendingExternalMsgs); lastOverflowWarning = n; } delete m; // ignore message } else { ptrProtectedQueueForExternalMessages->push(m); condVar.notify_one(); } } } void IncomingMsgsStorage::pushInternalMsg(InternalMessage* m) // can be called by any thread { std::unique_lock<std::mutex> mlock(lock); { ptrProtectedQueueForInternalMessages->push(m); condVar.notify_one(); } } bool IncomingMsgsStorage::pop(void*& item, bool& external, std::chrono::milliseconds timeout) // should only be called by the main thread { if (popThreadLocal(item, external)) return true; { std::unique_lock<std::mutex> mlock(lock); { if (ptrProtectedQueueForExternalMessages->empty() && ptrProtectedQueueForInternalMessages->empty()) condVar.wait_for(mlock, timeout); if (ptrProtectedQueueForExternalMessages->empty() && ptrProtectedQueueForInternalMessages->empty()) // no new message return false; // swap queues std::queue<MessageBase*>* t1 = ptrThreadLocalQueueForExternalMessages; ptrThreadLocalQueueForExternalMessages = ptrProtectedQueueForExternalMessages; ptrProtectedQueueForExternalMessages = t1; std::queue<InternalMessage*>* t2 = ptrThreadLocalQueueForInternalMessages; ptrThreadLocalQueueForInternalMessages = ptrProtectedQueueForInternalMessages; ptrProtectedQueueForInternalMessages = t2; } } return popThreadLocal(item, external); } bool IncomingMsgsStorage::empty() // should only be called by the main thread. { if (!ptrThreadLocalQueueForExternalMessages->empty() || !ptrThreadLocalQueueForInternalMessages->empty()) return false; { std::unique_lock<std::mutex> mlock(lock); { return (ptrProtectedQueueForExternalMessages->empty() && ptrProtectedQueueForInternalMessages->empty()); } } } bool IncomingMsgsStorage::popThreadLocal(void*& item, bool& external) { if (!ptrThreadLocalQueueForInternalMessages->empty()) { InternalMessage* iMsg = ptrThreadLocalQueueForInternalMessages->front(); ptrThreadLocalQueueForInternalMessages->pop(); item = (void*)iMsg; external = false; return true; } else if (!ptrThreadLocalQueueForExternalMessages->empty()) { MessageBase* eMsg = ptrThreadLocalQueueForExternalMessages->front(); ptrThreadLocalQueueForExternalMessages->pop(); item = (void*)eMsg; external = true; return true; } else { return false; } } bool MessageBaseCmp::operator() (MessageBase* a, MessageBase* b) { return a->type() < b->type(); } PriorityIncomingMsgsStorage::PriorityIncomingMsgsStorage(uint16_t maxNumOfPendingExternalMsgs) : maxNumberOfPendingExternalMsgs{ maxNumOfPendingExternalMsgs } { ptrProtectedQueueForExternalMessages = new std::priority_queue<MessageBase*, std::vector<MessageBase*>, MessageBaseCmp>(); ptrProtectedQueueForInternalMessages = new queue<InternalMessage*>(); lastOverflowWarning = MinTime; ptrThreadLocalQueueForExternalMessages = new std::priority_queue<MessageBase*, std::vector<MessageBase*>, MessageBaseCmp>(); ptrThreadLocalQueueForInternalMessages = new queue<InternalMessage*>(); } PriorityIncomingMsgsStorage::~PriorityIncomingMsgsStorage() { delete ptrProtectedQueueForExternalMessages; delete ptrProtectedQueueForInternalMessages; delete ptrThreadLocalQueueForExternalMessages; delete ptrThreadLocalQueueForInternalMessages; } void PriorityIncomingMsgsStorage::pushExternalMsg(MessageBase* m) // can be called by any thread { std::unique_lock<std::mutex> mlock(lock); { if (ptrProtectedQueueForExternalMessages->size() >= maxNumberOfPendingExternalMsgs && m->type() == MsgCode::Request) { Time n = getMonotonicTime(); if (subtract(n, lastOverflowWarning) > ((TimeDeltaMirco)minTimeBetweenOverflowWarningsMilli * 1000)) { LOG_WARN_F(GL, "More than %d pending messages in consensus queue - may ignore some of the messages!", (int)maxNumberOfPendingExternalMsgs); lastOverflowWarning = n; } delete m; // ignore message } else { ptrProtectedQueueForExternalMessages->push(m); condVar.notify_one(); } } } void PriorityIncomingMsgsStorage::pushExternalOrderingMsg(MessageBase* m) // can be called by any thread { std::unique_lock<std::mutex> mlock(lock); { if (ptrProtectedQueueForExternalMessages->size() >= (maxNumberOfPendingExternalMsgs >> 1) && m->type() == MsgCode::ClientGetTimeStamp) { Time n = getMonotonicTime(); if (subtract(n, lastOverflowWarning) > ((TimeDeltaMirco)minTimeBetweenOverflowWarningsMilli * 1000)) { LOG_WARN_F(GL, "More than %d pending messages in ordering queue - may ignore some of the messages!", (int)maxNumberOfPendingExternalMsgs); lastOverflowWarning = n; } delete m; // ignore message } else { ptrProtectedQueueForExternalMessages->push(m); condVar.notify_one(); } } } void PriorityIncomingMsgsStorage::pushInternalMsg(InternalMessage* m) // can be called by any thread { std::unique_lock<std::mutex> mlock(lock); { ptrProtectedQueueForInternalMessages->push(m); condVar.notify_one(); } } bool PriorityIncomingMsgsStorage::pop(void*& item, bool& external, std::chrono::milliseconds timeout) // should only be called by the main thread { if (popThreadLocal(item, external)) return true; { std::unique_lock<std::mutex> mlock(lock); { if (ptrProtectedQueueForExternalMessages->empty() && ptrProtectedQueueForInternalMessages->empty()) condVar.wait_for(mlock, timeout); if (ptrProtectedQueueForExternalMessages->empty() && ptrProtectedQueueForInternalMessages->empty()) // no new message return false; // swap queues std::priority_queue<MessageBase*, std::vector<MessageBase*>, MessageBaseCmp>* t1 = ptrThreadLocalQueueForExternalMessages; ptrThreadLocalQueueForExternalMessages = ptrProtectedQueueForExternalMessages; ptrProtectedQueueForExternalMessages = t1; std::queue<InternalMessage*>* t2 = ptrThreadLocalQueueForInternalMessages; ptrThreadLocalQueueForInternalMessages = ptrProtectedQueueForInternalMessages; ptrProtectedQueueForInternalMessages = t2; } } return popThreadLocal(item, external); } bool PriorityIncomingMsgsStorage::empty() // should only be called by the main thread. { if (!ptrThreadLocalQueueForExternalMessages->empty() || !ptrThreadLocalQueueForInternalMessages->empty()) return false; { std::unique_lock<std::mutex> mlock(lock); { return (ptrProtectedQueueForExternalMessages->empty() && ptrProtectedQueueForInternalMessages->empty()); } } } bool PriorityIncomingMsgsStorage::popThreadLocal(void*& item, bool& external) { if (!ptrThreadLocalQueueForInternalMessages->empty()) { InternalMessage* iMsg = ptrThreadLocalQueueForInternalMessages->front(); ptrThreadLocalQueueForInternalMessages->pop(); item = (void*)iMsg; external = false; return true; } else if (!ptrThreadLocalQueueForExternalMessages->empty()) { MessageBase* eMsg = ptrThreadLocalQueueForExternalMessages->top(); ptrThreadLocalQueueForExternalMessages->pop(); item = (void*)eMsg; external = true; return true; } else { return false; } } } }
31.094512
235
0.721149
[ "vector" ]
04f55eea6bb1e2226b3ba129e2e21b4f2a258322
2,815
cpp
C++
Asteroids/src/renderer/DebugLine.cpp
alan-y-han/Asteroids
1428d9a3e73952f27e6fa106d1720aab6bcf10e7
[ "Zlib", "MIT" ]
1
2018-04-24T15:41:27.000Z
2018-04-24T15:41:27.000Z
Asteroids/src/renderer/DebugLine.cpp
alan-y-han/Asteroids
1428d9a3e73952f27e6fa106d1720aab6bcf10e7
[ "Zlib", "MIT" ]
null
null
null
Asteroids/src/renderer/DebugLine.cpp
alan-y-han/Asteroids
1428d9a3e73952f27e6fa106d1720aab6bcf10e7
[ "Zlib", "MIT" ]
null
null
null
#include "DebugLine.h" #include <iostream> DebugLine::DebugLine() { // Create VAO glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); // Create VBO glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // Setup instancing (N.B. instance data is uploaded in draw()) glGenBuffers(1, &instanceVBO); glBindBuffer(GL_ARRAY_BUFFER, instanceVBO); // alpha attribute (instanced) glEnableVertexAttribArray(2); glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(InstanceVAs), (void*)(offsetof(struct InstanceVAs, alpha))); glVertexAttribDivisor(2, 1); // model matrix attribute (instanced) (N.B. using offsetof() in case of struct padding) // column 1 glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(InstanceVAs), (void*)(offsetof(struct InstanceVAs, modelMatrix))); glVertexAttribDivisor(3, 1); // column 2 glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(InstanceVAs), (void*)(offsetof(struct InstanceVAs, modelMatrix) + sizeof(glm::vec4))); glVertexAttribDivisor(4, 1); // column 3 glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(InstanceVAs), (void*)(offsetof(struct InstanceVAs, modelMatrix) + (2 * sizeof(glm::vec4)))); glVertexAttribDivisor(5, 1); // column 4 glEnableVertexAttribArray(6); glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(InstanceVAs), (void*)(offsetof(struct InstanceVAs, modelMatrix) + (3 * sizeof(glm::vec4)))); glVertexAttribDivisor(6, 1); // unbind buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } DebugLine::~DebugLine() { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &instanceVBO); } void DebugLine::draw(glm::vec2 p1, glm::vec2 p2, glm::vec3 color) { VBOtemp.clear(); VBOtemp.push_back(glm::vec3(p1, 0.0f)); VBOtemp.push_back(color); VBOtemp.push_back(glm::vec3(p2, 0.0f)); VBOtemp.push_back(color); // Upload data glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), VBOtemp.data(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, instanceVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(InstanceVAs), &instance, GL_DYNAMIC_DRAW); // draw glBindVertexArray(VAO); glDrawArrays(GL_LINE_LOOP, 0, 2); // unbind buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); }
33.915663
151
0.698757
[ "model" ]
04f74e61395a7e911b99cce321691e01bd02148d
2,619
cc
C++
TFM/click-2.0.1/elements/standard/portinfo.cc
wangyang2013/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
3
2018-04-14T14:43:31.000Z
2019-12-06T13:09:58.000Z
TFM/click-2.0.1/elements/standard/portinfo.cc
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
TFM/click-2.0.1/elements/standard/portinfo.cc
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
// -*- c-basic-offset: 4; related-file-name: "../../include/click/standard/portinfo.hh" -*- /* * portinfo.{cc,hh} -- element stores TCP/UDP port information * Eddie Kohler * * Copyright (c) 2004 The Regents of the University of California * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/standard/portinfo.hh> #include <click/nameinfo.hh> #include <click/glue.hh> #include <click/confparse.hh> #include <click/router.hh> #include <click/error.hh> CLICK_DECLS PortInfo::PortInfo() { } PortInfo::~PortInfo() { } int PortInfo::configure(Vector<String> &conf, ErrorHandler *errh) { for (int i = 0; i < conf.size(); i++) { String str = conf[i]; String name_str = cp_shift_spacevec(str); if (!name_str // allow empty arguments || name_str[0] == '#') // allow comments continue; String port_str = cp_shift_spacevec(str); uint32_t port; int32_t proto = IP_PROTO_TCP_OR_UDP; const char *slash = cp_integer(port_str.begin(), port_str.end(), 0, &port); if (slash != port_str.end() && *slash == '/') { if (slash + 4 == port_str.end() && memcmp(slash, "/tcp", 4) == 0) proto = IP_PROTO_TCP; else if (slash + 4 == port_str.end() && memcmp(slash, "/udp", 4) == 0) proto = IP_PROTO_UDP; else if (NameInfo::query_int(NameInfo::T_IP_PROTO, this, port_str.substring(slash + 1, port_str.end()), &proto)) /* got proto */; else continue; } else if (slash == port_str.begin() || slash != port_str.end()) { errh->error("expected %<NAME PORT/PROTO%>"); continue; } do { if (proto == IP_PROTO_TCP_OR_UDP) { NameInfo::define(NameInfo::T_TCP_PORT, this, name_str, &port, 4); NameInfo::define(NameInfo::T_UDP_PORT, this, name_str, &port, 4); } else NameInfo::define(NameInfo::T_IP_PORT + proto, this, name_str, &port, 4); name_str = cp_shift_spacevec(str); } while (name_str && name_str[0] != '#'); } return errh->nerrors() ? -1 : 0; } CLICK_ENDDECLS EXPORT_ELEMENT(PortInfo) ELEMENT_HEADER(<click/standard/portinfo.hh>)
32.333333
117
0.683467
[ "vector" ]
04f7929c03f4c5361f3fd371c3f54539bad6e91a
16,865
cpp
C++
Co-Simulation/Sumo/sumo-1.7.0/src/guisim/GUICalibrator.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/guisim/GUICalibrator.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/guisim/GUICalibrator.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 GUICalibrator.cpp /// @author Daniel Krajzewicz /// @author Jakob Erdmann /// @author Michael Behrisch /// @date Mon, 26.04.2004 /// // Changes flow and speed on a set of lanes (gui version) /****************************************************************************/ #include <config.h> #include <string> #include <utils/common/MsgHandler.h> #include <utils/geom/PositionVector.h> #include <utils/geom/Boundary.h> #include <utils/gui/div/GLHelper.h> #include <utils/common/ToString.h> #include <utils/common/Command.h> #include <microsim/MSNet.h> #include <microsim/MSLane.h> #include <microsim/MSEdge.h> #include <guisim/GUINet.h> #include <guisim/GUIEdge.h> #include <utils/gui/globjects/GUIGLObjectPopupMenu.h> #include <utils/gui/windows/GUIAppEnum.h> #include <gui/GUIGlobals.h> #include <utils/gui/div/GUIParameterTableWindow.h> #include <gui/GUIApplicationWindow.h> #include <microsim/logging/FunctionBinding.h> #include <utils/gui/div/GUIGlobalSelection.h> #include <utils/gui/images/GUIIconSubSys.h> #include <guisim/GUICalibrator.h> #include <utils/gui/globjects/GLIncludes.h> #include "GUICalibrator.h" // =========================================================================== // FOX callback mapping // =========================================================================== /* ------------------------------------------------------------------------- * GUICalibrator::GUICalibratorPopupMenu - mapping * ----------------------------------------------------------------------- */ FXDEFMAP(GUICalibrator::GUICalibratorPopupMenu) GUICalibratorPopupMenuMap[] = { FXMAPFUNC(SEL_COMMAND, MID_MANIP, GUICalibrator::GUICalibratorPopupMenu::onCmdOpenManip), }; // Object implementation FXIMPLEMENT(GUICalibrator::GUICalibratorPopupMenu, GUIGLObjectPopupMenu, GUICalibratorPopupMenuMap, ARRAYNUMBER(GUICalibratorPopupMenuMap)) /* ------------------------------------------------------------------------- * GUICalibrator::GUIManip_Calibrator - mapping * ----------------------------------------------------------------------- */ FXDEFMAP(GUICalibrator::GUIManip_Calibrator) GUIManip_CalibratorMap[] = { FXMAPFUNC(SEL_COMMAND, GUICalibrator::GUIManip_Calibrator::MID_USER_DEF, GUICalibrator::GUIManip_Calibrator::onCmdUserDef), FXMAPFUNC(SEL_UPDATE, GUICalibrator::GUIManip_Calibrator::MID_USER_DEF, GUICalibrator::GUIManip_Calibrator::onUpdUserDef), FXMAPFUNC(SEL_COMMAND, GUICalibrator::GUIManip_Calibrator::MID_PRE_DEF, GUICalibrator::GUIManip_Calibrator::onCmdPreDef), FXMAPFUNC(SEL_UPDATE, GUICalibrator::GUIManip_Calibrator::MID_PRE_DEF, GUICalibrator::GUIManip_Calibrator::onUpdPreDef), FXMAPFUNC(SEL_COMMAND, GUICalibrator::GUIManip_Calibrator::MID_OPTION, GUICalibrator::GUIManip_Calibrator::onCmdChangeOption), FXMAPFUNC(SEL_COMMAND, GUICalibrator::GUIManip_Calibrator::MID_CLOSE, GUICalibrator::GUIManip_Calibrator::onCmdClose), }; FXIMPLEMENT(GUICalibrator::GUIManip_Calibrator, GUIManipulator, GUIManip_CalibratorMap, ARRAYNUMBER(GUIManip_CalibratorMap)) // =========================================================================== // method definitions // =========================================================================== /* ------------------------------------------------------------------------- * GUICalibrator::GUIManip_Calibrator - methods * ----------------------------------------------------------------------- */ GUICalibrator::GUIManip_Calibrator::GUIManip_Calibrator( GUIMainWindow& app, const std::string& name, GUICalibrator& o, int /*xpos*/, int /*ypos*/) : GUIManipulator(app, name, 0, 0), myParent(&app), myChosenValue(0), myChosenTarget(myChosenValue, nullptr, MID_OPTION), //mySpeed(o.getDefaultSpeed()), mySpeed(0), mySpeedTarget(mySpeed), myObject(&o) { myChosenTarget.setTarget(this); FXVerticalFrame* f1 = new FXVerticalFrame(this, LAYOUT_FILL_X | LAYOUT_FILL_Y, 0, 0, 0, 0, 0, 0, 0, 0); FXGroupBox* gp = new FXGroupBox(f1, "Change Speed", GROUPBOX_TITLE_LEFT | FRAME_RIDGE, 0, 0, 0, 0, 4, 4, 1, 1, 2, 0); { // default FXHorizontalFrame* gf1 = new FXHorizontalFrame(gp, LAYOUT_TOP | LAYOUT_LEFT, 0, 0, 0, 0, 10, 10, 5, 5); new FXRadioButton(gf1, "Default", &myChosenTarget, FXDataTarget::ID_OPTION + 0, ICON_BEFORE_TEXT | LAYOUT_SIDE_TOP, 0, 0, 0, 0, 2, 2, 0, 0); } { // loaded FXHorizontalFrame* gf0 = new FXHorizontalFrame(gp, LAYOUT_TOP | LAYOUT_LEFT, 0, 0, 0, 0, 10, 10, 5, 5); new FXRadioButton(gf0, "Loaded", &myChosenTarget, FXDataTarget::ID_OPTION + 1, ICON_BEFORE_TEXT | LAYOUT_SIDE_TOP, 0, 0, 0, 0, 2, 2, 0, 0); } { // predefined FXHorizontalFrame* gf2 = new FXHorizontalFrame(gp, LAYOUT_TOP | LAYOUT_LEFT, 0, 0, 0, 0, 10, 10, 5, 5); new FXRadioButton(gf2, "Predefined: ", &myChosenTarget, FXDataTarget::ID_OPTION + 2, ICON_BEFORE_TEXT | LAYOUT_SIDE_TOP | LAYOUT_CENTER_Y, 0, 0, 0, 0, 2, 2, 0, 0); myPredefinedValues = new FXComboBox(gf2, 10, this, MID_PRE_DEF, ICON_BEFORE_TEXT | LAYOUT_SIDE_TOP | LAYOUT_CENTER_Y | COMBOBOX_STATIC); myPredefinedValues->appendItem("20 km/h"); myPredefinedValues->appendItem("40 km/h"); myPredefinedValues->appendItem("60 km/h"); myPredefinedValues->appendItem("80 km/h"); myPredefinedValues->appendItem("100 km/h"); myPredefinedValues->appendItem("120 km/h"); myPredefinedValues->appendItem("140 km/h"); myPredefinedValues->appendItem("160 km/h"); myPredefinedValues->appendItem("180 km/h"); myPredefinedValues->appendItem("200 km/h"); myPredefinedValues->setNumVisible(5); } { // free FXHorizontalFrame* gf12 = new FXHorizontalFrame(gp, LAYOUT_TOP | LAYOUT_LEFT, 0, 0, 0, 0, 10, 10, 5, 5); new FXRadioButton(gf12, "Free Entry: ", &myChosenTarget, FXDataTarget::ID_OPTION + 3, ICON_BEFORE_TEXT | LAYOUT_SIDE_TOP | LAYOUT_CENTER_Y, 0, 0, 0, 0, 2, 2, 0, 0); myUserDefinedSpeed = new FXRealSpinner(gf12, 10, this, MID_USER_DEF, LAYOUT_TOP | FRAME_SUNKEN | FRAME_THICK); //myUserDefinedSpeed->setFormatString("%.0f km/h"); //myUserDefinedSpeed->setIncrements(1, 10, 10); myUserDefinedSpeed->setIncrement(10); myUserDefinedSpeed->setRange(0, 300); myUserDefinedSpeed->setValue(0); //static_cast<GUICalibrator*>(myObject)->getDefaultSpeed() * 3.6); } new FXButton(f1, "Close", nullptr, this, MID_CLOSE, BUTTON_INITIAL | BUTTON_DEFAULT | FRAME_RAISED | FRAME_THICK | LAYOUT_TOP | LAYOUT_LEFT | LAYOUT_CENTER_X, 0, 0, 0, 0, 30, 30, 4, 4); //static_cast<GUICalibrator*>(myObject)->setOverriding(true); } GUICalibrator::GUIManip_Calibrator::~GUIManip_Calibrator() {} long GUICalibrator::GUIManip_Calibrator::onCmdClose(FXObject*, FXSelector, void*) { destroy(); return 1; } long GUICalibrator::GUIManip_Calibrator::onCmdUserDef(FXObject*, FXSelector, void*) { //mySpeed = (double)(myUserDefinedSpeed->getValue() / 3.6); //static_cast<GUICalibrator*>(myObject)->setOverridingValue(mySpeed); //myParent->updateChildren(); return 1; } long GUICalibrator::GUIManip_Calibrator::onUpdUserDef(FXObject* sender, FXSelector, void* ptr) { sender->handle(this, myChosenValue != 3 ? FXSEL(SEL_COMMAND, ID_DISABLE) : FXSEL(SEL_COMMAND, ID_ENABLE), ptr); myParent->updateChildren(); return 1; } long GUICalibrator::GUIManip_Calibrator::onCmdPreDef(FXObject*, FXSelector, void*) { //mySpeed = (double)(double)((myPredefinedValues->getCurrentItem() * 20 + 20) / 3.6); //static_cast<GUICalibrator*>(myObject)->setOverridingValue(mySpeed); //myParent->updateChildren(); return 1; } long GUICalibrator::GUIManip_Calibrator::onUpdPreDef(FXObject* sender, FXSelector, void* ptr) { sender->handle(this, myChosenValue != 2 ? FXSEL(SEL_COMMAND, ID_DISABLE) : FXSEL(SEL_COMMAND, ID_ENABLE), ptr); myParent->updateChildren(); return 1; } long GUICalibrator::GUIManip_Calibrator::onCmdChangeOption(FXObject*, FXSelector, void*) { //static_cast<GUICalibrator*>(myObject)->setOverriding(true); //switch (myChosenValue) { // case 0: // mySpeed = (double) static_cast<GUICalibrator*>(myObject)->getDefaultSpeed(); // break; // case 1: // mySpeed = (double) static_cast<GUICalibrator*>(myObject)->getLoadedSpeed(); // break; // case 2: // mySpeed = (double)((myPredefinedValues->getCurrentItem() * 20 + 20) / 3.6); // break; // case 3: // mySpeed = (double)(myUserDefinedSpeed->getValue() / 3.6); // break; // default: // // hmmm, should not happen // break; //} //static_cast<GUICalibrator*>(myObject)->setOverridingValue(mySpeed); //myParent->updateChildren(); //if (myChosenValue == 1) { // // !!! lock in between // static_cast<GUICalibrator*>(myObject)->setOverriding(false); //} return 1; } /* ------------------------------------------------------------------------- * GUICalibrator::GUICalibratorPopupMenu - methods * ----------------------------------------------------------------------- */ GUICalibrator::GUICalibratorPopupMenu::GUICalibratorPopupMenu( GUIMainWindow& app, GUISUMOAbstractView& parent, GUIGlObject& o) : GUIGLObjectPopupMenu(app, parent, o) {} GUICalibrator::GUICalibratorPopupMenu::~GUICalibratorPopupMenu() {} long GUICalibrator::GUICalibratorPopupMenu::onCmdOpenManip(FXObject*, FXSelector, void*) { static_cast<GUICalibrator*>(myObject)->openManipulator( *myApplication, *myParent); return 1; } /* ------------------------------------------------------------------------- * GUICalibrator - methods * ----------------------------------------------------------------------- */ GUICalibrator::GUICalibrator(MSCalibrator* calibrator) : GUIGlObject_AbstractAdd(GLO_CALIBRATOR, calibrator->getID()), myCalibrator(calibrator), myShowAsKMH(true) { const std::vector<MSLane*>& destLanes = calibrator->myEdge->getLanes(); const MSLane* lane = calibrator->myLane; const double pos = calibrator->myPos; for (std::vector<MSLane*>::const_iterator i = destLanes.begin(); i != destLanes.end(); ++i) { if (lane == nullptr || (*i) == lane) { const PositionVector& v = (*i)->getShape(); myFGPositions.push_back(v.positionAtOffset(pos)); myBoundary.add(v.positionAtOffset(pos)); myFGRotations.push_back(-v.rotationDegreeAtOffset(pos)); } } } GUICalibrator::~GUICalibrator() {} GUIGLObjectPopupMenu* GUICalibrator::getPopUpMenu(GUIMainWindow& app, GUISUMOAbstractView& parent) { GUIGLObjectPopupMenu* ret = new GUICalibratorPopupMenu(app, parent, *this); buildPopupHeader(ret, app); buildCenterPopupEntry(ret); //buildShowManipulatorPopupEntry(ret); buildNameCopyPopupEntry(ret); buildSelectionPopupEntry(ret); buildShowParamsPopupEntry(ret); buildPositionCopyEntry(ret, false); return ret; } GUIParameterTableWindow* GUICalibrator::getParameterWindow(GUIMainWindow& app, GUISUMOAbstractView&) { GUIParameterTableWindow* ret; auto myCurrentStateInterval = myCalibrator->myCurrentStateInterval; if (myCalibrator->isActive()) { ret = new GUIParameterTableWindow(app, *this); // add items ret->mkItem("interval start", false, STEPS2TIME(myCurrentStateInterval->begin)); ret->mkItem("interval end", false, STEPS2TIME(myCurrentStateInterval->end)); ret->mkItem("aspired flow [veh/h]", false, myCurrentStateInterval->q); ret->mkItem("aspired speed", false, myCurrentStateInterval->v); ret->mkItem("current flow [veh/h]", true, new FunctionBinding<MSCalibrator, double>(myCalibrator, &MSCalibrator::currentFlow)); ret->mkItem("current speed", true, new FunctionBinding<MSCalibrator, double>(myCalibrator, &MSCalibrator::currentSpeed)); ret->mkItem("default speed", false, myCalibrator->myDefaultSpeed); ret->mkItem("required vehicles", true, new FunctionBinding<MSCalibrator, int>(myCalibrator, &MSCalibrator::totalWished)); ret->mkItem("passed vehicles", true, new FunctionBinding<MSCalibrator, int>(myCalibrator, &MSCalibrator::passed)); ret->mkItem("inserted vehicles", true, new FunctionBinding<MSCalibrator, int>(myCalibrator, &MSCalibrator::inserted)); ret->mkItem("removed vehicles", true, new FunctionBinding<MSCalibrator, int>(myCalibrator, &MSCalibrator::removed)); ret->mkItem("cleared in jam", true, new FunctionBinding<MSCalibrator, int>(myCalibrator, &MSCalibrator::clearedInJam)); } else { ret = new GUIParameterTableWindow(app, *this); const std::string nextStart = (myCurrentStateInterval != myCalibrator->myIntervals.end() ? time2string(myCurrentStateInterval->begin) : "simulation end"); ret->mkItem("inactive until", false, nextStart); } // close building ret->closeBuilding(); return ret; } void GUICalibrator::drawGL(const GUIVisualizationSettings& s) const { glPushName(getGlID()); std::string flow = "-"; std::string speed = "-"; if (myCalibrator->isActive()) { auto myCurrentStateInterval = myCalibrator->myCurrentStateInterval; if (myCurrentStateInterval->v >= 0) { speed = toString(myCurrentStateInterval->v) + "m/s"; } if (myCurrentStateInterval->q >= 0) { flow = toString((int)myCurrentStateInterval->q) + "v/h"; } } const double exaggeration = s.addSize.getExaggeration(s, this); for (int i = 0; i < (int)myFGPositions.size(); ++i) { const Position& pos = myFGPositions[i]; double rot = myFGRotations[i]; glPushMatrix(); glTranslated(pos.x(), pos.y(), getType()); glRotated(rot, 0, 0, 1); glTranslated(0, 0, getType()); glScaled(exaggeration, exaggeration, 1); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLES); glColor3d(1, .8f, 0); // base glVertex2d(0 - 1.4, 0); glVertex2d(0 - 1.4, 6); glVertex2d(0 + 1.4, 6); glVertex2d(0 + 1.4, 0); glVertex2d(0 - 1.4, 0); glVertex2d(0 + 1.4, 6); glEnd(); // draw text if (s.scale * exaggeration >= 1.) { glTranslated(0, 0, .1); GLHelper::drawText("C", Position(0, 2), 0.1, 3, RGBColor::BLACK, 180); GLHelper::drawText(flow, Position(0, 4), 0.1, 0.7, RGBColor::BLACK, 180); GLHelper::drawText(speed, Position(0, 5), 0.1, 0.7, RGBColor::BLACK, 180); } glPopMatrix(); } drawName(getCenteringBoundary().getCenter(), s.scale, s.addName); glPopName(); } Boundary GUICalibrator::getCenteringBoundary() const { Boundary b(myBoundary); b.grow(20); return b; } GUIManipulator* GUICalibrator::openManipulator(GUIMainWindow& app, GUISUMOAbstractView&) { GUIManip_Calibrator* gui = new GUIManip_Calibrator(app, getFullName(), *this, 0, 0); gui->create(); gui->show(); return gui; } /****************************************************************************/
41.034063
150
0.604744
[ "object", "vector" ]
04f93e108373a19514933a9ef24d46f4e54407e5
2,459
cc
C++
leet_code/Evaluate_Division/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
leet_code/Evaluate_Division/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
leet_code/Evaluate_Division/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { private : const int maxLength = 20; const double init = 0.0f; const double invalid = -1.0f; public: vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { vector<vector<double> > graph; unordered_map<string, int> node; vector<double> answer; for (int i = 0; i < maxLength; ++i) { vector<double> vec(maxLength, init); graph.push_back(vec); } for (int i = 0; i < equations.size(); ++i) { if (node.find(equations[i][0]) == node.end()) { node[equations[i][0]] = node.size(); } if (node.find(equations[i][1]) == node.end()) { node[equations[i][1]] = node.size(); } int first = node[equations[i][0]], second = node[equations[i][1]]; graph[second][first] = values[i]; graph[first][second] = 1.0f / values[i]; graph[first][first] = 1.0f; graph[second][second] = 1.0f; } for (int i = 0; i < queries.size(); ++i) { if (node.find(queries[i][0]) == node.end() || node.find(queries[i][1]) == node.end()) { answer.push_back(-1.0f); continue; } int first = node[queries[i][0]], second = node[queries[i][1]]; queue<int> q; vector<bool> visit(node.size(), false); if (graph[second][first] != init) { answer.push_back(graph[second][first]); continue; } visit[second] = true; q.push(second); while (!q.empty()) { for (int size = q.size(); size > 0; --size) { int src = q.front(); q.pop(); for (int j = 0; j < visit.size(); ++j) { if ((visit[j] == false) && (graph[src][j] > init)) { visit[j] = true; q.push(j); graph[second][j] = graph[second][src] * graph[src][j]; } } } } if (graph[second][first] == init) { graph[second][first] = invalid; } answer.push_back(graph[second][first]); } return answer; } };
32.786667
125
0.431476
[ "vector" ]
ca03cd78a3fe6f42ecfe457b857b23553687b1e1
6,410
cpp
C++
component/oai-amf/src/sbi/amf_server/api/IndividualUeContextDocumentApi.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/amf_server/api/IndividualUeContextDocumentApi.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/amf_server/api/IndividualUeContextDocumentApi.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * Namf_Communication * AMF Communication Service © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ #include "IndividualUeContextDocumentApi.h" #include "Helpers.h" #include "amf_config.hpp" extern config::amf_config amf_cfg; namespace oai { namespace amf { namespace api { using namespace oai::amf::helpers; using namespace oai::amf::model; IndividualUeContextDocumentApi::IndividualUeContextDocumentApi( std::shared_ptr<Pistache::Rest::Router> rtr) { router = rtr; } void IndividualUeContextDocumentApi::init() { setupRoutes(); } void IndividualUeContextDocumentApi::setupRoutes() { using namespace Pistache::Rest; Routes::Put( *router, base + amf_cfg.sbi_api_version + "/ue-contexts/:ueContextId", Routes::bind( &IndividualUeContextDocumentApi::create_ue_context_handler, this)); Routes::Post( *router, base + amf_cfg.sbi_api_version + "/ue-contexts/:ueContextId/assign-ebi", Routes::bind( &IndividualUeContextDocumentApi::e_bi_assignment_handler, this)); Routes::Post( *router, base + amf_cfg.sbi_api_version + "/ue-contexts/:ueContextId/transfer-update", Routes::bind( &IndividualUeContextDocumentApi::registration_status_update_handler, this)); Routes::Post( *router, base + amf_cfg.sbi_api_version + "/ue-contexts/:ueContextId/release", Routes::bind( &IndividualUeContextDocumentApi::release_ue_context_handler, this)); Routes::Post( *router, base + amf_cfg.sbi_api_version + "/ue-contexts/:ueContextId/transfer", Routes::bind( &IndividualUeContextDocumentApi::u_e_context_transfer_handler, this)); // Default handler, called when a route is not found router->addCustomHandler(Routes::bind( &IndividualUeContextDocumentApi:: individual_ue_context_document_api_default_handler, this)); } void IndividualUeContextDocumentApi::create_ue_context_handler( const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Getting the path params auto ueContextId = request.param(":ueContextId").as<std::string>(); // Getting the body param Inline_object inlineObject; try { nlohmann::json::parse(request.body()).get_to(inlineObject); this->create_ue_context(ueContextId, inlineObject, response); } catch (nlohmann::detail::exception& e) { // send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); return; } catch (std::exception& e) { // send a 500 error response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); return; } } void IndividualUeContextDocumentApi::e_bi_assignment_handler( const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Getting the path params auto ueContextId = request.param(":ueContextId").as<std::string>(); // Getting the body param AssignEbiData assignEbiData; try { nlohmann::json::parse(request.body()).get_to(assignEbiData); this->e_bi_assignment(ueContextId, assignEbiData, response); } catch (nlohmann::detail::exception& e) { // send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); return; } catch (std::exception& e) { // send a 500 error response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); return; } } void IndividualUeContextDocumentApi::registration_status_update_handler( const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Getting the path params auto ueContextId = request.param(":ueContextId").as<std::string>(); // Getting the body param UeRegStatusUpdateReqData ueRegStatusUpdateReqData; try { nlohmann::json::parse(request.body()).get_to(ueRegStatusUpdateReqData); this->registration_status_update( ueContextId, ueRegStatusUpdateReqData, response); } catch (nlohmann::detail::exception& e) { // send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); return; } catch (std::exception& e) { // send a 500 error response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); return; } } void IndividualUeContextDocumentApi::release_ue_context_handler( const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Getting the path params auto ueContextId = request.param(":ueContextId").as<std::string>(); // Getting the body param UEContextRelease uEContextRelease; try { nlohmann::json::parse(request.body()).get_to(uEContextRelease); this->release_ue_context(ueContextId, uEContextRelease, response); } catch (nlohmann::detail::exception& e) { // send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); return; } catch (std::exception& e) { // send a 500 error response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); return; } } void IndividualUeContextDocumentApi::u_e_context_transfer_handler( const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { // Getting the path params auto ueContextId = request.param(":ueContextId").as<std::string>(); // Getting the body param UeContextTransferReqData ueContextTransferReqData; try { nlohmann::json::parse(request.body()).get_to(ueContextTransferReqData); this->u_e_context_transfer(ueContextId, ueContextTransferReqData, response); } catch (nlohmann::detail::exception& e) { // send a 400 error response.send(Pistache::Http::Code::Bad_Request, e.what()); return; } catch (std::exception& e) { // send a 500 error response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); return; } } void IndividualUeContextDocumentApi:: individual_ue_context_document_api_default_handler( const Pistache::Rest::Request&, Pistache::Http::ResponseWriter response) { response.send( Pistache::Http::Code::Not_Found, "The requested method does not exist"); } } // namespace api } // namespace amf } // namespace oai
31.890547
80
0.707644
[ "model" ]
ca05129df34218b64d3bfd3766558341974f8f29
2,448
cpp
C++
thirdparty/simpleuv/thirdparty/libigl/include/igl/gaussian_curvature.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
thirdparty/simpleuv/thirdparty/libigl/include/igl/gaussian_curvature.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
thirdparty/simpleuv/thirdparty/libigl/include/igl/gaussian_curvature.cpp
MelvinG24/dust3d
c4936fd900a9a48220ebb811dfeaea0effbae3ee
[ "MIT" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "gaussian_curvature.h" #include "internal_angles.h" #include "PI.h" #include <iostream> template <typename DerivedV, typename DerivedF, typename DerivedK> IGL_INLINE void igl::gaussian_curvature( const Eigen::PlainObjectBase<DerivedV>& V, const Eigen::PlainObjectBase<DerivedF>& F, Eigen::PlainObjectBase<DerivedK> & K) { using namespace Eigen; using namespace std; // internal corner angles Matrix< typename DerivedV::Scalar, DerivedF::RowsAtCompileTime, DerivedF::ColsAtCompileTime> A; internal_angles(V,F,A); K.resize(V.rows(),1); K.setConstant(V.rows(),1,2.*PI); assert(A.rows() == F.rows()); assert(A.cols() == F.cols()); assert(K.rows() == V.rows()); assert(F.maxCoeff() < V.rows()); assert(K.cols() == 1); const int Frows = F.rows(); //K_G(x_i) = (2π - ∑θj) //#ifndef IGL_GAUSSIAN_CURVATURE_OMP_MIN_VALUE //# define IGL_GAUSSIAN_CURVATURE_OMP_MIN_VALUE 1000 //#endif //#pragma omp parallel for if (Frows>IGL_GAUSSIAN_CURVATURE_OMP_MIN_VALUE) for(int f = 0;f<Frows;f++) { // throw normal at each corner for(int j = 0; j < 3;j++) { // Q: Does this need to be critical? // H: I think so, sadly. Maybe there's a way to use reduction //#pragma omp critical K(F(f,j),0) -= A(f,j); } } } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation template void igl::gaussian_curvature<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); template void igl::gaussian_curvature<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&); #endif
42.947368
375
0.660131
[ "geometry" ]
ca09dfc21a04bb7244e978529b18585583695c75
1,428
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/views/box_view.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
libs/boost/libs/geometry/doc/src/examples/views/box_view.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/geometry/doc/src/examples/views/box_view.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // QuickBook Example // Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands. // 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) //[box_view //` Shows usage of the Boost.Range compatible view on a box #include <iostream> #include <boost/geometry.hpp> int main() { typedef boost::geometry::model::box < boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> > box_type; // Define the Boost.Range compatible type: typedef boost::geometry::box_view<box_type> box_view; box_type box; boost::geometry::assign_values(box, 0, 0, 4, 4); box_view view(box); // Iterating in clockwise direction over the points of this box for (boost::range_iterator<box_view const>::type it = boost::begin(view); it != boost::end(view); ++it) { std::cout << " " << boost::geometry::dsv(*it); } std::cout << std::endl; // Note that a box_view is tagged as a ring, so supports area etc. std::cout << "Area: " << boost::geometry::area(view) << std::endl; return 0; } //] //[box_view_output /*` Output: [pre (0, 0) (0, 4) (4, 4) (4, 0) (0, 0) Area: 16 ] */ //]
24.20339
85
0.612045
[ "geometry", "model" ]