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
2e39ed99ec6d9641c1a68046d7f514b7927a4c32
8,895
cpp
C++
MIDItoScore.cpp
Yamamoto0773/MIDItoScore
93a87013ba993513b40db1121fa49cff00ddcdb5
[ "MIT" ]
5
2018-08-18T00:15:35.000Z
2019-10-09T01:10:27.000Z
MIDItoScore.cpp
Yamamoto0773/MIDItoScore
93a87013ba993513b40db1121fa49cff00ddcdb5
[ "MIT" ]
12
2019-08-06T07:11:19.000Z
2019-10-11T07:17:34.000Z
MIDItoScore.cpp
Yamamoto0773/MIDItoScore
93a87013ba993513b40db1121fa49cff00ddcdb5
[ "MIT" ]
null
null
null
#include "MIDItoScore.hpp" #include <iostream> #include <iomanip> #include <algorithm> #include <numeric> namespace miditoscore { MIDItoScore::MIDItoScore() {} MIDItoScore::~MIDItoScore() {} int MIDItoScore::writeScore(const std::string & fileName, const NoteFormat & format, const std::vector<midireader::NoteEvent> &notes) { std::ofstream scoreFile(fileName.c_str(), std::ios::app); if (!scoreFile.is_open()) return Status::E_CANNOT_OPEN_FILE; return writeScore(scoreFile, format, notes); } int MIDItoScore::writeScore(std::ostream & stream, const NoteFormat & format, const std::vector<midireader::NoteEvent> &notes) { using namespace midireader; int ret = Status::S_OK; clear(); noteFormat = format; noteAggregate.resize(format.laneAllocation.size()); std::vector<std::vector<NoteEvent>> laneNotes(format.laneAllocation.size()); // group by lane number and handle invalid notes int64_t prevTime = notes.front().time; size_t counter = 1; for (const auto& note : notes) { int laneIndex = selectNoteLane(format, note); if (laneIndex >= 0) { laneNotes.at(laneIndex).push_back(note); } if (note.type == midireader::MidiEvent::NoteOn) { // enumerize invalid notes if (laneIndex < 0) { deviatedNotes.push_back(note); ret |= Status::S_EXIST_DEVIATEDNOTES; } // check number of lanes where exists parallel notes if (format.parallelsLimit.has_value()) { if (prevTime != note.time) { counter = 1; } else { counter++; if (counter > format.parallelsLimit) { parallelNotes.push_back(note); ret |= Status::E_MANY_PARALLELS; } } prevTime = note.time; } // add exsiting channels if (std::find(channels.cbegin(), channels.cend(), note.channel) != channels.cend()) { channels.push_back(note.channel); } } } std::sort(channels.begin(), channels.end(), std::less<int>()); std::string scoreString; size_t currentBar = 1; std::vector<noteevent_const_itr_t> beginIterators(format.laneAllocation.size()); std::vector<noteevent_const_itr_t> endIterators(format.laneAllocation.size()); for (size_t i = 0; i < format.laneAllocation.size(); i++) { beginIterators.at(i) = laneNotes.at(i).cbegin(); endIterators.at(i) = laneNotes.at(i).cbegin(); } std::vector<bool> holdStarted(format.laneAllocation.size(), false); while (true) { for (size_t lane = 0; lane < format.laneAllocation.size(); lane++) { auto& beginIt = beginIterators.at(lane); auto& endIt = endIterators.at(lane); // calculate range of current bar for (endIt = beginIt; endIt != laneNotes.at(lane).cend(); endIt++) { if (endIt->bar != currentBar) break; }; // enumerate useable events to write score std::vector<ScoreNote> scoreNotes; for (auto it = beginIt; it != endIt; it++) { if (it == beginIt && holdStarted.at(lane)) { scoreNotes.emplace_back(NoteType::HOLD_END, &*it); holdStarted.at(lane) = false; // aggregate noteAggregate.at(lane).increment(scoreNotes.back().type); } else if (it->type == MidiEvent::NoteOn) { // calculate note length const math::Fraction end = (it + 1)->bar + (it + 1)->posInBar; const math::Fraction beg = it->bar + it->posInBar; const math::Fraction length = end - beg; const bool isHold = (length >= format.holdMinLength); if (isHold) { scoreNotes.emplace_back(NoteType::HOLD_BEGIN, &*it); if ((it + 1)->bar == currentBar) { // hold end is in current bar scoreNotes.emplace_back(NoteType::HOLD_END, &*(it+1)); } else { // hold end is out of current bar holdStarted.at(lane) = true; } } else { NoteType type = NoteType::HIT; if (format.exNoteDecider) { if (format.exNoteDecider(&*it)) type = NoteType::EX_HIT; else type = NoteType::HIT; } scoreNotes.emplace_back(type, &*it); } // aggregate noteAggregate.at(lane).increment(scoreNotes.back().type); } } if (scoreNotes.size() > 0) { ret |= createScoreString(scoreNotes, scoreString); if (scoreString.size() > format.allowedLineLength) { longLines.emplace_back(currentBar, format.laneAllocation.at(lane)); ret |= Status::E_EXIST_LONGLINES; } // write the score data to file. using namespace std; stream << lane << ':' << setfill('0') << setw(3) << currentBar << ':' << scoreString << endl; } // ready for next bar beginIt = endIt; } // check loop condition size_t numofEndedLanes = 0; for (size_t lane = 0; lane < format.laneAllocation.size(); lane++) { if (beginIterators.at(lane) == laneNotes.at(lane).cend()) numofEndedLanes++; } if (numofEndedLanes == format.laneAllocation.size()) { break; } currentBar++; } return ret; } int MIDItoScore::createScoreString(const std::vector<ScoreNote>& scoreNotes, std::string& scoreString) { int ret = Status::S_OK; // calculate line length of score data size_t mininalUnit = 1; for (auto it = scoreNotes.cbegin(); it != scoreNotes.cend(); it++) { mininalUnit = std::lcm(mininalUnit, it->evt->posInBar.get().d); } // create empty score data scoreString.resize(mininalUnit); for (auto it = scoreString.begin(); it != scoreString.end(); it++) *it = '0'; // add note to the score data for (auto it = scoreNotes.cbegin(); it != scoreNotes.cend(); it++) { // calculate note offset math::Fraction notePos(it->evt->posInBar); math::Fraction unit(1, mininalUnit); math::adjustDenom(notePos, unit); size_t offset = notePos.get().n; // check concurrent notes if (scoreString.at(offset) != '0') { concurrentNotes.push_back(*(it->evt)); ret |= Status::E_EXIST_CONCURRENTNOTES; } // write to buffer scoreString.at(offset) = '0' + static_cast<int>(it->type) + (it->evt->channel << 3); } return ret; } MIDItoScore::NoteAggregate MIDItoScore::getNoteAggregate(int interval) const { int pos = -1; for (size_t i = 0; i < noteFormat.laneAllocation.size(); i++) { if (noteFormat.laneAllocation.at(i) == interval) { pos = i; } } if (pos < 0) abort(); return noteAggregate.at(pos); } int MIDItoScore::selectNoteLane(const NoteFormat &format, const midireader::NoteEvent &note) { auto lane_it = std::find(format.laneAllocation.begin(), format.laneAllocation.end(), note.interval); if (lane_it == format.laneAllocation.cend()) return -1; return static_cast<int>(lane_it - format.laneAllocation.cbegin()); } void MIDItoScore::clear() { concurrentNotes.clear(); deviatedNotes.clear(); noteAggregate.clear(); parallelNotes.clear(); } bool Success(int s) { return s >= 0; }; bool Failed(int s) { return s < 0; }; }
36.908714
139
0.49511
[ "vector" ]
2e3b57554cdfe651e15e414aded9aab0ed45d4d4
12,225
cc
C++
extensions/renderer/js_extension_bindings_system.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
extensions/renderer/js_extension_bindings_system.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
extensions/renderer/js_extension_bindings_system.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/renderer/js_extension_bindings_system.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/strings/string_split.h" #include "content/public/child/v8_value_converter.h" #include "content/public/common/content_switches.h" #include "extensions/common/extension.h" #include "extensions/common/extension_api.h" #include "extensions/common/extension_urls.h" #include "extensions/common/extensions_client.h" #include "extensions/common/features/feature.h" #include "extensions/common/features/feature_provider.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/manifest_handlers/externally_connectable.h" #include "extensions/renderer/binding_generating_native_handler.h" #include "extensions/renderer/event_bindings.h" #include "extensions/renderer/ipc_message_sender.h" #include "extensions/renderer/renderer_extension_registry.h" #include "extensions/renderer/request_sender.h" #include "extensions/renderer/resource_bundle_source_map.h" #include "extensions/renderer/script_context.h" #include "gin/converter.h" #include "v8/include/v8.h" namespace extensions { namespace { // Gets |field| from |object| or creates it as an empty object if it doesn't // exist. v8::Local<v8::Object> GetOrCreateObject(const v8::Local<v8::Object>& object, const std::string& field, v8::Isolate* isolate) { v8::Local<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str()); // If the object has a callback property, it is assumed it is an unavailable // API, so it is safe to delete. This is checked before GetOrCreateObject is // called. if (object->HasRealNamedCallbackProperty(key)) { object->Delete(key); } else if (object->HasRealNamedProperty(key)) { v8::Local<v8::Value> value = object->Get(key); CHECK(value->IsObject()); return v8::Local<v8::Object>::Cast(value); } v8::Local<v8::Object> new_object = v8::Object::New(isolate); object->Set(key, new_object); return new_object; } // Returns the global value for "chrome" from |context|. If one doesn't exist // creates a new object for it. If a chrome property exists on the window // already (as in the case when a script did `window.chrome = true`), returns // an empty object. v8::Local<v8::Object> GetOrCreateChrome(ScriptContext* context) { v8::Local<v8::String> chrome_string( v8::String::NewFromUtf8(context->isolate(), "chrome")); v8::Local<v8::Object> global(context->v8_context()->Global()); v8::Local<v8::Value> chrome(global->Get(chrome_string)); if (chrome->IsUndefined()) { chrome = v8::Object::New(context->isolate()); global->Set(chrome_string, chrome); } return chrome->IsObject() ? chrome.As<v8::Object>() : v8::Local<v8::Object>(); } v8::Local<v8::Object> GetOrCreateBindObjectIfAvailable( const std::string& api_name, std::string* bind_name, ScriptContext* context) { std::vector<std::string> split = base::SplitString( api_name, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); v8::Local<v8::Object> bind_object; // Check if this API has an ancestor. If the API's ancestor is available and // the API is not available, don't install the bindings for this API. If // the API is available and its ancestor is not, delete the ancestor and // install the bindings for the API. This is to prevent loading the ancestor // API schema if it will not be needed. // // For example: // If app is available and app.window is not, just install app. // If app.window is available and app is not, delete app and install // app.window on a new object so app does not have to be loaded. const FeatureProvider* api_feature_provider = FeatureProvider::GetAPIFeatures(); std::string ancestor_name; bool only_ancestor_available = false; for (size_t i = 0; i < split.size() - 1; ++i) { ancestor_name += (i ? "." : "") + split[i]; if (api_feature_provider->GetFeature(ancestor_name) && context->GetAvailability(ancestor_name).is_available() && !context->GetAvailability(api_name).is_available()) { only_ancestor_available = true; break; } if (bind_object.IsEmpty()) { bind_object = GetOrCreateChrome(context); if (bind_object.IsEmpty()) return v8::Local<v8::Object>(); } bind_object = GetOrCreateObject(bind_object, split[i], context->isolate()); } if (only_ancestor_available) return v8::Local<v8::Object>(); DCHECK(bind_name); *bind_name = split.back(); return bind_object.IsEmpty() ? GetOrCreateChrome(context) : bind_object; } // Creates the event bindings if necessary for the given |context|. void MaybeCreateEventBindings(ScriptContext* context) { // chrome.Event is part of the public API (although undocumented). Make it // lazily evalulate to Event from event_bindings.js. For extensions only // though, not all webpages! if (!context->extension()) return; v8::Local<v8::Object> chrome = GetOrCreateChrome(context); if (chrome.IsEmpty()) return; context->module_system()->SetLazyField(chrome, "Event", kEventBindings, "Event"); } } // namespace JsExtensionBindingsSystem::JsExtensionBindingsSystem( ResourceBundleSourceMap* source_map, std::unique_ptr<IPCMessageSender> ipc_message_sender) : source_map_(source_map), ipc_message_sender_(std::move(ipc_message_sender)), request_sender_( base::MakeUnique<RequestSender>(ipc_message_sender_.get())) {} JsExtensionBindingsSystem::~JsExtensionBindingsSystem() {} void JsExtensionBindingsSystem::DidCreateScriptContext(ScriptContext* context) { MaybeCreateEventBindings(context); } void JsExtensionBindingsSystem::WillReleaseScriptContext( ScriptContext* context) { // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|. // In fact |request_sender_| should really be owned by ScriptContext. request_sender_->InvalidateSource(context); } void JsExtensionBindingsSystem::UpdateBindingsForContext( ScriptContext* context) { v8::HandleScope handle_scope(context->isolate()); v8::Context::Scope context_scope(context->v8_context()); // TODO(kalman): Make the bindings registration have zero overhead then run // the same code regardless of context type. switch (context->context_type()) { case Feature::UNSPECIFIED_CONTEXT: case Feature::WEB_PAGE_CONTEXT: case Feature::BLESSED_WEB_PAGE_CONTEXT: // Hard-code registration of any APIs that are exposed to webpage-like // contexts, because it's too expensive to run the full bindings code. // All of the same permission checks will still apply. for (const char* feature_name : kWebAvailableFeatures) { if (context->GetAvailability(feature_name).is_available()) RegisterBinding(feature_name, feature_name, context); } if (IsRuntimeAvailableToContext(context)) RegisterBinding("runtime", "runtime", context); break; case Feature::SERVICE_WORKER_CONTEXT: DCHECK(ExtensionsClient::Get() ->ExtensionAPIEnabledInExtensionServiceWorkers()); // Intentional fallthrough. case Feature::BLESSED_EXTENSION_CONTEXT: case Feature::UNBLESSED_EXTENSION_CONTEXT: case Feature::CONTENT_SCRIPT_CONTEXT: case Feature::LOCK_SCREEN_EXTENSION_CONTEXT: case Feature::WEBUI_CONTEXT: { // Extension context; iterate through all the APIs and bind the available // ones. const FeatureProvider* api_feature_provider = FeatureProvider::GetAPIFeatures(); for (const auto& map_entry : api_feature_provider->GetAllFeatures()) { // Internal APIs are included via require(api_name) from internal code // rather than chrome[api_name]. if (map_entry.second->IsInternal()) continue; // If this API has a parent feature (and isn't marked 'noparent'), // then this must be a function or event, so we should not register. if (api_feature_provider->GetParent(map_entry.second.get()) != nullptr) continue; // Skip chrome.test if this isn't a test. if (map_entry.first == "test" && !base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kTestType)) { continue; } if (context->IsAnyFeatureAvailableToContext( *map_entry.second, CheckAliasStatus::NOT_ALLOWED)) { // Check if the API feature is indeed an alias. If it is, the API // should use source API bindings as its own. const std::string& source = map_entry.second->source(); // TODO(lazyboy): RegisterBinding() uses |source_map_|, any thread // safety issue? RegisterBinding(source.empty() ? map_entry.first : source, map_entry.first, context); } } break; } } } void JsExtensionBindingsSystem::HandleResponse(int request_id, bool success, const base::ListValue& response, const std::string& error) { request_sender_->HandleResponse(request_id, success, response, error); ipc_message_sender_->SendOnRequestResponseReceivedIPC(request_id); } RequestSender* JsExtensionBindingsSystem::GetRequestSender() { return request_sender_.get(); } IPCMessageSender* JsExtensionBindingsSystem::GetIPCMessageSender() { return ipc_message_sender_.get(); } void JsExtensionBindingsSystem::DispatchEventInContext( const std::string& event_name, const base::ListValue* event_args, const EventFilteringInfo* filtering_info, ScriptContext* context) { EventBindings::DispatchEventInContext(event_name, event_args, filtering_info, context); } bool JsExtensionBindingsSystem::HasEventListenerInContext( const std::string& event_name, ScriptContext* context) { return EventBindings::HasListener(context, event_name); } void JsExtensionBindingsSystem::RegisterBinding( const std::string& api_name, const std::string& api_bind_name, ScriptContext* context) { std::string bind_name; v8::Local<v8::Object> bind_object = GetOrCreateBindObjectIfAvailable(api_bind_name, &bind_name, context); // Empty if the bind object failed to be created, probably because the // extension overrode chrome with a non-object, e.g. window.chrome = true. if (bind_object.IsEmpty()) return; v8::Local<v8::String> v8_bind_name = v8::String::NewFromUtf8(context->isolate(), bind_name.c_str()); if (bind_object->HasRealNamedProperty(v8_bind_name)) { // The bind object may already have the property if the API has been // registered before (or if the extension has put something there already, // but, whatevs). // // In the former case, we need to re-register the bindings for the APIs // which the extension now has permissions for (if any), but not touch any // others so that we don't destroy state such as event listeners. // // TODO(kalman): Only register available APIs to make this all moot. if (bind_object->HasRealNamedCallbackProperty(v8_bind_name)) return; // lazy binding still there, nothing to do if (bind_object->Get(v8_bind_name)->IsObject()) return; // binding has already been fully installed } ModuleSystem* module_system = context->module_system(); if (!source_map_->Contains(api_name)) { module_system->RegisterNativeHandler( api_bind_name, std::unique_ptr<NativeHandler>( new BindingGeneratingNativeHandler(context, api_name, "binding"))); module_system->SetNativeLazyField(bind_object, bind_name, api_bind_name, "binding"); } else { module_system->SetLazyField(bind_object, bind_name, api_name, "binding"); } } } // namespace extensions
40.213816
80
0.697096
[ "object", "vector" ]
2e3f165286f17abf632be22c86e5579ed85921ac
14,784
cpp
C++
src/Simulation/EXIT/EXIT.cpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2022-02-17T08:47:47.000Z
2022-02-17T08:47:47.000Z
src/Simulation/EXIT/EXIT.cpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
null
null
null
src/Simulation/EXIT/EXIT.cpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2021-11-24T01:54:41.000Z
2021-11-24T01:54:41.000Z
#if !defined(AFF3CT_8BIT_PREC) && !defined(AFF3CT_16BIT_PREC) #include <functional> #include <algorithm> #include <iostream> #include <cstdint> #include <sstream> #include <chrono> #include <limits> #include <string> #include <cmath> #include "Tools/Exception/exception.hpp" #include "Tools/Display/rang_format/rang_format.h" #include "Tools/Display/Statistics/Statistics.hpp" #include "Tools/general_utils.h" #include "Tools/Math/utils.h" #include "Tools/Display/Reporter/EXIT/Reporter_EXIT.hpp" #include "Tools/Display/Reporter/Noise/Reporter_noise.hpp" #include "Tools/Display/Reporter/Throughput/Reporter_throughput.hpp" #include "Simulation/EXIT/EXIT.hpp" using namespace aff3ct; using namespace aff3ct::simulation; template <typename B, typename R> EXIT<B,R> ::EXIT(const factory::EXIT::parameters& params_EXIT) : Simulation (params_EXIT), params_EXIT(params_EXIT), sig_a ((R)0 ) { #ifdef AFF3CT_MPI std::clog << rang::tag::warning << "This simulation is not MPI ready, the same computations will be launched " "on each MPI processes." << std::endl; #endif if (params_EXIT.noise->type != "EBN0" && params_EXIT.noise->type != "ESN0") { std::stringstream message; message << "Wrong noise type, must be gaussian noise EBN0 or ESN0 ('params_EXIT.noise->type' = " << params_EXIT.noise->type << ")."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } if (params_EXIT.n_threads > 1) throw tools::invalid_argument(__FILE__, __LINE__, __func__, "EXIT simu does not support the multi-threading."); this->add_module("source" , params_EXIT.n_threads); this->add_module("codec" , params_EXIT.n_threads); this->add_module("encoder" , params_EXIT.n_threads); this->add_module("decoder" , params_EXIT.n_threads); this->add_module("modem" , params_EXIT.n_threads); this->add_module("modem_a" , params_EXIT.n_threads); this->add_module("channel" , params_EXIT.n_threads); this->add_module("channel_a", params_EXIT.n_threads); this->add_module("monitor" , params_EXIT.n_threads); this->monitor = this->build_monitor(); this->set_module("monitor", 0, this->monitor); auto reporter_noise = new tools::Reporter_noise<R>(this->noise); reporters.push_back(std::unique_ptr<tools::Reporter_noise<R>>(reporter_noise)); auto reporter_EXIT = new tools::Reporter_EXIT<B,R>(*this->monitor, this->noise_a); reporters.push_back(std::unique_ptr<tools::Reporter_EXIT<B,R>>(reporter_EXIT)); auto reporter_thr = new tools::Reporter_throughput<uint64_t>(*this->monitor); reporters.push_back(std::unique_ptr<tools::Reporter_throughput<uint64_t>>(reporter_thr)); } template <typename B, typename R> void EXIT<B,R> ::_build_communication_chain() { const auto N_mod = params_EXIT.mdm->N_mod; const auto K_mod = factory::Modem::get_buffer_size_after_modulation(params_EXIT.mdm->type, params_EXIT.cdc->K, params_EXIT.mdm->bps, params_EXIT.mdm->cpm_upf, params_EXIT.mdm->cpm_L); // build the objects source = build_source ( ); codec = build_codec ( ); modem = build_modem ( ); modem_a = build_modem_a ( ); channel = build_channel (N_mod); channel_a = build_channel_a(K_mod); terminal = build_terminal ( ); this->set_module("source" , 0, source); this->set_module("codec" , 0, codec); this->set_module("encoder" , 0, codec->get_encoder()); this->set_module("decoder" , 0, codec->get_decoder_siso()); this->set_module("modem" , 0, modem); this->set_module("modem_a" , 0, modem_a); this->set_module("channel" , 0, channel); this->set_module("channel_a", 0, channel_a); this->monitor->add_handler_measure(std::bind(&module::Codec_SISO<B,R>::reset, codec.get())); if (codec->get_decoder_siso()->get_n_frames() > 1) throw tools::runtime_error(__FILE__, __LINE__, __func__, "The inter frame is not supported."); } template <typename B, typename R> void EXIT<B,R> ::launch() { this->terminal = this->build_terminal(); // allocate and build all the communication chain to generate EXIT chart this->build_communication_chain(); this->sockets_binding(); // for each channel NOISE to be simulated for (unsigned noise_idx = 0; noise_idx < params_EXIT.noise->range.size(); noise_idx ++) { R ebn0 = params_EXIT.noise->range[noise_idx]; // For EXIT simulation, NOISE is considered as Es/N0 const R bit_rate = 1.; R esn0 = tools::ebn0_to_esn0 (ebn0, bit_rate, params_EXIT.mdm->bps); R sigma = tools::esn0_to_sigma(esn0, params_EXIT.mdm->cpm_upf); this->noise.set_noise(sigma, ebn0, esn0); channel ->set_noise(this->noise); modem ->set_noise(this->noise); codec ->set_noise(this->noise); // for each "a" standard deviation (sig_a) to be simulated using namespace module; for (unsigned sig_a_idx = 0; sig_a_idx < params_EXIT.sig_a_range.size(); sig_a_idx ++) { sig_a = params_EXIT.sig_a_range[sig_a_idx]; if (sig_a == 0.f) // if sig_a = 0, La_K2 = 0 { auto &mdm = *this->modem_a; if (params_EXIT.chn->type.find("RAYLEIGH") != std::string::npos) { auto mdm_data = (uint8_t*)(mdm[mdm::sck::demodulate_wg::Y_N2].get_dataptr()); auto mdm_bytes = mdm[mdm::sck::demodulate_wg::Y_N2].get_databytes(); std::fill(mdm_data, mdm_data + mdm_bytes, 0); } else { auto mdm_data = (uint8_t*)(mdm[mdm::sck::demodulate::Y_N2].get_dataptr()); auto mdm_bytes = mdm[mdm::sck::demodulate::Y_N2].get_databytes(); std::fill(mdm_data, mdm_data + mdm_bytes, 0); } this->noise_a.set_noise(std::numeric_limits<R>::infinity()); } else { const R bit_rate = 1.; auto sig_a_2 = (R)2. / sig_a; R sig_a_esn0 = tools::sigma_to_esn0(sig_a_2, params_EXIT.mdm->cpm_upf); R sig_a_ebn0 = tools::esn0_to_ebn0 (sig_a_esn0, bit_rate, params_EXIT.mdm->bps); this->noise_a.set_noise(sig_a_2, sig_a_ebn0, sig_a_esn0); channel_a->set_noise(this->noise_a); modem_a ->set_noise(this->noise_a); } if ((!params_EXIT.ter->disabled && noise_idx == 0 && sig_a_idx == 0 && !params_EXIT.debug) || (params_EXIT.statistics && !params_EXIT.debug)) terminal->legend(std::cout); // start the terminal to display BER/FER results if (!params_EXIT.ter->disabled && params_EXIT.ter->frequency != std::chrono::nanoseconds(0) && !params_EXIT.debug) this->terminal->start_temp_report(params_EXIT.ter->frequency); this->simulation_loop(); if (!params_EXIT.ter->disabled) { if (params_EXIT.debug) terminal->legend(std::cout); terminal->final_report(std::cout); if (params_EXIT.statistics) { std::vector<std::vector<const module::Module*>> mod_vec; for (auto &vm : modules) { std::vector<const module::Module*> sub_mod_vec; for (auto& m : vm.second) sub_mod_vec.push_back(m); mod_vec.push_back(std::move(sub_mod_vec)); } std::cout << "#" << std::endl; tools::Stats::show(mod_vec, true, std::cout); std::cout << "#" << std::endl; } } this->monitor->reset(); for (auto &m : modules) for (auto& mm : m.second) if (mm != nullptr) for (auto &t : mm->tasks) t->reset_stats(); if (tools::Terminal::is_over()) break; } if (tools::Terminal::is_over()) break; } } template <typename B, typename R> void EXIT<B,R> ::sockets_binding() { auto &src = *this->source; auto &cdc = *this->codec; auto &enc = *this->codec->get_encoder(); auto &dec = *this->codec->get_decoder_siso(); auto &mdm = *this->modem; auto &mda = *this->modem_a; auto &chn = *this->channel; auto &cha = *this->channel_a; auto &mnt = *this->monitor; using namespace module; mnt[mnt::sck::check_mutual_info::bits](src[src::sck::generate::U_K]); mda[mdm::sck::modulate ::X_N1](src[src::sck::generate::U_K]); enc[enc::sck::encode ::U_K ](src[src::sck::generate::U_K]); mdm[mdm::sck::modulate ::X_N1](enc[enc::sck::encode ::X_N]); // Rayleigh channel if (params_EXIT.chn->type.find("RAYLEIGH") != std::string::npos) { cha[chn::sck::add_noise_wg ::X_N ](mda[mdm::sck::modulate ::X_N2]); mda[mdm::sck::demodulate_wg::H_N ](cha[chn::sck::add_noise_wg::H_N ]); mda[mdm::sck::demodulate_wg::Y_N1](cha[chn::sck::add_noise_wg::Y_N ]); } else // additive channel (AWGN, USER, NO) { cha[chn::sck::add_noise ::X_N ](mda[mdm::sck::modulate ::X_N2]); mda[mdm::sck::demodulate::Y_N1](cha[chn::sck::add_noise::Y_N ]); } // Rayleigh channel if (params_EXIT.chn->type.find("RAYLEIGH") != std::string::npos) { mnt[mnt::sck::check_mutual_info::llrs_a](mda[mdm::sck::demodulate_wg::Y_N2]); chn[chn::sck::add_noise_wg ::X_N ](mdm[mdm::sck::modulate ::X_N2]); mdm[mdm::sck::demodulate_wg ::H_N ](chn[chn::sck::add_noise_wg ::H_N ]); mdm[mdm::sck::demodulate_wg ::Y_N1 ](chn[chn::sck::add_noise_wg ::Y_N ]); cdc[cdc::sck::add_sys_ext ::ext ](mda[mdm::sck::demodulate_wg::Y_N2]); cdc[cdc::sck::add_sys_ext ::Y_N ](mdm[mdm::sck::demodulate_wg::Y_N2]); dec[dec::sck::decode_siso ::Y_N1 ](mdm[mdm::sck::demodulate_wg::Y_N2]); } else // additive channel (AWGN, USER, NO) { mnt[mnt::sck::check_mutual_info::llrs_a](mda[mdm::sck::demodulate::Y_N2]); chn[chn::sck::add_noise ::X_N ](mdm[mdm::sck::modulate ::X_N2]); mdm[mdm::sck::demodulate ::Y_N1 ](chn[chn::sck::add_noise ::Y_N ]); cdc[cdc::sck::add_sys_ext ::ext ](mda[mdm::sck::demodulate::Y_N2]); cdc[cdc::sck::add_sys_ext ::Y_N ](mdm[mdm::sck::demodulate::Y_N2]); dec[dec::sck::decode_siso ::Y_N1 ](mdm[mdm::sck::demodulate::Y_N2]); } cdc[cdc::sck::extract_sys_llr ::Y_N ](dec[dec::sck::decode_siso ::Y_N2]); mnt[mnt::sck::check_mutual_info::llrs_e](cdc[cdc::sck::extract_sys_llr::Y_K ]); } template <typename B, typename R> void EXIT<B,R> ::simulation_loop() { auto &source = *this->source; auto &codec = *this->codec; auto &encoder = *this->codec->get_encoder(); auto &decoder = *this->codec->get_decoder_siso(); auto &modem = *this->modem; auto &modem_a = *this->modem_a; auto &channel = *this->channel; auto &channel_a = *this->channel_a; auto &monitor = *this->monitor; using namespace module; while (!monitor.n_trials_achieved()) { if (params_EXIT.debug) { if (!monitor[mnt::tsk::check_mutual_info].get_n_calls()) std::cout << "#" << std::endl; auto fid = monitor[mnt::tsk::check_mutual_info].get_n_calls(); std::cout << "# -------------------------------" << std::endl; std::cout << "# New communication (n°" << fid << ")" << std::endl; std::cout << "# -------------------------------" << std::endl; std::cout << "#" << std::endl; } source [src::tsk::generate].exec(); modem_a[mdm::tsk::modulate].exec(); encoder[enc::tsk::encode ].exec(); modem [mdm::tsk::modulate].exec(); //if sig_a = 0, La_K = 0, no noise to add if (sig_a != (R)0.) { // Rayleigh channel if (params_EXIT.chn->type.find("RAYLEIGH") != std::string::npos) { channel_a[chn::tsk::add_noise_wg ].exec(); modem_a [mdm::tsk::demodulate_wg].exec(); } else // additive channel (AWGN, USER, NO) { channel_a[chn::tsk::add_noise ].exec(); modem_a [mdm::tsk::demodulate].exec(); } } // Rayleigh channel if (params_EXIT.chn->type.find("RAYLEIGH") != std::string::npos) { channel[chn::tsk::add_noise_wg ].exec(); modem [mdm::tsk::demodulate_wg].exec(); } else // additive channel (AWGN, USER, NO) { channel[chn::tsk::add_noise ].exec(); modem [mdm::tsk::demodulate].exec(); } codec [cdc::tsk::add_sys_ext ].exec(); decoder[dec::tsk::decode_siso ].exec(); codec [cdc::tsk::extract_sys_llr ].exec(); monitor[mnt::tsk::check_mutual_info].exec(); } } template <typename B, typename R> std::unique_ptr<module::Source<B>> EXIT<B,R> ::build_source() { return std::unique_ptr<module::Source<B>>(params_EXIT.src->template build<B>()); } template <typename B, typename R> std::unique_ptr<module::Codec_SISO<B,R>> EXIT<B,R> ::build_codec() { return std::unique_ptr<module::Codec_SISO<B,R>>(params_EXIT.cdc->template build<B,R>()); } template <typename B, typename R> std::unique_ptr<module::Modem<B,R,R>> EXIT<B,R> ::build_modem() { return std::unique_ptr<module::Modem<B,R,R>>(params_EXIT.mdm->template build<B,R>()); } template <typename B, typename R> std::unique_ptr<module::Modem<B,R>> EXIT<B,R> ::build_modem_a() { std::unique_ptr<factory::Modem::parameters> mdm_params(params_EXIT.mdm->clone()); mdm_params->N = params_EXIT.cdc->K; return std::unique_ptr<module::Modem<B,R>>(mdm_params->template build<B,R>()); } template <typename B, typename R> std::unique_ptr<module::Channel<R>> EXIT<B,R> ::build_channel(const int size) { return std::unique_ptr<module::Channel<R>>(params_EXIT.chn->template build<R>()); } template <typename B, typename R> std::unique_ptr<module::Channel<R>> EXIT<B,R> ::build_channel_a(const int size) { std::unique_ptr<factory::Channel::parameters> chn_params(params_EXIT.chn->clone()); chn_params->N = factory::Modem::get_buffer_size_after_modulation(params_EXIT.mdm->type, params_EXIT.cdc->K, params_EXIT.mdm->bps, params_EXIT.mdm->cpm_upf, params_EXIT.mdm->cpm_L); return std::unique_ptr<module::Channel<R>>(chn_params->template build<R>()); } template <typename B, typename R> std::unique_ptr<module::Monitor_EXIT<B,R>> EXIT<B,R> ::build_monitor() { return std::unique_ptr<module::Monitor_EXIT<B,R>>(params_EXIT.mnt->template build<B,R>()); } template <typename B, typename R> std::unique_ptr<tools::Terminal> EXIT<B,R> ::build_terminal() { return std::unique_ptr<tools::Terminal>(params_EXIT.ter->build(this->reporters)); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef AFF3CT_MULTI_PREC template class aff3ct::simulation::EXIT<B_32,R_32>; template class aff3ct::simulation::EXIT<B_64,R_64>; #else template class aff3ct::simulation::EXIT<B,R>; #endif // ==================================================================================== explicit template instantiation #endif
34.704225
119
0.632238
[ "vector" ]
2e3f77f7c0e476fdffc3c665a918998d00fb2485
11,644
cpp
C++
src/atoms_md.cpp
1mingfei/mapp4py
b72a90b4ab8984cf40d90944df60505e1a3f6a49
[ "MIT" ]
null
null
null
src/atoms_md.cpp
1mingfei/mapp4py
b72a90b4ab8984cf40d90944df60505e1a3f6a49
[ "MIT" ]
null
null
null
src/atoms_md.cpp
1mingfei/mapp4py
b72a90b4ab8984cf40d90944df60505e1a3f6a49
[ "MIT" ]
null
null
null
#include "atoms_md.h" #include "xmath.h" /*-------------------------------------------- --------------------------------------------*/ AtomsMD::AtomsMD(MPI_Comm& world): Atoms(world), S_pe{DESIG2(__dim__,__dim__,NAN)}, pe(NAN) { elem=new Vec<elem_type>(this,1,"elem"); x_d=new Vec<type0>(this,__dim__,"x_d"); x_d->empty(0.0); } /*-------------------------------------------- --------------------------------------------*/ AtomsMD::~AtomsMD() { delete x_d; delete elem; } /*-------------------------------------------- --------------------------------------------*/ AtomsMD& AtomsMD::operator=(const Atoms& r) { elements=r.elements; comm=r.comm; natms_lcl=r.natms_lcl; natms_ph=r.natms_ph; natms=r.natms; step=r.step; max_cut=r.max_cut; kB=r.kB; hP=r.hP; vol=r.vol; memcpy(depth_inv,r.depth_inv,__dim__*sizeof(type0)); memcpy(__h,r.__h,__nvoigt__*sizeof(type0)); memcpy(__b,r.__b,__nvoigt__*sizeof(type0)); memcpy(&H[0][0],&r.H[0][0],__dim__*__dim__*sizeof(type0)); memcpy(&B[0][0],&r.B[0][0],__dim__*__dim__*sizeof(type0)); for(int i=0;i<nvecs;i++) if(!vecs[i]->is_empty()) vecs[i]->resize(natms_lcl); memcpy(x->begin(),r.x->begin(),natms_lcl*__dim__*sizeof(type0)); memcpy(id->begin(),r.id->begin(),natms_lcl*sizeof(unsigned int)); return* this; } /*-------------------------------------------- x2s --------------------------------------------*/ void AtomsMD::x_d2s_d_dump() { Algebra::X2S_NOCORR<__dim__>(__b,natms,x_d->begin_dump()); } /*-------------------------------------------- --------------------------------------------*/ #include "random.h" #include "elements.h" #include "xmath.h" void AtomsMD::create_T(type0 T,int seed) { x_d->fill(); Random rand(seed+comm_rank); type0* __x_d=x_d->begin(); type0* m=elements.masses; elem_type* __elem=elem->begin(); type0 fac; if(!x_dof->is_empty()) { bool* __dof=x_dof->begin(); for(int i=0;i<natms_lcl;i++) { fac=sqrt(kB*T/m[*__elem]); Algebra::Do<__dim__>::func([&fac,&rand,&__x_d,__dof,this](const int i){if(__dof[i]) __x_d[i]=rand.gaussian()*fac;}); __x_d+=__dim__; __dof+=__dim__; ++__elem; } } else { for(int i=0;i<natms_lcl;i++) { fac=sqrt(kB*T/m[*__elem]); Algebra::Do<__dim__>::func([&fac,&rand,&__x_d,this](const int i){__x_d[i]=rand.gaussian()*fac;}); __x_d+=__dim__; ++__elem; } } } /*-------------------------------------------- --------------------------------------------*/ int AtomsMD::count_elem(elem_type ielem) { elem_type* __elem=elem->begin(); int n_lcl=0; for(int i=0;i<natms_lcl;i++) if(__elem[i]==ielem) n_lcl++; int n=0; MPI_Allreduce(&n_lcl,&n,1,Vec<int>::MPI_T,MPI_SUM,world); return n; } /*-------------------------------------------- --------------------------------------------*/ void AtomsMD::DO(PyObject* op) { class Func_x { public: void operator()(type0*,type0*) {}; }; Func_x func_x; VecPy<type0,Func_x> x_vec_py(x,func_x); class Func_x_d { public: void operator()(type0*,type0*) {}; }; Func_x_d func_x_d; VecPy<type0,Func_x_d> x_d_vec_py(x_d,func_x_d); class Func_id { public: void operator()(unsigned int* old_val,unsigned int* new_val) { if(*old_val!=*new_val) throw std::string("id of atoms cannot be changed"); }; }; Func_id func_id; VecPy<unsigned int,Func_id> id_vec_py(id,func_id); class Func_elem { public: elem_type nelem; Func_elem(elem_type __nelem):nelem(__nelem){} void operator()(elem_type* old_val,elem_type* new_val) { if(*new_val>=nelem) throw std::string("elem of atoms should be less than ")+Print::to_string(static_cast<int>(nelem)); }; }; Func_elem func_elem(elements.__nelems); VecPy<elem_type,Func_elem> elem_vec_py(elem,func_elem); class Func_dof { public: void operator()(bool*,bool*) { }; }; Func_dof func_dof; VecPy<bool,Func_dof> dof_vec_py(x_dof,func_dof); try { VecPyFunc::Do(this,op,id_vec_py,x_vec_py,x_d_vec_py,elem_vec_py,dof_vec_py); } catch(std::string& err_msg) { throw err_msg; } if(x_vec_py.inc) this->reset_domain(); } /*------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------------*/ #include "ff_styles.h" #include "import_styles.h" PyObject* AtomsMD::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds) { Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0)); PyObject* self=reinterpret_cast<PyObject*>(__self); return self; } /*-------------------------------------------- --------------------------------------------*/ int AtomsMD::__init__(PyObject* self,PyObject* args,PyObject* kwds) { FuncAPI<> func("__init__"); if(func(args,kwds)==-1) return -1; Object* __self=reinterpret_cast<Object*>(self); __self->atoms=NULL; __self->ff=NULL; return 0; } /*-------------------------------------------- --------------------------------------------*/ PyObject* AtomsMD::__alloc__(PyTypeObject* type,Py_ssize_t) { Object* __self=new Object; Py_TYPE(__self)=type; Py_REFCNT(__self)=1; __self->atoms=NULL; __self->ff=NULL; return reinterpret_cast<PyObject*>(__self); } /*-------------------------------------------- --------------------------------------------*/ void AtomsMD::__dealloc__(PyObject* self) { Object* __self=reinterpret_cast<Object*>(self); delete __self->ff; delete __self->atoms; delete __self; } /*--------------------------------------------*/ PyTypeObject AtomsMD::TypeObject ={PyObject_HEAD_INIT(NULL)}; /*--------------------------------------------*/ int AtomsMD::setup_tp() { TypeObject.tp_name="mapp.md.atoms"; TypeObject.tp_doc="container class"; TypeObject.tp_flags=Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; TypeObject.tp_basicsize=sizeof(Object); TypeObject.tp_new=__new__; TypeObject.tp_init=__init__; TypeObject.tp_alloc=__alloc__; TypeObject.tp_dealloc=__dealloc__; setup_tp_getset(); TypeObject.tp_getset=getset; setup_tp_methods(); TypeObject.tp_methods=methods; int ichk=PyType_Ready(&TypeObject); if(ichk<0) return ichk; Py_INCREF(&TypeObject); return ichk; } /*--------------------------------------------*/ PyGetSetDef AtomsMD::getset[]=EmptyPyGetSetDef(15); /*--------------------------------------------*/ void AtomsMD::setup_tp_getset() { getset_step(getset[0]); getset_hP(getset[1]); getset_kB(getset[2]); getset_H(getset[3]); getset_B(getset[4]); getset_vol(getset[5]); getset_elems(getset[6]); getset_skin(getset[7]); getset_comm_rank(getset[8]); getset_comm_size(getset[9]); getset_comm_coords(getset[10]); getset_comm_dims(getset[11]); getset_pe(getset[12]); getset_S_pe(getset[13]); } /*-------------------------------------------- --------------------------------------------*/ void AtomsMD::getset_S_pe(PyGetSetDef& getset) { getset.name=(char*)"S_pe"; getset.doc=(char*)R"---( (double) potential energy stress Potential energy part of virial stress )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<type0[__dim__][__dim__]>::build(reinterpret_cast<Object*>(self)->atoms->S_pe); }; getset.set=[](PyObject* self,PyObject* val,void*)->int { PyErr_SetString(PyExc_TypeError,"readonly attribute"); return -1; }; } /*-------------------------------------------- --------------------------------------------*/ void AtomsMD::getset_pe(PyGetSetDef& getset) { getset.name=(char*)"pe"; getset.doc=(char*)R"---( (double) potential energy Potential energy )---"; getset.get=[](PyObject* self,void*)->PyObject* { return var<type0>::build(reinterpret_cast<Object*>(self)->atoms->pe); }; getset.set=[](PyObject* self,PyObject* val,void*)->int { PyErr_SetString(PyExc_TypeError,"readonly attribute"); return -1; }; } /*--------------------------------------------*/ #ifdef POTFIT PyMethodDef AtomsMD::methods[]=EmptyPyMethodDef(16); #else PyMethodDef AtomsMD::methods[]=EmptyPyMethodDef(13); #endif /*--------------------------------------------*/ void AtomsMD::setup_tp_methods() { ml_do(methods[0]); ml_mul(methods[1]); ml_strain(methods[2]); ml_create_temp(methods[3]); ml_add_elem(methods[4]); ForceFieldLJ::ml_new(methods[5]); ForceFieldEAM::ml_new(methods[6],methods[7],methods[8]); ForceFieldFS::ml_new(methods[9]); ForceFieldEAMFunc::ml_new(methods[10]); ImportCFGMD::ml_import(methods[11]); #ifdef POTFIT ForceFieldEAMFit::ml_new(methods[12]); ForceFieldEAMFitO::ml_new(methods[13]); ForceFieldEAMPotFitAckOgata::ml_new(methods[14]); #endif } /*-------------------------------------------- --------------------------------------------*/ void AtomsMD::ml_create_temp(PyMethodDef& tp_method) { tp_method.ml_flags=METH_VARARGS | METH_KEYWORDS; tp_method.ml_name="create_temp"; tp_method.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { AtomsMD::Object* __self=reinterpret_cast<AtomsMD::Object*>(self); if(std::isnan(__self->atoms->kB)) { PyErr_SetString(PyExc_TypeError,"boltzmann constant should be set prior to create_temp"); return NULL; } FuncAPI<type0,int> f("create_temp",{"temp","seed"}); f.logics<0>()[0]=VLogics("gt",0.0); f.logics<1>()[0]=VLogics("gt",0); if(f(args,kwds)) return NULL; __self->atoms->create_T(f.val<0>(),f.val<1>()); Py_RETURN_NONE; }); tp_method.ml_doc=R"---( create_temp(temp,seed) Create a random velcity field Parameters ---------- temp : double Temperature seed : int random seed Returns ------- None )---"; } /*-------------------------------------------- --------------------------------------------*/ void AtomsMD::ml_add_elem(PyMethodDef& tp_method) { tp_method.ml_flags=METH_VARARGS | METH_KEYWORDS; tp_method.ml_name="add_elem"; tp_method.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { FuncAPI<std::string,type0> f("add_elem",{"elem","mass"}); f.logics<1>()[0]=VLogics("gt",0.0); if(f(args,kwds)) return NULL; AtomsMD::Object* __self=reinterpret_cast<AtomsMD::Object*>(self); __self->atoms->elements.add_type(f.val<1>(),f.val<0>().c_str()); Py_RETURN_NONE; }); tp_method.ml_doc=R"---( add_elem(elem,mass) Add a new element to the system Parameters ---------- elem : string New element seed : double Mass of the element Returns ------- None )---"; }
27.462264
135
0.513913
[ "object" ]
2e41b314d601c76be0fe1619477bdbe644a4a26b
22,029
cc
C++
modules/perception/obstacle/lidar/visualizer/opengl_visualizer/glfw_viewer.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
22
2018-10-10T14:46:32.000Z
2022-02-28T12:43:43.000Z
modules/perception/obstacle/lidar/visualizer/opengl_visualizer/glfw_viewer.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
5
2020-06-13T00:36:33.000Z
2022-02-10T17:50:43.000Z
modules/perception/obstacle/lidar/visualizer/opengl_visualizer/glfw_viewer.cc
BaiduXLab/apollo
2764e934b6d0da1342be781447348288ac84c5e9
[ "Apache-2.0" ]
12
2018-12-24T02:17:19.000Z
2021-12-06T01:54:09.000Z
/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/glfw_viewer.h" #include <cmath> #include <fstream> #include <iomanip> #include <vector> #include "pcl/io/pcd_io.h" #include "modules/common/log.h" #include "modules/perception/obstacle/base/object.h" #include "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/arc_ball.h" #include "modules/perception/obstacle/lidar/visualizer/opengl_visualizer/frame_content.h" namespace apollo { namespace perception { #define BUFFER_OFFSET(offset) (reinterpret_cast<GLvoid *>(offset)) GLFWViewer::GLFWViewer() { init_ = false; window_ = nullptr; pers_camera_ = nullptr; forward_dir_ = Eigen::Vector3d::Zero(); scn_center_ = Eigen::Vector3d::Zero(); bg_color_ = Eigen::Vector3d::Zero(); mode_mat_ = Eigen::Matrix4d::Identity(); view_mat_ = Eigen::Matrix4d::Identity(); win_width_ = 800; win_height_ = 600; mouse_prev_x_ = 0; mouse_prev_y_ = 0; show_cloud_ = true; show_cloud_state_ = 0; show_velocity_ = true; show_direction_ = false; show_polygon_ = false; } GLFWViewer::~GLFWViewer() { Close(); if (pers_camera_) delete pers_camera_; } bool GLFWViewer::Initialize() { AINFO << "GLFWViewer::initialize()" << std::endl; if (init_) { AINFO << " GLFWViewer is already initialized !" << std::endl; return false; } if (!WindowInit()) { AINFO << " Failed to initialize the window !" << std::endl; return false; } if (!CameraInit()) { AINFO << " Failed to initialize the camera !" << std::endl; return false; } if (!OpenglInit()) { AINFO << " Failed to initialize opengl !" << std::endl; return false; } init_ = true; show_cloud_ = 1; show_velocity_ = 1; show_polygon_ = 0; return true; } void GLFWViewer::Spin() { while (!glfwWindowShouldClose(window_)) { glfwPollEvents(); Render(); glfwSwapBuffers(window_); } glfwDestroyWindow(window_); } void GLFWViewer::SpinOnce() { glfwPollEvents(); Render(); glfwSwapBuffers(window_); } void GLFWViewer::Close() { glfwTerminate(); } void GLFWViewer::SetSize(int w, int h) { win_width_ = w; win_height_ = h; } void GLFWViewer::SetCameraPara(Eigen::Vector3d i_position, Eigen::Vector3d i_scn_center, Eigen::Vector3d i_up_vector) { pers_camera_->SetPosition(i_position); pers_camera_->LookAt(i_scn_center); pers_camera_->SetUpDirection(i_up_vector); view_mat_ = pers_camera_->GetViewMat(); scn_center_ = i_scn_center; } bool GLFWViewer::WindowInit() { if (!glfwInit()) { AERROR << "Failed to initialize glfw !\n"; return false; } window_ = glfwCreateWindow(win_width_, win_height_, "opengl_visualizer", nullptr, nullptr); if (window_ == nullptr) { AERROR << "Failed to create glfw window!\n"; glfwTerminate(); return false; } glfwMakeContextCurrent(window_); glfwSwapInterval(1); glfwSetWindowUserPointer(window_, this); // set callback functions glfwSetFramebufferSizeCallback(window_, FramebufferSizeCallback); glfwSetKeyCallback(window_, KeyCallback); glfwSetMouseButtonCallback(window_, MouseButtonCallback); glfwSetCursorPosCallback(window_, MouseCursorPositionCallback); glfwSetScrollCallback(window_, MouseScrollCallback); glfwShowWindow(window_); return true; } bool GLFWViewer::CameraInit() { // perspective cameras pers_camera_ = new Camera; pers_camera_->SetScreenWidthHeight(win_width_, win_height_); pers_camera_->SetFov(45.0); pers_camera_->SetPosition(Eigen::Vector3d(0, 0, -30)); return true; } bool GLFWViewer::OpenglInit() { glClearColor(bg_color_(0), bg_color_(1), bg_color_(2), 0.0); glClearDepth(1.0f); glShadeModel(GL_SMOOTH); glDepthFunc(GL_LEQUAL); // lighting GLfloat mat_shininess[] = {20.0}; GLfloat light_position[] = {1.0, -1.0, 1.0, 0.0}; GLfloat lmodel_ambient[] = {.5, .5, .5, 1.0}; glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); // glew if (glewInit() != GLEW_OK) { AERROR << "Failed to initialize glew !"; exit(EXIT_FAILURE); } // allocation of vbo // point cloud { GLfloat cloud_colors[kPoint_Num_Per_Cloud_VAO_][3]; GLuint cloud_indices[kPoint_Num_Per_Cloud_VAO_]; for (int i = 0; i < kPoint_Num_Per_Cloud_VAO_; i++) { cloud_colors[i][0] = 0.7; cloud_colors[i][1] = 0.7; cloud_colors[i][2] = 0.7; cloud_indices[i] = GLuint(i); } glGenVertexArrays(kCloud_VAO_Num_, cloud_VAO_buf_ids_); for (int i = 0; i < kCloud_VAO_Num_; i++) { glBindVertexArray(cloud_VAO_buf_ids_[i]); glGenBuffers(static_cast<int>(VBO_Type::NUM_VBO_TYPE), cloud_VBO_buf_ids_[i]); glBindBuffer( GL_ARRAY_BUFFER, cloud_VBO_buf_ids_[i][static_cast<int>(VBO_Type::VBO_VERTICES)]); glBufferData(GL_ARRAY_BUFFER, sizeof(cloud_verts_), cloud_verts_, GL_STREAM_DRAW); glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer( GL_ARRAY_BUFFER, cloud_VBO_buf_ids_[i][static_cast<int>(VBO_Type::VBO_COLORS)]); glBufferData(GL_ARRAY_BUFFER, sizeof(cloud_colors), cloud_colors, GL_STREAM_DRAW); glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, cloud_VBO_buf_ids_[i][static_cast<int>(VBO_Type::VBO_ELEMENTS)]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cloud_indices), cloud_indices, GL_STREAM_DRAW); } } // circle { GLfloat circle_verts[kPoint_Num_Per_Circle_VAO_][3]; GLfloat circle_colors[kPoint_Num_Per_Circle_VAO_][3]; GLuint circle_indices[kPoint_Num_Per_Circle_VAO_]; for (int i = 0; i < kPoint_Num_Per_Circle_VAO_; ++i) { circle_verts[i][2] = -1.0; circle_colors[i][0] = 0.0; circle_colors[i][1] = 0.0; circle_colors[i][2] = 0.9; circle_indices[i] = GLuint(i); } float ang_interv = 2 * M_PI / static_cast<float>(kPoint_Num_Per_Circle_VAO_); glGenVertexArrays(kCircle_VAO_Num_, circle_VAO_buf_ids_); for (int vao = 0; vao < kCircle_VAO_Num_; ++vao) { for (int i = 0; i < kPoint_Num_Per_Circle_VAO_; ++i) { float theta = i * ang_interv; circle_verts[i][0] = 20 * (vao + 1) * cos(theta); circle_verts[i][1] = 20 * (vao + 1) * sin(theta); } glBindVertexArray(circle_VAO_buf_ids_[vao]); glGenBuffers(static_cast<int>(VBO_Type::NUM_VBO_TYPE), circle_VBO_buf_ids_[vao]); glBindBuffer( GL_ARRAY_BUFFER, circle_VBO_buf_ids_[vao][static_cast<int>(VBO_Type::VBO_VERTICES)]); glBufferData(GL_ARRAY_BUFFER, sizeof(circle_verts), circle_verts, GL_STATIC_DRAW); glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer( GL_ARRAY_BUFFER, circle_VBO_buf_ids_[vao][static_cast<int>(VBO_Type::VBO_COLORS)]); glBufferData(GL_ARRAY_BUFFER, sizeof(circle_colors), circle_colors, GL_STATIC_DRAW); glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, circle_VBO_buf_ids_[vao][static_cast<int>(VBO_Type::VBO_ELEMENTS)]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(circle_indices), circle_indices, GL_STATIC_DRAW); } } return true; } void GLFWViewer::PreDraw() { Eigen::Matrix4d e_proj_mat = pers_camera_->GetProjectionMat(); // column major GLdouble proj_mat[16] = { e_proj_mat(0, 0), e_proj_mat(1, 0), e_proj_mat(2, 0), e_proj_mat(3, 0), e_proj_mat(0, 1), e_proj_mat(1, 1), e_proj_mat(2, 1), e_proj_mat(3, 1), e_proj_mat(0, 2), e_proj_mat(1, 2), e_proj_mat(2, 2), e_proj_mat(3, 2), e_proj_mat(0, 3), e_proj_mat(1, 3), e_proj_mat(2, 3), e_proj_mat(3, 3)}; GLdouble mode_mat[16] = { mode_mat_(0, 0), mode_mat_(1, 0), mode_mat_(2, 0), mode_mat_(3, 0), mode_mat_(0, 1), mode_mat_(1, 1), mode_mat_(2, 1), mode_mat_(3, 1), mode_mat_(0, 2), mode_mat_(1, 2), mode_mat_(2, 2), mode_mat_(3, 2), mode_mat_(0, 3), mode_mat_(1, 3), mode_mat_(2, 3), mode_mat_(3, 3)}; GLdouble view_mat[16] = { view_mat_(0, 0), view_mat_(1, 0), view_mat_(2, 0), view_mat_(3, 0), view_mat_(0, 1), view_mat_(1, 1), view_mat_(2, 1), view_mat_(3, 1), view_mat_(0, 2), view_mat_(1, 2), view_mat_(2, 2), view_mat_(3, 2), view_mat_(0, 3), view_mat_(1, 3), view_mat_(2, 3), view_mat_(3, 3)}; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMultMatrixd(proj_mat); glMatrixMode(GL_MODELVIEW); glLoadMatrixd(mode_mat); glMultMatrixd(view_mat); GLfloat light_position[] = {1.0, -1.0, 1.0, 0.0}; glLightfv(GL_LIGHT0, GL_POSITION, light_position); } void GLFWViewer::Render() { glClear(GL_COLOR_BUFFER_BIT); PreDraw(); if (show_cloud_) DrawCloud(); DrawObstacles(); DrawCircle(); DrawCarForwardDir(); } void GLFWViewer::DrawCloud() { pcl_util::PointCloudPtr cloud; pcl_util::PointCloudPtr roi_cloud; if (show_cloud_state_ == 0) { // only show original point cloud cloud = frame_content_.GetCloud(); } else if (show_cloud_state_ == 1) { // show roi roi_cloud = frame_content_.GetRoiCloud(); } else { // show both cloud = frame_content_.GetCloud(); roi_cloud = frame_content_.GetRoiCloud(); } // draw original point cloud if (cloud && !cloud->points.empty()) { glPointSize(1); int count = 0; int p_num = 0; int vao_num = (cloud->points.size() / kPoint_Num_Per_Cloud_VAO_) + 1; for (int vao = 0; vao < vao_num; vao++) { for (p_num = 0; p_num < kPoint_Num_Per_Cloud_VAO_; ++p_num) { cloud_verts_[p_num][0] = cloud->points[count].x; cloud_verts_[p_num][1] = cloud->points[count].y; cloud_verts_[p_num][2] = cloud->points[count].z; count++; if (count >= static_cast<int>(cloud->points.size())) { break; } } glBindVertexArray(cloud_VAO_buf_ids_[vao]); glBindBuffer( GL_ARRAY_BUFFER, cloud_VBO_buf_ids_[vao][static_cast<int>(VBO_Type::VBO_VERTICES)]); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(cloud_verts_), cloud_verts_); glDrawElements(GL_POINTS, p_num, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glBindVertexArray(0); if (count >= static_cast<int>(cloud->points.size())) { break; } } if (count < static_cast<int>(cloud->points.size())) { AINFO << "VAO_num * VBO_num < cloud->points.size()"; } } // draw roi point cloud if (roi_cloud && !roi_cloud->points.empty()) { glPointSize(3); glColor3f(0, 0.8, 0); glBegin(GL_POINTS); for (const auto &point : roi_cloud->points) { glVertex3f(point.x, point.y, point.z); } glEnd(); } } void GLFWViewer::DrawCircle() { Eigen::Matrix4d v2w_pose = frame_content_.GetPoseV2w(); GLdouble mat[16] = { v2w_pose(0, 0), v2w_pose(1, 0), v2w_pose(2, 0), v2w_pose(3, 0), v2w_pose(0, 1), v2w_pose(1, 1), v2w_pose(2, 1), v2w_pose(3, 1), v2w_pose(0, 2), v2w_pose(1, 2), v2w_pose(2, 2), v2w_pose(3, 2), v2w_pose(0, 3), v2w_pose(1, 3), v2w_pose(2, 3), v2w_pose(3, 3)}; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixd(mat); int vao = 0; for (vao = 0; vao < kCircle_VAO_Num_; vao++) { glBindVertexArray(circle_VAO_buf_ids_[vao]); glDrawElements(GL_LINE_LOOP, kPoint_Num_Per_Circle_VAO_, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); glBindVertexArray(0); } glPopMatrix(); } void GLFWViewer::DrawCarForwardDir() { glColor3f(1.0, 0.5, 0.17); glLineWidth(5); glBegin(GL_LINES); Eigen::Vector3d forward_vp = scn_center_ + forward_dir_ * 10; glVertex3f(scn_center_(0), scn_center_(1), scn_center_(2)); glVertex3f(forward_vp(0), forward_vp(1), forward_vp(2)); glEnd(); glLineWidth(1); } void GLFWViewer::DrawObstacle(const std::shared_ptr<Object> obj, bool show_cloud, bool show_polygon, bool show_velocity, bool show_direction) { float type_color[3] = {0, 0, 0}; // TODO(All): modify GetClassColor params GetClassColor(static_cast<int>(obj->type), type_color); if (show_polygon) { double h = obj->height; glColor3f(type_color[0], type_color[1], type_color[2]); glBegin(GL_LINE_LOOP); for (auto point : obj->polygon.points) { glVertex3f(point.x, point.y, point.z); } glEnd(); glBegin(GL_LINE_LOOP); for (auto point : obj->polygon.points) { glVertex3f(point.x, point.y, point.z + h); } glEnd(); glBegin(GL_LINES); for (auto point : obj->polygon.points) { glVertex3f(point.x, point.y, point.z); glVertex3f(point.x, point.y, point.z + h); } glEnd(); } else { glColor3f(type_color[0], type_color[1], type_color[2]); Eigen::Vector3d dir(cos(obj->theta), sin(obj->theta), 0); Eigen::Vector3d odir(-dir[1], dir[0], 0); Eigen::Vector3d bottom_quad[4]; double half_l = obj->length / 2; double half_w = obj->width / 2; double h = obj->height; bottom_quad[0] = obj->center - dir * half_l - odir * half_w; bottom_quad[1] = obj->center + dir * half_l - odir * half_w; bottom_quad[2] = obj->center + dir * half_l + odir * half_w; bottom_quad[3] = obj->center - dir * half_l + odir * half_w; DrawOffsetVolumn(bottom_quad, h, 4); } if (show_velocity) { glColor3f(1, 0, 0); const Eigen::Vector3d &center = obj->center; const Eigen::Vector3d &velocity = obj->velocity; Eigen::Vector3d dir(cos(obj->theta), sin(obj->theta), 0); Eigen::Vector3d start_point; if (dir.dot(velocity) < 0) { start_point = center - dir * (obj->length / 2); } else { start_point = center + dir * (obj->length / 2); } Eigen::Vector3d end_point = start_point + velocity; glBegin(GL_LINES); glVertex3f(start_point[0], start_point[1], start_point[2]); glVertex3f(end_point[0], end_point[1], end_point[2]); glEnd(); } if (show_direction) { glColor3f(0, 0, 1); const Eigen::Vector3d &center = obj->center; Eigen::Vector3d dir(cos(obj->theta), sin(obj->theta), 0); Eigen::Vector3d odir(-dir[1], dir[0], 0); Eigen::Vector3d start_point = center + dir * (obj->length / 2) + odir * (obj->width / 2); Eigen::Vector3d end_point = start_point + dir * 3; glBegin(GL_LINES); glVertex3f(start_point[0], start_point[1], start_point[2]); glVertex3f(end_point[0], end_point[1], end_point[2]); glEnd(); } } void GLFWViewer::DrawObstacles() { std::vector<std::shared_ptr<Object>> tracked_objects = frame_content_.GetTrackedObjects(); for (std::size_t i = 0; i < tracked_objects.size(); i++) { DrawObstacle(tracked_objects[i], true, show_polygon_, show_velocity_, show_direction_); } } void GLFWViewer::DrawOffsetVolumn(Eigen::Vector3d *polygon_points, double h, int polygon_size) { if (polygon_points == nullptr) { return; } glBegin(GL_LINE_LOOP); for (int i = 0; i < polygon_size; i++) { glVertex3d(polygon_points[i][0], polygon_points[i][1], polygon_points[i][2]); } glEnd(); glBegin(GL_LINE_LOOP); for (int i = 0; i < polygon_size; i++) { glVertex3d(polygon_points[i][0], polygon_points[i][1], polygon_points[i][2] + h); } glEnd(); glBegin(GL_LINES); for (int i = 0; i < polygon_size; i++) { glVertex3d(polygon_points[i][0], polygon_points[i][1], polygon_points[i][2]); glVertex3d(polygon_points[i][0], polygon_points[i][1], polygon_points[i][2] + h); } glEnd(); } void GLFWViewer::GetClassColor(int cls, float rgb[3]) { switch (cls) { case 0: rgb[0] = 0.5; rgb[1] = 0; rgb[2] = 1; // purple break; case 1: rgb[0] = 0; rgb[1] = 1; rgb[2] = 1; // cryan break; case 2: rgb[0] = 1; rgb[1] = 1; rgb[2] = 0; // yellow break; case 3: rgb[0] = 1; rgb[1] = 0.5; rgb[2] = 0.5; // red break; case 4: rgb[0] = 0; rgb[1] = 0; rgb[2] = 1; // blue break; case 5: rgb[0] = 0; rgb[1] = 1; rgb[2] = 0; // green break; case 6: rgb[0] = 1; rgb[1] = 0.5; rgb[2] = 0; // orange break; case 7: rgb[0] = 1; rgb[1] = 0; rgb[2] = 0; // red break; default: rgb[0] = 1; rgb[1] = 1; rgb[2] = 1; // white break; } } /************************callback functions************************/ void GLFWViewer::FramebufferSizeCallback(GLFWwindow *window, int width, int height) { void *user_data = glfwGetWindowUserPointer(window); if (user_data == nullptr) return; GLFWViewer *vis = static_cast<GLFWViewer *>(user_data); vis->ResizeFramebuffer(width, height); } void GLFWViewer::KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { void *user_data = glfwGetWindowUserPointer(window); if (user_data == nullptr) return; if (action == GLFW_PRESS) { GLFWViewer *vis = static_cast<GLFWViewer *>(user_data); AINFO << "key_value: " << key; vis->Keyboard(key); } } void GLFWViewer::MouseButtonCallback(GLFWwindow *window, int button, int action, int mods) {} void GLFWViewer::MouseCursorPositionCallback(GLFWwindow *window, double xpos, double ypos) { void *user_data = glfwGetWindowUserPointer(window); if (user_data == nullptr) return; GLFWViewer *vis = static_cast<GLFWViewer *>(user_data); vis->MouseMove(xpos, ypos); } void GLFWViewer::MouseScrollCallback(GLFWwindow *window, double xoffset, double yoffset) { void *user_data = glfwGetWindowUserPointer(window); if (user_data == nullptr) return; GLFWViewer *vis = static_cast<GLFWViewer *>(user_data); vis->MouseWheel(yoffset); } void GLFWViewer::ErrorCallback(int error, const char *description) { AINFO << "ERROR - " << error << " " << description; } /************************callback assistants************************/ /*void GLFWViewer::resize_window(int width, int height){ }*/ void GLFWViewer::ResizeFramebuffer(int width, int height) { glViewport(0, 0, width, height); win_width_ = width; win_height_ = height; } void GLFWViewer::MouseMove(double xpos, double ypos) { int state_left = glfwGetMouseButton(window_, GLFW_MOUSE_BUTTON_LEFT); int state_right = glfwGetMouseButton(window_, GLFW_MOUSE_BUTTON_RIGHT); int x_delta = xpos - mouse_prev_x_; int y_delta = ypos - mouse_prev_y_; if (state_left == GLFW_PRESS) { Eigen::Vector3d obj_cen_screen = pers_camera_->PointOnScreen(scn_center_); Eigen::Quaterniond rot = ArcBall::RotateByMouse( static_cast<double>(mouse_prev_x_), static_cast<double>(mouse_prev_y_), xpos, ypos, obj_cen_screen(0), obj_cen_screen(1), static_cast<double>(win_width_), static_cast<double>(win_height_)); Eigen::Matrix3d rot_mat = rot.inverse().toRotationMatrix(); Eigen::Vector3d scn_center = scn_center_; Eigen::Vector4d scn_center_tmp(scn_center(0), scn_center(1), scn_center(2), 1); scn_center_tmp = mode_mat_ * view_mat_ * scn_center_tmp; scn_center = scn_center_tmp.head(3); Eigen::Vector3d r_multi_scn_center = rot_mat * scn_center; Eigen::Vector3d t = scn_center - r_multi_scn_center; Eigen::Matrix4d cur_mat = Eigen::Matrix4d::Identity(); cur_mat.topLeftCorner(3, 3) = rot_mat; cur_mat.topRightCorner(3, 1) = t; mode_mat_ = cur_mat * mode_mat_; } else if (state_right == GLFW_PRESS) { mode_mat_(0, 3) += 0.1 * x_delta; mode_mat_(1, 3) -= 0.1 * y_delta; } mouse_prev_x_ = xpos; mouse_prev_y_ = ypos; } void GLFWViewer::MouseWheel(double delta) { mode_mat_(2, 3) -= delta; } void GLFWViewer::Reset() { mode_mat_ = Eigen::Matrix4d::Identity(); } void GLFWViewer::Keyboard(int key) { switch (key) { case GLFW_KEY_R: // 'R' Reset(); break; case GLFW_KEY_P: // 'P' show_polygon_ = !show_polygon_; break; case GLFW_KEY_V: // 'V' show_velocity_ = !show_velocity_; break; case GLFW_KEY_D: // d show_direction_ = !show_direction_; break; case GLFW_KEY_S: // 'S' show_cloud_state_ = (show_cloud_state_ + 1) % 3; break; } } } // namespace perception } // namespace apollo
31.335704
89
0.637614
[ "render", "object", "vector" ]
2e4ee494f01f36ee710bdf063b28ed1f2f96c45a
3,286
hpp
C++
Camera.hpp
blakeanedved/shade-engine
75a9b30b569efd55374a25c23c07f4cbafa711a7
[ "MIT" ]
1
2019-08-18T19:17:23.000Z
2019-08-18T19:17:23.000Z
Camera.hpp
blakeanedved/Vex3D
75a9b30b569efd55374a25c23c07f4cbafa711a7
[ "MIT" ]
null
null
null
Camera.hpp
blakeanedved/Vex3D
75a9b30b569efd55374a25c23c07f4cbafa711a7
[ "MIT" ]
null
null
null
#pragma once #include "GameObject.hpp" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> namespace Vex { class Camera : public GameObject { private: glm::mat4 model; glm::mat4 view; glm::mat4 projection; glm::mat4 MVP; float FoV; float aspectRatio; public: Camera(std::string name, glm::vec3 position, glm::vec3 rotation, float FoV, float aspectRatio); virtual ~Camera(); auto GetMVP() -> glm::mat4; auto SetPosition(glm::vec3 position) -> void; auto SetRotation(glm::vec3 rotation) -> void; auto SetRotation(glm::vec3 rotation, glm::vec3 origin) -> void; auto SetChildPosition(glm::vec3 position) -> void; auto Move(glm::vec3 adjustment) -> void; auto Rotate(glm::vec3 rotation) -> void; auto Rotate(glm::vec3 rotation, glm::vec3 origin) -> void; private: auto update_model() -> void; auto update_view() -> void; auto update_projection() -> void; auto internal_render() -> void; }; std::shared_ptr<Vex::Camera> ActiveCamera; } Vex::Camera::Camera(std::string name, glm::vec3 position, glm::vec3 rotation, float FoV, float aspectRatio) : GameObject(name, position, rotation) { this->FoV = FoV; this->aspectRatio = aspectRatio; this->update_projection(); this->update_view(); this->update_model(); this->MVP = this->projection * this->view * this->model; } Vex::Camera::~Camera() { } auto Vex::Camera::GetMVP() -> glm::mat4 { return this->MVP; } auto Vex::Camera::SetPosition(glm::vec3 position) -> void { GameObject::SetPosition(position); this->update_view(); } auto Vex::Camera::SetRotation(glm::vec3 rotation) -> void { GameObject::SetRotation(rotation); this->update_view(); } auto Vex::Camera::SetRotation(glm::vec3 rotation, glm::vec3 origin) -> void { GameObject::SetRotation(rotation, origin); this->update_view(); }; auto Vex::Camera::SetChildPosition(glm::vec3 position) -> void { GameObject::SetChildPosition(position); this->update_view(); }; auto Vex::Camera::Move(glm::vec3 adjustment) -> void { GameObject::Move(adjustment); this->update_view(); }; auto Vex::Camera::Rotate(glm::vec3 rotation) -> void { GameObject::Rotate(rotation); this->update_view(); }; auto Vex::Camera::Rotate(glm::vec3 rotation, glm::vec3 origin) -> void { GameObject::Rotate(rotation, origin); this->update_view(); }; auto Vex::Camera::update_model() -> void { this->model = glm::mat4(1.0f); this->MVP = this->projection * this->view * this->model; } auto Vex::Camera::update_view() -> void { this->view = glm::mat4(1.0f); this->view = glm::rotate(this->view, this->rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); this->view = glm::rotate(this->view, this->rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); this->view = glm::rotate(this->view, this->rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); this->view = glm::translate(this->view, -this->position); this->MVP = this->projection * this->view * this->model; }; auto Vex::Camera::update_projection() -> void { this->projection = glm::perspective( glm::radians(this->FoV), this->aspectRatio, 0.1f, 100.0f ); this->MVP = this->projection * this->view * this->model; } auto Vex::Camera::internal_render() -> void {} // Pretty sure this has to be here just to override the pure virual GameObject::internal_render()
26.288
148
0.678332
[ "model" ]
2e5429b006ed402660b97e1108d0d5121ee8b232
2,692
cpp
C++
trview.app/Camera/FreeCamera.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
20
2018-10-17T02:00:03.000Z
2022-03-24T09:37:20.000Z
trview.app/Camera/FreeCamera.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
396
2018-07-22T16:11:47.000Z
2022-03-29T11:57:03.000Z
trview.app/Camera/FreeCamera.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
8
2018-07-25T21:31:06.000Z
2021-11-01T14:36:26.000Z
#include "FreeCamera.h" namespace trview { using namespace DirectX::SimpleMath; FreeCamera::FreeCamera(const Size& size) : Camera(size) { _rotation_yaw = 0.0f; _rotation_pitch = 0.0f; } void FreeCamera::move(const Vector3& movement, float elapsed) { update_acceleration(movement, elapsed); // Scale the movement by elapsed time to keep it framerate independent - also apply // camera movement acceleration if present. auto scaled_movement = movement * elapsed * _acceleration; if (_projection_mode == ProjectionMode::Orthographic) { auto rotate = Matrix::CreateFromYawPitchRoll(_rotation_yaw, _rotation_pitch, 0); _position += Vector3::Transform(Vector3(scaled_movement.x, -scaled_movement.z, 0), rotate); } else { if (_alignment == Alignment::Camera) { auto rotate = Matrix::CreateFromYawPitchRoll(_rotation_yaw, _rotation_pitch, 0); _position += Vector3(0, scaled_movement.y, 0) + Vector3::Transform(Vector3(scaled_movement.x, 0, scaled_movement.z), rotate); } else if (_alignment == Alignment::Axis) { _position += scaled_movement; } } if (scaled_movement.LengthSquared() > 0) { calculate_view_matrix(); } } void FreeCamera::set_alignment(Alignment alignment) { _alignment = alignment; calculate_projection_matrix(); } void FreeCamera::set_position(const Vector3& position) { _position = position; calculate_view_matrix(); } void FreeCamera::set_acceleration_settings(bool enabled, float rate) { _acceleration_enabled = enabled; _acceleration_rate = rate; if (!_acceleration_enabled) { _acceleration = 1.0f; } } void FreeCamera::update_vectors() { const auto rotation = Matrix::CreateFromYawPitchRoll(_rotation_yaw, _rotation_pitch, 0); _forward = Vector3::Transform(Vector3::Backward, rotation); _up = Vector3::Transform(Vector3::Down, rotation); calculate_view_matrix(); } void FreeCamera::update_acceleration(const Vector3& movement, float elapsed) { if (!_acceleration_enabled) { _acceleration = 1.0f; } else if (movement.LengthSquared() == 0) { _acceleration = 0.0f; } else { _acceleration = std::min(_acceleration + std::max(_acceleration_rate, 0.1f) * elapsed, 1.0f); } } }
28.946237
141
0.596582
[ "transform" ]
2e558eabc84905a350fd1d750356831fceab9f42
9,164
cpp
C++
src/diardi/diardi.cpp
ahmyi/Scala
c1dc14c62da5abb90948b708fe5b74c429764b7c
[ "MIT" ]
35
2019-10-31T10:18:19.000Z
2022-03-21T10:18:19.000Z
src/diardi/diardi.cpp
Cryptonoz/Scala
b98b44057f37ca59e4be01b05aa93d43c8bfcbe8
[ "MIT" ]
28
2019-10-07T16:51:53.000Z
2021-12-20T03:35:50.000Z
src/diardi/diardi.cpp
Cryptonoz/Scala
b98b44057f37ca59e4be01b05aa93d43c8bfcbe8
[ "MIT" ]
18
2019-08-21T08:06:40.000Z
2022-03-11T19:38:34.000Z
//Copyright (c) 2014-2019, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 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 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 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "diardi.h" /* This is here because the epee libraries seem to have a problem with cloudflare workers */ #include "HTTPRequest.hpp" using namespace epee; #undef SCALA_DEFAULT_LOG_CATEGORY #define SCALA_DEFAULT_LOG_CATEGORY "diardi" namespace cryptonote { const std::vector<std::string> diardi::offlineSeedList = {"62.171.149.67:11811", "164.68.117.160:11811"}; const std::vector<std::string> diardi::offlineBansList = {}; const std::string diardi::seedsName = "seeds.scalaproject.io"; const std::string diardi::bansName = "bans.scalaproject.io"; const std::string diardi:: staticCheckpointsName = "static-checkpoints.scalaproject.io"; const std::string diardi::fallBackHistorical = "http://fallback-historical-checkpoints.scalaproject.io/"; const std::string diardi::localGatewayIPNS = "http://127.0.0.1:11815/ipns/"; const std::string diardi::localGatewayIPFS = "http://127.0.0.1:11815/ipfs/"; const std::string diardi::errorDat = "error:error"; const std::vector<std::string> diardi::notaryNodes = { "alpha.scalaproject.io", "beta.scalaproject.io", "gamma.scalaproject.io", "delta.scalaproject.io", "epsilon.scalaproject.io", "zeta.scalaproject.io", "eta.scalaproject.io", "theta.scalaproject.io", "iota.scalaproject.io", "kappa.scalaproject.io", "lambda.scalaproject.io", "pi.scalaproject.io", "sigma.scalaproject.io", "phi.scalaproject.io", "omega.scalaproject.io", "zed.scalaproject.io" }; /* Initialize for epee HTTP client */ epee::net_utils::http::http_simple_client client; epee::net_utils::http::url_content uC; //--------------------------------------------------------------------------- diardi::diardi() {} //--------------------------------------------------------------------------- bool diardi::getRequest(std::string& requestUrl, std::string& response){ if (!epee::net_utils::parse_url(requestUrl, uC)){ LOG_PRINT_L0("Failed to parse URL for diardi node " << requestUrl); return false; } if (uC.host.empty()){ LOG_PRINT_L0("Failed to determine address from URL " << requestUrl); return false; } epee::net_utils::ssl_support_t ssl_requirement = uC.schema == "https" ? epee::net_utils::ssl_support_t::e_ssl_support_enabled : epee::net_utils::ssl_support_t::e_ssl_support_disabled; uint16_t port = uC.port ? uC.port : ssl_requirement == epee::net_utils::ssl_support_t::e_ssl_support_enabled ? 443 : 80; client.set_server(uC.host, std::to_string(port), boost::none, ssl_requirement); epee::net_utils::http::fields_list fields; const epee::net_utils::http::http_response_info *info = NULL; if (!client.invoke_get(uC.uri, std::chrono::seconds(20), "", &info, fields)){ return false; }else{ response = std::string(info->m_body); return true; } } //--------------------------------------------------------------------------- CheckPointListType diardi::getHistoricalCheckpoints(bool ipfsDisabled){ CheckPointListType m; std::string requestUrl = (ipfsDisabled == true) ? (fallBackHistorical) : (localGatewayIPNS + staticCheckpointsName); std::string response; bool tryRequest; if(ipfsDisabled == false){ tryRequest = getRequest(requestUrl, response); }else{ try{ http::Request request{requestUrl}; const auto responseH = request.send("GET"); response = std::string{responseH.body.begin(), responseH.body.end()}; tryRequest = true; }catch(...){ tryRequest = false; } } if(!tryRequest){ LOG_PRINT_L0("Unable to get static list of checkpoints from IPFS"); }else{ try{ Document checkpointsJson; checkpointsJson.Parse(response.c_str()); for (rapidjson::Value::ConstValueIterator itr = checkpointsJson.Begin(); itr != checkpointsJson.End(); ++itr) { if (itr->HasMember("height")) { uint64_t height = (*itr)["height"].GetInt64(); std::stringstream hD; hD << (*itr)["hash"].GetString() << ":" << (*itr)["c_difficulty"].GetString(); m.insert({height, hD.str()}); } } } catch(...){ m.insert({0, "3fa5c8976978f52ad7d8fc3663e902a229a232ef987fc11ca99628366652ba99:0x1"}); } } return m; } //--------------------------------------------------------------------------- std::string diardi::getMajority(std::vector<std::string> &checkpoints) { uint64_t majIndex = 0; uint64_t count = 1; uint64_t vecSize = checkpoints.size(); for(uint64_t i = 1; i < vecSize; i++) { if(checkpoints[i]==checkpoints[majIndex]) { count++; } else { count--; } if(count == 0) { majIndex = i; count = 1; } } return checkpoints[majIndex]; } //--------------------------------------------------------------------------- bool diardi::checkMajority(std::vector<std::string> &checkpoints, std::string& checkpoint) { uint64_t count = 0; uint64_t vecSize = checkpoints.size(); for(uint64_t i = 0; i < vecSize; i++) { if(checkpoints[i] == checkpoint) { count++; } } if(count > (vecSize/2)){ return true; } else { return false; } } //--------------------------------------------------------------------------- bool diardi::getLatestCheckpoint(std::string& checkpoint) { std::vector<std::string> responses; for (auto &node: diardi::notaryNodes) { std::string requestUrl = (localGatewayIPNS + node + "/latestCheckpoint.json"); std::string response; bool tryRequest = getRequest(requestUrl, response); if(!tryRequest){ return false; }else{ responses.push_back(response); } } std::string mFcheckpoint = getMajority(responses); bool isMajority = checkMajority(responses, mFcheckpoint); if(isMajority){ LOG_PRINT_L1("Most prevalent checkpoint is " << mFcheckpoint); checkpoint = mFcheckpoint; return true; } LOG_PRINT_L0("Skip checkpointing, since no checkpoint was prevalent enough"); return false; } //--------------------------------------------------------------------------- }
40.192982
192
0.544849
[ "vector" ]
2e5fa35990b25d2e29fc640146bb2fdbe43f6784
732
cpp
C++
third_party/WebKit/Source/modules/webgl/WebGLSharedPlatform3DObject.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/webgl/WebGLSharedPlatform3DObject.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/modules/webgl/WebGLSharedPlatform3DObject.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/webgl/WebGLSharedPlatform3DObject.h" #include "modules/webgl/WebGLRenderingContextBase.h" namespace blink { WebGLSharedPlatform3DObject::WebGLSharedPlatform3DObject( WebGLRenderingContextBase* ctx) : WebGLSharedObject(ctx), object_(0) {} void WebGLSharedPlatform3DObject::SetObject(GLuint object) { // object==0 && deleted==false indicating an uninitialized state; DCHECK(!object_); DCHECK(!IsDeleted()); object_ = object; } bool WebGLSharedPlatform3DObject::HasObject() const { return object_ != 0; } } // namespace blink
27.111111
73
0.759563
[ "object" ]
2e6484cdeed686b1730e1ce864aea2328d424961
8,375
cpp
C++
term3_project11_path_planning/src/main.cpp
SID-TWRI/self-driving-car
c9ab88576d9f2fff4c198978984159b1976416c9
[ "MIT" ]
null
null
null
term3_project11_path_planning/src/main.cpp
SID-TWRI/self-driving-car
c9ab88576d9f2fff4c198978984159b1976416c9
[ "MIT" ]
null
null
null
term3_project11_path_planning/src/main.cpp
SID-TWRI/self-driving-car
c9ab88576d9f2fff4c198978984159b1976416c9
[ "MIT" ]
null
null
null
#include "vehicle.h" #include "cost_functions.h" #include "constants.h" #include "helper.h" #include <fstream> #include <math.h> #include <uWS/uWS.h> #include <chrono> #include <iostream> #include <thread> #include <vector> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "json.hpp" #include "spline.h" #include "coordinates.h" using namespace std; // for convenience using json = nlohmann::json; static const string stSTART_STATE = "KL"; static const double dSTART_ACC = 0.; static const double dSTART_ACC_LAST = -99.; int gl_iSensor_fusion_size; int iNext_Lane = -1; vector<vector<double>> gl_vSensor_fusion; vector<vector<vector<double>>> gl_vLane_traffic(3); vector<vector<vector<double>>> gl_vLane_traffic_last(3); // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. string hasData(string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_first_of("}"); if (found_null != string::npos) { return ""; } else if (b1 != string::npos && b2 != string::npos) { return s.substr(b1, b2 - b1 + 2); } return ""; } int main() { uWS::Hub h; // Load up map values for waypoint's x,y,s and d normalized normal vectors vector<double> map_waypoints_x; vector<double> map_waypoints_y; vector<double> map_waypoints_s; vector<double> map_waypoints_dx; vector<double> map_waypoints_dy; Vehicle ego_car; ego_car.state = stSTART_STATE; ego_car.a_last = dSTART_ACC_LAST; ego_car.a = dSTART_ACC; //########################################################## // Waypoint map to read from string map_file_ = "../data/highway_map.csv"; // The max s value before wrapping around the track back to 0 //double max_s = 6945.554; ifstream in_map_(map_file_.c_str(), ifstream::in); string line; while (getline(in_map_, line)) { istringstream iss(line); double x; double y; float s; float d_x; float d_y; iss >> x; iss >> y; iss >> s; iss >> d_x; iss >> d_y; map_waypoints_x.push_back(x); map_waypoints_y.push_back(y); map_waypoints_s.push_back(s); map_waypoints_dx.push_back(d_x); map_waypoints_dy.push_back(d_y); } h.onMessage([&ego_car, &map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event //auto sdata = string(data).substr(0, length); //cout << sdata << endl; bool bDebug_main = false; if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(data); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { // j[1] is the data JSON object // Main car's localization Data double car_x = j[1]["x"]; double car_y = j[1]["y"]; double car_s = j[1]["s"]; double car_d = j[1]["d"]; double car_yaw = j[1]["yaw"]; double car_speed = j[1]["speed"]; // Previous path data given to the Planner vector<double> previous_path_x = j[1]["previous_path_x"]; vector<double> previous_path_y = j[1]["previous_path_y"]; // Previous path's end s and d values double end_path_s = j[1]["end_path_s"]; double end_path_d = j[1]["end_path_d"]; // Sensor Fusion Data, a list of all other cars on the same side of the road. vector<vector<double>> sensor_fusion = j[1]["sensor_fusion"]; //auto sensor_fusion = j[1]["sensor_fusion"]; int prev_size = previous_path_x.size(); ego_car.iNum_Steps = 50 - prev_size; ego_car.iNum_rest_steps = prev_size; // set all informations about the car to the ego car ego_car.vehicle_set(car_x, car_y, car_s, car_d, car_yaw, car_speed, previous_path_x, previous_path_y, end_path_s, end_path_d); // set all informations about all other cars to a vector gl_vSensor_fusion = sensor_fusion; gl_iSensor_fusion_size = sensor_fusion.size(); gl_vLane_traffic_last = gl_vLane_traffic; // determine for each lane the car ahead and behind Lane_Traffic(gl_vSensor_fusion, gl_iSensor_fusion_size, gl_vLane_traffic, ego_car, gl_vLane_traffic_last); //cout for debug if(bDebug_main){ cout << "prev_size: " << prev_size << endl; cout << "ego car lane : " << ego_car.lane << "\t s position: \t" << ego_car.s << "\t v : \t" << ego_car.v << "\t timestep calculated: \t" << double(ego_car.iNum_Steps * ego_car.dTimestep) << "\t a calculated: \t" << ego_car.a << endl; cout << "ego lane last: " << ego_car.lane_last << "\t s position: \t" << ego_car.s_last << "\t v : \t" << ego_car.v_last << "\t timestep calculated: \t" << double(ego_car.iNum_Steps * ego_car.dTimestep) << "\t a calculated: \t" << ego_car.a_last << endl; cout << "gl_vLane_traffic !!!" << endl; for (int k = 0; k < 3; k++){ cout << "lane: " << k << endl; for(int p = 0; p < gl_vLane_traffic[k].size(); p++){ vector<double> car_test = gl_vLane_traffic[k][p]; cout << "car_set id: " << car_test[0] << "\t lane:" << car_test[9] <<"\t s: " <<car_test[5] << "\t s_dist: " << car_test[8]<< "\t v: " << car_test[7]<< "\t acc: " << car_test[11]<<endl; } } cout << "gl_vLane_traffic_last !!!" << endl; for (int k = 0; k < 3; k++){ cout << "lane: " << k << endl; for(int p = 0; p < gl_vLane_traffic_last[k].size(); p++){ vector<double> car_test = gl_vLane_traffic_last[k][p]; cout << "car_set id: " << car_test[0] << "\t lane:" << car_test[9] <<"\t s: " <<car_test[5] << "\t s_dist: " << car_test[8]<< "\t v: " << car_test[7]<< "\t acc: " << car_test[11]<<endl; } } } //############### Behavioral Planner // determine the best choice for driving BehavioralPlanner(gl_vLane_traffic, ego_car, iNext_Lane); //############### Path Planner // calculate the best path, according to all restrictions (acc, speed ..), for this choice vector<vector<double>> next_vals; next_vals = PathPlanner(gl_vLane_traffic, ego_car, iNext_Lane, map_waypoints_x, map_waypoints_y, map_waypoints_s); //################################################### json msgJson; msgJson["next_x"] = next_vals[0]; msgJson["next_y"] = next_vals[1]; auto msg = "42[\"control\","+ msgJson.dump()+"]"; //this_thread::sleep_for(chrono::milliseconds(1000)); ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); // We don't need this since we're not using HTTP but if it's removed the // program // doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
35.638298
268
0.578269
[ "object", "vector" ]
2e64af3882ae4fd8de8641b9814ecb654c0bf488
6,325
cpp
C++
hackathon/MK/DeepNeuron/tester.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/MK/DeepNeuron/tester.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/MK/DeepNeuron/tester.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <ctime> #include "v3d_message.h" #include "tester.h" #include "classification.h" #include "mean_shift_fun.h" #include "caffe/caffe.hpp" using namespace std; void Tester::test1() { QString model_file = inputStrings[0]; QString trained_file = inputStrings[1]; QString mean_file = inputStrings[2]; QString outswc_file = outputStrings[0]; int Sxy = 4; QList<ImageMarker> inputMarkers; inputMarkers = readMarker_file(inputFileStrings[1]); unsigned char* ImgPtr = 0; V3DLONG in_sz[4]; int datatype; if (!simple_loadimage_wrapper(*theCallbackPtr, inputFileStrings[0].toStdString().c_str(), ImgPtr, in_sz, datatype)) { cerr << "Error reading image file [" << inputFileStrings[0].toStdString() << "]. Exit." << endl; return; } int imgX = in_sz[0]; int imgY = in_sz[1]; int imgZ = in_sz[2]; int channel = in_sz[3]; V3DLONG start_z = 0; NeuronTree sampledTree; int zhb = imgZ; for (QList<ImageMarker>::iterator markerIt = inputMarkers.begin(); markerIt != inputMarkers.end(); ++markerIt) { //qDebug() << markerIt->x << " " << markerIt->y << " " << markerIt->z; int markerX = int(floor(markerIt->x)) - 1; int markerY = int(floor(markerIt->y)) - 1; int z = int(floor(markerIt->z)) - 1; V3DLONG VOIxyz[4]; VOIxyz[0] = 97; VOIxyz[1] = 97; VOIxyz[2] = imgZ; VOIxyz[3] = channel; V3DLONG VOIsz = VOIxyz[0] * VOIxyz[1] * VOIxyz[2]; unsigned char* VOIPtr = new unsigned char[VOIsz]; int xlb = markerX - 48; int xhb = markerX + 48; int ylb = markerY - 48; int yhb = markerY + 48; cropStack(ImgPtr, VOIPtr, xlb, xhb, ylb, yhb, 1, zhb, imgX, imgY, imgZ); V3DLONG ROIsz = VOIxyz[0] * VOIxyz[1]; unsigned char* blockarea = new unsigned char[ROIsz]; maxIPStack(VOIPtr, blockarea, xlb, xhb, ylb, yhb, 1, zhb); std::vector<std::vector<float> > detection_results; LandmarkList marklist_2D; Classifier classifier(model_file.toStdString(), trained_file.toStdString(), mean_file.toStdString()); /*detection_results = batch_detection(blockarea, classifier, 97, 97, 1, Sxy); V3DLONG d = 0; for (V3DLONG iiy = 0 + Sxy; iiy < 98; iiy = iiy + Sxy) { for (V3DLONG iix = 0 + Sxy; iix < 98; iix = iix + Sxy) { std::vector<float> output = detection_results[d]; if (output.at(1) > output.at(0) && output.at(1) > output.at(2)) { LocationSimple S; S.x = iix; S.y = iiy; S.z = 1; S.category = 2; marklist_2D.push_back(S); } else if (output.at(2) > output.at(0) && output.at(2) > output.at(1)) { LocationSimple S; S.x = iix; S.y = iiy; S.z = 1; S.category = 3; marklist_2D.push_back(S); } //cout << output.at(0) << " " << output.at(1) << " " << output.at(2) << " " << endl; d++; } } mean_shift_fun fun_obj; LandmarkList marklist_2D_shifted; vector<V3DLONG> poss_landmark; vector<float> mass_center; double windowradius = Sxy + 5; V3DLONG sz_img[4]; sz_img[0] = 97; sz_img[1] = 97; sz_img[2] = 1; sz_img[3] = 1; fun_obj.pushNewData<unsigned char>((unsigned char*)blockarea, sz_img); poss_landmark = landMarkList2poss(marklist_2D, sz_img[0], sz_img[0] * sz_img[1]); for (V3DLONG j = 0; j<poss_landmark.size(); j++) { mass_center = fun_obj.mean_shift_center_mass(poss_landmark[j], windowradius); LocationSimple tmp(mass_center[0] + 1, mass_center[1] + 1, mass_center[2] + 1); tmp.category = marklist_2D[j].category; marklist_2D_shifted.append(tmp); } QList <ImageMarker> marklist_3D; ImageMarker S; for (V3DLONG i = 0; i < marklist_2D_shifted.size(); i++) { V3DLONG ix_2D = marklist_2D_shifted.at(i).x; V3DLONG iy_2D = marklist_2D_shifted.at(i).y; double I_max = 0; double I_sum = 0; V3DLONG iz_2D; for (V3DLONG j = 0; j < imgZ - start_z; j++) { I_sum += VOIPtr[j*sz_img[1] * sz_img[0] + iy_2D*sz_img[0] + ix_2D]; if (VOIPtr[j*sz_img[1] * sz_img[0] + iy_2D*sz_img[0] + ix_2D] >= I_max) { I_max = VOIPtr[j*sz_img[1] * sz_img[0] + iy_2D*sz_img[0] + ix_2D]; iz_2D = j; } } S.x = ix_2D; S.y = iy_2D; S.z = iz_2D; S.color.r = 255; S.color.g = 0; S.color.b = 0; S.type = marklist_2D_shifted[i].category; marklist_3D.append(S); } QList <ImageMarker> marklist_3D_pruned = batch_deletion(VOIPtr, classifier, marklist_3D, 97, 97, imgZ - start_z); if (marklist_3D_pruned.size()>0) { for (V3DLONG i = 0; i < marklist_3D_pruned.size(); i++) { if (marklist_3D_pruned.at(i).radius > 0.9) //was 0.995 { V3DLONG ix = marklist_3D_pruned.at(i).x + markerX - 48; V3DLONG iy = marklist_3D_pruned.at(i).y + markerY - 48; V3DLONG iz = marklist_3D_pruned.at(i).z; int type = marklist_3D_pruned.at(i).type; NeuronSWC n; n.x = ix - 1; n.y = iy - 1; n.z = iz - 1 + start_z; n.n = i + 1; n.type = type; //cout << n.type << " "; n.r = marklist_3D_pruned.at(i).radius; n.pn = -1; //so the first one will be root sampledTree.listNeuron << n; } } //cout << endl; }*/ if (blockarea) { delete[]blockarea; blockarea = 0; } if (VOIPtr) { delete[]VOIPtr; VOIPtr = 0; } cout << "complete 1 marker" << endl; } delete[] ImgPtr; writeSWC_file(outswc_file, sampledTree); sampledTree.listNeuron.clear(); } void Tester::cropStack(unsigned char InputImagePtr[], unsigned char OutputImagePtr[], int xlb, int xhb, int ylb, int yhb, int zlb, int zhb, int imgX, int imgY, int imgZ) { V3DLONG OutputArrayi = 0; for (V3DLONG zi = zlb; zi <= zhb; ++zi) { for (V3DLONG yi = ylb; yi <= yhb; ++yi) { for (V3DLONG xi = xlb; xi <= xhb; ++xi) { OutputImagePtr[OutputArrayi] = InputImagePtr[imgX*imgY*(zi - 1) + imgX*(yi - 1) + (xi - 1)]; ++OutputArrayi; } } } } void Tester::maxIPStack(unsigned char inputVOIPtr[], unsigned char OutputImage2DPtr[], int xlb, int xhb, int ylb, int yhb, int zlb, int zhb) { int xDim = xhb - xlb + 1; int yDim = yhb - ylb + 1; int zDim = zhb - zlb + 1; for (int yi = 0; yi < yDim; ++yi) { for (int xi = 0; xi < xDim; ++xi) { short int maxVal = 0; for (int zi = 0; zi < zDim; ++zi) { short int curValue = inputVOIPtr[xDim*yDim*zi + xDim*yi + xi]; if (curValue > maxVal) maxVal = curValue; } OutputImage2DPtr[xDim*yi + xi] = (unsigned char)(maxVal); } } }
29.147465
116
0.62498
[ "vector" ]
2e6d1e0f3b5506d12e8a16de4dfc8f785f4b7d5a
3,617
hpp
C++
src/lua_iface.hpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/lua_iface.hpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/lua_iface.hpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #if defined(USE_LUA) #include <memory> #include "eris/lua.h" #include "formula_callable.hpp" #include "formula_callable_definition.hpp" namespace game_logic { class FormulaObject; } namespace lua { class LuaContext; class CompiledChunk { public: CompiledChunk() {} virtual ~CompiledChunk() {} void resetChunks() { chunks_.clear(); chunks_it_ = chunks_.begin(); } void addChunk(const void* p, size_t sz) { const char* pp = static_cast<const char*>(p); chunks_.push_back(std::vector<char>(pp,pp+sz)); } bool run(const LuaContext &) const; const std::vector<char>& current() const { return *chunks_it_; } void next() { ++chunks_it_; } void setName(const std::string &); private: typedef std::vector<std::vector<char>> chunk_list_type; chunk_list_type chunks_; mutable chunk_list_type::const_iterator chunks_it_; std::string chunk_name_; }; class LuaCompiled : public game_logic::FormulaCallable, public CompiledChunk { public: LuaCompiled(); virtual ~LuaCompiled(); private: DECLARE_CALLABLE(LuaCompiled); }; typedef ffl::IntrusivePtr<LuaCompiled> LuaCompiledPtr; class LuaContext : public reference_counted_object { public: LuaContext(); explicit LuaContext(game_logic::FormulaObject&); virtual ~LuaContext(); lua_State* getState() const { return state_; } void setSelfObject(game_logic::FormulaObject&); void setSelfCallable(game_logic::FormulaCallable& callable); bool execute(const variant& value, game_logic::FormulaCallable* callable=nullptr); bool dostring(const std::string&name, const std::string& str, game_logic::FormulaCallable* callable=nullptr); bool dofile(const std::string&name, const std::string& str, game_logic::FormulaCallable* callable=nullptr); LuaCompiledPtr compile(const std::string& name, const std::string& str); CompiledChunk* compileChunk(const std::string& name, const std::string& str); std::string persist(); private: void init(); lua_State * state_; LuaContext(const LuaContext&); }; typedef ffl::IntrusivePtr<LuaContext> LuaContextPtr; class LuaFunctionReference : public game_logic::FormulaCallable { public: LuaFunctionReference(lua_State* L, int ref); virtual ~LuaFunctionReference(); virtual variant call() const; virtual variant call(const variant & args) const; void set_return_type(const variant_type_ptr &) const; private: LuaContextPtr L_; int ref_; mutable variant_type_ptr target_return_type_; DECLARE_CALLABLE(LuaFunctionReference); LuaFunctionReference(); LuaFunctionReference(const LuaFunctionReference&); }; typedef ffl::IntrusivePtr<LuaFunctionReference> LuaFunctionReferencePtr; } #endif
27.823077
111
0.751728
[ "vector" ]
2e73c3cbcee8537eec8a82d949ca25951e59407a
560
cpp
C++
496-next-greater-element-i/496-next-greater-element-i.cpp
LSSYA/Competitve-Programming
5217cc509fe2c4560b64ef7fc7a655c94e9580a5
[ "MIT" ]
null
null
null
496-next-greater-element-i/496-next-greater-element-i.cpp
LSSYA/Competitve-Programming
5217cc509fe2c4560b64ef7fc7a655c94e9580a5
[ "MIT" ]
null
null
null
496-next-greater-element-i/496-next-greater-element-i.cpp
LSSYA/Competitve-Programming
5217cc509fe2c4560b64ef7fc7a655c94e9580a5
[ "MIT" ]
null
null
null
// Time complexity - O(n2) class Solution { public: vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) { vector<int> ans; for(int i=0; i<nums1.size(); i++) { int k = -1; for(int j = nums2.size() - 1; nums2[j] != nums1[i] && j>=0; j--) { if(nums2[j] > nums1[i]) { k = nums2[j]; } } ans.push_back(k); } return ans; } };
20.740741
76
0.360714
[ "vector" ]
2e771464e2e372dd2a7c416c89f5a79d8cd29231
11,595
cpp
C++
thirdparty/physx/APEXSDK/shared/general/HACD/src/AutoGeometry.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
thirdparty/physx/APEXSDK/shared/general/HACD/src/AutoGeometry.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
thirdparty/physx/APEXSDK/shared/general/HACD/src/AutoGeometry.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
/*! ** ** Copyright (c) 2014 by John W. Ratcliff mailto:jratcliffscarab@gmail.com ** ** ** The MIT license: ** ** 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. ** ** If you find this code snippet useful; you can tip me at this bitcoin address: ** ** BITCOIN TIP JAR: "1BT66EoaGySkbY9J6MugvQRhMMXDwPxPya" ** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "AutoGeometry.h" #include "ConvexHull.h" namespace HACD { void fm_transform(const float matrix[16],const float v[3],float t[3]) // rotate and translate this point { if ( matrix ) { float tx = (matrix[0*4+0] * v[0]) + (matrix[1*4+0] * v[1]) + (matrix[2*4+0] * v[2]) + matrix[3*4+0]; float ty = (matrix[0*4+1] * v[0]) + (matrix[1*4+1] * v[1]) + (matrix[2*4+1] * v[2]) + matrix[3*4+1]; float tz = (matrix[0*4+2] * v[0]) + (matrix[1*4+2] * v[1]) + (matrix[2*4+2] * v[2]) + matrix[3*4+2]; t[0] = tx; t[1] = ty; t[2] = tz; } else { t[0] = v[0]; t[1] = v[1]; t[2] = v[2]; } } inline float det(const float *p1,const float *p2,const float *p3) { return p1[0]*p2[1]*p3[2] + p2[0]*p3[1]*p1[2] + p3[0]*p1[1]*p2[2] -p1[0]*p3[1]*p2[2] - p2[0]*p1[1]*p3[2] - p3[0]*p2[1]*p1[2]; } float fm_computeMeshVolume(const float *vertices,size_t tcount,const uint32_t *indices) { float volume = 0; for (uint32_t i=0; i<tcount; i++,indices+=3) { const float *p1 = &vertices[ indices[0]*3 ]; const float *p2 = &vertices[ indices[1]*3 ]; const float *p3 = &vertices[ indices[2]*3 ]; volume+=det(p1,p2,p3); // compute the volume of the tetrahedran relative to the origin. } volume*=(1.0f/6.0f); if ( volume < 0 ) volume*=-1; return volume; } class Vec3 { public: Vec3(const float *pos) { x = pos[0]; y = pos[1]; z = pos[2]; } float x; float y; float z; }; typedef hacd::vector< Vec3 > Vec3Vector; class MyHull : public HACD::SimpleHull, public UANS::UserAllocated { public: MyHull(void) { mValidHull = false; } ~MyHull(void) { release(); } void release(void) { HACD_FREE(mIndices); HACD_FREE(mVertices); mIndices = 0; mVertices = 0; mTriCount = 0; mVertexCount = 0; } void addPos(const float *p) { Vec3 v(p); mPoints.push_back(v); } float generateHull(void) { release(); if ( mPoints.size() >= 3 ) // must have at least 3 vertices to create a hull. { // now generate the convex hull. HullDesc desc((uint32_t)mPoints.size(),&mPoints[0].x, sizeof(float)*3); desc.mMaxVertices = 32; desc.mSkinWidth = 0.001f; HullLibrary h; HullResult result; HullError e = h.CreateConvexHull(desc,result); if ( e == QE_OK ) { mTriCount = result.mNumTriangles; mIndices = (uint32_t *)HACD_ALLOC(sizeof(uint32_t)*mTriCount*3); memcpy(mIndices,result.mIndices,sizeof(uint32_t)*mTriCount*3); mVertexCount = result.mNumOutputVertices; mVertices = (float *)HACD_ALLOC(sizeof(float)*mVertexCount*3); memcpy(mVertices,result.mOutputVertices,sizeof(float)*mVertexCount*3); mValidHull = true; mMeshVolume = fm_computeMeshVolume( mVertices, mTriCount, mIndices ); // compute the volume of this mesh. h.ReleaseResult(result); } } return mMeshVolume; } void inherit(MyHull &c) { Vec3Vector::iterator i; for (i=c.mPoints.begin(); i!=c.mPoints.end(); ++i) { mPoints.push_back( (*i) ); } c.mPoints.clear(); c.mValidHull = false; generateHull(); } void setTransform(const HACD::SimpleBone &b,int32_t bone_index) { mBoneName = b.mBoneName; mBoneIndex = bone_index; mParentIndex = b.mParentIndex; memcpy(mTransform,b.mTransform,sizeof(float)*16); if ( mVertexCount ) { for (uint32_t i=0; i<mVertexCount; i++) { float *vtx = &mVertices[i*3]; fm_transform(b.mInverseTransform,vtx,vtx); // inverse transform the point into bone relative object space } } } bool mValidHull; Vec3Vector mPoints; }; class MyAutoGeometry : public HACD::AutoGeometry, public UANS::UserAllocated { public: MyAutoGeometry() { mHulls = 0; mSimpleHulls = 0; } virtual ~MyAutoGeometry(void) { release(); } void release(void) { delete []mHulls; mHulls = 0; HACD_FREE(mSimpleHulls); mSimpleHulls = 0; } #define MAX_BONE_COUNT 8 void addBone(uint32_t bone,uint32_t *bones,uint32_t &bcount) { HACD_ASSERT(bcount < MAX_BONE_COUNT); if ( bcount < MAX_BONE_COUNT ) { bool found = false; for (uint32_t i=0; i<bcount; i++) { if ( bones[i] == bone ) { found = true; break; } } if ( !found ) { bones[bcount] = bone; bcount++; } } } void addBones(const HACD::SimpleSkinnedVertex &v,uint32_t *bones,uint32_t &bcount, const HACD::SimpleBone *sbones) { if ( v.mWeight[0] >= sbones[v.mBone[0]].mBoneMinimalWeight) addBone(v.mBone[0],bones,bcount); if ( v.mWeight[1] >= sbones[v.mBone[1]].mBoneMinimalWeight) addBone(v.mBone[1],bones,bcount); if ( v.mWeight[2] >= sbones[v.mBone[2]].mBoneMinimalWeight) addBone(v.mBone[2],bones,bcount); if ( v.mWeight[3] >= sbones[v.mBone[3]].mBoneMinimalWeight) addBone(v.mBone[3],bones,bcount); } void addTri(const HACD::SimpleSkinnedVertex &v1,const HACD::SimpleSkinnedVertex &v2,const HACD::SimpleSkinnedVertex &v3,const HACD::SimpleBone *sbones) { uint32_t bcount = 0; uint32_t bones[MAX_BONE_COUNT]; addBones(v1,bones,bcount, sbones); addBones(v2,bones,bcount, sbones); addBones(v3,bones,bcount, sbones); for (uint32_t i=0; i<bcount; i++) { addPos(v1.mPos, (physx::PxI32)bones[i], sbones ); addPos(v2.mPos, (physx::PxI32)bones[i], sbones ); addPos(v3.mPos, (physx::PxI32)bones[i], sbones ); } } virtual HACD::SimpleHull ** createCollisionVolumes(float collapse_percentage, uint32_t bone_count, const HACD::SimpleBone *bones, const HACD::SimpleSkinnedMesh *mesh, uint32_t &geom_count) { release(); geom_count = 0; mHulls = HACD_NEW(MyHull)[bone_count]; for (uint32_t i=0; i<bone_count; i++) { const HACD::SimpleBone &b = bones[i]; mHulls[i].setTransform(b,(physx::PxI32)i); } uint32_t tcount = mesh->mVertexCount/3; for (uint32_t i=0; i<tcount; i++) { const HACD::SimpleSkinnedVertex &v1 = mesh->mVertices[i*3+0]; const HACD::SimpleSkinnedVertex &v2 = mesh->mVertices[i*3+0]; const HACD::SimpleSkinnedVertex &v3 = mesh->mVertices[i*3+0]; addTri(v1,v2,v3,bones); } float totalVolume = 0; for (uint32_t i=0; i<bone_count; i++) { totalVolume+=mHulls[i].generateHull(); } // ok.. now do auto-collapse of hulls... #if 1 if ( collapse_percentage > 0 ) { float ratio = collapse_percentage / 100.0f; for (int32_t i=(int32_t)(bone_count-1); i>=0; i--) { MyHull &h = mHulls[i]; const HACD::SimpleBone &b = bones[i]; if ( b.mParentIndex >= 0 ) { MyHull &parent_hull = mHulls[b.mParentIndex]; if ( h.mValidHull && parent_hull.mValidHull ) { if ( h.mMeshVolume < (parent_hull.mMeshVolume*ratio) ) // if we are less than 1/3 the volume of our parent, copy our vertices to the parent.. { parent_hull.inherit(h); } } } } } #endif for (int32_t i=0; i<(int32_t)bone_count; i++) { MyHull &h = mHulls[i]; if ( h.mValidHull ) geom_count++; } if ( geom_count ) { mSimpleHulls = (HACD::SimpleHull **)HACD_ALLOC(sizeof(HACD::SimpleHull *)*geom_count); int32_t index = 0; for (int32_t i=0; i<(int32_t)bone_count; i++) { MyHull *hull = &mHulls[i]; if ( hull->mValidHull ) { const HACD::SimpleBone &b = bones[i]; hull->setTransform(b,i); mSimpleHulls[index] = hull; index++; } } } return mSimpleHulls; } void addPos(const float *p,int32_t bone,const HACD::SimpleBone *bones) { switch ( bones[bone].mOption ) { case HACD::BO_INCLUDE: mHulls[bone].addPos(p); break; case HACD::BO_EXCLUDE: break; case HACD::BO_COLLAPSE: { while ( bone >= 0 ) { bone = bones[bone].mParentIndex; if ( bones[bone].mOption == HACD::BO_INCLUDE ) break; else if ( bones[bone].mOption == HACD::BO_EXCLUDE ) { bone = -1; break; } } if ( bone >= 0 ) { mHulls[bone].addPos(p); // collapse into the parent } } break; } } virtual HACD::SimpleHull ** createCollisionVolumes(float collapse_percentage,uint32_t &geom_count) { HACD::SimpleHull **ret = 0; if ( !mVertices.empty() && !mBones.empty() ) { HACD::SimpleSkinnedMesh mesh; mesh.mVertexCount = (uint32_t)mVertices.size(); mesh.mVertices = &mVertices[0]; ret = createCollisionVolumes(collapse_percentage,(uint32_t)mBones.size(),&mBones[0],&mesh,geom_count); mVertices.clear(); mBones.clear(); } return ret; } virtual void addSimpleSkinnedTriangle(const HACD::SimpleSkinnedVertex &v1,const HACD::SimpleSkinnedVertex &v2,const HACD::SimpleSkinnedVertex &v3) { mVertices.push_back(v1); mVertices.push_back(v2); mVertices.push_back(v3); } virtual void addSimpleBone(const HACD::SimpleBone &_b) { HACD::SimpleBone b = _b; mBones.push_back(b); } void mystrlwr(char *str) { while ( *str ) { char c = *str; if ( c >= 'A' && c <= 'Z' ) { c+=32; *str = c; } str++; } } virtual const char * stristr(const char *str,const char *key) // case insensitive ststr { HACD_ASSERT( strlen(str) < 2048 ); HACD_ASSERT( strlen(key) < 2048 ); char istr[2048]; char ikey[2048]; strncpy(istr,str,2048); strncpy(ikey,key,2048); mystrlwr(istr); mystrlwr(ikey); char *foo = strstr(istr,ikey); if ( foo ) { uint32_t loc = (uint32_t)(foo - istr); foo = (char *)str+loc; } return foo; } private: typedef hacd::vector< HACD::SimpleBone > SimpleBoneVector; typedef hacd::vector< HACD::SimpleSkinnedVertex > SimpleSkinnedVertexVector; SimpleBoneVector mBones; SimpleSkinnedVertexVector mVertices; MyHull *mHulls; HACD::SimpleHull **mSimpleHulls; }; HACD::AutoGeometry * createAutoGeometry() { HACD::MyAutoGeometry *g = HACD_NEW(HACD::MyAutoGeometry); return static_cast< HACD::AutoGeometry *>(g); } void releaseAutoGeometry(HACD::AutoGeometry *g) { HACD::MyAutoGeometry * m = static_cast<HACD::MyAutoGeometry *>(g); delete m; } }; // end of namespace
24.565678
153
0.631824
[ "mesh", "object", "vector", "transform" ]
2e78d4518837d421d0383b4f93dbe2ce03a0fa80
7,874
cpp
C++
DGP/Random.cpp
sidch/DGP
20a2d47563b6e36cd89bea0b1326e5267df8e9a6
[ "BSD-3-Clause" ]
14
2016-03-15T16:24:10.000Z
2022-01-06T13:43:17.000Z
a3/src/DGP/Random.cpp
meetps/CS-749
f1ddc4ed003b3a9f222f2a724d53076ddec697a6
[ "MIT" ]
null
null
null
a3/src/DGP/Random.cpp
meetps/CS-749
f1ddc4ed003b3a9f222f2a724d53076ddec697a6
[ "MIT" ]
5
2017-04-12T17:40:57.000Z
2022-01-06T13:43:20.000Z
//============================================================================ // // DGP: Digital Geometry Processing toolkit // Copyright (C) 2016, Siddhartha Chaudhuri // // This software is covered by a BSD license. Portions derived from other // works are covered by their respective licenses. For full licensing // information see the LICENSE.txt file. // //============================================================================ /* ORIGINAL HEADER @file Random.cpp @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2009-01-02 @edited 2009-03-29 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #include "Random.hpp" #include "Math.hpp" #include <ctime> #include <limits> #ifdef DGP_WINDOWS # include <windows.h> #else # include <unistd.h> #endif namespace DGP { Random::Random(void * x) : state(NULL), m_threadsafe(false) { (void)x; } Random::Random(uint32 seed, bool threadsafe) : m_threadsafe(threadsafe) { uint32 const X = 1812433253UL; state = new uint32[N]; state[0] = seed; for (index = 1; index < (int32)N; ++index) { state[index] = X * (state[index - 1] ^ (state[index - 1] >> 30)) + index; } } Random::~Random() { delete [] state; state = NULL; } uint32 Random::bits() { // See http://en.wikipedia.org/wiki/Mersenne_twister // Make a local copy of the index variable to ensure that it is not out of bounds int32 localIndex = index; // Automatically checks for index < 0 if corrupted by unsynchronized threads. if ((uint32)localIndex >= (uint32)N) { generate(); localIndex = 0; } // Increment the global index. It may go out of bounds on multiple threads, but the above check ensures that the array index // actually used never goes out of bounds. It doesn't matter if we grab the same array index twice on two threads, since the // distribution of random numbers will still be uniform. ++index; // Return the next random in the sequence uint32 r = state[localIndex]; // Temper the result r ^= r >> U; r ^= (r << S) & B; r ^= (r << T) & C; r ^= r >> L; return r; } void Random::generate() { // Lower R bits static uint32 const LOWER_MASK = (1LU << R) - 1; // Upper (32 - R) bits static uint32 const UPPER_MASK = 0xFFFFFFFF << R; static uint32 const mag01[2] = { 0UL, (uint32)A }; if (m_threadsafe) lock.lock(); // First N - M bits for (unsigned int i = 0; i < N - M; ++i) { uint32 x = (state[i] & UPPER_MASK) | (state[i + 1] & LOWER_MASK); state[i] = state[i + M] ^ (x >> 1) ^ mag01[x & 1]; } // Remaining bits for (unsigned int i = N - M + 1; i < N - 1; ++i) { uint32 x = (state[i] & UPPER_MASK) | (state[i + 1] & LOWER_MASK); state[i] = state[i + (M - N)] ^ (x >> 1) ^ mag01[x & 1]; } uint32 y = (state[N - 1] & UPPER_MASK) | (state[0] & LOWER_MASK); state[N - 1] = state[M - 1] ^ (y >> 1) ^ mag01[y & 1]; index = 0; if (m_threadsafe) lock.unlock(); } bool Random::coinToss() { // Probably not as fast as generating just the next bit but will do for now return (bool)(bits() & 0x01); } int32 Random::integer() { return (int32)(bits() & MAX_INTEGER); } int32 Random::integer(int32 low, int32 high) { int32 r = (int32)std::floor(low + (high - low + 1) * (double)bits() / 0xFFFFFFFFUL); // There is a *very small* chance of generating a number larger than high. if (r > high) { return high; } else { return r; } } Real Random::gaussian(Real mean, Real stddev) { // Using Box-Mueller method from http://www.taygeta.com/random/gaussian.html // Modified to specify standard deviation and mean of distribution Real w, x1, x2; // Loop until w is less than 1 so that log(w) is negative do { x1 = uniform(-1.0f, 1.0f); x2 = uniform(-1.0f, 1.0f); w = (Real)(Math::square(x1) + Math::square(x2)); } while (w > 1.0f); // Transform to gassian distribution. Multiply by the variance \a sigma (stddev^2) and add the \a mean. return x2 * (Real)Math::square(stddev) * std::sqrt((-2.0f * std::log(w) ) / w) + mean; } void Random::cosHemi(Real & x, Real & y, Real & z) { Real const e1 = uniform01(); Real const e2 = uniform01(); // Jensen's method Real const sin_theta = std::sqrt(1.0f - e1); Real const cos_theta = std::sqrt(e1); Real const phi = 6.28318531f * e2; x = std::cos(phi) * sin_theta; y = std::sin(phi) * sin_theta; z = cos_theta; // We could also use Malley's method (pbrt p.657), since they are the same cost: // // r = sqrt(e1); // t = 2*pi*e2; // x = cos(t)*r; // y = sin(t)*r; // z = sqrt(1.0 - x*x + y*y); } void Random::cosPowHemi(Real const k, Real & x, Real & y, Real & z) { Real const e1 = uniform01(); Real const e2 = uniform01(); Real const cos_theta = std::pow(e1, 1.0f / (k + 1.0f)); Real const sin_theta = std::sqrt(1.0f - Math::square(cos_theta)); Real const phi = 6.28318531f * e2; x = std::cos(phi) * sin_theta; y = std::sin(phi) * sin_theta; z = cos_theta; } void Random::hemi(Real & x, Real & y, Real & z) { sphere(x, y, z); z = std::abs(z); } void Random::sphere(Real & x, Real & y, Real & z) { // Adapted from: Robert E. Knop, "Algorithm 381: Random Vectors Uniform in Solid Angle", CACM, 13, p326, 1970. // It uses the fact that the projection of the uniform 2-sphere distribution onto any axis (in this case the Z axis) is // uniform. Real m2; // squared magnitude do { x = 2 * uniform01() - 1; y = 2 * uniform01() - 1; m2 = x * x + y * y; } while (m2 > 1 || m2 < 1e-10); // The squared length happens to be uniformly distributed in [0, 1]. Since the projection of the 2-sphere distribution onto // the Z axis is uniform (can be derived from the observation that the area of a spherical cap is linear in its height), we // can use the squared length, rescaled to [-1, 1], as the Z value (latitude). z = 2 * m2 - 1; // x and y now locate the longitude of the point after scaling to lie on the sphere Real s = 2 * std::sqrt(1 - m2); // this factor ensures x^2 + y^2 + z^2 = 1 x *= s; y *= s; } void Random::integers(int32 lo, int32 hi, int32 m, int32 * selected) { // The current algorithm does no extra work to sort sortedIntegers(lo, hi, m, selected); } namespace RandomInternal { // Get a very large random integer int32 bigRand(Random & r) { static int32 const BIG_HALF = Random::MAX_INTEGER / 2; return BIG_HALF + r.integer() % BIG_HALF; // guaranteed to not exceed MAX_INTEGER } } // namespace RandomInternal void Random::sortedIntegers(int32 lo, int32 hi, int32 m, int32 * selected) { int32 remaining = m; for (int32 i = lo; i <= hi; ++i) { // Select m of remaining n - i int32 r = RandomInternal::bigRand(*this); if ((r % (hi - i + 1)) < remaining) { selected[m - remaining] = i; remaining--; if (remaining <= 0) return; } } } namespace RandomInternal { // http://burtleburtle.net/bob/hash/doobs.html unsigned long mix(unsigned long a, unsigned long b, unsigned long c) { a=a-b; a=a-c; a=a^(c >> 13); b=b-c; b=b-a; b=b^(a << 8); c=c-a; c=c-b; c=c^(b >> 13); a=a-b; a=a-c; a=a^(c >> 12); b=b-c; b=b-a; b=b^(a << 16); c=c-a; c=c-b; c=c^(b >> 5); a=a-b; a=a-c; a=a^(c >> 3); b=b-c; b=b-a; b=b^(a << 10); c=c-a; c=c-b; c=c^(b >> 15); return c; } } // namespace RandomInternal uint32 Random::getRandomSeed() { // http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand #ifdef DGP_WINDOWS return (uint32)RandomInternal::mix((unsigned long)std::clock(), (unsigned long)std::time(NULL), (unsigned long)GetCurrentProcessId()); #else return (uint32)RandomInternal::mix((unsigned long)std::clock(), (unsigned long)std::time(NULL), (unsigned long)getpid()); #endif } } // namespace DGP
24.377709
127
0.605918
[ "geometry", "transform", "solid" ]
2e7f36ffd1cbb1e0b163990de5d1613df5b281ec
11,531
cpp
C++
src/sig/gs.cpp
harsha336/rrt_sig
1afa8ad45562f20850360d691c2cc29faf18565b
[ "Apache-2.0" ]
null
null
null
src/sig/gs.cpp
harsha336/rrt_sig
1afa8ad45562f20850360d691c2cc29faf18565b
[ "Apache-2.0" ]
null
null
null
src/sig/gs.cpp
harsha336/rrt_sig
1afa8ad45562f20850360d691c2cc29faf18565b
[ "Apache-2.0" ]
null
null
null
/*======================================================================= Copyright (c) 2018 Marcelo Kallmann. This software is distributed under the Apache License, Version 2.0. All copies must contain the full copyright notice licence.txt located at the base folder of the distribution. =======================================================================*/ # include <stdio.h> # include <stdlib.h> # include <string.h> # include <sys/types.h> # include <sys/stat.h> # include <sig/gs.h> # include <sig/gs_output.h> # ifdef GS_WINDOWS # include <Windows.h> # include <sys/timeb.h> # include <io.h> # else # include <unistd.h> # include <sys/time.h> # endif //================================ math ============================================ float gs_mix ( float a, float b, float t ) { return GS_MIX(a,b,t); } float gs_cubicmix ( float a, float b, float t ) { t = GS_CUBIC(t); // cubic spline mapping return GS_MIX(a,b,t); // shape comparison with sine for graphmatica: // y=-(2.0*(x*x*x)) + (3.0*(x*x)) // y=sin((x-0.5)*3)/2+0.5 } float gs_todeg ( float radians ) { return 180.0f * radians / float(GS_PI); } double gs_todeg ( double radians ) { return 180.0 * radians / double(GS_PI); } float gs_torad ( float degrees ) { return float(GS_PI) * degrees / 180.0f; } double gs_torad ( double degrees ) { return double(GS_PI) * degrees / 180.0; } inline float gs_angnorm_inline ( float radians ) { float v = radians + gspi; return ( v - ( gs2pi*gs_floor(v/gs2pi) ) ) - gspi; } float gs_angnorm ( float radians ) { return gs_angnorm_inline ( radians ); } float gs_anglerp ( float radians1, float radians2, float t ) { float a, a1, a2; if ( radians1<radians2 ) { a1=radians1; a2=radians2; } else { a1=radians2; a2=radians1; } if ( a2-a1<=gspi ) { a = GS_MIX(radians1,radians2,t); } else // by the other side is shorter { a1 += gs2pi; if ( radians1<radians2 ) { a = GS_MIX(a1,a2,t); } else { a = GS_MIX(a2,a1,t); } if ( a>=gs2pi ) a-=gs2pi; } //gsout<<gs_todeg(radians1)<<gspc<<gs_todeg(radians2)<<gspc<<gs_todeg(a)<<gsnl; return a; } float gs_angdist ( float radians1, float radians2 ) { float a1, a2; if ( radians1<radians2 ) { a1=radians1; a2=radians2; } else { a1=radians2; a2=radians1; } float adist = a2-a1; if ( a2-a1>gspi ) // by the other side is shorter { a1 += gs2pi; adist = GS_DIST(a1,a2); if ( adist>=gs2pi ) adist-=gs2pi; } return adist; } float gs_trunc ( float x ) { return (float) (int) (x); } double gs_trunc ( double x ) { return (double) (int) (x); } int gs_round ( float x ) { return (int) ((x>0.0)? (x+0.5f) : (x-0.5f)); } float gs_round ( float x, float prec ) { return (float) (double(prec) * gs_round( double(x)/double(prec) )); } int gs_round ( double x ) { return (int) ((x>0.0)? (x+0.5) : (x-0.5)); } double gs_round ( double x, double prec ) { x = gs_round( x/prec ); return x*prec; } int gs_floor ( float x ) { return (int) ((x>0.0)? x : (x-1.0f)); } int gs_floor ( double x ) { return (int) ((x>0.0)? x : (x-1.0)); } int gs_ceil ( float x ) { return (int) ((x>0.0)? (x+1.0f) : (x)); } int gs_ceil ( double x ) { return (int) ((x>0.0)? (x+1.0) : (x)); } int gs_sqrt ( int n ) { register int i, s=0, t; for ( i=15; i>=0; i-- ) { t = ( s | (1<<i) ); if (t*t<=n) s=t; } return s; } int gs_fact ( int x ) { if ( x<2 ) return 1; int m = x; while ( --x>1 ) m *= x; return m; } int gs_pow ( int b, int e ) { if ( e<=0 ) return 1; int pow=b; while ( --e>0 ) pow*=b; return pow; } float gs_pow ( float b, int e ) { if ( e<=0 ) return 1.0f; float pow=b; while ( --e>0 ) pow*=b; return pow; } double gs_pow ( double b, int e ) { if ( e<=0 ) return 1.0; double pow=b; while ( --e>0 ) pow*=b; return pow; } float gs_dist ( float a, float b ) { return GS_DIST(a,b); } float gs_abs ( float a ) { return GS_ABS(a); } //========================== compare ========================== int gs_compare ( const char *s1, const char *s2 ) { int c1, c2; // ANSI definition of toupper() uses int types while ( *s1 && *s2 ) { c1 = GS_UPPER(*s1); c2 = GS_UPPER(*s2); if ( c1!=c2 ) return c1-c2; s1++; s2++; } if ( !*s1 && !*s2 ) return 0; return !*s1? -1:1; } int gs_comparecs ( const char *s1, const char *s2 ) { while ( *s1 && *s2 ) { if ( *s1!=*s2 ) return int(*s1)-int(*s2); s1++; s2++; } if ( !*s1 && !*s2 ) return 0; return !*s1? -1:1; } int gs_compare ( const char *s1, const char *s2, int n ) { int c1, c2; // ANSI definition of toupper() uses int types // printf("[%s]<>[%s] (%d)\n",s1,s2,n); while ( *s1 && *s2 ) { c1 = GS_UPPER(*s1); c2 = GS_UPPER(*s2); if ( c1!=c2 ) return c1-c2; s1++; s2++; n--; if ( n==0 ) return n; // are equal } if ( !*s1 && !*s2 ) return 0; return !*s1? -1:1; } int gs_comparecs ( const char *s1, const char *s2, int n ) { while ( *s1 && *s2 ) { if ( *s1!=*s2) return int(*s1)-int(*s2); s1++; s2++; n--; if ( n==0 ) return n; // are equal } if ( !*s1 && !*s2 ) return 0; return !*s1? -1:1; } int gs_compare ( const int *i1, const int *i2 ) { return *i1-*i2; } int gs_compare ( const float *f1, const float *f2 ) { return GS_COMPARE(*f1,*f2); } int gs_compare ( const double *d1, const double *d2 ) { return GS_COMPARE(*d1,*d2); } //========================== string ========================== char* gs_string_new ( const char *tocopy ) { if ( !tocopy ) return 0; char *s = new char [ strlen(tocopy)+1 ]; strcpy ( s, tocopy ); return s; } void gs_string_delete ( char*& s ) { delete[] s; s=0; } void gs_string_set ( char*& s, const char *tocopy ) { delete[] s; if ( !tocopy ) { s=0; return; } s = new char [ strlen(tocopy)+1 ]; strcpy ( s, tocopy ); } void gs_string_renew ( char*& s, int size ) { char *news = 0; if ( size>0 ) { news = new char[size]; news[0] = 0; if ( s ) { int i; for ( i=0; i<size; i++ ) { news[i]=s[i]; if(!s[i]) break; } } news[size-1] = 0; } delete []s; s = news; } void gs_string_append ( char*&s, const char* toadd ) { if ( !toadd ) return; if ( !toadd[0] ) return; char *tmp=0; if ( toadd==s ) { tmp=gs_string_new(toadd); toadd=tmp; } int slen = s? strlen(s):0; int newlen = slen+strlen(toadd)+1; gs_string_renew ( s, newlen ); strcat ( s, toadd ); delete[] tmp; } //========================== IO ========================== # ifdef GS_WINDOWS static bool ConsoleShown=false; # endif void gs_output_to_disk ( const char* outfile, const char* errfile ) { # ifdef GS_WINDOWS ConsoleShown=true; # endif if ( freopen ( outfile? outfile:"stdout.txt", "w", stdout ) ) setbuf ( stdout, NULL ); if ( freopen ( errfile? errfile:"stderr.txt", "w", stderr ) ) setbuf ( stderr, NULL ); } void gs_show_console () { # ifdef GS_WINDOWS # ifndef __CYGWIN32__ ConsoleShown = true; if ( !AttachConsole(ATTACH_PARENT_PROCESS) ) // if there is already a console attch to it { AllocConsole(); } // otherwise create one freopen("conin$", "r", stdin); freopen("conout$", "w", stdout); freopen("conout$", "w", stderr); # endif # endif } bool gs_console_shown () { # ifdef GS_WINDOWS return ConsoleShown; # else return true; # endif } bool gs_canopen ( const char* fname ) { FILE* fp = fopen ( fname, "r" ); if ( fp ) { fclose(fp); return true; } else { return false; } } bool gs_absolute ( const char* path ) { if ( !path ) return false; if ( !path[0] ) return false; if ( path[0]=='\\' || path[0]=='/' ) return true; // /dir, \\machine\dir if ( !path[1] ) return false; // eg a 1-letter filename if ( path[1]==':' ) return true; // c:dir is considered absolute in windows return false; } const char* gs_filename ( const char* fname ) { if ( !fname ) return 0; int i, len = strlen(fname); for ( i=len-1; i>=0; i-- ) { if ( fname[i]=='/' || fname[i]=='\\' ) { return fname+i+1; } } return fname; } const char* gs_extension ( const char* fname ) { if ( !fname ) return 0; int i, len = strlen(fname); for ( i=len-1; i>=0; i-- ) { if ( fname[i]=='.' ) { return fname+i+1; } if ( fname[i]=='/' || fname[i]=='\\' ) return 0; // no extension } return 0; } static struct stat _lstat; inline bool fillstat ( const char *fname ) { return stat(fname,&_lstat)==0; } bool gs_isdir ( const char* fname ) { if ( !fname || !fname[0] || !fillstat(fname) ) return false; return ( _lstat.st_mode&0170000 )==0040000; } bool gs_exists ( const char* fname ) { return fname && fname[0] && fillstat(fname); } gsuint gs_size ( const char* fname ) { if ( fname && !fillstat(fname) ) return 0; return (gsuint)_lstat.st_size; } unsigned long long gs_sizel ( const char* fname ) { if ( fname && !fillstat(fname) ) return 0; return (unsigned long long)_lstat.st_size; } gsuint gs_mtime ( const char *fname ) // modification time of the file as a Unix timestamp { if ( fname && !fillstat(fname) ) return 0; if ( _lstat.st_mtime ) return (gsuint) _lstat.st_mtime; if ( _lstat.st_atime ) return (gsuint) _lstat.st_atime; return (gsuint) _lstat.st_ctime; } void gs_exit ( int code ) { exit ( code ); } void gs_sleep ( int milisecs ) { # ifdef GS_WINDOWS SleepEx ( (DWORD)(milisecs), TRUE ); # else usleep ( ((useconds_t)milisecs)*useconds_t(1000) ); # endif } // ================================= Timer ================================== double gs_time () { static bool first=true; #ifdef GS_WINDOWS static double _perf_freq = 0.0; static double _utc_origin = 0.0; #endif if ( first ) { first = false; # ifdef GS_WINDOWS LARGE_INTEGER lpFrequency; LARGE_INTEGER lpPerformanceCount; struct _timeb tbuf; if ( QueryPerformanceFrequency(&lpFrequency)==false ) { gsout.put("GsTimer: WIN32 High Resolution Performance Counter not supported.\n"); } else { _perf_freq = (double)lpFrequency.QuadPart; QueryPerformanceCounter ( &lpPerformanceCount ); _ftime( &tbuf ); // get UTC time in seconds from Jan 1, 1970 double hrcTime = double(lpPerformanceCount.QuadPart) / double(lpFrequency.QuadPart); double utcTime = double(tbuf.time) + double(tbuf.millitm)*1.0E-3; _utc_origin = utcTime - hrcTime; } # endif } # ifdef GS_WINDOWS if ( _perf_freq==0 ) // not available { _timeb tp; _ftime(&tp); return 0.001*(double)tp.millitm + (double)tp.time; } else { LARGE_INTEGER lpPerformanceCount; QueryPerformanceCounter (&lpPerformanceCount); return _utc_origin + double(lpPerformanceCount.QuadPart) / _perf_freq; } # endif # ifdef GS_LINUX timeval tp; if ( gettimeofday(&tp,0)==-1 ) return 0; return 0.000001*(double)tp.tv_usec + (double)tp.tv_sec; # endif } // =============================== Random Methods ================================== // The docs say: rand function returns a pseudorandom integer in the range 0 to RAND_MAX, // where RAND_MAX has value 32767=(2^15)-1, so these functions have very low resolution void gs_rseed ( gsuint i ) { srand ( unsigned(i) ); } # define RANDF01 ((float)rand()/(float)RAND_MAX) float gs_random () // in [0,1] { return RANDF01; } float gs_random ( float min, float max ) // in [min,max] { return min + (max-min)*RANDF01; } # define RANDD01 ((double)((a<<15)+b)/(double)1073741824) // factor is 2^30 double gs_randomd () { unsigned a = rand(); unsigned b = rand(); return RANDD01; } double gs_random ( double min, double max ) { unsigned a = rand(); unsigned b = rand(); return min + (max-min)*RANDD01; } int gs_random ( int min, int max ) { return min + (rand()%(max-min+1)); } //============================ End of File =================================
19.812715
90
0.5872
[ "shape" ]
2e82e6d2730857ed490594a6dfb2a30cada50ef3
2,054
cpp
C++
src/main/algorithms/cpp/tree/closest_binary_search_tree_value_ii_272/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/tree/closest_binary_search_tree_value_ii_272/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/tree/closest_binary_search_tree_value_ii_272/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
#include "../../head.h" #include "../tree.h" class Solution { public: std::vector<int> closestValues(TreeNode* root, float target, int k) { if (nullptr == root) { return {}; } std::vector<int> ans; dfsInOrder(root, ans); int mid = 0; float diff = std::abs(ans[0] - target); for (int idx = 1; idx < ans.size(); idx++) { float curDiff = std::abs(ans[idx] - target); if (diff > curDiff) { diff = curDiff; mid = idx; } } std::vector<int> res; int left = mid, right = mid + 1; while (k-- > 0) { float leftDiff = left > -1 ? std::abs(ans[left] - target) : INT_MAX; float rightDiff = right < ans.size() ? std::abs(ans[right] - target) : INT_MAX; if (leftDiff < rightDiff) { res.emplace_back(ans[left]); left--; } else { res.emplace_back(ans[right]); right++; } } return res; } void dfsInOrder(TreeNode* root, std::vector<int> & ans) { if (nullptr == root) { return; } dfsInOrder(root->left, ans); ans.emplace_back(root->val); dfsInOrder(root->right, ans); } }; #define TEST_MAIN #define PRINT_TO_SCREEN int main() { std::vector<int> nums{{4,2,5,1,3}}; TreeNode * root = new TreeNode(nums[0]); std::queue<TreeNode*> que; que.emplace(root); for (int idx = 1; idx < nums.size();) { TreeNode * cur = que.front(); cur->left = new TreeNode(nums[idx++]); que.emplace(cur->left); cur->right = new TreeNode(nums[idx++]); que.emplace(cur->right); } Solution obj; std::vector<int> ans = obj.closestValues(root, 3.714286, 2); #ifdef PRINT_TO_SCREEN for (int const num : ans) { std::cout << num << "\t"; } std::cout << "\n"; #endif std::cout << "TEST SUCCESSFULLY" << std::endl; return 0; }
27.026316
91
0.493184
[ "vector" ]
2e85e64342be928c0506873ee7d14e7dc892d8c1
6,402
cpp
C++
NeuronMap.cpp
brandontrabucco/self_organizing_map
c993e0095310310c6ccd129073d9d2064248e4c4
[ "MIT" ]
null
null
null
NeuronMap.cpp
brandontrabucco/self_organizing_map
c993e0095310310c6ccd129073d9d2064248e4c4
[ "MIT" ]
null
null
null
NeuronMap.cpp
brandontrabucco/self_organizing_map
c993e0095310310c6ccd129073d9d2064248e4c4
[ "MIT" ]
null
null
null
/* * NeuronMap.cpp * * Created on: Jul 14, 2016 * Author: trabucco */ #include "NeuronMap.h" NeuronMap::NeuronMap(int connectionsPerNeuron, int *_dim, unsigned int _type, double _width, double _learningRate, double _decayRate) { // TODO Auto-generated constructor stub type = _type; width = _width; learningRate = _learningRate; decayRate = _decayRate; dim = _dim; int nNeurons = 1; for (int i = 0; i < type; i++) { nNeurons *= dim[i]; } for (int i = 0; i < nNeurons; i++) { map.push_back(Neuron()); vector<Synapse> temp; for (int j = 0; j < connectionsPerNeuron; j++) { temp.push_back(Synapse()); } connections.push_back(temp); } } NeuronMap::~NeuronMap() { // TODO Auto-generated destructor stub } /** * * A recursive loop to simulate an n-dimensional vector space * */ void NeuronMap::activateNeuron(vector<double> input, int dimension, int index) { int idx; if (dimension < type) { for (int i = 0; i < dim[dimension]; i++) { idx = index * dim[dimension] + i; activateNeuron(input, dimension + 1, idx); if (dimension == (type - 1)) { double sum = 0; for (int l = 0; l < connections[idx].size(); l++) sum += connections[idx][l].get(input[l]); map[idx].get(sum); } } } else return; } /** * * A recursive loop to simulate an n-dimensional vector space * */ void NeuronMap::findLargestDistance(vector<double> input, double &bestDistance, int &bestIndex, int dimension, int index) { int idx; if (dimension < type) { for (int i = 0; i < dim[dimension]; i++) { idx = index * dim[dimension] + i; findLargestDistance(input, bestDistance, bestIndex, dimension + 1, idx); if (dimension == (type - 1)) { double temp = distance(connections[idx], input); if (temp < bestDistance) { bestDistance = temp; bestIndex = idx; } } } } else return; } /** * * A recursive loop to simulate an n-dimensional vector space * */ void NeuronMap::getCorrection(vector<double> input, int bestIndex, int dimension, int index, bool print) { int idx; if (dimension < type) { for (int i = 0; i < dim[dimension]; i++) { idx = index * dim[dimension] + i; getCorrection(input, bestIndex, dimension + 1, idx, print); if (dimension == (type - 1)) { for (int l = 0; l < connections[idx].size(); l++) { connections[idx][l].correction += learningRate * neighborhood(bestIndex, idx) * (input[l] - connections[idx][l].weight); } } } } else return; } /** * * A recursive loop to simulate an n-dimensional vector space * */ void NeuronMap::updateWeight(int dimension, int index) { int idx; if (dimension < type) { for (int i = 0; i < dim[dimension]; i++) { idx = index * dim[dimension] + i; updateWeight(dimension + 1, idx); if (dimension == (type - 1)) { for (int l = 0; l < connections[idx].size(); l++) { connections[idx][l].weight += connections[idx][l].correction; connections[idx][l].correction = 0; } } } } else return; } /** * * Calculate correction * Update weights every cycle * */ void NeuronMap::online(vector<double> input, bool print) { // find the winning node int bestIndex = 0; double bestDistance = distance(connections[0], input); findLargestDistance(input, bestDistance, bestIndex, 0, 0); // update the weights of all nodes in the map getCorrection(input, bestIndex, 0, 0, print); updateWeight(0, 0); width *= decayRate; learningRate *= decayRate; } /** * * Calculate and sum correction * Update weights every n cycles * */ void NeuronMap::batch(vector<double> input, bool print, bool update) { // find the winning node int bestIndex = 0; double bestDistance = distance(connections[0], input); findLargestDistance(input, bestDistance, bestIndex, 0, 0); // update the weights of all nodes in the map getCorrection(input, bestIndex, 0, 0, print); if (update) { updateWeight(0, 0); width *= decayRate; learningRate *= decayRate; } } /** * * Pass an input vector through the map * */ vector<double> NeuronMap::recognize(vector<double> input) { activateNeuron(input, 0, 0); vector<double> output; for (int i = 0; i < map.size(); i++) { output.push_back(map[i].activation); } return output; } /** * * Get Euclidean Distance between the input and weight vectors * */ double NeuronMap::distance(vector<Synapse> s, vector<double> t) { double sum = 0; if (s.size() == t.size()) { for (int i = 0; i < s.size(); i++) { sum += (s[i].weight - t[i]) * (s[i].weight - t[i]); } return sqrt(sum); } else return 0; } /** * * Weight Neurons with a Euclidean Distance * Neurons closer to winner in n-dim space have higher weight * */ double NeuronMap::neighborhood(int a, int b) { double positionA[type], positionB[type]; for (int i = 0; i < type; i++) { // get the linear ID of the element positionA[i] = (double)a; positionB[i] = (double)b; // calculate the dimensional modulation int modulo = 1; for (int j = 0; j <= i; j++) modulo *= dim[j]; // modulate the ID to repeat per dimension positionA[i] = (double)(((int)positionA[i]) % modulo); positionB[i] = (double)(((int)positionB[i]) % modulo); // calculate the dimension index for (int j = 0; j < i; j++) positionA[i] /= (double)dim[j]; positionA[i] = floor(positionA[i]); } double sum = 0; for (int i = 0; i < type; i++) sum += pow((positionA[i] - positionB[i]), 2); sum = sqrt(sum); return exp((-1*(sum * sum)) / (2 * width)); } struct tm *currentDate() { time_t t = time(NULL); struct tm *timeObject = localtime(&t); return timeObject; } /** * * Save the current instance of the network * Output a file of weights and biases * */ void NeuronMap::toFile(int iteration, int trainingSet, int epoch) { ostringstream fileName; fileName << "/stash/tlab/trabucco/ANN_Saves/" << (currentDate()->tm_year + 1900) << "-" << (currentDate()->tm_mon + 1) << "-" << currentDate()->tm_mday << "_Single-Core-SOM-Save-" << iteration << "_" << trainingSet << "-trainingSet_" << epoch << "-epoch_" << learningRate << "-learning_" << decayRate << "-decay.csv"; ofstream _file(fileName.str()); for (int i = 0; i < map.size(); i++) { for (int j = 0; j < connections[i].size(); j++) { if (j == (connections[i].size() - 1)) _file << connections[i][j].weight << endl; else _file << connections[i][j].weight << ", "; } } _file.close(); }
24.813953
135
0.628397
[ "vector" ]
2e88de0c4852c9c643af2f8481267635c5231244
5,859
hpp
C++
boost/geometry/extensions/gis/io/shapelib/shp_create_object.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2015-01-02T14:24:56.000Z
2015-01-02T14:25:17.000Z
boost/geometry/extensions/gis/io/shapelib/shp_create_object.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2019-01-13T23:45:51.000Z
2019-02-03T08:13:26.000Z
boost/geometry/extensions/gis/io/shapelib/shp_create_object.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
1
2016-05-29T13:41:15.000Z
2016-05-29T13:41:15.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-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) #ifndef BOOST_GEOMETRY_EXT_GIS_IO_SHAPELIB_SHP_CREATE_OBJECT_HPP #define BOOST_GEOMETRY_EXT_GIS_IO_SHAPELIB_SHP_CREATE_OBJECT_HPP #include <boost/mpl/assert.hpp> #include <boost/range.hpp> #include <boost/scoped_array.hpp> #include <boost/typeof/typeof.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/core/ring_type.hpp> #include <boost/geometry/algorithms/num_interior_rings.hpp> #include <boost/geometry/algorithms/num_points.hpp> #include <boost/geometry/views/box_view.hpp> #include <boost/geometry/views/segment_view.hpp> // Should be somewhere in your include path #include "shapefil.h" namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace shp_create_object { template <typename Point> struct shape_create_point { static inline SHPObject* apply(Point const& point) { double x = get<0>(point); double y = get<1>(point); int const parts = 0; return ::SHPCreateObject(SHPT_POINT, -1, 1, &parts, NULL, 1, &x, &y, NULL, NULL); } }; template <typename Range> static inline int range_to_part(Range const& range, double* x, double* y, int offset = 0) { x += offset; y += offset; for (typename boost::range_iterator<Range const>::type it = boost::begin(range); it != boost::end(range); ++it, ++x, ++y) { *x = get<0>(*it); *y = get<1>(*it); offset++; } return offset; } template <typename Range, int ShapeType> struct shape_create_range { static inline SHPObject* apply(Range const& range) { int const n = boost::size(range); boost::scoped_array<double> x(new double[n]); boost::scoped_array<double> y(new double[n]); range_to_part(range, x.get(), y.get()); int const parts = 0; return ::SHPCreateObject(ShapeType, -1, 1, &parts, NULL, n, x.get(), y.get(), NULL, NULL); } }; template <typename Polygon> struct shape_create_polygon { static inline void process_polygon(Polygon const& polygon, double* xp, double* yp, int* parts, int& offset, int& ring) { parts[ring++] = offset; offset = range_to_part(geometry::exterior_ring(polygon), xp, yp, offset); typename interior_return_type<Polygon const>::type rings = interior_rings(polygon); for (BOOST_AUTO_TPL(it, boost::begin(rings)); it != boost::end(rings); ++it) { parts[ring++] = offset; offset = range_to_part(*it, xp, yp, offset); } } static inline SHPObject* apply(Polygon const& polygon) { int const n = geometry::num_points(polygon); int const ring_count = 1 + geometry::num_interior_rings(polygon); boost::scoped_array<double> x(new double[n]); boost::scoped_array<double> y(new double[n]); boost::scoped_array<int> parts(new int[ring_count]); int ring = 0; int offset = 0; process_polygon(polygon, x.get(), y.get(), parts.get(), offset, ring); return ::SHPCreateObject(SHPT_POLYGON, -1, ring_count, parts.get(), NULL, n, x.get(), y.get(), NULL, NULL); } }; template <typename Geometry, typename AdaptedRange, int ShapeType> struct shape_create_adapted_range { static inline SHPObject* apply(Geometry const& geometry) { return shape_create_range<AdaptedRange, ShapeType>::apply(AdaptedRange(geometry)); } }; }} // namespace detail::shp_create_object #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template <typename Tag, typename Geometry> struct shp_create_object { BOOST_MPL_ASSERT_MSG ( false, NOT_OR_NOT_YET_IMPLEMENTED_FOR_THIS_GEOMETRY_TYPE , (Geometry) ); }; template <typename Point> struct shp_create_object<point_tag, Point> : detail::shp_create_object::shape_create_point<Point> {}; template <typename LineString> struct shp_create_object<linestring_tag, LineString> : detail::shp_create_object::shape_create_range<LineString, SHPT_ARC> {}; template <typename Ring> struct shp_create_object<ring_tag, Ring> : detail::shp_create_object::shape_create_range<Ring, SHPT_POLYGON> {}; template <typename Polygon> struct shp_create_object<polygon_tag, Polygon> : detail::shp_create_object::shape_create_polygon<Polygon> {}; template <typename Box> struct shp_create_object<box_tag, Box> : detail::shp_create_object::shape_create_adapted_range < Box, box_view<Box>, SHPT_POLYGON > {}; template <typename Segment> struct shp_create_object<segment_tag, Segment> : detail::shp_create_object::shape_create_adapted_range < Segment, segment_view<Segment>, SHPT_ARC > {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH // Redirect shapelib's SHPCreateObject to this boost::geometry::SHPCreateObject. // The only difference is their parameters, one just accepts a geometry template <typename Geometry> inline SHPObject* SHPCreateObject(Geometry const& geometry) { return dispatch::shp_create_object < typename tag<Geometry>::type, Geometry >::apply(geometry); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_EXT_GIS_IO_SHAPELIB_SHP_CREATE_OBJECT_HPP
25.697368
90
0.667179
[ "geometry" ]
2e8c0574035094a1f0ff557794b8e105f0217ecf
12,427
cpp
C++
qttools/src/shared/qtgradienteditor/qtgradientstopsmodel.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qttools/src/shared/qtgradienteditor/qtgradientstopsmodel.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qttools/src/shared/qtgradienteditor/qtgradientstopsmodel.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtgradientstopsmodel.h" #include <QtGui/QColor> QT_BEGIN_NAMESPACE class QtGradientStopPrivate { public: qreal m_position; QColor m_color; QtGradientStopsModel *m_model; }; qreal QtGradientStop::position() const { return d_ptr->m_position; } QColor QtGradientStop::color() const { return d_ptr->m_color; } QtGradientStopsModel *QtGradientStop::gradientModel() const { return d_ptr->m_model; } void QtGradientStop::setColor(const QColor &color) { d_ptr->m_color = color; } void QtGradientStop::setPosition(qreal position) { d_ptr->m_position = position; } QtGradientStop::QtGradientStop(QtGradientStopsModel *model) : d_ptr(new QtGradientStopPrivate()) { d_ptr->m_position = 0; d_ptr->m_color = Qt::white; d_ptr->m_model = model; } QtGradientStop::~QtGradientStop() { } class QtGradientStopsModelPrivate { QtGradientStopsModel *q_ptr; Q_DECLARE_PUBLIC(QtGradientStopsModel) public: QMap<qreal, QtGradientStop *> m_posToStop; QMap<QtGradientStop *, qreal> m_stopToPos; QMap<QtGradientStop *, bool> m_selection; QtGradientStop *m_current; }; QtGradientStopsModel::QtGradientStopsModel(QObject *parent) : QObject(parent), d_ptr(new QtGradientStopsModelPrivate) { d_ptr->q_ptr = this; d_ptr->m_current = 0; } QtGradientStopsModel::~QtGradientStopsModel() { clear(); } QtGradientStopsModel::PositionStopMap QtGradientStopsModel::stops() const { return d_ptr->m_posToStop; } QtGradientStop *QtGradientStopsModel::at(qreal pos) const { if (d_ptr->m_posToStop.contains(pos)) return d_ptr->m_posToStop[pos]; return 0; } QColor QtGradientStopsModel::color(qreal pos) const { PositionStopMap gradStops = stops(); if (gradStops.isEmpty()) return QColor::fromRgbF(pos, pos, pos, 1.0); if (gradStops.contains(pos)) return gradStops[pos]->color(); gradStops[pos] = 0; PositionStopMap::ConstIterator itStop = gradStops.constFind(pos); if (itStop == gradStops.constBegin()) { ++itStop; return itStop.value()->color(); } if (itStop == --gradStops.constEnd()) { --itStop; return itStop.value()->color(); } PositionStopMap::ConstIterator itPrev = itStop; PositionStopMap::ConstIterator itNext = itStop; --itPrev; ++itNext; double prevX = itPrev.key(); double nextX = itNext.key(); double coefX = (pos - prevX) / (nextX - prevX); QColor prevCol = itPrev.value()->color(); QColor nextCol = itNext.value()->color(); QColor newColor; newColor.setRgbF((nextCol.redF() - prevCol.redF() ) * coefX + prevCol.redF(), (nextCol.greenF() - prevCol.greenF()) * coefX + prevCol.greenF(), (nextCol.blueF() - prevCol.blueF() ) * coefX + prevCol.blueF(), (nextCol.alphaF() - prevCol.alphaF()) * coefX + prevCol.alphaF()); return newColor; } QList<QtGradientStop *> QtGradientStopsModel::selectedStops() const { return d_ptr->m_selection.keys(); } QtGradientStop *QtGradientStopsModel::currentStop() const { return d_ptr->m_current; } bool QtGradientStopsModel::isSelected(QtGradientStop *stop) const { if (d_ptr->m_selection.contains(stop)) return true; return false; } QtGradientStop *QtGradientStopsModel::addStop(qreal pos, const QColor &color) { qreal newPos = pos; if (pos < 0.0) newPos = 0.0; if (pos > 1.0) newPos = 1.0; if (d_ptr->m_posToStop.contains(newPos)) return 0; QtGradientStop *stop = new QtGradientStop(); stop->setPosition(newPos); stop->setColor(color); d_ptr->m_posToStop[newPos] = stop; d_ptr->m_stopToPos[stop] = newPos; emit stopAdded(stop); return stop; } void QtGradientStopsModel::removeStop(QtGradientStop *stop) { if (!d_ptr->m_stopToPos.contains(stop)) return; if (currentStop() == stop) setCurrentStop(0); selectStop(stop, false); emit stopRemoved(stop); qreal pos = d_ptr->m_stopToPos[stop]; d_ptr->m_stopToPos.remove(stop); d_ptr->m_posToStop.remove(pos); delete stop; } void QtGradientStopsModel::moveStop(QtGradientStop *stop, qreal newPos) { if (!d_ptr->m_stopToPos.contains(stop)) return; if (d_ptr->m_posToStop.contains(newPos)) return; if (newPos > 1.0) newPos = 1.0; else if (newPos < 0.0) newPos = 0.0; emit stopMoved(stop, newPos); const qreal oldPos = stop->position(); stop->setPosition(newPos); d_ptr->m_stopToPos[stop] = newPos; d_ptr->m_posToStop.remove(oldPos); d_ptr->m_posToStop[newPos] = stop; } void QtGradientStopsModel::swapStops(QtGradientStop *stop1, QtGradientStop *stop2) { if (stop1 == stop2) return; if (!d_ptr->m_stopToPos.contains(stop1)) return; if (!d_ptr->m_stopToPos.contains(stop2)) return; emit stopsSwapped(stop1, stop2); const qreal pos1 = stop1->position(); const qreal pos2 = stop2->position(); stop1->setPosition(pos2); stop2->setPosition(pos1); d_ptr->m_stopToPos[stop1] = pos2; d_ptr->m_stopToPos[stop2] = pos1; d_ptr->m_posToStop[pos1] = stop2; d_ptr->m_posToStop[pos2] = stop1; } void QtGradientStopsModel::changeStop(QtGradientStop *stop, const QColor &newColor) { if (!d_ptr->m_stopToPos.contains(stop)) return; if (stop->color() == newColor) return; emit stopChanged(stop, newColor); stop->setColor(newColor); } void QtGradientStopsModel::selectStop(QtGradientStop *stop, bool select) { if (!d_ptr->m_stopToPos.contains(stop)) return; bool selected = d_ptr->m_selection.contains(stop); if (select == selected) return; emit stopSelected(stop, select); if (select) d_ptr->m_selection[stop] = true; else d_ptr->m_selection.remove(stop); } void QtGradientStopsModel::setCurrentStop(QtGradientStop *stop) { if (stop && !d_ptr->m_stopToPos.contains(stop)) return; if (stop == currentStop()) return; emit currentStopChanged(stop); d_ptr->m_current = stop; } QtGradientStop *QtGradientStopsModel::firstSelected() const { PositionStopMap stopList = stops(); PositionStopMap::ConstIterator itStop = stopList.constBegin(); while (itStop != stopList.constEnd()) { QtGradientStop *stop = itStop.value(); if (isSelected(stop)) return stop; ++itStop; }; return 0; } QtGradientStop *QtGradientStopsModel::lastSelected() const { PositionStopMap stopList = stops(); PositionStopMap::ConstIterator itStop = stopList.constEnd(); while (itStop != stopList.constBegin()) { --itStop; QtGradientStop *stop = itStop.value(); if (isSelected(stop)) return stop; }; return 0; } QtGradientStopsModel *QtGradientStopsModel::clone() const { QtGradientStopsModel *model = new QtGradientStopsModel(); QMap<qreal, QtGradientStop *> stopsToClone = stops(); QMapIterator<qreal, QtGradientStop *> it(stopsToClone); while (it.hasNext()) { it.next(); model->addStop(it.key(), it.value()->color()); } // clone selection and current also return model; } void QtGradientStopsModel::moveStops(double newPosition) { QtGradientStop *current = currentStop(); if (!current) return; double newPos = newPosition; if (newPos > 1) newPos = 1; else if (newPos < 0) newPos = 0; if (newPos == current->position()) return; double offset = newPos - current->position(); QtGradientStop *first = firstSelected(); QtGradientStop *last = lastSelected(); if (first && last) { // multiselection double maxOffset = 1.0 - last->position(); double minOffset = -first->position(); if (offset > maxOffset) offset = maxOffset; else if (offset < minOffset) offset = minOffset; } if (offset == 0) return; bool forward = (offset > 0) ? false : true; PositionStopMap stopList; QList<QtGradientStop *> selected = selectedStops(); QListIterator<QtGradientStop *> it(selected); while (it.hasNext()) { QtGradientStop *stop = it.next(); stopList[stop->position()] = stop; } stopList[current->position()] = current; PositionStopMap::ConstIterator itStop = forward ? stopList.constBegin() : stopList.constEnd(); while (itStop != (forward ? stopList.constEnd() : stopList.constBegin())) { if (!forward) --itStop; QtGradientStop *stop = itStop.value(); double pos = stop->position() + offset; if (pos > 1) pos = 1; if (pos < 0) pos = 0; if (current == stop) pos = newPos; QtGradientStop *oldStop = at(pos); if (oldStop && !stopList.values().contains(oldStop)) removeStop(oldStop); moveStop(stop, pos); if (forward) ++itStop; } } void QtGradientStopsModel::clear() { QList<QtGradientStop *> stopsList = stops().values(); QListIterator<QtGradientStop *> it(stopsList); while (it.hasNext()) removeStop(it.next()); } void QtGradientStopsModel::clearSelection() { QList<QtGradientStop *> stopsList = selectedStops(); QListIterator<QtGradientStop *> it(stopsList); while (it.hasNext()) selectStop(it.next(), false); } void QtGradientStopsModel::flipAll() { QMap<qreal, QtGradientStop *> stopsMap = stops(); QMapIterator<qreal, QtGradientStop *> itStop(stopsMap); itStop.toBack(); QMap<QtGradientStop *, bool> swappedList; while (itStop.hasPrevious()) { itStop.previous(); QtGradientStop *stop = itStop.value(); if (swappedList.contains(stop)) continue; const double newPos = 1.0 - itStop.key(); if (stopsMap.contains(newPos)) { QtGradientStop *swapped = stopsMap.value(newPos); swappedList[swapped] = true; swapStops(stop, swapped); } else { moveStop(stop, newPos); } } } void QtGradientStopsModel::selectAll() { QList<QtGradientStop *> stopsList = stops().values(); QListIterator<QtGradientStop *> it(stopsList); while (it.hasNext()) selectStop(it.next(), true); } void QtGradientStopsModel::deleteStops() { QList<QtGradientStop *> selected = selectedStops(); QListIterator<QtGradientStop *> itSel(selected); while (itSel.hasNext()) { QtGradientStop *stop = itSel.next(); removeStop(stop); } QtGradientStop *current = currentStop(); if (current) removeStop(current); } QT_END_NAMESPACE
26.440426
98
0.64376
[ "model" ]
2e95862a414722ed02e08a3ab5f615aec96087d2
1,879
cpp
C++
examples/bench_replace.cpp
jbaldwin/libchain
fcceaa141c4aa12abd588f1b9032c4a8c48fd0b4
[ "MIT" ]
3
2020-09-03T20:05:24.000Z
2022-02-03T20:49:33.000Z
examples/bench_replace.cpp
jbaldwin/libchain
fcceaa141c4aa12abd588f1b9032c4a8c48fd0b4
[ "MIT" ]
8
2020-11-12T18:13:19.000Z
2021-12-05T18:58:28.000Z
examples/bench_replace.cpp
jbaldwin/libchain
fcceaa141c4aa12abd588f1b9032c4a8c48fd0b4
[ "MIT" ]
null
null
null
#include <chrono> #include <iostream> #include <mutex> #include <string> #include <thread> #include <vector> #include <chain/chain.hpp> int main() { using namespace std::string_literals; using namespace chain; static constexpr size_t ITERATIONS = 10'000'000; std::string input = "herp derp cherp merp derp derp"s; std::mutex cout_guard{}; auto executor_func([&]() { { auto start1 = std::chrono::steady_clock::now(); for (size_t i = 0; i < ITERATIONS; ++i) { std::string data = input; str::replace<str::case_t::sensitive>(data, "derp", "ferp", 2); } auto end1 = std::chrono::steady_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end1 - start1); std::lock_guard<std::mutex> g{cout_guard}; std::cout << "replace(sensitive): " << elapsed.count() << "ms\n"; } { auto start1 = std::chrono::steady_clock::now(); for (size_t i = 0; i < ITERATIONS; ++i) { std::string data = input; str::replace<str::case_t::insensitive>(data, "DERP", "ferp", 2); } auto end1 = std::chrono::steady_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end1 - start1); std::lock_guard<std::mutex> g{cout_guard}; std::cout << "replace(insensitive): " << elapsed.count() << "ms\n"; } }); std::vector<std::thread> workers; for (size_t i = 0; i < 8; ++i) { workers.emplace_back(std::thread{executor_func}); } for (auto& worker : workers) { worker.join(); } return 0; }
28.469697
119
0.508781
[ "vector" ]
2e976bcff7f67be7c9e493a7f6a6698293127942
458
hh
C++
include/blaze/operation/file_scan.hh
anujjamwal/blaze
58da3110ce1d1abdf0a04f36f92db7f1379a1fec
[ "Apache-2.0" ]
null
null
null
include/blaze/operation/file_scan.hh
anujjamwal/blaze
58da3110ce1d1abdf0a04f36f92db7f1379a1fec
[ "Apache-2.0" ]
null
null
null
include/blaze/operation/file_scan.hh
anujjamwal/blaze
58da3110ce1d1abdf0a04f36f92db7f1379a1fec
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include "blaze/operation/base_operation.hh" namespace blaze { namespace operation { /** * @brief Operation to read the data from one or more files. * */ class FileScanOperation : BaseOperation { private: std::vector<std::string> _paths; std::vector<std::string> _field_selection; public: std::string ToString(); }; } // namespace operation } // namespace blaze
19.913043
64
0.637555
[ "vector" ]
2ea0a6c457db49ef26131be7576faeefe5c7fbac
355
cpp
C++
src/IntrospectionView/FloatElement.cpp
kyle-piddington/ShaderTool
c753a53bde6eab942da617adab9483c945f27f51
[ "MIT" ]
2
2016-03-11T00:07:33.000Z
2016-04-14T22:35:44.000Z
src/IntrospectionView/FloatElement.cpp
kyle-piddington/ShaderTool
c753a53bde6eab942da617adab9483c945f27f51
[ "MIT" ]
null
null
null
src/IntrospectionView/FloatElement.cpp
kyle-piddington/ShaderTool
c753a53bde6eab942da617adab9483c945f27f51
[ "MIT" ]
1
2021-02-18T14:42:03.000Z
2021-02-18T14:42:03.000Z
#include "FloatElement.h" #include <imgui.h> FloatElement::FloatElement(std::shared_ptr<FloatObjectController> controller): ProgramManagerElement(controller->getName()), ctrl(controller) { } void FloatElement::render() { float val = ctrl->getFloat(); if(ImGui::DragFloat(ctrl->getName().c_str(),&val,0.01)) { ctrl->bind(val); } }
20.882353
78
0.687324
[ "render" ]
2ea275ffc500ed55aef00cbe628a4f2a04a27a68
6,590
cc
C++
src/search_local/index_storage/common/plugin_sync.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
3
2021-08-18T09:59:42.000Z
2021-09-07T03:11:28.000Z
src/search_local/index_storage/common/plugin_sync.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
src/search_local/index_storage/common/plugin_sync.cc
jdisearch/isearch1
272bd4ab0dc82d9e33c8543474b1294569947bb3
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <sys/un.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <sys/socket.h> #include "plugin_agent_mgr.h" #include "plugin_sync.h" #include "plugin_unit.h" #include "poll_thread.h" #include "log.h" #include "stat_dtc.h" #include "mem_check.h" //static int statEnable=0; static StatItemU32 statPluginAcceptCount; static StatItemU32 statPluginCurConnCount; extern "C" { extern unsigned int get_local_ip(); } PluginSync::PluginSync(PluginDecoderUnit *plugin_decoder, int fd, void *peer, int peer_size) : PollerObject(plugin_decoder->owner_thread(), fd), _plugin_stage(PLUGIN_IDLE), owner(plugin_decoder), _plugin_request(NULL), _worker_notifier(NULL), _plugin_receiver(fd, PluginAgentManager::Instance()->get_dll()), _plugin_sender(fd, PluginAgentManager::Instance()->get_dll()) { _addr_len = peer_size; _addr = MALLOC(peer_size); memcpy((char *)_addr, (char *)peer, peer_size); ++statPluginAcceptCount; ++statPluginCurConnCount; } PluginSync::~PluginSync(void) { --statPluginCurConnCount; if (PLUGIN_PROC == _plugin_stage) { _plugin_request->_plugin_sync = NULL; } else { DELETE(_plugin_request); } FREE_CLEAR(_addr); } int PluginSync::create_request(void) { if (NULL != _plugin_request) { DELETE(_plugin_request); _plugin_request = NULL; } NEW(PluginStream(this, PluginAgentManager::Instance()->get_dll()), _plugin_request); if (NULL == _plugin_request) { log_error("create plugin request object failed, msg:%s", strerror(errno)); return -1; } //set plugin request info _plugin_request->_skinfo.sockfd = netfd; _plugin_request->_skinfo.type = SOCK_STREAM; _plugin_request->_skinfo.local_ip = get_local_ip(); _plugin_request->_skinfo.local_port = 0; _plugin_request->_skinfo.remote_ip = ((struct sockaddr_in *)_addr)->sin_addr.s_addr; _plugin_request->_skinfo.remote_port = ((struct sockaddr_in *)_addr)->sin_port; _plugin_request->_incoming_notifier = owner->get_incoming_notifier(); return 0; } int PluginSync::Attach() { if (create_request() != 0) { log_error("create request object failed"); return -1; } //get worker notifier _worker_notifier = PluginAgentManager::Instance()->get_worker_notifier(); if (NULL == _worker_notifier) { log_error("get worker notifier failed."); return -1; } enable_input(); if (attach_poller() == -1) { return -1; } attach_timer(owner->idle_list()); _plugin_stage = PLUGIN_IDLE; return 0; } int PluginSync::recv_request() { disable_timer(); int ret_stage = _plugin_receiver.recv(_plugin_request); switch (ret_stage) { default: case NET_FATAL_ERROR: return -1; case NET_IDLE: attach_timer(owner->idle_list()); _plugin_stage = PLUGIN_IDLE; break; case NET_RECVING: //如果收到部分包,则需要加入idle list, 防止该连接挂死 attach_timer(owner->idle_list()); _plugin_stage = PLUGIN_RECV; break; case NET_RECV_DONE: _plugin_request->set_time_info(); if (_worker_notifier->Push(_plugin_request) != 0) { log_error("push plugin request failed, fd[%d]", netfd); return -1; } _plugin_stage = PLUGIN_PROC; break; } return 0; } int PluginSync::proc_multi_request(void) { _plugin_receiver.set_stage(NET_IDLE); switch (_plugin_receiver.proc_remain_packet(_plugin_request)) { default: case NET_FATAL_ERROR: return -1; case NET_RECVING: _plugin_stage = PLUGIN_RECV; _plugin_sender.set_stage(NET_IDLE); _plugin_receiver.set_stage(NET_RECVING); break; case NET_RECV_DONE: _plugin_request->set_time_info(); if (_worker_notifier->Push(_plugin_request) != 0) { log_error("push plugin request failed, fd[%d]", netfd); return -1; } _plugin_stage = PLUGIN_PROC; break; } return 0; } int PluginSync::Response(void) { if (_plugin_request->recv_only()) { goto proc_multi; } switch (_plugin_sender.send(_plugin_request)) { default: case NET_FATAL_ERROR: return -1; case NET_SENDING: _plugin_stage = PLUGIN_SEND; enable_output(); return 0; case NET_SEND_DONE: break; } proc_multi: //multi request process logic if (_plugin_request->multi_packet()) { if (proc_multi_request() != 0) { return -1; } } else { _plugin_request->release_buffer(); _plugin_sender.set_stage(NET_IDLE); _plugin_receiver.set_stage(NET_IDLE); _plugin_stage = PLUGIN_IDLE; } //防止多一次output事件触发 disable_output(); enable_input(); attach_timer(owner->idle_list()); return 0; } void PluginSync::input_notify(void) { log_debug("enter input_notify!"); if (_plugin_stage == PLUGIN_IDLE || _plugin_stage == PLUGIN_RECV) { if (recv_request() < 0) { delete this; return; } } else /* receive input events again. */ { /* check whether client close connection. */ if (check_link_status()) { log_debug("client close connection, delete PluginSync obj, plugin stage=%d", _plugin_stage); delete this; return; } else { DisableInput(); } } apply_events(); return; } void PluginSync::output_notify(void) { if (_plugin_stage == PLUGIN_SEND) { if (Response() < 0) { delete this; } } else { disable_output(); log_info("Spurious PluginSync::output_notify, plugin stage=%d", _plugin_stage); } return; }
23.963636
159
0.56783
[ "object" ]
2ea3422728acb635225fecb9c949c234fb31ea1d
21,401
cpp
C++
C++code/inifile/inifile.cpp
xhyangxianjun/something
864c8c1cb8afd72cf9e15f78f112d1d84138204a
[ "MIT" ]
2
2019-04-30T06:24:46.000Z
2020-10-19T09:27:17.000Z
C++code/inifile/inifile.cpp
xhyangxianjun/something
864c8c1cb8afd72cf9e15f78f112d1d84138204a
[ "MIT" ]
null
null
null
C++code/inifile/inifile.cpp
xhyangxianjun/something
864c8c1cb8afd72cf9e15f78f112d1d84138204a
[ "MIT" ]
1
2021-09-06T02:44:23.000Z
2021-09-06T02:44:23.000Z
/* Copyright (c) 2014-2019 WinnerHust * 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. * * 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 <stdlib.h> #include <stdio.h> #include <ctype.h> #include <iostream> #include <fstream> #include "inifile.h" namespace inifile { // 构造函数,会初始化注释字符集合flags_(容器),目前只使用#和;作为注释前缀 IniFile::IniFile() :commentDelimiter("#") { } //解析一行数据,得到键值 /* --------------------------------------------------------------------------*/ /** * @brief parse * * @param content 数据源指针 * @param key 键名 * @param value 键值 * @param c 分隔符 * * @return bool */ /* ----------------------------------------------------------------------------*/ bool IniFile::parse(const string &content, string *key, string *value) { return split(content, "=", key, value); } int IniFile::UpdateSection(const string &cleanLine, const string &comment, const string &rightComment, IniSection **section) { IniSection *newSection; // 查找右中括号 size_t index = cleanLine.find_first_of(']'); if (index == string::npos) { errMsg = string("no matched ] found"); return ERR_UNMATCHED_BRACKETS; } int len = index - 1; // 若段名为空,继续下一行 if (len <= 0) { errMsg = string("section name is empty"); return ERR_SECTION_EMPTY; } // 取段名 string s(cleanLine, 1, len); trim(s); //检查段是否已存在 if (getSection(s) != NULL) { errMsg = string("section ") + s + string("already exist"); return ERR_SECTION_ALREADY_EXISTS; } // 申请一个新段,由于map容器会自动排序,打乱原有顺序,因此改用vector存储(sections_vt) newSection = new IniSection(); // 填充段名 newSection->name = s; // 填充段开头的注释 newSection->comment = comment; newSection->rightComment = rightComment; sections_vt.push_back(newSection); *section = newSection; return 0; } int IniFile::AddKeyValuePair(const string &cleanLine, const string &comment, const string &rightComment, IniSection *section) { string key, value; if (!parse(cleanLine, &key, &value)) { errMsg = string("parse line failed:") + cleanLine; return ERR_PARSE_KEY_VALUE_FAILED; } IniItem item; item.key = key; item.value = value; item.comment = comment; item.rightComment = rightComment; section->items.push_back(item); return 0; } int IniFile::Load(const string &filePath) { int err; string line; // 带注释的行 string cleanLine; // 去掉注释后的行 string comment; string rightComment; IniSection *currSection = NULL; // 初始化一个字段指针 release(); iniFilePath = filePath; //_CreatFile(iniFilePath); std::ifstream ifs(iniFilePath); if (!ifs.is_open()) { errMsg = string("open") + iniFilePath+ string(" file failed"); return ERR_OPEN_FILE_FAILED; } //增加默认段,即 无名段"" currSection = new IniSection(); currSection->name = ""; sections_vt.push_back(currSection); // 每次读取一行内容到line while (std::getline(ifs, line)) { trim(line); // step 0,空行处理,如果长度为0,说明是空行,添加到comment,当作是注释的一部分 if (line.length() <= 0) { comment += delim; continue; } // step 1 // 如果行首不是注释,查找行尾是否存在注释 // 如果该行以注释开头,添加到comment,跳过当前循环,continue if (IsCommentLine(line)) { comment += line + delim; continue; } // 如果行首不是注释,查找行尾是否存在注释,若存在,切割该行,将注释内容添加到rightComment split(line, commentDelimiter, &cleanLine, &rightComment); // step 2,判断line内容是否为段或键 //段开头查找 [ if (cleanLine[0] == '[') { err = UpdateSection(cleanLine, comment, rightComment, &currSection); } else { // 如果该行是键值,添加到section段的items容器 err = AddKeyValuePair(cleanLine, comment, rightComment, currSection); } if (err != 0) { ifs.close(); return err; } // comment清零 comment = ""; rightComment = ""; } ifs.close(); return 0; } int IniFile::Save() { return SaveAs(iniFilePath); } int IniFile::SaveAs(const string &filePath) { string data = ""; /* 载入section数据 */ for (IniSection_it sect = sections_vt.begin(); sect != sections_vt.end(); ++sect) { if ((*sect)->comment != "") { data += (*sect)->comment; } if ((*sect)->name != "") { data += string("[") + (*sect)->name + string("]"); data += delim; } if ((*sect)->rightComment != "") { data += " " + commentDelimiter +(*sect)->rightComment; } /* 载入item数据 */ for (IniSection::IniItem_it item = (*sect)->items.begin(); item != (*sect)->items.end(); ++item) { if (item->comment != "") { data += item->comment; if (data[data.length()-1] != '\n') { data += delim; } } data += item->key + "=" + item->value; if (item->rightComment != "") { data += " " + commentDelimiter + item->rightComment; } if (data[data.length()-1] != '\n') { data += delim; } } } std::ofstream ofs(filePath); ofs << data; ofs.close(); return 0; } IniSection *IniFile::getSection(const string &section /*=""*/) { for (IniSection_it it = sections_vt.begin(); it != sections_vt.end(); ++it) { if ((*it)->name == section) { return *it; } } return NULL; } int IniFile::GetSections(vector<string> *sections) { for (IniSection_it it = sections_vt.begin(); it != sections_vt.end(); ++it) { sections->push_back((*it)->name); } return sections->size(); } int IniFile::GetSectionNum() { return sections_vt.size(); } int IniFile::GetStringValue(const string &section, const string &key, string *value) { return getValue(section, key, value); } int IniFile::GetIntValue(const string &section, const string &key, int *intValue) { int err; string strValue; err = getValue(section, key, &strValue); *intValue = atoi(strValue.c_str()); return err; } int IniFile::GetDoubleValue(const string &section, const string &key, double *value) { int err; string strValue; err = getValue(section, key, &strValue); *value = atof(strValue.c_str()); return err; } int IniFile::GetBoolValue(const string &section, const string &key, bool *value) { int err; string strValue; err = getValue(section, key, &strValue); if (StringCmpIgnoreCase(strValue, "true") || StringCmpIgnoreCase(strValue, "1")) { *value = true; } else if (StringCmpIgnoreCase(strValue, "false") || StringCmpIgnoreCase(strValue, "0")) { *value = false; } return err; } /* 获取section段第一个键为key的string值,成功返回获取的值,否则返回默认值 */ void IniFile::GetStringValueOrDefault(const string &section, const string &key, string *value, const string &defaultValue) { if (GetStringValue(section, key, value) != 0) { *value = defaultValue; } return; } /* 获取section段第一个键为key的int值,成功返回获取的值,否则返回默认值 */ void IniFile::GetIntValueOrDefault(const string &section, const string &key, int *value, int defaultValue) { if (GetIntValue(section, key, value) != 0) { *value = defaultValue; } return; } /* 获取section段第一个键为key的double值,成功返回获取的值,否则返回默认值 */ void IniFile::GetDoubleValueOrDefault(const string &section, const string &key, double *value, double defaultValue) { if (GetDoubleValue(section, key, value) != 0) { *value = defaultValue; } return; } /* 获取section段第一个键为key的bool值,成功返回获取的值,否则返回默认值 */ void IniFile::GetBoolValueOrDefault(const string &section, const string &key, bool *value, bool defaultValue) { if (GetBoolValue(section, key, value) != 0) { *value = defaultValue; } return; } /* 获取注释,如果key=""则获取段注释 */ int IniFile::GetComment(const string &section, const string &key, string *comment) { IniSection *sect = getSection(section); if (sect == NULL) { errMsg = string("not find the section ")+section; return ERR_NOT_FOUND_SECTION; } if (key == "") { *comment = sect->comment; return RET_OK; } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { *comment = it->comment; return RET_OK; } } errMsg = string("not find the key ")+section; return ERR_NOT_FOUND_KEY; } /* 获取行尾注释,如果key=""则获取段的行尾注释 */ int IniFile::GetRightComment(const string &section, const string &key, string *rightComment) { IniSection *sect = getSection(section); if (sect == NULL) { errMsg = string("not find the section ")+section; return ERR_NOT_FOUND_SECTION; } if (key == "") { *rightComment = sect->rightComment; return RET_OK; } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { *rightComment = it->rightComment; return RET_OK; } } errMsg = string("not find the key ")+key; return ERR_NOT_FOUND_KEY; } int IniFile::getValue(const string &section, const string &key, string *value) { string comment; return getValue(section, key, value, &comment); } int IniFile::getValue(const string &section, const string &key, string *value, string *comment) { IniSection *sect = getSection(section); if (sect == NULL) { errMsg = string("not find the section ")+section; return ERR_NOT_FOUND_SECTION; } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { *value = it->value; *comment = it->comment; return RET_OK; } } errMsg = string("not find the key ")+key; return ERR_NOT_FOUND_KEY; } int IniFile::GetValues(const string &section, const string &key, vector<string> *values) { vector<string> comments; return GetValues(section, key, values, &comments); } int IniFile::GetValues(const string &section, const string &key, vector<string> *values, vector<string> *comments) { string value, comment; values->clear(); comments->clear(); IniSection *sect = getSection(section); if (sect == NULL) { errMsg = string("not find the section ")+section; return ERR_NOT_FOUND_SECTION; } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { value = it->value; comment = it->comment; values->push_back(value); comments->push_back(comment); } } if (values->size() == 0) { errMsg = string("not find the key ")+key; return ERR_NOT_FOUND_KEY; } return RET_OK; } bool IniFile::HasSection(const string &section) { return (getSection(section) != NULL); } bool IniFile::HasKey(const string &section, const string &key) { IniSection *sect = getSection(section); if (sect != NULL) { for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { return true; } } } return false; } int IniFile::setValue(const string &section, const string &key, const string &value, const string &comment /*=""*/) { IniSection *sect = getSection(section); string comt = comment; if (comt != "") { comt = commentDelimiter + comt; } if (sect == NULL) { //如果段不存在,新建一个 sect = new IniSection(); if (sect == NULL) { errMsg = string("no enough memory!"); return ERR_NO_ENOUGH_MEMORY; } sect->name = section; if (sect->name == "") { // 确保空section在第一个 sections_vt.insert(sections_vt.begin(), sect); } else { sections_vt.push_back(sect); } } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { it->value = value; it->comment = comt; return RET_OK; } } // not found key IniItem item; item.key = key; item.value = value; item.comment = comt; sect->items.push_back(item); return RET_OK; } int IniFile::SetStringValue(const string &section, const string &key, const string &value) { return setValue(section, key, value); } int IniFile::SetIntValue(const string &section, const string &key, int value) { char buf[64] = {0}; snprintf(buf, sizeof(buf), "%d", value); return setValue(section, key, buf); } int IniFile::SetDoubleValue(const string &section, const string &key, double value) { char buf[64] = {0}; snprintf(buf, sizeof(buf), "%f", value); return setValue(section, key, buf); } int IniFile::SetBoolValue(const string &section, const string &key, bool value) { if (value) { return setValue(section, key, "true"); } else { return setValue(section, key, "false"); } } int IniFile::SetComment(const string &section, const string &key, const string &comment) { IniSection *sect = getSection(section); if (sect == NULL) { errMsg = string("Not find the section ")+section; return ERR_NOT_FOUND_SECTION; } if (key == "") { sect->comment = comment; return RET_OK; } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { it->comment = comment; return RET_OK; } } errMsg = string("not find the key ")+key; return ERR_NOT_FOUND_KEY; } int IniFile::SetRightComment(const string &section, const string &key, const string &rightComment) { IniSection *sect = getSection(section); if (sect == NULL) { errMsg = string("Not find the section ")+section; return ERR_NOT_FOUND_SECTION; } if (key == "") { sect->rightComment = rightComment; return RET_OK; } for (IniSection::IniItem_it it = sect->begin(); it != sect->end(); ++it) { if (it->key == key) { it->rightComment = rightComment; return RET_OK; } } errMsg = string("not find the key ")+key; return ERR_NOT_FOUND_KEY; } void IniFile::SetCommentDelimiter(const string &delimiter) { commentDelimiter = delimiter; } void IniFile::DeleteSection(const string &section) { for (IniSection_it it = sections_vt.begin(); it != sections_vt.end(); ) { if ((*it)->name == section) { delete *it; it = sections_vt.erase(it); break; } else { it++; } } } void IniFile::DeleteKey(const string &section, const string &key) { IniSection *sect = getSection(section); if (sect != NULL) { for (IniSection::IniItem_it it = sect->begin(); it != sect->end();) { if (it->key == key) { it = sect->items.erase(it); break; } else { it++; } } } } /*-------------------------------------------------------------------------*/ /** @brief release: 释放全部资源,清空容器 @param none @return none */ /*--------------------------------------------------------------------------*/ void IniFile::release() { iniFilePath = ""; for (IniSection_it it = sections_vt.begin(); it != sections_vt.end(); ++it) { delete (*it); // 清除section } sections_vt.clear(); } /*-------------------------------------------------------------------------*/ /** @brief 判断是否是注释 @param str 一个string变量 @return 如果是注释则为真 */ /*--------------------------------------------------------------------------*/ bool IniFile::IsCommentLine(const string &str) { return StartWith(str, commentDelimiter); } /*-------------------------------------------------------------------------*/ /** @brief print for debug @param none @return none */ /*--------------------------------------------------------------------------*/ void IniFile::print() { printf("############ print start ############\n"); printf("filePath:[%s]\n", iniFilePath.c_str()); printf("commentDelimiter:[%s]\n", commentDelimiter.c_str()); for (IniSection_it it = sections_vt.begin(); it != sections_vt.end(); ++it) { printf("comment :[\n%s]\n", (*it)->comment.c_str()); printf("section :\n[%s]\n", (*it)->name.c_str()); if ((*it)->rightComment != "") { printf("rightComment:\n%s", (*it)->rightComment.c_str()); } for (IniSection::IniItem_it i = (*it)->items.begin(); i != (*it)->items.end(); ++i) { printf(" comment :[\n%s]\n", i->comment.c_str()); printf(" parm :%s=%s\n", i->key.c_str(), i->value.c_str()); if (i->rightComment != "") { printf(" rcomment:[\n%s]\n", i->rightComment.c_str()); } } } printf("############ print end ############\n"); return; } const string & IniFile::GetErrMsg() { return errMsg; } bool IniFile::StartWith(const string &str, const string &prefix) { if (strncmp(str.c_str(), prefix.c_str(), prefix.size()) == 0) { return true; } return false; } void IniFile::trimleft(string &str, char c /*=' '*/) { int len = str.length(); int i = 0; while (str[i] == c && str[i] != '\0') { i++; } if (i != 0) { str = string(str, i, len - i); } } void IniFile::trimright(string &str, char c /*=' '*/) { int i = 0; int len = str.length(); for (i = len - 1; i >= 0; --i) { if (str[i] != c) { break; } } str = string(str, 0, i + 1); } bool IniFile::isExist(std::string file) { std::fstream _file; _file.open(file, std::ios::in); if (!_file) { return false; } else { return true; } _file.close(); return false; } void IniFile::_CreatFile(std::string file) { if (isExist(file)) return; std::ofstream ofile; ofile.open(file); ofile.close(); } /*-------------------------------------------------------------------------*/ /** @brief trim,整理一行字符串,去掉首尾空格 @param str string变量 */ /*--------------------------------------------------------------------------*/ void IniFile::trim(string &str) { int len = str.length(); int i = 0; while ((i < len) && isspace(str[i]) && (str[i] != '\0')) { i++; } if (i != 0) { str = string(str, i, len - i); } len = str.length(); for (i = len - 1; i >= 0; --i) { if (!isspace(str[i])) { break; } } str = string(str, 0, i + 1); } /*-------------------------------------------------------------------------*/ /** @brief split,用分隔符切割字符串 @param str 输入字符串 @param left_str 分隔后得到的左字符串 @param right_str 分隔后得到的右字符串(不包含seperator) @param seperator 分隔符 @return pos */ /*--------------------------------------------------------------------------*/ bool IniFile::split(const string &str, const string &sep, string *pleft, string *pright) { size_t pos = str.find(sep); string left, right; if (pos != string::npos) { left = string(str, 0, pos); right = string(str, pos+1); trim(left); trim(right); *pleft = left; *pright = right; return true; } else { left = str; right = ""; trim(left); *pleft = left; *pright = right; return false; } } bool IniFile::StringCmpIgnoreCase(const string &str1, const string &str2) { string a = str1; string b = str2; transform(a.begin(), a.end(), a.begin(), towupper); transform(b.begin(), b.end(), b.begin(), towupper); return (a == b); } } /* namespace inifile */
24.74104
115
0.551329
[ "vector", "transform" ]
2ea45c0f0d70d348acfbfcb55b443a3bc80c0806
5,146
cpp
C++
CheckSDL/CheckSDL/ImportStatus.cpp
tandasat/CheckSDL
ddca581ccf521b9cab37f3a627a59aec30b07503
[ "MIT" ]
16
2015-02-13T02:47:35.000Z
2019-12-05T01:40:33.000Z
CheckSDL/CheckSDL/ImportStatus.cpp
tandasat/CheckSDL
ddca581ccf521b9cab37f3a627a59aec30b07503
[ "MIT" ]
null
null
null
CheckSDL/CheckSDL/ImportStatus.cpp
tandasat/CheckSDL
ddca581ccf521b9cab37f3a627a59aec30b07503
[ "MIT" ]
10
2015-03-25T14:13:27.000Z
2021-10-05T08:58:58.000Z
// // This module implements a class responsible for extracting interesting // characteristics from an import section // #include "stdafx.h" #include "ImportStatus.h" // C/C++ standard headers // Other external headers // Windows headers // Project headers #include "BannedFunctions.h" //////////////////////////////////////////////////////////////////////////////// // // macro utilities // //////////////////////////////////////////////////////////////////////////////// // // constants and macros // //////////////////////////////////////////////////////////////////////////////// // // types // //////////////////////////////////////////////////////////////////////////////// // // prototypes // namespace { bool IsMSVB( const char* ModuleName); bool IsMSCOREE( const char* ModuleName); bool IsBannedRequiredFunction( const char* FunctionName); bool IsBannedRecommendedFunction( const char* FunctionName); bool IsHeapProtectionFunction( const char* FunctionName); } // End of namespace {unnamed} //////////////////////////////////////////////////////////////////////////////// // // variables // //////////////////////////////////////////////////////////////////////////////// // // implementations // ImportStatus::ImportStatus( void* BaseAddress) : m_isVB6PE(false) , m_isManagedPE(false) , m_isMSVBVM60Imported(false) , m_isMSCOREEImported(false) , m_isHeapProtectionFunctionImported(false) { auto bytesOfDirectoryEntry = 0ul; auto importDesc = static_cast<PIMAGE_IMPORT_DESCRIPTOR>( ::ImageDirectoryEntryToData(BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &bytesOfDirectoryEntry)); if (!importDesc) { throw std::runtime_error("No Import Directory."); } const auto baseAddr = reinterpret_cast<std::uintptr_t>(BaseAddress); auto numberOfImportedModules = 0ul; for (; importDesc->OriginalFirstThunk; ++importDesc, ++numberOfImportedModules) { ProcessImportedModule(baseAddr, importDesc); } m_isVB6PE = (m_isMSVBVM60Imported && numberOfImportedModules == 1); m_isManagedPE = (m_isMSCOREEImported && numberOfImportedModules == 1); } bool ImportStatus::isVB6PE() const { return m_isVB6PE; } bool ImportStatus::isManagedPE() const { return m_isManagedPE; } bool ImportStatus::isHeapProtectionFunctionImported() const { return m_isHeapProtectionFunctionImported; } const std::vector<std::string>& ImportStatus::getImportedBannedFunctionsRequired() const { return m_importedBannedFunctionsRequired; } const std::vector<std::string>& ImportStatus::getimportedBannedFunctionsRecommended() const { return m_importedBannedFunctionsRecommended; } void ImportStatus::ProcessImportedModule( std::uintptr_t BaseAddress, const PIMAGE_IMPORT_DESCRIPTOR ImportDesc) { const auto moduleName = reinterpret_cast<char*>(BaseAddress + ImportDesc->Name); m_isMSVBVM60Imported = m_isMSVBVM60Imported || IsMSVB(moduleName); m_isMSCOREEImported = m_isMSCOREEImported || IsMSCOREE(moduleName); auto thunkData = reinterpret_cast<PIMAGE_THUNK_DATA>( BaseAddress + ImportDesc->OriginalFirstThunk); for (; thunkData->u1.Ordinal; ++thunkData) { ProcessImportedFunction(BaseAddress, thunkData); } } void ImportStatus::ProcessImportedFunction( std::uintptr_t BaseAddress, const PIMAGE_THUNK_DATA ThunkData) { if (IMAGE_SNAP_BY_ORDINAL(ThunkData->u1.Ordinal)) { return; } const auto importByName = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>( BaseAddress + ThunkData->u1.AddressOfData); const auto functionName = reinterpret_cast<char*>( importByName->Name); if (IsBannedRequiredFunction(functionName)) { m_importedBannedFunctionsRequired.push_back(functionName); } if (IsBannedRecommendedFunction(functionName)) { m_importedBannedFunctionsRecommended.push_back(functionName); } m_isHeapProtectionFunctionImported = m_isHeapProtectionFunctionImported || IsHeapProtectionFunction(functionName); } namespace { bool IsMSVB( const char* ModuleName) { return ::_stricmp(ModuleName, "MSVBVM60.DLL") == 0; } bool IsMSCOREE( const char* ModuleName) { return ::_stricmp(ModuleName, "MSCOREE.DLL") == 0; } bool IsBannedRequiredFunction( const char* FunctionName) { return std::find_if( std::begin(BANNED_FUNCTIONS_REQUIRED), std::end(BANNED_FUNCTIONS_REQUIRED), [=](const char* Banned) { return strcmp(Banned, FunctionName) == 0; }) != std::end(BANNED_FUNCTIONS_REQUIRED); } bool IsBannedRecommendedFunction( const char* FunctionName) { return std::find_if( std::begin(BANNED_FUNCTIONS_RECOMMENDED), std::end(BANNED_FUNCTIONS_RECOMMENDED), [=](const char* Banned) { return strcmp(Banned, FunctionName) == 0; }) != std::end(BANNED_FUNCTIONS_RECOMMENDED); } bool IsHeapProtectionFunction( const char* FunctionName) { return ::strcmp("HeapSetInformation", FunctionName) == 0; } } // End of namespace {unnamed}
22.570175
91
0.644578
[ "vector" ]
2eb141c48d831b55521861d127f648b506d107f6
8,866
cpp
C++
moderngl/experimental/mgl/internal/glsl.cpp
dougbrion/ModernGL
6de8938ccd0042c1389a32b697af5f9c9d279e41
[ "MIT" ]
null
null
null
moderngl/experimental/mgl/internal/glsl.cpp
dougbrion/ModernGL
6de8938ccd0042c1389a32b697af5f9c9d279e41
[ "MIT" ]
null
null
null
moderngl/experimental/mgl/internal/glsl.cpp
dougbrion/ModernGL
6de8938ccd0042c1389a32b697af5f9c9d279e41
[ "MIT" ]
null
null
null
#include "glsl.hpp" #include "opengl/opengl.hpp" /* Remove the rightmost leading brackets. */ void clean_glsl_name(char * name, int & name_len) { if (name_len && name[name_len - 1] == ']') { name_len -= 1; while (name_len && name[name_len] != '[') { name_len -= 1; } } name[name_len] = 0; } /* GLSL type info. */ GLTypeInfo type_info(int type) { GLTypeInfo info = {}; int & cols = info.cols; int & rows = info.rows; int & shape = info.shape; switch (type) { case GL_FLOAT: cols = 1; rows = 1; shape = 'f'; break; case GL_FLOAT_VEC2: cols = 2; rows = 1; shape = 'f'; break; case GL_FLOAT_VEC3: cols = 3; rows = 1; shape = 'f'; break; case GL_FLOAT_VEC4: cols = 4; rows = 1; shape = 'f'; break; case GL_DOUBLE: cols = 1; rows = 1; shape = 'd'; break; case GL_DOUBLE_VEC2: cols = 2; rows = 1; shape = 'd'; break; case GL_DOUBLE_VEC3: cols = 3; rows = 1; shape = 'd'; break; case GL_DOUBLE_VEC4: cols = 4; rows = 1; shape = 'd'; break; case GL_INT: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_VEC2: cols = 2; rows = 1; shape = 'i'; break; case GL_INT_VEC3: cols = 3; rows = 1; shape = 'i'; break; case GL_INT_VEC4: cols = 4; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT: cols = 1; rows = 1; shape = 'u'; break; case GL_UNSIGNED_INT_VEC2: cols = 2; rows = 1; shape = 'u'; break; case GL_UNSIGNED_INT_VEC3: cols = 3; rows = 1; shape = 'u'; break; case GL_UNSIGNED_INT_VEC4: cols = 4; rows = 1; shape = 'u'; break; case GL_BOOL: cols = 1; rows = 1; shape = 'p'; break; case GL_BOOL_VEC2: cols = 2; rows = 1; shape = 'p'; break; case GL_BOOL_VEC3: cols = 3; rows = 1; shape = 'p'; break; case GL_BOOL_VEC4: cols = 4; rows = 1; shape = 'p'; break; case GL_FLOAT_MAT2: cols = 2; rows = 2; shape = 'f'; break; case GL_FLOAT_MAT3: cols = 3; rows = 3; shape = 'f'; break; case GL_FLOAT_MAT4: cols = 4; rows = 4; shape = 'f'; break; case GL_FLOAT_MAT2x3: cols = 3; rows = 2; shape = 'f'; break; case GL_FLOAT_MAT2x4: cols = 4; rows = 2; shape = 'f'; break; case GL_FLOAT_MAT3x2: cols = 2; rows = 3; shape = 'f'; break; case GL_FLOAT_MAT3x4: cols = 4; rows = 3; shape = 'f'; break; case GL_FLOAT_MAT4x2: cols = 2; rows = 4; shape = 'f'; break; case GL_FLOAT_MAT4x3: cols = 3; rows = 4; shape = 'f'; break; case GL_DOUBLE_MAT2: cols = 2; rows = 2; shape = 'd'; break; case GL_DOUBLE_MAT3: cols = 3; rows = 3; shape = 'd'; break; case GL_DOUBLE_MAT4: cols = 4; rows = 4; shape = 'd'; break; case GL_DOUBLE_MAT2x3: cols = 3; rows = 2; shape = 'd'; break; case GL_DOUBLE_MAT2x4: cols = 4; rows = 2; shape = 'd'; break; case GL_DOUBLE_MAT3x2: cols = 2; rows = 3; shape = 'd'; break; case GL_DOUBLE_MAT3x4: cols = 4; rows = 3; shape = 'd'; break; case GL_DOUBLE_MAT4x2: cols = 2; rows = 4; shape = 'd'; break; case GL_DOUBLE_MAT4x3: cols = 3; rows = 4; shape = 'd'; break; case GL_SAMPLER_1D: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_3D: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_CUBE: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_1D_SHADOW: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_SHADOW: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_1D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_1D_ARRAY_SHADOW: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_ARRAY_SHADOW: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_MULTISAMPLE: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_CUBE_SHADOW: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_BUFFER: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_RECT: cols = 1; rows = 1; shape = 'i'; break; case GL_SAMPLER_2D_RECT_SHADOW: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_1D: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_2D: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_3D: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_CUBE: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_1D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_2D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_2D_MULTISAMPLE: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_BUFFER: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_SAMPLER_2D_RECT: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_1D: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_2D: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_3D: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_CUBE: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_BUFFER: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_SAMPLER_2D_RECT: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_1D: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_2D: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_3D: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_2D_RECT: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_CUBE: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_BUFFER: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_1D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_2D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_2D_MULTISAMPLE: cols = 1; rows = 1; shape = 'i'; break; case GL_IMAGE_2D_MULTISAMPLE_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_1D: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_2D: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_3D: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_2D_RECT: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_CUBE: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_BUFFER: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_1D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_2D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_2D_MULTISAMPLE: cols = 1; rows = 1; shape = 'i'; break; case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_1D: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_2D: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_3D: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_2D_RECT: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_CUBE: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_BUFFER: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_1D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_2D_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY: cols = 1; rows = 1; shape = 'i'; break; case GL_UNSIGNED_INT_ATOMIC_COUNTER: cols = 1; rows = 1; shape = 'i'; break; } return info; } void read_float(float *& ptr, PyObject * value) { *ptr++ = (float)PyFloat_AsDouble(value); } void read_int(int *& ptr, PyObject * value) { *ptr++ = PyLong_AsLong(value); } void read_unsigned(unsigned *& ptr, PyObject * value) { *ptr++ = PyLong_AsUnsignedLong(value); } void read_double(double *& ptr, PyObject * value) { *ptr++ = PyFloat_AsDouble(value); } void read_bool(int *& ptr, PyObject * value) { *ptr++ = PyObject_IsTrue(value); }
57.2
98
0.597902
[ "shape" ]
e4815ce6074ef17af8db1a9cd33077ddedf833e7
22,861
cpp
C++
solveInFive.cpp
pjherron/deepwordle
12e31728ef1861654cd380c466988625273e278e
[ "MIT" ]
2
2022-01-26T19:21:04.000Z
2022-02-13T19:09:12.000Z
solveInFive.cpp
pjherron/deepwordle
12e31728ef1861654cd380c466988625273e278e
[ "MIT" ]
null
null
null
solveInFive.cpp
pjherron/deepwordle
12e31728ef1861654cd380c466988625273e278e
[ "MIT" ]
1
2022-02-14T00:28:56.000Z
2022-02-14T00:28:56.000Z
// Created by Xan Gregg on 1/12/22. // #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <array> #include <map> #include <unordered_map> #include <set> #include <algorithm> #include <sstream> #include <iostream> #include <cassert> #include <fstream> #include <future> #include <thread> #include <chrono> #include <iomanip> #include <thread> #include <atomic> #include <numeric> using int64 = int64_t; using namespace std; std::chrono::time_point<std::chrono::system_clock> now() { return std::chrono::system_clock::now(); } double timeDiff(const std::chrono::time_point<std::chrono::system_clock> &t0, const std::chrono::time_point<std::chrono::system_clock> &t1) { return std::chrono::duration<double>(t1 - t0).count(); } double since(const std::chrono::time_point<std::chrono::system_clock> &t0) { return timeDiff(t0, std::chrono::system_clock::now()); } // given a guess and the solution, return the response clue packed into a base-3 integer. // the low-order digit is the last character. // 0 == no match, 1 == right letter, wrong place, 2 == right letter in right place // Using Wordle rules for duplicate letters, which are not treated the same static int getResponse(string guess, string solution) { int g = 0; for (int i = 0; i < 5; ++i) { if (i > 0) g *= 3; if (guess[i] == solution[i]) { g += 2; guess[i] = ' '; solution[i] = ' '; } } int y = 0; for (int i = 0; i < 5; ++i) { if (i > 0) y *= 3; if (guess[i] == ' ') continue; auto loc = solution.find(guess[i]); if (loc != std::string::npos) { y += 1; solution[loc] = ' '; } } return g + y; } // given a list of possible solutions and the solutionClue data for a specific guess word, // return a separate list for each of the 243 possible responses. static vector<int> splitIntoPartsCount(vector<short> const &solutions, vector<short> const & solutionClue) { vector<int> count(243); for (short sol : solutions) { count[solutionClue[sol]] += 1; } return count; } // given a list of possible solutions and the solutionClue data for a specific guess word, // return a separate list for each of the 243 possible responses. static vector<vector<short>> splitIntoParts(vector<short> const &solutions, vector<short> const & solutionClue) { vector<int> count = splitIntoPartsCount(solutions, solutionClue); vector<vector<short>> parts(243); for (int i = 0; i < 243; ++i) parts[i].reserve(count[i]); for (short sol : solutions) { parts[solutionClue[sol]].push_back(sol); } return parts; } // size of the largest partition static int splitIntoPartsMax(vector<short> const &solutions, vector<short> const & solutionClue) { vector<int> count = splitIntoPartsCount(solutions, solutionClue); return *max_element(count.begin(), count.end()); } // read a file of words into a vector static vector<string> readWordFile(string const & fn) { vector<string> words; ifstream wordFile(fn); string w; while (getline(wordFile, w)) { words.push_back(w); } wordFile.close(); return words; } // show the response in a printable form, using the Wordle Unicode characters static string responseToString(int r) { vector<string> code{"⬜", "\xF0\x9F\x9F\xA8", "\xF0\x9F\x9F\xA9"}; // "\uD83D\uDFE8","\uD83D\uDFE9", string s; int m = 81; for (int i = 0; i < 5; i++) { s += code[(r / m) % 3]; m /= 3; } return s; } // given a guess word, w, and its response, update data on 'dead' letters by position. // dead letters can't possible appear at a given position (position 0 is the first letter of a word) // Doesn't have to be perfect -- just used as a hint to reduce the list of words to try. static array<int, 5> collectDead(string w, int response, array<int, 5> const & deadLetters) { array<int, 5> dead = deadLetters; array<int, 5> code; int m = 81; for (int i = 0; i < 5; i++) { code[i] = (response / m) % 3; m /= 3; } for (int i = 0; i < 5; i++) { if (code[i] == 0) { // letter does not appear; add to dead list bool hasMultiple = false; // unless it occurs multiple times in w and some are non-zero for (int j = 0; j < 5; ++j) { if (i != j && code[j] != 0 && w[i] == w[j]) { hasMultiple = true; break; } } if (hasMultiple) dead[i] |= 1 << (w[i] - 'a'); // not here else { for (int j = 0; j < 5; ++j) dead[j] |= 1 << (w[i] - 'a'); // not anywhere } } else if (code[i] == 1) { dead[i] |= 1 << (w[i] - 'a'); // not here } } return dead; } // decision tree struct Path { int guess = -1; int nSolution = -1; int maxDepth = 0; // worst case number of guesses, including this guess double ev = 0; // expected number of guess, including this guess int64 solutionsPack = -1; // up to 5 possible solutions packed 12-bits each into 64-bit int map<int, Path> choices; // [243] }; // Main work function to recursively explore and optimize the decisition tree from a given starting point. static Path exploreGuess(vector<short> const & solution, int g, vector<vector<short>> const & solutionClue, vector<string> const & guess, array<int, 5> const & deadLetters, int depthToBeat, int effort, bool shallow, int callDepth) { Path path; path.guess = g; path.nSolution = int(solution.size()); if (path.nSolution <= 1) { // should never happen since caller tests for this (except the very first caller, which has many solutions) cout << "wasn't expecting <= 1 solution for " << g << endl; path.maxDepth = path.nSolution; path.ev = path.nSolution; if (path.nSolution > 0) path.solutionsPack = solution[0]; return path; } int nGuess = int(solutionClue.size()); // ~3000 double evsum = 0; double evn = 0; vector<vector<short>> const & parts = splitIntoParts(solution, solutionClue[g]); // special case for 242 == all green if (!parts[242].empty()) { evsum += 1; evn += 1; path.solutionsPack = g; // indicates the guess is a solution } // first pass: check viability of this guess before exploring any subtree for (int ip = 0; ip < 242; ++ip) { vector<short> const & sols = parts[ip]; if (solution.size() == sols.size()) { // must be a repeated or otherwise useless guess path.maxDepth = 999; return path; } if (callDepth > 0 && ( (solution.size() > 100 && sols.size() > solution.size() * (22 + effort * 5) / 100) || (solution.size() > 75 && sols.size() > solution.size() * (33 + effort * 2) / 100) || (solution.size() > 50 && sols.size() > solution.size() * (44 + effort * 2) / 100))) { // not a very productive guess path.maxDepth = 999; return path; } } // second pass: dive into each partition for (int ip = 0; ip < 242; ++ip) { // auto t0 = std::chrono::system_clock::now(); vector<short> const & sols = parts[ip]; if (sols.empty()) continue; int nipSol = int(sols.size()); Path best; if (nipSol == 1) { // only one solution, but it isn't guess[g] because the response is not 242 best.guess = sols[0]; best.maxDepth = 1; best.nSolution = 1; best.ev = best.maxDepth; best.solutionsPack = sols[0]; } else if (nipSol == 2) { best.guess = sols[0]; best.maxDepth = 2; best.nSolution = 2; best.ev = 1.5; best.solutionsPack = (sols[1] << 12) + sols[0]; } else if (nipSol < 6) { // see if any solution will work for (int ig : sols) { array<int, 5> clues; for (int j = 0; j < nipSol; ++j) { clues[j] = solutionClue[ig][sols[j]]; } sort(clues.begin(), clues.begin() + nipSol); if (std::adjacent_find(clues.begin(), clues.begin() + nipSol) == clues.begin() + nipSol) { best.guess = ig; best.nSolution = nipSol; best.ev = double(nipSol * 2 - 1) / nipSol; best.maxDepth = 2; best.solutionsPack = 0; for (int i = 0; i < min(best.nSolution, 5); ++i) { if (ig != sols[i]) best.solutionsPack = (best.solutionsPack << 12) + sols[i]; } best.solutionsPack = (best.solutionsPack << 12) + ig; // put the best next guess first break; } } } if (best.guess >= 0) { // one of the above quick checks worked } else if (depthToBeat <= 3 || shallow || (callDepth == 1 && nipSol >= 70 + effort * 20 ) || (callDepth == 2 && nipSol > (8 + effort * 3)) || callDepth == 3) { // pessimistic guess // if (depthToBeat > 3 && callDepth == 2 && !shallow) // cout << "guessing" << " " << callDepth << " " << nipSol << endl; best.guess = sols[0]; best.nSolution = int(sols.size()); best.maxDepth = 3 + best.nSolution / 10; best.ev = 1.75 + best.nSolution / 6.0; best.solutionsPack = sols[0]; for (int i = 1; i < min(best.nSolution, 5); ++i) best.solutionsPack = (best.solutionsPack << 12) + sols[i]; } else { array<int, 5> deadLetters2 = collectDead(guess[g], ip, deadLetters); int deadLimit = (callDepth == 0 ? 0 : callDepth == 1 ? 1 : 2) + int(nipSol < 20); // first word pass: filter words bases on dead letters and also collect the max partition size for each word vector<pair<short, short>> maxPart; // pair<maxPart, guess> for (int ig = 0; ig < nGuess; ++ig) { if (g == ig) continue; string const & iw = guess[ig]; int ndead = 0; for (int i = 0; i < 5; ++i) { if ((deadLetters2[i] & (1 << (iw[i] - 'a'))) != 0) { ndead++; if (ndead > deadLimit) break; } } if (ndead > deadLimit) continue; maxPart.push_back(make_pair(short(splitIntoPartsMax(sols, solutionClue[ig])), short(ig))); } if (maxPart.empty()) { cout << " *** no words to consider " << g << endl; continue; } sort(maxPart.begin(), maxPart.end()); int bestMax = maxPart.front().first; vector<int> visit; if (bestMax <= 2) { // found a winner -- just use that visit.push_back(maxPart.front().second); } else { // choose most promising words to visit fully int limit = bestMax * 125 / 100 + 2; // if (callDepth == 0) { // cout << guess[g] << setw(4) << ip << " " << setw(4) << bestMax << setw(4) << limit << endl; // } if (callDepth == 0) { // still far enough from end that we need to keep more avenues open limit = max(limit, nipSol / (effort == 0 ? 7 : effort == 1 ? 6 : effort <= 3 ? 5 : 4)); //5 // HAUTE, SHADE and SPADE all have a best route with max of 36 or 35 and nipSol in 210..240 range (and bestMax is ~18) } int minVisit = clamp(int(maxPart.size()), 1, 5); for (auto const & mp : maxPart) { if (mp.first <= limit || visit.size() < minVisit) visit.push_back(mp.second); else break; } } // cout << "reduction " << g << " " << setw(4) << maxPart.size() << " " << visit.size() << " " << fixed << setprecision(2) << double(visit.size()) / double(maxPart.size()) << endl; vector<int> revisit; double bestScore = 999; best.maxDepth = 999; int minGood = effort == 0 ? 10 : effort == 1 ? 3 : 1; // as long as maxDepth effort is light, try more for low EV int nGood = 0; for (int ig : visit) { Path p = exploreGuess(sols, ig, solutionClue, guess, deadLetters2, best.maxDepth, effort, shallow || callDepth == 1, callDepth + 1); if (p.maxDepth <= 2) nGood++; if (p.maxDepth + p.ev < bestScore) { bestScore = p.maxDepth + p.ev; best = std::move(p); if (best.maxDepth <= 2 && nGood >= minGood) break; } else if (callDepth == 1 && p.maxDepth > 3) { revisit.push_back(ig); } } if (callDepth == 1 && depthToBeat >= 4 // our best.maxDepth will be at least 3 and then add 1 before returning, so we can't beat 4 && best.maxDepth > 3 // 3 is ok, since the below code is not going to find a 2 && !shallow) { // another pass not changing shallow for (int ig : revisit) { // if (callDepth <= 0) { // cout << "explore " << callDepth << setw(3 * callDepth) << " " << guess[g] << " " << setw(3) << ip << " " << guess[ig] << " " << nipSol << endl; // } Path p = exploreGuess(sols, ig, solutionClue, guess, deadLetters2, best.maxDepth, effort, shallow, callDepth + 1); if (p.maxDepth + p.ev < bestScore) { bestScore = p.maxDepth + p.ev; best = std::move(p); if (best.maxDepth <= 2) break; } } } } evsum += best.ev * best.nSolution; evn += best.nSolution; if (best.maxDepth > path.maxDepth) path.maxDepth = best.maxDepth; path.choices[ip] = best; // if (callDepth == 0 && sols.size() > 10) { // cout << ip << " " << sols.size(); // cout << std::fixed << std::setprecision(3) << " sec: " << " " << since(t0) << endl; // } } path.ev = evsum / evn + 1; path.maxDepth += 1; return path; } static void showPath(ofstream & treefile, string const & prefix, Path const & path, vector<string> const & guess, vector<vector<short>> const & solutionClue, int depth = 0) { if (path.guess < 0) return; if (path.nSolution <= 0) return; if (path.choices.empty()) { if (path.maxDepth <= 2 && path.nSolution <= 5 && path.solutionsPack >= 0) { // expand the compressed path tree int g = path.solutionsPack & 0x0fff; for (int i = 0; i < min(5, path.nSolution); ++i) { int s = (path.solutionsPack >> (i * 12)) & 0x0fff; int response = solutionClue[g][s]; treefile << prefix << guess[g]; if (response != 242) treefile << " " << responseToString(response) << std::setw(4) << 1 << " " << guess[s]; treefile << endl; } } else { treefile << prefix << std::setw(6) << std::fixed << std::setprecision(3) << path.ev << " " << path.maxDepth; for (int i = 0; i < min(5, path.nSolution); ++i) { treefile << " ** " << guess[(path.solutionsPack >> (i * 12)) & 0x0fff]; } treefile << std::endl; } } else { for (auto & kv : path.choices) { if (kv.second.nSolution > 0) { std::stringstream ss; ss << prefix << guess[path.guess] << " " << responseToString(kv.first) << std::setw(5) << kv.second.nSolution << " "; showPath(treefile, ss.str(), kv.second, guess, solutionClue, depth + 1); } } if (path.solutionsPack >= 0) { // indicates the guess is a solution std::stringstream ss; treefile << prefix << guess[path.guess] << endl; } } } static void pushSolutions(vector<int> & sols, Path const & path) { if (path.choices.empty()) { for (int i = 0; i < min(5, path.nSolution); ++i) { sols.push_back((path.solutionsPack >> (i * 12)) & 0x0fff); } } else { if (path.solutionsPack >= 0) // indicates the guess is a solution sols.push_back(path.guess); for (auto const & kv : path.choices) pushSolutions(sols, kv.second); } } static void showSolutions(ostream & tableFile, Path const & path, vector<string> const & guess) { vector<int> sols; pushSolutions(sols, path); if (sols.size() != path.nSolution) tableFile << sols.size() << ";"; for (int i = 0; i < int(sols.size()); ++i) { if (i > 0) tableFile << ";"; tableFile << guess[sols[i]]; } } static void showTable(ostream & tableFile, Path const & path, vector<string> const & guess) { // "first guess,avg guesses,max guesses,first clue,n solutions,second guess,max guesses remaining,solutions" for (int ip = 0; ip < 243; ++ip) { if (path.choices.find(ip) == path.choices.end()) continue; // impossible response -- no solutions Path const & next = path.choices.at(ip); if (next.guess < 0 || next.nSolution == 0) { cout << "empty choice" << path.guess << " " << ip << endl; continue; // impossible response -- no solutions } tableFile << guess[path.guess] << "," << path.ev << "," << path.maxDepth << "," << responseToString(ip) << "," << next.nSolution << "," << guess[next.guess] << "," << (next.nSolution == 1 && next.solutionsPack == next.guess ? 0 : next.maxDepth - 1) << ","; showSolutions(tableFile, next, guess); tableFile << endl; } } int main() { //vector<string> allWords = readWordFile("wordle words lines.txt"); vector<string> solutionText = readWordFile("wordle solutions.txt"); //solution.resize(2315); // only the first 2315 are used as solutions //vector<string> guess = readWordFile("guesses5.txt"); vector<string> guess = readWordFile("common.txt"); sort(guess.begin(), guess.end()); vector<short> solution; for (auto const & s : solutionText) { auto loc = find(guess.begin(), guess.end(), s); // assert (loc != guess.end()); if (loc != guess.end()) solution.push_back(int(loc - guess.begin())); else cout << "*** solution not found " << s << endl; } sort(solution.begin(), solution.end()); // int nWords = int(words.size()); // 12972 int nGuess = int(guess.size()); // ~3000 int nSolution = int(solution.size()); // other words are allowed as guesses // encode response as 5 base-3 digits, 0 - 3^5, 0 - 243 vector<int> place{0, 3, 9, 27, 81, 243}; vector<vector<vector<short>>> partitions(nGuess); // [nguess][243][nsol] vector<vector<short>> solutionClue(nGuess); // [nguess][nguess] -> clue vector<double> score(nGuess); // build the response partitions for each word // (also compute a score for prioritizing work which is no longer used) auto t0 = std::chrono::system_clock::now(); int nThread = std::clamp(int(std::thread::hardware_concurrency()), 2, 32); std::vector<std::thread> threads; for (int it = 0; it < nThread; ++it) { threads.emplace_back([it, nGuess, nThread, nSolution, &guess, &solution, &partitions, &solutionClue, &score]() { for (int ig = it * nGuess / nThread; ig < (it + 1) * nGuess / nThread; ++ig) { partitions[ig].resize(243); solutionClue[ig].resize(nGuess); for (short is = 0; is < nSolution; ++is) { int response = getResponse(guess[ig], guess[solution[is]]); partitions[ig][response].push_back(solution[is]); solutionClue[ig][solution[is]] = response; } double s = 0; for (int ip = 0; ip < 243; ++ip) { double hits = sqrt(ip % 3) + sqrt(ip/3 % 3) + sqrt(ip/9 % 3) + sqrt(ip/27 % 3) + sqrt(ip/81 % 3); double weight = hits == 0 ? 5.0 : hits == 1 ? 3.0 : hits < 2 ? 2.5 : hits == 2 ? 2.0 : hits < 3 ? 1.7 : 1.0; double ps = int(partitions[ig][ip].size()) / weight; if (ps > s) s = ps; } score[ig] = s; } } ); } for (auto & t : threads) t.join(); cout << std::fixed << std::setprecision(3) << "build time " << " " << since(t0) << endl; vector<int> index(nGuess); std::iota(index.begin(), index.end(), 0); std::sort(index.begin(), index.end(), [&](int a, int b) { return score[a] < score[b];}); // most promising start words? -- no longer used for (int i = 0; i < 10; ++i) { int iw = index[i]; //cout << std::right << std::setw(4) << score[iw] << " " << words[iw] << endl; cout << std::fixed << std::setprecision(3) << score[iw] << " " << guess[iw] << endl; } cout << endl; #if 0 // use this branch to try out a few specific words //vector<string> favWords{"trend", "begin", "route", "stein", "first", "clout", "trunk", "clone", "raise", "trend", "intro", "inert", "tinge", "avoid", "adieu"}; //vector<string> favWords{"shush", "yummy", "mamma", "mummy", "vivid", "puppy"}; vector<string> favWords{"shush", "yummy", "mummy"}; // 6 vector<int> favs; for (auto const & s : favWords) { favs.push_back(int(std::find(guess.begin(), guess.end(), s) - guess.begin())); } #else vector<int> favs; for (int i = 0; i < nGuess; ++i) { //int iw = index[i]; // in score order favs.push_back(i); } #endif vector<int> favMax(favs.size()); vector<double> favEV(favs.size()); std::vector<stringstream> wordstreams(favs.size()); std::vector<stringstream> summstreams(nThread); std::vector<std::thread> ethreads; std::atomic<int> next = 0; std::atomic<int> nDone = 0; std::atomic<int> nTogo = int(favs.size()); auto te0 = std::chrono::system_clock::now(); for (int it = 0; it < nThread; ++it) { ethreads.emplace_back([it, nThread, nSolution, te0, &nTogo, &nDone, &next, &favs, &guess, &solution, &partitions, &solutionClue, &score, &favMax, &favEV, &summstreams, &wordstreams]() { int nFav = int(favs.size()); for (int ifav = next++; ifav < nFav; ifav = next++) { Path path; int pass = 0; auto tf = std::chrono::system_clock::now(); for (; pass < 5; pass++) { auto tf0 = std::chrono::system_clock::now(); if (pass > 0) nTogo++; path = exploreGuess(solution, favs[ifav], solutionClue, guess, array<int, 5>(), 999, pass, false, 0); favMax[ifav] = path.maxDepth; favEV[ifav] = path.ev; if (path.guess != favs[ifav]) { cout << "unexpected guess " << path.guess << " " << favs[ifav] << endl; cout.flush(); } nDone++; double dt = since(te0); double done = double(nDone) / nTogo; // these two atomics could be fetched out of sync but no big deal double rem = dt / done - dt; stringstream ss; ss << setw(3) << it << " " << setw(3) << min(4, pass) << " " << setw(4) << ifav << " " << guess[favs[ifav]] << " " << std::fixed << std::setprecision(5) << favEV[ifav] << std::right << std::setw(6) << favMax[ifav] << " " << setw(7) << std::setprecision(2) << since(tf0)/60 << " min " << setw(5) << std::setprecision(1) << done * 100 << "% done " << setw(5) << std::setprecision(0) << rem/60 << " min to go"<< endl; cout << ss.str(); // *** "results" directory needs to already exist *** // the entire decision tree for this starting word ofstream treefile; treefile.open(std::filesystem::path(string("results/tree ") + (path.maxDepth > 5 && pass < 4 ? (std::to_string(pass) + " ") : string("")) + guess[favs[ifav]] + ".txt")); showPath(treefile, "", path, guess, solutionClue); treefile.close(); if (path.maxDepth <= 5) break; // good enough } showTable(wordstreams[ifav], path, guess); summstreams[it] << guess[favs[ifav]] << "," << std::fixed << std::setprecision(5) << path.ev << "," << path.maxDepth << "," << pass << "," << since(tf) << endl; } } ); } for (auto & t : ethreads) t.join(); for (int ifav = 0; ifav < int(favs.size()); ++ifav) { cout << guess[favs[ifav]] << " " << std::fixed << std::setw(6) << std::setprecision(3) << favEV[ifav] << std::right << std::setw(6) << favMax[ifav] << endl; } ofstream summFile; summFile.open(std::filesystem::path(string("results/summary ev.csv"))); summFile << "guess" << "," << "ev" << "," << "max guesses" << "," << "pass" << "," << "time" << endl; for (auto & s : summstreams) { summFile << s.str(); } summFile.close(); ofstream twoDeepFile; twoDeepFile.open(std::filesystem::path(string("results/summary two-deep.csv"))); twoDeepFile << "first guess,avg guesses,max guesses,first clue,n solutions,second guess,max guesses remaining,solutions" << endl; for (auto & s : wordstreams) { twoDeepFile << s.str(); } twoDeepFile.close(); cout << endl; return 0; }
35.170769
187
0.60203
[ "vector" ]
e4895b51d2a9ccdd03c6aa1a642a19fabefd0232
7,645
cc
C++
ion/port/tests/fileutils_test.cc
RobLoach/ion
9e659416fb04bb3d3a67df1e018d7c2ccab9d468
[ "Apache-2.0" ]
null
null
null
ion/port/tests/fileutils_test.cc
RobLoach/ion
9e659416fb04bb3d3a67df1e018d7c2ccab9d468
[ "Apache-2.0" ]
null
null
null
ion/port/tests/fileutils_test.cc
RobLoach/ion
9e659416fb04bb3d3a67df1e018d7c2ccab9d468
[ "Apache-2.0" ]
null
null
null
/** Copyright 2016 Google 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. */ #include "ion/port/fileutils.h" #if defined(ION_PLATFORM_WINDOWS) #include <windows.h> #endif #include "ion/base/stringutils.h" #include "ion/port/string.h" #include "ion/port/timer.h" #include "third_party/googletest/googletest/include/gtest/gtest.h" TEST(FileUtils, GetCanonicalFilePath) { using ion::port::GetCanonicalFilePath; #if defined(ION_PLATFORM_WINDOWS) EXPECT_EQ("this/is/a/file/path", GetCanonicalFilePath("this/is\\a/file\\path")); EXPECT_EQ("/leading/and/trailing/", GetCanonicalFilePath("\\leading\\and\\trailing\\")); EXPECT_EQ("this/has/no/changes/", GetCanonicalFilePath("this/has/no/changes/")); #else EXPECT_EQ("this/is\\a/file\\path", GetCanonicalFilePath("this/is\\a/file\\path")); EXPECT_EQ("\\leading\\and\\trailing\\", GetCanonicalFilePath("\\leading\\and\\trailing\\")); EXPECT_EQ("this/has/no/changes/", GetCanonicalFilePath("this/has/no/changes/")); #endif } // NaCl has no file support. #if !defined(ION_PLATFORM_NACL) TEST(FileUtils, GetCurrentWorkingDirectory) { std::string dir; #if defined(ION_PLATFORM_WINDOWS) WCHAR pwd[MAX_PATH]; ::GetCurrentDirectoryW(MAX_PATH, pwd); dir = ion::port::GetCanonicalFilePath(ion::port::WideToUtf8(pwd)); #else static const int kPathLength = 2048; char path[kPathLength]; getcwd(path, kPathLength); dir = path; #endif // This is a rather trivial test, but there are few ways to test this that // will work on all platforms. EXPECT_EQ(dir, ion::port::GetCurrentWorkingDirectory()); } // Test that the file modification time returned by GetFileModificationTime // matches the system clock. TEST(FileUtils, GetTemporaryFileModificationTimeMatchesSystemTime) { using ion::port::GetFileModificationTime; using ion::port::GetTemporaryFilename; using ion::port::OpenFile; const std::string path = GetTemporaryFilename(); EXPECT_FALSE(path.empty()); // Open the file, write to it, and close it. const std::string data("Some string\nto write\n"); FILE* fp = OpenFile(path, "wb"); EXPECT_FALSE(fp == NULL); EXPECT_EQ(data.length(), fwrite(data.c_str(), sizeof(data[0]), data.length(), fp)); fclose(fp); fp = NULL; // Get the file's modification time; it should be close to the system clock's // now. Since this does a disk write, expect a generous 1 minute accuracy. const std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::system_clock::time_point file_timestamp; EXPECT_TRUE(GetFileModificationTime(path, &file_timestamp)); EXPECT_GE(std::chrono::minutes(1), now - file_timestamp); EXPECT_GE(std::chrono::minutes(1), file_timestamp - now); } TEST(FileUtils, GetTemporaryDirectory) { const std::string temp_directory = ion::port::GetTemporaryDirectory(); EXPECT_FALSE(temp_directory.empty()); const std::string temp_file = ion::port::GetTemporaryFilename(); const std::size_t last_slash = temp_file.find_last_of('/'); const std::string temp_prefix = temp_file.substr(0, last_slash); EXPECT_EQ(temp_prefix, temp_directory); } TEST(FileUtils, GetTemporaryFilenameModificationTimeOpenFileRemoveFile) { using ion::port::GetCanonicalFilePath; using ion::port::GetFileModificationTime; using ion::port::GetTemporaryFilename; using ion::port::OpenFile; using ion::port::RemoveFile; using ion::port::Timer; const std::string data("Some string\nto write\n"); // Create a temporary file to write to and read from. const std::string path = GetTemporaryFilename(); EXPECT_FALSE(path.empty()); const std::chrono::system_clock::time_point current_time = std::chrono::system_clock::now(); Timer::SleepNSeconds(1); // Open the file, write to it, and close it. FILE* fp = OpenFile(path, "wb"); EXPECT_FALSE(fp == NULL); EXPECT_EQ(data.length(), fwrite(data.c_str(), sizeof(data[0]), data.length(), fp)); fclose(fp); fp = NULL; // Get the file's modification time, it should be at or after the current // time. std::chrono::system_clock::time_point timestamp; EXPECT_TRUE(GetFileModificationTime(path, &timestamp)); EXPECT_GE(timestamp, current_time); // Open the file, read from it, and close it. fp = OpenFile(path, "rb"); EXPECT_FALSE(fp == NULL); std::string read_data; read_data.resize(data.length()); EXPECT_EQ(read_data.length(), fread(&read_data[0], sizeof(data[0]), data.length(), fp)); EXPECT_EQ(data, read_data); fclose(fp); EXPECT_TRUE(RemoveFile(path)); EXPECT_FALSE(GetFileModificationTime(path, &timestamp)); EXPECT_FALSE(RemoveFile( GetCanonicalFilePath("this/path/is/unlikely/to/exist.anywhere"))); EXPECT_FALSE(GetFileModificationTime( GetCanonicalFilePath("this/path/is/unlikely/to/exist.anywhere"), &timestamp)); } TEST(FileUtils, NonAsciiFilename) { // Construct a path with some non-ASCII characters by appending to a temp // file name. const std::string temp_path = ion::port::GetTemporaryFilename(); const std::string alpha_beta_gamma = "\xCE\xB1\xCE\xB2\xCE\xB3"; // UTF-8 const std::string path = temp_path + alpha_beta_gamma; FILE* fp = ion::port::OpenFile(path, "wb"); EXPECT_FALSE(fp == NULL); fclose(fp); EXPECT_TRUE(ion::port::RemoveFile(path)); // On Windows, getting a temporary filename generates the file, so we have // to clean it up. On other platforms, this will fail. ion::port::RemoveFile(temp_path); } TEST(FileUtils, TestListDirectory) { using ion::port::OpenFile; using ion::port::RemoveFile; using ion::port::ListDirectory; using ion::port::GetTemporaryDirectory; using ion::port::GetTemporaryFilename; std::string filename = GetTemporaryFilename(); FILE* f = OpenFile(filename, "w"); ASSERT_TRUE(f != NULL); ASSERT_EQ(fclose(f), 0); std::vector<std::string> files = ListDirectory(GetTemporaryDirectory()); bool found = false; for (auto it = files.begin(); !found && it != files.end(); ++it) found = filename == GetTemporaryDirectory() + "/" + *it; EXPECT_TRUE(found) << "Failed to find [" << filename << "] in [" << ion::base::JoinStrings(files, ":") << "]"; EXPECT_TRUE(RemoveFile(filename)); } TEST(FileUtils, TestReadDataFromFile) { using ion::port::OpenFile; using ion::port::RemoveFile; using ion::port::ReadDataFromFile; using ion::port::GetTemporaryFilename; // Create a temporary file and write some data to it. const std::string data("Some string\nto write\n"); const std::string path = GetTemporaryFilename(); FILE* fp = OpenFile(path, "wb"); EXPECT_EQ(data.length(), fwrite(data.c_str(), sizeof(data[0]), data.length(), fp)); fclose(fp); fp = NULL; // Now read it back into a string. std::string output; EXPECT_TRUE(ReadDataFromFile(path, &output)); EXPECT_EQ(data, output); EXPECT_TRUE(RemoveFile(path)); // Also try the failure case where the file isn't available. std::string output2; EXPECT_FALSE(ReadDataFromFile("blah", &output2)); } #endif // !ION_PLATFORM_NACL
33.977778
79
0.708698
[ "vector" ]
e48b465ea1da84d4438190b8fdb8adae8bd51f8a
27,625
cxx
C++
PWGJE/UserTasks/AliAnalysisTaskJetHBOM.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGJE/UserTasks/AliAnalysisTaskJetHBOM.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGJE/UserTasks/AliAnalysisTaskJetHBOM.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
// ************************************** // Task used for the correction of detector effects for background fluctuations in jet spectra by the HBOM method // ******************************************* /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <TROOT.h> #include <TRandom3.h> #include <TSystem.h> #include <TInterpreter.h> #include <TChain.h> #include <TRefArray.h> #include <TFile.h> #include <TKey.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <TProfile.h> #include <TF1.h> #include <TList.h> #include <TLorentzVector.h> #include <TClonesArray.h> #include "TDatabasePDG.h" #include "AliAnalysisTaskJetHBOM.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliAODHandler.h" #include "AliAODExtension.h" #include "AliAODTrack.h" #include "AliAODJet.h" #include "AliAODMCParticle.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliGenPythiaEventHeader.h" #include "AliGenCocktailEventHeader.h" #include "AliInputEventHandler.h" #include "AliAODJetEventBackground.h" using std::cout; using std::endl; using std::vector; ClassImp(AliAnalysisTaskJetHBOM) AliAnalysisTaskJetHBOM::~AliAnalysisTaskJetHBOM(){ // // Destructor // delete fRef; fRef = 0; delete fRandom; fRandom = 0; if(fTCARandomConesOut)fTCARandomConesOut->Delete(); delete fTCARandomConesOut; fTCARandomConesOut = 0; } AliAnalysisTaskJetHBOM::AliAnalysisTaskJetHBOM(): AliAnalysisTaskSE(), fAOD(0x0), fAODExtension(0x0), fRef(0), fUseAODTrackInput(kFALSE), fUseAODMCInput(kFALSE), fEventSelection(kFALSE), fFilterMask(0), fFilterMaskBestPt(0), fFilterType(0), fJetTypes(kJet), fTrackTypeRec(kTrackUndef), fTrackTypeGen(kTrackUndef), fNSkipLeadingRan(0), fNSkipLeadingCone(0), fNRandomCones(0), randCone_pos(0), randCone_Eta(0), randCone_Phi(0), fNHBOM(0), fTrackEtaWindow(0.9), fTrackPtCut(0.), fJetOutputMinPt(0.150), fMaxTrackPtInJet(100.), fVtxZCut(8), fVtxR2Cut(1), fCentCutUp(0), fCentCutLo(0), fNonStdBranch(""), fBackgroundBranch(""), fNonStdFile(""), fMomResH1(0x0), fMomResH2(0x0), fMomResH3(0x0), fMomResH1Fit(0x0), fMomResH2Fit(0x0), fMomResH3Fit(0x0), fhEffH1(0x0), fhEffH2(0x0), fhEffH3(0x0), fUseTrMomentumSmearing(kFALSE), fUseDiceEfficiency(kFALSE), fRparam(1.0), fAlgorithm(fastjet::kt_algorithm), fStrategy(fastjet::Best), fRecombScheme(fastjet::BIpt_scheme), fAreaType(fastjet::active_area), fGhostArea(0.01), fActiveAreaRepeats(1), fGhostEtamax(1.5), background(0), fTCARandomConesOut(0x0), fRandom(0), fh1Xsec(0x0), fh1Trials(0x0), fh1PtHard(0x0), fh1PtHardNoW(0x0), fh1PtHardTrials(0x0), fh1Nch(0x0), fh1CentralityPhySel(0x0), fh1Centrality(0x0), fh1DeltapT(0x0), fh1Rho(0x0), fh1RhoSigma(0x0), fh1PtRandCone(0x0), fh1efficiencyPt(0x0), fh2efficiencyPhi(0x0), fh1ZPhySel(0x0), fh1Z(0x0), fHistList(0x0) { } AliAnalysisTaskJetHBOM::AliAnalysisTaskJetHBOM(const char* name): AliAnalysisTaskSE(name), fAOD(0x0), fAODExtension(0x0), fRef(0), fUseAODTrackInput(kFALSE), fUseAODMCInput(kFALSE), fEventSelection(kFALSE), fFilterMask(0), fFilterMaskBestPt(0), fFilterType(0), fJetTypes(kJet), fTrackTypeRec(kTrackUndef), fTrackTypeGen(kTrackUndef), fNSkipLeadingRan(0), fNSkipLeadingCone(0), fNRandomCones(0), randCone_pos(0), randCone_Eta(0), randCone_Phi(0), fNHBOM(0), fTrackEtaWindow(0.9), fTrackPtCut(0.), fJetOutputMinPt(0.150), fMaxTrackPtInJet(100.), fVtxZCut(8), fVtxR2Cut(1), fCentCutUp(0), fCentCutLo(0), fNonStdBranch(""), fBackgroundBranch(""), fNonStdFile(""), fMomResH1(0x0), fMomResH2(0x0), fMomResH3(0x0), fMomResH1Fit(0x0), fMomResH2Fit(0x0), fMomResH3Fit(0x0), fhEffH1(0x0), fhEffH2(0x0), fhEffH3(0x0), fUseTrMomentumSmearing(kFALSE), fUseDiceEfficiency(kFALSE), fRparam(1.0), fAlgorithm(fastjet::kt_algorithm), fStrategy(fastjet::Best), fRecombScheme(fastjet::BIpt_scheme), fAreaType(fastjet::active_area), fGhostArea(0.01), fActiveAreaRepeats(1), fGhostEtamax(1.5), background(0), fTCARandomConesOut(0x0), fRandom(0), fh1Xsec(0x0), fh1Trials(0x0), fh1PtHard(0x0), fh1PtHardNoW(0x0), fh1PtHardTrials(0x0), fh1Nch(0x0), fh1CentralityPhySel(0x0), fh1Centrality(0x0), fh1DeltapT(0x0), fh1Rho(0x0), fh1RhoSigma(0x0), fh1PtRandCone(0x0), fh1efficiencyPt(0x0), fh2efficiencyPhi(0x0), fh1ZPhySel(0x0), fh1Z(0x0), fHistList(0x0) { DefineOutput(1, TList::Class()); } Bool_t AliAnalysisTaskJetHBOM::Notify() { // // Implemented Notify() to read the cross sections // and number of trials from pyxsec.root // return kTRUE; } void AliAnalysisTaskJetHBOM::UserCreateOutputObjects() { // // Create the output container // fRandom = new TRandom3(0); // Connect the AOD if (fDebug > 1) printf("AnalysisTaskJetHBOM::UserCreateOutputObjects() \n"); if(fNonStdBranch.Length()!=0) { // only create the output branch if we have a name // Create a new branch for jets... // -> cleared in the UserExec.... // here we can also have the case that the brnaches are written to a separate file // create the branch for the random cones with the same R TString cName = Form("%sRandomConeSkip%02d",fNonStdBranch.Data(),fNSkipLeadingCone); if(fUseDiceEfficiency || fUseTrMomentumSmearing) cName = Form("%sDetector%d%d_RandomConeSkip%02d",fNonStdBranch.Data(),fUseTrMomentumSmearing,fUseDiceEfficiency,fNSkipLeadingCone); //create array for the random cones; Until now only one cone per event is used if(!AODEvent()->FindListObject(cName.Data())){ fTCARandomConesOut = new TClonesArray("AliAODJet", 0); fTCARandomConesOut->SetName(cName.Data()); AddAODBranch("TClonesArray",&fTCARandomConesOut,fNonStdFile.Data()); } if(fNonStdFile.Length()!=0){ // // case that we have an AOD extension we need to fetch the jets from the extended output // we identify the extension aod event by looking for the branchname AliAODHandler *aodH = dynamic_cast<AliAODHandler*>(AliAnalysisManager::GetAnalysisManager()->GetOutputEventHandler()); // case that we have an AOD extension we need can fetch the background maybe from the extended output fAODExtension = (aodH?aodH->GetExtension(fNonStdFile.Data()):0); } } // FitMomentumResolution(); if(!fHistList)fHistList = new TList(); fHistList->SetOwner(); PostData(1, fHistList); // post data in any case once Bool_t oldStatus = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); // // Histogram const Int_t nBinPt = 100; Double_t binLimitsPt[nBinPt+1]; for(Int_t iPt = 0;iPt <= nBinPt;iPt++){ if(iPt == 0){ binLimitsPt[iPt] = 0.0; } else {// 1.0 binLimitsPt[iPt] = binLimitsPt[iPt-1] + 2.0; } } const Int_t nBinPhi = 90; Double_t binLimitsPhi[nBinPhi+1]; for(Int_t iPhi = 0;iPhi<=nBinPhi;iPhi++){ if(iPhi==0){ binLimitsPhi[iPhi] = -1.*TMath::Pi(); } else{ binLimitsPhi[iPhi] = binLimitsPhi[iPhi-1] + 1/(Float_t)nBinPhi * TMath::Pi()*2; } } const Int_t nBinEta = 40; Double_t binLimitsEta[nBinEta+1]; for(Int_t iEta = 0;iEta<=nBinEta;iEta++){ if(iEta==0){ binLimitsEta[iEta] = -2.0; } else{ binLimitsEta[iEta] = binLimitsEta[iEta-1] + 0.1; } } const int nChMax = 5000; fh1Xsec = new TProfile("fh1Xsec","xsec from pyxsec.root",1,0,1); fh1Xsec->GetXaxis()->SetBinLabel(1,"<#sigma>"); fh1Trials = new TH1F("fh1Trials","trials root file",1,0,1); fh1Trials->GetXaxis()->SetBinLabel(1,"#sum{ntrials}"); fh1PtHard = new TH1F("fh1PtHard","PYTHIA Pt hard;p_{T,hard}",nBinPt,binLimitsPt); fh1PtHardNoW = new TH1F("fh1PtHardNoW","PYTHIA Pt hard no weight;p_{T,hard}",nBinPt,binLimitsPt); fh1PtHardTrials = new TH1F("fh1PtHardTrials","PYTHIA Pt hard weight with trials;p_{T,hard}",nBinPt,binLimitsPt); fh1Nch = new TH1F("fh1Nch","charged multiplicity; N_{ch}",nChMax,-0.5,nChMax-0.5); fh1Centrality = new TH1F("fh1Centrality",";cent (%)",111,-0.5,110.5); fh1CentralityPhySel = new TH1F("fh1CentralityPhySel",";cent (%)",111,-0.5,110.5); fh1Z = new TH1F("fh1Z",";zvtx",100,-25,25); fh1ZPhySel = new TH1F("fh1ZPhySel",";zvtx",100,-25,25); fh1DeltapT = new TH1F("fh1DeltapT","DeltapT",100,-50,50); fh1Rho = new TH1F("fh1Rho","Rho",100,0,200); fh1RhoSigma = new TH1F("fh1RhoSigma","SigmaRho",40,0,40); fh1PtRandCone = new TH1F("fh1PtRandCone","pt",100,0,200); const Int_t saveLevel = 3; // large save level more histos if(saveLevel>0){ fHistList->Add(fh1Xsec); fHistList->Add(fh1Trials); fHistList->Add(fh1Nch); fHistList->Add(fh1Centrality); fHistList->Add(fh1CentralityPhySel); fHistList->Add(fh1Z); fHistList->Add(fh1ZPhySel); fHistList->Add(fh1DeltapT); fHistList->Add(fh1Rho); fHistList->Add(fh1RhoSigma); fHistList->Add(fh1PtRandCone); } // =========== Switch on Sumw2 for all histos =========== for (Int_t i=0; i<fHistList->GetEntries(); ++i) { TH1 *h1 = dynamic_cast<TH1*>(fHistList->At(i)); if (h1){ h1->Sumw2(); continue; } THnSparse *hn = dynamic_cast<THnSparse*>(fHistList->At(i)); if(hn)hn->Sumw2(); } TH1::AddDirectory(oldStatus); } void AliAnalysisTaskJetHBOM::Init() { // // Initialization // if (fDebug > 1) printf("AnalysisTaskJetHBOM::Init() \n"); FitMomentumResolution(); } void AliAnalysisTaskJetHBOM::UserExec(Option_t */*option*/) { // handle and reset the output jet branch if(fTCARandomConesOut)fTCARandomConesOut->Delete(); // // Execute analysis for current event // AliESDEvent *fESD = 0; if(fUseAODTrackInput){ fAOD = dynamic_cast<AliAODEvent*>(InputEvent()); if(!fAOD){ Printf("%s:%d AODEvent not found in Input Manager %d",(char*)__FILE__,__LINE__,fUseAODTrackInput); return; } // fetch the header } else{ // assume that the AOD is in the general output... fAOD = AODEvent(); if(!fAOD){ Printf("%s:%d AODEvent not found in the Output",(char*)__FILE__,__LINE__); return; } if(fDebug>0){ fESD = dynamic_cast<AliESDEvent*> (InputEvent()); } } //Check if information is provided detector level effects if(!fMomResH1 || !fMomResH2 || !fMomResH3) fUseTrMomentumSmearing = kFALSE; if(!fhEffH1 || !fhEffH2 || !fhEffH3) fUseDiceEfficiency = kFALSE; Bool_t selectEvent = false; Bool_t physicsSelection = true;// handled by the framework(fInputHandler->IsEventSelected()&AliVEvent::kMB)==AliVEvent::kMB; Float_t cent = 0; Float_t zVtx = 0; if(fAOD){ const AliAODVertex *vtxAOD = fAOD->GetPrimaryVertex(); TString vtxTitle(vtxAOD->GetTitle()); zVtx = vtxAOD->GetZ(); cent = ((AliVAODHeader*)fAOD->GetHeader())->GetCentrality(); if(physicsSelection){ fh1CentralityPhySel->Fill(cent); fh1ZPhySel->Fill(zVtx); } // zVertex and centrality selection if(fEventSelection){ if(vtxAOD->GetNContributors()>2&&!vtxTitle.Contains("TPCVertex")){ Float_t yvtx = vtxAOD->GetY(); Float_t xvtx = vtxAOD->GetX(); Float_t r2 = yvtx*yvtx+xvtx*xvtx; if(TMath::Abs(zVtx)<fVtxZCut&&r2<fVtxR2Cut){//usual fVtxZCut=10 and fVtxR2Cut=1 // apply vertex cut later on if(physicsSelection){ selectEvent = true; } } } //centrality selection if(fCentCutUp>0){ if(cent<fCentCutLo||cent>fCentCutUp){ selectEvent = false; } } }else{ selectEvent = true; } } if(!selectEvent){ PostData(1, fHistList); return; } fh1Centrality->Fill(cent); fh1Z->Fill(zVtx); fh1Trials->Fill("#sum{ntrials}",1); if (fDebug > 10)Printf("%s:%d",(char*)__FILE__,__LINE__); // ==== General variables needed // we simply fetch the tracks/mc particles as a list of AliVParticles //reconstructed particles TList recParticles; Int_t nT = GetListOfTracks(&recParticles,fTrackTypeRec); Float_t nCh = recParticles.GetEntries(); fh1Nch->Fill(nCh); if(fDebug>2)Printf("%s:%d Selected Rec tracks: %d %d",(char*)__FILE__,__LINE__,nT,recParticles.GetEntries()); //nT = GetListOfTracks(&genParticles,fTrackTypeGen); //if(fDebug>2)Printf("%s:%d Selected Gen tracks: %d %d",(char*)__FILE__,__LINE__,nT,genParticles.GetEntries()); //apply efficiency fNHBOM times if(fNHBOM>0){ for(int particle=0;particle<recParticles.GetEntries();particle++){ // hier Effizienzen laden und überprüfen ob das Teilchen nachgewiesen wird. AliVParticle *vp = (AliVParticle*)recParticles.At(particle); Double_t pT = vp->Pt(); Double_t phi = vp->Phi(); //load efficiency Double_t efficiencyPt = fh1efficiencyPt->GetBinContent(fh1efficiencyPt->FindBin(pT)); Double_t efficiencyPhi = fh2efficiencyPhi->GetBinContent(fh2efficiencyPhi->FindBin(phi,pT)); Double_t eff = efficiencyPt*efficiencyPhi; //over all efficiency // if ran<eff -> particle is detected eff^fNHBOM = efficiency to detect particle fNHBOM times Double_t ran = fRandom->Rndm(); if(ran>TMath::Power(eff,fNHBOM)){ recParticles.Remove(vp); } } } // find the jets.... vector<fastjet::PseudoJet> inputParticlesRec; vector<fastjet::PseudoJet> inputParticlesRecRan; //randomize particles AliAODJet vTmpRan(1,0,0,1); for(int i = 0; i < recParticles.GetEntries(); i++){ AliVParticle *vp = (AliVParticle*)recParticles.At(i); // Carefull energy is not well determined in real data, should not matter for p_T scheme? // we take total momentum here //Add particles to fastjet in case we are not running toy model fastjet::PseudoJet jInp(vp->Px(),vp->Py(),vp->Pz(),vp->P()); jInp.set_user_index(i); inputParticlesRec.push_back(jInp); // the randomized input changes eta and phi, but keeps the p_T Double_t pT = vp->Pt(); Double_t eta = 2.*fTrackEtaWindow * fRandom->Rndm() - fTrackEtaWindow; Double_t phi = 2.* TMath::Pi() * fRandom->Rndm(); Double_t theta = 2.*TMath::ATan(TMath::Exp(-eta)); Double_t pZ = pT/TMath::Tan(theta); Double_t pX = pT * TMath::Cos(phi); Double_t pY = pT * TMath::Sin(phi); Double_t p = TMath::Sqrt(pT*pT+pZ*pZ); fastjet::PseudoJet jInpRan(pX,pY,pZ,p); jInpRan.set_user_index(i); inputParticlesRecRan.push_back(jInpRan); vTmpRan.SetPxPyPzE(pX,pY,pZ,p); }// recparticles if(inputParticlesRec.size()==0){ if(fDebug)Printf("%s:%d No input particles found, skipping event",(char*)__FILE__,__LINE__); PostData(1, fHistList); return; } // run fast jet // employ setters for these... fastjet::GhostedAreaSpec ghostSpec(fGhostEtamax, fActiveAreaRepeats, fGhostArea); fastjet::AreaType areaType = fastjet::active_area; fastjet::AreaDefinition areaDef = fastjet::AreaDefinition(areaType,ghostSpec); fastjet::JetDefinition jetDef(fAlgorithm, fRparam, fRecombScheme, fStrategy); fastjet::ClusterSequenceArea clustSeq(inputParticlesRec, jetDef,areaDef); //range where to compute background Double_t phiMin = 0, phiMax = 0, rapMin = 0, rapMax = 0; phiMin = 0; phiMax = 2*TMath::Pi(); rapMax = fGhostEtamax - fRparam; rapMin = - fGhostEtamax + fRparam; fastjet::RangeDefinition range(rapMin,rapMax, phiMin, phiMax); const vector <fastjet::PseudoJet> &inclusiveJets = clustSeq.inclusive_jets(); const vector <fastjet::PseudoJet> &sortedJets = sorted_by_pt(inclusiveJets); // loop over all jets and fill information, first one is the leading jet if(inclusiveJets.size()>0){ //background estimates:all bckg jets wo the 2 hardest vector<fastjet::PseudoJet> jets2=sortedJets; if(jets2.size()>2) jets2.erase(jets2.begin(),jets2.begin()+2); //removes the two jets with the highest pT; +2 is correct ro remove 2 jets Double_t bkg1=0; Double_t sigma1=0.; Double_t meanarea1=0.; clustSeq.get_median_rho_and_sigma(jets2, range, true, bkg1, sigma1, meanarea1, true); fh1RhoSigma->Fill(sigma1);// fluctuation of the background background = bkg1;//sets background variable of the task to the correct value // generate random cones if(fTCARandomConesOut){ // create a random jet within the acceptance Double_t etaMax = fTrackEtaWindow - fRparam;//0.9 - 0.4 Int_t nCone = 0; Double_t pTC = 1; // small number Double_t etaC = etaMax*2.*(fRandom->Rndm()-0.5); // +- etamax Double_t phiC = fRandom->Rndm()*2.*TMath::Pi(); // 0 - 2pi // use fixed position for random Cones if(randCone_pos){ etaC = randCone_Eta; phiC = randCone_Phi; } // massless jet Double_t thetaC = 2.*TMath::ATan(TMath::Exp(-etaC)); Double_t pZC = pTC/TMath::Tan(thetaC); Double_t pXC = pTC * TMath::Cos(phiC); Double_t pYC = pTC * TMath::Sin(phiC); Double_t pC = TMath::Sqrt(pTC*pTC+pZC*pZC); AliAODJet tmpRecC (pXC,pYC,pZC, pC); tmpRecC.SetBgEnergy(0,0); // this is use as temporary storage of the summed p_T below if(fTCARandomConesOut)new ((*fTCARandomConesOut)[nCone++]) AliAODJet(tmpRecC); // loop over the reconstructed particles and add up the pT in the random cones // maybe better to loop over randomized particles not in the real jets... // but this by definition brings dow average energy in the whole event AliAODJet vTmpRanR(1,0,0,1); for(int i = 0; i < recParticles.GetEntries(); i++){ AliVParticle *vp = (AliVParticle*)recParticles.At(i); //add up energy in cone if(fTCARandomConesOut){ AliAODJet *jC = (AliAODJet*)fTCARandomConesOut->At(0); if(jC&&jC->DeltaR(vp)<fRparam){ if(vp->Pt()>fMaxTrackPtInJet)jC->SetTrigger(AliAODJet::kHighTrackPtTriggered); jC->SetBgEnergy(jC->ChargedBgEnergy()+vp->Pt(),0); } }// add up energy in cone }// loop over recparticles } //fTCARandomConesOut Float_t jetArea = fRparam*fRparam*TMath::Pi(); if(fTCARandomConesOut){ // rescale the momentum vectors for the random cones AliAODJet *rC = (AliAODJet*)fTCARandomConesOut->At(0); if(rC){ Double_t etaC = rC->Eta(); Double_t phiC = rC->Phi(); // massless jet, unit vector Double_t pTC = rC->ChargedBgEnergy(); if(pTC<=0)pTC = 0.001; // for almost empty events Double_t thetaC = 2.*TMath::ATan(TMath::Exp(-etaC)); Double_t pZC = pTC/TMath::Tan(thetaC); Double_t pXC = pTC * TMath::Cos(phiC); Double_t pYC = pTC * TMath::Sin(phiC); Double_t pC = TMath::Sqrt(pTC*pTC+pZC*pZC); rC->SetPxPyPzE(pXC,pYC,pZC, pC); rC->SetBgEnergy(0,0); rC->SetEffArea(jetArea,0); } } }//inclusive Jets > 0 //Calculate delta pT AliAODJet *randCone = (AliAODJet*)fTCARandomConesOut->At(0); if(randCone){ //background is the backbround density per area and area=pi*0.4^2 -> backgroundCone is the background energy under the cone Float_t backgroundCone = background * randCone->EffectiveAreaCharged(); //calculates difference between expected and measured energy density Float_t ptSub = randCone->Pt() - backgroundCone; fh1DeltapT->Fill(ptSub);// delta pT fh1Rho->Fill(background);// background rho fh1PtRandCone->Fill(randCone->Pt());// pT of random cone }else{ if(fDebug)Printf("%s:%d No random Cone found",(char*)__FILE__,__LINE__); } if (fDebug > 2){ if(fTCARandomConesOut)Printf("%s:%d RC %d",(char*)__FILE__,__LINE__,fTCARandomConesOut->GetEntriesFast()); } PostData(1, fHistList); } void AliAnalysisTaskJetHBOM::Terminate(Option_t */*option*/) { // // Terminate analysis // if (fDebug > 1) printf("AnalysisJetHBOM: Terminate() \n"); if(fMomResH1Fit) delete fMomResH1Fit; if(fMomResH2Fit) delete fMomResH2Fit; if(fMomResH3Fit) delete fMomResH3Fit; } Int_t AliAnalysisTaskJetHBOM::GetListOfTracks(TList *list,Int_t type){ // // get list of tracks/particles for different types // if(fDebug>2)Printf("%s:%d Selecting tracks with %d",(char*)__FILE__,__LINE__,type); Int_t iCount = 0; if(type==kTrackAOD || type==kTrackAODextra || type==kTrackAODextraonly){ if(type!=kTrackAODextraonly) { AliAODEvent *aod = 0; if(fUseAODTrackInput)aod = dynamic_cast<AliAODEvent*>(InputEvent()); else aod = AODEvent(); if(!aod){ if(fDebug>2)Printf("%s:%d No AOD",(char*)__FILE__,__LINE__); return iCount; } for(int it = 0;it < aod->GetNumberOfTracks();++it){ AliAODTrack *tr = dynamic_cast<AliAODTrack*>(aod->GetTrack(it)); if(!tr) AliFatal("Not a standard AOD"); Bool_t bGood = false; if(fFilterType == 0)bGood = true; else if(fFilterType == 1)bGood = tr->IsHybridTPCConstrainedGlobal(); else if(fFilterType == 2)bGood = tr->IsHybridGlobalConstrainedGlobal(); if((fFilterMask>0)&&((!tr->TestFilterBit(fFilterMask)||(!bGood)))){ if(fDebug>10)Printf("%s:%d Not matching filter %d/%d %d/%d",(char*)__FILE__,__LINE__,it,aod->GetNumberOfTracks(),fFilterMask,tr->GetFilterMap()); continue; } if(TMath::Abs(tr->Eta())>fTrackEtaWindow){ if(fDebug>10)Printf("%s:%d Not matching eta %d/%d",(char*)__FILE__,__LINE__,it,aod->GetNumberOfTracks()); continue; } if(tr->Pt()<fTrackPtCut){ if(fDebug>10)Printf("%s:%d Not matching pt %d/%d",(char*)__FILE__,__LINE__,it,aod->GetNumberOfTracks()); continue; } if(fDebug>10)Printf("%s:%d MATCHED %d/%d",(char*)__FILE__,__LINE__,it,aod->GetNumberOfTracks()); list->Add(tr); iCount++; } } if(type==kTrackAODextra || type==kTrackAODextraonly) { AliAODEvent *aod = 0; if(fUseAODTrackInput)aod = dynamic_cast<AliAODEvent*>(InputEvent()); else aod = AODEvent(); if(!aod){ return iCount; } TClonesArray *aodExtraTracks = dynamic_cast<TClonesArray*>(aod->FindListObject("aodExtraTracks")); if(!aodExtraTracks)return iCount; for(int it =0; it<aodExtraTracks->GetEntries(); it++) { AliVParticle *track = dynamic_cast<AliVParticle*> ((*aodExtraTracks)[it]); if (!track) continue; AliAODTrack *trackAOD = dynamic_cast<AliAODTrack*> (track); if(!trackAOD)continue; Bool_t bGood = false; if(fFilterType == 0)bGood = true; else if(fFilterType == 1)bGood = trackAOD->IsHybridTPCConstrainedGlobal(); else if(fFilterType == 2)bGood = trackAOD->IsHybridGlobalConstrainedGlobal(); if((fFilterMask>0)&&((!trackAOD->TestFilterBit(fFilterMask)||(!bGood))))continue; if(TMath::Abs(trackAOD->Eta())>fTrackEtaWindow) continue; if(trackAOD->Pt()<fTrackPtCut) continue; list->Add(trackAOD); iCount++; } } } else if (type == kTrackKineAll||type == kTrackKineCharged){ AliMCEvent* mcEvent = MCEvent(); if(!mcEvent)return iCount; // we want to have alivpartilces so use get track for(int it = 0;it < mcEvent->GetNumberOfTracks();++it){ if(!mcEvent->IsPhysicalPrimary(it))continue; AliMCParticle* part = (AliMCParticle*)mcEvent->GetTrack(it); if(type == kTrackKineAll){ if(part->Pt()<fTrackPtCut)continue; list->Add(part); iCount++; } else if(type == kTrackKineCharged){ if(part->Particle()->GetPDG()->Charge()==0)continue; if(part->Pt()<fTrackPtCut)continue; list->Add(part); iCount++; } } } else if (type == kTrackAODMCCharged || type == kTrackAODMCAll || type == kTrackAODMCChargedAcceptance) { AliAODEvent *aod = 0; if(fUseAODMCInput)aod = dynamic_cast<AliAODEvent*>(InputEvent()); else aod = AODEvent(); if(!aod)return iCount; TClonesArray *tca = dynamic_cast<TClonesArray*>(aod->FindListObject(AliAODMCParticle::StdBranchName())); if(!tca)return iCount; for(int it = 0;it < tca->GetEntriesFast();++it){ AliAODMCParticle *part = (AliAODMCParticle*)(tca->At(it)); if(!part->IsPhysicalPrimary())continue; if(type == kTrackAODMCAll){ if(part->Pt()<fTrackPtCut)continue; list->Add(part); iCount++; } else if (type == kTrackAODMCCharged || type == kTrackAODMCChargedAcceptance ){ if(part->Charge()==0)continue; if(part->Pt()<fTrackPtCut)continue; if(kTrackAODMCCharged){ list->Add(part); } else { if(TMath::Abs(part->Eta())>fTrackEtaWindow)continue; list->Add(part); } iCount++; } } }// AODMCparticle list->Sort(); return iCount; } void AliAnalysisTaskJetHBOM::SetMomentumResolutionHybrid(TProfile *p1, TProfile *p2, TProfile *p3) { // // set mom res profiles // fMomResH1 = (TProfile*)p1->Clone("fMomResH1"); fMomResH2 = (TProfile*)p2->Clone("fMomResH2"); fMomResH3 = (TProfile*)p3->Clone("fMomResH3"); } void AliAnalysisTaskJetHBOM:: SetEfficiencyHybrid(TH1 *h1, TH1 *h2, TH1 *h3) { // // set tracking efficiency histos // fhEffH1 = (TH1*)h1->Clone("fhEffH1"); fhEffH2 = (TH1*)h2->Clone("fhEffH2"); fhEffH3 = (TH1*)h3->Clone("fhEffH3"); } Double_t AliAnalysisTaskJetHBOM::GetMomentumSmearing(Int_t cat, Double_t pt) { // // Get smearing on generated momentum // //printf("GetMomentumSmearing for cat %d and pt = %f \n",cat,pt); TProfile *fMomRes = 0x0; if(cat==1) fMomRes = (TProfile*)fMomResH1->Clone("fMomRes"); if(cat==2) fMomRes = (TProfile*)fMomResH2->Clone("fMomRes"); if(cat==3) fMomRes = (TProfile*)fMomResH3->Clone("fMomRes"); if(!fMomRes) { return 0.; } Double_t smear = 0.; if(pt>20.) { if(cat==1 && fMomResH1Fit) smear = fMomResH1Fit->Eval(pt); if(cat==2 && fMomResH2Fit) smear = fMomResH2Fit->Eval(pt); if(cat==3 && fMomResH3Fit) smear = fMomResH3Fit->Eval(pt); } else { Int_t bin = fMomRes->FindBin(pt); smear = fRandom->Gaus(fMomRes->GetBinContent(bin),fMomRes->GetBinError(bin)); } if(fMomRes) delete fMomRes; return smear; } void AliAnalysisTaskJetHBOM::FitMomentumResolution() { // // Fit linear function on momentum resolution at high pT // if(!fMomResH1Fit && fMomResH1) { fMomResH1Fit = new TF1("fMomResH1Fit","[0]+[1]*x",0.,200.); fMomResH1->Fit(fMomResH1Fit,"LL V0","",5.,30.); fMomResH1Fit ->SetRange(5.,100.); } if(!fMomResH2Fit && fMomResH2) { fMomResH2Fit = new TF1("fMomResH2Fit","[0]+[1]*x",0.,200.); fMomResH2->Fit(fMomResH2Fit,"LL V0","",5.,30.); fMomResH2Fit ->SetRange(5.,100.); } if(!fMomResH3Fit && fMomResH3) { fMomResH3Fit = new TF1("fMomResH3Fit","[0]+[1]*x",0.,200.); fMomResH3->Fit(fMomResH3Fit,"LL V0","",5.,30.); fMomResH3Fit ->SetRange(5.,100.); } }
30.257393
168
0.662045
[ "vector", "model" ]
e48cb541113c832f477e933797f3c3414671dc05
4,143
cpp
C++
AVSCommon/AVS/src/CapabilitySemantics/StatesToValueMapping.cpp
tsweet77/avs-device-sdk
703b06188eae146af396f58be4e47442d7ce5b1e
[ "Apache-2.0" ]
1
2018-07-09T16:44:28.000Z
2018-07-09T16:44:28.000Z
AVSCommon/AVS/src/CapabilitySemantics/StatesToValueMapping.cpp
tsweet77/avs-device-sdk
703b06188eae146af396f58be4e47442d7ce5b1e
[ "Apache-2.0" ]
null
null
null
AVSCommon/AVS/src/CapabilitySemantics/StatesToValueMapping.cpp
tsweet77/avs-device-sdk
703b06188eae146af396f58be4e47442d7ce5b1e
[ "Apache-2.0" ]
2
2019-02-05T23:42:48.000Z
2020-03-01T11:11:30.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <AVSCommon/AVS/CapabilitySemantics/StatesToValueMapping.h> #include <AVSCommon/Utils/JSON/JSONGenerator.h> #include <AVSCommon/Utils/Logger/Logger.h> #include <algorithm> #include <limits> namespace alexaClientSDK { namespace avsCommon { namespace avs { namespace capabilitySemantics { /// The "@type" key of mapping object JSON. static const std::string TYPE_KEY("@type"); /// The "StatesToValue" mapping type. static const std::string MAPPING_TYPE_VALUE("StatesToValue"); /// The "states" key of mapping object JSON. static const std::string STATES_KEY("states"); /// The "value" key of mapping object JSON. static const std::string VALUE_KEY("value"); /// Indicates @c m_doubleValue is not initialized. static constexpr double UNINITIALIZED_DOUBLE = std::numeric_limits<double>::min(); /// Indicates @c m_stringValue is not initialized. static std::string UNINITIALIZED_STRING = ""; /// Empty JSON object. static const std::string EMPTY_JSON("{}"); /// String to identify log entries originating from this file. static const std::string TAG("StatesToValueMapping"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param event The event string for this @c LogEntry. */ #define LX(event) utils::logger::LogEntry(TAG, event) StatesToValueMapping::StatesToValueMapping() : m_isValid{true}, m_stringValue{UNINITIALIZED_STRING}, m_doubleValue{UNINITIALIZED_DOUBLE} { } bool StatesToValueMapping::addState(const std::string& stateId) { if (stateId.empty()) { ACSDK_ERROR(LX("addStateFailed").d("reason", "emptyStateId")); m_isValid = false; return false; } if (std::find(m_states.begin(), m_states.end(), stateId) != m_states.end()) { ACSDK_ERROR(LX("addStateFailed").d("reason", "duplicateStateId").d("stateId", stateId)); m_isValid = false; return false; } m_states.push_back(stateId); return true; } bool StatesToValueMapping::setValue(const std::string& value) { if (isValueSet()) { ACSDK_ERROR(LX("setValueFailed").d("reason", "valueAlreadySet")); m_isValid = false; return false; } if (value.empty()) { ACSDK_ERROR(LX("setValueFailed").d("reason", "emptyValue")); m_isValid = false; return false; } m_stringValue = value; return true; } bool StatesToValueMapping::setValue(double value) { if (isValueSet()) { ACSDK_ERROR(LX("setValueFailed").d("reason", "valueAlreadySet")); m_isValid = false; return false; } m_doubleValue = value; return true; } bool StatesToValueMapping::isValid() const { return m_isValid && isValueSet() && !m_states.empty(); } std::string StatesToValueMapping::toJson() const { if (!isValid()) { ACSDK_ERROR(LX("toJsonFailed").d("reason", "invalidStatesToValueMapping")); return EMPTY_JSON; } utils::json::JsonGenerator jsonGenerator; jsonGenerator.addMember(TYPE_KEY, MAPPING_TYPE_VALUE); jsonGenerator.addStringArray(STATES_KEY, m_states); if (m_stringValue != UNINITIALIZED_STRING) { jsonGenerator.addMember(VALUE_KEY, m_stringValue); } else { jsonGenerator.addMember(VALUE_KEY, m_doubleValue); } return jsonGenerator.toString(); } bool StatesToValueMapping::isValueSet() const { return m_stringValue != UNINITIALIZED_STRING || m_doubleValue != UNINITIALIZED_DOUBLE; } } // namespace capabilitySemantics } // namespace avs } // namespace avsCommon } // namespace alexaClientSDK
30.91791
96
0.698769
[ "object" ]
e48ebc59109c4d3b550fa9502d91a85c40f8d175
24,596
cpp
C++
src/curvemesh/curvemesh.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
src/curvemesh/curvemesh.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
src/curvemesh/curvemesh.cpp
GarethNelson/ares
fb2b2d25f000a3e0aa974ff08a3f0ec8fc89845e
[ "MIT" ]
null
null
null
/* The MIT License Copyright (c) 2010 by Jorrit Tyberghein 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 "cssysdef.h" #include "csutil/event.h" #include "csutil/eventnames.h" #include "csutil/eventhandlers.h" #include "csutil/stringarray.h" #include "csutil/csstring.h" #include "csutil/xmltiny.h" #include "csutil/scfstr.h" #include "csutil/scanstr.h" #include "iutil/objreg.h" #include "iutil/object.h" #include "iutil/eventh.h" #include "iutil/plugin.h" #include "csgeom/tri.h" #include "imap/services.h" #include "iengine/movable.h" #include "iengine/sector.h" #include "curvemesh.h" #define VERBOSE 0 CS_PLUGIN_NAMESPACE_BEGIN(CurvedMesh) { //--------------------------------------------------------------------------------------- void ClingyPath::SetBasePoints (const csArray<PathEntry> pts) { basePoints = pts; size_t l = pts.GetSize (); float totalDistance = 0.0f; for (size_t i = 0 ; i < l-1 ; i++) { float dist = sqrt (csSquaredDist::PointPoint (pts[i].pos, pts[i+1].pos)); totalDistance += dist; } float travelDistance = 0.0f; basePoints[0].time = 0.0f; for (size_t i = 1 ; i < l ; i++) { travelDistance += sqrt (csSquaredDist::PointPoint (pts[i-1].pos, pts[i].pos)); basePoints[i].time = travelDistance / totalDistance; } } void ClingyPath::RefreshWorkingPath () { points = basePoints; } static bool HeightDiff (const csVector3& pos, iMeshWrapper* thisMesh, float& dy) { const csReversibleTransform& meshtrans = thisMesh->GetMovable ()->GetTransform (); csVector3 p = meshtrans.This2Other (pos); iSector* sector = thisMesh->GetMovable ()->GetSectors ()->Get (0); csSectorHitBeamResult result = sector->HitBeamPortals ( p + csVector3 (0, 2, 0), p - csVector3 (0, 2, 0)); if (result.mesh) { dy = p.y - result.isect.y; return true; } else { dy = 0.0f; return false; } } //#define BOTTOM_MARGIN .02f //#define TOP_MARGIN 1.0f #define BOTTOM_MARGIN .1f #define TOP_MARGIN .1f static float cmax (bool u1, float v1, bool u2, float v2) { if (u1 && u2) return csMax (v1, v2); else if (u1) return v1; return v2; } void ClingyPath::FitToTerrain (size_t idx, float width, iMeshWrapper* thisMesh) { const csVector3& pos = points[idx].pos; csVector3 right = (width / 2.0) * (points[idx].front % points[idx].up); csVector3 rightPos = pos + right; csVector3 leftPos = pos - right; float dyL, dy, dyR; bool hL = HeightDiff (leftPos, thisMesh, dyL); bool h = HeightDiff (pos, thisMesh, dy); bool hR = HeightDiff (rightPos, thisMesh, dyR); if ((hL && dyL > TOP_MARGIN) || (hR && dyR > TOP_MARGIN)) { // First we lower the segment. After that we check if it is // not too low. float lowerY = cmax (hL, dyL-TOP_MARGIN, hR, dyR-TOP_MARGIN); points[idx].pos.y -= lowerY; dy -= lowerY; dyL -= lowerY; dyR -= lowerY; # if VERBOSE printf (" FitToTerrain %d, dy=%g/%g/%g, lowerY=%g\n", idx, dyL, dy, dyR, lowerY); fflush (stdout); # endif } if ((hL && dyL < BOTTOM_MARGIN) || (h && dy < BOTTOM_MARGIN) || (hR && dyR < BOTTOM_MARGIN)) { // Some part of this point gets (almost) under the terrain. Need to raise // everything. float raiseY = cmax (hL, BOTTOM_MARGIN-dyL, hR, BOTTOM_MARGIN-dyR); raiseY = cmax (true, raiseY, h, BOTTOM_MARGIN-dy); points[idx].pos.y += raiseY; # if VERBOSE printf (" FitToTerrain %d, dy=%g/%g/%g, raiseY=%g\n", idx, dyL, dy, dyR, raiseY); fflush (stdout); # endif } else { # if VERBOSE printf (" FitToTerrain %d, dy=%g/%g/%g\n", idx, dyL, dy, dyR); fflush (stdout); # endif } } void ClingyPath::FixSlope (size_t idx) { if (points.GetSize () <= 1) return; const csVector3& pos = points[idx].pos; csVector3 fr; if (idx == 0) { csVector3& p2 = points[idx+1].pos; fr = (p2 - pos).Unit (); } else if (idx == points.GetSize ()-1) { csVector3& p1 = points[idx-1].pos; fr = (pos - p1).Unit (); } else { csVector3& p1 = points[idx-1].pos; csVector3& p2 = points[idx+1].pos; fr = ((p2 - pos).Unit () + (pos - p1).Unit ()) / 2.0; } csVector3 right = fr % points[idx].up; points[idx].up = - (fr % right).Unit (); } static float Distance2d (const csVector3& p1, const csVector3& p2) { csVector2 p1two (p1.x, p1.z); csVector2 p2two (p2.x, p2.z); csVector2 d = p1two - p2two; return sqrt (d*d); } float ClingyPath::GetTotalDistance () { size_t l = points.GetSize (); float totalDistance = 0.0f; for (size_t i = 0 ; i < l-1 ; i++) { float dist = sqrt (csSquaredDist::PointPoint (points[i].pos, points[i+1].pos)); //float dist = Distance2d (points[i].pos, points[i+1].pos); totalDistance += dist; } return totalDistance; } void ClingyPath::GeneratePath (csPath& path) { size_t l = points.GetSize (); path.Setup (l); for (size_t i = 0 ; i < l ; i++) { path.SetTime (i, points[i].time); path.SetPositionVector (i, points[i].pos); path.SetForwardVector (i, points[i].front); path.SetUpVector (i, points[i].up); # if VERBOSE printf (" path %d (%g): pos:%g,%g,%g front:%g,%g,%g up:%g,%g,%g\n", i, points[i].time, points[i].pos.x, points[i].pos.y, points[i].pos.z, points[i].front.x, points[i].front.y, points[i].front.z, points[i].up.x, points[i].up.y, points[i].up.z); # endif } } void ClingyPath::GetSegmentTime (const csPath& path, size_t segIdx, float& startTime, float& endTime) { const float* times = path.GetTimes (); startTime = times[segIdx]; endTime = times[segIdx+1]; } #define PATH_STEP .1f #define LOOSE_BOTTOM_MARGIN .02f #define LOOSE_TOP_MARGIN 1.0f void ClingyPath::CalcMinMaxDY (size_t segIdx, float width, iMeshWrapper* thisMesh, float& maxRaiseY, float& maxLowerY) { csPath path (1); GeneratePath (path); float startTime, endTime; GetSegmentTime (path, segIdx, startTime, endTime); maxRaiseY = -1.0f; maxLowerY = -1.0f; float dist = sqrt (csSquaredDist::PointPoint (points[segIdx].pos, points[segIdx+1].pos)); int steps = int (dist / PATH_STEP); if (steps <= 1) return; // Segment is too small. Don't do anything. float timeStep = (endTime-startTime) / float (steps); if (timeStep < 0.0001) return; // Segment is too small. Don't do anything. # if VERBOSE printf (" CalcMinMaxDY: segIdx=%d dist=%g steps=%d time:%g/%g timeStep=%g\n", segIdx, dist, steps, startTime, endTime, timeStep); Dump (10); # endif for (float t = startTime ; t <= endTime ; t += timeStep) { path.CalculateAtTime (t); csVector3 pos, front, up; path.GetInterpolatedPosition (pos); path.GetInterpolatedForward (front); path.GetInterpolatedUp (up); csVector3 right = (width / 2.0) * (front % up); csVector3 rightPos = pos + right; csVector3 leftPos = pos - right; float dyL, dy, dyR; bool hL = HeightDiff (leftPos, thisMesh, dyL); bool h = HeightDiff (pos, thisMesh, dy); bool hR = HeightDiff (rightPos, thisMesh, dyR); if ((hL && dyL > LOOSE_TOP_MARGIN) || (hR && dyR > LOOSE_TOP_MARGIN)) { float lowerY = cmax (hL, dyL-LOOSE_TOP_MARGIN, hR, dyR-LOOSE_TOP_MARGIN); if (lowerY > 0.0f) { if (hL && dyL-lowerY < LOOSE_BOTTOM_MARGIN) lowerY = dyL - LOOSE_BOTTOM_MARGIN; if (hR && dyR-lowerY < LOOSE_BOTTOM_MARGIN) lowerY = dyR - LOOSE_BOTTOM_MARGIN; if (h && dy-lowerY < LOOSE_BOTTOM_MARGIN) lowerY = dy - LOOSE_BOTTOM_MARGIN; } if (lowerY > maxLowerY) maxLowerY = lowerY; # if VERBOSE printf (" CalcMinMaxDY %g, dy=%g/%g/%g, lowerY=%g\n", t, dyL, dy, dyR, lowerY); fflush (stdout); # endif } if ((hL && dyL < LOOSE_BOTTOM_MARGIN) || (h && dy < LOOSE_BOTTOM_MARGIN) || (hR && dyR < LOOSE_BOTTOM_MARGIN)) { // Some part of this point gets (almost) under the terrain. Need to raise // everything. float raiseY = cmax (hL, LOOSE_BOTTOM_MARGIN-dyL, hR, LOOSE_BOTTOM_MARGIN-dyR); raiseY = cmax (true, raiseY, h, LOOSE_BOTTOM_MARGIN-dy); if (raiseY > maxRaiseY) maxRaiseY = raiseY; # if VERBOSE printf (" CalcMinMaxDY %g, dy=%g/%g/%g, raiseY=%g\n", t, dyL, dy, dyR, raiseY); fflush (stdout); # endif } else { # if VERBOSE printf (" CalcMinMaxDY %g, dy=%g/%g/%g\n", t, dyL, dy, dyR); fflush (stdout); # endif } } } static float FindHorizontalMiddlePoint (csPath& path, float error, float t1, const csVector3& pos1, float t2, const csVector3& pos2) { float time = (t1+t2) / 2.0f; path.CalculateAtTime (time); csVector3 pos; path.GetInterpolatedPosition (pos); float d1 = Distance2d (pos1, pos); float d2 = Distance2d (pos, pos2); # if VERBOSE printf ("t1=%g t2=%g time=%g d1=%g d2=%g error=%g\n", t1, t2, time, d1, d2, error); fflush (stdout); # endif if (fabs (d1-d2) < error) return time; if (d1 > d2) return FindHorizontalMiddlePoint (path, error, t1, pos1, time, pos); else return FindHorizontalMiddlePoint (path, error, time, pos, t2, pos2); } void ClingyPath::SplitSegment (size_t segIdx) { csPath path (1); GeneratePath (path); float startTime, endTime; GetSegmentTime (path, segIdx, startTime, endTime); //float time = (startTime+endTime) / 2.0f; csVector3 pos1, pos2; path.CalculateAtTime (startTime); path.GetInterpolatedPosition (pos1); path.CalculateAtTime (endTime); path.GetInterpolatedPosition (pos2); float time = FindHorizontalMiddlePoint (path, 0.01f, startTime, pos1, endTime, pos2); path.CalculateAtTime (time); PathEntry pe; pe.time = time; path.GetInterpolatedPosition (pe.pos); path.GetInterpolatedForward (pe.front); path.GetInterpolatedUp (pe.up); # if VERBOSE printf (" Split segment %d (time: %g/%g -> %g) pos=%g,%g,%g\n", segIdx, startTime, endTime, time, pe.pos.x, pe.pos.y, pe.pos.z); printf (" seg1: %g,%g,%g\n", points[segIdx].pos.x, points[segIdx].pos.y, points[segIdx].pos.z); printf (" seg2: %g,%g,%g\n", points[segIdx+1].pos.x, points[segIdx+1].pos.y, points[segIdx+1].pos.z); fflush (stdout); # endif points.Insert (segIdx+1, pe); } void ClingyPath::Flatten (iMeshWrapper* thisMesh, float width) { RefreshWorkingPath (); // Flatten the terrain first. for (size_t i = 0 ; i < points.GetSize () ; i++) FitToTerrain (i, width, thisMesh); Dump (2); // Now fix the slope. for (size_t i = 0 ; i < points.GetSize () ; i++) FixSlope (i); size_t segIdx = 0; float maxRaiseY, maxLowerY; while (segIdx < points.GetSize ()-1) { CalcMinMaxDY (segIdx, width, thisMesh, maxRaiseY, maxLowerY); if (maxRaiseY > 0.0f || maxLowerY > 0.0f) { // The segment needs improving. Let's split it. SplitSegment (segIdx); FitToTerrain (segIdx+1, width, thisMesh); FixSlope (segIdx); FixSlope (segIdx+1); FixSlope (segIdx+2); } else { // This segment is ok. We can go to the next. segIdx++; } } } void ClingyPath::Dump (int indent) { # if VERBOSE static char* sspaces = " "; char spaces[100]; strcpy (spaces, sspaces); spaces[indent] = 0; for (size_t i = 0 ; i < points.GetSize () ; i++) printf ("%s%d: pos:%g,%g,%g front:%g,%g,%g up:%g,%g,%g\n", spaces, i, points[i].pos.x, points[i].pos.y, points[i].pos.z, points[i].front.x, points[i].front.y, points[i].front.z, points[i].up.x, points[i].up.y, points[i].up.z ); fflush (stdout); spaces[indent] = ' '; # endif } //--------------------------------------------------------------------------------------- CurvedFactory::CurvedFactory (CurvedMeshCreator* creator, const char* name) : scfImplementationType (this), creator (creator), name (name) { material = 0; width = 1.0f; sideHeight = 0.4f; offsetHeight = 0.1f; factory = creator->engine->CreateMeshFactory ( "crystalspace.mesh.object.genmesh", name); state = scfQueryInterface<iGeneralFactoryState> (factory->GetMeshObjectFactory ()); } CurvedFactory::~CurvedFactory () { } void CurvedFactory::GenerateGeometry (iMeshWrapper* thisMesh) { # if VERBOSE printf ("#############################################################\n"); fflush (stdout); # endif csFlags oldFlags = thisMesh->GetFlags (); thisMesh->GetFlags ().Set (CS_ENTITY_NOHITBEAM); clingyPath.SetBasePoints (anchorPoints); # if VERBOSE printf ("GenerateGeometry: Flatten\n"); fflush (stdout); # endif clingyPath.Flatten (thisMesh, width); csPath path (1); # if VERBOSE printf ("GenerateGeometry: GeneratePath\n"); fflush (stdout); # endif clingyPath.GeneratePath (path); printf ("Path has %d control points\n", int (clingyPath.GetWorkingPointCount ())); fflush (stdout); float totalDistance = clingyPath.GetTotalDistance (); // @@@todo, the entire detail on the path should be customizable. Also it should // use less detail on relatively straight lines. float samplesPerUnit = 1.0; // Calculate a rounded number of samples from the samplesPerUnit and // then correct samplesPerUnit so that the samples are evenly spread. size_t samples = size_t (totalDistance / samplesPerUnit) + 1; samplesPerUnit = totalDistance / (samples - 1); state->SetVertexCount (samples * 4); state->SetTriangleCount ((samples-1) * 6); csVector3 pos, front, up, prevPos; csVector3* vertices = state->GetVertices (); csVector3* normals = state->GetNormals (); csVector2* texels = state->GetTexels (); path.CalculateAtTime (0); path.GetInterpolatedPosition (prevPos); float traveledDistance = 0; for (size_t i = 0 ; i < samples ; i++) { float time = float (i) / float (samples-1); path.CalculateAtTime (time); path.GetInterpolatedPosition (pos); traveledDistance += sqrt (csSquaredDist::PointPoint (pos, prevPos)); //printf ("%d time=%g pos=%g,%g,%g dist=%g\n", i, time, pos.x, pos.y, pos.z, traveledDistance); fflush (stdout); prevPos = pos; path.GetInterpolatedForward (front); path.GetInterpolatedUp (up); csVector3 right = (width / 2.0) * (front % up); csVector3 down = -up.Unit () * sideHeight; csVector3 offsetUp = up.Unit () * offsetHeight; csVector3 rightPos = pos + right; csVector3 leftPos = pos - right; rightPos += offsetUp; leftPos += offsetUp; *vertices++ = rightPos; *vertices++ = leftPos; *vertices++ = rightPos + down; *vertices++ = leftPos + down; *normals++ = (up*.8+right*.2).Unit (); *normals++ = (up*.8-right*.2).Unit (); *normals++ = right; *normals++ = -right; *texels++ = csVector2 (0, traveledDistance / width); *texels++ = csVector2 (1, traveledDistance / width); *texels++ = csVector2 (-width/sideHeight, traveledDistance / width); *texels++ = csVector2 (width/sideHeight, traveledDistance / width); } csTriangle* tris = state->GetTriangles (); int vtidx = 0; for (size_t i = 0 ; i < samples-1 ; i++) { *tris++ = csTriangle (vtidx+5, vtidx+1, vtidx+0); *tris++ = csTriangle (vtidx+4, vtidx+5, vtidx+0); *tris++ = csTriangle (vtidx+6, vtidx+4, vtidx+0); *tris++ = csTriangle (vtidx+2, vtidx+6, vtidx+0); *tris++ = csTriangle (vtidx+3, vtidx+1, vtidx+7); *tris++ = csTriangle (vtidx+7, vtidx+1, vtidx+5); vtidx += 4; } factory->GetMeshObjectFactory ()->SetMaterialWrapper (material); state->Invalidate (); thisMesh->GetFlags ().SetAll (oldFlags.Get ()); } void CurvedFactory::SetMaterial (const char* materialName) { material = creator->engine->FindMaterial (materialName); if (!material) { printf ("Could not find material '%s' for curve factory '%s'!\n", materialName, name.GetData ()); fflush (stdout); } } void CurvedFactory::SetCharacteristics (float width, float sideHeight) { CurvedFactory::width = width; CurvedFactory::sideHeight = sideHeight; } size_t CurvedFactory::AddPoint (const csVector3& pos, const csVector3& front, const csVector3& up) { return anchorPoints.Push (PathEntry (pos, front.Unit (), up.Unit ())); } void CurvedFactory::ChangePoint (size_t idx, const csVector3& pos, const csVector3& front, const csVector3& up) { anchorPoints[idx] = PathEntry (pos, front.Unit (), up.Unit ()); } void CurvedFactory::DeletePoint (size_t idx) { anchorPoints.DeleteIndex (idx); } void CurvedFactory::Save (iDocumentNode* node, iSyntaxService* syn) { node->SetAttribute ("name", name); node->SetAttributeAsFloat ("width", width); node->SetAttributeAsFloat ("sideheight", sideHeight); node->SetAttribute ("material", material->QueryObject ()->GetName ()); size_t i; for (i = 0 ; i < anchorPoints.GetSize () ; i++) { csRef<iDocumentNode> el = node->CreateNodeBefore (CS_NODE_ELEMENT); el->SetValue ("p"); csString vector; vector.Format ("%g %g %g", anchorPoints[i].pos.x, anchorPoints[i].pos.y, anchorPoints[i].pos.z); el->SetAttribute ("pos", (const char*)vector); vector.Format ("%g %g %g", anchorPoints[i].front.x, anchorPoints[i].front.y, anchorPoints[i].front.z); el->SetAttribute ("front", (const char*)vector); vector.Format ("%g %g %g", anchorPoints[i].up.x, anchorPoints[i].up.y, anchorPoints[i].up.z); el->SetAttribute ("up", (const char*)vector); } } bool CurvedFactory::Load (iDocumentNode* node, iSyntaxService* syn) { width = node->GetAttributeValueAsFloat ("width"); if (fabs (width) < .0001) width = 1.0; sideHeight = node->GetAttributeValueAsFloat ("sideheight"); if (fabs (sideHeight) < 0.0001f) sideHeight = 0.2f; csString materialName = node->GetAttributeValue ("material"); SetMaterial (materialName); anchorPoints.DeleteAll (); csRef<iDocumentNodeIterator> it = node->GetNodes (); while (it->HasNext ()) { csRef<iDocumentNode> child = it->Next (); if (child->GetType () != CS_NODE_ELEMENT) continue; csString value = child->GetValue (); if (value == "p") { csVector3 pos, front (0, 0, 1), up (0, 1, 0); csString vector = child->GetAttributeValue ("pos"); if (vector.Length () > 0) csScanStr ((const char*)vector, "%f %f %f", &pos.x, &pos.y, &pos.z); vector = child->GetAttributeValue ("front"); if (vector.Length () > 0) csScanStr ((const char*)vector, "%f %f %f", &front.x, &front.y, &front.z); vector = child->GetAttributeValue ("up"); if (vector.Length () > 0) csScanStr ((const char*)vector, "%f %f %f", &up.x, &up.y, &up.z); AddPoint (pos, front, up); } } return true; } //--------------------------------------------------------------------------------------- CurvedFactoryTemplate::CurvedFactoryTemplate (CurvedMeshCreator* creator, const char* name) : scfImplementationType (this), creator (creator), name (name) { width = 1.0f; sideHeight = 0.2f; } CurvedFactoryTemplate::~CurvedFactoryTemplate () { } void CurvedFactoryTemplate::SetAttribute (const char* name, const char* value) { attributes.Put (name, value); } const char* CurvedFactoryTemplate::GetAttribute (const char* name) const { return attributes.Get (name, (const char*)0); } void CurvedFactoryTemplate::SetMaterial (const char* materialName) { material = materialName; } void CurvedFactoryTemplate::SetCharacteristics (float width, float sideHeight) { CurvedFactoryTemplate::width = width; CurvedFactoryTemplate::sideHeight = sideHeight; } size_t CurvedFactoryTemplate::AddPoint (const csVector3& pos, const csVector3& front, const csVector3& up) { return points.Push (PathEntry (pos, front.Unit (), up.Unit ())); } //--------------------------------------------------------------------------------------- SCF_IMPLEMENT_FACTORY (CurvedMeshCreator) CurvedMeshCreator::CurvedMeshCreator (iBase *iParent) : scfImplementationType (this, iParent) { object_reg = 0; } CurvedMeshCreator::~CurvedMeshCreator () { } bool CurvedMeshCreator::Initialize (iObjectRegistry *object_reg) { CurvedMeshCreator::object_reg = object_reg; engine = csQueryRegistry<iEngine> (object_reg); return true; } void CurvedMeshCreator::DeleteFactories () { size_t i; for (i = 0 ; i < factories.GetSize () ; i++) engine->RemoveObject (factories[i]->GetFactory ()); factories.DeleteAll (); factory_hash.Empty (); } iCurvedFactoryTemplate* CurvedMeshCreator::AddCurvedFactoryTemplate (const char* name) { CurvedFactoryTemplate* cf = new CurvedFactoryTemplate (this, name); factoryTemplates.Push (cf); cf->DecRef (); return cf; } CurvedFactoryTemplate* CurvedMeshCreator::FindFactoryTemplate (const char* name) { size_t i; csString tn = name; for (i = 0 ; i < factoryTemplates.GetSize () ; i++) { if (tn == factoryTemplates[i]->GetName ()) return factoryTemplates[i]; } return 0; } void CurvedMeshCreator::DeleteCurvedFactoryTemplates () { factoryTemplates.DeleteAll (); } iCurvedFactory* CurvedMeshCreator::AddCurvedFactory (const char* name, const char* templatename) { CurvedFactoryTemplate* cftemp = FindFactoryTemplate (templatename); if (!cftemp) { printf ("ERROR! Can't find factory template '%s'!\n", templatename); return 0; } CurvedFactory* cf = new CurvedFactory (this, name); cf->SetMaterial (cftemp->GetMaterial ()); cf->SetCharacteristics (cftemp->GetWidth (), cftemp->GetSideHeight ()); const csArray<PathEntry>& points = cftemp->GetPoints (); for (size_t i = 0 ; i < points.GetSize () ; i++) cf->AddPoint (points[i].pos, points[i].front, points[i].up); factories.Push (cf); factory_hash.Put (name, cf); cf->DecRef (); return cf; } void CurvedMeshCreator::Save (iDocumentNode* node) { csRef<iSyntaxService> syn = csQueryRegistryOrLoad<iSyntaxService> (object_reg, "crystalspace.syntax.loader.service.text"); for (size_t i = 0 ; i < factories.GetSize () ; i++) { csRef<iDocumentNode> el = node->CreateNodeBefore (CS_NODE_ELEMENT); el->SetValue ("fact"); factories[i]->Save (el, syn); } } csRef<iString> CurvedMeshCreator::Load (iDocumentNode* node) { csRef<iSyntaxService> syn = csQueryRegistryOrLoad<iSyntaxService> (object_reg, "crystalspace.syntax.loader.service.text"); csRef<iDocumentNodeIterator> it = node->GetNodes (); while (it->HasNext ()) { csRef<iDocumentNode> child = it->Next (); if (child->GetType () != CS_NODE_ELEMENT) continue; csString value = child->GetValue (); if (value == "fact") { csRef<CurvedFactory> cfact; csString name = child->GetAttributeValue ("name"); cfact.AttachNew (new CurvedFactory (this, name)); if (!cfact->Load (child, syn)) { csRef<iString> str; str.AttachNew (new scfString ("Error loading factory!")); return str; } factories.Push (cfact); factory_hash.Put (name, cfact); } } return 0; } } CS_PLUGIN_NAMESPACE_END(CurvedMesh)
31.055556
117
0.626281
[ "mesh", "object", "vector" ]
e492e7a0724e011a9d57965f0363a654720dc9d4
41,141
cpp
C++
libredex/ReflectionAnalysis.cpp
kami-lang/madex-redex
90ae1bc46c6e20a0aed2c128183b9f289cecee34
[ "MIT" ]
null
null
null
libredex/ReflectionAnalysis.cpp
kami-lang/madex-redex
90ae1bc46c6e20a0aed2c128183b9f289cecee34
[ "MIT" ]
null
null
null
libredex/ReflectionAnalysis.cpp
kami-lang/madex-redex
90ae1bc46c6e20a0aed2c128183b9f289cecee34
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ReflectionAnalysis.h" #include <iomanip> #include <ostream> #include <unordered_map> #include <boost/optional.hpp> #include "BaseIRAnalyzer.h" #include "ControlFlow.h" #include "FiniteAbstractDomain.h" #include "HashedSetAbstractDomain.h" #include "IRCode.h" #include "IRInstruction.h" #include "IROpcode.h" #include "PatriciaTreeMapAbstractEnvironment.h" #include "ReducedProductAbstractDomain.h" #include "Resolver.h" #include "Show.h" #include "Trace.h" using namespace sparta; std::ostream& operator<<(std::ostream& out, const std::unordered_set<DexType*>& x) { if (x.empty()) { return out; } out << "("; for (auto i = x.begin(); i != x.end(); ++i) { out << SHOW(*i); if (std::next(i) != x.end()) { out << ","; } } out << ")"; return out; } std::ostream& operator<<(std::ostream& out, const reflection::AbstractObject& x) { switch (x.obj_kind) { case reflection::OBJECT: { out << "OBJECT{" << SHOW(x.dex_type) << x.potential_dex_types << "}"; break; } case reflection::INT: { out << "INT{" << (x.dex_int ? std::to_string(*x.dex_int) : "none") << "}"; break; } case reflection::STRING: { if (x.dex_string != nullptr) { auto str = x.dex_string->str(); if (str.empty()) { out << "\"\""; } else { out << std::quoted(str_copy(str)); } } break; } case reflection::CLASS: { out << "CLASS{" << SHOW(x.dex_type) << x.potential_dex_types << "}"; break; } case reflection::FIELD: { out << "FIELD{" << SHOW(x.dex_type) << x.potential_dex_types << ":" << SHOW(x.dex_string) << "}"; break; } case reflection::METHOD: { out << "METHOD{" << SHOW(x.dex_type) << x.potential_dex_types << ":" << SHOW(x.dex_string); if (x.dex_type_array) { out << "("; for (auto type : *x.dex_type_array) { out << (type ? type->str() : "?"); } out << ")"; } out << "}"; break; } } return out; } std::ostream& operator<<(std::ostream& out, const reflection::AbstractObjectDomain& x) { if (x.is_top()) { out << "TOP"; } else if (x.is_bottom()) { out << "BOTTOM"; } else { out << *(x.get_object()); } return out; } std::ostream& operator<<(std::ostream& out, const reflection::ClassObjectSource& cls_src) { switch (cls_src) { case reflection::NON_REFLECTION: { out << "NON_REFLECTION"; break; } case reflection::REFLECTION: { out << "REFLECTION"; break; } } return out; } std::ostream& operator<<(std::ostream& out, const reflection::ReflectionAbstractObject& aobj) { out << aobj.first; if (aobj.first.obj_kind == reflection::CLASS && aobj.second) { out << "(" << *aobj.second << ")"; } return out; } std::ostream& operator<<(std::ostream& out, const reflection::ReflectionSites& sites) { out << "["; bool is_first_insn = true; for (const auto& insn_to_env : sites) { if (is_first_insn) { is_first_insn = false; } else { out << ", "; } out << show(insn_to_env.first) << " -> {"; bool is_first_reg = true; for (const auto& reg_to_refl_obj : insn_to_env.second) { if (is_first_reg) { is_first_reg = false; } else { out << ", "; } out << "(" << show(reg_to_refl_obj.first) << ", " << reg_to_refl_obj.second << ")"; } out << "}"; } out << "]"; return out; } namespace reflection { AbstractHeapAddress allocate_heap_address() { static AbstractHeapAddress addr = 1; return addr++; } bool is_not_reflection_output(const AbstractObject& obj) { switch (obj.obj_kind) { case reflection::OBJECT: case reflection::INT: case reflection::STRING: return true; default: return false; } } bool operator==(const AbstractObject& x, const AbstractObject& y) { if (x.obj_kind != y.obj_kind) { return false; } switch (x.obj_kind) { case INT: { return x.dex_int == y.dex_int; } case OBJECT: { return x.dex_type == y.dex_type && x.potential_dex_types == y.potential_dex_types && x.heap_address == y.heap_address && x.dex_type_array == y.dex_type_array; } case CLASS: { return x.dex_type == y.dex_type && x.potential_dex_types == y.potential_dex_types; } case STRING: { return x.dex_string == y.dex_string; } case FIELD: { return x.dex_type == y.dex_type && x.potential_dex_types == y.potential_dex_types && x.dex_string == y.dex_string; } case METHOD: { return x.dex_type == y.dex_type && x.potential_dex_types == y.potential_dex_types && x.dex_string == y.dex_string && x.dex_type_array == y.dex_type_array; } } } bool operator!=(const AbstractObject& x, const AbstractObject& y) { return !(x == y); } bool AbstractObject::leq(const AbstractObject& other) const { // Check if `other` is a general CLASS or OBJECT if (obj_kind == other.obj_kind) { switch (obj_kind) { case AbstractObjectKind::INT: { if (other.dex_int == boost::none) { return true; } break; } case AbstractObjectKind::CLASS: case AbstractObjectKind::OBJECT: if (dex_type && other.dex_type == nullptr) { return true; } if (dex_type_array && other.dex_type_array == boost::none) { return true; } if (heap_address && other.heap_address == 0) { return true; } break; case AbstractObjectKind::STRING: if (other.dex_string == nullptr) { return true; } break; case AbstractObjectKind::FIELD: if (other.dex_type == nullptr && other.dex_string == nullptr) { return true; } break; case AbstractObjectKind::METHOD: if (other.dex_type == nullptr && other.dex_string == nullptr) { return true; } if (dex_type_array && other.dex_type_array == boost::none) { return true; } break; } } return equals(other); } bool AbstractObject::equals(const AbstractObject& other) const { return *this == other; } sparta::AbstractValueKind AbstractObject::join_with( const AbstractObject& other) { if (other.leq(*this)) { // We are higher on the lattice return sparta::AbstractValueKind::Value; } if (obj_kind != other.obj_kind) { return sparta::AbstractValueKind::Top; } switch (obj_kind) { case AbstractObjectKind::INT: // Be conservative and drop the int dex_int = boost::none; break; case AbstractObjectKind::OBJECT: case AbstractObjectKind::CLASS: // Be conservative and drop the type info dex_type = nullptr; heap_address = 0; dex_type_array = boost::none; potential_dex_types.clear(); break; case AbstractObjectKind::STRING: // Be conservative and drop the string info dex_string = nullptr; break; case AbstractObjectKind::FIELD: case AbstractObjectKind::METHOD: // Be conservative and drop the field and method info dex_type = nullptr; dex_string = nullptr; dex_type_array = boost::none; potential_dex_types.clear(); break; } return sparta::AbstractValueKind::Value; } sparta::AbstractValueKind AbstractObject::meet_with( const AbstractObject& other) { if (leq(other)) { // We are lower on the lattice return sparta::AbstractValueKind::Value; } if (other.leq(*this)) { *this = other; return sparta::AbstractValueKind::Value; } return sparta::AbstractValueKind::Bottom; } namespace impl { using namespace ir_analyzer; using ClassObjectSourceDomain = sparta::ConstantAbstractDomain<ClassObjectSource>; using BasicAbstractObjectEnvironment = PatriciaTreeMapAbstractEnvironment<reg_t, AbstractObjectDomain>; using ClassObjectSourceEnvironment = PatriciaTreeMapAbstractEnvironment<reg_t, ClassObjectSourceDomain>; using HeapClassArrayEnvironment = PatriciaTreeMapAbstractEnvironment< AbstractHeapAddress, ConstantAbstractDomain<std::vector<DexType*>>>; using ReturnValueDomain = AbstractObjectDomain; class AbstractObjectEnvironment final : public ReducedProductAbstractDomain<AbstractObjectEnvironment, BasicAbstractObjectEnvironment, ClassObjectSourceEnvironment, HeapClassArrayEnvironment, ReturnValueDomain, CallingContextMap> { public: using ReducedProductAbstractDomain::ReducedProductAbstractDomain; static void reduce_product(std::tuple<BasicAbstractObjectEnvironment, ClassObjectSourceEnvironment, HeapClassArrayEnvironment, ReturnValueDomain, CallingContextMap>& /* product */) {} AbstractObjectDomain get_abstract_obj(reg_t reg) const { return get<0>().get(reg); } void set_abstract_obj(reg_t reg, const AbstractObjectDomain aobj) { apply<0>([=](auto env) { env->set(reg, aobj); }, true); } void update_abstract_obj( reg_t reg, const std::function<AbstractObjectDomain(const AbstractObjectDomain&)>& operation) { apply<0>([=](auto env) { env->update(reg, operation); }, true); } ClassObjectSourceDomain get_class_source(reg_t reg) const { return get<1>().get(reg); } void set_class_source(reg_t reg, const ClassObjectSourceDomain cls_src) { apply<1>([=](auto env) { env->set(reg, cls_src); }, true); } ConstantAbstractDomain<std::vector<DexType*>> get_heap_class_array( AbstractHeapAddress addr) const { return get<2>().get(addr); } void set_heap_class_array( AbstractHeapAddress addr, const ConstantAbstractDomain<std::vector<DexType*>>& array) { apply<2>([=](auto env) { env->set(addr, array); }, true); } void set_heap_addr_to_top(AbstractHeapAddress addr) { auto domain = get_heap_class_array(addr); domain.set_to_top(); set_heap_class_array(addr, domain); } ReturnValueDomain get_return_value() const { return get<3>(); } void join_return_value(const ReturnValueDomain& domain) { apply<3>([=](auto original) { original->join_with(domain); }, true); } CallingContextMap get_calling_context_partition() const { return get<4>(); } void set_calling_context(const IRInstruction* insn, const CallingContext& context) { apply<4>([=](auto partition) { partition->set(insn, context); }, true); } }; class Analyzer final : public BaseIRAnalyzer<AbstractObjectEnvironment> { public: explicit Analyzer(const DexMethod* dex_method, const cfg::ControlFlowGraph& cfg, SummaryQueryFn* summary_query_fn, const MetadataCache* cache) : BaseIRAnalyzer(cfg), m_dex_method(dex_method), m_cfg(cfg), m_summary_query_fn(summary_query_fn), m_cache(cache) {} void run(CallingContext* context) { // We need to compute the initial environment by assigning the parameter // registers their correct abstract object derived from the method's // signature. The IOPCODE_LOAD_PARAM_* instructions are pseudo-operations // that are used to specify the formal parameters of the method. They must // be interpreted separately. // // Note that we do not try to infer them as STRINGs. // Since we don't have the the actual value of the string other than their // type being String. Also for CLASSes, the exact Java type they refer to is // not available here. auto init_state = AbstractObjectEnvironment::top(); m_return_value.set_to_bottom(); const auto* signature = m_dex_method->get_proto()->get_args(); auto sig_it = signature->begin(); param_index_t param_position = 0; for (const auto& mie : InstructionIterable(m_cfg.get_param_instructions())) { IRInstruction* insn = mie.insn; switch (insn->opcode()) { case IOPCODE_LOAD_PARAM_OBJECT: { if (param_position == 0 && !is_static(m_dex_method)) { // If the method is not static, the first parameter corresponds to // `this`. update_non_string_input(&init_state, insn, m_dex_method->get_class()); } else { // This is a regular parameter of the method. AbstractObjectDomain param_abstract_obj; DexType* type = *sig_it; always_assert(sig_it++ != signature->end()); if (context && (param_abstract_obj = context->get(param_position), param_abstract_obj.is_value())) { // Parameter domain is provided with the calling context. init_state.set_abstract_obj(insn->dest(), context->get(param_position)); } else { update_non_string_input(&init_state, insn, type); } } param_position++; break; } case IOPCODE_LOAD_PARAM: case IOPCODE_LOAD_PARAM_WIDE: { default_semantics(insn, &init_state); param_position++; break; } default: not_reached(); } } MonotonicFixpointIterator::run(init_state); populate_environments(m_cfg); } void analyze_instruction( const IRInstruction* insn, AbstractObjectEnvironment* current_state) const override { AbstractObjectDomain callee_return; callee_return.set_to_bottom(); if (opcode::is_an_invoke(insn->opcode())) { CallingContext cc; auto srcs = insn->srcs(); for (param_index_t i = 0; i < srcs.size(); i++) { reg_t src = insn->src(i); auto aobj = current_state->get_abstract_obj(src); cc.set(i, aobj); } if (!cc.is_bottom()) { current_state->set_calling_context(insn, cc); } if (m_summary_query_fn) { callee_return = (*m_summary_query_fn)(insn); } } switch (insn->opcode()) { case IOPCODE_LOAD_PARAM: case IOPCODE_LOAD_PARAM_OBJECT: case IOPCODE_LOAD_PARAM_WIDE: { // IOPCODE_LOAD_PARAM_* instructions have been processed before the // analysis. break; } case OPCODE_MOVE: case OPCODE_MOVE_OBJECT: { const auto aobj = current_state->get_abstract_obj(insn->src(0)); current_state->set_abstract_obj(insn->dest(), aobj); const auto obj = aobj.get_object(); if (obj && obj->obj_kind == AbstractObjectKind::CLASS) { current_state->set_class_source( insn->dest(), current_state->get_class_source(insn->src(0))); } break; } case IOPCODE_MOVE_RESULT_PSEUDO_OBJECT: case OPCODE_MOVE_RESULT_OBJECT: { const auto aobj = current_state->get_abstract_obj(RESULT_REGISTER); current_state->set_abstract_obj(insn->dest(), aobj); const auto obj = aobj.get_object(); if (obj && obj->obj_kind == AbstractObjectKind::CLASS) { current_state->set_class_source( insn->dest(), current_state->get_class_source(RESULT_REGISTER)); } break; } case OPCODE_CONST: { current_state->set_abstract_obj( insn->dest(), AbstractObjectDomain(AbstractObject(insn->get_literal()))); break; } case OPCODE_CONST_STRING: { current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain(AbstractObject(insn->get_string()))); break; } case OPCODE_CONST_CLASS: { auto aobj = AbstractObject(AbstractObjectKind::CLASS, insn->get_type()); current_state->set_abstract_obj(RESULT_REGISTER, AbstractObjectDomain(aobj)); current_state->set_class_source( RESULT_REGISTER, ClassObjectSourceDomain(ClassObjectSource::REFLECTION)); break; } case OPCODE_CHECK_CAST: { const auto aobj = current_state->get_abstract_obj(insn->src(0)); current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain( AbstractObject(AbstractObjectKind::OBJECT, insn->get_type()))); const auto obj = aobj.get_object(); if (obj && obj->obj_kind == AbstractObjectKind::CLASS) { current_state->set_class_source( RESULT_REGISTER, current_state->get_class_source(insn->src(0))); } // Note that this is sound. In a concrete execution, if the check-cast // operation fails, an exception is thrown and the control point // following the check-cast becomes unreachable, which corresponds to // _|_ in the abstract domain. Any abstract state is a sound // approximation of _|_. break; } case OPCODE_INSTANCE_OF: { const auto aobj = current_state->get_abstract_obj(insn->src(0)); auto obj = aobj.get_object(); // Append the referenced type here to the potential dex types list. // Doing this increases the type information we have at the reflection // site. It's up to the user of the analysis how to interpret this // information. if (obj && (obj->obj_kind == AbstractObjectKind::OBJECT) && obj->dex_type) { auto dex_type = insn->get_type(); if (obj->dex_type != dex_type) { obj->potential_dex_types.insert(dex_type); current_state->set_abstract_obj( insn->src(0), AbstractObjectDomain(AbstractObject(obj->obj_kind, obj->dex_type, obj->potential_dex_types))); } } break; } case OPCODE_AGET_OBJECT: { const auto array_object = current_state->get_abstract_obj(insn->src(0)).get_object(); if (array_object) { auto type = array_object->dex_type; if (type && type::is_array(type)) { const auto etype = type::get_array_component_type(type); update_non_string_input(current_state, insn, etype); break; } } default_semantics(insn, current_state); break; } case OPCODE_APUT_OBJECT: { // insn format: aput <source> <array> <offset> const auto source_object = current_state->get_abstract_obj(insn->src(0)).get_object(); const auto array_object = current_state->get_abstract_obj(insn->src(1)).get_object(); const auto offset_object = current_state->get_abstract_obj(insn->src(2)).get_object(); if (source_object && source_object->obj_kind == CLASS && array_object && array_object->is_known_class_array() && offset_object && offset_object->obj_kind == INT) { auto type = source_object->dex_type; boost::optional<int64_t> offset = offset_object->dex_int; boost::optional<std::vector<DexType*>> class_array = current_state->get_heap_class_array(array_object->heap_address) .get_constant(); if (offset && class_array && *offset >= 0 && class_array->size() > (size_t)*offset) { (*class_array)[*offset] = type; current_state->set_heap_class_array( array_object->heap_address, ConstantAbstractDomain<std::vector<DexType*>>(*class_array)); } } if (source_object && source_object->is_known_class_array()) { current_state->set_heap_addr_to_top(source_object->heap_address); } default_semantics(insn, current_state); break; } case OPCODE_IPUT_OBJECT: case OPCODE_SPUT_OBJECT: { const auto source_object = current_state->get_abstract_obj(insn->src(0)).get_object(); if (source_object && source_object->is_known_class_array()) { current_state->set_heap_addr_to_top(source_object->heap_address); } break; } case OPCODE_IGET_OBJECT: case OPCODE_SGET_OBJECT: { always_assert(insn->has_field()); const auto field = insn->get_field(); DexType* primitive_type = check_primitive_type_class(field); if (primitive_type) { // The field being accessed is a Class object to a primitive type // likely being used for reflection auto aobj = AbstractObject(AbstractObjectKind::CLASS, primitive_type); current_state->set_abstract_obj(RESULT_REGISTER, AbstractObjectDomain(aobj)); current_state->set_class_source( RESULT_REGISTER, ClassObjectSourceDomain(ClassObjectSource::REFLECTION)); } else { update_non_string_input(current_state, insn, field->get_type()); } break; } case OPCODE_NEW_INSTANCE: { current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain( AbstractObject(AbstractObjectKind::OBJECT, insn->get_type()))); break; } case OPCODE_NEW_ARRAY: { auto array_type = insn->get_type(); always_assert(type::is_array(array_type)); auto component_type = type::get_array_component_type(array_type); if (component_type == type::java_lang_Class()) { const auto aobj = current_state->get_abstract_obj(insn->src(0)).get_object(); if (aobj && aobj->obj_kind == INT && aobj->dex_int) { AbstractHeapAddress addr = allocate_heap_address(); int64_t size = *(aobj->dex_int); std::vector<DexType*> array(size); ConstantAbstractDomain<std::vector<DexType*>> heap_array(array); current_state->set_heap_class_array(addr, heap_array); current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain( AbstractObject(AbstractObjectKind::OBJECT, addr))); break; } } current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain( AbstractObject(AbstractObjectKind::OBJECT, insn->get_type()))); break; } case OPCODE_FILLED_NEW_ARRAY: { auto array_type = insn->get_type(); always_assert(type::is_array(array_type)); auto component_type = type::get_array_component_type(array_type); AbstractObject aobj(AbstractObjectKind::OBJECT, insn->get_type()); if (component_type == type::java_lang_Class()) { auto arg_count = insn->srcs_size(); std::vector<DexType*> known_types; known_types.reserve(arg_count); // collect known types from the filled new array for (auto src_reg : insn->srcs()) { auto reg_obj = current_state->get_abstract_obj(src_reg).get_object(); if (reg_obj && reg_obj->obj_kind == CLASS && reg_obj->dex_type) { known_types.push_back(reg_obj->dex_type); } } if (known_types.size() == arg_count) { AbstractHeapAddress addr = allocate_heap_address(); ConstantAbstractDomain<std::vector<DexType*>> heap_array(known_types); current_state->set_heap_class_array(addr, heap_array); aobj = AbstractObject(AbstractObjectKind::OBJECT, addr); } } current_state->set_abstract_obj(RESULT_REGISTER, AbstractObjectDomain(aobj)); break; } case OPCODE_INVOKE_VIRTUAL: { auto receiver = current_state->get_abstract_obj(insn->src(0)).get_object(); if (!receiver) { update_return_object_and_invalidate_heap_args(current_state, insn, callee_return); break; } process_virtual_call(insn, *receiver, current_state, callee_return); break; } case OPCODE_INVOKE_STATIC: { if (insn->get_method() == m_cache->for_name) { auto class_name = current_state->get_abstract_obj(insn->src(0)).get_object(); if (class_name && class_name->obj_kind == STRING) { if (class_name->dex_string != nullptr) { auto internal_name = DexString::make_string(java_names::external_to_internal( class_name->dex_string->str())); current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain( AbstractObject(AbstractObjectKind::CLASS, DexType::make_type(internal_name)))); } else { current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain( AbstractObject(AbstractObjectKind::CLASS, nullptr))); } current_state->set_class_source( RESULT_REGISTER, ClassObjectSourceDomain(ClassObjectSource::REFLECTION)); break; } } update_return_object_and_invalidate_heap_args(current_state, insn, callee_return); break; } case OPCODE_INVOKE_INTERFACE: case OPCODE_INVOKE_SUPER: case OPCODE_INVOKE_DIRECT: { update_return_object_and_invalidate_heap_args(current_state, insn, callee_return); break; } case OPCODE_RETURN_OBJECT: { this->m_return_value.join_with( current_state->get_abstract_obj(insn->src(0))); break; } default: { default_semantics(insn, current_state); } } } boost::optional<AbstractObject> get_abstract_object( size_t reg, IRInstruction* insn) const { auto it = m_environments.find(insn); if (it == m_environments.end()) { return boost::none; } return it->second.get_abstract_obj(reg).get_object(); } boost::optional<ClassObjectSource> get_class_source( size_t reg, IRInstruction* insn) const { auto it = m_environments.find(insn); if (it == m_environments.end()) { return boost::none; } return it->second.get_class_source(reg).get_constant(); } AbstractObjectDomain get_return_value() const { return m_return_value; } AbstractObjectEnvironment get_exit_state() const { return get_exit_state_at(m_cfg.exit_block()); } private: const DexMethod* m_dex_method; const cfg::ControlFlowGraph& m_cfg; std::unordered_map<IRInstruction*, AbstractObjectEnvironment> m_environments; mutable AbstractObjectDomain m_return_value; SummaryQueryFn* m_summary_query_fn; const MetadataCache* m_cache; void update_non_string_input(AbstractObjectEnvironment* current_state, const IRInstruction* insn, DexType* type) const { auto dest_reg = insn->has_move_result_any() ? RESULT_REGISTER : insn->dest(); if (type == type::java_lang_Class()) { // We don't have precise type information to which the Class obj refers // to. current_state->set_abstract_obj(dest_reg, AbstractObjectDomain(AbstractObject( AbstractObjectKind::CLASS, nullptr))); current_state->set_class_source( dest_reg, ClassObjectSourceDomain(ClassObjectSource::NON_REFLECTION)); } else { current_state->set_abstract_obj(dest_reg, AbstractObjectDomain(AbstractObject( AbstractObjectKind::OBJECT, type))); } } DexType* check_primitive_type_class(const DexFieldRef* field) const { auto type = m_cache->primitive_field_to_type.find(field); if (type != m_cache->primitive_field_to_type.end()) { return type->second; } else { return nullptr; } } void update_return_object_and_invalidate_heap_args( AbstractObjectEnvironment* current_state, const IRInstruction* insn, const AbstractObjectDomain& callee_return) const { invalidate_argument_heap_objects(current_state, insn); DexMethodRef* callee = insn->get_method(); DexType* return_type = callee->get_proto()->get_rtype(); if (type::is_void(return_type) || !type::is_object(return_type)) { return; } if (callee_return.is_value()) { current_state->set_abstract_obj(RESULT_REGISTER, callee_return); } else { update_non_string_input(current_state, insn, return_type); } } void default_semantics(const IRInstruction* insn, AbstractObjectEnvironment* current_state) const { // For instructions that are transparent for this analysis, we just need // to clobber the destination registers in the abstract environment. Note // that this also covers the MOVE_RESULT_* and MOVE_RESULT_PSEUDO_* // instructions following operations that are not considered by this // analysis. Hence, the effect of those operations is correctly abstracted // away regardless of the size of the destination register. if (insn->has_dest()) { current_state->set_abstract_obj(insn->dest(), AbstractObjectDomain::top()); if (insn->dest_is_wide()) { current_state->set_abstract_obj(insn->dest() + 1, AbstractObjectDomain::top()); } } // We need to invalidate RESULT_REGISTER if the instruction writes into // this register. if (insn->has_move_result_any()) { current_state->set_abstract_obj(RESULT_REGISTER, AbstractObjectDomain::top()); } } const DexString* get_dex_string_from_insn( AbstractObjectEnvironment* current_state, const IRInstruction* insn, reg_t reg) const { auto element_name = current_state->get_abstract_obj(insn->src(reg)).get_object(); if (element_name && element_name->obj_kind == STRING) { return element_name->dex_string; } else { return nullptr; } } bool is_method_known_to_preserve_args(DexMethodRef* method) const { const std::set<DexMethodRef*, dexmethods_comparator> known_methods{ m_cache->get_method, m_cache->get_declared_method, }; return known_methods.count(method); } void invalidate_argument_heap_objects( AbstractObjectEnvironment* current_state, const IRInstruction* insn) const { if (!insn->has_method() || is_method_known_to_preserve_args(insn->get_method())) { return; } for (const auto reg : insn->srcs()) { auto aobj = current_state->get_abstract_obj(reg).get_object(); if (!aobj) { continue; } auto addr = aobj->heap_address; if (!addr) { continue; } current_state->set_heap_addr_to_top(addr); } } void process_virtual_call(const IRInstruction* insn, const AbstractObject& receiver, AbstractObjectEnvironment* current_state, const AbstractObjectDomain& callee_return) const { DexMethodRef* callee = insn->get_method(); switch (receiver.obj_kind) { case INT: { // calling on int, not valid break; } case OBJECT: { if (callee == m_cache->get_class) { current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain(AbstractObject(AbstractObjectKind::CLASS, receiver.dex_type, receiver.potential_dex_types))); current_state->set_class_source( RESULT_REGISTER, ClassObjectSourceDomain(ClassObjectSource::REFLECTION)); return; } break; } case STRING: { if (callee == m_cache->get_class) { current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain(AbstractObject(AbstractObjectKind::CLASS, type::java_lang_String()))); current_state->set_class_source( RESULT_REGISTER, ClassObjectSourceDomain(ClassObjectSource::REFLECTION)); return; } break; } case CLASS: { AbstractObjectKind element_kind; const DexString* element_name = nullptr; boost::optional<std::vector<DexType*>> method_param_types = boost::none; if (callee == m_cache->get_method || callee == m_cache->get_declared_method) { element_kind = METHOD; element_name = get_dex_string_from_insn(current_state, insn, 1); auto arr_reg = insn->src(2); // holds java.lang.Class array auto arr_obj = current_state->get_abstract_obj(arr_reg).get_object(); if (arr_obj && arr_obj->is_known_class_array()) { auto maybe_array = current_state->get_heap_class_array(arr_obj->heap_address) .get_constant(); if (maybe_array) { method_param_types = *maybe_array; } } } else if (callee == m_cache->get_constructor || callee == m_cache->get_declared_constructor) { element_kind = METHOD; element_name = DexString::get_string("<init>"); auto arr_reg = insn->src(1); auto arr_obj = current_state->get_abstract_obj(arr_reg).get_object(); if (arr_obj && arr_obj->is_known_class_array()) { auto maybe_array = current_state->get_heap_class_array(arr_obj->heap_address) .get_constant(); if (maybe_array) { method_param_types = *maybe_array; } } } else if (callee == m_cache->get_field || callee == m_cache->get_declared_field) { element_kind = FIELD; element_name = get_dex_string_from_insn(current_state, insn, 1); } else if (callee == m_cache->get_fields || callee == m_cache->get_declared_fields) { element_kind = FIELD; element_name = DexString::get_string(""); } else if (callee == m_cache->get_methods || callee == m_cache->get_declared_methods) { element_kind = METHOD; element_name = DexString::get_string(""); } else if (callee == m_cache->get_constructors || callee == m_cache->get_declared_constructors) { element_kind = METHOD; element_name = DexString::get_string("<init>"); } if (element_name == nullptr) { break; } AbstractObject aobj(element_kind, receiver.dex_type, element_name, receiver.potential_dex_types); if (method_param_types) { aobj.dex_type_array = method_param_types; } current_state->set_abstract_obj(RESULT_REGISTER, AbstractObjectDomain(aobj)); return; } case FIELD: case METHOD: { if ((receiver.obj_kind == FIELD && callee == m_cache->get_field_name) || (receiver.obj_kind == METHOD && callee == m_cache->get_method_name)) { current_state->set_abstract_obj( RESULT_REGISTER, AbstractObjectDomain(AbstractObject(receiver.dex_string))); return; } break; } } update_return_object_and_invalidate_heap_args(current_state, insn, callee_return); } // After the fixpoint iteration completes, we replay the analysis on all // blocks and we cache the abstract state at each instruction. This cache is // used by get_abstract_object() to query the state of a register at a given // instruction. Since we use an abstract domain based on Patricia trees, the // memory footprint of storing the abstract state at each program point is // small. void populate_environments(const cfg::ControlFlowGraph& cfg) { // We reserve enough space for the map in order to avoid repeated // rehashing during the computation. m_environments.reserve(cfg.blocks().size() * 16); for (cfg::Block* block : cfg.blocks()) { AbstractObjectEnvironment current_state = get_entry_state_at(block); for (auto& mie : InstructionIterable(block)) { IRInstruction* insn = mie.insn; m_environments.emplace(insn, current_state); analyze_instruction(insn, &current_state); } } } }; } // namespace impl ReflectionAnalysis::~ReflectionAnalysis() { if (m_fallback_cache) { delete m_fallback_cache; m_fallback_cache = nullptr; } } ReflectionAnalysis::ReflectionAnalysis(DexMethod* dex_method, CallingContext* context, SummaryQueryFn* summary_query_fn, const MetadataCache* cache) : m_dex_method(dex_method) { always_assert(dex_method != nullptr); IRCode* code = dex_method->get_code(); if (code == nullptr) { return; } code->build_cfg(/* editable */ false); cfg::ControlFlowGraph& cfg = code->cfg(); cfg.calculate_exit_block(); if (!cache) { m_fallback_cache = new MetadataCache; cache = m_fallback_cache; } m_analyzer = std::make_unique<impl::Analyzer>(dex_method, cfg, summary_query_fn, cache); m_analyzer->run(context); } void ReflectionAnalysis::get_reflection_site( const reg_t reg, IRInstruction* insn, std::map<reg_t, ReflectionAbstractObject>* abstract_objects) const { auto aobj = m_analyzer->get_abstract_object(reg, insn); if (!aobj) { return; } if (is_not_reflection_output(*aobj)) { return; } boost::optional<ClassObjectSource> cls_src = aobj->obj_kind == AbstractObjectKind::CLASS ? m_analyzer->get_class_source(reg, insn) : boost::none; if (aobj->obj_kind == AbstractObjectKind::CLASS && cls_src == ClassObjectSource::NON_REFLECTION) { return; } if (traceEnabled(REFL, 5)) { std::ostringstream out; out << "reg " << reg << " " << *aobj << " "; if (cls_src) { out << *cls_src; } out << std::endl; TRACE(REFL, 5, " reflection site: %s", out.str().c_str()); } (*abstract_objects)[reg] = ReflectionAbstractObject(*aobj, cls_src); } ReflectionSites ReflectionAnalysis::get_reflection_sites() const { ReflectionSites reflection_sites; auto code = m_dex_method->get_code(); if (code == nullptr) { return reflection_sites; } auto reg_size = code->get_registers_size(); for (auto& mie : InstructionIterable(code)) { IRInstruction* insn = mie.insn; std::map<reg_t, ReflectionAbstractObject> abstract_objects; for (size_t i = 0; i < reg_size; i++) { get_reflection_site(i, insn, &abstract_objects); } get_reflection_site(RESULT_REGISTER, insn, &abstract_objects); if (!abstract_objects.empty()) { reflection_sites.push_back(std::make_pair(insn, abstract_objects)); } } return reflection_sites; } AbstractObjectDomain ReflectionAnalysis::get_return_value() const { if (!m_analyzer) { // Method has no code, or is a native method. return AbstractObjectDomain::top(); } return m_analyzer->get_return_value(); } boost::optional<std::vector<DexType*>> ReflectionAnalysis::get_method_params( IRInstruction* invoke_insn) const { auto code = m_dex_method->get_code(); IRInstruction* move_result_insn = nullptr; auto ii = InstructionIterable(code); for (auto it = ii.begin(); it != ii.end(); ++it) { auto* insn = it->insn; if (insn == invoke_insn) { move_result_insn = std::next(it)->insn; break; } } if (!move_result_insn || !opcode::is_a_move_result(move_result_insn->opcode())) { return boost::none; } auto arg_param = get_abstract_object(RESULT_REGISTER, move_result_insn); if (!arg_param || arg_param->obj_kind != reflection::AbstractObjectKind::METHOD) { return boost::none; } return arg_param->dex_type_array; } bool ReflectionAnalysis::has_found_reflection() const { return !get_reflection_sites().empty(); } boost::optional<AbstractObject> ReflectionAnalysis::get_abstract_object( size_t reg, IRInstruction* insn) const { if (m_analyzer == nullptr) { return boost::none; } return m_analyzer->get_abstract_object(reg, insn); } boost::optional<ClassObjectSource> ReflectionAnalysis::get_class_source( size_t reg, IRInstruction* insn) const { if (m_analyzer == nullptr) { return boost::none; } return m_analyzer->get_class_source(reg, insn); } CallingContextMap ReflectionAnalysis::get_calling_context_partition() const { if (m_analyzer == nullptr) { return CallingContextMap::top(); } return this->m_analyzer->get_exit_state().get_calling_context_partition(); } } // namespace reflection
33.805259
80
0.625823
[ "object", "vector" ]
e4a00907795f3e2f1471fcb4f28509f274857bb5
14,651
hpp
C++
drivers/usb/xhci/xhci.hpp
thomtl/Sigma
30da9446a1f1b5cae4eff77bf9917fae1446ce85
[ "BSD-2-Clause" ]
46
2019-09-30T18:40:06.000Z
2022-02-20T12:54:59.000Z
drivers/usb/xhci/xhci.hpp
thomtl/Sigma
30da9446a1f1b5cae4eff77bf9917fae1446ce85
[ "BSD-2-Clause" ]
11
2019-08-18T18:31:11.000Z
2021-09-14T22:34:16.000Z
drivers/usb/xhci/xhci.hpp
thomtl/Sigma
30da9446a1f1b5cae4eff77bf9917fae1446ce85
[ "BSD-2-Clause" ]
1
2020-01-20T16:55:13.000Z
2020-01-20T16:55:13.000Z
#pragma once #include <libsigma/sys.h> #include "trb.hpp" #include "context.hpp" #include <vector> #include "../usb.hpp" namespace xhci { struct [[gnu::packed]] cap_regs { uint8_t cap_length; uint8_t reserved; union [[gnu::packed]] hci_version_t { struct { uint16_t subminor : 4; uint16_t minor : 4; uint16_t major : 8; }; uint16_t raw; }; static_assert(sizeof(hci_version_t) == 2); uint16_t hci_version; union [[gnu::packed]] hcs_params_1_t { struct { uint32_t max_slots : 8; uint32_t n_irqs : 11; uint32_t reserved : 5; uint32_t max_ports : 8; }; uint32_t raw; }; static_assert(sizeof(hcs_params_1_t) == 4); union [[gnu::packed]] hcs_params_2_t { struct { uint32_t iso_sheduling_threshold : 4; uint32_t erst_max : 4; uint32_t reserved : 13; uint32_t max_scratchpad_hi : 5; uint32_t scratchpad_restore : 1; uint32_t max_scratchpad_low : 5; }; uint32_t raw; }; static_assert(sizeof(hcs_params_2_t) == 4); union [[gnu::packed]] hcs_params_3_t { struct { uint32_t u1_device_exit_latency : 8; uint32_t reserved : 8; uint32_t u2_device_exit_latency : 16; }; uint32_t raw; }; static_assert(sizeof(hcs_params_3_t) == 4); uint32_t hcs_params[3]; union [[gnu::packed]] hcc_params_1_t { struct { uint32_t addressing_64 : 1; uint32_t bw_negotiation : 1; uint32_t context_size : 1; uint32_t port_power_control : 1; uint32_t port_indicators : 1; uint32_t light_hc_reset : 1; uint32_t latency_tolerance_messaging : 1; uint32_t no_secondary_sid : 1; uint32_t parse_all_event_data : 1; uint32_t short_packed : 1; uint32_t stopped_edtla : 1; uint32_t contiguous_frame_id : 1; uint32_t max_psa_size : 4; uint32_t extended_cap_ptr : 16; }; uint32_t raw; }; static_assert(sizeof(hcc_params_1_t) == 4); uint32_t hcc_params_1; uint32_t doorbell_offset; uint32_t runtime_offset; uint32_t hcc_params_2; }; struct [[gnu::packed]] operational_regs { union [[gnu::packed]] usbcmd { struct { uint32_t run : 1; uint32_t reset : 1; uint32_t irq_enable : 1; uint32_t host_system_error_enable : 1; uint32_t reserved : 3; uint32_t light_host_controller_reset : 1; uint32_t controller_save_state : 1; uint32_t controller_restore_state : 1; uint32_t enable_wrap_event : 1; uint32_t enable_u3_stop : 1; uint32_t reserved_0 : 1; uint32_t cem_enable : 1; uint32_t ext_tbc_enable : 1; uint32_t ext_tbc_status_enable : 1; uint32_t vtio_enable : 1; uint32_t reserved_1 : 15; }; uint32_t raw; }; static_assert(sizeof(usbcmd) == 4); uint32_t command; union [[gnu::packed]] usbsts { struct { uint32_t halted : 1; uint32_t reserved : 1; uint32_t host_system_error : 1; uint32_t event_irq : 1; uint32_t port_change : 1; uint32_t reserved_0 : 3; uint32_t save_state_status : 1; uint32_t restore_state_status : 1; uint32_t save_restore_error : 1; uint32_t controller_not_ready : 1; uint32_t host_controller_error : 1; }; uint32_t raw; }; static_assert(sizeof(usbsts) == 4); uint32_t status; uint32_t page_size; uint8_t reserved[8]; uint32_t notification_control; union [[gnu::packed]] crcr { struct { uint64_t ring_cycle_state : 1; uint64_t command_stop : 1; uint64_t command_abort : 1; uint64_t command_ring_running : 1; uint64_t reserved : 2; uint64_t command_ring_ptr : 58; }; uint64_t raw; }; static_assert(sizeof(crcr) == 8); uint64_t command_ring_control; uint8_t reserved_0[16]; uint64_t device_context_base; union [[gnu::packed]] config_reg { struct { uint32_t slot_enable : 8; uint32_t u3_entry_enable : 1; uint32_t configuration_info_enable : 1; uint32_t reserved : 22; }; uint32_t raw; }; static_assert(sizeof(config_reg) == 4); uint32_t config; uint8_t reserved_1[0x3C4]; struct [[gnu::packed]] port_regs{ union [[gnu::packed]] control_reg { struct { uint32_t connect_status : 1; uint32_t enabled : 1; uint32_t reserved : 1; uint32_t over_current_active : 1; uint32_t port_reset : 1; uint32_t port_link_state : 4; uint32_t port_power : 1; uint32_t port_speed : 4; uint32_t port_indicator_control : 2; uint32_t port_link_state_write_strobe : 1; uint32_t connect_status_change : 1; uint32_t port_enabled_change : 1; uint32_t warm_port_reset_change : 1; uint32_t over_current_change : 1; uint32_t port_reset_change : 1; uint32_t port_link_state_change : 1; uint32_t port_config_error_change : 1; uint32_t cold_attach_status : 1; uint32_t wake_on_connect_enable : 1; uint32_t wake_on_disconnect_enable : 1; uint32_t wake_on_over_current_enable : 1; uint32_t reserved_0 : 2; uint32_t device_removable : 1; uint32_t warm_port_reset : 1; }; uint32_t raw; }; static_assert(sizeof(control_reg) == 4); uint32_t control; uint32_t power_management; uint32_t link_info; uint32_t lpm_control; }; port_regs ports[0xFF]; }; struct [[gnu::packed]] runtime_regs { uint32_t microframe_index; uint8_t reserved[0x1C]; struct [[gnu::packed]] interrupter_t { union [[gnu::packed]] iman_t { struct { uint32_t irq_pending : 1; uint32_t irq_enable : 1; uint32_t reserved : 30; }; uint32_t raw; }; static_assert(sizeof(iman_t) == 4); uint32_t iman; union [[gnu::packed]] imod_t { struct { uint32_t interval : 16; uint32_t counter : 16; }; uint32_t raw; }; static_assert(sizeof(imod_t) == 4); uint32_t imod; union [[gnu::packed]] erst_size_t { struct { uint32_t size : 16; uint32_t reserved : 16; }; uint32_t raw; }; static_assert(sizeof(erst_size_t) == 4); uint32_t erst_size; uint32_t reserved; uint64_t erst_base; union [[gnu::packed]] erst_dequeue_t { struct { uint64_t segment_index : 3; uint64_t event_handler_busy : 1; uint64_t dequeue : 60; }; uint64_t raw; }; static_assert(sizeof(erst_dequeue_t) == 8); uint64_t erst_dequeue; }; interrupter_t interrupter[1024]; }; union [[gnu::packed]] doorbell_reg { struct { uint32_t target : 8; uint32_t reserved : 8; uint32_t task_id : 16; }; uint32_t raw; }; struct [[gnu::packed]] event_ring_segment_table_entry { uint64_t base; uint16_t size; uint16_t reserved; uint32_t reserved_0; }; namespace extended_caps { struct [[gnu::packed]] bios_os_handoff { union [[gnu::packed]] capability_reg { struct { uint32_t cap_id : 8; uint32_t next_cap : 8; uint32_t bios_owned_semaphore : 1; uint32_t reserved : 7; uint32_t os_owned_semaphore : 1; uint32_t reserved_1 : 7; }; uint32_t raw; }; static_assert(sizeof(capability_reg) == 4); uint32_t capability; union [[gnu::packed]] control_reg { struct { uint32_t smi_enable: 1; uint32_t reserved_2 : 3; uint32_t smi_host_system_error_enable : 1; uint32_t reserved_3 : 8; uint32_t smi_on_os_owner : 1; uint32_t smi_on_pci_command_enable : 1; uint32_t smi_on_bar_enable : 1; uint32_t smi_on_event_irq : 1; uint32_t reserved_4 : 3; uint32_t smi_on_host_system : 1; uint32_t reserved_5 : 8; uint32_t smi_on_os_ownership_change : 1; uint32_t smi_on_pci_command : 1; uint32_t smi_on_bar : 1; }; uint32_t raw; }; static_assert(sizeof(control_reg) == 4); uint32_t command; }; struct [[gnu::packed]] supported_protocol_cap { union [[gnu::packed]] version_t { struct { uint32_t cap_id : 8; uint32_t next : 8; uint32_t minor_rev : 8; uint32_t major_rev : 8; }; uint32_t raw; }; static_assert(sizeof(version_t) == 4); uint32_t version; union [[gnu::packed]] name_t { struct { uint8_t name_string[4]; }; uint32_t raw; }; static_assert(sizeof(name_t) == 4); uint32_t name; union [[gnu::packed]] ports_info_t { struct { uint32_t compatible_port_offset : 8; uint32_t compatible_port_count : 8; uint32_t protocol_defined : 12; uint32_t protocol_speed_id_count : 4; }; uint32_t raw; }; static_assert(sizeof(ports_info_t) == 4); uint32_t ports_info; union [[gnu::packed]] slot_type_t { struct { uint32_t protocol_slot_type : 5; uint32_t reserved : 27; }; uint32_t raw; }; static_assert(sizeof(slot_type_t) == 4); uint32_t slot_type; struct [[gnu::packed]] { uint32_t speed_id_value : 4; uint32_t speed_id_exponent : 2; uint32_t speed_id_type : 2; uint32_t full_duplex : 1; uint32_t rserved : 5; uint32_t link_protocol : 2; uint32_t speed_id_mantissa : 16; } speed_ids[]; static_assert(sizeof(speed_ids[0]) == 4); }; } // namespace extended_caps enum { speedFull = 1, speedLow = 2, speedHi = 3, speedSuper = 4, }; class controller { public: controller(uint64_t device_descriptor); private: struct supported_protocol { uint32_t major, minor; uint32_t port_offset, port_count; uint32_t slot_type; }; std::vector<supported_protocol> supported_protocols; struct port { supported_protocol* protocol; uint32_t offset; bool active; bool has_pair; uint32_t other_port_num; uint32_t slot_id; uint64_t packet_size; int speed; in_context in_ctx; out_context out_ctx; transfer_ring command; }; void do_bios_os_handoff(); void intel_enable_xhci_ports(); void reset_controller(); void stop_execution(); void start_execution(); command_completion_event_trb send_command(raw_trb* trb); void handle_irq(); // Port functions void get_descriptor(size_t p); void setup_port_protocols(); void init_ports(); bool reset_port(size_t p); void send_control(size_t p, usb::packet packet, uint8_t* data, int write); volatile cap_regs* capabilities; volatile operational_regs* operation; volatile runtime_regs* runtime; volatile uint32_t* doorbells; volatile extended_caps::bios_os_handoff* bios_os_handoff; volatile uint64_t* dcbaap; volatile event_ring_segment_table_entry* erst; std::vector<port> ports; std::unordered_map<uint32_t, port*> port_by_slot_id; size_t page_size; size_t n_scratchpads; size_t n_ports; size_t dcbaap_size; size_t context_size; command_ring cmd_ring; event_ring evt_ring; uint64_t device_descriptor; uint64_t irq_descriptor; enum { quirkIntel = (1 << 0) }; uint64_t quirks; }; } // namespace xhci
31.17234
82
0.494164
[ "vector" ]
e4a974fe577c47795ecde0c49c341025d83da3a8
8,355
cc
C++
centreon-broker/tls2/src/connector.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
8
2020-07-26T09:12:02.000Z
2022-03-30T17:24:29.000Z
centreon-broker/tls2/src/connector.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
47
2020-06-18T12:11:37.000Z
2022-03-16T10:28:56.000Z
centreon-broker/tls2/src/connector.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
5
2020-06-29T14:22:02.000Z
2022-03-17T10:34:10.000Z
/* ** Copyright 2009-2013, 2021 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/tls2/connector.hh" #include <openssl/x509v3.h> #include "com/centreon/broker/log_v2.hh" #include "com/centreon/broker/tls2/internal.hh" #include "com/centreon/broker/tls2/stream.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::tls2; using namespace com::centreon::exceptions; /** * Default constructor * * @param[in] cert Certificate. * @param[in] key Key file. * @param[in] ca Trusted CA's certificate. */ connector::connector(std::string cert, std::string key, std::string ca, std::string tls_hostname) : io::endpoint(false), _ca(std::move(ca)), _cert(std::move(cert)), _key(std::move(key)), _tls_hostname(std::move(tls_hostname)) {} /** * Connect to the remote TLS peer. * * @return New connected stream. */ std::unique_ptr<io::stream> connector::open() { // First connect the lower layer. std::unique_ptr<io::stream> lower(_from->open()); if (lower) return open(std::move(lower)); return nullptr; } static int verify_callback(int preverify_ok, X509_STORE_CTX* ctx) { char buf[256]; X509* err_cert; int err, depth; err_cert = X509_STORE_CTX_get_current_cert(ctx); err = X509_STORE_CTX_get_error(ctx); depth = X509_STORE_CTX_get_error_depth(ctx); /* * Retrieve the pointer to the SSL of the connection currently treated * and the application specific data stored into the SSL object. */ // ssl = X509_STORE_CTX_get_ex_data(ctx, // SSL_get_ex_data_X509_STORE_CTX_idx()); // mydata = SSL_get_ex_data(ssl, mydata_index); X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256); /* * Catch a too long certificate chain. The depth limit set using * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so * that whenever the "depth>verify_depth" condition is met, we * have violated the limit and want to log this error condition. * We must do it here, because the CHAIN_TOO_LONG error would not * be found explicitly; only errors introduced by cutting off the * additional certificates would be logged. */ log_v2::tls()->info("depth = {}", depth); // if (depth > mydata->verify_depth) { // preverify_ok = 0; // err = X509_V_ERR_CERT_CHAIN_TOO_LONG; // X509_STORE_CTX_set_error(ctx, err); // } if (!preverify_ok) { log_v2::tls()->error("verify error:num={}:{}:depth={}:{}", err, X509_verify_cert_error_string(err), depth, buf); } /* * At this point, err contains the last verification error. We can use * it for something special */ if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) { X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, 256); printf("issuer= %s\n", buf); } // if (mydata->always_continue) // return 1; // else return preverify_ok; } static void info_callback(const SSL* s, int where, int ret) { const char* str1; int w = where & ~SSL_ST_MASK; if (w & SSL_ST_CONNECT) str1 = "INFO CLIENT"; else if (w & SSL_ST_ACCEPT) str1 = "INFO SERVER"; else str1 = "undefined"; if (where & SSL_CB_LOOP) { log_v2::tls()->info("INFO: {}:{}", str1, SSL_state_string_long(s)); } else if (where & SSL_CB_ALERT) { const char* str = (where & SSL_CB_READ) ? "read" : "write"; log_v2::tls()->info("INFO: {}:SSL3 alert {}:{}:{}", str1, str, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); } else if (where & SSL_CB_EXIT) { if (ret == 0) log_v2::tls()->info("INFO: {}: failed in {}", str1, SSL_state_string_long(s)); else if (ret < 0) { log_v2::tls()->info("INFO: {}:error in {}", str1, SSL_state_string_long(s)); } } } /** * Overload of open, using base stream. * * @param[in] lower Open stream. * * @return Encrypted stream. */ std::unique_ptr<io::stream> connector::open(std::shared_ptr<io::stream> lower) { std::unique_ptr<stream> u; if (lower) { try { /* First, we clear SSL errors */ ERR_clear_error(); SSL* c_ssl = SSL_new(tls2::ctx); if (c_ssl == nullptr) throw msg_fmt("Unable to allocate connector ssl object"); // SSL_set_info_callback(c_ssl, info_callback); if (!_cert.empty() && !_key.empty()) { log_v2::tls()->info("TLS: using certificates as credentials"); X509_VERIFY_PARAM* ssl_params = SSL_get0_param(c_ssl); X509_VERIFY_PARAM_set_hostflags(ssl_params, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); SSL_set_mode(c_ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY); /* Force TLS hostname */ int mode; if (!_tls_hostname.empty()) { if (!SSL_set_tlsext_host_name(c_ssl, _tls_hostname.c_str())) throw msg_fmt("Error: cannot set tls2 hostname '{}'", _tls_hostname); if (!X509_VERIFY_PARAM_set1_host(ssl_params, _tls_hostname.c_str(), _tls_hostname.size())) throw msg_fmt( "Error: cannot set tls2 host name '{}' to X509 parameters", _tls_hostname); mode = SSL_VERIFY_PEER; } else mode = SSL_VERIFY_NONE; SSL_set_verify(c_ssl, mode, verify_callback); if ( #ifdef TLS1_3_VERSION !SSL_set_ciphersuites(c_ssl, "HIGH") && #endif !SSL_set_cipher_list(c_ssl, "HIGH")) throw msg_fmt("Error: cannot set the cipher list to HIGH"); /* Load CA certificate */ if (!_ca.empty()) { if (SSL_CTX_load_verify_locations(tls2::ctx, _ca.c_str(), nullptr) != 1) throw msg_fmt( "Error: cannot load trusted certificate authority's file '{}': " "{}", _ca, ERR_reason_error_string(ERR_get_error())); } /* Load certificate */ if (SSL_use_certificate_file(c_ssl, _cert.c_str(), SSL_FILETYPE_PEM) != 1) throw msg_fmt("Error: cannot load certificate file '{}'", _cert); /* Load private key */ if (SSL_use_PrivateKey_file(c_ssl, _key.c_str(), SSL_FILETYPE_PEM) != 1) throw msg_fmt("Error: cannot load private key file '{}'", _key); /* Check if the private key is valid */ if (SSL_check_private_key(c_ssl) != 1) throw msg_fmt("Error: checking the private key '{}' failed.", _key); } else { log_v2::tls()->info("TLS: using anonymous client credentials"); SSL_set_security_level(c_ssl, 0); if (!SSL_set_cipher_list(c_ssl, "aNULL")) throw msg_fmt("Error: cannot set the cipher list to HIGH"); } BIO *c_bio = nullptr, *client = nullptr, *c_bio_io = nullptr; // size_t bufsiz = 2048; /* small buffer for testing */ if (!BIO_new_bio_pair(&client, 0 /*bufsiz*/, &c_bio_io, 0 /*bufsiz*/)) throw msg_fmt("Unable to build SSL pair."); c_bio = BIO_new(BIO_f_ssl()); if (!c_bio) throw msg_fmt("Unable to build SSL filter."); SSL_set_connect_state(c_ssl); SSL_set_bio(c_ssl, client, client); (void)BIO_set_ssl(c_bio, c_ssl, BIO_NOCLOSE); // Create stream object. u = std::make_unique<stream>(c_ssl, c_bio, c_bio_io, false); } catch (...) { // delete c_ssl; throw; } u->set_substream(lower); /* Handshake as connector */ u->handshake(); } return u; }
32.509728
80
0.620467
[ "object" ]
e4b4a3e5fb6a6f7a2869ef9083e894396574d3e7
2,457
hpp
C++
include/stl2/detail/algorithm/min.hpp
marehr/cmcstl2
7a7cae1e23beacb18fd786240baef4ae121d813f
[ "MIT" ]
null
null
null
include/stl2/detail/algorithm/min.hpp
marehr/cmcstl2
7a7cae1e23beacb18fd786240baef4ae121d813f
[ "MIT" ]
null
null
null
include/stl2/detail/algorithm/min.hpp
marehr/cmcstl2
7a7cae1e23beacb18fd786240baef4ae121d813f
[ "MIT" ]
null
null
null
// cmcstl2 - A concept-enabled C++ standard library // // Copyright Casey Carter 2015 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/caseycarter/cmcstl2 // #ifndef STL2_DETAIL_ALGORITHM_MIN_HPP #define STL2_DETAIL_ALGORITHM_MIN_HPP #include <initializer_list> #include <stl2/functional.hpp> #include <stl2/iterator.hpp> #include <stl2/detail/fwd.hpp> #include <stl2/detail/concepts/callable.hpp> #include <stl2/detail/concepts/object.hpp> /////////////////////////////////////////////////////////////////////////// // min [alg.min.max] // STL2_OPEN_NAMESPACE { namespace __min { template<InputRange Rng, class Comp = less<>, class Proj = identity> requires Copyable<iter_value_t<iterator_t<Rng>>> && IndirectStrictWeakOrder< Comp, projected<iterator_t<Rng>, Proj>> constexpr iter_value_t<iterator_t<Rng>> impl(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}) { auto first = __stl2::begin(rng); auto last = __stl2::end(rng); STL2_EXPECT(first != last); iter_value_t<iterator_t<Rng>> result = *first; while (++first != last) { auto&& tmp = *first; if (__invoke::impl(comp, __invoke::impl(proj, tmp), __invoke::impl(proj, result))) { result = (decltype(tmp)&&)tmp; } } return result; } } template<class T, class Comp = less<>, class Proj = identity> requires IndirectStrictWeakOrder< Comp, projected<const T*, Proj>> constexpr const T& min(const T& a, const T& b, Comp comp = Comp{}, Proj proj = Proj{}) { return __invoke::impl(comp, __invoke::impl(proj, b), __invoke::impl(proj, a)) ? b : a; } template<InputRange Rng, class Comp = less<>, class Proj = identity> requires Copyable<iter_value_t<iterator_t<Rng>>> && IndirectStrictWeakOrder< Comp, projected<iterator_t<Rng>, Proj>> STL2_CONSTEXPR_EXT iter_value_t<iterator_t<Rng>> min(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}) { return __min::impl(rng, std::ref(comp), std::ref(proj)); } template<Copyable T, class Comp = less<>, class Proj = identity> requires IndirectStrictWeakOrder< Comp, projected<const T*, Proj>> constexpr T min(std::initializer_list<T>&& rng, Comp comp = Comp{}, Proj proj = Proj{}) { return __min::impl(rng, std::ref(comp), std::ref(proj)); } } STL2_CLOSE_NAMESPACE #endif
29.963415
88
0.671144
[ "object" ]
e4bb068e2098dc69a5d518cc68f386efee78570c
46,641
cpp
C++
dockerfile/catkin_ws/src/tools/justina_tools/src/JustinaManip.cpp
RobotJustina/tmc_justina_docker
8aa968a81ae4526f6f6c2d55b83954b57b28ea92
[ "BSD-3-Clause-Clear" ]
null
null
null
dockerfile/catkin_ws/src/tools/justina_tools/src/JustinaManip.cpp
RobotJustina/tmc_justina_docker
8aa968a81ae4526f6f6c2d55b83954b57b28ea92
[ "BSD-3-Clause-Clear" ]
null
null
null
dockerfile/catkin_ws/src/tools/justina_tools/src/JustinaManip.cpp
RobotJustina/tmc_justina_docker
8aa968a81ae4526f6f6c2d55b83954b57b28ea92
[ "BSD-3-Clause-Clear" ]
null
null
null
#include "justina_tools/JustinaManip.h" bool JustinaManip::is_node_set = false; tf::TransformListener * JustinaManip::tf_listener; ros::ServiceClient JustinaManip::cltIKFloatArray; ros::ServiceClient JustinaManip::cltIKPath; ros::ServiceClient JustinaManip::cltIKPose; ros::ServiceClient JustinaManip::cltDK; //Subscribers for indicating that a goal pose has been reached ros::Subscriber JustinaManip::subLaGoalReached; ros::Subscriber JustinaManip::subRaGoalReached; ros::Subscriber JustinaManip::subHdGoalReached; ros::Subscriber JustinaManip::subTrGoalReached; ros::Subscriber JustinaManip::subStopRobot; ros::Subscriber JustinaManip::subObjOnRightHand; ros::Subscriber JustinaManip::subObjOnLeftHand; ros::Subscriber JustinaManip::subLaCurrentPos; ros::Subscriber JustinaManip::subRaCurrentPos; ros::Subscriber JustinaManip::subTorsoCurrentPos; //Publishers for the commands executed by this node ros::Publisher JustinaManip::pubLaGoToAngles; ros::Publisher JustinaManip::pubRaGoToAngles; ros::Publisher JustinaManip::pubHdGoToAngles; ros::Publisher JustinaManip::pubLaGoToPoseWrtArm; ros::Publisher JustinaManip::pubRaGoToPoseWrtArm; ros::Publisher JustinaManip::pubLaGoToPoseWrtRobot; ros::Publisher JustinaManip::pubRaGoToPoseWrtRobot; ros::Publisher JustinaManip::pubLaGoToPoseWrtArmFeedback; ros::Publisher JustinaManip::pubRaGoToPoseWrtArmFeedback; ros::Publisher JustinaManip::pubLaGoToPoseWrtRobotFeedback; ros::Publisher JustinaManip::pubRaGoToPoseWrtRobotFeedback; ros::Publisher JustinaManip::pubLaStopGoTo; ros::Publisher JustinaManip::pubRaStopGoTo; ros::Publisher JustinaManip::pubLaGoToPoseWrtArmTraj; ros::Publisher JustinaManip::pubRaGoToPoseWrtArmTraj; ros::Publisher JustinaManip::pubLaGoToPoseWrtRobotTraj; ros::Publisher JustinaManip::pubRaGoToPoseWrtRobotTraj; ros::Publisher JustinaManip::pubLaGoToLoc; ros::Publisher JustinaManip::pubRaGoToLoc; ros::Publisher JustinaManip::pubHdGoToLoc; ros::Publisher JustinaManip::pubLaMove; ros::Publisher JustinaManip::pubRaMove; ros::Publisher JustinaManip::pubHdMove; ros::Publisher JustinaManip::pubLaCloseGripper; ros::Publisher JustinaManip::pubRaCloseGripper; ros::Publisher JustinaManip::pubLaOpenGripper; ros::Publisher JustinaManip::pubRaOpenGripper; ros::Publisher JustinaManip::pubTrGoToPose; ros::Publisher JustinaManip::pubTrGoToRelPose; //For moving up and down torso ros::Publisher JustinaManip::pubTorsoUp; ros::Publisher JustinaManip::pubTorsoDown; // bool JustinaManip::_isLaGoalReached = false; bool JustinaManip::_isRaGoalReached = false; bool JustinaManip::_isHdGoalReached = false; bool JustinaManip::_isTrGoalReached = false; bool JustinaManip::_isObjOnRightHand = false; bool JustinaManip::_isObjOnLeftHand = false; bool JustinaManip::_stopReceived = false; ros::NodeHandle * JustinaManip::_nh; std::vector<float> JustinaManip::_laCurrentPos; std::vector<float> JustinaManip::_raCurrentPos; std::vector<float> JustinaManip::_torsoCurrentPos; bool JustinaManip::setNodeHandle(ros::NodeHandle* nh) { if(JustinaManip::is_node_set) return true; if(nh == 0) return false; std::cout << "JustinaManip.->Setting ros node..." << std::endl; JustinaManip::cltIKFloatArray = nh->serviceClient<manip_msgs::InverseKinematicsFloatArray>("/manipulation/ik_geometric/ik_float_array"); JustinaManip::cltIKPath = nh->serviceClient<manip_msgs::InverseKinematicsPath>("/manipulation/ik_geometric/ik_path"); JustinaManip::cltIKPose = nh->serviceClient<manip_msgs::InverseKinematicsPose>("/manipulation/ik_geometric/ik_pose"); JustinaManip::cltDK = nh->serviceClient<manip_msgs::DirectKinematics>("/manipulation/ik_geometric/direct_kinematics"); //Subscribers for indicating that a goal pose has been reached JustinaManip::subLaGoalReached = nh->subscribe("/manipulation/la_goal_reached", 1, &JustinaManip::callbackLaGoalReached); JustinaManip::subRaGoalReached = nh->subscribe("/manipulation/ra_goal_reached", 1, &JustinaManip::callbackRaGoalReached); JustinaManip::subHdGoalReached = nh->subscribe("/manipulation/hd_goal_reached", 1, &JustinaManip::callbackHdGoalReached); JustinaManip::subTrGoalReached = nh->subscribe("/hardware/torso/goal_reached", 1, &JustinaManip::callbackTrGoalReached); JustinaManip::subObjOnRightHand = nh->subscribe("/hardware/right_arm/object_on_hand", 1, &JustinaManip::callbackObjOnRightHand); JustinaManip::subObjOnLeftHand = nh->subscribe("/hardware/left_arm/object_on_hand", 1, &JustinaManip::callbackObjOnLeftHand); JustinaManip::subLaCurrentPos = nh->subscribe("/hardware/left_arm/current_pose", 1, &JustinaManip::callbackLaCurrentPos); JustinaManip::subRaCurrentPos = nh->subscribe("/hardware/right_arm/current_pose", 1, &JustinaManip::callbackRaCurrentPos); JustinaManip::subTorsoCurrentPos = nh->subscribe("/hardware/torso/current_pose", 1, &JustinaManip::callbackTorsoCurrentPos); JustinaManip::subStopRobot = nh->subscribe("/hardware/robot_state/stop", 1, &JustinaManip::callbackRobotStop); //Publishers for the commands executed by this node JustinaManip::pubLaGoToAngles = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_goto_angles", 1); JustinaManip::pubRaGoToAngles = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_goto_angles", 1); JustinaManip::pubHdGoToAngles = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/hd_goto_angles", 1); JustinaManip::pubLaGoToPoseWrtArm = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_pose_wrt_arm", 1); JustinaManip::pubRaGoToPoseWrtArm = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_pose_wrt_arm", 1); JustinaManip::pubLaGoToPoseWrtRobot = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_pose_wrt_robot", 1); JustinaManip::pubRaGoToPoseWrtRobot = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_pose_wrt_robot", 1); JustinaManip::pubLaGoToPoseWrtArmFeedback = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_pose_wrt_arm_feedback", 1); JustinaManip::pubRaGoToPoseWrtArmFeedback = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_pose_wrt_arm_feedback", 1); JustinaManip::pubLaGoToPoseWrtRobotFeedback = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_pose_wrt_robot_feedback", 1); JustinaManip::pubRaGoToPoseWrtRobotFeedback = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_pose_wrt_robot_feedback", 1); JustinaManip::pubLaGoToPoseWrtArmTraj = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_pose_wrt_arm_traj", 1); JustinaManip::pubRaGoToPoseWrtArmTraj = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_pose_wrt_arm_traj", 1); JustinaManip::pubLaGoToPoseWrtRobotTraj = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/la_pose_wrt_robot_traj", 1); JustinaManip::pubRaGoToPoseWrtRobotTraj = nh->advertise<std_msgs::Float32MultiArray>("/manipulation/manip_pln/ra_pose_wrt_robot_traj", 1); JustinaManip::pubLaStopGoTo = nh->advertise<std_msgs::Empty>("/manipulation/manip_pln/la_stop", 1); JustinaManip::pubRaStopGoTo = nh->advertise<std_msgs::Empty>("/manipulation/manip_pln/ra_stop", 1); JustinaManip::pubLaGoToLoc = nh->advertise<std_msgs::String>("/manipulation/manip_pln/la_goto_loc", 1); JustinaManip::pubRaGoToLoc = nh->advertise<std_msgs::String>("/manipulation/manip_pln/ra_goto_loc", 1); JustinaManip::pubHdGoToLoc = nh->advertise<std_msgs::String>("/manipulation/manip_pln/hd_goto_loc", 1); JustinaManip::pubLaMove = nh->advertise<std_msgs::String>("/manipulation/manip_pln/la_move", 1); JustinaManip::pubRaMove = nh->advertise<std_msgs::String>("/manipulation/manip_pln/la_move", 1); JustinaManip::pubHdMove = nh->advertise<std_msgs::String>("/manipulation/manip_pln/la_move", 1); JustinaManip::pubLaCloseGripper = nh->advertise<std_msgs::Float32>("/hardware/left_arm/torque_gripper", 1); JustinaManip::pubLaOpenGripper = nh->advertise<std_msgs::Float32>("/hardware/left_arm/goal_gripper", 1); JustinaManip::pubRaCloseGripper = nh->advertise<std_msgs::Float32>("/hardware/right_arm/torque_gripper", 1); JustinaManip::pubRaOpenGripper = nh->advertise<std_msgs::Float32>("/hardware/right_arm/goal_gripper", 1); JustinaManip::pubTrGoToPose = nh->advertise<std_msgs::Float32MultiArray>("/hardware/torso/goal_pose", 1); JustinaManip::pubTrGoToRelPose = nh->advertise<std_msgs::Float32MultiArray>("/hardware/torso/goal_rel_pose", 1); JustinaManip::is_node_set = true; JustinaManip::tf_listener = new tf::TransformListener(); JustinaManip::tf_listener->waitForTransform("base_link", "right_arm_grip_center", ros::Time(0), ros::Duration(10.0)); JustinaManip::tf_listener->waitForTransform("base_link", "left_arm_grip_center", ros::Time(0), ros::Duration(10.0)); //For moving up and down torso JustinaManip::pubTorsoUp = nh->advertise<std_msgs::String>("/hardware/torso/torso_up", 1); JustinaManip::pubTorsoDown = nh->advertise<std_msgs::String>("/hardware/torso/torso_down", 1); JustinaManip::_nh = nh; return true; } bool JustinaManip::isLaGoalReached() { return JustinaManip::_isLaGoalReached; } bool JustinaManip::isRaGoalReached() { return JustinaManip::_isRaGoalReached; } bool JustinaManip::isHdGoalReached() { //std::cout << "JustinaManip.-> isHdGoalReached: " << JustinaManip::_isHdGoalReached << std::endl; return JustinaManip::_isHdGoalReached; } bool JustinaManip::isTorsoGoalReached() { return JustinaManip::_isTrGoalReached; } bool JustinaManip::waitForLaGoalReached(int timeOut_ms) { int attempts = timeOut_ms / 100; ros::Rate loop(10); JustinaManip::_stopReceived = false; JustinaManip::_isLaGoalReached = false; while(ros::ok() && !JustinaManip::_isLaGoalReached && !JustinaManip::_stopReceived && attempts-- >= 0) { ros::spinOnce(); loop.sleep(); } JustinaManip::_stopReceived = false; //This flag is set True in the subscriber callback return JustinaManip::_isLaGoalReached; } bool JustinaManip::waitForRaGoalReached(int timeOut_ms) { int attempts = timeOut_ms / 100; ros::Rate loop(10); JustinaManip::_stopReceived = false; JustinaManip::_isRaGoalReached = false; while(ros::ok() && !JustinaManip::_isRaGoalReached && !JustinaManip::_stopReceived && attempts-- >= 0) { ros::spinOnce(); loop.sleep(); } JustinaManip::_stopReceived = false; //This flag is set True in the subscriber callback return JustinaManip::_isRaGoalReached; } bool JustinaManip::waitForHdGoalReached(int timeOut_ms) { int attempts = timeOut_ms / 100; ros::Rate loop(10); JustinaManip::_stopReceived = false; JustinaManip::_isHdGoalReached = false; while(ros::ok() && !JustinaManip::_isHdGoalReached && !JustinaManip::_stopReceived && attempts-- >= 0) { ros::spinOnce(); loop.sleep(); } JustinaManip::_stopReceived = false; //This flag is set True in the subscriber callback return JustinaManip::_isHdGoalReached; } bool JustinaManip::waitForTorsoGoalReached(int timeOut_ms) { int attempts = timeOut_ms / 100; ros::Rate loop(10); JustinaManip::_stopReceived = false; JustinaManip::_isTrGoalReached = false; while(ros::ok() && !JustinaManip::_isTrGoalReached && !JustinaManip::_stopReceived && attempts-- >= 0) { ros::spinOnce(); loop.sleep(); } JustinaManip::_stopReceived = false; //This flag is set True in the subscriber callback return JustinaManip::_isTrGoalReached; } bool JustinaManip::inverseKinematics(std::vector<float>& cartesian, std::vector<float>& articular) { std::cout << "JustinaManip.->Calling service for inverse kinematics..." << std::endl; manip_msgs::InverseKinematicsFloatArray srv; srv.request.cartesian_pose.data = cartesian; bool success = JustinaManip::cltIKFloatArray.call(srv); articular = srv.response.articular_pose.data; return success; } bool JustinaManip::inverseKinematics(float x, float y, float z, float roll, float pitch, float yaw, std::vector<float>& articular) { std::cout << "JustinaManip.->Calling service for inverse kinematics..." << std::endl; manip_msgs::InverseKinematicsFloatArray srv; srv.request.cartesian_pose.data.push_back(x); srv.request.cartesian_pose.data.push_back(y); srv.request.cartesian_pose.data.push_back(z); srv.request.cartesian_pose.data.push_back(roll); srv.request.cartesian_pose.data.push_back(pitch); srv.request.cartesian_pose.data.push_back(yaw); bool success = JustinaManip::cltIKFloatArray.call(srv); articular = srv.response.articular_pose.data; return success; } bool JustinaManip::inverseKinematics(float x, float y, float z, float roll, float pitch, float yaw, float elbow, std::vector<float>& articular) { std::cout << "JustinaManip.->Calling service for inverse kinematics..." << std::endl; manip_msgs::InverseKinematicsFloatArray srv; srv.request.cartesian_pose.data.push_back(x); srv.request.cartesian_pose.data.push_back(y); srv.request.cartesian_pose.data.push_back(z); srv.request.cartesian_pose.data.push_back(roll); srv.request.cartesian_pose.data.push_back(pitch); srv.request.cartesian_pose.data.push_back(yaw); srv.request.cartesian_pose.data.push_back(elbow); bool success = JustinaManip::cltIKFloatArray.call(srv); articular = srv.response.articular_pose.data; return success; } bool JustinaManip::inverseKinematics(float x, float y, float z, std::vector<float>& articular) { std::cout << "JustinaManip.->Calling service for inverse kinematics..." << std::endl; manip_msgs::InverseKinematicsFloatArray srv; srv.request.cartesian_pose.data.push_back(x); srv.request.cartesian_pose.data.push_back(y); srv.request.cartesian_pose.data.push_back(z); bool success = JustinaManip::cltIKFloatArray.call(srv); articular = srv.response.articular_pose.data; return success; } bool JustinaManip::inverseKinematics(std::vector<float>& cartesian, std::string frame_id, std::vector<float>& articular) { return false; } bool JustinaManip::inverseKinematics(float x, float y, float z, float roll, float pitch, float yaw, std::string frame_id, std::vector<float>& articular) { return false; } bool JustinaManip::inverseKinematics(float x, float y, float z, std::string frame_id, std::vector<float>& articular) { return false; } // bool JustinaManip::inverseKinematics(geometry_msgs::Pose& cartesian, std::vector<float>& articular); // bool JustinaManip::inverseKinematics(nav_msgs::Path& cartesianPath, std::vector<std::vector<float> >& articularPath); // bool JustinaManip::inverseKinematics(nav_msgs::Path& cartesianPath, std::vector<Float32MultiArray>& articularPath); bool JustinaManip::directKinematics(std::vector<float>& cartesian, std::vector<float>& articular) { std::cout << "JustinaManip.->Calling service for direct kinematics..." << std::endl; manip_msgs::DirectKinematics srv; srv.request.articular_pose.data = articular; bool success = JustinaManip::cltDK.call(srv); cartesian = srv.response.cartesian_pose.data; return success; } // //Methods for operating arms and head // void JustinaManip::startLaGoToArticular(std::vector<float>& articular) { std_msgs::Float32MultiArray msg; msg.data = articular; JustinaManip::pubLaGoToAngles.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesian(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubLaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubLaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); JustinaManip::pubLaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesian(float x, float y, float z) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); JustinaManip::pubLaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianWrtRobot(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubLaGoToPoseWrtRobot.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianWrtRobot(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubLaGoToPoseWrtRobot.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianFeedback(std::vector<float>& cartesian){ std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubLaGoToPoseWrtArmFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianFeedback(float x, float y, float z, float roll, float pitch, float yaw, float elbow){ std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubLaGoToPoseWrtArmFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianFeedback(float x, float y, float z){ std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); JustinaManip::pubLaGoToPoseWrtArmFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianWrtRobotFeedback(std::vector<float>& cartesian){ std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubLaGoToPoseWrtRobotFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianWrtRobotFeedback(float x, float y, float z, float roll, float pitch, float yaw, float elbow){ std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubLaGoToPoseWrtRobotFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianTraj(std::vector<float>& cartesian){ std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubLaGoToPoseWrtArmTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianTraj(float x, float y, float z, float roll, float pitch, float yaw, float elbow){ std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubLaGoToPoseWrtArmTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianTraj(float x, float y, float z){ std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); JustinaManip::pubLaGoToPoseWrtArmTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianWrtRobotTraj(std::vector<float>& cartesian){ std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubLaGoToPoseWrtRobotTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoToCartesianWrtRobotTraj(float x, float y, float z, float roll, float pitch, float yaw, float elbow){ std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubLaGoToPoseWrtRobotTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaGoTo(std::string location) { std_msgs::String msg; msg.data = location; JustinaManip::pubLaGoToLoc.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaMove(std::string movement) { std_msgs::String msg; msg.data = movement; JustinaManip::pubLaMove.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaOpenGripper(float angle) { std_msgs::Float32 msgAngle; msgAngle.data = angle; JustinaManip::pubLaOpenGripper.publish(msgAngle); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startLaCloseGripper(float torque) { std_msgs::Float32 msgTorque; msgTorque.data = torque; JustinaManip::pubLaCloseGripper.publish(msgTorque); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToArticular(std::vector<float>& articular) { std_msgs::Float32MultiArray msg; msg.data = articular; JustinaManip::pubRaGoToAngles.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesian(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubRaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubRaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); JustinaManip::pubRaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesian(float x, float y, float z) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); JustinaManip::pubRaGoToPoseWrtArm.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianWrtRobot(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubRaGoToPoseWrtRobot.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianWrtRobot(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubRaGoToPoseWrtRobot.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianFeedback(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubRaGoToPoseWrtArmFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianFeedback(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubRaGoToPoseWrtArmFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianFeedback(float x, float y, float z) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); JustinaManip::pubRaGoToPoseWrtArmFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianWrtRobotFeedback(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubRaGoToPoseWrtRobotFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianWrtRobotFeedback(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubRaGoToPoseWrtRobotFeedback.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianTraj(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubRaGoToPoseWrtArmTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianTraj(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubRaGoToPoseWrtArmTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianTraj(float x, float y, float z) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); JustinaManip::pubRaGoToPoseWrtArmTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianWrtRobotTraj(std::vector<float>& cartesian) { std_msgs::Float32MultiArray msg; msg.data = cartesian; JustinaManip::pubRaGoToPoseWrtRobotTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoToCartesianWrtRobotTraj(float x, float y, float z, float roll, float pitch, float yaw, float elbow) { std_msgs::Float32MultiArray msg; msg.data.push_back(x); msg.data.push_back(y); msg.data.push_back(z); msg.data.push_back(roll); msg.data.push_back(pitch); msg.data.push_back(yaw); msg.data.push_back(elbow); JustinaManip::pubRaGoToPoseWrtRobotTraj.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaGoTo(std::string location) { std_msgs::String msg; msg.data = location; JustinaManip::pubRaGoToLoc.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaMove(std::string movement) { std_msgs::String msg; msg.data = movement; JustinaManip::pubRaMove.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaOpenGripper(float angle) { std_msgs::Float32 msgAngle; msgAngle.data = angle; JustinaManip::pubRaOpenGripper.publish(msgAngle); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startRaCloseGripper(float torque) { std_msgs::Float32 msgTorque; msgTorque.data = torque; JustinaManip::pubRaCloseGripper.publish(msgTorque); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startHdGoTo(float pan, float tilt) { std_msgs::Float32MultiArray msg; msg.data.push_back(pan); msg.data.push_back(tilt); JustinaManip::pubHdGoToAngles.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startHdGoTo(std::string location) { std_msgs::String msg; msg.data = location; JustinaManip::pubHdGoToLoc.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startHdMove(std::string movement) { std_msgs::String msg; msg.data = movement; JustinaManip::pubHdMove.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startTorsoGoTo(float goalSpine, float goalWaist, float goalShoulders) { std_msgs::Float32MultiArray msg; msg.data.push_back(goalSpine); msg.data.push_back(goalWaist); msg.data.push_back(goalShoulders); JustinaManip::pubTrGoToPose.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } void JustinaManip::startTorsoGoToRel(float goalRelSpine, float goalRelWaist, float goalRelShoulders) { std_msgs::Float32MultiArray msg; msg.data.push_back(goalRelSpine); msg.data.push_back(goalRelWaist); msg.data.push_back(goalRelShoulders); JustinaManip::pubTrGoToRelPose.publish(msg); ros::spinOnce(); boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } bool JustinaManip::laGoToArticular(std::vector<float>& articular, int timeOut_ms) { JustinaManip::startLaGoToArticular(articular); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesian(std::vector<float>& cartesian, int timeOut_ms) { JustinaManip::startLaGoToCartesian(cartesian); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw, float elbow, int timeOut_ms) { JustinaManip::startLaGoToCartesian(x, y, z, roll, pitch, yaw, elbow); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw, int timeOut_ms) { JustinaManip::startLaGoToCartesian(x, y, z, roll, pitch, yaw); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesian(float x, float y, float z, int timeOut_ms) { JustinaManip::startLaGoToCartesian(x, y, z); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesianFeedback(std::vector<float>& cartesian, int timeOut_ms) { JustinaManip::startLaGoToCartesianFeedback(cartesian); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesianFeedback(float x, float y, float z, float roll, float pitch, float yaw, float elbow, int timeOut_ms) { JustinaManip::startLaGoToCartesianFeedback(x, y, z, roll, pitch, yaw, elbow); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesianFeedback(float x, float y, float z, int timeOut_ms) { JustinaManip::startLaGoToCartesianFeedback(x, y, z); return JustinaManip::waitForLaGoalReached(timeOut_ms); } void JustinaManip::laStopGoToCartesian(){ std_msgs::Empty msg; JustinaManip::pubLaStopGoTo.publish(msg); } bool JustinaManip::laGoToCartesianTraj(std::vector<float>& cartesian, int timeOut_ms) { JustinaManip::startLaGoToCartesianTraj(cartesian); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesianTraj(float x, float y, float z, float roll, float pitch, float yaw, float elbow, int timeOut_ms) { JustinaManip::startLaGoToCartesianTraj(x, y, z, roll, pitch, yaw, elbow); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoToCartesianTraj(float x, float y, float z, int timeOut_ms) { JustinaManip::startLaGoToCartesianTraj(x, y, z); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laGoTo(std::string location, int timeOut_ms) { if(location == "navigation" && JustinaManip::isLaInPredefPos("home")) { JustinaManip::startLaGoTo("pre_nav"); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); } else if (location == "home" && JustinaManip::isLaInPredefPos("navigation")) { JustinaManip::startLaGoTo("pre_nav"); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); } JustinaManip::startLaGoTo(location); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::laMove(std::string movement, int timeOut_ms) { JustinaManip::startLaMove(movement); return JustinaManip::waitForLaGoalReached(timeOut_ms); } bool JustinaManip::raGoToArticular(std::vector<float>& articular, int timeOut_ms) { JustinaManip::startRaGoToArticular(articular); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesian(std::vector<float>& cartesian, int timeOut_ms) { JustinaManip::startRaGoToCartesian(cartesian); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw, float elbow, int timeOut_ms) { JustinaManip::startRaGoToCartesian(x, y, z, roll, pitch, yaw, elbow); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesian(float x, float y, float z, float roll, float pitch, float yaw, int timeOut_ms) { JustinaManip::startRaGoToCartesian(x, y, z, roll, pitch, yaw); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesian(float x, float y, float z, int timeOut_ms) { JustinaManip::startRaGoToCartesian(x, y, z); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesianFeedback(std::vector<float>& cartesian, int timeOut_ms) { JustinaManip::startRaGoToCartesianFeedback(cartesian); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesianFeedback(float x, float y, float z, float roll, float pitch, float yaw, float elbow, int timeOut_ms) { JustinaManip::startRaGoToCartesianFeedback(x, y, z, roll, pitch, yaw, elbow); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesianFeedback(float x, float y, float z, int timeOut_ms) { JustinaManip::startRaGoToCartesianFeedback(x, y, z); return JustinaManip::waitForRaGoalReached(timeOut_ms); } void JustinaManip::raStopGoToCartesian(){ std_msgs::Empty msg; JustinaManip::pubRaStopGoTo.publish(msg); } bool JustinaManip::raGoToCartesianTraj(std::vector<float>& cartesian, int timeOut_ms) { JustinaManip::startRaGoToCartesianTraj(cartesian); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesianTraj(float x, float y, float z, float roll, float pitch, float yaw, float elbow, int timeOut_ms) { JustinaManip::startRaGoToCartesianTraj(x, y, z, roll, pitch, yaw, elbow); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoToCartesianTraj(float x, float y, float z, int timeOut_ms) { JustinaManip::startRaGoToCartesianTraj(x, y, z); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raGoTo(std::string location, int timeOut_ms) { if(location == "navigation" && JustinaManip::isRaInPredefPos("home")) { JustinaManip::startRaGoTo("pre_nav"); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); } else if (location == "home" && JustinaManip::isRaInPredefPos("navigation")) { JustinaManip::startRaGoTo("pre_nav"); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); } JustinaManip::startRaGoTo(location); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::raMove(std::string movement, int timeOut_ms) { JustinaManip::startRaMove(movement); return JustinaManip::waitForRaGoalReached(timeOut_ms); } bool JustinaManip::hdGoTo(float pan, float tilt, int timeOut_ms) { JustinaManip::startHdGoTo(pan, tilt); return JustinaManip::waitForHdGoalReached(timeOut_ms); } bool JustinaManip::hdGoTo(std::string location, int timeOut_ms) { JustinaManip::startHdGoTo(location); return JustinaManip::waitForHdGoalReached(timeOut_ms); } bool JustinaManip::hdMove(std::string movement, int timeOut_ms) { JustinaManip::startHdMove(movement); return JustinaManip::waitForHdGoalReached(timeOut_ms); } bool JustinaManip::torsoGoTo(float goalSpine, float goalWaist, float goalShoulders, int timeOut_ms) { JustinaManip::startTorsoGoTo(goalSpine, goalWaist, goalShoulders); return JustinaManip::waitForTorsoGoalReached(timeOut_ms); } bool JustinaManip::torsoGoToRel(float goalRelSpine, float goalRelWaist, float goalRelShoulders, int timeOut_ms) { JustinaManip::startTorsoGoToRel(goalRelSpine, goalRelWaist, goalRelShoulders); return JustinaManip::waitForTorsoGoalReached(timeOut_ms); } bool JustinaManip::objOnRightHand(){ return _isObjOnRightHand; } bool JustinaManip::objOnLeftHand(){ return _isObjOnLeftHand; } void JustinaManip::getRightHandPosition(float &x, float &y, float &z){ tf::StampedTransform transform; tf_listener->waitForTransform("base_link", "right_arm_grip_center", ros::Time(0), ros::Duration(10.0)); tf_listener->lookupTransform("base_link", "right_arm_grip_center", ros::Time(0), transform); x = transform.getOrigin().getX(); y = transform.getOrigin().getY(); z = transform.getOrigin().getZ(); std::cout << "JustinaManip.->right_arm_griper_center.x:" << x << std::endl; std::cout << "JustinaManip.->right_arm_griper_center.y:" << y << std::endl; std::cout << "JustinaManip.->right_arm_griper_center.z:" << z << std::endl; } void JustinaManip::getLeftHandPosition(float &x, float &y, float &z){ tf::StampedTransform transform; tf_listener->waitForTransform("base_link", "left_arm_grip_center", ros::Time(0), ros::Duration(10.0)); tf_listener->lookupTransform("base_link", "left_arm_grip_center", ros::Time(0), transform); x = transform.getOrigin().getX(); y = transform.getOrigin().getY(); z = transform.getOrigin().getZ(); std::cout << "JustinaManip.->left_arm_griper_center.x:" << x << std::endl; std::cout << "JustinaManip.->left_arm_griper_center.y:" << y << std::endl; std::cout << "JustinaManip.->left_arm_griper_center.z:" << z << std::endl; } // //Callbacks for catching goal-reached signals // void JustinaManip::callbackRobotStop(const std_msgs::Empty::ConstPtr& msg) { JustinaManip::_stopReceived = true; } void JustinaManip::callbackLaGoalReached(const std_msgs::Bool::ConstPtr& msg) { JustinaManip::_isLaGoalReached = msg->data; } void JustinaManip::callbackRaGoalReached(const std_msgs::Bool::ConstPtr& msg) { JustinaManip::_isRaGoalReached = msg->data; } void JustinaManip::callbackHdGoalReached(const std_msgs::Bool::ConstPtr& msg) { JustinaManip::_isHdGoalReached = msg->data; } void JustinaManip::callbackTrGoalReached(const std_msgs::Bool::ConstPtr& msg) { JustinaManip::_isTrGoalReached = msg->data; } void JustinaManip::callbackObjOnRightHand(const std_msgs::Bool::ConstPtr& msg) { JustinaManip::_isObjOnRightHand = msg->data; } void JustinaManip::callbackObjOnLeftHand(const std_msgs::Bool::ConstPtr& msg) { JustinaManip::_isObjOnLeftHand = msg->data; } void JustinaManip::callbackLaCurrentPos(const std_msgs::Float32MultiArray::ConstPtr& msg) { //std::cout << "La pose received" << std::endl; JustinaManip::_laCurrentPos = msg->data; //std::cout << "LA current_pos: " << JustinaManip::_laCurrentPos.size() << std::endl; } void JustinaManip::callbackRaCurrentPos(const std_msgs::Float32MultiArray::ConstPtr& msg) { //std::cout << "Ra pose received" << std::endl; JustinaManip::_raCurrentPos = msg->data; //std::cout << "RA current_pos: " << JustinaManip::_raCurrentPos.size() << std::endl; } void JustinaManip::callbackTorsoCurrentPos(const std_msgs::Float32MultiArray::ConstPtr& msg) { //std::cout << "Torso pose received: "; JustinaManip::_torsoCurrentPos = msg->data; //std::cout << JustinaManip::_torsoCurrentPos << std::endl; } void JustinaManip::getLaCurrentPos(std::vector<float>& pos) { //std::cout << "LA current_pos: " << JustinaManip::_laCurrentPos.size() << std::endl; pos = JustinaManip::_laCurrentPos; } void JustinaManip::getRaCurrentPos(std::vector<float>& pos) { //std::cout << "RA current_pos: " << JustinaManip::_raCurrentPos.size() << std::endl; pos = JustinaManip::_raCurrentPos; } void JustinaManip::getTorsoCurrentPos(std::vector<float>& pos) { pos = JustinaManip::_torsoCurrentPos; } void JustinaManip::setLaTrajectoryTime(float time) { std::cout<<"New trajectory time established for left arm"<<std::endl; _nh->setParam("/manipulation/la_control/trajectory_time", time); } void JustinaManip::setRaTrajectoryTime(float time) { std::cout<<"New trajectory time established for right arm"<<std::endl; _nh->setParam("/manipulation/ra_control/trajectory_time", time); } bool JustinaManip::isLaInPredefPos(std::string id) { float threshold = 0.2; std::vector<float> poses; JustinaKnowledge::getPredLaArmPose(id, poses); if(poses.size() < 1) return false; //std::cout << "JustinaManip::isLaInPredefPos.-> pose_size: " << JustinaManip::_laCurrentPos.size() << " - " << JustinaManip::_laCurrentPos[0] << std::endl; std::cout << "JustinaManip::isLaInPredefPos current_pos" << std::endl; for(int i = 0; i < poses.size(); i++) { //std::cout << "I'm into the for...." << std::endl; //std::cout << " " << poses[i] << " " << JustinaManip::_laCurrentPos[i] << std::endl; if(poses[i] > JustinaManip::_laCurrentPos[i]-threshold && poses[i] < JustinaManip::_laCurrentPos[i]+threshold ) { continue; } else { std::cout << " " << poses[i] << " " << JustinaManip::_laCurrentPos[i] << std::endl; std::cout << "Left arm is NOT in " << id << " pose" << std::endl; return false; } } std::cout << "Left arm is Already in " << id << " pose" << std::endl; return true; } bool JustinaManip::isRaInPredefPos(std::string id) { float threshold = 0.2; std::vector<float> poses; JustinaKnowledge::getPredRaArmPose(id, poses); if(poses.size() < 1) return false; //std::cout << "JustinaManip::isRaInPredefPos.-> pose_size: " << poses.size() << " - " << poses[0] << std::endl; std::cout << "JustinaManip::isRaInPredefPos current_pos" << std::endl; for(int i = 0; i < poses.size(); i++) { //std::cout << "I'm into the for...." << std::endl; //std::cout << " " << poses[i] << " " << JustinaManip::_raCurrentPos[i] << std::endl; if(poses[i] > JustinaManip::_raCurrentPos[i]-threshold && poses[i] < JustinaManip::_raCurrentPos[i]+threshold ) { continue; } else { std::cout << " " << poses[i] << " " << JustinaManip::_raCurrentPos[i] << std::endl; std::cout << "Right arm is NOT in " << id << " pose" << std::endl; return false; } } std::cout << "Right arm is Already in " << id << " pose" << std::endl; return true; } //Methods for moving torso up or down void JustinaManip::moveTorsoUp(std_msgs::String msg) { JustinaManip::pubTorsoUp.publish(msg); } void JustinaManip::moveTorsoDown(std_msgs::String msg) { JustinaManip::pubTorsoDown.publish(msg); }
37.765992
162
0.73236
[ "vector", "transform" ]
e4bc5894a5d6231ecb390ec6f726976b3a12f54e
123,715
cc
C++
src/game/Utils/_ItalianText.cc
oldlaptop/ja2-stracciatella
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
[ "BSD-Source-Code" ]
null
null
null
src/game/Utils/_ItalianText.cc
oldlaptop/ja2-stracciatella
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
[ "BSD-Source-Code" ]
null
null
null
src/game/Utils/_ItalianText.cc
oldlaptop/ja2-stracciatella
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
[ "BSD-Source-Code" ]
null
null
null
#include "Text.h" #ifdef WITH_UNITTESTS #include "gtest/gtest.h" #endif // ****************************************************************************************************** // ** IMPORTANT TRANSLATION NOTES ** // ****************************************************************************************************** // // GENERAL INSTRUCTIONS // - Always be aware that foreign strings should be of equal or shorter length than the English equivalent. // I know that this is difficult to do on many occasions due to the nature of foreign languages when // compared to English. By doing so, this will greatly reduce the amount of work on both sides. In // most cases (but not all), JA2 interfaces were designed with just enough space to fit the English word. // The general rule is if the string is very short (less than 10 characters), then it's short because of // interface limitations. On the other hand, full sentences commonly have little limitations for length. // Strings in between are a little dicey. // - Never translate a string to appear on multiple lines. All strings L"This is a really long string...", // must fit on a single line no matter how long the string is. All strings start with L" and end with ", // - Never remove any extra spaces in strings. In addition, all strings containing multiple sentences only // have one space after a period, which is different than standard typing convention. Never modify sections // of strings contain combinations of % characters. These are special format characters and are always // used in conjunction with other characters. For example, %ls means string, and is commonly used for names, // locations, items, etc. %d is used for numbers. %c%d is a character and a number (such as A9). // %% is how a single % character is built. There are countless types, but strings containing these // special characters are usually commented to explain what they mean. If it isn't commented, then // if you can't figure out the context, then feel free to ask SirTech. // - Comments are always started with // Anything following these two characters on the same line are // considered to be comments. Do not translate comments. Comments are always applied to the following // string(s) on the next line(s), unless the comment is on the same line as a string. // - All new comments made by SirTech will use "//@@@ comment" (without the quotes) notation. By searching // for @@@ everytime you recieve a new version, it will simplify your task and identify special instructions. // Commonly, these types of comments will be used to ask you to abbreviate a string. Please leave the // comments intact, and SirTech will remove them once the translation for that particular area is resolved. // - If you have a problem or question with translating certain strings, please use "//!!! comment" // (without the quotes). The syntax is important, and should be identical to the comments used with @@@ // symbols. SirTech will search for !!! to look for your problems and questions. This is a more // efficient method than detailing questions in email, so try to do this whenever possible. // // // // FAST HELP TEXT -- Explains how the syntax of fast help text works. // ************** // // 1) BOLDED LETTERS // The popup help text system supports special characters to specify the hot key(s) for a button. // Anytime you see a '|' symbol within the help text string, that means the following key is assigned // to activate the action which is usually a button. // // EX: L"|Map Screen" // // This means the 'M' is the hotkey. In the game, when somebody hits the 'M' key, it activates that // button. When translating the text to another language, it is best to attempt to choose a word that // uses 'M'. If you can't always find a match, then the best thing to do is append the 'M' at the end // of the string in this format: // // EX: L"Ecran De Carte (|M)" (this is the French translation) // // Other examples are used multiple times, like the Esc key or "|E|s|c" or Space -> (|S|p|a|c|e) // // 2) NEWLINE // Any place you see a \n within the string, you are looking at another string that is part of the fast help // text system. \n notation doesn't need to be precisely placed within that string, but whereever you wish // to start a new line. // // EX: L"Clears all the mercs' positions,\nand allows you to re-enter them manually." // // Would appear as: // // Clears all the mercs' positions, // and allows you to re-enter them manually. // // NOTE: It is important that you don't pad the characters adjacent to the \n with spaces. If we did this // in the above example, we would see // // WRONG WAY -- spaces before and after the \n // EX: L"Clears all the mercs' positions, \n and allows you to re-enter them manually." // // Would appear as: (the second line is moved in a character) // // Clears all the mercs' positions, // and allows you to re-enter them manually. // // // @@@ NOTATION // ************ // // Throughout the text files, you'll find an assortment of comments. Comments are used to describe the // text to make translation easier, but comments don't need to be translated. A good thing is to search for // "@@@" after receiving new version of the text file, and address the special notes in this manner. // // !!! NOTATION // ************ // // As described above, the "!!!" notation should be used by you to ask questions and address problems as // SirTech uses the "@@@" notation. static StrPointer s_it_WeaponType[WeaponType_SIZE] = { L"Altro", L"Arma", L"Mitragliatrice", L"Mitra", L"Fucile", L"Fucile del cecchino", L"Fucile d'assalto", L"Mitragliatrice leggera", L"Fucile a canne mozze", }; static StrPointer s_it_TeamTurnString[TeamTurnString_SIZE] = { L"Turno del giocatore", // player's turn L"Turno degli avversari", L"Turno delle creature", L"Turno dell'esercito", L"Turno dei civili", // planning turn }; static StrPointer s_it_Message[Message_SIZE] = { // In the following 8 strings, the %ls is the merc's name, and the %d (if any) is a number. L"%ls è stato colpito alla testa e perde un punto di saggezza!", L"%ls è stato colpito alla spalla e perde un punto di destrezza!", L"%ls è stato colpito al torace e perde un punto di forza!", L"%ls è stato colpito alle gambe e perde un punto di agilità!", L"%ls è stato colpito alla testa e perde %d punti di saggezza!", L"%ls è stato colpito alle palle perde %d punti di destrezza!", L"%ls è stato colpito al torace e perde %d punti di forza!", L"%ls è stato colpito alle gambe e perde %d punti di agilità!", L"Interrompete!", L"I vostri rinforzi sono arrivati!", // In the following four lines, all %ls's are merc names L"%ls ricarica.", L"%ls non ha abbastanza Punti Azione!", // the following 17 strings are used to create lists of gun advantages and disadvantages // (separated by commas) L"affidabile", L"non affidabile", L"facile da riparare", L"difficile da riparare", L"danno grave", L"danno lieve", L"fuoco veloce", L"fuoco", L"raggio lungo", L"raggio corto", L"leggero", L"pesante", L"piccolo", L"fuoco a raffica", L"niente raffiche", L"grande deposito d'armi", L"piccolo deposito d'armi", // In the following two lines, all %ls's are merc names L"Il travestimento di %ls è stato scoperto.", L"Il travestimento di %ls è stato scoperto.", // The first %ls is a merc name and the second %ls is an item name L"La seconda arma è priva di munizioni!", L"%ls ha rubato il %ls.", // The %ls is a merc name L"L'arma di %ls non può più sparare a raffica.", L"Ne avete appena ricevuto uno di quelli attaccati.", L"Volete combinare gli oggetti?", // Both %ls's are item names L"Non potete attaccare %ls a un %ls.", L"Nessuno", L"Espelli munizioni", L"Attaccare", //You cannot use "item(s)" and your "other item" at the same time. //Ex: You cannot use sun goggles and you gas mask at the same time. L"Non potete usare %ls e il vostro %ls contemporaneamente.", L"L'oggetto puntato dal vostro cursore può essere combinato ad alcuni oggetti ponendolo in uno dei quattro slot predisposti.", L"L'oggetto puntato dal vostro cursore può essere combinato ad alcuni oggetti ponendolo in uno dei quattro slot predisposti. (Comunque, in questo caso, l'oggetto non è compatibile.)", L"Il settore non è libero da nemici!", L"Vi dovete ancora dare %ls %ls", L"%ls è stato colpito alla testa!", L"Abbandonate la battaglia?", L"Questo attaco sarà definitivo. Andate avanti?", L"%ls si sente molto rinvigorito!", L"%ls ha dormito di sasso!", L"%ls non è riuscito a catturare il %ls!", L"%ls ha riparato il %ls", L"Interrompete per ", L"Vi arrendete?", L"Questa persona rifiuta il vostro aiuto.", L"NON sono d'accordo!", L"Per viaggiare sull'elicottero di Skyrider, dovrete innanzitutto ASSEGNARE mercenari al VEICOLO/ELICOTTERO.", L"solo %ls aveva abbastanza tempo per ricaricare UNA pistola", L"Turno dei Bloodcat", }; // the names of the towns in the game static const wchar_t *s_it_pTownNames[pTownNames_SIZE] = { L"", L"Omerta", L"Drassen", L"Alma", L"Grumm", L"Tixa", L"Cambria", L"San Mona", L"Estoni", L"Orta", L"Balime", L"Meduna", L"Chitzena", }; static const wchar_t *s_it_g_towns_locative[g_towns_locative_SIZE] = { L"", L"Omerta", L"Drassen", L"Alma", L"Grumm", L"Tixa", L"Cambria", L"San Mona", L"Estoni", L"Orta", L"Balime", L"Meduna", L"Chitzena" }; // the types of time compression. For example: is the timer paused? at normal speed, 5 minutes per second, etc. // min is an abbreviation for minutes static const wchar_t *s_it_sTimeStrings[sTimeStrings_SIZE] = { L"Fermo", L"Normale", L"5 min", L"30 min", L"60 min", L"6 ore", }; // Assignment Strings: what assignment does the merc have right now? For example, are they on a squad, training, // administering medical aid (doctor) or training a town. All are abbreviated. 8 letters is the longest it can be. static const wchar_t *s_it_pAssignmentStrings[pAssignmentStrings_SIZE] = { L"Squad. 1", L"Squad. 2", L"Squad. 3", L"Squad. 4", L"Squad. 5", L"Squad. 6", L"Squad. 7", L"Squad. 8", L"Squad. 9", L"Squad. 10", L"Squad. 11", L"Squad. 12", L"Squad. 13", L"Squad. 14", L"Squad. 15", L"Squad. 16", L"Squad. 17", L"Squad. 18", L"Squad. 19", L"Squad. 20", L"Servizio", // on active duty L"Dottore", // administering medical aid L"Paziente", // getting medical aid L"Veicolo", // in a vehicle L"Transito", // in transit - abbreviated form L"Riparare", // repairing L"Esercit.", // training themselves L"Esercit.", // training a town to revolt L"Istrutt.", // training a teammate L"Studente", // being trained by someone else L"Morto", // dead L"Incap.", // abbreviation for incapacitated L"PDG", // Prisoner of war - captured L"Ospedale", // patient in a hospital L"Vuoto", // Vehicle is empty }; static const wchar_t *s_it_pMilitiaString[pMilitiaString_SIZE] = { L"Esercito", // the title of the militia box L"Non incaricato", //the number of unassigned militia troops L"Non potete ridistribuire reclute, se ci sono nemici nei paraggi!", }; static const wchar_t *s_it_pMilitiaButtonString[pMilitiaButtonString_SIZE] = { L"Auto", // auto place the militia troops for the player L"Eseguito", // done placing militia troops }; static const wchar_t *s_it_pConditionStrings[pConditionStrings_SIZE] = { L"Eccellente", //the state of a soldier .. excellent health L"Buono", // good health L"Discreto", // fair health L"Ferito", // wounded health L"Stanco", // tired L"Grave", // bleeding to death L"Svenuto", // knocked out L"Morente", // near death L"Morto", // dead }; static const wchar_t *s_it_pEpcMenuStrings[pEpcMenuStrings_SIZE] = { L"In servizio", // set merc on active duty L"Paziente", // set as a patient to receive medical aid L"Veicolo", // tell merc to enter vehicle L"Non scortato", // let the escorted character go off on their own L"Cancella", // close this menu }; // look at pAssignmentString above for comments static const wchar_t *s_it_pLongAssignmentStrings[pLongAssignmentStrings_SIZE] = { L"Squadra 1", L"Squadra 2", L"Squadra 3", L"Squadra 4", L"Squadra 5", L"Squadra 6", L"Squadra 7", L"Squadra 8", L"Squadra 9", L"Squadra 10", L"Squadra 11", L"Squadra 12", L"Squadra 13", L"Squadra 14", L"Squadra 15", L"Squadra 16", L"Squadra 17", L"Squadra 18", L"Squadra 19", L"Squadra 20", L"In servizio", L"Dottore", L"Paziente", L"Veicolo", L"In transito", L"Riparare", L"Esercitarsi", L"Allenatore esercito", L"Allena squadra", L"Studente", L"Morto", L"Incap.", L"PDG", L"Ospedale", // patient in a hospital L"Vuoto", // Vehicle is empty }; // the contract options static const wchar_t *s_it_pContractStrings[pContractStrings_SIZE] = { L"Opzioni del contratto:", L"", // a blank line, required L"Offri 1 giorno", // offer merc a one day contract extension L"Offri 1 settimana", // 1 week L"Offri 2 settimane", // 2 week L"Termina contratto", // end merc's contract L"Annulla", // stop showing this menu }; static const wchar_t *s_it_pPOWStrings[pPOWStrings_SIZE] = { L"PDG", //an acronym for Prisoner of War L"??", }; static const wchar_t *s_it_pInvPanelTitleStrings[pInvPanelTitleStrings_SIZE] = { L"Giubb. A-P", // the armor rating of the merc L"Peso", // the weight the merc is carrying L"Trav.", // the merc's camouflage rating }; static const wchar_t *s_it_pShortAttributeStrings[pShortAttributeStrings_SIZE] = { L"Abi", // the abbreviated version of : agility L"Des", // dexterity L"For", // strength L"Com", // leadership L"Sag", // wisdom L"Liv", // experience level L"Tir", // marksmanship skill L"Esp", // explosive skill L"Mec", // mechanical skill L"PS", // medical skill }; static const wchar_t *s_it_pUpperLeftMapScreenStrings[pUpperLeftMapScreenStrings_SIZE] = { L"Compito", // the mercs current assignment L"Salute", // the health level of the current merc L"Morale", // the morale of the current merc L"Cond.", // the condition of the current vehicle }; static const wchar_t *s_it_pTrainingStrings[pTrainingStrings_SIZE] = { L"Esercitarsi", // tell merc to train self L"Esercito", // tell merc to train town L"Allenatore", // tell merc to act as trainer L"Studente", // tell merc to be train by other }; static const wchar_t *s_it_pAssignMenuStrings[pAssignMenuStrings_SIZE] = { L"In servizio", // merc is on active duty L"Dottore", // the merc is acting as a doctor L"Paziente", // the merc is receiving medical attention L"Veicolo", // the merc is in a vehicle L"Ripara", // the merc is repairing items L"Si esercita", // the merc is training L"Annulla", // cancel this menu }; static const wchar_t *s_it_pRemoveMercStrings[pRemoveMercStrings_SIZE] = { L"Rimuovi Mercenario", // remove dead merc from current team L"Annulla", }; static const wchar_t *s_it_pAttributeMenuStrings[pAttributeMenuStrings_SIZE] = { L"Forza", L"Destrezza", L"Agilità", L"Salute", L"Mira", L"Pronto socc.", L"Meccanica", L"Comando", L"Esplosivi", L"Annulla", }; static const wchar_t *s_it_pTrainingMenuStrings[pTrainingMenuStrings_SIZE] = { L"Allenati", // train yourself L"Esercito", // train the town L"Allenatore", // train your teammates L"Studente", // be trained by an instructor L"Annulla", // cancel this menu }; static const wchar_t *s_it_pSquadMenuStrings[pSquadMenuStrings_SIZE] = { L"Squadra 1", L"Squadra 2", L"Squadra 3", L"Squadra 4", L"Squadra 5", L"Squadra 6", L"Squadra 7", L"Squadra 8", L"Squadra 9", L"Squadra 10", L"Squadra 11", L"Squadra 12", L"Squadra 13", L"Squadra 14", L"Squadra 15", L"Squadra 16", L"Squadra 17", L"Squadra 18", L"Squadra 19", L"Squadra 20", L"Annulla", }; static const wchar_t *s_it_pPersonnelScreenStrings[pPersonnelScreenStrings_SIZE] = { L"Deposito med.:", // amount of medical deposit put down on the merc L"Contratto in corso:", // cost of current contract L"Uccisi", // number of kills by merc L"Assistiti", // number of assists on kills by merc L"Costo giornaliero:", // daily cost of merc L"Tot. costo fino a oggi:", // total cost of merc L"Contratto:", // cost of current contract L"Tot. servizio fino a oggi:", // total service rendered by merc L"Salario arretrato:", // amount left on MERC merc to be paid L"Percentuale di colpi:", // percentage of shots that hit target L"Battaglie", // number of battles fought L"Numero ferite", // number of times merc has been wounded L"Destrezza:", L"Nessuna abilità", }; //These string correspond to enums used in by the SkillTrait enums in SoldierProfileType.h static const wchar_t *s_it_gzMercSkillText[gzMercSkillText_SIZE] = { L"Nessuna abilità", L"Forzare serrature", L"Corpo a corpo", L"Elettronica", L"Op. notturne", L"Lanciare", L"Istruire", L"Armi pesanti", L"Armi automatiche", L"Clandestino", L"Ambidestro", L"Furtività", L"Arti marziali", L"Coltelli", L"Bonus per altezza", L"Camuffato", L"(Esperto)", }; // This is pop up help text for the options that are available to the merc static const wchar_t *s_it_pTacticalPopupButtonStrings[pTacticalPopupButtonStrings_SIZE] = { L"|Stare fermi/Camminare", L"|Accucciarsi/Muoversi accucciato", L"Stare fermi/|Correre", L"|Prono/Strisciare", L"|Guardare", L"Agire", L"Parlare", L"Esaminare (|C|t|r|l)", // Pop up door menu L"Aprire manualmente", L"Esaminare trappole", L"Grimaldello", L"Forzare", L"Liberare da trappole", L"Chiudere", L"Aprire", L"Usare esplosivo per porta", L"Usare piede di porco", L"Annulla (|E|s|c)", L"Chiudere", }; // Door Traps. When we examine a door, it could have a particular trap on it. These are the traps. static const wchar_t *s_it_pDoorTrapStrings[pDoorTrapStrings_SIZE] = { L"Nessuna trappola", L"una trappola esplosiva", L"una trappola elettrica", L"una trappola con sirena", L"una trappola con allarme insonoro", }; // On the map screen, there are four columns. This text is popup help text that identifies the individual columns. static const wchar_t *s_it_pMapScreenMouseRegionHelpText[pMapScreenMouseRegionHelpText_SIZE] = { L"Selezionare postazioni", L"Assegnare mercenario", L"Tracciare percorso di viaggio", L"Merc |Contratto", L"Eliminare mercenario", L"Dormire", }; // volumes of noises static const wchar_t *s_it_pNoiseVolStr[pNoiseVolStr_SIZE] = { L"DEBOLE", L"DEFINITO", L"FORTE", L"MOLTO FORTE", }; // types of noises static const wchar_t *s_it_pNoiseTypeStr[pNoiseTypeStr_SIZE] = // OBSOLETE { L"SCONOSCIUTO", L"rumore di MOVIMENTO", L"SCRICCHIOLIO", L"TONFO IN ACQUA", L"IMPATTO", L"SPARO", L"ESPLOSIONE", L"URLA", L"IMPATTO", L"IMPATTO", L"FRASTUONO", L"SCHIANTO", }; // Directions that are used to report noises static const wchar_t *s_it_pDirectionStr[pDirectionStr_SIZE] = { L"il NORD-EST", L"il EST", L"il SUD-EST", L"il SUD", L"il SUD-OVEST", L"il OVEST", L"il NORD-OVEST", L"il NORD", }; // These are the different terrain types. static const wchar_t *s_it_pLandTypeStrings[pLandTypeStrings_SIZE] = { L"Urbano", L"Strada", L"Pianure", L"Deserto", L"Boschi", L"Foresta", L"Palude", L"Acqua", L"Colline", L"Impervio", L"Fiume", //river from north to south L"Fiume", //river from east to west L"Paese straniero", //NONE of the following are used for directional travel, just for the sector description. L"Tropicale", L"Campi", L"Pianure, strada", L"Boschi, strada", L"Fattoria, strada", L"Tropicale, strada", L"Foresta, strada", L"Linea costiera", L"Montagna, strada", L"Litoraneo, strada", L"Deserto, strada", L"Palude, strada", L"Boschi, postazione SAM", L"Deserto, postazione SAM", L"Tropicale, postazione SAM", L"Meduna, postazione SAM", //These are descriptions for special sectors L"Ospedale di Cambria", L"Aeroporto di Drassen", L"Aeroporto di Meduna", L"Postazione SAM", L"Nascondiglio ribelli", //The rebel base underground in sector A10 L"Prigione sotterranea di Tixa", //The basement of the Tixa Prison (J9) L"Tana della creatura", //Any mine sector with creatures in it L"Cantina di Orta", //The basement of Orta (K4) L"Tunnel", //The tunnel access from the maze garden in Meduna //leading to the secret shelter underneath the palace L"Rifugio", //The shelter underneath the queen's palace L"", //Unused }; static const wchar_t *s_it_gpStrategicString[gpStrategicString_SIZE] = { L"%ls sono stati individuati nel settore %c%d e un'altra squadra sta per arrivare.", //STR_DETECTED_SINGULAR L"%ls sono stati individuati nel settore %c%d e un'altra squadra sta per arrivare.", //STR_DETECTED_PLURAL L"Volete coordinare un attacco simultaneo?", //STR_COORDINATE //Dialog strings for enemies. L"Il nemico offre la possibilità di arrendervi.", //STR_ENEMY_SURRENDER_OFFER L"Il nemico ha catturato i vostri mercenari sopravvissuti.", //STR_ENEMY_CAPTURED //The text that goes on the autoresolve buttons L"Ritirarsi", //The retreat button //STR_AR_RETREAT_BUTTON L"Fine", //The done button //STR_AR_DONE_BUTTON //The headers are for the autoresolve type (MUST BE UPPERCASE) L"DIFENDERE", //STR_AR_DEFEND_HEADER L"ATTACCARE", //STR_AR_ATTACK_HEADER L"INCONTRARE", //STR_AR_ENCOUNTER_HEADER L"settore", //The Sector A9 part of the header //STR_AR_SECTOR_HEADER //The battle ending conditions L"VITTORIA!", //STR_AR_OVER_VICTORY L"SCONFITTA!", //STR_AR_OVER_DEFEAT L"ARRENDERSI!", //STR_AR_OVER_SURRENDERED L"CATTURATI!", //STR_AR_OVER_CAPTURED L"RITIRARSI!", //STR_AR_OVER_RETREATED //These are the labels for the different types of enemies we fight in autoresolve. L"Esercito", //STR_AR_MILITIA_NAME, L"Èlite", //STR_AR_ELITE_NAME, L"Truppa", //STR_AR_TROOP_NAME, L"Amministratore", //STR_AR_ADMINISTRATOR_NAME, L"Creatura", //STR_AR_CREATURE_NAME, //Label for the length of time the battle took L"Tempo trascorso", //STR_AR_TIME_ELAPSED, //Labels for status of merc if retreating. (UPPERCASE) L"RITIRATOSI", //STR_AR_MERC_RETREATED, L"RITIRARSI", //STR_AR_MERC_RETREATING, L"RITIRATA", //STR_AR_MERC_RETREAT, //PRE BATTLE INTERFACE STRINGS //Goes on the three buttons in the prebattle interface. The Auto resolve button represents //a system that automatically resolves the combat for the player without having to do anything. //These strings must be short (two lines -- 6-8 chars per line) L"Esito", //STR_PB_AUTORESOLVE_BTN, L"Vai al settore", //STR_PB_GOTOSECTOR_BTN, L"Ritira merc.", //STR_PB_RETREATMERCS_BTN, //The different headers(titles) for the prebattle interface. L"SCONTRO NEMICO", //STR_PB_ENEMYENCOUNTER_HEADER, L"INVASIONE NEMICA", //STR_PB_ENEMYINVASION_HEADER, // 30 L"IMBOSCATA NEMICA", //STR_PB_ENEMYAMBUSH_HEADER L"INTRUSIONE NEMICA NEL SETTORE", //STR_PB_ENTERINGENEMYSECTOR_HEADER L"ATTACCO DELLE CREATURE", //STR_PB_CREATUREATTACK_HEADER L"IMBOSCATA DEI BLOODCAT", //STR_PB_BLOODCATAMBUSH_HEADER L"INTRUSIONE NELLA TANA BLOODCAT", //STR_PB_ENTERINGBLOODCATLAIR_HEADER //Various single words for direct translation. The Civilians represent the civilian //militia occupying the sector being attacked. Limited to 9-10 chars L"Postazione", L"Nemici", L"Mercenari", L"Esercito", L"Creature", L"Bloodcat", L"Settore", L"Nessuno", //If there are no uninvolved mercs in this fight. L"N/A", //Acronym of Not Applicable L"g", //One letter abbreviation of day L"o", //One letter abbreviation of hour //TACTICAL PLACEMENT USER INTERFACE STRINGS //The four buttons L"Sgombro", L"Sparsi", L"In gruppo", L"Fine", //The help text for the four buttons. Use \n to denote new line (just like enter). L"|Mostra chiaramente tutte le postazioni dei mercenari,\ne vi permette di rimetterli in gioco manualmente.", L"A caso |sparge i vostri mercenari\nogni volta che lo premerete.", L"Vi permette di scegliere dove vorreste |raggruppare i vostri mercenari.", L"Cliccate su questo pulsante quando avrete\nscelto le postazioni dei vostri mercenari. (|I|n|v|i|o)", L"Dovete posizionare tutti i vostri mercenari\nprima di iniziare la battaglia.", //Various strings (translate word for word) L"Settore", L"Scegliete le postazioni di intervento", //Strings used for various popup message boxes. Can be as long as desired. L"Non sembra così bello qui. È inacessibile. Provate con una diversa postazione.", L"Posizionate i vostri mercenari nella sezione illuminata della mappa.", //These entries are for button popup help text for the prebattle interface. All popup help //text supports the use of \n to denote new line. Do not use spaces before or after the \n. L"|Automaticamente svolge i combattimenti al vostro posto\nsenza caricare la mappa.", L"Non è possibile utilizzare l'opzione di risoluzione automatica quando\nil giocatore sta attaccando.", L"|Entrate nel settore per catturare il nemico.", L"|Rimandate il gruppo al settore precedente.", //singular version L"|Rimandate tutti i gruppi ai loro settori precedenti.", //multiple groups with same previous sector //various popup messages for battle conditions. //%c%d is the sector -- ex: A9 L"I nemici attaccano il vostro esercito nel settore %c%d.", //%c%d is the sector -- ex: A9 L"Le creature attaccano il vostro esercito nel settore %c%d.", //1st %d refers to the number of civilians eaten by monsters, %c%d is the sector -- ex: A9 //Note: the minimum number of civilians eaten will be two. L"Le creature attaccano e uccidono %d civili nel settore %ls.", //%ls is the sector location -- ex: A9: Omerta L"I nemici attaccano i vostri mercenari nel settore %ls. Nessuno dei vostri mercenari è in grado di combattere!", //%ls is the sector location -- ex: A9: Omerta L"I nemici attaccano i vostri mercenari nel settore %ls. Nessuno dei vostri mercenari è in grado di combattere!", }; //This is the day represented in the game clock. Must be very short, 4 characters max. static const wchar_t s_it_gpGameClockString[] = L"Gg"; //When the merc finds a key, they can get a description of it which //tells them where and when they found it. static const wchar_t *s_it_sKeyDescriptionStrings[sKeyDescriptionStrings_SIZE] = { L"Settore trovato:", L"Giorno trovato:", }; //The headers used to describe various weapon statistics. static StrPointer s_it_gWeaponStatsDesc[ gWeaponStatsDesc_SIZE] = { L"Peso (%ls):", L"Stato:", L"Ammontare:", // Number of bullets left in a magazine L"Git:", // Range L"Dan:", // Damage L"PA:", // abbreviation for Action Points L"=" }; //The headers used for the merc's money. static const wchar_t *s_it_gMoneyStatsDesc[gMoneyStatsDesc_SIZE] = { L"Ammontare", L"Rimanenti:", //this is the overall balance L"Ammontare", L"Da separare:", // the amount he wants to separate from the overall balance to get two piles of money L"Bilancio", L"corrente", L"Ammontare", L"del prelievo", }; //The health of various creatures, enemies, characters in the game. The numbers following each are for comment //only, but represent the precentage of points remaining. static const wchar_t *s_it_zHealthStr[zHealthStr_SIZE] = { L"MORENTE", // >= 0 L"CRITICO", // >= 15 L"DEBOLE", // >= 30 L"FERITO", // >= 45 L"SANO", // >= 60 L"FORTE", // >= 75 L"ECCELLENTE", // >= 90 }; static const wchar_t *s_it_gzMoneyAmounts[gzMoneyAmounts_SIZE] = { L"$1000", L"$100", L"$10", L"Fine", L"Separare", L"Prelevare", }; // short words meaning "Advantages" for "Pros" and "Disadvantages" for "Cons." static const wchar_t s_it_gzProsLabel[] = L"Vant.:"; static const wchar_t s_it_gzConsLabel[] = L"Svant.:"; //Conversation options a player has when encountering an NPC static StrPointer s_it_zTalkMenuStrings[zTalkMenuStrings_SIZE] = { L"Vuoi ripetere?", //meaning "Repeat yourself" L"Amichevole", //approach in a friendly L"Diretto", //approach directly - let's get down to business L"Minaccioso", //approach threateningly - talk now, or I'll blow your face off L"Dai", L"Recluta", }; //Some NPCs buy, sell or repair items. These different options are available for those NPCs as well. static StrPointer s_it_zDealerStrings[zDealerStrings_SIZE] = { L"Compra/Vendi", L"Compra", L"Vendi", L"Ripara", }; static const wchar_t s_it_zDialogActions[] = L"Fine"; //These are vehicles in the game. static const wchar_t *s_it_pVehicleStrings[pVehicleStrings_SIZE] = { L"Eldorado", L"Hummer", // a hummer jeep/truck -- military vehicle L"Icecream Truck", L"Jeep", L"Carro armato", L"Elicottero", }; static const wchar_t *s_it_pShortVehicleStrings[pVehicleStrings_SIZE] = { L"Eldor.", L"Hummer", // the HMVV L"Truck", L"Jeep", L"Carro", L"Eli", // the helicopter }; static const wchar_t *s_it_zVehicleName[pVehicleStrings_SIZE] = { L"Eldorado", L"Hummer", //a military jeep. This is a brand name. L"Truck", // Ice cream truck L"Jeep", L"Carro", L"Eli", //an abbreviation for Helicopter }; //These are messages Used in the Tactical Screen static StrPointer s_it_TacticalStr[TacticalStr_SIZE] = { L"Attacco aereo", L"Ricorrete al pronto soccorso automaticamente?", // CAMFIELD NUKE THIS and add quote #66. L"%ls nota ch egli oggetti mancano dall'equipaggiamento.", // The %ls is a string from pDoorTrapStrings L"La serratura ha %ls", L"Non ci sono serrature", L"La serratura non presenta trappole", // The %ls is a merc name L"%ls non ha la chiave giusta", L"La serratura non presenta trappole", L"Serrato", L"", L"TRAPPOLE", L"SERRATO", L"APERTO", L"FRACASSATO", L"C'è un interruttore qui. Lo volete attivare?", L"Disattivate le trappole?", L"Più...", // In the next 2 strings, %ls is an item name L"Il %ls è stato posizionato sul terreno.", L"Il %ls è stato dato a %ls.", // In the next 2 strings, %ls is a name L"%ls è stato pagato completamente.", L"Bisogna ancora dare %d a %ls.", L"Scegliete la frequenza di detonazione:", //in this case, frequency refers to a radio signal L"Quante volte finché la bomba non esploderà:", //how much time, in turns, until the bomb blows L"Stabilite la frequenza remota di detonazione:", //in this case, frequency refers to a radio signal L"Disattivate le trappole?", L"Rimuovete la bandiera blu?", L"Mettete qui la bandiera blu?", L"Fine del turno", // In the next string, %ls is a name. Stance refers to way they are standing. L"Siete sicuri di volere attaccare %ls ?", L"Ah, i veicoli non possono cambiare posizione.", L"Il robot non può cambiare posizione.", // In the next 3 strings, %ls is a name L"%ls non può cambiare posizione.", L"%ls non sono ricorsi al pronto soccorso qui.", L"%ls non ha bisogno del pronto soccorso.", L"Non può muoversi là.", L"La vostra squadra è al completo. Non c'è spazio per una recluta.", //there's no room for a recruit on the player's team // In the next string, %ls is a name L"%ls è stato reclutato.", // Here %ls is a name and %d is a number L"Bisogna dare %d a $%ls.", // In the next string, %ls is a name L"Scortate %ls?", // In the next string, the first %ls is a name and the second %ls is an amount of money (including $ sign) L"Il salario di %ls ammonta a %ls per giorno?", // This line is used repeatedly to ask player if they wish to participate in a boxing match. L"Volete combattere?", // In the next string, the first %ls is an item name and the // second %ls is an amount of money (including $ sign) L"Comprate %ls per %ls?", // In the next string, %ls is a name L"%ls è scortato dalla squadra %d.", // These messages are displayed during play to alert the player to a particular situation L"INCEPPATA", //weapon is jammed. L"Il robot ha bisogno di munizioni calibro %ls.", //Robot is out of ammo L"Cosa? Impossibile.", //Merc can't throw to the destination he selected // These are different buttons that the player can turn on and off. L"Modalità furtiva (|Z)", L"Schermata della |mappa", L"Fine del turno (|D)", L"Parlato", L"Muto", L"Alza (|P|a|g|S|ù)", L"Livello della vista (|T|a|b)", L"Scala / Salta", L"Abbassa (|P|a|g|G|i|ù)", L"Esamina (|C|t|r|l)", L"Mercenario precedente", L"Prossimo mercenario (|S|p|a|z|i|o)", L"|Opzioni", L"Modalità a raffica (|B)", L"Guarda/Gira (|L)", L"Salute: %d/%d\nEnergia: %d/%d\nMorale: %ls", L"Eh?", //this means "what?" L"Fermo", //an abbrieviation for "Continued" L"Audio on per %ls.", L"Audio off per %ls.", L"Salute: %d/%d\nCarburante: %d/%d", L"Uscita veicoli" , L"Cambia squadra (|M|a|i|u|s|c |S|p|a|z|i|o)", L"Guida", L"N/A", //this is an acronym for "Not Applicable." L"Usa (Corpo a corpo)", L"Usa (Arma da fuoco)", L"Usa (Lama)", L"Usa (Esplosivo)", L"Usa (Kit medico)", L"Afferra", L"Ricarica", L"Dai", L"%ls è partito.", L"%ls è arrivato.", L"%ls ha esaurito i Punti Azione.", L"%ls non è disponibile.", L"%ls è tutto bendato.", L"%ls non è provvisto di bende.", L"Nemico nel settore!", L"Nessun nemico in vista.", L"Punti Azione insufficienti.", L"Nessuno sta utilizzando il comando a distanza.", L"Il fuoco a raffica ha svuotato il caricatore!", L"SOLDATO", L"CREPITUS", L"ESERCITO", L"CIVILE", L"Settore di uscita", L"OK", L"Annulla", L"Merc. selezionato", L"Tutta la squadra", L"Vai nel settore", L"Vai alla mappa", L"Non puoi uscire dal settore da questa parte.", L"%ls è troppo lontano.", L"Rimuovi le fronde degli alberi", L"Mostra le fronde degli alberi", L"CORVO", //Crow, as in the large black bird L"COLLO", L"TESTA", L"TORSO", L"GAMBE", L"Vuoi dire alla Regina cosa vuole sapere?", L"Impronta digitale ID ottenuta", L"Impronta digitale ID non valida. Arma non funzionante", L"Raggiunto scopo", L"Sentiero bloccato", L"Deposita/Preleva soldi", //Help text over the $ button on the Single Merc Panel L"Nessuno ha bisogno del pronto soccorso.", L"Bloccato.", // Short form of JAMMED, for small inv slots L"Non può andare là.", // used ( now ) for when we click on a cliff L"La persona rifiuta di muoversi.", // In the following message, '%ls' would be replaced with a quantity of money (e.g. $200) L"Sei d'accordo a pagare %ls?", L"Accetti il trattamento medico gratuito?", L"Vuoi sposare Daryl?", L"Quadro delle chiavi", L"Non puoi farlo con un EPC.", L"Risparmi Krott?", L"Fuori dalla gittata dell'arma", L"Minatore", L"Il veicolo può viaggiare solo tra i settori", L"Non è in grado di fasciarsi da solo ora", L"Sentiero bloccato per %ls", // L"I tuoi mercenari, che erano stati catturati dall'esercito di Deidranna, sono stati imprigionati qui!", L"I mercenari catturati dall'esercito di Deidranna, sono stati imprigionati qui!", L"Serratura manomessa", L"Serratura distrutta", L"Qualcun altro sta provando a utilizzare questa porta.", L"Salute: %d/%d\nCarburante: %d/%d", L"%ls non riesce a vedere %ls.", // Cannot see person trying to talk to }; //Varying helptext explains (for the "Go to Sector/Map" checkbox) what will happen given different circumstances in the "exiting sector" interface. static const wchar_t *s_it_pExitingSectorHelpText[pExitingSectorHelpText_SIZE] = { //Helptext for the "Go to Sector" checkbox button, that explains what will happen when the box is checked. L"Se selezionato, il settore adiacente verrà immediatamente caricato.", L"Se selezionato, sarete automaticamente posti nella schermata della mappa\nvisto che i vostri mercenari avranno bisogno di tempo per viaggiare.", //If you attempt to leave a sector when you have multiple squads in a hostile sector. L"Questo settore è occupato da nemicie non potete lasciare mercenari qui.\nDovete risolvere questa situazione prima di caricare qualsiasi altro settore.", //Because you only have one squad in the sector, and the "move all" option is checked, the "go to sector" option is locked to on. //The helptext explains why it is locked. L"Rimuovendo i vostri mercenari da questo settore,\nil settore adiacente verrà immediatamente caricato.", L"Rimuovendo i vostri mercenari da questo settore,\nverrete automaticamente postinella schermata della mappa\nvisto che i vostri mercenari avranno bisogno di tempo per viaggiare.", //If an EPC is the selected merc, it won't allow the merc to leave alone as the merc is being escorted. The "single" button is disabled. L"%ls ha bisogno di essere scortato dai vostri mercenari e non può lasciare questo settore da solo.", //If only one conscious merc is left and is selected, and there are EPCs in the squad, the merc will be prohibited from leaving alone. //There are several strings depending on the gender of the merc and how many EPCs are in the squad. //DO NOT USE THE NEWLINE HERE AS IT IS USED FOR BOTH HELPTEXT AND SCREEN MESSAGES! L"%ls non può lasciare questo settore da solo, perché sta scortando %ls.", //male singular L"%ls non può lasciare questo settore da solo, perché sta scortando %ls.", //female singular L"%ls non può lasciare questo settore da solo, perché sta scortando altre persone.", //male plural L"%ls non può lasciare questo settore da solo, perché sta scortando altre persone.", //female plural //If one or more of your mercs in the selected squad aren't in range of the traversal area, then the "move all" option is disabled, //and this helptext explains why. L"Tutti i vostri personaggi devono trovarsi nei paraggi\nin modo da permettere alla squadra di attraversare.", //Standard helptext for single movement. Explains what will happen (splitting the squad) L"Se selezionato, %ls viaggerà da solo, e\nautomaticamente verrà riassegnato a un'unica squadra.", //Standard helptext for all movement. Explains what will happen (moving the squad) L"Se selezionato, la vostra\nsquadra attualmente selezionata viaggerà, lasciando questo settore.", //This strings is used BEFORE the "exiting sector" interface is created. If you have an EPC selected and you attempt to tactically //traverse the EPC while the escorting mercs aren't near enough (or dead, dying, or unconscious), this message will appear and the //"exiting sector" interface will not appear. This is just like the situation where //This string is special, as it is not used as helptext. Do not use the special newline character (\n) for this string. L"%ls è scortato dai vostri mercenari e non può lasciare questo settore da solo. Gli altri vostri mercenari devono trovarsi nelle vicinanze prima che possiate andarvene.", }; static const wchar_t *s_it_pRepairStrings[pRepairStrings_SIZE] = { L"Oggetti", // tell merc to repair items in inventory L"Sito SAM", // tell merc to repair SAM site - SAM is an acronym for Surface to Air Missile L"Annulla", // cancel this menu L"Robot", // repair the robot }; // NOTE: combine prestatbuildstring with statgain to get a line like the example below. // "John has gained 3 points of marksmanship skill." static const wchar_t *s_it_sPreStatBuildString[sPreStatBuildString_SIZE] = { L"perduto", // the merc has lost a statistic L"guadagnato", // the merc has gained a statistic L"punto di", // singular L"punti di", // plural L"livello di", // singular L"livelli di", // plural }; static const wchar_t *s_it_sStatGainStrings[sStatGainStrings_SIZE] = { L"salute.", L"agilità.", L"destrezza.", L"saggezza.", L"pronto socc.", L"abilità esplosivi.", L"abilità meccanica.", L"mira.", L"esperienza.", L"forza.", L"comando.", }; static const wchar_t *s_it_pHelicopterEtaStrings[pHelicopterEtaStrings_SIZE] = { L"Distanza totale: ", // total distance for helicopter to travel L"Sicura: ", // distance to travel to destination L"Insicura: ", // distance to return from destination to airport L"Costo totale: ", // total cost of trip by helicopter L"TPA: ", // ETA is an acronym for "estimated time of arrival" L"L'elicottero ha poco carburante e deve atterrare in territorio nemico!", // warning that the sector the helicopter is going to use for refueling is under enemy control -> L"Passeggeri: ", L"Seleziona Skyrider o gli Arrivi Drop-off?", L"Skyrider", L"Arrivi", }; static const wchar_t s_it_sMapLevelString[] = L"Sottolivello:"; // what level below the ground is the player viewing in mapscreen static const wchar_t s_it_gsLoyalString[] = L"%d%% Leale"; // the loyalty rating of a town ie : Loyal 53% // error message for when player is trying to give a merc a travel order while he's underground. static const wchar_t s_it_gsUndergroundString[] = L"non può portare ordini di viaggio sottoterra."; static const wchar_t *s_it_gsTimeStrings[gsTimeStrings_SIZE] = { L"h", // hours abbreviation L"m", // minutes abbreviation L"s", // seconds abbreviation L"g", // days abbreviation }; // text for the various facilities in the sector static const wchar_t *s_it_sFacilitiesStrings[sFacilitiesStrings_SIZE] = { L"Nessuno", L"Ospedale", L"Fabbrica", L"Prigione", L"Militare", L"Aeroporto", L"Frequenza di fuoco", // a field for soldiers to practise their shooting skills }; // text for inventory pop up button static const wchar_t *s_it_pMapPopUpInventoryText[pMapPopUpInventoryText_SIZE] = { L"Inventario", L"Uscita", }; // town strings static const wchar_t *s_it_pwTownInfoStrings[pwTownInfoStrings_SIZE] = { L"Dimensione", // size of the town in sectors L"Controllo", // how much of town is controlled L"Miniera", // mine associated with this town L"Lealtà", // the loyalty level of this town L"Servizi principali", // main facilities in this town L"addestramento civili", // state of civilian training in town L"Esercito", // the state of the trained civilians in the town }; // Mine strings static const wchar_t *s_it_pwMineStrings[pwMineStrings_SIZE] = { L"Miniera", // 0 L"Argento", L"Oro", L"Produzione giornaliera", L"Produzione possibile", L"Abbandonata", // 5 L"Chiudi", L"Esci", L"Produci", L"Stato", L"Ammontare produzione", L"Tipo di minerale", // 10 L"Controllo della città", L"Lealtà della città", }; // blank sector strings static const wchar_t *s_it_pwMiscSectorStrings[pwMiscSectorStrings_SIZE] = { L"Forze nemiche", L"Settore", L"# di oggetti", L"Sconosciuto", L"Controllato", L"Sì", L"No", }; // error strings for inventory static const wchar_t *s_it_pMapInventoryErrorString[pMapInventoryErrorString_SIZE] = { L"Non può selezionare quel mercenario.", //MARK CARTER L"%ls non si trova nel settore per prendere quell'oggetto.", L"Durante il combattimento, dovrete raccogliere gli oggetti manualmente.", L"Durante il combattimento, dovrete rilasciare gli oggetti manualmente.", L"%ls non si trova nel settore per rilasciare quell'oggetto.", }; static const wchar_t *s_it_pMapInventoryStrings[pMapInventoryStrings_SIZE] = { L"Posizione", // sector these items are in L"Totale oggetti", // total number of items in sector }; // movement menu text static const wchar_t *s_it_pMovementMenuStrings[pMovementMenuStrings_SIZE] = { L"Muovere mercenari nel settore %ls", // title for movement box L"Rotta spostamento esercito", // done with movement menu, start plotting movement L"Annulla", // cancel this menu L"Altro", // title for group of mercs not on squads nor in vehicles }; static const wchar_t *s_it_pUpdateMercStrings[pUpdateMercStrings_SIZE] = { L"Oops:", // an error has occured L"Scaduto contratto mercenari:", // this pop up came up due to a merc contract ending L"Portato a termine incarico mercenari:", // this pop up....due to more than one merc finishing assignments L"Mercenari di nuovo al lavoro:", // this pop up ....due to more than one merc waking up and returing to work L"Mercenari a riposo:", // this pop up ....due to more than one merc being tired and going to sleep L"Contratti in scadenza:", // this pop up came up due to a merc contract ending }; // map screen map border buttons help text static const wchar_t *s_it_pMapScreenBorderButtonHelpText[pMapScreenBorderButtonHelpText_SIZE] = { L"Mostra città (|w)", L"Mostra |miniere", L"Mos|tra squadre & nemici", L"Mostra spazio |aereo", L"Mostra oggett|i", L"Mostra esercito & nemici (|Z)", }; static const wchar_t *s_it_pMapScreenBottomFastHelp[pMapScreenBottomFastHelp_SIZE] = { L"Portati|le", L"Tattico (|E|s|c)", L"|Opzioni", L"Dilata tempo (|+)", // time compress more L"Comprime tempo (|-)", // time compress less L"Messaggio precedente (|S|u)\nIndietro (|P|a|g|S|u)", // previous message in scrollable list L"Messaggio successivo (|G|i|ù)\nAvanti (|P|a|g|G|i|ù)", // next message in the scrollable list L"Inizia/Ferma tempo (|S|p|a|z|i|o)", // start/stop time compression }; static const wchar_t s_it_pMapScreenBottomText[] = L"Bilancio attuale"; // current balance in player bank account static const wchar_t s_it_pMercDeadString[] = L"%ls è morto."; static const wchar_t s_it_pDayStrings[] = L"Giorno"; // the list of email sender names static const wchar_t *s_it_pSenderNameList[pSenderNameList_SIZE] = { L"Enrico", L"Psych Pro Inc", L"Help Desk", L"Psych Pro Inc", L"Speck", L"R.I.S.", //5 L"Barry", L"Blood", L"Lynx", L"Grizzly", L"Vicki", //10 L"Trevor", L"Grunty", L"Ivan", L"Steroid", L"Igor", //15 L"Shadow", L"Red", L"Reaper", L"Fidel", L"Fox", //20 L"Sidney", L"Gus", L"Buns", L"Ice", L"Spider", //25 L"Cliff", L"Bull", L"Hitman", L"Buzz", L"Raider", //30 L"Raven", L"Static", L"Len", L"Danny", L"Magic", L"Stephan", L"Scully", L"Malice", L"Dr.Q", L"Nails", L"Thor", L"Scope", L"Wolf", L"MD", L"Meltdown", //---------- L"Assicurazione M.I.S.", L"Bobby Ray", L"Capo", L"John Kulba", L"A.I.M.", }; // new mail notify string static const wchar_t s_it_pNewMailStrings[] = L"Avete una nuova E-mail..."; // confirm player's intent to delete messages static const wchar_t *s_it_pDeleteMailStrings[pDeleteMailStrings_SIZE] = { L"Eliminate l'E-mail?", L"Eliminate l'E-mail NON LETTA?", }; // the sort header strings static const wchar_t *s_it_pEmailHeaders[pEmailHeaders_SIZE] = { L"Da:", L"Sogg.:", L"Giorno:", }; // email titlebar text static const wchar_t s_it_pEmailTitleText[] = L"posta elettronica"; // the financial screen strings static const wchar_t s_it_pFinanceTitle[] = L"Contabile aggiuntivo"; // the name we made up for the financial program in the game static const wchar_t *s_it_pFinanceSummary[pFinanceSummary_SIZE] = { L"Crediti:", // credit (subtract from) to player's account L"Debiti:", // debit (add to) to player's account L"Entrate effettive di ieri:", L"Altri depositi di ieri:", L"Debiti di ieri:", L"Bilancio di fine giornata:", L"Entrate effettive di oggi:", L"Altri depositi di oggi:", L"Debiti di oggi:", L"Bilancio attuale:", L"Entrate previste:", L"Bilancio previsto:", // projected balance for player for tommorow }; // headers to each list in financial screen static const wchar_t *s_it_pFinanceHeaders[pFinanceHeaders_SIZE] = { L"Giorno", // the day column L"Crediti", // the credits column (to ADD money to your account) L"Debiti", // the debits column (to SUBTRACT money from your account) L"Transazione", // transaction type - see TransactionText below L"Bilancio", // balance at this point in time L"Pagina", // page number L"Giorno(i)", // the day(s) of transactions this page displays }; static const wchar_t *s_it_pTransactionText[pTransactionText_SIZE] = { L"Interessi maturati", // interest the player has accumulated so far L"Deposito anonimo", L"Tassa di transazione", L"Arruolato %ls dall'A.I.M.", // Merc was hired L"Acquistato da Bobby Ray", // Bobby Ray is the name of an arms dealer L"Acconti pagati al M.E.R.C.", L"Deposito medico per %ls", // medical deposit for merc L"Analisi del profilo I.M.P.", // IMP is the acronym for International Mercenary Profiling L"Assicurazione acquistata per %ls", L"Assicurazione ridotta per %ls", L"Assicurazione estesa per %ls", // johnny contract extended L"Assicurazione annullata %ls", L"Richiesta di assicurazione per %ls", // insurance claim for merc L"Est. contratto di %ls per 1 giorno.", // entend mercs contract by a day L"Est. %ls contratto per 1 settimana.", L"Est. %ls contratto per 2 settimane.", L"Entrata mineraria", L"", //String nuked L"Fiori acquistati", L"Totale rimborso medico per %ls", L"Parziale rimborso medico per %ls", L"Nessun rimborso medico per %ls", L"Pagamento a %ls", // %ls is the name of the npc being paid L"Trasferimento fondi a %ls", // transfer funds to a merc L"Trasferimento fondi da %ls", // transfer funds from a merc L"Equipaggiamento esercito in %ls", // initial cost to equip a town's militia L"Oggetti acquistati da%ls.", //is used for the Shop keeper interface. The dealers name will be appended to the end of the string. L"%ls soldi depositati.", }; // helicopter pilot payment static const wchar_t *s_it_pSkyriderText[pSkyriderText_SIZE] = { L"Skyrider è stato pagato $%d", // skyrider was paid an amount of money L"A Skyrider bisogna ancora dare $%d", // skyrider is still owed an amount of money L"Skyrider non ha passeggeri. Se avete intenzione di trasportare mercenari in questo settore, assegnateli prima al Veicolo/Elicottero.", }; // strings for different levels of merc morale static const wchar_t *s_it_pMoralStrings[pMoralStrings_SIZE] = { L"Ottimo", L"Buono", L"Medio", L"Basso", L"Panico", L"Cattivo", }; // Mercs equipment has now arrived and is now available in Omerta or Drassen. static const wchar_t s_it_str_left_equipment[] = L"L'equipaggio di %ls è ora disponibile a %ls (%c%d)."; // Status that appears on the Map Screen static const wchar_t *s_it_pMapScreenStatusStrings[pMapScreenStatusStrings_SIZE] = { L"Salute", L"Energia", L"Morale", L"Condizione", // the condition of the current vehicle (its "health") L"Carburante", // the fuel level of the current vehicle (its "energy") }; static const wchar_t *s_it_pMapScreenPrevNextCharButtonHelpText[pMapScreenPrevNextCharButtonHelpText_SIZE] = { L"Mercenario precedente (|S|i|n)", // previous merc in the list L"Mercenario successivo (|D|e|s)", // next merc in the list }; static const wchar_t s_it_pEtaString[] = L"TAP"; // eta is an acronym for Estimated Time of Arrival static const wchar_t *s_it_pTrashItemText[pTrashItemText_SIZE] = { L"Non lo vedrete mai più. Siete sicuri?", // do you want to continue and lose the item forever L"Questo oggetto sembra DAVVERO importante. Siete DAVVERO SICURISSIMI di volerlo gettare via?", // does the user REALLY want to trash this item }; static const wchar_t *s_it_pMapErrorString[pMapErrorString_SIZE] = { L"La squadra non può muoversi, se un mercenario dorme.", //1-5 L"Muovete la squadra al primo piano.", L"Ordini di movimento? È un settore nemico!", L"I mercenari devono essere assegnati a una squadra o a un veicolo per potersi muovere.", L"Non avete ancora membri nella squadra.", // you have no members, can't do anything L"I mercenari non possono attenersi agli ordini.", // merc can't comply with your order //6-10 L"%ls ha bisogno di una scorta per muoversi. Inseritelo in una squadra che ne è provvista.", // merc can't move unescorted .. for a male L"%ls ha bisogno di una scorta per muoversi. Inseritela in una squadra che ne è provvista.", // for a female L"Il mercenario non è ancora arrivato ad Arulco!", L"Sembra che ci siano negoziazioni di contratto da stabilire.", L"", //11-15 L"Ordini di movimento? È in corso una battaglia!", L"Siete stati vittima di un'imboscata da parte dai Bloodcat nel settore %ls!", L"Siete appena entrati in quella che sembra una tana di un Bloodcat nel settore I16!", L"", L"La zona SAM in %ls è stata assediata.", //16-20 L"La miniera di %ls è stata assediata. La vostra entrata giornaliera è stata ridotta di %ls per giorno.", L"Il nemico ha assediato il settore %ls senza incontrare resistenza.", L"Almeno uno dei vostri mercenari non ha potuto essere affidato a questo incarico.", L"%ls non ha potuto unirsi alla %ls visto che è completamente pieno", L"%ls non ha potuto unirsi alla %ls visto che è troppo lontano.", //21-25 L"La miniera di %ls è stata invasa dalle forze armate di Deidranna!", L"Le forze armate di Deidranna hanno appena invaso la zona SAM in %ls", L"Le forze armate di Deidranna hanno appena invaso %ls", L"Le forze armate di Deidranna sono appena state avvistate in %ls.", L"Le forze armate di Deidranna sono appena partite per %ls.", //26-30 L"Almeno uno dei vostri mercenari non può riposarsi.", L"Almeno uno dei vostri mercenari non è stato svegliato.", L"L'esercito non si farà vivo finché non avranno finito di esercitarsi.", L"%ls non possono ricevere ordini di movimento adesso.", L"I militari che non si trovano entro i confini della città non possono essere spostati inquesto settore.", //31-35 L"Non potete avere soldati in %ls.", L"Un veicolo non può muoversi se è vuoto!", L"%ls è troppo grave per muoversi!", L"Prima dovete lasciare il museo!", L"%ls è morto!", //36-40 L"%ls non può andare a %ls perché si sta muovendo", L"%ls non può salire sul veicolo in quel modo", L"%ls non può unirsi alla %ls", L"Non potete comprimere il tempo finché non arruolerete nuovi mercenari!", L"Questo veicolo può muoversi solo lungo le strade!", //41-45 L"Non potete riassegnare i mercenari che sono già in movimento", L"Il veicolo è privo di benzina!", L"%ls è troppo stanco per muoversi.", L"Nessuno a bordo è in grado di guidare il veicolo.", L"Uno o più membri di questa squadra possono muoversi ora.", //46-50 L"Uno o più degli altri mercenari non può muoversi ora.", L"Il veicolo è troppo danneggiato!", L"Osservate che solo due mercenari potrebbero addestrare i militari in questo settore.", L"Il robot non può muoversi senza il suo controller. Metteteli nella stessa squadra.", }; // help text used during strategic route plotting static const wchar_t *s_it_pMapPlotStrings[pMapPlotStrings_SIZE] = { L"Cliccate di nuovo su una destinazione per confermare la vostra meta finale, oppure cliccate su un altro settore per fissare più tappe.", L"Rotta di spostamento confermata.", L"Destinazione immutata.", L"Rotta di spostamento annullata.", L"Rotta di spostamento accorciata.", }; // help text used when moving the merc arrival sector static const wchar_t *s_it_pBullseyeStrings[pBullseyeStrings_SIZE] = { L"Cliccate sul settore dove desiderate che i mercenari arrivino.", L"OK. I mercenari che stavano arrivando si sono dileguati a %ls", L"I mercenari non possono essere trasportati, lo spazio aereo non è sicuro!", L"Annullato. Il settore d'arrivo è immutato", L"Lo spazio aereo sopra %ls non è più sicuro! Il settore d'arrivo è stato spostato a %ls.", }; // help text for mouse regions static const wchar_t *s_it_pMiscMapScreenMouseRegionHelpText[pMiscMapScreenMouseRegionHelpText_SIZE] = { L"Entra nell'inventario (|I|n|v|i|o)", L"Getta via l'oggetto", L"Esci dall'inventario (|I|n|v|i|o)", }; static const wchar_t s_it_str_he_leaves_where_drop_equipment[] = L"Volete che %ls lasci il suo equipaggiamento dove si trova ora (%ls) o in seguito a %ls (%ls) dopo aver preso il volo da Arulco?"; static const wchar_t s_it_str_she_leaves_where_drop_equipment[] = L"Volete che %ls lasci il suo equipaggiamento dove si trova ora (%ls) o in seguito a %ls (%ls) dopo aver preso il volo da Arulco?"; static const wchar_t s_it_str_he_leaves_drops_equipment[] = L"%ls sta per partire e spedirà il suo equipaggiamento a %ls."; static const wchar_t s_it_str_she_leaves_drops_equipment[] = L"%ls sta per partire e spedirà il suo equipaggiamento a %ls."; // Text used on IMP Web Pages static const wchar_t *s_it_pImpPopUpStrings[pImpPopUpStrings_SIZE] = { L"Codice di autorizzazione non valido", L"State per riiniziare l'intero processo di profilo. Ne siete certi?", L"Inserite nome e cognome corretti oltre che al sesso", L"L'analisi preliminare del vostro stato finanziario mostra che non potete offrire un'analisi di profilo.", L"Opzione non valida questa volta.", L"Per completare un profilo accurato, dovete aver spazio per almeno uno dei membri della squadra.", L"Profilo già completato.", }; // button labels used on the IMP site static const wchar_t *s_it_pImpButtonText[pImpButtonText_SIZE] = { L"Cosa offriamo", // about the IMP site L"INIZIO", // begin profiling L"Personalità", // personality section L"Attributi", // personal stats/attributes section L"Ritratto", // the personal portrait selection L"Voce %d", // the voice selection L"Fine", // done profiling L"Ricomincio", // start over profiling L"Sì, scelgo la risposta evidenziata.", L"Sì", L"No", L"Finito", // finished answering questions L"Prec.", // previous question..abbreviated form L"Avanti", // next question L"SÌ, LO SONO.", // yes, I am certain L"NO, VOGLIO RICOMINCIARE.", // no, I want to start over the profiling process L"SÌ", L"NO", L"Indietro", // back one page L"Annulla", // cancel selection L"Sì, ne sono certo.", L"No, lasciami dare un'altra occhiata.", L"Immatricolazione", // the IMP site registry..when name and gender is selected L"Analisi", // analyzing your profile results L"OK", L"Voce", }; static const wchar_t *s_it_pExtraIMPStrings[pExtraIMPStrings_SIZE] = { L"Per completare il profilo attuale, seleziona 'Personalità'.", L"Ora che hai completato la Personalità, seleziona i tuoi attributi.", L"Con gli attributi ora assegnati, puoi procedere alla selezione del ritratto.", L"Per completare il processo, seleziona il campione della voce che più ti piace.", }; static const wchar_t s_it_pFilesTitle[] = L"Gestione risorse"; static const wchar_t *s_it_pFilesSenderList[pFilesSenderList_SIZE] = { L"Rapporto", // the recon report sent to the player. Recon is an abbreviation for reconissance L"Intercetta #1", // first intercept file .. Intercept is the title of the organization sending the file...similar in function to INTERPOL/CIA/KGB..refer to fist record in files.txt for the translated title L"Intercetta #2", // second intercept file L"Intercetta #3", // third intercept file L"Intercetta #4", // fourth intercept file L"Intercetta #5", // fifth intercept file L"Intercetta #6", // sixth intercept file }; // Text having to do with the History Log static const wchar_t s_it_pHistoryTitle[] = L"Registro"; static const wchar_t *s_it_pHistoryHeaders[pHistoryHeaders_SIZE] = { L"Giorno", // the day the history event occurred L"Pagina", // the current page in the history report we are in L"Giorno", // the days the history report occurs over L"Posizione", // location (in sector) the event occurred L"Evento", // the event label }; // various history events // THESE STRINGS ARE "HISTORY LOG" STRINGS AND THEIR LENGTH IS VERY LIMITED. // PLEASE BE MINDFUL OF THE LENGTH OF THESE STRINGS. ONE WAY TO "TEST" THIS // IS TO TURN "CHEAT MODE" ON AND USE CONTROL-R IN THE TACTICAL SCREEN, THEN // GO INTO THE LAPTOP/HISTORY LOG AND CHECK OUT THE STRINGS. CONTROL-R INSERTS // MANY (NOT ALL) OF THE STRINGS IN THE FOLLOWING LIST INTO THE GAME. static const wchar_t *s_it_pHistoryStrings[pHistoryStrings_SIZE] = { L"", // leave this line blank //1-5 L"%ls è stato assunto dall'A.I.M.", // merc was hired from the aim site L"%ls è stato assunto dal M.E.R.C.", // merc was hired from the aim site L"%ls morì.", // merc was killed L"Acconti stanziati al M.E.R.C.", // paid outstanding bills at MERC L"Assegno accettato da Enrico Chivaldori", //6-10 L"Profilo generato I.M.P.", L"Acquistato contratto d'assicurazione per %ls.", // insurance contract purchased L"Annullato contratto d'assicurazione per %ls.", // insurance contract canceled L"Versamento per richiesta assicurazione per %ls.", // insurance claim payout for merc L"Esteso contratto di %ls di 1 giorno.", // Extented "mercs name"'s for a day //11-15 L"Esteso contratto di %ls di 1 settimana.", // Extented "mercs name"'s for a week L"Esteso contratto di %ls di 2 settimane.", // Extented "mercs name"'s 2 weeks L"%ls è stato congedato.", // "merc's name" was dismissed. L"%ls è partito.", // "merc's name" quit. L"avventura iniziata.", // a particular quest started //16-20 L"avventura completata.", L"Parlato col capo minatore di %ls", // talked to head miner of town L"Liberato %ls", L"Inganno utilizzato", L"Il cibo dovrebbe arrivare a Omerta domani", //21-25 L"%ls ha lasciato la squadra per diventare la moglie di Daryl Hick", L"contratto di %ls scaduto.", L"%ls è stato arruolato.", L"Enrico si è lamentato della mancanza di progresso", L"Vinta battaglia", //26-30 L"%ls miniera ha iniziato a esaurire i minerali", L"%ls miniera ha esaurito i minerali", L"%ls miniera è stata chiusa", L"%ls miniera è stata riaperta", L"Trovata una prigione chiamata Tixa.", //31-35 L"Sentito di una fabbrica segreta di armi chiamata Orta.", L"Alcuni scienziati a Orta hanno donato una serie di lanciamissili.", L"La regina Deidranna ha bisogno di cadaveri.", L"Frank ha parlato di scontri a San Mona.", L"Un paziente pensa che lui abbia visto qualcosa nella miniera.", //36-40 L"Incontrato qualcuno di nome Devin - vende esplosivi.", L"Imbattutosi nel famoso ex-mercenario dell'A.I.M. Mike!", L"Incontrato Tony - si occupa di armi.", L"Preso un lanciamissili dal Sergente Krott.", L"Concessa a Kyle la licenza del negozio di pelle di Angel.", //41-45 L"Madlab ha proposto di costruire un robot.", L"Gabby può effettuare operazioni di sabotaggio contro sistemi d'allarme.", L"Keith è fuori dall'affare.", L"Howard ha fornito cianuro alla regina Deidranna.", L"Incontrato Keith - si occupa di un po' di tutto a Cambria.", //46-50 L"Incontrato Howard - si occupa di farmaceutica a Balime", L"Incontrato Perko - conduce una piccola impresa di riparazioni.", L"Incontrato Sam di Balime - ha un negozio di hardware.", L"Franz si occupa di elettronica e altro.", L"Arnold possiede un'impresa di riparazioni a Grumm.", //51-55 L"Fredo si occupa di elettronica a Grumm.", L"Donazione ricevuta da un ricco ragazzo a Balime.", L"Incontrato un rivenditore di un deposito di robivecchi di nome Jake.", L"Alcuni vagabondi ci hanno dato una scheda elettronica.", L"Corrotto Walter per aprire la porta del seminterrato.", //56-60 L"Se Dave ha benzina, potrà fare il pieno gratis.", L"Corrotto Pablo.", L"Kingpin tiene i soldi nella miniera di San Mona.", L"%ls ha vinto il Combattimento Estremo", L"%ls ha perso il Combattimento Estremo", //61-65 L"%ls è stato squalificato dal Combattimento Estremo", L"trovati moltissimi soldi nascosti nella miniera abbandonata.", L"Incontrato assassino ingaggiato da Kingpin.", L"Perso il controllo del settore", //ENEMY_INVASION_CODE L"Difeso il settore", //66-70 L"Persa la battaglia", //ENEMY_ENCOUNTER_CODE L"Imboscata fatale", //ENEMY_AMBUSH_CODE L"Annientata imboscata nemica", L"Attacco fallito", //ENTERING_ENEMY_SECTOR_CODE L"Attacco riuscito!", //71-75 L"Creature attaccate", //CREATURE_ATTACK_CODE L"Ucciso dai Bloodcat", //BLOODCAT_AMBUSH_CODE L"Massacrati dai Bloodcat", L"%ls è stato ucciso", L"Data a Carmen la testa di un terrorista", L"Massacro sinistro", L"Ucciso %ls", }; static const wchar_t s_it_pHistoryLocations[] = L"N/A"; // N/A is an acronym for Not Applicable // icon text strings that appear on the laptop static const wchar_t *s_it_pLaptopIcons[pLaptopIcons_SIZE] = { L"E-mail", L"Rete", L"Finanza", L"Personale", L"Cronologia", L"File", L"Chiudi", L"sir-FER 4.0", // our play on the company name (Sirtech) and web surFER }; // bookmarks for different websites // IMPORTANT make sure you move down the Cancel string as bookmarks are being added static const wchar_t *s_it_pBookMarkStrings[pBookMarkStrings_SIZE] = { L"A.I.M.", L"Bobby Ray", L"I.M.P", L"M.E.R.C.", L"Pompe funebri", L"Fiorista", L"Assicurazione", L"Annulla", }; // When loading or download a web page static const wchar_t *s_it_pDownloadString[pDownloadString_SIZE] = { L"Caricamento", L"Caricamento", }; //This is the text used on the bank machines, here called ATMs for Automatic Teller Machine static const wchar_t *s_it_gsAtmStartButtonText[gsAtmStartButtonText_SIZE] = { L"Stato", // view stats of the merc L"Inventario", // view the inventory of the merc L"Impiego", }; // Web error messages. Please use foreign language equivilant for these messages. // DNS is the acronym for Domain Name Server // URL is the acronym for Uniform Resource Locator static const wchar_t s_it_pErrorStrings[] = L"Connessione intermittente all'host. Tempi d'attesa più lunghi per il trasferimento."; static const wchar_t s_it_pPersonnelString[] = L"Mercenari:"; // mercs we have static const wchar_t s_it_pWebTitle[] = L"sir-FER 4.0"; // our name for the version of the browser, play on company name // The titles for the web program title bar, for each page loaded static const wchar_t *s_it_pWebPagesTitles[pWebPagesTitles_SIZE] = { L"A.I.M.", L"Membri dell'A.I.M.", L"Ritratti A.I.M.", // a mug shot is another name for a portrait L"Categoria A.I.M.", L"A.I.M.", L"Membri dell'A.I.M.", L"Tattiche A.I.M.", L"Storia A.I.M.", L"Collegamenti A.I.M.", L"M.E.R.C.", L"Conti M.E.R.C.", L"Registrazione M.E.R.C.", L"Indice M.E.R.C.", L"Bobby Ray", L"Bobby Ray - Armi", L"Bobby Ray - Munizioni", L"Bobby Ray - Giubb. A-P", L"Bobby Ray - Varie", //misc is an abbreviation for miscellaneous L"Bobby Ray - Usato", L"Bobby Ray - Ordine Mail", L"I.M.P.", L"I.M.P.", L"Servizio Fioristi Riuniti", L"Servizio Fioristi Riuniti - Galleria", L"Servizio Fioristi Riuniti - Ordine", L"Servizio Fioristi Riuniti - Card Gallery", L"Agenti assicurativi Malleus, Incus & Stapes", L"Informazione", L"Contratto", L"Commenti", L"Servizio di pompe funebri di McGillicutty", L"URL non ritrovato.", L"Bobby Ray - Spedizioni recenti", L"", L"", }; static const wchar_t *s_it_pShowBookmarkString[pShowBookmarkString_SIZE] = { L"Aiuto", L"Cliccate su Rete un'altra volta per i segnalibri.", }; static const wchar_t *s_it_pLaptopTitles[pLaptopTitles_SIZE] = { L"Cassetta della posta", L"Gestione risorse", L"Personale", L"Contabile aggiuntivo", L"Ceppo storico", }; static const wchar_t *s_it_pPersonnelDepartedStateStrings[pPersonnelDepartedStateStrings_SIZE] = { //reasons why a merc has left. L"Ucciso in azione", L"Licenziato", L"Sposato", L"Contratto Scaduto", L"Liberato", }; // personnel strings appearing in the Personnel Manager on the laptop static const wchar_t *s_it_pPersonelTeamStrings[pPersonelTeamStrings_SIZE] = { L"Squadra attuale", L"Partenze", L"Costo giornaliero:", L"Costo più alto:", L"Costo più basso:", L"Ucciso in azione:", L"Licenziato:", L"Altro:", }; static const wchar_t *s_it_pPersonnelCurrentTeamStatsStrings[pPersonnelCurrentTeamStatsStrings_SIZE] = { L"Più basso", L"Normale", L"Più alto", }; static const wchar_t *s_it_pPersonnelTeamStatsStrings[pPersonnelTeamStatsStrings_SIZE] = { L"SAL", L"AGI", L"DES", L"FOR", L"COM", L"SAG", L"LIV", L"TIR", L"MEC", L"ESP", L"PS", }; // horizontal and vertical indices on the map screen static const wchar_t *s_it_pMapVertIndex[pMapVertIndex_SIZE] = { L"X", L"A", L"B", L"C", L"D", L"E", L"F", L"G", L"H", L"I", L"J", L"K", L"L", L"M", L"N", L"O", L"P", }; static const wchar_t *s_it_pMapHortIndex[pMapHortIndex_SIZE] = { L"X", L"1", L"2", L"3", L"4", L"5", L"6", L"7", L"8", L"9", L"10", L"11", L"12", L"13", L"14", L"15", L"16", }; static const wchar_t *s_it_pMapDepthIndex[pMapDepthIndex_SIZE] = { L"", L"-1", L"-2", L"-3", }; // text that appears on the contract button static const wchar_t s_it_pContractButtonString[] = L"Contratto"; // text that appears on the update panel buttons static const wchar_t *s_it_pUpdatePanelButtons[pUpdatePanelButtons_SIZE] = { L"Continua", L"Fermati", }; // Text which appears when everyone on your team is incapacitated and incapable of battle static StrPointer s_it_LargeTacticalStr[LargeTacticalStr_SIZE] = { L"Siete stati sconfitti in questo settore!", L"Il nemico, non avendo alcuna pietà delle anime della squadra, divorerà ognuno di voi!", L"I membri inconscenti della vostra squadra sono stati catturati!", L"I membri della vostra squadra sono stati fatti prigionieri dal nemico.", }; //Insurance Contract.c //The text on the buttons at the bottom of the screen. static const wchar_t *s_it_InsContractText[InsContractText_SIZE] = { L"Indietro", L"Avanti", L"Accetta", L"Pulisci", }; //Insurance Info // Text on the buttons on the bottom of the screen static const wchar_t *s_it_InsInfoText[InsInfoText_SIZE] = { L"Indietro", L"Avanti", }; //For use at the M.E.R.C. web site. Text relating to the player's account with MERC static const wchar_t *s_it_MercAccountText[MercAccountText_SIZE] = { // Text on the buttons on the bottom of the screen L"Autorizza", L"Home Page", L"Conto #:", L"Merc", L"Giorni", L"Tasso", //5 L"Costo", L"Totale:", L"Conferma il pagamento di %ls?", //the %ls is a string that contains the dollar amount ( ex. "$150" ) }; //For use at the M.E.R.C. web site. Text relating a MERC mercenary static const wchar_t *s_it_MercInfo[MercInfo_SIZE] = { L"Indietro", L"Ricompensa", L"Successivo", L"Info. addizionali", L"Home Page", L"Assoldato", L"Salario:", L"Al giorno", L"Deceduto", L"Sembra che state arruolando troppi mercenari. Il vostro limite è di 18.", L"Non disponibile", }; // For use at the M.E.R.C. web site. Text relating to opening an account with MERC static const wchar_t *s_it_MercNoAccountText[MercNoAccountText_SIZE] = { //Text on the buttons at the bottom of the screen L"Apri conto", L"Annulla", L"Non hai alcun conto. Vuoi aprirne uno?", }; // For use at the M.E.R.C. web site. MERC Homepage static const wchar_t *s_it_MercHomePageText[MercHomePageText_SIZE] = { //Description of various parts on the MERC page L"Speck T. Kline, fondatore e proprietario", L"Per aprire un conto, cliccate qui", L"Per visualizzare un conto, cliccate qui", L"Per visualizzare i file, cliccate qui", // The version number on the video conferencing system that pops up when Speck is talking L"Speck Com v3.2", }; // For use at MiGillicutty's Web Page. static const wchar_t *s_it_sFuneralString[sFuneralString_SIZE] = { L"Impresa di pompe funebri di McGillicutty: Il dolore delle famiglie che hanno fornito il loro aiuto dal 1983.", L"Precedentemente mercenario dell'A.I.M. Murray \"Pops\" McGillicutty è un impresario di pompe funebri qualificato e con molta esperienza.", L"Essendo coinvolto profondamente nella morte e nel lutto per tutta la sua vita, Pops sa quanto sia difficile affrontarli.", L"L'impresa di pompe funebri di McGillicutty offre una vasta gamma di servizi funebri, da una spalla su cui piangere a ricostruzioni post-mortem per corpi mutilati o sfigurati.", L"Lasciate che l'impresa di pompe funebri di McGillicutty vi aiuti e i vostri amati riposeranno in pace.", // Text for the various links available at the bottom of the page L"SPEDISCI FIORI", L"ESPOSIZIONE DI BARE & URNE", L"SERVIZI DI CREMAZIONE", L"SERVIZI PRE-FUNEBRI", L"CERIMONIALE FUNEBRE", // The text that comes up when you click on any of the links ( except for send flowers ). L"Purtroppo, il resto di questo sito non è stato completato a causa di una morte in famiglia. Aspettando la lettura del testamento e la riscossione dell'eredità, il sito verrà ultimato non appena possibile.", L"Vi porgiamo, comunque, le nostre condolianze in questo momento di dolore. Contatteci ancora.", }; // Text for the florist Home Page static const wchar_t *s_it_sFloristText[sFloristText_SIZE] = { //Text on the button on the bottom of the page L"Galleria", //Address of United Florist L"\"Ci lanciamo col paracadute ovunque\"", L"1-555-SCENT-ME", L"333 Dot. NoseGay, Seedy City, CA USA 90210", L"http://www.scent-me.com", // detail of the florist page L"Siamo veloci ed efficienti!", L"Consegna il giorno successivo in quasi tutto il mondo, garantito. Applicate alcune restrizioni.", L"I prezzi più bassi in tutto il mondo, garantito!", L"Mostrateci un prezzo concorrente più basso per qualsiasi progetto, e riceverete una dozzina di rose, gratuitamente.", L"Flora, fauna & fiori in volo dal 1981.", L"I nostri paracadutisti decorati ex-bomber lanceranno il vostro bouquet entro un raggio di dieci miglia dalla locazione richiesta. Sempre e ovunque!", L"Soddisfiamo la vostra fantasia floreale.", L"Lasciate che Bruce, il nostro esperto in composizioni floreali, selezioni con cura i fiori più freschi e della migliore qualità dalle nostre serre più esclusive.", L"E ricordate, se non l'abbiamo, possiamo coltivarlo - E subito!", }; //Florist OrderForm static const wchar_t *s_it_sOrderFormText[sOrderFormText_SIZE] = { //Text on the buttons L"Indietro", L"Spedisci", L"Home", L"Galleria", L"Nome del bouquet:", L"Prezzo:", //5 L"Numero ordine:", L"Data consegna", L"gior. succ.", L"arriva quando arriva", L"Luogo consegna", //10 L"Servizi aggiuntivi", L"Bouquet schiacciato ($10)", L"Rose nere ($20)", L"Bouquet appassito ($10)", L"Torta di frutta (se disponibile 10$)", //15 L"Sentimenti personali:", L"Il vostro messaggio non può essere più lungo di 75 caratteri.", L"... oppure sceglietene uno dai nostri", L"BIGLIETTI STANDARD", L"Informazioni sulla fatturazione",//20 //The text that goes beside the area where the user can enter their name L"Nome:", }; //Florist Gallery.c static const wchar_t *s_it_sFloristGalleryText[sFloristGalleryText_SIZE] = { //text on the buttons L"Prec.", //abbreviation for previous L"Succ.", //abbreviation for next L"Clicca sul modello che vuoi ordinare.", L"Ricorda: c'è un supplemento di 10$ per tutti i bouquet appassiti o schiacciati.", //text on the button L"Home", }; //Florist Cards static const wchar_t *s_it_sFloristCards[sFloristCards_SIZE] = { L"Cliccate sulla vostra selezione", L"Indietro", }; // Text for Bobby Ray's Mail Order Site static const wchar_t *s_it_BobbyROrderFormText[BobbyROrderFormText_SIZE] = { L"Ordine", //Title of the page L"Qta", // The number of items ordered L"Peso (%ls)", // The weight of the item L"Nome oggetto", // The name of the item L"Prezzo unit.", // the item's weight L"Totale", //5 // The total price of all of items of the same type L"Sotto-totale", // The sub total of all the item totals added L"S&C (Vedete luogo consegna)", // S&H is an acronym for Shipping and Handling L"Totale finale", // The grand total of all item totals + the shipping and handling L"Luogo consegna", L"Spedizione veloce", //10 // See below L"Costo (per %ls.)", // The cost to ship the items L"Espresso di notte", // Gets deliverd the next day L"2 giorni d'affari", // Gets delivered in 2 days L"Servizio standard", // Gets delivered in 3 days L"Annulla ordine",//15 // Clears the order page L"Accetta ordine", // Accept the order L"Indietro", // text on the button that returns to the previous page L"Home Page", // Text on the button that returns to the home Page L"* Indica oggetti usati", // Disclaimer stating that the item is used L"Non potete permettervi di pagare questo.", //20 // A popup message that to warn of not enough money L"<NESSUNO>", // Gets displayed when there is no valid city selected L"Siete sicuri di volere spedire quest'ordine a %ls?", // A popup that asks if the city selected is the correct one L"peso del pacco**", // Displays the weight of the package L"** Peso min.", // Disclaimer states that there is a minimum weight for the package L"Spedizioni", }; // This text is used when on the various Bobby Ray Web site pages that sell items static const wchar_t *s_it_BobbyRText[BobbyRText_SIZE] = { L"Ordini:", // Title // instructions on how to order L"Cliccate sull'oggetto. Sinistro per aggiungere pezzi, destro per toglierne. Una volta selezionata la quantità, procedete col nuovo ordine.", //Text on the buttons to go the various links L"Oggetti prec.", // L"Armi", //3 L"Munizioni", //4 L"Giubb. A-P", //5 L"Varie", //6 //misc is an abbreviation for miscellaneous L"Usato", //7 L"Oggetti succ.", L"ORDINE", L"Home Page", //10 //The following lines provide information on the items L"Peso:", // Weight of all the items of the same type L"Cal.:", // the caliber of the gun L"Mag.:", // number of rounds of ammo the Magazine can hold L"Git.:", // The range of the gun L"Dan.:", // Damage of the weapon L"FFA:", // Weapon's Rate Of Fire, acronym ROF L"Costo:", // Cost of the item L"Inventario:", // The number of items still in the store's inventory L"Num. ordine:", // The number of items on order L"Danneggiato", // If the item is damaged L"Totale:", // The total cost of all items on order L"* funzionale al %", // if the item is damaged, displays the percent function of the item //Popup that tells the player that they can only order 10 items at a time L"Darn! Quest'ordine qui accetterà solo 10 oggetti. Se avete intenzione di ordinare più merce (ed è quello che speriamo), fate un ordine a parte e accettate le nostre scuse.", // A popup that tells the user that they are trying to order more items then the store has in stock L"Ci dispiace. Non disponiamo più di questo articolo. Riprovate più tardi.", //A popup that tells the user that the store is temporarily sold out L"Ci dispiace, ma siamo momentaneamente sprovvisti di oggetti di questo genere.", }; // The following line is used on the Ammunition page. It is used for help text // to display how many items the player's merc has that can use this type of // ammo. static const wchar_t s_it_str_bobbyr_guns_num_guns_that_use_ammo[] = L"La vostra squadra ha %d arma(i) che usa(no) questo tipo di munizioni"; // Text for Bobby Ray's Home Page static const wchar_t *s_it_BobbyRaysFrontText[BobbyRaysFrontText_SIZE] = { //Details on the web site L"Questo è il negozio con la fornitura militare e le armi più recenti e potenti!", L"Possiamo trovare la soluzione perfetta per tutte le vostre esigenze riguardo agli esplosivi.", L"Oggetti usati e riparati", //Text for the various links to the sub pages L"Varie", L"ARMI", L"MUNIZIONI", //5 L"GIUBB. A-P", //Details on the web site L"Se non lo vendiamo, non potrete averlo!", L"In costruzione", }; // Text for the AIM page. // This is the text used when the user selects the way to sort the aim mercanaries on the AIM mug shot page static const wchar_t *s_it_AimSortText[AimSortText_SIZE] = { L"Membri dell'A.I.M.", // Title // Title for the way to sort L"Ordine per:", //Text of the links to other AIM pages L"Visualizza le facce dei mercenari disponibili", L"Rivedi il file di ogni singolo mercenario", L"Visualizza la galleria degli associati dell'A.I.M." }; // text to display how the entries will be sorted static const wchar_t s_it_str_aim_sort_price[] = L"Prezzo"; static const wchar_t s_it_str_aim_sort_experience[] = L"Esperienza"; static const wchar_t s_it_str_aim_sort_marksmanship[] = L"Mira"; static const wchar_t s_it_str_aim_sort_medical[] = L"Pronto socc."; static const wchar_t s_it_str_aim_sort_explosives[] = L"Esplosivi"; static const wchar_t s_it_str_aim_sort_mechanical[] = L"Meccanica"; static const wchar_t s_it_str_aim_sort_ascending[] = L"Crescente"; static const wchar_t s_it_str_aim_sort_descending[] = L"Decrescente"; //Aim Policies.c //The page in which the AIM policies and regulations are displayed static const wchar_t *s_it_AimPolicyText[AimPolicyText_SIZE] = { // The text on the buttons at the bottom of the page L"Indietro", L"Home Page", L"Indice", L"Avanti", L"Disaccordo", L"Accordo", }; //Aim Member.c //The page in which the players hires AIM mercenaries // Instructions to the user to either start video conferencing with the merc, or to go the mug shot index static const wchar_t *s_it_AimMemberText[AimMemberText_SIZE] = { L"Clic sinistro", L"per contattarlo", L"Clic destro", L"per i mercenari disponibili.", }; //Aim Member.c //The page in which the players hires AIM mercenaries static const wchar_t *s_it_CharacterInfo[CharacterInfo_SIZE] = { // the contract expenses' area L"Paga", L"Durata", L"1 giorno", L"1 settimana", L"2 settimane", // text for the buttons that either go to the previous merc, // start talking to the merc, or go to the next merc L"Indietro", L"Contratto", L"Avanti", L"Ulteriori informazioni", // Title for the additional info for the merc's bio L"Membri attivi", // Title of the page L"Dispositivo opzionale:", // Displays the optional gear cost L"Deposito MEDICO richiesto", // If the merc required a medical deposit, this is displayed }; //Aim Member.c //The page in which the player's hires AIM mercenaries //The following text is used with the video conference popup static const wchar_t *s_it_VideoConfercingText[VideoConfercingText_SIZE] = { L"Costo del contratto:", //Title beside the cost of hiring the merc //Text on the buttons to select the length of time the merc can be hired L"1 giorno", L"1 settimana", L"2 settimane", //Text on the buttons to determine if you want the merc to come with the equipment L"Nessun equip.", L"Compra equip.", // Text on the Buttons L"TRASFERISCI FONDI", // to actually hire the merc L"ANNULLA", // go back to the previous menu L"ARRUOLA", // go to menu in which you can hire the merc L"TACI", // stops talking with the merc L"OK", L"LASCIA MESSAGGIO", // if the merc is not there, you can leave a message //Text on the top of the video conference popup L"Videoconferenza con", L"Connessione...", L"con deposito" // Displays if you are hiring the merc with the medical deposit }; //Aim Member.c //The page in which the player hires AIM mercenaries // The text that pops up when you select the TRANSFER FUNDS button static const wchar_t *s_it_AimPopUpText[AimPopUpText_SIZE] = { L"TRASFERIMENTO ELETTRONICO FONDI RIUSCITO", // You hired the merc L"NON IN GRADO DI TRASFERIRE", // Player doesn't have enough money, message 1 L"FONDI INSUFFICIENTI", // Player doesn't have enough money, message 2 // if the merc is not available, one of the following is displayed over the merc's face L"In missione", L"Lascia messaggio", L"Deceduto", //If you try to hire more mercs than game can support L"Avete già una squadra di 18 mercenari.", L"Messaggio già registrato", L"Messaggio registrato", }; //AIM Link.c static const wchar_t s_it_AimLinkText[] = L"Collegamenti dell'A.I.M."; // The title of the AIM links page //Aim History // This page displays the history of AIM static const wchar_t *s_it_AimHistoryText[AimHistoryText_SIZE] = { L"Storia dell'A.I.M.", //Title // Text on the buttons at the bottom of the page L"Indietro", L"Home Page", L"Associati", L"Avanti", }; //Aim Mug Shot Index //The page in which all the AIM members' portraits are displayed in the order selected by the AIM sort page. static const wchar_t *s_it_AimFiText[AimFiText_SIZE] = { // displays the way in which the mercs were sorted L"Prezzo", L"Esperienza", L"Mira", L"Pronto socc.", L"Esplosivi", L"Meccanica", // The title of the page, the above text gets added at the end of this text L"Membri scelti dell'A.I.M. in ordine crescente secondo %ls", L"Membri scelti dell'A.I.M. in ordine decrescente secondo %ls", // Instructions to the players on what to do L"Clic sinistro", L"Per scegliere un mercenario.", //10 L"Clic destro", L"Per selezionare opzioni", // Gets displayed on top of the merc's portrait if they are... L"Deceduto", //14 L"In missione", }; //AimArchives. // The page that displays information about the older AIM alumni merc... mercs who are no longer with AIM static const wchar_t *s_it_AimAlumniText[AimAlumniText_SIZE] = { // Text of the buttons L"PAGINA 1", L"PAGINA 2", L"PAGINA 3", L"Membri dell'A.I.M.", // Title of the page L"FINE" // Stops displaying information on selected merc }; //AIM Home Page static const wchar_t *s_it_AimScreenText[AimScreenText_SIZE] = { // AIM disclaimers L"A.I.M. e il logo A.I.M. sono marchi registrati in diversi paesi.", L"Di conseguenza, non cercate di copiarci.", L"Copyright 1998-1999 A.I.M., Ltd. Tutti i diritti riservati.", //Text for an advertisement that gets displayed on the AIM page L"Servizi riuniti floreali", L"\"Atterriamo col paracadute ovunque\"", //10 L"Fallo bene", L"... la prima volta", L"Se non abbiamo armi e oggetti, non ne avrete bisogno.", }; //Aim Home Page static const wchar_t *s_it_AimBottomMenuText[AimBottomMenuText_SIZE] = { //Text for the links at the bottom of all AIM pages L"Home Page", L"Membri", L"Associati", L"Assicurazioni", L"Storia", L"Collegamenti", }; //ShopKeeper Interface // The shopkeeper interface is displayed when the merc wants to interact with // the various store clerks scattered through out the game. static const wchar_t *s_it_SKI_Text[SKI_SIZE ] = { L"MERCANZIA IN STOCK", //Header for the merchandise available L"PAGINA", //The current store inventory page being displayed L"COSTO TOTALE", //The total cost of the the items in the Dealer inventory area L"VALORE TOTALE", //The total value of items player wishes to sell L"STIMATO", //Button text for dealer to evaluate items the player wants to sell L"TRANSAZIONE", //Button text which completes the deal. Makes the transaction. L"FINE", //Text for the button which will leave the shopkeeper interface. L"COSTO DI RIPARAZIONE", //The amount the dealer will charge to repair the merc's goods L"1 ORA", // SINGULAR! The text underneath the inventory slot when an item is given to the dealer to be repaired L"%d ORE", // PLURAL! The text underneath the inventory slot when an item is given to the dealer to be repaired L"RIPARATO", // Text appearing over an item that has just been repaired by a NPC repairman dealer L"Non c'è abbastanza spazio nel vostro margine di ordine.", //Message box that tells the user there is no more room to put there stuff L"%d MINUTI", // The text underneath the inventory slot when an item is given to the dealer to be repaired L"Lascia oggetto a terra.", }; static const wchar_t *s_it_SkiMessageBoxText[SkiMessageBoxText_SIZE] = { L"Volete sottrarre %ls dal vostro conto principale per coprire la differenza?", L"Fondi insufficienti. Avete pochi %ls", L"Volete sottrarre %ls dal vostro conto principale per coprire la spesa?", L"Rivolgetevi all'operatore per iniziare la transazione", L"Rivolgetevi all'operatore per riparare gli oggetti selezionati", L"Fine conversazione", L"Bilancio attuale", }; //OptionScreen.c static const wchar_t *s_it_zOptionsText[zOptionsText_SIZE] = { //button Text L"Salva partita", L"Carica partita", L"Abbandona", L"Fine", //Text above the slider bars L"Effetti", L"Parlato", L"Musica", //Confirmation pop when the user selects.. L"Volete terminare la partita e tornare al menu principale?", L"Avete bisogno dell'opzione 'Parlato' o di quella 'Sottotitoli' per poter giocare.", }; //SaveLoadScreen static const wchar_t *s_it_zSaveLoadText[zSaveLoadText_SIZE] = { L"Salva partita", L"Carica partita", L"Annulla", L"Salvamento selezionato", L"Caricamento selezionato", L"Partita salvata con successo", L"ERRORE durante il salvataggio!", L"Partita caricata con successo", L"ERRORE durante il caricamento: \"%hs\"", L"La versione del gioco nel file della partita salvata è diverso dalla versione attuale. È abbastanza sicuro proseguire. Continuate?", L"I file della partita salvata potrebbero essere annullati. Volete cancellarli tutti?", L"Tentativo di caricare una versione salvata più vecchia. Aggiornate e caricate automaticamente quella salvata?", L"Tentativo di caricare una vecchia versione salvata. Aggiornate e caricate automaticamente quella salvata?", L"Siete sicuri di volere sovrascrivere la partita salvata nello slot #%d?", //The first %d is a number that contains the amount of free space on the users hard drive, //the second is the recommended amount of free space. L"Lo spazio su disco si sta esaurendo. Sono disponibili solo %d MB, mentre per giocare a Jagged dovrebbero esserci almeno %d MB liberi .", L"Salvataggio in corso...", //When saving a game, a message box with this string appears on the screen L"Armi normali", L"Tonn. di armi", L"Stile realistico", L"Stile fantascientifico", L"Difficoltà", }; //MapScreen static const wchar_t *s_it_zMarksMapScreenText[zMarksMapScreenText_SIZE] = { L"Livello mappa", L"Non avete soldati. Avete bisogno di addestrare gli abitanti della città per poter disporre di un esercito cittadino.", L"Entrata giornaliera", L"Il mercenario ha l'assicurazione sulla vita", L"%ls non è stanco.", L"%ls si sta muovendo e non può riposare", L"%ls è troppo stanco, prova un po' più tardi.", L"%ls sta guidando.", L"La squadra non può muoversi, se un mercenario dorme.", // stuff for contracts L"Visto che non potete pagare il contratto, non avete neanche i soldi per coprire il premio dell'assicurazione sulla vita di questo nercenario.", L"%ls premio dell'assicurazione costerà %ls per %d giorno(i) extra. Volete pagare?", L"Settore inventario", L"Il mercenario ha una copertura medica.", // other items L"Medici", // people acting a field medics and bandaging wounded mercs L"Pazienti", // people who are being bandaged by a medic L"Fine", // Continue on with the game after autobandage is complete L"Ferma", // Stop autobandaging of patients by medics now L"%ls non ha un kit di riparazione.", L"%ls non ha un kit di riparazione.", L"Non ci sono abbastanza persone che vogliono essere addestrate ora.", L"%ls è pieno di soldati.", L"Il mercenario ha un contratto a tempo determinato.", L"Il contratto del mercenario non è assicurato", }; static const wchar_t s_it_pLandMarkInSectorString[] = L"La squadra %d ha notato qualcuno nel settore %ls"; // confirm the player wants to pay X dollars to build a militia force in town static const wchar_t *s_it_pMilitiaConfirmStrings[pMilitiaConfirmStrings_SIZE] = { L"Addestrare una squadra dell'esercito cittadino costerà $", // telling player how much it will cost L"Approvate la spesa?", // asking player if they wish to pay the amount requested L"Non potete permettervelo.", // telling the player they can't afford to train this town L"Continuate ad aeddestrare i soldati in %ls (%ls %d)?", // continue training this town? L"Costo $", // the cost in dollars to train militia L"(S/N)", // abbreviated yes/no L"Addestrare l'esrecito cittadino nei settori di %d costerà $ %d. %ls", // cost to train sveral sectors at once L"Non potete permettervi il $%d per addestrare l'esercito cittadino qui.", L"%ls ha bisogno di una percentuale di %d affinché possiate continuare ad addestrare i soldati.", L"Non potete più addestrare i soldati a %ls.", }; //Strings used in the popup box when withdrawing, or depositing money from the $ sign at the bottom of the single merc panel static const wchar_t *s_it_gzMoneyWithdrawMessageText[gzMoneyWithdrawMessageText_SIZE] = { L"Potete prelevare solo fino a $20,000 alla volta.", L"Sieti sicuri di voler depositare il %ls sul vostro conto?", }; static const wchar_t s_it_gzCopyrightText[] = L"Copyright (C) 1999 Sir-tech Canada Ltd. Tutti i diritti riservati."; //option Text static const wchar_t *s_it_zOptionsToggleText[zOptionsToggleText_SIZE] = { L"Parlato", L"Conferme mute", L"Sottotitoli", L"Mettete in pausa il testo del dialogo", L"Fumo dinamico", L"Sangue e violenza", L"Non è necessario usare il mouse!", L"Vecchio metodo di selezione", L"Mostra il percorso dei mercenari", L"Mostra traiettoria colpi sbagliati", L"Conferma in tempo reale", L"Visualizza gli avvertimenti sveglio/addormentato", L"Utilizza il sistema metrico", L"Tragitto illuminato durante gli spostamenti", L"Sposta il cursore sui mercenari", L"Sposta il cursore sulle porte", L"Evidenzia gli oggetti", L"Mostra le fronde degli alberi", L"Mostra strutture", L"Mostra il cursore 3D", }; //This is the help text associated with the above toggles. static const wchar_t *s_it_zOptionsScreenHelpText[zOptionsToggleText_SIZE] = { //speech L"Attivate questa opzione, se volete ascoltare il dialogo dei personaggi.", //Mute Confirmation L"Attivate o disattivate le conferme verbali dei personaggi.", //Subtitles L"Controllate se il testo su schermo viene visualizzato per il dialogo.", //Key to advance speech L"Se i sottotitoli sono attivati, utilizzate questa opzione per leggere tranquillamente i dialoghi NPC.", //Toggle smoke animation L"Disattivate questa opzione, se il fumo dinamico diminuisce la frequenza d'aggiornamento.", //Blood n Gore L"Disattivate questa opzione, se il sangue vi disturba.", //Never move my mouse L"Disattivate questa opzione per muovere automaticamente il mouse sulle finestre a comparsa di conferma al loro apparire.", //Old selection method L"Attivate questa opzione per selezionare i personaggi e muoverli come nel vecchio JA (dato che la funzione è stata invertita).", //Show movement path L"Attivate questa opzione per visualizzare i sentieri di movimento in tempo reale (oppure disattivatela utilizzando il tasto MAIUSC).", //show misses L"Attivate per far sì che la partita vi mostri dove finiscono i proiettili quando \"sbagliate\".", //Real Time Confirmation L"Se attivata, sarà richiesto un altro clic su \"salva\" per il movimento in tempo reale.", //Sleep/Wake notification L"Se attivata, verrete avvisati quando i mercenari in \"servizio\" vanno a riposare e quando rientrano in servizio.", //Use the metric system L"Se attivata, utilizza il sistema metrico di misurazione; altrimenti ricorre al sistema britannico.", //Merc Lighted movement L"Se attivata, il mercenario mostrerà il terreno su cui cammina. Disattivatela per un aggiornamento più veloce.", //Smart cursor L"Se attivata, muovendo il cursore vicino ai vostri mercenari li evidenzierà automaticamente.", //snap cursor to the door L"Se attivata, muovendo il cursore vicino a una porta farà posizionare automaticamente il cursore sopra di questa.", //glow items L"Se attivata, l'opzione evidenzierà gli |Oggetti automaticamente.", //toggle tree tops L"Se attivata, mostra le |fronde degli alberi.", //toggle wireframe L"Se attivata, visualizza le |Strutture dei muri nascosti.", L"Se attivata, il cursore di movimento verrà mostrato in 3D (|H|o|m|e).", }; static const wchar_t *s_it_gzGIOScreenText[gzGIOScreenText_SIZE] = { L"INSTALLAZIONE INIZIALE DEL GIOCO", L"Versione del gioco", L"Realistica", L"Fantascientifica", L"Opzioni delle armi", L"Varietà di armi", L"Normale", L"Livello di difficoltà", L"Principiante", L"Esperto", L"Professionista", L"Ok", L"Annulla", L"Difficoltà extra", L"Tempo illimitato", L"Turni a tempo", L"Dead is Dead", }; static const wchar_t *s_it_pDeliveryLocationStrings[pDeliveryLocationStrings_SIZE] = { L"Austin", //Austin, Texas, USA L"Baghdad", //Baghdad, Iraq (Suddam Hussein's home) L"Drassen", //The main place in JA2 that you can receive items. The other towns are dummy names... L"Hong Kong", //Hong Kong, Hong Kong L"Beirut", //Beirut, Lebanon (Middle East) L"Londra", //London, England L"Los Angeles", //Los Angeles, California, USA (SW corner of USA) L"Meduna", //Meduna -- the other airport in JA2 that you can receive items. L"Metavira", //The island of Metavira was the fictional location used by JA1 L"Miami", //Miami, Florida, USA (SE corner of USA) L"Mosca", //Moscow, USSR L"New York", //New York, New York, USA L"Ottawa", //Ottawa, Ontario, Canada -- where JA2 was made! L"Parigi", //Paris, France L"Tripoli", //Tripoli, Libya (eastern Mediterranean) L"Tokyo", //Tokyo, Japan L"Vancouver", //Vancouver, British Columbia, Canada (west coast near US border) }; // This string is used in the IMP character generation. It is possible to // select 0 ability in a skill meaning you can't use it. This text is // confirmation to the player. static const wchar_t s_it_pSkillAtZeroWarning[] = L"Siete sicuri? Un valore di zero significa NESSUNA abilità."; static const wchar_t s_it_pIMPBeginScreenStrings[] = L"(max 8 personaggi)"; static const wchar_t s_it_pIMPFinishButtonText[] = L"Analisi"; static const wchar_t s_it_pIMPFinishStrings[] = L"Grazie, %ls"; //%ls is the name of the merc static const wchar_t s_it_pIMPVoicesStrings[] = L"Voce"; // the strings for imp voices screen // title for program static const wchar_t s_it_pPersTitleText[] = L"Manager del personale"; // paused game strings static const wchar_t *s_it_pPausedGameText[pPausedGameText_SIZE] = { L"Partita in pausa", L"Riprendi la partita (|P|a|u|s|a)", L"Metti in pausa la partita (|P|a|u|s|a)", }; static const wchar_t *s_it_pMessageStrings[pMessageStrings_SIZE] = { L"Vuoi uscire dalla partita?", L"OK", L"SÌ", L"NO", L"ANNULLA", L"RIASSUMI", L"MENTI", L"Nessuna descrizione", //Save slots that don't have a description. L"Partita salvata.", L"Giorno", L"Mercenari", L"Slot vuoto", //An empty save game slot L"ppm", //Abbreviation for Rounds per minute -- the potential # of bullets fired in a minute. L"dm", //Abbreviation for minute. L"m", //One character abbreviation for meter (metric distance measurement unit). L"colpi", //Abbreviation for rounds (# of bullets) L"kg", //Abbreviation for kilogram (metric weight measurement unit) L"lb", //Abbreviation for pounds (Imperial weight measurement unit) L"Home Page", //Home as in homepage on the internet. L"USD", //Abbreviation to US dollars L"n/a", //Lowercase acronym for not applicable. L"In corso", //Meanwhile L"%ls si trova ora nel settore %ls%ls", //Name/Squad has arrived in sector A9. Order must not change without notifying //SirTech L"Versione", L"Slot di salvataggio rapido vuoto", L"Questo slot è riservato ai salvataggi rapidi fatti dalle schermate tattiche e dalla mappa utilizzando ALT+S.", L"Aperto", L"Chiuso", L"Lo spazio su disco si sta esaurendo. Avete liberi solo %ls MB e Jagged Alliance 2 ne richiede %ls.", L"%ls ha preso %ls.", //'Merc name' has caught 'item' -- let SirTech know if name comes after item. L"%ls ha assunto della droga.", //'Merc name' has taken the drug L"%ls non ha alcuna abilità medica",//'Merc name' has no medical skill. //CDRom errors (such as ejecting CD while attempting to read the CD) L"L'integrità del gioco è stata compromessa.", L"ERRORE: CD-ROM non valido", //When firing heavier weapons in close quarters, you may not have enough room to do so. L"Non c'è spazio per sparare da qui.", //Can't change stance due to objects in the way... L"Non potete cambiare posizione questa volta.", //Simple text indications that appear in the game, when the merc can do one of these things. L"Fai cadere", L"Getta", L"Passa", L"%ls è passato a %ls.", //"Item" passed to "merc". Please try to keep the item %ls before the merc %ls, //otherwise, must notify SirTech. L"Nessun spazio per passare %ls a %ls.", //pass "item" to "merc". Same instructions as above. //A list of attachments appear after the items. Ex: Kevlar vest (Ceramic Plate 'Attached)' L" Compreso)", //Cheat modes L"Raggiunto il livello Cheat UNO", L"Raggiunto il livello Cheat DUE", //Toggling various stealth modes L"Squadra in modalità furtiva.", L"Squadra non in modalità furtiva.", L"%ls in modalità furtiva.", L"%ls non in modalità furtiva.", //Wireframes are shown through buildings to reveal doors and windows that can't otherwise be seen in //an isometric engine. You can toggle this mode freely in the game. L"Strutture visibili", L"Strutture nascoste", //These are used in the cheat modes for changing levels in the game. Going from a basement level to //an upper level, etc. L"Non potete passare al livello superiore...", L"Non esiste nessun livello inferiore...", L"Entra nel seminterrato %d...", L"Abbandona il seminterrato...", L"di", // used in the shop keeper inteface to mark the ownership of the item eg Red's gun L"Modalità segui disattiva.", L"Modalità segui attiva.", L"Cursore 3D disattivo.", L"Cursore 3D attivo.", L"Squadra %d attiva.", L"Non potete permettervi di pagare a %ls un salario giornaliero di %ls", //first %ls is the mercs name, the seconds is a string containing the salary L"Salta", L"%ls non può andarsene da solo.", L"Un salvataggio è stato chiamato SaveGame99.sav. Se necessario, rinominatelo da SaveGame01 a SaveGame10 e così potrete accedervi nella schermata di caricamento.", L"%ls ha bevuto del %ls", L"Un pacco è arivato a Drassen.", L"%ls dovrebbe arrivare al punto designato di partenza (settore %ls) nel giorno %d, approssimativamente alle ore %ls.", //first %ls is mercs name, next is the sector location and name where they will be arriving in, lastely is the day an the time of arrival L"Registro aggiornato.", }; static const wchar_t *s_it_ItemPickupHelpPopup[ItemPickupHelpPopup_SIZE] = { L"OK", L"Scorrimento su", L"Seleziona tutto", L"Scorrimento giù", L"Annulla", }; static const wchar_t *s_it_pDoctorWarningString[pDoctorWarningString_SIZE] = { L"%ls non è abbstanza vicina per poter esser riparata.", L"I vostri medici non sono riusciti a bendare completamente tutti.", }; static const wchar_t *s_it_pMilitiaButtonsHelpText[pMilitiaButtonsHelpText_SIZE] = { L"Raccogli (Clicca di destro)/lascia (Clicca di sinistro) le truppe verdi", // button help text informing player they can pick up or drop militia with this button L"Raccogli (Clicca di destro)/lascia (Clicca di sinistro) le truppe regolari", L"Raccogli (Clicca di destro)/lascia (Clicca di sinistro) le truppe veterane", L"Distribuisci equamente i soldati disponibili tra i vari settori", }; // to inform the player to hire some mercs to get things going static const wchar_t s_it_pMapScreenJustStartedHelpText[] = L"Andate all'A.I.M. e arruolate alcuni mercenari (*Hint* è nel Laptop)"; static const wchar_t s_it_pAntiHackerString[] = L"Errore. File mancanti o corrotti. Il gioco verrà completato ora."; static const wchar_t *s_it_gzLaptopHelpText[gzLaptopHelpText_SIZE] = { //Buttons: L"Visualizza E-mail", L"Siti web", L"Visualizza file e gli attach delle E-mail", L"Legge il registro degli eventi", L"Visualizza le informazioni inerenti la squadra", L"Visualizza la situazione finanziaria e la storia", L"Chiude laptop", //Bottom task bar icons (if they exist): L"Avete nuove E-mail", L"Avete nuovi file", //Bookmarks: L"Associazione Internazionale Mercenari", L"Ordinativi di armi online dal sito di Bobby Ray", L"Istituto del Profilo del Mercenario", L"Centro più economico di reclutamento", L"Impresa di pompe funebri McGillicutty", L"Servizio Fioristi Riuniti", L"Contratti assicurativi per agenti A.I.M.", }; static const wchar_t s_it_gzHelpScreenText[] = L"Esci dalla schermata di aiuto"; static const wchar_t *s_it_gzNonPersistantPBIText[gzNonPersistantPBIText_SIZE] = { L"È in corso una battaglia. Potete solo ritirarvi dalla schermata delle tattiche.", L"|Entra nel settore per continuare l'attuale battaglia in corso.", L"|Automaticamente decide l'esito della battaglia in corso.", L"Non potete decidere l'esito della battaglia in corso automaticamente, se siete voi ad attaccare.", L"Non potete decidere l'esito della battaglia in corso automaticamente, se subite un'imboscata.", L"Non potete decidere l'esito della battaglia in corso automaticamente, se state combattendo contro le creature nelle miniere.", L"Non potete decidere l'esito della battaglia in corso automaticamente, se ci sono civili nemici.", L"Non potete decidere l'esito della battaglia in corso automaticamente, se ci sono dei Bloodcat.", L"BATTAGLIA IN CORSO", L"Non potete ritirarvi ora.", }; static const wchar_t *s_it_gzMiscString[gzMiscString_SIZE] = { L"I vostri soldati continuano a combattere senza l'aiuto dei vostri mercenari...", L"Il veicolo non ha più bisogno di carburante.", L"La tanica della benzina è piena %d%%.", L"L'esercito di Deidrannaha riguadagnato il controllo completo su %ls.", L"Avete perso una stazione di rifornimento.", }; static const wchar_t s_it_gzIntroScreen[] = L"Video introduttivo non trovato"; // These strings are combined with a merc name, a volume string (from pNoiseVolStr), // and a direction (either "above", "below", or a string from pDirectionStr) to // report a noise. // e.g. "Sidney hears a loud sound of MOVEMENT coming from the SOUTH." static const wchar_t *s_it_pNewNoiseStr[pNewNoiseStr_SIZE] = { L"%ls sente un %ls rumore proveniente da %ls.", L"%ls sente un %ls rumore di MOVIMENTO proveniente da %ls.", L"%ls sente uno %ls SCRICCHIOLIO proveniente da %ls.", L"%ls sente un %ls TONFO NELL'ACQUA proveniente da %ls.", L"%ls sente un %ls URTO proveniente da %ls.", L"%ls sente una %ls ESPLOSIONE verso %ls.", L"%ls sente un %ls URLO verso %ls.", L"%ls sente un %ls IMPATTO verso %ls.", L"%ls sente un %ls IMPATTO a %ls.", L"%ls sente un %ls SCHIANTO proveniente da %ls.", L"%ls sente un %ls FRASTUONO proveniente da %ls.", }; static const wchar_t *s_it_wMapScreenSortButtonHelpText[wMapScreenSortButtonHelpText_SIZE] = { L"Nome (|F|1)", L"Assegnato (|F|2)", L"Tipo di riposo (|F|3)", L"Postazione (|F|4)", L"Destinazione (|F|5)", L"Durata dell'incarico (|F|6)", }; static const wchar_t *s_it_BrokenLinkText[BrokenLinkText_SIZE] = { L"Errore 404", L"Luogo non trovato.", }; static const wchar_t *s_it_gzBobbyRShipmentText[gzBobbyRShipmentText_SIZE] = { L"Spedizioni recenti", L"Ordine #", L"Numero di oggetti", L"Ordinato per", }; static const wchar_t *s_it_gzCreditNames[gzCreditNames_SIZE]= { L"Chris Camfield", L"Shaun Lyng", L"Kris Märnes", L"Ian Currie", L"Linda Currie", L"Eric \"WTF\" Cheng", L"Lynn Holowka", L"Norman \"NRG\" Olsen", L"George Brooks", L"Andrew Stacey", L"Scot Loving", L"Andrew \"Big Cheese\" Emmons", L"Dave \"The Feral\" French", L"Alex Meduna", L"Joey \"Joeker\" Whelan", }; static const wchar_t *s_it_gzCreditNameTitle[gzCreditNameTitle_SIZE]= { L"Programmatore del gioco", // Chris Camfield L"Co-designer / Autore", // Shaun Lyng L"Programmatore sistemi strategici & Editor", //Kris Marnes L"Produttore / Co-designer", // Ian Currie L"Co-designer / Designer della mappa", // Linda Currie L"Grafico", // Eric \"WTF\" Cheng L"Coordinatore beta, supporto", // Lynn Holowka L"Grafico straordinario", // Norman \"NRG\" Olsen L"Guru dell'audio", // George Brooks L"Designer delle schermate / Grafico", // Andrew Stacey L"Capo grafico / Animatore", // Scot Loving L"Capo programmatore", // Andrew \"Big Cheese Doddle\" Emmons L"Programmatore", // Dave French L"Programmatore sistemi & bilancio di gioco", // Alex Meduna L"Grafico dei ritratti", // Joey \"Joeker\" Whelan", }; static const wchar_t *s_it_gzCreditNameFunny[gzCreditNameFunny_SIZE]= { L"", // Chris Camfield L"(deve ancora esercitarsi con la punteggiatura)", // Shaun Lyng L"(\"Fatto. Devo solo perfezionarmi\")", //Kris \"The Cow Rape Man\" Marnes L"(sta diventando troppo vecchio per questo)", // Ian Currie L"(sta lavorando a Wizardry 8)", // Linda Currie L"(obbligato a occuparsi anche del CQ)", // Eric \"WTF\" Cheng L"(ci ha lasciato per CFSA...)", // Lynn Holowka L"", // Norman \"NRG\" Olsen L"", // George Brooks L"(Testa matta e amante del jazz)", // Andrew Stacey L"(il suo nome vero è Robert)", // Scot Loving L"(l'unica persona responsabile)", // Andrew \"Big Cheese Doddle\" Emmons L"(può ora tornare al motocross)", // Dave French L"(rubato da Wizardry 8)", // Alex Meduna L"", // Joey \"Joeker\" Whelan", }; static const wchar_t *s_it_sRepairsDoneString[sRepairsDoneString_SIZE] = { L"%ls ha finito di riparare gli oggetti", L"%ls ha finito di riparare le armi e i giubbotti antiproiettile di tutti", L"%ls ha finito di riparare gli oggetti dell'equipaggiamento di tutti", L"%ls ha finito di riparare gli oggetti trasportati di tutti", }; static const wchar_t *s_it_zGioDifConfirmText[zGioDifConfirmText_SIZE]= { //L"You have chosen NOVICE mode. This setting is appropriate for those new to Jagged Alliance, those new to strategy games in general, or those wishing shorter battles in the game. Your choice will affect things throughout the entire course of the game, so choose wisely. Are you sure you want to play in Novice mode?", L"Avete selezionato la modalità PRINCIPIANTE. Questo scenario è adatto a chi gioca per la prima volta a Jagged Alliance, a chi prova a giocare per la prima volta in generale o a chi desidera combattere battaglie più brevi nel gioco. La vostra decisione influirà sull'intero corso della partita; scegliete, quindi, con attenzione. Siete sicuri di voler giocare nella modalità PRINCIPIANTE?", //L"You have chosen EXPERIENCED mode. This setting is suitable for those already familiar with Jagged Alliance or similar games. Your choice will affect things throughout the entire course of the game, so choose wisely. Are you sure you want to play in Experienced mode?", L"Avete selezionato la modalità ESPERTO. Questo scenario è adatto a chi ha già una certa dimestichezza con Jagged Alliance o con giochi simili. La vostra decisione influirà sull'intero corso della partita; scegliete, quindi, con attenzione. Siete sicuri di voler giocare nella modalità ESPERTO?", //L"You have chosen EXPERT mode. We warned you. Don't blame us if you get shipped back in a body bag. Your choice will affect things throughout the entire course of the game, so choose wisely. Are you sure you want to play in Expert mode?", L"Avete selezionato la modalità PROFESSIONISTA. Siete avvertiti. Non malediteci, se vi ritroverete a brandelli. La vostra decisione influirà sull'intero corso della partita; scegliete, quindi, con attenzione. Siete sicuri di voler giocare nella modalità PROFESSIONISTA?", }; static const wchar_t *s_it_gzLateLocalizedString[gzLateLocalizedString_SIZE] = { //1-5 L"Il robot non può lasciare questo settore, se nessuno sta usando il controller.", //This message comes up if you have pending bombs waiting to explode in tactical. L"Non potete comprimere il tempo ora. Aspettate le esplosioni!", //'Name' refuses to move. L"%ls si rifiuta di muoversi.", //%ls a merc name L"%ls non ha abbastanza energia per cambiare posizione.", //A message that pops up when a vehicle runs out of gas. L"Il %ls ha esaurito la benzina e ora è rimasto a piedi a %c%d.", //6-10 // the following two strings are combined with the pNewNoise[] strings above to report noises // heard above or below the merc L"sopra", L"sotto", //The following strings are used in autoresolve for autobandaging related feedback. L"Nessuno dei vostri mercenari non sa praticare il pronto soccorso.", L"Non ci sono supporti medici per bendare.", L"Non ci sono stati supporti medici sufficienti per bendare tutti.", L"Nessuno dei vostri mercenari ha bisogno di fasciature.", L"Fascia i mercenari automaticamento.", L"Tutti i vostri mercenari sono stati bendati.", //14 L"Arulco", L"(tetto)", L"Salute: %d/%d", //In autoresolve if there were 5 mercs fighting 8 enemies the text would be "5 vs. 8" //"vs." is the abbreviation of versus. L"%d contro %d", L"Il %ls è pieno!", //(ex "The ice cream truck is full") L"%ls non ha bisogno immediatamente di pronto soccorso o di fasciature, quanto piuttosto di cure mediche più serie e/o riposo.", //20 //Happens when you get shot in the legs, and you fall down. L"%ls è stato colpito alla gamba e collassa!", //Name can't speak right now. L"%ls non può parlare ora.", //22-24 plural versions L"%d l'esercito verde è stato promosso a veterano.", L"%d l'esercito verde è stato promosso a regolare.", L"%d l'esercito regolare è stato promosso a veterano.", //25 L"Interruttore", //26 //Name has gone psycho -- when the game forces the player into burstmode (certain unstable characters) L"%ls è impazzito!", //27-28 //Messages why a player can't time compress. L"Non è al momento sicuro comprimere il tempo visto che avete dei mercenari nel settore %ls.", L"Non è al momento sicuro comprimere il tempo quando i mercenari sono nelle miniere infestate dalle creature.", //29-31 singular versions L"1 esercito verde è stato promosso a veterano.", L"1 esercito verde è stato promosso a regolare.", L"1 eserciro regolare è stato promosso a veterano.", //32-34 L"%ls non dice nulla.", L"Andate in superficie?", L"(Squadra %d)", //35 //Ex: "Red has repaired Scope's MP5K". Careful to maintain the proper order (Red before Scope, Scope before MP5K) L"%ls ha riparato %ls's %ls", //36 L"BLOODCAT", //37-38 "Name trips and falls" L"%ls trips and falls", L"Questo oggetto non può essere raccolto qui.", //39 L"Nessuno dei vostri rimanenti mercenari è in grado di combattere. L'esercito combatterà contro le creature da solo.", //40-43 //%ls is the name of merc. L"%ls è rimasto sprovvisto di kit medici!", L"%ls non è in grado di curare nessuno!", L"%ls è rimasto sprovvisto di forniture mediche!", L"%ls non è in grado di riparare niente!", //44-45 L"Tempo di riparazione", L"%ls non può vedere questa persona.", //46-48 L"L'estensore della canna dell'arma di %ls si è rotto!", L"Non più di %d allenatori di soldati sono ammessi in questo settore.", L"Siete sicuri?", //49-50 L"Compressione del tempo", L"La tanica della benzina del veicolo è ora piena.", //51-52 Fast help text in mapscreen. L"Continua la compressione del tempo (|S|p|a|z|i|o)", L"Ferma la compressione del tempo (|E|s|c)", //53-54 "Magic has unjammed the Glock 18" or "Magic has unjammed Raven's H&K G11" L"%ls ha sbloccata il %ls", L"%ls ha sbloccato il %ls di %ls", //55 L"Non potete comprimere il tempo mentre visualizzate l'inventario del settore.", //56 //Displayed with the version information when cheats are enabled. L"Attuale/Massimo Progresso: %d%%/%d%%", //57 L"Accompagnate John e Mary?", L"Interruttore attivato.", }; static const wchar_t s_it_str_ceramic_plates_smashed[] = L"%ls's ceramic plates have been smashed!"; // TODO translate static const wchar_t s_it_str_arrival_rerouted[] = L"Arrival of new recruits is being rerouted to sector %ls, as scheduled drop-off point of sector %ls is enemy occupied."; // TODO translate static const wchar_t s_it_str_stat_health[] = L"Salute"; static const wchar_t s_it_str_stat_agility[] = L"Agilità"; static const wchar_t s_it_str_stat_dexterity[] = L"Destrezza"; static const wchar_t s_it_str_stat_strength[] = L"Forza"; static const wchar_t s_it_str_stat_leadership[] = L"Comando"; static const wchar_t s_it_str_stat_wisdom[] = L"Saggezza"; static const wchar_t s_it_str_stat_exp_level[] = L"Esperienza"; // Livello esperienza static const wchar_t s_it_str_stat_marksmanship[] = L"Mira"; static const wchar_t s_it_str_stat_mechanical[] = L"Meccanica"; static const wchar_t s_it_str_stat_explosive[] = L"Esplosivi"; static const wchar_t s_it_str_stat_medical[] = L"Pronto socc."; static const wchar_t *s_it_str_stat_list[str_stat_list_SIZE] = { s_it_str_stat_health, s_it_str_stat_agility, s_it_str_stat_dexterity, s_it_str_stat_strength, s_it_str_stat_leadership, s_it_str_stat_wisdom, s_it_str_stat_exp_level, s_it_str_stat_marksmanship, s_it_str_stat_mechanical, s_it_str_stat_explosive, s_it_str_stat_medical }; static const wchar_t *s_it_str_aim_sort_list[str_aim_sort_list_SIZE] = { s_it_str_aim_sort_price, s_it_str_aim_sort_experience, s_it_str_aim_sort_marksmanship, s_it_str_aim_sort_medical, s_it_str_aim_sort_explosives, s_it_str_aim_sort_mechanical, s_it_str_aim_sort_ascending, s_it_str_aim_sort_descending, }; extern const wchar_t *g_eng_zNewTacticalMessages[]; extern const wchar_t *g_eng_str_iron_man_mode_warning; extern const wchar_t *g_eng_str_dead_is_dead_mode_warning; extern const wchar_t *g_eng_str_dead_is_dead_mode_enter_name; static const wchar_t *s_it_gs_dead_is_dead_mode_tab_name[gs_dead_is_dead_mode_tab_name_SIZE] = { L"Normal", // Normal Tab L"DiD", // Dead is Dead Tab }; // Italian language resources. LanguageRes g_LanguageResItalian = { s_it_WeaponType, s_it_Message, s_it_TeamTurnString, s_it_pAssignMenuStrings, s_it_pTrainingStrings, s_it_pTrainingMenuStrings, s_it_pAttributeMenuStrings, s_it_pVehicleStrings, s_it_pShortAttributeStrings, s_it_pContractStrings, s_it_pAssignmentStrings, s_it_pConditionStrings, s_it_pTownNames, s_it_g_towns_locative, s_it_pPersonnelScreenStrings, s_it_pUpperLeftMapScreenStrings, s_it_pTacticalPopupButtonStrings, s_it_pSquadMenuStrings, s_it_pDoorTrapStrings, s_it_pLongAssignmentStrings, s_it_pMapScreenMouseRegionHelpText, s_it_pNoiseVolStr, s_it_pNoiseTypeStr, s_it_pDirectionStr, s_it_pRemoveMercStrings, s_it_sTimeStrings, s_it_pLandTypeStrings, s_it_pInvPanelTitleStrings, s_it_pPOWStrings, s_it_pMilitiaString, s_it_pMilitiaButtonString, s_it_pEpcMenuStrings, s_it_pRepairStrings, s_it_sPreStatBuildString, s_it_sStatGainStrings, s_it_pHelicopterEtaStrings, s_it_sMapLevelString, s_it_gsLoyalString, s_it_gsUndergroundString, s_it_gsTimeStrings, s_it_sFacilitiesStrings, s_it_pMapPopUpInventoryText, s_it_pwTownInfoStrings, s_it_pwMineStrings, s_it_pwMiscSectorStrings, s_it_pMapInventoryErrorString, s_it_pMapInventoryStrings, s_it_pMovementMenuStrings, s_it_pUpdateMercStrings, s_it_pMapScreenBorderButtonHelpText, s_it_pMapScreenBottomFastHelp, s_it_pMapScreenBottomText, s_it_pMercDeadString, s_it_pSenderNameList, s_it_pNewMailStrings, s_it_pDeleteMailStrings, s_it_pEmailHeaders, s_it_pEmailTitleText, s_it_pFinanceTitle, s_it_pFinanceSummary, s_it_pFinanceHeaders, s_it_pTransactionText, s_it_pMoralStrings, s_it_pSkyriderText, s_it_str_left_equipment, s_it_pMapScreenStatusStrings, s_it_pMapScreenPrevNextCharButtonHelpText, s_it_pEtaString, s_it_pShortVehicleStrings, s_it_pTrashItemText, s_it_pMapErrorString, s_it_pMapPlotStrings, s_it_pBullseyeStrings, s_it_pMiscMapScreenMouseRegionHelpText, s_it_str_he_leaves_where_drop_equipment, s_it_str_she_leaves_where_drop_equipment, s_it_str_he_leaves_drops_equipment, s_it_str_she_leaves_drops_equipment, s_it_pImpPopUpStrings, s_it_pImpButtonText, s_it_pExtraIMPStrings, s_it_pFilesTitle, s_it_pFilesSenderList, s_it_pHistoryLocations, s_it_pHistoryStrings, s_it_pHistoryHeaders, s_it_pHistoryTitle, s_it_pShowBookmarkString, s_it_pWebPagesTitles, s_it_pWebTitle, s_it_pPersonnelString, s_it_pErrorStrings, s_it_pDownloadString, s_it_pBookMarkStrings, s_it_pLaptopIcons, s_it_gsAtmStartButtonText, s_it_pPersonnelTeamStatsStrings, s_it_pPersonnelCurrentTeamStatsStrings, s_it_pPersonelTeamStrings, s_it_pPersonnelDepartedStateStrings, s_it_pMapHortIndex, s_it_pMapVertIndex, s_it_pMapDepthIndex, s_it_pLaptopTitles, s_it_pDayStrings, s_it_pMilitiaConfirmStrings, s_it_pDeliveryLocationStrings, s_it_pSkillAtZeroWarning, s_it_pIMPBeginScreenStrings, s_it_pIMPFinishButtonText, s_it_pIMPFinishStrings, s_it_pIMPVoicesStrings, s_it_pPersTitleText, s_it_pPausedGameText, s_it_zOptionsToggleText, s_it_zOptionsScreenHelpText, s_it_pDoctorWarningString, s_it_pMilitiaButtonsHelpText, s_it_pMapScreenJustStartedHelpText, s_it_pLandMarkInSectorString, s_it_gzMercSkillText, s_it_gzNonPersistantPBIText, s_it_gzMiscString, s_it_wMapScreenSortButtonHelpText, s_it_pNewNoiseStr, s_it_gzLateLocalizedString, s_it_pAntiHackerString, s_it_pMessageStrings, s_it_ItemPickupHelpPopup, s_it_TacticalStr, s_it_LargeTacticalStr, s_it_zDialogActions, s_it_zDealerStrings, s_it_zTalkMenuStrings, s_it_gzMoneyAmounts, s_it_gzProsLabel, s_it_gzConsLabel, s_it_gMoneyStatsDesc, s_it_gWeaponStatsDesc, s_it_sKeyDescriptionStrings, s_it_zHealthStr, s_it_zVehicleName, s_it_pExitingSectorHelpText, s_it_InsContractText, s_it_InsInfoText, s_it_MercAccountText, s_it_MercInfo, s_it_MercNoAccountText, s_it_MercHomePageText, s_it_sFuneralString, s_it_sFloristText, s_it_sOrderFormText, s_it_sFloristGalleryText, s_it_sFloristCards, s_it_BobbyROrderFormText, s_it_BobbyRText, s_it_str_bobbyr_guns_num_guns_that_use_ammo, s_it_BobbyRaysFrontText, s_it_AimSortText, s_it_str_aim_sort_price, s_it_str_aim_sort_experience, s_it_str_aim_sort_marksmanship, s_it_str_aim_sort_medical, s_it_str_aim_sort_explosives, s_it_str_aim_sort_mechanical, s_it_str_aim_sort_ascending, s_it_str_aim_sort_descending, s_it_AimPolicyText, s_it_AimMemberText, s_it_CharacterInfo, s_it_VideoConfercingText, s_it_AimPopUpText, s_it_AimLinkText, s_it_AimHistoryText, s_it_AimFiText, s_it_AimAlumniText, s_it_AimScreenText, s_it_AimBottomMenuText, s_it_zMarksMapScreenText, s_it_gpStrategicString, s_it_gpGameClockString, s_it_SKI_Text, s_it_SkiMessageBoxText, s_it_zSaveLoadText, s_it_zOptionsText, s_it_gzGIOScreenText, s_it_gzHelpScreenText, s_it_gzLaptopHelpText, s_it_gzMoneyWithdrawMessageText, s_it_gzCopyrightText, s_it_BrokenLinkText, s_it_gzBobbyRShipmentText, s_it_zGioDifConfirmText, s_it_gzCreditNames, s_it_gzCreditNameTitle, s_it_gzCreditNameFunny, s_it_pContractButtonString, s_it_gzIntroScreen, s_it_pUpdatePanelButtons, s_it_sRepairsDoneString, s_it_str_ceramic_plates_smashed, s_it_str_arrival_rerouted, s_it_str_stat_health, s_it_str_stat_agility, s_it_str_stat_dexterity, s_it_str_stat_strength, s_it_str_stat_leadership, s_it_str_stat_wisdom, s_it_str_stat_exp_level, s_it_str_stat_marksmanship, s_it_str_stat_mechanical, s_it_str_stat_explosive, s_it_str_stat_medical, s_it_str_stat_list, s_it_str_aim_sort_list, g_eng_zNewTacticalMessages, g_eng_str_iron_man_mode_warning, g_eng_str_dead_is_dead_mode_warning, g_eng_str_dead_is_dead_mode_enter_name, s_it_gs_dead_is_dead_mode_tab_name, }; #ifdef WITH_UNITTESTS #define ARR_SIZE(x) (sizeof(x)/sizeof(x[0])) TEST(WideStringEncodingTest, ItalianTextFile) { // This test checks that the wide string literals in this file are correctly // interpreted by the compiler. Visual Studio requires BOM (byte-order mark) // to correctly identify file encoding. Failed test means that the compiler // cannot correctly interpret the string literals. const wchar_t str[] = L"тест"; ASSERT_EQ(ARR_SIZE(str), 5u) << "Compiler cannot correctly interpret wide string literals"; EXPECT_EQ(str[0], 0x0442); EXPECT_EQ(str[1], 0x0435); EXPECT_EQ(str[2], 0x0441); EXPECT_EQ(str[3], 0x0442); EXPECT_EQ(str[4], 0x00); } #endif
32.929199
391
0.728368
[ "3d" ]
e4bee80a58bb24993550ddf9e1d92874d4b04a79
1,456
cpp
C++
returnbook.cpp
Kwanhooo/LibManagement
56f7719321159e869c361d86024b62cf8fcb44eb
[ "MIT" ]
null
null
null
returnbook.cpp
Kwanhooo/LibManagement
56f7719321159e869c361d86024b62cf8fcb44eb
[ "MIT" ]
null
null
null
returnbook.cpp
Kwanhooo/LibManagement
56f7719321159e869c361d86024b62cf8fcb44eb
[ "MIT" ]
null
null
null
#include "returnbook.h" #include "ui_returnbook.h" returnbook::returnbook(QWidget *parent) : QWidget(parent), ui(new Ui::returnbook) { ui->setupUi(this); connect(this->ui->listView,SIGNAL(clicked(QModelIndex)),this,SLOT(returnABook(QModelIndex))); } returnbook::~returnbook() { delete ui; } void returnbook::init(QString s,int n) { QStringListModel *listmodel = new QStringListModel(list); ui->listView->setModel(listmodel); name = s; if(n==0)ui->label->setText("Books borrowed by Xiao Li <b>"+s+"</b> :"); else ui->label->setText("Books in library: "); this->model = n; } void returnbook::returnABook(QModelIndex index) { if(model==0){ int x = index.row(); QMessageBox::StandardButton reply; reply = QMessageBox::information(NULL,"Confirm","Are you sure user <b>"+name+"</b> wants to return the Book <b>"+list.at(x)+"</b> ?",QMessageBox::Yes|QMessageBox::No); if(reply==QMessageBox::Yes){ list.erase(list.begin()+x); this->init(name,model); } } else{ int x = index.row(); QMessageBox::StandardButton reply; reply = QMessageBox::information(NULL,"Confirm","Are you sure user <b>"+name+"</b> wants to borrow the Book <b>"+list.at(x)+"</b> ?",QMessageBox::Yes|QMessageBox::No); if(reply==QMessageBox::Yes){ list.erase(list.begin()+x); this->init(name,model); } } }
29.714286
175
0.611951
[ "model" ]
e4c1f8bcfaad1b775d4f80a4b37c20ce32b8065b
1,142
cpp
C++
DP/Palindrome Partitioning with Minimum Cuts.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
1
2021-07-20T06:08:26.000Z
2021-07-20T06:08:26.000Z
DP/Palindrome Partitioning with Minimum Cuts.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
null
null
null
DP/Palindrome Partitioning with Minimum Cuts.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<string>> partition(string s) { int n = s.size(); int dp[n][n]; //gap method for (int g = 0; g < n; g++) { for (int i = 0, j = g; g < dp.size(); i++, j++) { if (g == 0) { dp[i][j] = true; } else if (g == 1) { dp[i][j] = s[i] == s[j]; } else { //bich wala part if (s[i] == s[j] and dp[i + 1][j - 1] == true) dp[i][j] = true; else dp[i][j] = false; } } } int store[n][n]; for (int g = 0; g < n; g++) { for (int i = 0, j = g; g < store.size(); i++, j++) { if (g == 0) { store[i][j] = 0; } else if (g == 1) { if (s[i] == s[j]) store[i][j] = 0; else store[i][j] = 1; //char baraber ni toh ek cut. } else { if (dp[i][j]) { store[i][j] = 0; } else { int mn = INT_MAX; for (int k = i; k < j; k++) { int left = store[i][k]; int right = store[k + 1][j]; if (left + right + 1 < mn) { mn = left + right + 1; } } store[i][j] = mn; } } } } return store[0][s.size() - 1]; } };
18.419355
53
0.376532
[ "vector" ]
e4cb8b3b0243d25cf1d7031d46db906f1a83ef1f
5,126
hpp
C++
include/ball_pushing_planner.hpp
ytlei/ballCollectorRobot
5ae64368fe92f7c050cbad908eee74bc2d44eaff
[ "MIT" ]
null
null
null
include/ball_pushing_planner.hpp
ytlei/ballCollectorRobot
5ae64368fe92f7c050cbad908eee74bc2d44eaff
[ "MIT" ]
null
null
null
include/ball_pushing_planner.hpp
ytlei/ballCollectorRobot
5ae64368fe92f7c050cbad908eee74bc2d44eaff
[ "MIT" ]
null
null
null
/** * @file * @author Yiting Lei <ytlei@umd.edu> * @brief push_planner node for planning paths for pushing targets header * @copyright BSD License * Copyright (c) 2017 Yiting Lei * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #ifndef BALL_PUSHING_PLANNER_H_ #define BALL_PUSHING_PLANNER_H_ #include "ros/ros.h" #include <vector> #include <sensor_msgs/LaserScan.h> #include <geometry_msgs/Point.h> #include "ball_collector_robot/Target.h" #include "ball_collector_robot/NewTarget.h" #include "ball_collector_robot/UpdateTarget.h" #include "ball_collector_robot/GetPushPlan.h" #include "ball_collector_robot/ClearAll.h" /** * Class for creating push plans for Targets to push them to the coordinates of the * configured jail */ class ballPushingPlanner { private: ros::NodeHandle n; // subscriber for Target push updates ros::Subscriber sub; // location of the Jail relative to the world frame geometry_msgs::Point corner; ros::ServiceServer addTargetService; ros::ServiceServer updateTargetService; ros::ServiceServer getPushPlanService; ros::ServiceServer clearAllService; // target list std::vector<ball_collector_robot::Target> targets; // plan list std::vector<ball_collector_robot::PushPlan> plans; // current target id int currentTargetId = 0; // offset from target to start from double offset = 0.0; // minimum distance from target double minimumDistance = 0.25; // internal methods /** * determines if a target centroid constitutes a new target or not * @param centroid of the suspected target * @return the id if this is an existing target or -1 if new */ int targetExists(geometry_msgs::Point centroid); /** * get the target with id if exists * @param id of the target to get */ ball_collector_robot::Target getTarget(int targetId); /** * creates a target using centroid provided * @param centroid of target * @return the constructed target */ ball_collector_robot::Target createTarget(geometry_msgs::Point centroid); /** * creates a push plan for the given target * @param the target to push * @return the constructed PushPlan for the target */ ball_collector_robot::PushPlan createPushPlan( ball_collector_robot::Target target); /** * calculates distance between two points * @param p1 point 1 * @param p2 point 2 * @return the euclidian distance between the two points */ double distance(geometry_msgs::Point p1, geometry_msgs::Point p2); /** * gets the push plan for target with given id, raise domain error if target not there * @param id of target * @return the push plan for target with id */ ball_collector_robot::PushPlan getPushPlanForTarget(int id); /** * sets the orientation for the quaternion */ void setOrientation(geometry_msgs::Quaternion &startOrientation, double zAngleDegrees); public: /** * Construct and initialize the push_planner node * @param nh the valid node handle for this node */ explicit ballPushingPlanner(ros::NodeHandle nh); /** * Destructor */ virtual ~ballPushingPlanner(); /** * Starts the node loop to listen for new targets to create plans for */ void spin(); /** * Service for adding a new target */ bool addTarget(ball_collector_robot::NewTargetRequest &req, ball_collector_robot::NewTargetResponse &resp); /** * Service for updating an existing target */ bool updateTarget(ball_collector_robot::UpdateTargetRequest &req, ball_collector_robot::UpdateTargetResponse &resp); /** * Service for getting a push plan, if any are available */ bool getPushPlan(ball_collector_robot::GetPushPlanRequest &req, ball_collector_robot::GetPushPlanResponse &resp); /** * Service for clearing all targets and plans */ bool clearAll(ball_collector_robot::ClearAllRequest &req, ball_collector_robot::ClearAllResponse &resp); }; #endif // BALL_PUSHING_PLANNER_H_
33.503268
87
0.752634
[ "vector" ]
e4d4b4d10cfd12f74fcebe58fb4b479f092c894e
4,831
cpp
C++
TestsParallel/test_t2d_me_mt_pipe_conference.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
null
null
null
TestsParallel/test_t2d_me_mt_pipe_conference.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
2
2020-10-19T02:03:11.000Z
2021-03-19T16:34:39.000Z
TestsParallel/test_t2d_me_mt_pipe_conference.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
1
2020-04-28T00:33:14.000Z
2020-04-28T00:33:14.000Z
#include "TestsParallel_pcp.h" #include "test_parallel_utils.h" #include "Model_T2D_CHM_mt.h" #include "Step_T2D_CHM_mt.h" #include "ModelData_T2D_CHM_mt.h" #include "TimeHistory_T2D_CHM_mt_complete.h" #include "TimeHistory_ConsoleProgressBar.h" #include "QtApp_Prep_T2D_CHM_mt.h" #include "test_simulations_omp.h" void test_t2d_chm_mt_pipe_conference(int argc, char** argv) { TriangleMesh tri_mesh; tri_mesh.load_mesh_from_hdf5("../../Asset/rect_pipe_conference_mesh.h5"); tri_mesh.init_search_grid(0.05, 0.05); ParticleGenerator2D<TriangleMesh> pcl_generator; pcl_generator.generate_pcls_in_grid_layout(Rect(-3.5, 3.5, -3.5, 0.0), 0.04, 0.04); pcl_generator.generate_pcls_in_grid_layout(Rect(-3.5, 3.5, -5.0, -3.5), 0.04, 0.04); pcl_generator.replace_with_pcls_in_grid_layout(Rect(-2.5, 2.5, -3.5, 0.0), 0.02, 0.02); pcl_generator.adjust_pcl_size_to_fit_elems(tri_mesh); Model_T2D_CHM_mt model; model.init_mesh(tri_mesh); model.init_search_grid(tri_mesh, 0.05, 0.05); tri_mesh.clear(); model.init_pcls(pcl_generator, 0.6, 2650.0, 1000.0, 1.0e7, 1.0e-12, 1.0e-3); pcl_generator.clear(); const size_t pcl_num = model.get_pcl_num(); MatModel::MaterialModel **mms = model.get_mat_models(); // mcc MatModel::ModifiedCamClay* mccs = model.add_ModifiedCamClay(pcl_num); double K = 1.0 - sin(23.5 / 180.0 * 3.14159165359); double ini_stress[6] = { -12025.0, -20000.0, -12025.0, 0.0, 0.0, 0.0 }; for (size_t p_id = 0; p_id < pcl_num; ++p_id) { //pcl.s11 = ini_stress[0]; //pcl.s22 = ini_stress[1]; //pcl.s12 = 0.0; MatModel::ModifiedCamClay& mcc = mccs[p_id]; mcc.set_param_NC(0.3, 0.044, 0.205, 23.5, 3.6677, ini_stress); mms[p_id] = &mcc; } model.init_rigid_circle(1.0e5, 1.0e3, 0.0, 0.5, 0.5); model.set_rigid_circle_velocity(0.0, -0.5, 0.0); IndexArray left_right_bc_pt_array(100); find_2d_nodes_on_x_line<Model_T2D_CHM_mt, Model_T2D_CHM_mt::Position>(model, left_right_bc_pt_array, -3.5); find_2d_nodes_on_x_line<Model_T2D_CHM_mt, Model_T2D_CHM_mt::Position>(model, left_right_bc_pt_array, 3.5, false); model.init_fixed_vx_s_bc(left_right_bc_pt_array.get_num(), left_right_bc_pt_array.get_mem()); model.init_fixed_vx_f_bc(left_right_bc_pt_array.get_num(), left_right_bc_pt_array.get_mem()); IndexArray bottom_bc_pt_array(100); find_2d_nodes_on_y_line<Model_T2D_CHM_mt, Model_T2D_CHM_mt::Position>(model, bottom_bc_pt_array, -5.0); model.init_fixed_vy_s_bc(bottom_bc_pt_array.get_num(), bottom_bc_pt_array.get_mem()); model.init_fixed_vy_f_bc(bottom_bc_pt_array.get_num(), bottom_bc_pt_array.get_mem()); //QtApp_Prep_T2D_CHM_mt md_disp(argc, argv); //md_disp.set_win_size(1200, 900); //md_disp.set_model(model); ////md_disp.set_pts_from_vx_s_bc(0.03); ////md_disp.set_pts_from_vx_f_bc(0.03); ////md_disp.set_pts_from_vy_s_bc(0.03); ////md_disp.set_pts_from_vy_f_bc(0.03); //// all ////md_disp.set_display_range(-3.6, 3.6, -5.1, 1.1); //// left ////md_disp.set_display_range(-3.8, -2.2, -1.0, 1.0); //// middle //md_disp.set_display_range(-1.6, 1.6, -0.9, 1.1); //// right ////md_disp.set_display_range(2.2, 3.8, -1.0, 1.0); //md_disp.start(); //return; ResultFile_hdf5 res_file_hdf5; res_file_hdf5.create("t2d_chm_mt_pipe_conference1.h5"); ModelData_T2D_CHM_mt md; md.output_model(model, res_file_hdf5); TimeHistory_T2D_CHM_mt_complete out("penetration"); out.set_res_file(res_file_hdf5); out.set_interval_num(100); out.set_output_init_state(); out.set_output_final_state(); TimeHistory_ConsoleProgressBar out_pb; out_pb.set_interval_num(5000); Step_T2D_CHM_mt step("step1"); step.set_model(model); step.set_step_time(1.0); //step.set_step_time(5.0e-4); step.set_dtime(2.0e-6); step.set_thread_num(7); step.add_time_history(out); step.add_time_history(out_pb); step.solve(); } #include "QtApp_Posp_T2D_CHM_mt.h" #include "test_model_view_omp.h" void test_t2d_chm_mt_pipe_conference_result(int argc, char** argv) { ResultFile_hdf5 rf; rf.open("t2d_chm_mt_pipe_conference1.h5"); QtApp_Posp_T2D_CHM_mt app(argc, argv, QtApp_Posp_T2D_CHM_mt::Animation); app.set_ani_time(5.0); app.set_win_size(1900, 950); //app.set_bg_color(1.0f, 1.0f, 1.0f); //app.set_char_color(0.0f, 0.0f, 0.0f); //app.set_display_range(-3.6, 3.6, -5.1, 0.6); app.set_display_range(-2.2, 2.2, -2.0, 0.6); // s22 //app.set_res_file(rf, "penetration", Hdf5Field::s22); //app.set_color_map_fld_range(-10000.0, 10000.0); // pore pressure //app.set_res_file(rf, "penetration", Hdf5Field::p); //app.set_color_map_fld_range(0, 30000.0); // mises strain app.set_res_file(rf, "penetration", Hdf5Field::mises_strain_2d); app.set_color_map_fld_range(0.0, 0.4); app.set_color_map_geometry(1.0f, 0.45f, 0.5f); //app.set_mono_color_pcl(); //app.set_png_name("t2d_chm_mt_pipe_conference1"); //app.set_gif_name("t2d_chm_mt_pipe_conference1"); app.start(); }
35.785185
114
0.745601
[ "model" ]
e4d609faac5dacf00cd347aca20e8798e7273f95
12,049
hpp
C++
src/perception/segmentation/euclidean_cluster/include/euclidean_cluster/euclidean_cluster.hpp
goodloop/autoware_auto_mirror
9ffc6c658b7ae5674bde8ee2c882f3dbb3fa1235
[ "Apache-2.0" ]
1
2021-07-29T01:28:10.000Z
2021-07-29T01:28:10.000Z
src/perception/segmentation/euclidean_cluster/include/euclidean_cluster/euclidean_cluster.hpp
goodloop/autoware_auto_mirror
9ffc6c658b7ae5674bde8ee2c882f3dbb3fa1235
[ "Apache-2.0" ]
null
null
null
src/perception/segmentation/euclidean_cluster/include/euclidean_cluster/euclidean_cluster.hpp
goodloop/autoware_auto_mirror
9ffc6c658b7ae5674bde8ee2c882f3dbb3fa1235
[ "Apache-2.0" ]
1
2021-12-09T15:44:10.000Z
2021-12-09T15:44:10.000Z
// Copyright 2019-2021 the Autoware Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. /// \file /// \brief This file defines the euclidean cluster algorithm for object detection #ifndef EUCLIDEAN_CLUSTER__EUCLIDEAN_CLUSTER_HPP_ #define EUCLIDEAN_CLUSTER__EUCLIDEAN_CLUSTER_HPP_ #include <autoware_auto_perception_msgs/msg/bounding_box_array.hpp> #include <autoware_auto_perception_msgs/msg/detected_objects.hpp> #include <autoware_auto_perception_msgs/msg/point_clusters.hpp> #include <geometry/spatial_hash.hpp> #include <euclidean_cluster/visibility_control.hpp> #include <common/types.hpp> #include <string> #include <vector> #include <utility> namespace autoware { namespace perception { namespace segmentation { /// \brief Supporting classes for euclidean clustering, an object detection algorithm namespace euclidean_cluster { using autoware::common::types::float32_t; using autoware::common::types::bool8_t; /// \brief Simple point struct for memory mapping to and from PointCloud2 type struct PointXYZI { float32_t x = 0.0f; float32_t y = 0.0f; float32_t z = 0.0f; float32_t intensity = 0.0f; }; // struct PointXYZI /// \brief Helper point for which euclidean distance is computed only once class EUCLIDEAN_CLUSTER_PUBLIC PointXYZIR { public: PointXYZIR() = default; /// \brief Conversion constructor /// \param[in] pt The point to convert explicit PointXYZIR(const common::types::PointXYZIF & pt); /// \brief Conversion constructor /// \param[in] pt The point to convert explicit PointXYZIR(const PointXYZI & pt); /// \brief Constructor /// \param[in] x The x position of the point /// \param[in] y The y position of the point /// \param[in] z The z position of the point /// \param[in] intensity The intensity value of the point PointXYZIR(const float32_t x, const float32_t y, const float32_t z, const float32_t intensity); /// \brief Getter for radius /// \return The projected radial distance float32_t get_r() const; /// \brief Get core point /// \return Reference to internally stored point const PointXYZI & get_point() const; /// \brief Explicit conversion operator from PointXYZIR to msg type PointXYZIF /// \return a PointXYZIF type explicit operator autoware_auto_perception_msgs::msg::PointXYZIF() const; private: // This could instead be a pointer; I'm pretty sure ownership would work out, but I'm // uncomfortable doing it that way (12 vs 20 bytes) PointXYZI m_point; float32_t m_r_xy; }; // class PointXYZIR using HashConfig = autoware::common::geometry::spatial_hash::Config2d; using Hash = autoware::common::geometry::spatial_hash::SpatialHash2d<PointXYZIR>; using Clusters = autoware_auto_perception_msgs::msg::PointClusters; /// \brief Configuration class for euclidean cluster /// In the future this can become a base class with subclasses defining different /// threshold functions. This configuration's threshold function currently assumes isotropy, and /// minor details in the clustering implementation also assume this property. class EUCLIDEAN_CLUSTER_PUBLIC Config { public: /// \brief Constructor /// \param[in] frame_id The frame id for which all clusters are initialized with /// \param[in] min_cluster_size The number of points that must be in a cluster before it is not /// considered noise /// \param[in] max_num_clusters The maximum preallocated number of clusters in a scene /// \param[in] min_cluster_threshold_m The minimum connectivity threshold when r = 0 /// \param[in] max_cluster_threshold_m The maximum connectivity threshold when /// r = cluster_threshold_saturation_distance /// \param[in] cluster_threshold_saturation_distance_m The distance at which the cluster threshold /// is clamped to the maximum value Config( const std::string & frame_id, const std::size_t min_cluster_size, const std::size_t max_num_clusters, const float32_t min_cluster_threshold_m, const float32_t max_cluster_threshold_m, const float32_t cluster_threshold_saturation_distance_m); /// \brief Gets minimum number of points needed for a cluster to not be considered noise /// \return Minimum cluster size std::size_t min_cluster_size() const; /// \brief Gets maximum preallocated number of clusters /// \return Maximum number of clusters std::size_t max_num_clusters() const; /// \brief Compute the connectivity threshold for a given point /// \param[in] pt The point whose connectivity criterion will be calculated /// \return The connectivity threshold, in meters float32_t threshold(const PointXYZIR & pt) const; /// \brief Compute the connectivity threshold for a given point /// \param[in] r The projected radial distance of the point /// \return The connectivity threshold, in meters float32_t threshold(const float32_t r) const; /// \brief Get frame id /// \return The frame id const std::string & frame_id() const; /// \brief Check the external clusters size with the EuclideanClusters configuration /// \param[in] clusters The clusters object /// \return True if config is valid bool match_clusters_size(const Clusters & clusters) const; private: const std::string m_frame_id; const std::size_t m_min_cluster_size; const std::size_t m_max_num_clusters; const float32_t m_min_thresh_m; const float32_t m_max_distance_m; const float32_t m_thresh_rate; }; // class Config /// \brief implementation of euclidean clustering for point cloud segmentation /// This clas implicitly projects points onto a 2D (x-y) plane, and segments /// according to euclidean distance. This can be thought of as a graph-based /// approach where points are vertices and edges are defined by euclidean distance /// The input to this should be nonground points pased through a voxel grid. class EUCLIDEAN_CLUSTER_PUBLIC EuclideanCluster { public: enum class Error : uint8_t { NONE = 0U, TOO_MANY_CLUSTERS }; // enum class Error /// \brief Constructor /// \param[in] cfg The configuration of the clustering algorithm, contains threshold function /// \param[in] hash_cfg The configuration of the underlying spatial hash, controls the maximum /// number of points in a scene EuclideanCluster(const Config & cfg, const HashConfig & hash_cfg); /// \brief Insert an individual point /// \param[in] pt The point to insert /// \throw std::length_error If the underlying spatial hash is full void insert(const PointXYZIR & pt); /// \brief Multi-insert /// \param[in] begin Iterator pointing to to the first point to insert /// \param[in] end Iterator pointing to one past the last point to insert /// \throw std::length_error If the underlying spatial hash is full /// \tparam IT The type of the iterator template<typename IT> void insert(const IT begin, const IT end) { if ((static_cast<std::size_t>(std::distance(begin, end)) + m_hash.size()) > m_hash.capacity()) { throw std::length_error{"EuclideanCluster: Multi insert would overrun capacity"}; } for (auto it = begin; it != end; ++it) { insert(PointXYZIR{*it}); } } /// \brief Compute the clusters from the inserted points, where the final clusters object lives in /// another scope. /// \param[inout] clusters The clusters object void cluster(Clusters & clusters); /// \brief Gets last error, intended to be used with clustering with internal cluster result /// This is a separate function rather than using an exception because the main error mode is /// exceeding preallocated cluster capacity. However, throwing an exception would throw away /// perfectly valid information that is still usable in an error state. Error get_error() const; /// \brief Gets the internal configuration class, for use when it was inline generated /// \return Internal configuration class const Config & get_config() const; /// \brief Throw the stored error during clustering process /// \throw std::runtime_error If the maximum number of clusters may have been exceeded void throw_stored_error() const; private: /// \brief Internal struct instead of pair since I can guarantee some memory stuff struct PointXY { float32_t x = 0.0f; float32_t y = 0.0f; }; // struct PointXYZ /// \brief Do the clustering process, with no error checking EUCLIDEAN_CLUSTER_LOCAL void cluster_impl(Clusters & clusters); /// \brief Compute the next cluster, seeded by the given point, and grown using the remaining /// points still contained in the hash EUCLIDEAN_CLUSTER_LOCAL void cluster(Clusters & clusters, const Hash::IT it); /// \brief Add all near neighbors of a point to a given cluster EUCLIDEAN_CLUSTER_LOCAL void add_neighbors_to_last_cluster( Clusters & clusters, const PointXY pt); /// \brief Adds a point to the last cluster, internal version since no error checking is needed EUCLIDEAN_CLUSTER_LOCAL static void add_point_to_last_cluster( Clusters & clusters, const PointXYZIR & pt); /// \brief Get a specified point from the cluster EUCLIDEAN_CLUSTER_LOCAL static PointXY get_point_from_last_cluster( const Clusters & clusters, const std::size_t cls_pt_idx); EUCLIDEAN_CLUSTER_LOCAL static std::size_t last_cluster_size(const Clusters & clusters); const Config m_config; Hash m_hash; Error m_last_error; std::vector<bool8_t> m_seen; }; // class EuclideanCluster /// \brief Common euclidean cluster functions not intended for external use namespace details { using BoundingBox = autoware_auto_perception_msgs::msg::BoundingBox; using BoundingBoxArray = autoware_auto_perception_msgs::msg::BoundingBoxArray; using DetectedObjects = autoware_auto_perception_msgs::msg::DetectedObjects; enum class BboxMethod { Eigenbox, LFit, }; /// \brief Compute bounding boxes from clusters /// \param[in] method Whether to use the eigenboxes or L-Fit algorithm. /// \param[in] compute_height Compute the height of the bounding box as well. /// \param[inout] clusters A set of clusters for which to compute the bounding boxes. Individual /// clusters may get their points shuffled. /// \returns Bounding boxes EUCLIDEAN_CLUSTER_PUBLIC BoundingBoxArray compute_bounding_boxes( Clusters & clusters, const BboxMethod method, const bool compute_height); /// \brief Convert this bounding box to a DetectedObjects message /// \param[in] boxes A bounding box array /// \returns A DetectedObjects message with the bounding boxes inside EUCLIDEAN_CLUSTER_PUBLIC DetectedObjects convert_to_detected_objects(const BoundingBoxArray & boxes); } // namespace details } // namespace euclidean_cluster } // namespace segmentation } // namespace perception namespace common { namespace geometry { namespace point_adapter { template<> inline EUCLIDEAN_CLUSTER_PUBLIC auto x_( const perception::segmentation::euclidean_cluster::PointXYZIR & pt) { return pt.get_point().x; } template<> inline EUCLIDEAN_CLUSTER_PUBLIC auto y_( const perception::segmentation::euclidean_cluster::PointXYZIR & pt) { return pt.get_point().y; } template<> inline EUCLIDEAN_CLUSTER_PUBLIC auto z_( const perception::segmentation::euclidean_cluster::PointXYZIR & pt) { return pt.get_point().z; } } // namespace point_adapter } // namespace geometry } // namespace common } // namespace autoware #endif // EUCLIDEAN_CLUSTER__EUCLIDEAN_CLUSTER_HPP_
41.548276
100
0.746701
[ "geometry", "object", "vector" ]
e4d82f4c63949e12c8e4c6a9f929729423082958
9,142
cpp
C++
src/test/key_tests.cpp
CoinGame/NuShadowTestnet
32ad6b407bea6490513790d15c2a2ed83f5917f3
[ "MIT" ]
2
2018-01-22T13:54:42.000Z
2018-01-22T13:54:46.000Z
src/test/key_tests.cpp
CoinGame/NuShadowTestnet
32ad6b407bea6490513790d15c2a2ed83f5917f3
[ "MIT" ]
null
null
null
src/test/key_tests.cpp
CoinGame/NuShadowTestnet
32ad6b407bea6490513790d15c2a2ed83f5917f3
[ "MIT" ]
1
2018-01-22T13:54:39.000Z
2018-01-22T13:54:39.000Z
#include <boost/test/unit_test.hpp> #include <string> #include <vector> #include "key.h" #include "base58.h" #include "uint256.h" #include "util.h" using namespace std; // Mixed style keys static const string strDefaultSecret1 ("7QRR3XwvHW963ERsAQQi2JScqv2PgNDcrwMXwAcmJ3g9byEbRqN"); static const string strDefaultSecret2 ("7RexmM8ERicLWvtNVZE3aQnViZLr2gqq1dShPDcSdmgf3MjNx64"); static const string strDefaultSecret1C ("VGNm8BbQBqchErGkQWKe4jz5Cu396kehHQudY5SrWEonyL9d9dhs"); static const string strDefaultSecret2C ("VMpZ8jpvG6ey96qjs3EaNTyokRkbQSrWumrRF4fS9JE2uPQ8a1xR"); // NuShares keys static const string strSSecret1 ("5zn9do6aVdjaNn2F64LjxqG6P8AENnpqp6P1gsj7YXPrstEgQxL"); static const string strSSecret2 ("621hMcGtdrCprUUkRDA5WwbyFmUgj7T3xnUB8vintFQNKHqSpda"); static const string strSSecret1C ("P42H7QTcqP8vK7iVBKk8dS1ckebk3BGASrkA2ztst99u9Rn9aEhP"); static const string strSSecret2C ("P9U57xh8ueBCDNHUdrf4wA1MJBKCLsTz5Dgwjz7TXCa95V2dt5c1"); // NuBits keys static const string strBSecret1 ("62itp2YcM4QoWbbwzdxjv9rsJEmx2VfibjT7w2R1YBQFNWuRPef"); static const string strBSecret2 ("63xSXqivVGt3zJ4TKnn5UGCkAt6QNpHvkRYHP5QgsuQkov3sKB2"); static const string strBSecret1C ("PCbugZpX1Y44HdjFjQ92Rc7715oPsbXtcJNHbTEyNcucRkyvVT4h"); static const string strBSecret2C ("PJ3hh8435o6LBtJFBw3xjL6qYcWrBHjiEfK5JSTZ1gKrMpGGxHs2"); // The resulting NSR addresses for the above keys static const CBitcoinAddress addrS1 ("SkYqsCFMoSkgZh5gqzses71yRWZsvBTYTA"); static const CBitcoinAddress addrS2 ("SbNy74rQ5yGkWw6LiagR8Nnch3TNyMGvd4"); static const CBitcoinAddress addrS1C("Sj6Jtef2gkNXBW5MqxS8qUmsWJeewfKuan"); static const CBitcoinAddress addrS2C("SYij48kVjZiiWawysqsnpF8FL9gaKpPNf9"); static const string strAddressBad("1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF"); #ifdef KEY_TESTS_DUMPINFO void dumpKeyInfo(uint256 privkey) { CSecret secret; secret.resize(32); memcpy(&secret[0], &privkey, 32); vector<unsigned char> sec; sec.resize(32); memcpy(&sec[0], &secret[0], 32); printf(" * secret (hex): %s\n", HexStr(sec).c_str()); for (int nCompressed=0; nCompressed<2; nCompressed++) { bool fCompressed = nCompressed == 1; printf(" * %s:\n", fCompressed ? "compressed" : "uncompressed"); CBitcoinSecret bsecret; bsecret.SetSecret(secret, fCompressed, '?'); printf(" * secret (base58): %s\n", bsecret.ToString().c_str()); CKey key; key.SetSecret(secret, fCompressed); vector<unsigned char> vchPubKey = key.GetPubKey(); printf(" * pubkey (hex): %s\n", HexStr(vchPubKey).c_str()); printf(" * address (base58): %s\n", CBitcoinAddress(vchPubKey).ToString().c_str()); } } #endif BOOST_AUTO_TEST_SUITE(key_tests) BOOST_AUTO_TEST_CASE(key_test1) { CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; BOOST_CHECK( bsecret1.SetString (strDefaultSecret1, '?')); BOOST_CHECK( bsecret2.SetString (strDefaultSecret2, '?')); BOOST_CHECK( bsecret1C.SetString(strDefaultSecret1C, '?')); BOOST_CHECK( bsecret2C.SetString(strDefaultSecret2C, '?')); BOOST_CHECK(!baddress1.SetString(strAddressBad, '?')); bool fCompressed; CSecret secret1 = bsecret1.GetSecret (fCompressed); BOOST_CHECK(fCompressed == false); CSecret secret2 = bsecret2.GetSecret (fCompressed); BOOST_CHECK(fCompressed == false); CSecret secret1C = bsecret1C.GetSecret(fCompressed); BOOST_CHECK(fCompressed == true); CSecret secret2C = bsecret2C.GetSecret(fCompressed); BOOST_CHECK(fCompressed == true); BOOST_CHECK(secret1 == secret1C); BOOST_CHECK(secret2 == secret2C); CKey key1, key2, key1C, key2C; key1.SetSecret(secret1, false); key2.SetSecret(secret2, false); key1C.SetSecret(secret1, true); key2C.SetSecret(secret2, true); BOOST_CHECK(addrS1.Get() == CTxDestination(key1.GetPubKey().GetID())); BOOST_CHECK(addrS2.Get() == CTxDestination(key2.GetPubKey().GetID())); BOOST_CHECK(addrS1C.Get() == CTxDestination(key1C.GetPubKey().GetID())); BOOST_CHECK(addrS2C.Get() == CTxDestination(key2C.GetPubKey().GetID())); for (int n=0; n<16; n++) { string strMsg = strprintf("Very secret message %i: 11", n); uint256 hashMsg = Hash(strMsg.begin(), strMsg.end()); // normal signatures vector<unsigned char> sign1, sign2, sign1C, sign2C; BOOST_CHECK(key1.Sign (hashMsg, sign1)); BOOST_CHECK(key2.Sign (hashMsg, sign2)); BOOST_CHECK(key1C.Sign(hashMsg, sign1C)); BOOST_CHECK(key2C.Sign(hashMsg, sign2C)); BOOST_CHECK( key1.Verify(hashMsg, sign1)); BOOST_CHECK(!key1.Verify(hashMsg, sign2)); BOOST_CHECK( key1.Verify(hashMsg, sign1C)); BOOST_CHECK(!key1.Verify(hashMsg, sign2C)); BOOST_CHECK(!key2.Verify(hashMsg, sign1)); BOOST_CHECK( key2.Verify(hashMsg, sign2)); BOOST_CHECK(!key2.Verify(hashMsg, sign1C)); BOOST_CHECK( key2.Verify(hashMsg, sign2C)); BOOST_CHECK( key1C.Verify(hashMsg, sign1)); BOOST_CHECK(!key1C.Verify(hashMsg, sign2)); BOOST_CHECK( key1C.Verify(hashMsg, sign1C)); BOOST_CHECK(!key1C.Verify(hashMsg, sign2C)); BOOST_CHECK(!key2C.Verify(hashMsg, sign1)); BOOST_CHECK( key2C.Verify(hashMsg, sign2)); BOOST_CHECK(!key2C.Verify(hashMsg, sign1C)); BOOST_CHECK( key2C.Verify(hashMsg, sign2C)); // compact signatures (with key recovery) vector<unsigned char> csign1, csign2, csign1C, csign2C; BOOST_CHECK(key1.SignCompact (hashMsg, csign1)); BOOST_CHECK(key2.SignCompact (hashMsg, csign2)); BOOST_CHECK(key1C.SignCompact(hashMsg, csign1C)); BOOST_CHECK(key2C.SignCompact(hashMsg, csign2C)); CKey rkey1, rkey2, rkey1C, rkey2C; BOOST_CHECK(rkey1.SetCompactSignature (hashMsg, csign1)); BOOST_CHECK(rkey2.SetCompactSignature (hashMsg, csign2)); BOOST_CHECK(rkey1C.SetCompactSignature(hashMsg, csign1C)); BOOST_CHECK(rkey2C.SetCompactSignature(hashMsg, csign2C)); BOOST_CHECK(rkey1.GetPubKey() == key1.GetPubKey()); BOOST_CHECK(rkey2.GetPubKey() == key2.GetPubKey()); BOOST_CHECK(rkey1C.GetPubKey() == key1C.GetPubKey()); BOOST_CHECK(rkey2C.GetPubKey() == key2C.GetPubKey()); } } BOOST_AUTO_TEST_CASE(key_test2) { CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C; // New encoding for NuShares BOOST_CHECK( bsecret1.SetString (strSSecret1, 'S')); BOOST_CHECK( bsecret2.SetString (strSSecret2, 'S')); BOOST_CHECK( bsecret1C.SetString(strSSecret1C, 'S')); BOOST_CHECK( bsecret2C.SetString(strSSecret2C, 'S')); // Set NuShares private key with NuBits unit, should fail BOOST_CHECK(!bsecret1.SetString (strSSecret1, 'B')); BOOST_CHECK(!bsecret2.SetString (strSSecret2, 'B')); BOOST_CHECK(!bsecret1C.SetString(strSSecret1C, 'B')); BOOST_CHECK(!bsecret2C.SetString(strSSecret2C, 'B')); // New encoding for NuBits BOOST_CHECK( bsecret1.SetString (strBSecret1, 'B')); BOOST_CHECK( bsecret2.SetString (strBSecret2, 'B')); BOOST_CHECK( bsecret1C.SetString(strBSecret1C, 'B')); BOOST_CHECK( bsecret2C.SetString(strBSecret2C, 'B')); // Set NuBits private key with NuShares unit, should fail BOOST_CHECK(!bsecret1.SetString (strBSecret1, 'S')); BOOST_CHECK(!bsecret2.SetString (strBSecret2, 'S')); BOOST_CHECK(!bsecret1C.SetString(strBSecret1C, 'S')); BOOST_CHECK(!bsecret2C.SetString(strBSecret2C, 'S')); // Old keys encoding for NuShares BOOST_CHECK( bsecret1.SetString (strDefaultSecret1, 'S')); BOOST_CHECK( bsecret2.SetString (strDefaultSecret2, 'S')); BOOST_CHECK( bsecret1C.SetString(strDefaultSecret1C, 'S')); BOOST_CHECK( bsecret2C.SetString(strDefaultSecret2C, 'S')); // Old keys encoding for NuBits BOOST_CHECK( bsecret1.SetString (strDefaultSecret1, 'B')); BOOST_CHECK( bsecret2.SetString (strDefaultSecret2, 'B')); BOOST_CHECK( bsecret1C.SetString(strDefaultSecret1C, 'B')); BOOST_CHECK( bsecret2C.SetString(strDefaultSecret2C, 'B')); // Check the CBitcoinSecret bool fCompressed; CSecret secret = bsecret1.GetSecret(fCompressed); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'S').ToString() == strSSecret1); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'B').ToString() == strBSecret1); secret = bsecret2.GetSecret(fCompressed); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'S').ToString() == strSSecret2); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'B').ToString() == strBSecret2); secret = bsecret1C.GetSecret(fCompressed); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'S').ToString() == strSSecret1C); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'B').ToString() == strBSecret1C); secret = bsecret2C.GetSecret(fCompressed); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'S').ToString() == strSSecret2C); BOOST_CHECK(CBitcoinSecret(secret, fCompressed, 'B').ToString() == strBSecret2C); } BOOST_AUTO_TEST_SUITE_END()
42.52093
99
0.713848
[ "vector" ]
e4da6a63e3c24a77a570c1434149b35c873f676d
7,460
hpp
C++
include/Zenject/AnimatorMoveHandlerManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/Zenject/AnimatorMoveHandlerManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/Zenject/AnimatorMoveHandlerManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: IAnimatorMoveHandler class IAnimatorMoveHandler; // Forward declaring type: InjectTypeInfo class InjectTypeInfo; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Forward declaring type: AnimatorMoveHandlerManager class AnimatorMoveHandlerManager; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Zenject::AnimatorMoveHandlerManager); DEFINE_IL2CPP_ARG_TYPE(::Zenject::AnimatorMoveHandlerManager*, "Zenject", "AnimatorMoveHandlerManager"); // Type namespace: Zenject namespace Zenject { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: Zenject.AnimatorMoveHandlerManager // [TokenAttribute] Offset: FFFFFFFF class AnimatorMoveHandlerManager : public ::UnityEngine::MonoBehaviour { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Collections.Generic.List`1<Zenject.IAnimatorMoveHandler> _handlers // Size: 0x8 // Offset: 0x18 ::System::Collections::Generic::List_1<::Zenject::IAnimatorMoveHandler*>* handlers; // Field size check static_assert(sizeof(::System::Collections::Generic::List_1<::Zenject::IAnimatorMoveHandler*>*) == 0x8); public: // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: private System.Collections.Generic.List`1<Zenject.IAnimatorMoveHandler> _handlers ::System::Collections::Generic::List_1<::Zenject::IAnimatorMoveHandler*>*& dyn__handlers(); // public System.Void Construct(System.Collections.Generic.List`1<Zenject.IAnimatorMoveHandler> handlers) // Offset: 0x1731CA0 void Construct(::System::Collections::Generic::List_1<::Zenject::IAnimatorMoveHandler*>* handlers); // public System.Void OnAnimatorMove() // Offset: 0x1731CA8 void OnAnimatorMove(); // static private System.Void __zenInjectMethod0(System.Object P_0, System.Object[] P_1) // Offset: 0x1731E10 static void __zenInjectMethod0(::Il2CppObject* P_0, ::ArrayW<::Il2CppObject*> P_1); // static private Zenject.InjectTypeInfo __zenCreateInjectTypeInfo() // Offset: 0x1731EFC static ::Zenject::InjectTypeInfo* __zenCreateInjectTypeInfo(); // public System.Void .ctor() // Offset: 0x1731E08 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static AnimatorMoveHandlerManager* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::AnimatorMoveHandlerManager::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<AnimatorMoveHandlerManager*, creationType>())); } }; // Zenject.AnimatorMoveHandlerManager #pragma pack(pop) static check_size<sizeof(AnimatorMoveHandlerManager), 24 + sizeof(::System::Collections::Generic::List_1<::Zenject::IAnimatorMoveHandler*>*)> __Zenject_AnimatorMoveHandlerManagerSizeCheck; static_assert(sizeof(AnimatorMoveHandlerManager) == 0x20); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Zenject::AnimatorMoveHandlerManager::Construct // Il2CppName: Construct template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Zenject::AnimatorMoveHandlerManager::*)(::System::Collections::Generic::List_1<::Zenject::IAnimatorMoveHandler*>*)>(&Zenject::AnimatorMoveHandlerManager::Construct)> { static const MethodInfo* get() { static auto* handlers = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("Zenject", "IAnimatorMoveHandler")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(Zenject::AnimatorMoveHandlerManager*), "Construct", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{handlers}); } }; // Writing MetadataGetter for method: Zenject::AnimatorMoveHandlerManager::OnAnimatorMove // Il2CppName: OnAnimatorMove template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Zenject::AnimatorMoveHandlerManager::*)()>(&Zenject::AnimatorMoveHandlerManager::OnAnimatorMove)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Zenject::AnimatorMoveHandlerManager*), "OnAnimatorMove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Zenject::AnimatorMoveHandlerManager::__zenInjectMethod0 // Il2CppName: __zenInjectMethod0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::Il2CppObject*, ::ArrayW<::Il2CppObject*>)>(&Zenject::AnimatorMoveHandlerManager::__zenInjectMethod0)> { static const MethodInfo* get() { static auto* P_0 = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* P_1 = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(Zenject::AnimatorMoveHandlerManager*), "__zenInjectMethod0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{P_0, P_1}); } }; // Writing MetadataGetter for method: Zenject::AnimatorMoveHandlerManager::__zenCreateInjectTypeInfo // Il2CppName: __zenCreateInjectTypeInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Zenject::InjectTypeInfo* (*)()>(&Zenject::AnimatorMoveHandlerManager::__zenCreateInjectTypeInfo)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Zenject::AnimatorMoveHandlerManager*), "__zenCreateInjectTypeInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Zenject::AnimatorMoveHandlerManager::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
54.452555
247
0.739946
[ "object", "vector" ]
e4e8da5c84c087bd7b2237846b6111d1f0374372
868
hpp
C++
CookieEngine/include/Resources/Loader.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Resources/Loader.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
CookieEngine/include/Resources/Loader.hpp
qbleuse/Cookie-Engine
705d19d9e4c79e935e32244759ab63523dfbe6c4
[ "CC-BY-4.0" ]
null
null
null
#ifndef __LOADER_HPP__ #define __LOADER_HPP__ #include <assimp/Importer.hpp> #include <assimp/material.h> namespace Cookie { namespace Resources { class ResourcesManager; class Loader { private: Assimp::Importer importer; public: /* CONSTRUCTORS/DESTRUCTORS */ Loader(); ~Loader(); void Load(const char* fileName, ResourcesManager& _resources, Render::Renderer& _renderer); void InitScene(const char* fileName, const aiScene* _scene, ResourcesManager& _resources, Render::Renderer& _renderer); void InitMeshes(const char* fileName, aiMesh** meshes, unsigned int nMeshes, ResourcesManager& _resources, Render::Renderer& _renderer); void InitTextures(const char* pathToFile, aiMaterial** materials, unsigned int nMatNb, ResourcesManager& _resources, Render::Renderer& _renderer); }; } } #endif /* __LOADER_HPP__ */
27.125
150
0.738479
[ "render" ]
e4e964f84e73ef063478271e5caa38151173769f
3,980
cpp
C++
src/ShellTable.cpp
arelenos/TurtleDB
65cbca6451a78d8cc304ab9ea45a131aa2cc8db1
[ "MIT" ]
null
null
null
src/ShellTable.cpp
arelenos/TurtleDB
65cbca6451a78d8cc304ab9ea45a131aa2cc8db1
[ "MIT" ]
null
null
null
src/ShellTable.cpp
arelenos/TurtleDB
65cbca6451a78d8cc304ab9ea45a131aa2cc8db1
[ "MIT" ]
1
2018-01-23T03:42:56.000Z
2018-01-23T03:42:56.000Z
#include "MetaRow.h" #include "String.h" #include "TurtleRow.h" #include <limits.h> // #include <string> #include <vector> #include <iostream> #include <map> struct TurtleRow {}; struct TurtleCol {}; struct MetaTable {}; using namespace std; class InvalidTableInput {}; typedef std::vector<std::string> VectorStr; TurtleTable::TurtleTable(VectorStr types, VectorStr labels) { if (types.size() != labels.size()) throw InvalidTableInput(); num_cols = types.size(); } TurtleTable::TurtleTable(String filename){ _constructTableFromCSV(filename); } TurtleTable::~TurtleTable(){ for (int i = 0; i < this->num_rows; ++i) { delete this->row_data[i]; // Delete objects that row points to } delete[] this->row_data; delete[] this->col_data; } static size_t csvRowCount(const char *file_name) { FILE *fptr = fopen(file_name, "r"); if (fptr == nullptr) throw FileNotFound(); char c; std::size_t count = 1; // Assumes #rows >= 1 while ( ((c = fgetc (fptr))!= EOF) ) { if (c == '\n') count++; } if ( ferror (fptr) ) throw FileReadError(); fclose(fptr); return count; } static size_t csvColumnCount(const char *file_name) { FILE *fptr = fopen(file_name, "r"); if (fptr == nullptr) throw FileNotFound(); char c; std::size_t count = 1; // Assumes at least one column (non empty file). while ( (c = fgetc (fptr)) != EOF ) { if (c == ',') count++; else if (c == '\n') break; } if ( ferror (fptr) ) throw FileReadError(); fclose(fptr); return count; } void TurtleTable::readfromCSV(const char *file_name) { this->num_rows = csvRowCount(file_name); this->num_cols = csvColumnCount(file_name); this->allocateData(); FILE *fp = fopen(file_name, "r"); if (! fp) throw FileNotFound(); std::size_t buff_size = (this->num_cols * sizeof(double) + 1) * TYPE_SIZE; for (std::size_t row = 0; row < this->num_rows; ++row) { char *row_data = new char[buff_size]; if (not fgets(row_data, buff_size, fp)) throw InvalidRead(); char *token; token = std::strtok(row_data, SEP); for (std::size_t col = 0; col < this->num_cols; ++col) { this->data[row]->set(col, ATOT(token)); token = std::strtok(nullptr, SEP); } delete[] row_data; } fclose(fp); } // Incomplete void TurtleTable::allocateData(std::size_t num_rows, std::size_t num_cols, MetaRow metarowdata) { // What do we want to do in this case if (num_rows == 0 or num_cols == 0) { return; } else if (num_rows > MAX_ROW_SIZE or num_cols > MAX_COL_SIZE) { throw AllocationTooLargeException(); } this->num_rows = num_rows; this->num_cols = num_cols; this->row_data = new TurtleRowPtr[this->num_rows]; for (std::size_t row = 0; row < this->num_rows; ++row) { this->data.emplace_back(new TurtleRow(num_cols)); } } MetaRow TurtleTable::getMetaRow(FILE *fp)( if (! fp)throw FileNotFound(); std:size_t buff_size = MAX_INT; MetaRow for(int i = 0; i < this->num_cols; i++){ } } void TurtleTable::_constructTableFromCSV(const char *file_name) { this->num_rows = csvRowCount(file_name); this->num_cols = csvColumnCount(file_name); MetaRow rowinfo; // How to obtain from CSV? guess column types? this->allocateData(this->num_rows, this->num_cols, rowinfo); FILE *fp = fopen(file_name, "r"); if (! fp) throw FileNotFound(); std::map<TurtleTypes, void (*)()> method_map = { {TurtleTypes::Integer_TT, Object::NewInteger}, {TurtleTypes::String_TT, Object::NewString}, {TurtleTypes::Char_TT, Object::NewChar}, {TurtleTypes::Double_TT, Object::NewDouble}}; std::size_t buff_size = (this->num_cols * sizeof(double) + 1) * TYPE_SIZE; for (std::size_t row = 0; row < this->num_rows; ++row) { char *row_data = new char[buff_size]; if (not fgets(row_data, buff_size, fp)) throw InvalidRead(); char *token; token = std::strtok(row_data, SEP); for (std::size_t col = 0; col < this->num_cols; ++col) { this->data[row]->set(col, ATOT(token)); token = std::strtok(nullptr, SEP); } delete[] row_data; } fclose(fp); }
23.411765
97
0.66809
[ "object", "vector" ]
e4eb3e520dc2f61050de30d05c541a6bdd3a3e05
2,479
cpp
C++
Sources/Elastos/LibCore/src/elastosx/xml/transform/TransformerFactory.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/src/elastosx/xml/transform/TransformerFactory.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/src/elastosx/xml/transform/TransformerFactory.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "TransformerFactory.h" namespace Elastosx { namespace Xml { namespace Transform { CAR_INTERFACE_IMPL(TransformerFactory, Object, ITransformerFactory) AutoPtr<ITransformerFactory> TransformerFactory::NewInstance() /*throws TransformerFactoryConfigurationError*/ { assert(0); //TODO // String className = "org.apache.xalan.processor.TransformerFactoryImpl"; // try { // return (TransformerFactory) Class.forName(className).newInstance(); // } catch (Exception e) { // throw new NoClassDefFoundError(className); // } return NULL; } AutoPtr<ITransformerFactory> TransformerFactory::NewInstance( /* [in] */ const String& factoryClassName, /* [in] */ IClassLoader* classLoader) /*throws TransformerFactoryConfigurationError*/ { assert(0); //TODO // if (factoryClassName == NULL) { // throw new TransformerFactoryConfigurationError("factoryClassName == null"); // } // if (classLoader == null) { // classLoader = Thread.currentThread().getContextClassLoader(); // } // try { // Class<?> type = classLoader != null // ? classLoader.loadClass(factoryClassName) // : Class.forName(factoryClassName); // return (TransformerFactory) type.newInstance(); // } catch (ClassNotFoundException e) { // throw new TransformerFactoryConfigurationError(e); // } catch (InstantiationException e) { // throw new TransformerFactoryConfigurationError(e); // } catch (IllegalAccessException e) { // throw new TransformerFactoryConfigurationError(e); // } return NULL; } } // namespace Transform } // namespace Xml } // namespace Elastosx
36.455882
110
0.646228
[ "object", "transform" ]
e4f3d656528fe06b52ac9cdce45cd27c6f219d53
1,943
cpp
C++
zip.cpp
isyangban/cpp-zip
46d0ce520c14d13cb9037c191f9dfc09200aa408
[ "MIT" ]
null
null
null
zip.cpp
isyangban/cpp-zip
46d0ce520c14d13cb9037c191f9dfc09200aa408
[ "MIT" ]
null
null
null
zip.cpp
isyangban/cpp-zip
46d0ce520c14d13cb9037c191f9dfc09200aa408
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<tuple> #include<string> #include<utility> using namespace std; // pretty-print a tuple (from http://stackoverflow.com/a/6245777/273767) template<class Ch, class Tr, class Tuple, std::size_t... Is> void print_tuple_impl(std::basic_ostream<Ch,Tr>& os, const Tuple & t, std::index_sequence<Is...>) { using swallow = int[]; // guaranties left to right order (void)swallow{0, (void(os << (Is == 0? "" : ", ") << std::get<Is>(t)), 0)...}; } template<class Ch, class Tr, class... Args> decltype(auto) operator<<(std::basic_ostream<Ch, Tr>& os, const std::tuple<Args...>& t) { os << "("; print_tuple_impl(os, t, std::index_sequence_for<Args...>{}); return os << ")"; } template<typename E, typename Tuple, size_t... I> auto combine(E e, Tuple t, index_sequence<I...>) { return make_tuple(e, get<I>(t)...); } template<typename C> auto zip(C first) { vector<tuple<typename C::value_type>> result; for (auto& e : first) { result.push_back(make_tuple(e)); } return result; } template<typename C, typename... Args> auto zip(C first, Args... args) { vector<tuple<typename C::value_type, typename Args::value_type...>> result; auto iter = first.begin(); auto rhs = zip(args...); auto iter2 = rhs.begin(); while (iter != first.end() && iter2 != rhs.end()) { auto e1 = *iter; auto e2 = *iter2; auto seq = make_index_sequence<tuple_size<decltype(e2)>::value>(); auto t = combine(e1, e2, seq); iter++; iter2++; result.push_back(t); } return result; } int main() { vector<int> a = {1, 2, 3, 4, 5}; string b = "hello"; vector<double> c = {0.5, 3.14, 1.414, 12.0, 1.0}; auto zipped = zip(a, b, c); for (auto& t : zipped) cout << t << ", "; cout << endl; return 0; }
25.233766
82
0.568708
[ "vector" ]
e4f6447bc8fe879b19d066eacf2d7527cdb637f7
7,004
cpp
C++
Classes/MainLayer.cpp
link-next-link/TestCoco1
4a0302fadd55b8043cec82ad58dce6435c347c38
[ "zlib-acknowledgement" ]
null
null
null
Classes/MainLayer.cpp
link-next-link/TestCoco1
4a0302fadd55b8043cec82ad58dce6435c347c38
[ "zlib-acknowledgement" ]
null
null
null
Classes/MainLayer.cpp
link-next-link/TestCoco1
4a0302fadd55b8043cec82ad58dce6435c347c38
[ "zlib-acknowledgement" ]
null
null
null
#include "MainLayer.h" #include "Utl.h" #include "AtlasLoader.h" #include "Number.h" #include "JniIf.h" Scene* MainLayer::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = MainLayer::create(); // add layer as a child to scene scene->addChild( layer ); // return the scene return scene; } bool MainLayer::init() { if( !Layer::init()) { return false; } /* * Set layer background color */ if( !LayerColor::initWithColor( Color4B( 168, 168, 168, 255 ))) { return false; } _screenSize = Director::getInstance()->getWinSize(); initCloseButton(); createLabel( this->__CLASS__ ); createLabelSys( "Press 'BACK' button\nto see if the app crashes..", 48); Sprite* sprite = Sprite::createWithSpriteFrame( AtlasLoader::getInstance()->getSpriteFrameByName( "CocosTitle1" )); sprite->setPosition( Vec2( _screenSize.width*0.5f, _screenSize.height*0.3f )); this->addChild( sprite, kZOrder::zMid ); initScoreDisplay(); initBackground(); initEvents(); testJni(); //create main loop this->schedule( schedule_selector( MainLayer::update )); Size sFrame = Utl::getFrameSize(); Size sVisible = Director::getInstance()->getVisibleSize(); setLabelText( "type=%d sWin=%.0f,%.0f\nsFrame=%.0f,%.0f\nsVisible=%.0f,%.0f" , Utl::getScreenTypeSaved() , _screenSize.width , _screenSize.height , sFrame.width , sFrame.height , sVisible.width , sVisible.height ); return true; } void MainLayer::initBackground() { Sprite* background = getBackground(); background->setPosition( _screenSize.width*0.5f, _screenSize.height*0.5f ); this->addChild( background, kZOrder::zBackground ); } void MainLayer::createLabel( const char* msg ) { // create and initialize a label int sizeFont = 30; TTFConfig ttfConfig( "Arial.ttf", sizeFont, GlyphCollection::DYNAMIC ); label1 = Label::createWithTTF( ttfConfig, msg ); label1->setPosition( _screenSize.width*0.5f, _screenSize.height*0.6f ); this->addChild( label1, kZOrder::zTest ); } void MainLayer::setLabelText( const char* format, ... ) { int maxLen = 1024; std::string str; va_list ap; va_start( ap, format ); char* buf = (char*)malloc( maxLen ); if( buf != nullptr ) { vsnprintf( buf, maxLen, format, ap ); str = buf; free( buf ); } va_end( ap ); label1->setString( str.c_str()); } void MainLayer::createLabelSys( const char* msg, int fontSize) { auto labelA = Label::createWithSystemFont( msg, "Arial.ttf", fontSize); auto size = labelA->getContentSize(); labelA->setDimensions( size.width, size.height ); labelA->setPosition( _screenSize.width*0.5f, _screenSize.height*0.8f ); addChild( labelA, kZOrder::zTest ); } void MainLayer::initCloseButton() { // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1( MainLayer::menuCloseCallback, this )); float x = _screenSize.width - closeItem->getContentSize().width/2; float y = closeItem->getContentSize().height/2; closeItem->setPosition( Vec2( x, y )); // create menu, it's an autorelease object auto menu = Menu::create( closeItem, nullptr ); menu->setPosition( Vec2::ZERO ); this->addChild( menu, kZOrder::zMenu ); } void MainLayer::initEvents() { auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2( MainLayer::onTouchBegan, this ); listener->onTouchMoved = CC_CALLBACK_2( MainLayer::onTouchMoved, this ); listener->onTouchEnded = CC_CALLBACK_2( MainLayer::onTouchEnded, this ); listener->onTouchCancelled = CC_CALLBACK_2( MainLayer::onTouchCancelled, this ); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority( listener, this ); auto keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyReleased = CC_CALLBACK_2( MainLayer::onKeyReleased, this ); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority( keyboardListener, this ); } void MainLayer::initScoreDisplay() { Number::getInstance()->loadNumber( NUMBER_SCORE.c_str(), "num_%02d" ); Sprite* scoreDisp = Sprite::createWithSpriteFrame( AtlasLoader::getInstance()->getSpriteFrameByName( "blank" )); Node* val = (Node*)Number::getInstance()->convert( NUMBER_SCORE.c_str(), 1234, Gravity::GRAVITY_CENTER ); scoreDisp->addChild( val ); scoreDisp->setPosition( Vec2( _screenSize.width*0.5f, _screenSize.height*0.5f )); this->addChild( scoreDisp, kZOrder::zBackground ); } void MainLayer::testJni() { CCL( "JNI testString=%s", testString()); CCL( "JNI testInt1=%d", testInt1()); CCL( "JNI testInt2=%d", testInt2( 5)); CCL( "JNI testFloat1=%f", testFloat1()); CCL( "JNI testFloat2=%f", testFloat2( 5)); CCL( "JNI testDouble2=%f", testDouble2( 5)); } bool MainLayer::onTouchBegan( cocos2d::Touch* touch, cocos2d::Event* event ) { return true; } void MainLayer::onTouchMoved( cocos2d::Touch* touch, cocos2d::Event* event ) { } void MainLayer::onTouchEnded( cocos2d::Touch* touch, cocos2d::Event* event ) { } void MainLayer::onTouchCancelled( cocos2d::Touch* touch, cocos2d::Event* event ) { } void MainLayer::update( float dt ) { } void MainLayer::menuCloseCallback( Ref* pSender ) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } void MainLayer::onKeyReleased( cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event ) { if( keyCode == EventKeyboard::KeyCode::KEY_ESCAPE ) { Director::getInstance()->end(); } } /** * Get background imange depends on specifid screen resolution * @return */ Sprite* MainLayer::getBackground() { int sType = TARGET_DESIGN_RESOLUTION_SIZE; bool land = Utl::isLandscape(); const char* img; if( sType == DESIGN_RESOLUTION_LARGE ) { if( land ) { img = kBackgroundImageLarge; } else { img = kBackgroundImageLargePort; } } else if( sType == DESIGN_RESOLUTION_MID ) { if( land ) { img = kBackgroundImageMid; } else { img = kBackgroundImageMidPort; } } else { if( land ) { img = kBackgroundImageSmall; } else { img = kBackgroundImageSmallPort; } } Sprite* background = Sprite::create( std::string( img )); return background; }
30.585153
137
0.651485
[ "object" ]
07e5dbdb730ad98314b4a3c35c34d52fca8957ff
59,745
cpp
C++
src/Core/OgreRenderingModule/OgreWorld.cpp
jesterKing/naali
1dc38ea1c21c37d93ea37c83eba9ad2fb2efe287
[ "Apache-2.0" ]
null
null
null
src/Core/OgreRenderingModule/OgreWorld.cpp
jesterKing/naali
1dc38ea1c21c37d93ea37c83eba9ad2fb2efe287
[ "Apache-2.0" ]
null
null
null
src/Core/OgreRenderingModule/OgreWorld.cpp
jesterKing/naali
1dc38ea1c21c37d93ea37c83eba9ad2fb2efe287
[ "Apache-2.0" ]
1
2018-08-22T16:27:17.000Z
2018-08-22T16:27:17.000Z
// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "CoreException.h" #define MATH_OGRE_INTEROP #include "OgreWorld.h" #include "Renderer.h" #include "EC_Camera.h" #include "EC_Placeable.h" #include "EC_Mesh.h" #include "OgreCompositionHandler.h" #include "OgreShadowCameraSetupFocusedPSSM.h" #include "OgreBulletCollisionsDebugLines.h" #include "OgreMaterialAsset.h" #include "OgreMeshAsset.h" #include "OgreMeshAsset.h" #include "Entity.h" #include "Scene/Scene.h" #include "Profiler.h" #include "ConfigAPI.h" #include "FrameAPI.h" #include "AssetAPI.h" #include "Transform.h" #include "Math/float2.h" #include "Math/float3x4.h" #include "Geometry/AABB.h" #include "Geometry/OBB.h" #include "Geometry/Plane.h" #include "Geometry/LineSegment.h" #include "Math/float3.h" #include "Geometry/Circle.h" #include "Geometry/Sphere.h" #include <Ogre.h> #include <OgreOverlaySystem.h> #ifdef ANDROID #include <OgreRTShaderSystem.h> #include <OgreShaderGenerator.h> #endif #include "MemoryLeakCheck.h" struct RaycastResultLessThan { bool operator()(const RaycastResult *left, const RaycastResult *right ) const { return left->t < right->t; } }; OgreWorld::OgreWorld(OgreRenderer::Renderer* renderer, ScenePtr scene) : framework_(scene->GetFramework()), renderer_(renderer), scene_(scene), sceneManager_(0), rayQuery_(0), debugLines_(0), debugLinesNoDepth_(0), drawDebugInstancing_(false) { assert(renderer_->IsInitialized()); sceneManager_ = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC, scene->Name().toStdString()); sceneManager_->addRenderQueueListener(renderer_->GetOverlaySystem()); #ifdef ANDROID Ogre::RTShader::ShaderGenerator* shaderGenerator = renderer_->GetShaderGenerator(); if (shaderGenerator) shaderGenerator->addSceneManager(sceneManager_); #endif if (!framework_->IsHeadless()) { rayQuery_ = sceneManager_->createRayQuery(Ogre::Ray()); rayQuery_->setQueryTypeMask(Ogre::SceneManager::FX_TYPE_MASK | Ogre::SceneManager::ENTITY_TYPE_MASK); rayQuery_->setSortByDistance(true); // If fog is FOG_NONE, force it to some default ineffective settings, because otherwise SuperShader shows just white if (sceneManager_->getFogMode() == Ogre::FOG_NONE) SetDefaultSceneFog(); // Set a default ambient color that matches the default ambient color of EC_EnvironmentLight, in case there is no environmentlight component. sceneManager_->setAmbientLight(DefaultSceneAmbientLightColor()); SetupShadows(); #include "DisableMemoryLeakCheck.h" debugLines_ = new DebugLines("PhysicsDebug"); debugLinesNoDepth_ = new DebugLines("PhysicsDebugNoDepth"); #include "EnableMemoryLeakCheck.h" sceneManager_->getRootSceneNode()->attachObject(debugLines_); sceneManager_->getRootSceneNode()->attachObject(debugLinesNoDepth_); debugLinesNoDepth_->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY); } connect(framework_->Frame(), SIGNAL(Updated(float)), this, SLOT(OnUpdated(float))); // Ensure there's always at least 1 raycast result object GetOrCreateRaycastResult(0); } OgreWorld::~OgreWorld() { if (!instancingTargets_.isEmpty()) { try { QList<Ogre::InstancedEntity *> parents; for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *meshTarget = instancingTargets_[i]; if (!meshTarget) continue; bool needsCleanup = false; foreach(MeshInstanceTarget::ManagerTarget *manager, meshTarget->managers) { if (manager && !manager->instances.isEmpty()) { // These should all be gone if DestroyInstance() were called by the creators correctly! LogWarning(QString("OgreWorld: %1 instanced entities for submesh %2 are still loaded to the system for %3, destroying them now!") .arg(manager->instances.size()).arg(manager->submesh).arg(meshTarget->ref)); needsCleanup = true; } } if (needsCleanup) parents += meshTarget->Parents(); } foreach(Ogre::InstancedEntity* instance, parents) DestroyInstance(instance); } catch (Ogre::Exception &e) { LogError(QString("OgreWorld: Exception occurred while destroying instance managers: ") + e.what()); } } if (rayQuery_) sceneManager_->destroyQuery(rayQuery_); for (std::vector<RaycastResult*>::iterator i = rayResults_.begin(); i != rayResults_.end(); ++i) { delete (*i); *i = 0; } rayResults_.clear(); if (debugLines_) { sceneManager_->getRootSceneNode()->detachObject(debugLines_); SAFE_DELETE(debugLines_); } if (debugLinesNoDepth_) { sceneManager_->getRootSceneNode()->detachObject(debugLinesNoDepth_); SAFE_DELETE(debugLinesNoDepth_); } // Remove all compositors. /// \todo This does not work with a proper multiscene approach OgreCompositionHandler* comp = renderer_->CompositionHandler(); if (comp) comp->RemoveAllCompositors(); #ifdef ANDROID Ogre::RTShader::ShaderGenerator* shaderGenerator = renderer_->GetShaderGenerator(); if (shaderGenerator) shaderGenerator->removeSceneManager(sceneManager_); #endif Ogre::Root::getSingleton().destroySceneManager(sceneManager_); } std::string OgreWorld::GenerateUniqueObjectName(const std::string &prefix) { return renderer_->GetUniqueObjectName(prefix); } void OgreWorld::FlushDebugGeometry() { if (debugLines_) debugLines_->draw(); if (debugLinesNoDepth_) debugLinesNoDepth_->draw(); } Color OgreWorld::DefaultSceneAmbientLightColor() { return Color(0.364f, 0.364f, 0.364f, 1.f); } void OgreWorld::SetDefaultSceneFog() { if (sceneManager_) { sceneManager_->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue::White, 0.001f, 2000.0f, 4000.0f); Renderer()->MainViewport()->setBackgroundColour(Color()); // Color default ctor == black } } Ogre::InstancedEntity *OgreWorld::CreateInstance(IComponent *owner, const QString &meshRef, const AssetReferenceList &materials, float drawDistance, bool castShadows) { return CreateInstance(owner, framework_->Asset()->GetAsset(meshRef), materials, drawDistance, castShadows); } Ogre::InstancedEntity *OgreWorld::CreateInstance(IComponent *owner, const AssetPtr &meshAsset, const AssetReferenceList &materials, float drawDistance, bool castShadows) { PROFILE(OgreWorld_CreateInstance); if (!sceneManager_ || !meshAsset.get()) return 0; if (!owner) { LogError(QString("OgreWorld::CreateInstance: Cannot create instance without owner component!")); return 0; } OgreMeshAsset *mesh = dynamic_cast<OgreMeshAsset*>(meshAsset.get()); if (!mesh || !mesh->IsLoaded()) return 0; int submeshCount = static_cast<int>(mesh->ogreMesh->getNumSubMeshes()); // Verify materials have been loaded. Use 'AssetLoadError' from Tundras core // materials for empty refs (or instancing will crash later to null mat ptr). QStringList instanceMaterials; for (int i=0; i<submeshCount; ++i) { QString materialRef = i < materials.Size() ? materials[i].ref.trimmed() : ""; if (!materialRef.isEmpty()) { AssetPtr materialAsset = framework_->Asset()->GetAsset(materialRef); if (!materialAsset.get() || !materialAsset->IsLoaded()) { LogError(QString("OgreWorld::CreateInstance: Cannot create instance for %1, material in index %2 is not loaded!").arg(mesh->Name()).arg(i)); return 0; } OgreMaterialAsset *material = dynamic_cast<OgreMaterialAsset*>(materialAsset.get()); if (!material) { LogError(QString("OgreWorld::CreateInstance: Cannot create instance for %1, material in index %2 is not type of OgreMaterial type!").arg(mesh->Name()).arg(i)); return 0; } // This function will clone the current material if needed for instancing use. // If it returns empty string it means something went wrong so bail out. materialRef = PrepareInstancingMaterial(material); if (materialRef.isEmpty()) { LogError(QString("OgreWorld::CreateInstance: Cannot create instance for %1, material in index %2 could not be prepared").arg(mesh->Name()).arg(i)); return 0; } } else materialRef = "Tundra/Instancing/HWBasic/Empty"; instanceMaterials << materialRef; } // Get instance manager and create the new instances, parenting submesh instances to the main instance. Ogre::InstancedEntity *mainInstance = 0; try { for (int i=0; i<submeshCount; ++i) { MeshInstanceTarget *target = GetOrCreateInstanceMeshTarget(mesh->OgreMeshName(), i); Ogre::InstancedEntity *instance = target->CreateInstance(sceneManager_, i, instanceMaterials[i], mainInstance); instance->setRenderingDistance(drawDistance); /// \todo This does not actually work. Shadow casting needs to be configured per instance batch. instance->setCastShadows(castShadows); instance->setUserAny(Ogre::Any(owner)); if (drawDebugInstancing_) target->SetDebuggingEnabled(true, instanceMaterials[i]); // Main instance that is being returned. if (!mainInstance) mainInstance = instance; } } catch (Exception &e) { LogError(QString("OgreWorld::CreateInstance: Exception occurred while creating instances: %1 for %2").arg(e.what()).arg(mesh->Name())); if (mainInstance) DestroyInstance(mainInstance); mainInstance = 0; } catch (Ogre::Exception &e) { LogError(QString("OgreWorld::CreateInstance: Exception occurred while creating instances: %1 for %2").arg(e.what()).arg(mesh->Name())); if (mainInstance) DestroyInstance(mainInstance); mainInstance = 0; } return mainInstance; } QList<Ogre::InstancedEntity*> OgreWorld::ChildInstances(Ogre::InstancedEntity *parent) { QList<Ogre::InstancedEntity*> children; for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *instancingTarget = instancingTargets_[i]; if (instancingTarget->Contains(parent)) return instancingTarget->Children(parent); } return QList<Ogre::InstancedEntity*>(); } void OgreWorld::DestroyInstance(Ogre::InstancedEntity* instance) { PROFILE(OgreWorld_DestroyInstance); /** @todo Optimize this, its might be a bit slow when huge amount of instances. Though we cant expect EC_Mesh etc. to tell us the meshRef (to slim down these iterations) so now we have to brute force it. iTarget and kTarget is my best attempt to reduce extra loops. */ if (!instance) return; try { for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *instancingTarget = instancingTargets_.at(i); if (instancingTarget->Contains(instance)) { // This destroys the parent, its children and the manager if no instances are left. instancingTarget->DestroyInstance(sceneManager_, instance); if (instancingTarget->managers.isEmpty()) { instancingTargets_.removeAt(i); SAFE_DELETE(instancingTarget); } return; } } } catch(Ogre::Exception &e) { LogError(QString("OgreWorld::DestroyInstance: Exception occurred while destroing instances: %1").arg(e.what())); } } MeshInstanceTarget *OgreWorld::GetOrCreateInstanceMeshTarget(const QString &meshRef, int submesh) { PROFILE(OgreWorld_GetOrCreateInstanceMeshTarget); for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *target = instancingTargets_[i]; if (target->ref.compare(meshRef, Qt::CaseSensitive) == 0) return target; } // The current instancing implementation will crash on meshes that use shared vertices. Filter them out here. Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().getByName(meshRef.toStdString()); if (!mesh.get()) throw ::Exception("Cannot create instances with null Ogre::Mesh!"); if (mesh->sharedVertexData != 0) throw ::Exception("Cannot create instances with Ogre::Mesh that uses shared vertexes!"); // No target for the mesh ref exists. MeshInstanceTarget *target = new MeshInstanceTarget(meshRef, MeshInstanceCount(meshRef)); instancingTargets_ << target; return target; } uint OgreWorld::MeshInstanceCount(const QString &meshRef) { if (scene_.expired()) return 64; uint count = 0; Entity::ComponentVector components = scene_.lock()->Components(EC_Mesh::TypeIdStatic()); for (Entity::ComponentVector::const_iterator iter = components.begin(); iter != components.end(); ++iter) { EC_Mesh *mesh = dynamic_cast<EC_Mesh*>((*iter).get()); if (!mesh) continue; // Check self resolved/sanitated mesh ref. If we were to use mesh->OgreEntity()->getMesh()->getName() // we would not get true count as OgreEntity might be null for most things when this is first called! QString ref = mesh->meshRef.Get().ref.trimmed(); if (ref.isEmpty()) continue; ref = AssetAPI::SanitateAssetRef(framework_->Asset()->ResolveAssetRef("", ref)); if (meshRef.compare(ref, Qt::CaseInsensitive) == 0) count++; } /// @todo Someone who understands ~optimal values of batch instance count better revisit this logic. /// This is just an naive implementation that makes sure we don't jam all our instances into a single batch. uint batchSize = (count >= 16384 ? 4096 : (count >= 8192 ? 2048 : (count >= 2048 ? 1024 : (count >= 1024 ? 512 : (count >= 512 ? 256 : (count > 0 ? count : 64)))))); LogDebug(QString("OgreWorld::MeshInstanceCount: Found %1 instances of %2 in the active scene. Returning batch size of %3.").arg(count).arg(meshRef).arg(batchSize)); return batchSize; } QString OgreWorld::PrepareInstancingMaterial(OgreMaterialAsset *material) { static QString InstancingHWBasic_VS = "Tundra/Instancing/HWBasicVS"; static QString InstancingHWBasic_PS = "Tundra/Instancing/HWBasicPS"; QString VS = material->VertexShader(0, 0).trimmed(); QString PS = material->PixelShader(0, 0).trimmed(); QString newVS; QString newPS; if (VS.isEmpty() || (!VS.contains("instanced", Qt::CaseInsensitive) && !VS.contains("instancing", Qt::CaseInsensitive))) { if (VS.isEmpty()) { newVS = InstancingHWBasic_VS; // No shader. Use basic instancing shader newPS = InstancingHWBasic_PS; } else { newVS = VS + "/Instanced"; // Automatically generated instancing shader for eg. SuperShader materials // Verify that the instancing shader exists if (Ogre::HighLevelGpuProgramManager::getSingletonPtr()->getByName(newVS.toStdString()).isNull()) { LogWarning(QString("OgreWorld::CreateInstance: Could not find matching instancing vertex shader for '%1' in material '%2', falling back to default instancing shader").arg(VS).arg(material->Name())); newVS = InstancingHWBasic_VS; newPS = InstancingHWBasic_PS; } } // We cannot modify the original material as it might be used in non-instanced meshes too. QString cloneRef = material->Name().replace(".material", "_Cloned_Instancing.material", Qt::CaseInsensitive); AssetPtr clone = framework_->Asset()->GetAsset(cloneRef); if (!clone.get()) { // Clone needs to be created clone = material->Clone(cloneRef); OgreMaterialAsset *clonedMaterial = dynamic_cast<OgreMaterialAsset*>(clone.get()); if (clonedMaterial) { if (!newVS.isEmpty()) { if (!clonedMaterial->SetVertexShader(0, 0, newVS)) { LogError(QString("OgreWorld::CreateInstance: Failed to clone material '%1' in submesh %2 with instancing shaders!").arg(material->Name())); return ""; } } if (!newPS.isEmpty()) { if (!clonedMaterial->SetPixelShader(0, 0, newPS)) { LogError(QString("OgreWorld::CreateInstance: Failed to clone material '%1' in submesh %2 with instancing shaders!").arg(material->Name())); return ""; } } // Setup instancing shadowcaster material Ogre::Material* ogreMat = clonedMaterial->ogreMaterial.get(); for (ushort i = 0; i < ogreMat->getNumTechniques(); ++i) ogreMat->getTechnique(i)->setShadowCasterMaterial("rex/ShadowCaster/Instanced"); return clonedMaterial->ogreAssetName; } else { LogError(QString("OgreWorld::CreateInstance: Failed to clone material '%1' with instancing shaders!").arg(material->Name())); return ""; } } else { OgreMaterialAsset *clonedMaterial = dynamic_cast<OgreMaterialAsset*>(clone.get()); return (clonedMaterial != 0 ? clonedMaterial->ogreAssetName : ""); } } return material->ogreAssetName; } RaycastResult* OgreWorld::Raycast(int x, int y) { return Raycast(x, y, 0xffffffff, FLOAT_INF); } RaycastResult* OgreWorld::Raycast(int x, int y, float maxDistance) { return Raycast(x, y, 0xffffffff, maxDistance); } RaycastResult* OgreWorld::Raycast(int x, int y, unsigned layerMask) { return Raycast(x, y, layerMask, FLOAT_INF); } RaycastResult* OgreWorld::Raycast(const Ray& ray, unsigned layerMask) { return Raycast(ray, layerMask, FLOAT_INF); } RaycastResult* OgreWorld::Raycast(int x, int y, unsigned layerMask, float maxDistance) { ClearRaycastResults(); int width = renderer_->WindowWidth(); int height = renderer_->WindowHeight(); if (width && height && rayQuery_) { Ogre::Camera* camera = VerifyCurrentSceneCamera(); if (camera) { float screenx = x / (float)width; float screeny = y / (float)height; Ogre::Ray ray = camera->getCameraToViewportRay(screenx, screeny); rayQuery_->setRay(ray); RaycastInternal(layerMask, maxDistance, false); } } // Return the closest hit, or a cleared raycastresult if no hits return rayHits_.size() ? rayHits_[0] : rayResults_[0]; } RaycastResult* OgreWorld::Raycast(const Ray& ray, unsigned layerMask, float maxDistance) { ClearRaycastResults(); if (rayQuery_) { rayQuery_->setRay(Ogre::Ray(ray.pos, ray.dir)); RaycastInternal(layerMask, maxDistance, false); } // Return the closest hit, or a cleared raycastresult if no hits return rayHits_.size() ? rayHits_[0] : rayResults_[0]; } QList<RaycastResult*> OgreWorld::RaycastAll(int x, int y) { return RaycastAll(x, y, 0xffffffff, FLOAT_INF); } QList<RaycastResult*> OgreWorld::RaycastAll(int x, int y, float maxDistance) { return RaycastAll(x, y, 0xffffffff, maxDistance); } QList<RaycastResult*> OgreWorld::RaycastAll(int x, int y, unsigned layerMask) { return RaycastAll(x, y, layerMask, FLOAT_INF); } QList<RaycastResult*> OgreWorld::RaycastAll(const Ray& ray, unsigned layerMask) { return RaycastAll(ray, layerMask, FLOAT_INF); } QList<RaycastResult*> OgreWorld::RaycastAll(int x, int y, unsigned layerMask, float maxDistance) { ClearRaycastResults(); int width = renderer_->WindowWidth(); int height = renderer_->WindowHeight(); if (width && height && rayQuery_) { Ogre::Camera* camera = VerifyCurrentSceneCamera(); if (camera) { float screenx = x / (float)width; float screeny = y / (float)height; Ogre::Ray ray = camera->getCameraToViewportRay(screenx, screeny); rayQuery_->setRay(ray); RaycastInternal(layerMask, maxDistance, true); } } return rayHits_; } QList<RaycastResult*> OgreWorld::RaycastAll(const Ray& ray, unsigned layerMask, float maxDistance) { ClearRaycastResults(); if (rayQuery_) { rayQuery_->setRay(Ogre::Ray(ray.pos, ray.dir)); RaycastInternal(layerMask, maxDistance, true); } return rayHits_; } void OgreWorld::RaycastInternal(unsigned layerMask, float maxDistance, bool getAllResults) { PROFILE(OgreWorld_Raycast); Ray ray = rayQuery_->getRay(); Ogre::RaySceneQueryResult &results = rayQuery_->execute(); float closestDistance = -1.0f; size_t hitIndex = 0; for(size_t i = 0; i < results.size(); ++i) { Ogre::RaySceneQueryResultEntry &entry = results[i]; // If entry further away than max. distance, terminate if (entry.distance > maxDistance) break; if (!entry.movable) continue; // No result for invisible entity if (!entry.movable->isVisible()) continue; const Ogre::Any& any = entry.movable->getUserAny(); if (any.isEmpty()) continue; Entity *entity = 0; IComponent *component = 0; try { component = Ogre::any_cast<IComponent*>(any); entity = component ? component->ParentEntity() : 0; } catch(Ogre::InvalidParametersException &/*e*/) { continue; } EC_Placeable* placeable = entity->GetComponent<EC_Placeable>().get(); if (placeable) { if (!(placeable->selectionLayer.Get() & layerMask)) continue; } // If we are not getting all results, and this MovableObject's bounding box is further away than our current best result, // skip the detailed (e.g. triangle-level) test, as this object possibly can't be closer. if (!getAllResults && closestDistance >= 0.0f && entry.distance > closestDistance) continue; Ogre::Entity* meshEntity = dynamic_cast<Ogre::Entity*>(entry.movable); if (meshEntity) { RayQueryResult r; bool hit; if (meshEntity->hasSkeleton()) hit = EC_Mesh::Raycast(meshEntity, ray, &r.t, &r.submeshIndex, &r.triangleIndex, &r.pos, &r.normal, &r.uv); else { Ogre::SceneNode *node = meshEntity->getParentSceneNode(); if (!node) continue; assume(!float3(node->_getDerivedScale()).IsZero()); float3x4 localToWorld = float3x4::FromTRS(node->_getDerivedPosition(), node->_getDerivedOrientation(), node->_getDerivedScale()); assume(localToWorld.IsColOrthogonal()); float3x4 worldToLocal = localToWorld.Inverted(); EC_Mesh *mesh = entity->GetComponent<EC_Mesh>().get(); shared_ptr<OgreMeshAsset> ogreMeshAsset = mesh ? mesh->MeshAsset() : shared_ptr<OgreMeshAsset>(); if (ogreMeshAsset) { Ray localRay = worldToLocal * ray; float oldLength = localRay.dir.Normalize(); if (oldLength == 0) continue; r = ogreMeshAsset->Raycast(localRay); hit = r.t < std::numeric_limits<float>::infinity(); r.pos = localToWorld.MulPos(r.pos); r.normal = localToWorld.MulDir(r.normal); r.t = r.pos.Distance(ray.pos); ///\todo Can optimize out a sqrt. } else { // No mesh asset available, probably hit terrain? EC_Mesh::Raycast still applicable. hit = EC_Mesh::Raycast(meshEntity, ray, &r.t, &r.submeshIndex, &r.triangleIndex, &r.pos, &r.normal, &r.uv); } } if (hit && r.t < maxDistance && (getAllResults || (closestDistance < 0.0f || r.t < closestDistance))) { closestDistance = r.t; RaycastResult* result = GetOrCreateRaycastResult(hitIndex); result->entity = entity; result->component = component; result->pos = r.pos; result->normal = r.normal; result->submesh = r.submeshIndex; result->index = r.triangleIndex; result->u = r.uv.x; result->v = r.uv.y; result->t = r.t; rayHits_.push_back(result); ++hitIndex; } } else { Ogre::BillboardSet *bbs = dynamic_cast<Ogre::BillboardSet*>(entry.movable); if (bbs) { float3x4 camWorldTransform = float4x4(renderer_->MainOgreCamera()->getParentSceneNode()->_getFullTransform()).Float3x4Part(); float3 billboardFrontDir = camWorldTransform.Col(2).Normalized(); // The -direction this camera views in world space. (In Ogre, like common in OpenGL, cameras view towards -Z in their local space). float3 cameraUpDir = camWorldTransform.Col(1).Normalized(); // The direction of the up vector of the camera in world space. float3 cameraRightDir = camWorldTransform.Col(0).Normalized(); // The direction of the right vector of the camera in world space. Ogre::Matrix4 w_; bbs->getWorldTransforms(&w_); float3x4 world = float4x4(w_).Float3x4Part(); // The world transform of the whole billboard set. bool hasHit = false; float closestBillboardDistance = -1.0f; // Closest hit in this billboard set // Test a precise hit to each individual billboard in turn, and output the index of hit to the closest billboard in the set. for(int i = 0; i < bbs->getNumBillboards(); ++i) { Ogre::Billboard *b = bbs->getBillboard(i); float3 worldPos = world.MulPos(b->getPosition()); // A point on this billboard in world space. (@todo assuming this is the center point, but Ogre can use others!) Plane billboardPlane(worldPos, billboardFrontDir); // The plane of this billboard in world space. float d; bool success = billboardPlane.Intersects(ray, &d); if (!success || d > maxDistance) continue; if (!getAllResults && closestDistance > 0.0f && d >= closestDistance) continue; if (hasHit && d > closestBillboardDistance) continue; float3 intersectionPoint = ray.GetPoint(d); // The point where the ray intersects the plane of the billboard. // Compute the 3D world space -> local normalized 2D (x,y) coordinate frame mapping for this billboard. float w = (b->hasOwnDimensions() ? b->getOwnWidth() : bbs->getDefaultWidth()) * world.Col(0).Length(); float h = (b->hasOwnDimensions() ? b->getOwnHeight() : bbs->getDefaultHeight()) * world.Col(1).Length(); float3x3 m(w*0.5f*cameraRightDir, h*0.5f*cameraUpDir, billboardFrontDir); success = m.InverseColOrthogonal(); assume(success); // Compute the 2D coordinates of the ray hit on the billboard plane. const float3 hit = m * (intersectionPoint - worldPos); /* Test code: To visualize the borders of the billboards, do this: float3 tl = worldPos - w*0.5f*cameraRightDir + h*0.5f*cameraUpDir; float3 tr = worldPos + w*0.5f*cameraRightDir + h*0.5f*cameraUpDir; float3 bl = worldPos - w*0.5f*cameraRightDir - h*0.5f*cameraUpDir; float3 br = worldPos + w*0.5f*cameraRightDir - h*0.5f*cameraUpDir; DebugDrawLineSegment(LineSegment(tl, tr), 1,1,0); DebugDrawLineSegment(LineSegment(tr, br), 1,0,0); DebugDrawLineSegment(LineSegment(br, bl), 1,0,0); DebugDrawLineSegment(LineSegment(bl, tl), 1,0,0); */ // The visible range of the billboard is normalized to [-1,1] in x & y. See if the hit is inside the billboard. if (hit.x >= -1.f && hit.x <= 1.f && hit.y >= -1.f && hit.y <= 1.f) { closestDistance = d; closestBillboardDistance = d; hasHit = true; RaycastResult* result = GetOrCreateRaycastResult(hitIndex); result->entity = entity; result->component = component; result->pos = intersectionPoint; result->normal = billboardFrontDir; result->submesh = i; // Store in the 'submesh' index the index of the individual billboard we hit. result->index = (unsigned int)-1; // Not applicable for billboards. result->u = (hit.x + 1.f) * 0.5f; result->v = (hit.y + 1.f) * 0.5f; result->t = d; } } if (hasHit) { rayHits_.push_back(GetOrCreateRaycastResult(hitIndex)); ++hitIndex; } } else { // Not a mesh entity, fall back to just using the bounding box - ray intersection if (getAllResults || (closestDistance < 0.0f || entry.distance < closestDistance)) { RaycastResult* result = GetOrCreateRaycastResult(hitIndex); closestDistance = entry.distance; result->entity = entity; result->component = component; result->pos = ray.GetPoint(closestDistance); result->normal = -ray.dir; result->submesh = 0; result->index = 0; result->u = 0.0f; result->v = 0.0f; result->t = entry.distance; rayHits_.push_back(result); ++hitIndex; } } } } // If several hits, re-sort them in case triangle-level test changed the order if (rayHits_.size() > 1) { qSort(rayHits_.begin(), rayHits_.end(), RaycastResultLessThan()); if (!getAllResults) rayHits_.erase(rayHits_.begin() + 1, rayHits_.end()); } } RaycastResult* OgreWorld::GetOrCreateRaycastResult(size_t index) { while (rayResults_.size() <= index) rayResults_.push_back(new RaycastResult()); return rayResults_[index]; } void OgreWorld::ClearRaycastResults() { // In case of returning only a single result, make sure its entity & component are cleared in case of no hit rayResults_[0]->entity = 0; rayResults_[0]->component = 0; rayResults_[0]->t = FLOAT_INF; rayHits_.clear(); } QList<Entity*> OgreWorld::FrustumQuery(QRect &viewrect) const { PROFILE(OgreWorld_FrustumQuery); QList<Entity*>l; int width = renderer_->WindowWidth(); int height = renderer_->WindowHeight(); if (!width || !height) return l; // Headless Ogre::Camera* camera = VerifyCurrentSceneCamera(); if (!camera) return l; float w= (float)width; float h= (float)height; float left = (float)(viewrect.left()) / w, right = (float)(viewrect.right()) / w; float top = (float)(viewrect.top()) / h, bottom = (float)(viewrect.bottom()) / h; if(left > right) std::swap(left, right); if(top > bottom) std::swap(top, bottom); // don't do selection box is too small if((right - left) * (bottom-top) < 0.0001) return l; Ogre::PlaneBoundedVolumeList volumes; Ogre::PlaneBoundedVolume p = camera->getCameraToViewportBoxVolume(left, top, right, bottom, true); volumes.push_back(p); Ogre::PlaneBoundedVolumeListSceneQuery *query = sceneManager_->createPlaneBoundedVolumeQuery(volumes); assert(query); Ogre::SceneQueryResult results = query->execute(); for(Ogre::SceneQueryResultMovableList::iterator iter = results.movables.begin(); iter != results.movables.end(); ++iter) { Ogre::MovableObject *m = *iter; const Ogre::Any& any = m->getUserAny(); if (any.isEmpty()) continue; Entity *entity = 0; try { IComponent *component = Ogre::any_cast<IComponent*>(any); entity = component ? component->ParentEntity() : 0; } catch(Ogre::InvalidParametersException &/*e*/) { continue; } if(entity) l << entity; } sceneManager_->destroyQuery(query); return l; } bool OgreWorld::IsEntityVisible(Entity* entity) const { EC_Camera* cameraComponent = VerifyCurrentSceneCameraComponent(); if (cameraComponent) return cameraComponent->IsEntityVisible(entity); return false; } QList<Entity*> OgreWorld::VisibleEntities() const { EC_Camera* cameraComponent = VerifyCurrentSceneCameraComponent(); if (cameraComponent) return cameraComponent->VisibleEntities(); return QList<Entity*>(); } void OgreWorld::StartViewTracking(Entity* entity) { if (!entity) { LogError("OgreWorld::StartViewTracking: null entity passed!"); return; } EntityPtr entityPtr = entity->shared_from_this(); for (unsigned i = 0; i < visibilityTrackedEntities_.size(); ++i) { if (visibilityTrackedEntities_[i].lock() == entityPtr) return; // Already added } visibilityTrackedEntities_.push_back(entity->shared_from_this()); } void OgreWorld::StopViewTracking(Entity* entity) { if (!entity) { LogError("OgreWorld::StopViewTracking: null entity passed!"); return; } EntityPtr entityPtr = entity->shared_from_this(); for (unsigned i = 0; i < visibilityTrackedEntities_.size(); ++i) { if (visibilityTrackedEntities_[i].lock() == entityPtr) { visibilityTrackedEntities_.erase(visibilityTrackedEntities_.begin() + i); return; } } } void OgreWorld::OnUpdated(float timeStep) { PROFILE(OgreWorld_OnUpdated); // Do nothing if visibility not being tracked for any entities if (visibilityTrackedEntities_.empty()) { if (!lastVisibleEntities_.empty()) lastVisibleEntities_.clear(); if (!visibleEntities_.empty()) visibleEntities_.clear(); return; } // Update visible objects from the active camera lastVisibleEntities_ = visibleEntities_; EC_Camera* activeCamera = VerifyCurrentSceneCameraComponent(); if (activeCamera) visibleEntities_ = activeCamera->VisibleEntityIDs(); else visibleEntities_.clear(); for (size_t i = visibilityTrackedEntities_.size() - 1; i < visibilityTrackedEntities_.size(); --i) { // Check if the entity has expired; erase from list in that case if (visibilityTrackedEntities_[i].expired()) visibilityTrackedEntities_.erase(visibilityTrackedEntities_.begin() + i); else { Entity* entity = visibilityTrackedEntities_[i].lock().get(); entity_id_t id = entity->Id(); // Check for change in visibility status bool last = lastVisibleEntities_.find(id) != lastVisibleEntities_.end(); bool now = visibleEntities_.find(id) != visibleEntities_.end(); if (!last && now) { emit EntityEnterView(entity); entity->EmitEnterView(activeCamera); } else if (last && !now) { emit EntityLeaveView(entity); entity->EmitLeaveView(activeCamera); } } } } void OgreWorld::SetupShadows() { OgreRenderer::Renderer::ShadowQualitySetting shadowQuality = renderer_->ShadowQuality(); if (shadowQuality == OgreRenderer::Renderer::Shadows_Off) { sceneManager_->setShadowTechnique(Ogre::SHADOWTYPE_NONE); return; } bool pssmEnabled = (shadowQuality == OgreRenderer::Renderer::Shadows_High); unsigned short shadowTextureFSAA = static_cast<unsigned short>(framework_->Config()->Get(ConfigAPI::FILE_FRAMEWORK, ConfigAPI::SECTION_RENDERING, "shadow texture antialias", 0).toInt()); unsigned short shadowTextureSize = static_cast<unsigned short>(framework_->Config()->Get(ConfigAPI::FILE_FRAMEWORK, ConfigAPI::SECTION_RENDERING, "shadow texture size", 2048).toInt()); unsigned short shadowTextureCount = 1; float shadowFarDist = 50; if (pssmEnabled) { shadowTextureSize = static_cast<unsigned short>(framework_->Config()->Get(ConfigAPI::FILE_FRAMEWORK, ConfigAPI::SECTION_RENDERING, "shadow texture size pssm", 1024).toInt()); shadowTextureCount = 3; } LogDebug(QString("[OgreWorld]: Shadow quality : %1").arg((shadowQuality == OgreRenderer::Renderer::Shadows_Low ? "Low" : "High"))); LogDebug(QString("[OgreWorld]: Shadow texture size : %1x%2").arg(shadowTextureSize).arg(shadowTextureSize)); LogDebug(QString("[OgreWorld]: Shadow texture count : %1").arg(shadowTextureCount)); LogDebug(QString("[OgreWorld]: Shadow texture FSAA : %1").arg(shadowTextureFSAA)); /** "rex/ShadowCaster" is the default material to use for shadow buffer rendering pass, can be overridden in user materials. @note We use the same single material (vertex program) for each object, so we're relying on that we use Ogre software skinning. Hardware skinning would require us to do different vertex programs for skinned/nonskinned geometry. */ sceneManager_->setShadowColour(Ogre::ColourValue(0.6f, 0.6f, 0.6f)); sceneManager_->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, shadowTextureCount); sceneManager_->setShadowTechnique(Ogre::SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); sceneManager_->setShadowTextureCasterMaterial("rex/ShadowCaster"); sceneManager_->setShadowTextureSelfShadow(true); sceneManager_->setShadowTextureFSAA(shadowTextureFSAA); /** On DirectX/Windows PF_FLOAT32_R format produces a blue tinted shadow. This occurs at least when the basic "rex/ShadowCaster" is enabled (default for materials). */ #ifdef DIRECTX_ENABLED sceneManager_->setShadowTextureSettings(shadowTextureSize, shadowTextureCount, Ogre::PF_R8G8B8A8); #else sceneManager_->setShadowTextureSettings(shadowTextureSize, shadowTextureCount, Ogre::PF_FLOAT32_R); #endif Ogre::ShadowCameraSetupPtr shadowCameraSetup; if (pssmEnabled) { /** The splitpoints are hardcoded also to the shaders. If you modify these, also change them to the shaders. */ OgreShadowCameraSetupFocusedPSSM::SplitPointList splitpoints; splitpoints.push_back(0.1f); // Default nearclip splitpoints.push_back(3.5); splitpoints.push_back(11); splitpoints.push_back(shadowFarDist); #include "DisableMemoryLeakCheck.h" OgreShadowCameraSetupFocusedPSSM* pssmSetup = new OgreShadowCameraSetupFocusedPSSM(); #include "EnableMemoryLeakCheck.h" pssmSetup->setSplitPoints(splitpoints); shadowCameraSetup = Ogre::ShadowCameraSetupPtr(pssmSetup); } else { #include "DisableMemoryLeakCheck.h" Ogre::FocusedShadowCameraSetup* focusedSetup = new Ogre::FocusedShadowCameraSetup(); #include "EnableMemoryLeakCheck.h" shadowCameraSetup = Ogre::ShadowCameraSetupPtr(focusedSetup); } sceneManager_->setShadowCameraSetup(shadowCameraSetup); sceneManager_->setShadowFarDistance(shadowFarDist); sceneManager_->setShadowCasterRenderBackFaces(false); // If set to true, problems with objects that clip into the ground // Debug overlays for shadow textures /* if(renderer_.expired()) return; Ogre::TexturePtr shadowTex; Ogre::String str("shadowDebug"); Ogre::Overlay* debugOverlay = Ogre::OverlayManager::getSingleton().getByName(str); if (!debugOverlay) debugOverlay= Ogre::OverlayManager::getSingleton().create(str); for(int i = 0; i<shadowTextureCount;i++) { shadowTex = sceneManager_->getShadowTexture(i); // Set up a debug panel to display the shadow Ogre::MaterialPtr debugMat = Ogre::MaterialManager::getSingleton().create( "Ogre/DebugTexture" + Ogre::StringConverter::toString(i), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); Ogre::TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(shadowTex->getName()); t->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP); //t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("spot_shadow_fade.png"); //t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); //t->setColourOperation(LBO_ADD); Ogre::OverlayContainer* debugPanel = (Ogre::OverlayContainer*) (Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i))); debugPanel->_setPosition(0.8, i*0.25+ 0.05); debugPanel->_setDimensions(0.2, 0.24); debugPanel->setMaterialName(debugMat->getName()); debugOverlay->add2D(debugPanel); } debugOverlay->show(); */ bool softShadowEnabled = framework_->Config()->Get(ConfigAPI::FILE_FRAMEWORK, ConfigAPI::SECTION_RENDERING, "soft shadow", false).toBool(); if (softShadowEnabled) { for(size_t i=0;i<shadowTextureCount;i++) { ::GaussianListener* gaussianListener = new GaussianListener(); Ogre::TexturePtr shadowTex = sceneManager_->getShadowTexture(0); Ogre::RenderTarget* shadowRtt = shadowTex->getBuffer()->getRenderTarget(); Ogre::Viewport* vp = shadowRtt->getViewport(0); Ogre::CompositorInstance *instance = Ogre::CompositorManager::getSingleton().addCompositor(vp, "Gaussian Blur"); Ogre::CompositorManager::getSingleton().setCompositorEnabled(vp, "Gaussian Blur", true); instance->addListener(gaussianListener); gaussianListener->notifyViewportSize(vp->getActualWidth(), vp->getActualHeight()); gaussianListeners_.push_back(gaussianListener); } } } Ogre::Camera* OgreWorld::VerifyCurrentSceneCamera() const { EC_Camera* cameraComponent = VerifyCurrentSceneCameraComponent(); return cameraComponent ? cameraComponent->GetCamera() : 0; } EC_Camera* OgreWorld::VerifyCurrentSceneCameraComponent() const { if (!renderer_) return 0; Entity *mainCamera = renderer_->MainCamera(); if (!mainCamera) return 0; EC_Camera *cameraComponent = dynamic_cast<EC_Camera*>(mainCamera->GetComponent<EC_Camera>().get()); if (!cameraComponent) return 0; Entity* entity = cameraComponent->ParentEntity(); if (!entity || entity->ParentScene() != scene_.lock().get()) return 0; return cameraComponent; } bool OgreWorld::IsActive() const { return VerifyCurrentSceneCamera() != 0; } bool OgreWorld::IsDebugInstancingEnabled() const { return drawDebugInstancing_; } bool OgreWorld::IsInstancingStatic(const QString &meshRef) { QString ref = AssetAPI::SanitateAssetRef(framework_->Asset()->ResolveAssetRef("", meshRef)); for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *instancingTarget = instancingTargets_[i]; if (instancingTarget->ref.compare(ref, Qt::CaseSensitive) == 0) return instancingTarget->isStatic; } return false; } bool OgreWorld::SetInstancingStatic(const QString &meshRef, bool _static) { QString ref = AssetAPI::SanitateAssetRef(framework_->Asset()->ResolveAssetRef("", meshRef)); for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *instancingTarget = instancingTargets_[i]; if (instancingTarget->ref.compare(ref, Qt::CaseSensitive) == 0) { instancingTarget->SetBatchesStatic(_static); return true; } } return false; } void OgreWorld::SetDebugInstancingEnabled(bool enabled) { drawDebugInstancing_ = enabled; for (int i=0; i<instancingTargets_.size(); ++i) { MeshInstanceTarget *instancingTarget = instancingTargets_[i]; instancingTarget->SetDebuggingEnabled(enabled); } } void OgreWorld::DebugDrawAABB(const AABB &aabb, const Color &clr, bool depthTest) { for(int i = 0; i < 12; ++i) DebugDrawLineSegment(aabb.Edge(i), clr, depthTest); } void OgreWorld::DebugDrawOBB(const OBB &obb, const Color &clr, bool depthTest) { for(int i = 0; i < 12; ++i) DebugDrawLineSegment(obb.Edge(i), clr, depthTest); } void OgreWorld::DebugDrawLineSegment(const LineSegment &l, const Color &clr, bool depthTest) { if (depthTest) { if (debugLines_) debugLines_->addLine(l.a, l.b, clr); } else { if (debugLinesNoDepth_) debugLinesNoDepth_->addLine(l.a, l.b, clr); } } void OgreWorld::DebugDrawLine(const float3& start, const float3& end, const Color &clr, bool depthTest) { if (depthTest) { if (debugLines_) debugLines_->addLine(start, end, clr); } else { if (debugLinesNoDepth_) debugLinesNoDepth_->addLine(start, end, clr); } } void OgreWorld::DebugDrawPlane(const Plane &plane, const Color &clr, const float3 &refPoint, float uSpacing, float vSpacing, int uSegments, int vSegments, bool depthTest) { float U0 = -uSegments * uSpacing / 2.f; float V0 = -vSegments * vSpacing / 2.f; float U1 = uSegments * uSpacing / 2.f; float V1 = vSegments * vSpacing / 2.f; for(int y = 0; y < vSegments; ++y) for(int x = 0; x < uSegments; ++x) { float u = U0 + x * uSpacing; float v = V0 + y * vSpacing; DebugDrawLine(plane.Point(U0, v, refPoint), plane.Point(U1, v, refPoint), clr, depthTest); DebugDrawLine(plane.Point(u, V0, refPoint), plane.Point(u, V1, refPoint), clr, depthTest); } } void OgreWorld::DebugDrawTransform(const Transform &t, float axisLength, float boxSize, const Color &clr, bool depthTest) { DebugDrawFloat3x4(t.ToFloat3x4(), axisLength, boxSize, clr, depthTest); } void OgreWorld::DebugDrawFloat3x4(const float3x4 &t, float axisLength, float boxSize, const Color &clr, bool depthTest) { AABB aabb(float3::FromScalar(-boxSize/2.f), float3::FromScalar(boxSize/2.f)); OBB obb = aabb.Transform(t); DebugDrawOBB(obb, clr); DebugDrawLineSegment(LineSegment(t.TranslatePart(), t.TranslatePart() + axisLength * t.Col(0)), 1, 0, 0, depthTest); DebugDrawLineSegment(LineSegment(t.TranslatePart(), t.TranslatePart() + axisLength * t.Col(1)), 0, 1, 0, depthTest); DebugDrawLineSegment(LineSegment(t.TranslatePart(), t.TranslatePart() + axisLength * t.Col(2)), 0, 0, 1, depthTest); } void OgreWorld::DebugDrawCircle(const Circle &c, int numSubdivisions, const Color &clr, bool depthTest) { float3 p = c.GetPoint(0); for(int i = 1; i <= numSubdivisions; ++i) { float3 p2 = c.GetPoint(i * 2.f * 3.14f / numSubdivisions); DebugDrawLineSegment(LineSegment(p, p2), clr, depthTest); p = p2; } } void OgreWorld::DebugDrawAxes(const float3x4 &t, bool depthTest) { float3 translate, scale; Quat rotate; t.Decompose(translate, rotate, scale); DebugDrawLine(translate, translate + rotate * float3(scale.x, 0.f, 0.f), 1, 0, 0, depthTest); DebugDrawLine(translate, translate + rotate * float3(0., scale.y, 0.f), 0, 1, 0, depthTest); DebugDrawLine(translate, translate + rotate * float3(0.f, 0.f, scale.z), 0, 0, 1, depthTest); } void OgreWorld::DebugDrawSphere(const float3& center, float radius, int vertices, const Color &clr, bool depthTest) { if (vertices <= 0) return; std::vector<float3> positions(vertices); Sphere sphere(center, radius); int actualVertices = sphere.Triangulate(&positions[0], 0, 0, vertices, true); for (int i = 0; i < actualVertices; i += 3) { DebugDrawLine(positions[i], positions[i + 1], clr, depthTest); DebugDrawLine(positions[i + 1], positions[i + 2], clr, depthTest); DebugDrawLine(positions[i + 2], positions[i], clr, depthTest); } } void OgreWorld::DebugDrawLight(const float3x4 &t, int lightType, float range, float spotAngle, const Color &clr, bool depthTest) { float3 translate, scale; Quat rotate; t.Decompose(translate, rotate, scale); float3 lightDirection = rotate * float3(0.0f, 0.0f, 1.0f); switch (lightType) { // Point case 0: DebugDrawCircle(Circle(translate, float3(1.f, 0.f, 0.f), range), 8, clr, depthTest); DebugDrawCircle(Circle(translate, float3(0.f, 1.f, 0.f), range), 8, clr, depthTest); DebugDrawCircle(Circle(translate, float3(0.f, 0.f, 1.f), range), 8, clr, depthTest); break; // Spot case 1: { float3 endPoint = translate + range * lightDirection; float coneRadius = range * sinf(DegToRad(spotAngle)); Circle spotCircle(endPoint, -lightDirection, coneRadius); DebugDrawCircle(Circle(endPoint, -lightDirection, coneRadius), 8, clr, depthTest); for (int i = 1; i <= 8; ++i) DebugDrawLine(translate, spotCircle.GetPoint(i * 2.f * 3.14f / 8), clr, depthTest); } break; // Directional case 2: { const float cDirLightRange = 10.f; float3 endPoint = translate + cDirLightRange * lightDirection; float3 offset = rotate * float3(1.f, 0.f, 0.f); DebugDrawLine(translate, endPoint, clr, depthTest); DebugDrawLine(translate + offset, endPoint + offset, clr, depthTest); DebugDrawLine(translate - offset, endPoint - offset, clr, depthTest); } break; } } void OgreWorld::DebugDrawCamera(const float3x4 &t, float size, const Color &clr, bool depthTest) { AABB aabb(float3(-size/2.f, -size/2.f, -size), float3(size/2.f, size/2.f, size)); OBB obb = aabb.Transform(t); DebugDrawOBB(obb, clr, depthTest); float3 translate(0, 0, -size * 1.25f); AABB aabb2(translate + float3::FromScalar(-size/4.f), translate + float3::FromScalar(size/4.f)); OBB obb2 = aabb2.Transform(t); DebugDrawOBB(obb2, clr, depthTest); } void OgreWorld::DebugDrawSoundSource(const float3 &soundPos, float soundInnerRadius, float soundOuterRadius, const Color &clr, bool depthTest) { // Draw three concentric diamonds as a visual cue for(int i = 2; i < 5; ++i) DebugDrawSphere(soundPos, i/3.f, 24, i==2?1:0, i==3?1:0, i==4?1:0, depthTest); DebugDrawSphere(soundPos, soundInnerRadius, 24*3*3*3, 1, 0, 0, depthTest); DebugDrawSphere(soundPos, soundOuterRadius, 24*3*3*3, 0, 1, 0, depthTest); } /// MeshInstanceTarget MeshInstanceTarget::MeshInstanceTarget(const QString &_ref, uint _batchSize, bool _static) : ref(_ref), batchSize(_batchSize), isStatic(_static), optimizationTimer_(new QTimer()) { optimizationTimer_->setSingleShot(true); connect(optimizationTimer_, SIGNAL(timeout()), SLOT(OptimizeBatches())); } MeshInstanceTarget::~MeshInstanceTarget() { SAFE_DELETE(optimizationTimer_); } Ogre::InstancedEntity *MeshInstanceTarget::CreateInstance(Ogre::SceneManager *sceneManager, int submesh, const QString &material, Ogre::InstancedEntity *parent) { PROFILE(OgreWorld_MeshInstanceTarget_CreateInstance); if (!sceneManager) throw ::Exception("Cannot create instances with null Ogre::SceneManager!"); ManagerTarget *managerTarget = 0; foreach(ManagerTarget *target, managers) { if (target->submesh == submesh) { managerTarget = target; break; } } if (!managerTarget) { managerTarget = new ManagerTarget(submesh); managerTarget->manager = sceneManager->createInstanceManager(QString("InstanceManager_%1_%2").arg(ref).arg(submesh).toStdString(), ref.toStdString(), Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, Ogre::InstanceManager::HWInstancingBasic, static_cast<size_t>(batchSize), Ogre::IM_USEALL, submesh); managers << managerTarget; } Ogre::InstancedEntity *instance = managerTarget->manager->createInstancedEntity(material.toStdString()); if (!instance) throw ::Exception("Failed to create instance for an unknown reason."); if (parent) parent->shareTransformWith(instance); managerTarget->changed = true; managerTarget->instances << QPair<Ogre::InstancedEntity*, Ogre::InstancedEntity*>(instance, parent); InvokeOptimizations(); return instance; } bool MeshInstanceTarget::Contains(const Ogre::InstancedEntity *instance) { for (int k=0; k<managers.size(); ++k) { ManagerTarget *manager = managers[k]; for (int i=0; i<manager->instances.size(); ++i) if (manager->instances[i].first == instance) return true; } return false; } QList<Ogre::InstancedEntity*> MeshInstanceTarget::Instances() const { QList<Ogre::InstancedEntity*> _intances; for (int k=0; k<managers.size(); ++k) { ManagerTarget *manager = managers[k]; for (int i=0; i<manager->instances.size(); ++i) _intances << manager->instances[i].first; } return _intances; } QList<Ogre::InstancedEntity*> MeshInstanceTarget::Parents() const { QList<Ogre::InstancedEntity*> _intances; for (int k=0; k<managers.size(); ++k) { ManagerTarget *manager = managers[k]; for (int i=0; i<manager->instances.size(); ++i) { // Parent is null, means this are a parent instance. if (!manager->instances[i].second) _intances << manager->instances[i].first; } } return _intances; } QList<Ogre::InstancedEntity*> MeshInstanceTarget::Children(const Ogre::InstancedEntity *parent) const { QList<Ogre::InstancedEntity*> children; for (int k=0; k<managers.size(); ++k) { ManagerTarget *manager = managers[k]; for (int i=0; i<manager->instances.size(); ++i) { const QPair<Ogre::InstancedEntity*, Ogre::InstancedEntity*> &instancePair = manager->instances[i]; if (instancePair.second == parent) children << instancePair.first; } } return children; } bool MeshInstanceTarget::DestroyInstance(Ogre::SceneManager *sceneManager, Ogre::InstancedEntity* instance) { PROFILE(OgreWorld_MeshInstanceTarget_ForgetInstance); bool found = false; for (int k=0; k<managers.size(); ++k) { ManagerTarget *manager = managers.at(k); for (int i=0; i<manager->instances.size(); ++i) { // 1) This is the instance we are looking for 2) The instance is a parent for this instance. const QPair<Ogre::InstancedEntity*, Ogre::InstancedEntity*> &instancePair = manager->instances.at(i); if (instancePair.first == instance || instancePair.second == instance) { sceneManager->destroyInstancedEntity(instancePair.first); manager->instances.removeAt(i); --i; found = true; } } if (found) { if (manager->instances.isEmpty()) { if (manager->manager) sceneManager->destroyInstanceManager(manager->manager); manager->manager = 0; managers.removeAt(k); SAFE_DELETE(manager); --k; } } } if (found && managers.size() > 0) InvokeOptimizations(); return found; } void MeshInstanceTarget::InvokeOptimizations(int optimizeAfterMsec) { if (managers.size() == 0) return; /** This timer waits for 5 seconds of rest before running optimizations to the managers batches. We don't want to be running these eg. after each instance creation as it would produce lots of resize/allocations in the target batches. It's best to do them after a big number or creations/deletions. */ if (optimizationTimer_->isActive()) optimizationTimer_->stop(); optimizationTimer_->start(optimizeAfterMsec); } void MeshInstanceTarget::OptimizeBatches() { PROFILE(OgreWorld_MeshInstanceTarget_OptimizeBatches); foreach(ManagerTarget *managerTarget, managers) { if (managerTarget->changed && !managerTarget->instances.isEmpty() && managerTarget->manager) { managerTarget->manager->cleanupEmptyBatches(); managerTarget->manager->defragmentBatches(true); managerTarget->manager->setBatchesAsStaticAndUpdate(isStatic); managerTarget->changed = false; } } } void MeshInstanceTarget::SetBatchesStatic(bool _static) { PROFILE(OgreWorld_MeshInstanceTarget_SetBatchesStatic); if (isStatic == _static) return; isStatic = _static; if (!optimizationTimer_->isActive()) { foreach(ManagerTarget *managerTarget, managers) if (managerTarget->manager) managerTarget->manager->setBatchesAsStaticAndUpdate(isStatic); } } void MeshInstanceTarget::SetDebuggingEnabled(bool enabled, const QString &material) { PROFILE(OgreWorld_MeshInstanceTarget_SetDebuggingEnabled); foreach(ManagerTarget *managerTarget, managers) if (managerTarget->manager) managerTarget->manager->setSetting(Ogre::InstanceManager::SHOW_BOUNDINGBOX, enabled, material.toStdString()); }
38.126994
214
0.627065
[ "mesh", "geometry", "object", "vector", "transform", "3d" ]
07e5e70e3e8bd8dde491f3671cc847f0e13dc3ca
10,486
cc
C++
zircon/system/utest/fdio/fdio_get_vmo.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
zircon/system/utest/fdio/fdio_get_vmo.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
zircon/system/utest/fdio/fdio_get_vmo.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
null
null
null
// 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 <cstdlib> #include <fbl/unique_fd.h> #include <fuchsia/io/c/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/fdio/fd.h> #include <lib/fdio/io.h> #include <lib/fidl-async/bind.h> #include <lib/zx/channel.h> #include <lib/zx/vmo.h> #include <zircon/limits.h> #include <algorithm> #include <string> #include <zxtest/zxtest.h> namespace { struct Context { zx::vmo vmo; bool is_vmofile; bool supports_read_at; bool supports_seek; bool supports_get_buffer; size_t content_size; // Must be <= ZX_PAGE_SIZE. uint32_t last_flags; }; zx_status_t FileClone(void* ctx, uint32_t flags, zx_handle_t object) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileClose(void* ctx, fidl_txn_t* txn) { return fuchsia_io_NodeClose_reply(txn, ZX_OK); } zx_status_t FileDescribe(void* ctx, fidl_txn_t* txn) { Context* context = reinterpret_cast<Context*>(ctx); fuchsia_io_NodeInfo info; memset(&info, 0, sizeof(info)); if (context->is_vmofile) { zx::vmo vmo; zx_status_t status = context->vmo.duplicate(ZX_RIGHTS_BASIC | ZX_RIGHT_MAP | ZX_RIGHT_READ, &vmo); if (status != ZX_OK) { return status; } info.tag = fuchsia_io_NodeInfoTag_vmofile; info.vmofile.vmo = vmo.release(); info.vmofile.offset = 0; info.vmofile.length = context->content_size; } else { info.tag = fuchsia_io_NodeInfoTag_file; } return fuchsia_io_NodeDescribe_reply(txn, &info); } zx_status_t FileSync(void* ctx, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileGetAttr(void* ctx, fidl_txn_t* txn) { Context* context = reinterpret_cast<Context*>(ctx); fuchsia_io_NodeAttributes attributes = {}; attributes.id = 5; attributes.content_size = context->content_size; attributes.storage_size = ZX_PAGE_SIZE; attributes.link_count = 1; return fuchsia_io_NodeGetAttr_reply(txn, ZX_OK, &attributes); } zx_status_t FileSetAttr(void* ctx, uint32_t flags, const fuchsia_io_NodeAttributes* attributes, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileIoctl(void* ctx, uint32_t opcode, uint64_t max_out, const zx_handle_t* handles_data, size_t handles_count, const uint8_t* in_data, size_t in_count, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileRead(void* ctx, uint64_t count, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileReadAt(void* ctx, uint64_t count, uint64_t offset, fidl_txn_t* txn) { Context* context = reinterpret_cast<Context*>(ctx); if (!context->supports_read_at) { return ZX_ERR_NOT_SUPPORTED; } if (offset >= context->content_size) { return fuchsia_io_FileRead_reply(txn, ZX_OK, nullptr, 0); } size_t actual = std::min(count, context->content_size - offset); uint8_t buffer[ZX_PAGE_SIZE]; zx_status_t status = context->vmo.read(buffer, offset, actual); if (status != ZX_OK) { return fuchsia_io_FileRead_reply(txn, status, nullptr, 0); } return fuchsia_io_FileRead_reply(txn, ZX_OK, buffer, actual); } zx_status_t FileWrite(void* ctx, const uint8_t* data_data, size_t data_count, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileWriteAt(void* ctx, const uint8_t* data_data, size_t data_count, uint64_t offset, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileSeek(void* ctx, int64_t offset, fuchsia_io_SeekOrigin start, fidl_txn_t* txn) { Context* context = reinterpret_cast<Context*>(ctx); if (!context->supports_seek) { return ZX_ERR_NOT_SUPPORTED; } return fuchsia_io_FileSeek_reply(txn, ZX_OK, 0); } zx_status_t FileTruncate(void* ctx, uint64_t length, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileGetFlags(void* ctx, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileSetFlags(void* ctx, uint32_t flags, fidl_txn_t* txn) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t FileGetBuffer(void* ctx, uint32_t flags, fidl_txn_t* txn) { Context* context = reinterpret_cast<Context*>(ctx); context->last_flags = flags; if (!context->supports_get_buffer) { return fuchsia_io_FileGetBuffer_reply(txn, ZX_ERR_NOT_SUPPORTED, nullptr); } fuchsia_mem_Buffer buffer; memset(&buffer, 0, sizeof(buffer)); buffer.size = context->content_size; zx_status_t status = ZX_OK; zx::vmo result; if (flags & fuchsia_io_VMO_FLAG_PRIVATE) { status = context->vmo.create_child(ZX_VMO_CHILD_COPY_ON_WRITE, 0, ZX_PAGE_SIZE, &result); } else { status = context->vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &result); } if (status != ZX_OK) { return fuchsia_io_FileGetBuffer_reply(txn, status, nullptr); } buffer.vmo = result.release(); return fuchsia_io_FileGetBuffer_reply(txn, ZX_OK, &buffer); } constexpr fuchsia_io_File_ops_t kFileOps = [] { fuchsia_io_File_ops_t ops = {}; ops.Clone = FileClone; ops.Close = FileClose; ops.Describe = FileDescribe; ops.Sync = FileSync; ops.GetAttr = FileGetAttr; ops.SetAttr = FileSetAttr; ops.Ioctl = FileIoctl; ops.Read = FileRead; ops.ReadAt = FileReadAt; ops.Write = FileWrite; ops.WriteAt = FileWriteAt; ops.Seek = FileSeek; ops.Truncate = FileTruncate; ops.GetFlags = FileGetFlags; ops.SetFlags = FileSetFlags; ops.GetBuffer = FileGetBuffer; return ops; }(); zx_koid_t get_koid(zx_handle_t handle) { zx_info_handle_basic_t info; zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); return status == ZX_OK ? info.koid : ZX_KOID_INVALID; } bool vmo_starts_with(const zx::vmo& vmo, const char* string) { size_t length = strlen(string); if (length > ZX_PAGE_SIZE) { return false; } char buffer[ZX_PAGE_SIZE]; zx_status_t status = vmo.read(buffer, 0, sizeof(buffer)); if (status != ZX_OK) { return false; } return strncmp(string, buffer, length) == 0; } TEST(GetVMOTest, Remote) { async::Loop loop(&kAsyncLoopConfigNoAttachToThread); ASSERT_OK(loop.StartThread("fake-filesystem")); async_dispatcher_t* dispatcher = loop.dispatcher(); zx::channel client, server; ASSERT_OK(zx::channel::create(0, &client, &server)); Context context = {}; context.is_vmofile = false; context.content_size = 43; context.supports_get_buffer = true; ASSERT_OK(zx::vmo::create(ZX_PAGE_SIZE, 0, &context.vmo)); ASSERT_OK(context.vmo.write("abcd", 0, 4)); ASSERT_OK(fidl_bind(dispatcher, server.release(), reinterpret_cast<fidl_dispatch_t*>(fuchsia_io_File_dispatch), &context, &kFileOps)); int raw_fd = -1; ASSERT_OK(fdio_fd_create(client.release(), &raw_fd)); fbl::unique_fd fd(raw_fd); zx::vmo received; ASSERT_OK(fdio_get_vmo_exact(fd.get(), received.reset_and_get_address())); ASSERT_EQ(get_koid(context.vmo.get()), get_koid(received.get())); ASSERT_EQ(fuchsia_io_VMO_FLAG_READ | fuchsia_io_VMO_FLAG_EXACT, context.last_flags); context.last_flags = 0; ASSERT_OK(fdio_get_vmo_clone(fd.get(), received.reset_and_get_address())); ASSERT_NE(get_koid(context.vmo.get()), get_koid(received.get())); ASSERT_EQ(fuchsia_io_VMO_FLAG_READ | fuchsia_io_VMO_FLAG_PRIVATE, context.last_flags); ASSERT_TRUE(vmo_starts_with(received, "abcd")); context.last_flags = 0; ASSERT_OK(fdio_get_vmo_copy(fd.get(), received.reset_and_get_address())); ASSERT_NE(get_koid(context.vmo.get()), get_koid(received.get())); ASSERT_EQ(fuchsia_io_VMO_FLAG_READ | fuchsia_io_VMO_FLAG_PRIVATE, context.last_flags); ASSERT_TRUE(vmo_starts_with(received, "abcd")); context.last_flags = 0; context.supports_get_buffer = false; context.supports_read_at = true; ASSERT_OK(fdio_get_vmo_copy(fd.get(), received.reset_and_get_address())); ASSERT_NE(get_koid(context.vmo.get()), get_koid(received.get())); ASSERT_EQ(fuchsia_io_VMO_FLAG_READ | fuchsia_io_VMO_FLAG_PRIVATE, context.last_flags); ASSERT_TRUE(vmo_starts_with(received, "abcd")); context.last_flags = 0; } TEST(GetVMOTest, VMOFile) { async::Loop loop(&kAsyncLoopConfigNoAttachToThread); ASSERT_OK(loop.StartThread("fake-filesystem")); async_dispatcher_t* dispatcher = loop.dispatcher(); zx::channel client, server; ASSERT_OK(zx::channel::create(0, &client, &server)); Context context = {}; context.content_size = 43; context.is_vmofile = true; context.supports_seek = true; ASSERT_OK(zx::vmo::create(ZX_PAGE_SIZE, 0, &context.vmo)); ASSERT_OK(context.vmo.write("abcd", 0, 4)); ASSERT_OK(fidl_bind(dispatcher, server.release(), reinterpret_cast<fidl_dispatch_t*>(fuchsia_io_File_dispatch), &context, &kFileOps)); int raw_fd = -1; ASSERT_OK(fdio_fd_create(client.release(), &raw_fd)); fbl::unique_fd fd(raw_fd); context.supports_seek = false; zx::vmo received; ASSERT_EQ(ZX_ERR_NOT_FOUND, fdio_get_vmo_exact(fd.get(), received.reset_and_get_address())); ASSERT_OK(fdio_get_vmo_clone(fd.get(), received.reset_and_get_address())); ASSERT_NE(get_koid(context.vmo.get()), get_koid(received.get())); ASSERT_TRUE(vmo_starts_with(received, "abcd")); ASSERT_OK(fdio_get_vmo_copy(fd.get(), received.reset_and_get_address())); ASSERT_NE(get_koid(context.vmo.get()), get_koid(received.get())); ASSERT_TRUE(vmo_starts_with(received, "abcd")); } TEST(GetVMOTest, VMOFilePage) { async::Loop loop(&kAsyncLoopConfigNoAttachToThread); ASSERT_OK(loop.StartThread("fake-filesystem")); async_dispatcher_t* dispatcher = loop.dispatcher(); zx::channel client, server; ASSERT_OK(zx::channel::create(0, &client, &server)); Context context = {}; context.content_size = ZX_PAGE_SIZE; context.is_vmofile = true; context.supports_seek = true; ASSERT_OK(zx::vmo::create(ZX_PAGE_SIZE, 0, &context.vmo)); ASSERT_OK(context.vmo.write("abcd", 0, 4)); ASSERT_OK(fidl_bind(dispatcher, server.release(), reinterpret_cast<fidl_dispatch_t*>(fuchsia_io_File_dispatch), &context, &kFileOps)); int raw_fd = -1; ASSERT_OK(fdio_fd_create(client.release(), &raw_fd)); fbl::unique_fd fd(raw_fd); context.supports_seek = false; zx::vmo received; ASSERT_OK(fdio_get_vmo_exact(fd.get(), received.reset_and_get_address())); ASSERT_EQ(get_koid(context.vmo.get()), get_koid(received.get())); } } // namespace
33.501597
100
0.726302
[ "object" ]
07ebcdbdc84f8fd2c52b23c46e1873780d457871
111,889
cpp
C++
src/services/config/events.cpp
dfranusic/mink-core
98b4ab8d6322a5593ab6c05132473753915a3bb8
[ "MIT" ]
1
2022-01-28T22:29:14.000Z
2022-01-28T22:29:14.000Z
src/services/config/events.cpp
dfranusic/mink-core
98b4ab8d6322a5593ab6c05132473753915a3bb8
[ "MIT" ]
28
2021-08-31T09:27:36.000Z
2022-03-17T13:57:56.000Z
src/services/config/events.cpp
dfranusic/mink-core
98b4ab8d6322a5593ab6c05132473753915a3bb8
[ "MIT" ]
5
2021-08-25T13:20:39.000Z
2022-01-27T18:04:15.000Z
/* _ _ * _ __ ___ (_)_ __ | | __ * | '_ ` _ \| | '_ \| |/ / * | | | | | | | | | | < * |_| |_| |_|_|_| |_|_|\_\ * * SPDX-License-Identifier: MIT * */ #include <antlr_utils.h> #include <events.h> #include <fstream> void ClientIdle::run(gdt::GDTCallbackArgs *args) { // * unlock to avoid deadlock // * could happen if client stream was interrupted and not properly closed // * if this client did not previously call lock(), unlock() method will // fail silently config->unlock(); } ClientDown::ClientDown(config::Config *_config) :config(_config) {} void ClientDown::run(gdt::GDTCallbackArgs *args) { // * unlock to avoid deadlock // * could happen if client stream was interrupted and not properly closed // * if this client did not previously call lock(), unlock() method will // fail silently config->unlock(); } ClientDone::ClientDone(config::Config *_config) : config(_config) {} void ClientDone::run(gdt::GDTCallbackArgs *args) { // nothing to do for now } void NewClient::run(gdt::GDTCallbackArgs *args) { auto client = (gdt::GDTClient *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_CLIENT); // handle new stream event for current client client->set_callback(gdt::GDT_ET_STREAM_NEW, &new_stream); // handle client idle client->set_callback(gdt::GDT_ET_CLIENT_IDLE, &client_idle); } NewClient::NewClient(config::Config *_config) : config(_config){ new_stream.config = config; client_idle.config = _config; } void StreamDone::run(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); auto snext = static_cast<StreamNext *>(stream->get_callback(gdt::GDT_ET_STREAM_NEXT)); gdt::GDTClient *client = stream->get_client(); // notifications if (!ntfy_lst.empty()) { for (unsigned int i = 0; i < ntfy_lst.size(); i++) { // gdt notification auto gdtn = (config::GDTCfgNotification *)ntfy_lst[i]; // notify all users unsigned int j = 0; while (j < gdtn->get_user_count()) { // check if client is still active if (client->get_session()->get_client(gdtn->get_user(j)->gdtc)) { // check if ready to send if (gdtn->ready) { config::notify_user(snext->new_stream->config, &gdtn->ntf_cfg_lst, gdtn->get_user(j), gdtn); } // next ++j; // client terminated, remove notification } else { gdtn->unreg_user(gdtn->get_user(j)); } } // clear and deallocate ntf cfg node list std::all_of(gdtn->ntf_cfg_lst.children.cbegin(), gdtn->ntf_cfg_lst.children.cend(), [](const config::ConfigItem *c) { delete c; return true; }); gdtn->ntf_cfg_lst.children.clear(); gdtn->ready = false; } // clear notification list ntfy_lst.clear(); } // unlock config mutex snext->new_stream->config->unlock(); // deallocate NewStream, allocated in NewStream::run // clear ac res list or it will be deallocated (big no no) snext->new_stream->ac_res.children.clear(); // clear tmp list std::all_of(snext->new_stream->tmp_node_lst.children.cbegin(), snext->new_stream->tmp_node_lst.children.cend(), [](const config::ConfigItem *c) { delete c; return true; }); snext->new_stream->tmp_node_lst.children.clear(); // free new stream delete snext->new_stream; } NewStream::NewStream() : config(nullptr), config_action(-1), tmp_size(0), res_size(0), error_count(0), res_index(0), err_index(0), ac_res_count(0), last_found(nullptr), cm_mode(config::CONFIG_MT_UNKNOWN), ac_mode(config::CONFIG_ACM_TAB), line_stream_lc(0), ca_cfg_result(asn1::ConfigAction::_ca_cfg_result) { stream_next.cfg_res = nullptr; stream_next.new_stream = nullptr; pt_mink_config_ac_line = htobe32(asn1::ParameterType::_pt_mink_config_ac_line); pt_mink_config_ac_err_count = htobe32(asn1::ParameterType::_pt_mink_config_ac_err_count); pt_mink_config_cli_path = htobe32(asn1::ParameterType::_pt_mink_config_cli_path); pt_mink_config_cfg_line_count = htobe32(asn1::ParameterType::_pt_mink_config_cfg_line_count); pt_cfg_item_cm_mode = htobe32(asn1::ParameterType::_pt_mink_config_cfg_cm_mode); } int NewStream::get_cfg_uid(config::UserId *usr_id, asn1::GDTMessage *in_msg, int sess_id) const { // null check if (usr_id == nullptr || in_msg == nullptr) return 1; // check for body if (!in_msg->_body) return 1; // check for config message if (!in_msg->_body->_conf->has_linked_data(sess_id)) return 1; // check for params part if (!in_msg->_body->_conf->_params) return 1; if (!in_msg->_body->_conf->_params->has_linked_data(sess_id)) return 1; asn1::ConfigMessage *c = in_msg->_body->_conf; asn1::Parameters *p = c->_params; // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for current session if (!p->get_child(i)->has_linked_data(sess_id)) continue; // check for value if (!p->get_child(i)) continue; // check if value exists in current session if (!p->get_child(i)->_value->has_linked_data(sess_id)) continue; // check if child exists if (!p->get_child(i)->_value->get_child(0)) continue; // check if child exists in current // sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(sess_id)) continue; // check param id, convert from big endian to host auto param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // set tmp values auto tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; unsigned int tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // match param switch (be32toh(*param_id)) { // config user auth id case asn1::ParameterType::_pt_mink_auth_id: // user id - user auth id if (tmp_val_l <= sizeof(usr_id->user_id)) memcpy(usr_id->user_id, tmp_val, tmp_val_l); // ok return 0; default: break; } } // err return 1; } void NewStream::run(gdt::GDTCallbackArgs *args) { auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); // create new instance of NewStream (think of it as forking) auto new_stream = new NewStream(); new_stream->config = config; new_stream->stream_next.cfg_res = &new_stream->ac_res; new_stream->stream_next.new_stream = new_stream; // set cfg user id pointer config::UserId *new_cfg_usr_id = &new_stream->cfg_user_id; const asn1::ConfigMessage *c = nullptr; // set events stream->set_callback(gdt::GDT_ET_STREAM_NEXT, &new_stream->stream_next); stream->set_callback(gdt::GDT_ET_STREAM_END, &new_stream->stream_done); stream->set_callback(gdt::GDT_ET_STREAM_TIMEOUT, &new_stream->stream_done); // create cfg user id if (get_cfg_uid(new_cfg_usr_id, in_msg, *in_sess) > 0) { stream->end_sequence(); return; } // check for body if (!in_msg->_body) { stream->end_sequence(); return; } // check for ConfigMessage if (!in_msg->_body->_conf->has_linked_data(*in_sess)) { stream->end_sequence(); return; } c = in_msg->_body->_conf; // User login if (c->_action ->linked_node ->tlv ->value[0] == asn1::ConfigAction::_ca_cfg_user_login) { new_stream->config_action = asn1::ConfigAction::_ca_cfg_user_login; // lock config mutex config->lock(); // set new user auto usr_info = new config::UserInfo(config->get_definition_root()); config->set_definition_wn(new_cfg_usr_id, usr_info); // process new_stream->process_user_login(args); // User logout } else if (c->_action ->linked_node ->tlv ->value[0] == asn1::ConfigAction::_ca_cfg_user_logout) { new_stream->config_action = asn1::ConfigAction::_ca_cfg_user_logout; // lock config mutex config->lock(); // process new_stream->process_user_logout(args); // AC mode (TAB mode in CLI) } else if (c->_action ->linked_node ->tlv ->value[0] == asn1::ConfigAction::_ca_cfg_ac) { new_stream->ac_mode = config::CONFIG_ACM_TAB; new_stream->config_action = asn1::ConfigAction::_ca_cfg_ac; // lock config mutex config->lock(); // check is user id exists config->update_definition_wn(new_cfg_usr_id); // process new_stream->process_tab(args); // SET mode (ENTER mode in CLI) } else if (c->_action ->linked_node ->tlv ->value[0] == asn1::ConfigAction::_ca_cfg_set) { new_stream->ac_mode = config::CONFIG_ACM_ENTER; new_stream->config_action = asn1::ConfigAction::_ca_cfg_set; // lock config mutex config->lock(); // check is user id exists config->update_definition_wn(new_cfg_usr_id); // process new_stream->process_enter(args); // GET mode } else if (c->_action ->linked_node ->tlv ->value[0] == asn1::ConfigAction::_ca_cfg_get) { new_stream->config_action = asn1::ConfigAction::_ca_cfg_get; // lock config mutex config->lock(); // check is user id exists config->update_definition_wn(new_cfg_usr_id); // process new_stream->process_get(args); // REPLICATE mode (action from other config daemon) } else if (c->_action ->linked_node ->tlv ->value[0] == asn1::ConfigAction::_ca_cfg_replicate) { new_stream->config_action = asn1::ConfigAction::_ca_cfg_replicate; // lock config mutex config->lock(); // check is user id exists config->update_definition_wn(new_cfg_usr_id); // process new_stream->process_replicate(args); } else stream->end_sequence(); } void NewStream::process_user_logout(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); // check if current user started transaction bool pretend = (config->get_transaction_owner() != cfg_user_id && config->transaction_started() ? true : false); if (!pretend) { // discard changes config->discard(config->get_definition_root()); // end transaction config->end_transaction(); } // remove user config->remove_wn_user(&cfg_user_id); // nothing more to do stream->end_sequence(); } void NewStream::process_user_login(gdt::GDTCallbackArgs *args) const { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); // nothing more to do stream->end_sequence(); } // new stream, start sending config tree void NewStream::process_replicate(gdt::GDTCallbackArgs *args) { auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); tmp_size = 0; res_size = 0; error_count = 0; err_index = -1; last_found = nullptr; res_index = 0; ac_res.children.clear(); char *tmp_val = nullptr; int tmp_val_l = 0; line.clear(); cm_mode = config::CONFIG_MT_UNKNOWN; asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; // check for body if (!in_msg->_body) goto process_lines; // check for config message if (!in_msg->_body->_conf->has_linked_data(*in_sess)) goto process_lines; c = in_msg->_body->_conf; // check for GET action if (c->_action ->linked_node ->tlv ->value[0] != asn1::ConfigAction::_ca_cfg_replicate) goto process_lines; // check for params part if (!c->_params) goto process_lines; if (!c->_params->has_linked_data(*in_sess)) goto process_lines; p = c->_params; // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for current session if (!p->get_child(i)->has_linked_data(*in_sess)) continue; // check for value if (!p->get_child(i)->_value) continue; // check if value exists in current session if (!p->get_child(i) ->_value ->has_linked_data(*in_sess)) continue; // check if child exists if (!p->get_child(i)->_value->get_child(0)) continue; // check if child exists in current // sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // check param id, convert from big endian to // host auto param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // set tmp values tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // match param switch (be32toh(*param_id)) { // config item path case asn1::ParameterType::_pt_mink_config_replication_line: line.append(tmp_val, tmp_val_l); break; default: break; } } process_lines: // check if replication line was received if (line.size() == 0) return; // check if replication line was received // tokenize mink_utils::tokenize(&line, tmp_lst, 50, &tmp_size, true); // check for transaction owner bool pretend = (config->get_transaction_owner() != cfg_user_id && config->transaction_started() ? true : false); // auto complete config->auto_complete(&cm_mode, config::CONFIG_ACM_ENTER, config->get_cmd_tree(), config->get_definition_wn(&cfg_user_id)->wnode, tmp_lst, tmp_size, &ac_res, &res_size, &last_found, &error_count, tmp_err, pretend, &tmp_node_lst); // process results if (ac_res.children.empty()) goto free_nodes; // delete mode if (cm_mode == config::CONFIG_MT_DEL) { // single result if (ac_res.children.size() == 1) { // item if (ac_res.children[0]->node_type != config::CONFIG_NT_ITEM) goto free_nodes; if (pretend) goto free_nodes; // start transaction config->start_transaction(&cfg_user_id); // mark as deleted ac_res.children[0]->node_state = config::CONFIG_NS_DELETED; goto free_nodes; } // multiple results if (ac_res.children.empty()) goto free_nodes; config::ConfigItem *tmp_item = nullptr; // check if parent is block item if (ac_res.children[0]->parent->node_type != config::CONFIG_NT_BLOCK) goto free_nodes; tmp_item = ac_res.children[0]->parent; // only allow deletion of template based node if (tmp_item->parent->children.size() <= 1) goto free_nodes; // check if template if (!tmp_item->parent->children[0]->is_template) goto free_nodes; // loop all template based nodes, try to match for (unsigned int i = 1; i < tmp_item->parent->children.size(); i++) { if (tmp_item->parent ->children[i] ->is_template) continue; if (tmp_item->parent->children[i] != tmp_item) continue; if (pretend) break; // start transaction config->start_transaction(&cfg_user_id); // mark as deleted tmp_item->parent ->children[i] ->node_state = config::CONFIG_NS_DELETED; break; } // cmd without params } else if (cm_mode == config::CONFIG_MT_CMD) { if (ac_res.children.size() < 1) goto free_nodes; // cmd without params if (ac_res.children[0]->node_type == config::CONFIG_NT_CMD) { if (ac_res.children[0]->name != "discard") goto free_nodes; if (pretend) goto free_nodes; // set current definition path to top level config->reset_all_wns(); // regenerate cli path cli_path = ""; // discard config->discard(config->get_definition_root()); // end transaction config->end_transaction(); // cmd with params } else if (ac_res.children[0]->node_type == config::CONFIG_NT_PARAM) { if (!ac_res.children[0]->parent) goto free_nodes; if (ac_res.children[0]->parent ->node_type != config::CONFIG_NT_CMD) goto free_nodes; if (ac_res.children[0]->parent->name == "commit") { if(pretend) goto free_nodes; if (config->commit(config->get_definition_root(), true) > 0) { // set current definition path to // top level config->reset_all_wns(); // regenerate cli path cli_path = ""; // get rollback count DIR *dir; int cn = 0; std::stringstream tmp_str; dir = opendir("./commit-log"); // if dir if (dir != nullptr) { dirent *ent; // get dir contents while ((ent = readdir(dir)) != nullptr) { if (strncmp(ent->d_name, ".rollback", 9) == 0) ++cn; } // close dir closedir(dir); } tmp_str << "./commit-log/.rollback." << cn << ".pmcfg"; // save rollback std::ofstream ofs(tmp_str.str().c_str(), std::ios::out | std::ios::binary); if (ofs.is_open()) { // save current config excluding // uncommitted changes config->show_config(config->get_definition_root(), 0, &tmp_size, false, &ofs, true, &ac_res.children[0]->new_value); ofs.close(); // prepare notifications prepare_notifications(); // commit new configuration config->commit(config->get_definition_root(), false); // sort config->sort(config->get_definition_root()); // end transaction config->end_transaction(); // update current configuration // contents file std::ofstream orig_fs(((std::string *)mink::CURRENT_DAEMON->get_param(1)) ->c_str(), std::ios::out | std::ios::binary); if (orig_fs.is_open()) { config->show_config(config->get_definition_root(), 0, &tmp_size, false, &orig_fs, false, nullptr); orig_fs.close(); } } } // clear value ac_res.children[0]->new_value = ""; // rollback } else if (ac_res.children[0]->parent->name == "rollback") { if (pretend) goto free_nodes; if (ac_res.children[0]->new_value != "") { std::string tmp_path; std::stringstream istr(ac_res.children[0]->new_value); int rev_num = -1; istr >> rev_num; bool rev_found = false; dirent **fnames; int n = scandir("./commit-log/", &fnames, mink_utils::_ac_rollback_revision_filter, mink_utils::_ac_rollback_revision_sort); if (n > 0) { for (int i = 0; i < n; i++) { if (rev_num == i) { rev_found = true; tmp_path = "./commit-log/"; tmp_path.append(fnames[i]->d_name); } free(fnames[i]); } free(fnames); // if revision found if (!rev_found) goto rollback_clear_value; tmp_size = 0; // err check tmp_size = mink_utils::get_file_size(tmp_path.c_str()); if (tmp_size == 0) { // nothing } else { char *tmp_file_buff = new char[tmp_size + 1]; memset(tmp_file_buff, 0, tmp_size + 1); mink_utils::load_file(tmp_path.c_str(), tmp_file_buff, &tmp_size); antlr::MinkParser *pmp = antlr::create_parser(); pANTLR3_INPUT_STREAM input = pmp->input; pminkLexer lxr = pmp->lexer; pANTLR3_COMMON_TOKEN_STREAM tstream = pmp->tstream; pminkParser psr = pmp->parser; minkParser_inputConfig_return_struct ast_cfg; auto cfg_cnt = new config::ConfigItem(); // reset error state lxr->pLexer->rec->state->errorCount = 0; psr->pParser->rec->state->errorCount = 0; input->reuse(input, (unsigned char *)tmp_file_buff, tmp_size, (unsigned char *)"file_" "stream"); // token stream tstream->reset(tstream); // ast ast_cfg = psr->inputConfig(psr); // err check int err_c = lxr->pLexer ->rec ->getNumberOfSyntaxErrors(lxr->pLexer->rec); err_c += psr->pParser ->rec ->getNumberOfSyntaxErrors(psr->pParser->rec); if (err_c > 0) { // nothing } else { // set current // definition path // to top level config->reset_all_wns(); // regenerate cli // path cli_path = ""; // get structure antlr::process_config(ast_cfg.tree, cfg_cnt); // validate if (config->validate(config->get_definition_root(), cfg_cnt)) { // prepare for // config data // replacement config->replace_prepare(config->get_definition_root()); // merge new // data int res = config->merge(config->get_definition_root(), cfg_cnt, true); // err check if (res != 0) { // nothing } else { // prepare // notifications prepare_notifications(); // commit // new // config config->commit(config->get_definition_root(), false); // update // current // configuration // contents // file std::ofstream orig_fs(((std::string*)mink::CURRENT_DAEMON->get_param(1)) ->c_str(), std::ios::out | std::ios::binary); if (orig_fs.is_open()) { config->show_config(config->get_definition_root(), 0, &tmp_size, false, &orig_fs, false, nullptr); orig_fs.close(); } // sort config->sort(config->get_definition_root()); // end // transaction config->end_transaction(); } } } // free mem delete cfg_cnt; delete[] tmp_file_buff; antlr::free_mem(pmp); } } } rollback_clear_value: // clear value ac_res.children[0]->new_value = ""; } } } else if ((cm_mode == config::CONFIG_MT_SET) && (!pretend)) { // do nothing, errors already present in tmp_err config->start_transaction(&cfg_user_id); } free_nodes: // free temp nodes and clear res buffer ac_res.children.clear(); std::all_of(tmp_node_lst.children.cbegin(), tmp_node_lst.children.cend(), [](const config::ConfigItem *ci) { delete ci; return true; }); tmp_node_lst.children.clear(); } // new stream, start sending config tree void NewStream::process_get(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); gdt::GDTClient *client = stream->get_client(); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); tmp_size = 0; res_size = 0; error_count = 0; err_index = -1; last_found = nullptr; res_index = 0; ac_res.children.clear(); char *tmp_val = nullptr; int tmp_val_l = 0; bool cfg_notify = false; asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; line.clear(); // check for body if (!in_msg->_body) goto process_lines; // check for config message if (!in_msg->_body->_conf->has_linked_data(*in_sess)) goto process_lines; c = in_msg->_body->_conf; // check for GET action if (c->_action ->linked_node ->tlv ->value[0] != asn1::ConfigAction::_ca_cfg_get) goto process_lines; // check for params part if (!c->_params) goto process_lines; if (!c->_params->has_linked_data(*in_sess)) goto process_lines; p = c->_params; // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for current session if (!p->get_child(i)->has_linked_data(*in_sess)) continue; // check for value if (!p->get_child(i)->_value) continue; // check if value exists in current session if (!p->get_child(i) ->_value ->has_linked_data(*in_sess)) continue; // check if child exists if (!p->get_child(i) ->_value ->get_child(0)) continue; // check if child exists in current // sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // check param id, convert from big endian to // host auto param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // set tmp values tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // match param switch (be32toh(*param_id)) { // config item path case asn1::ParameterType::_pt_mink_config_cfg_item_path: line.append(tmp_val, tmp_val_l); break; // config item notification flag case asn1::ParameterType::_pt_mink_config_cfg_item_notify: cfg_notify = (tmp_val[0] == 1); break; default: break; } } process_lines: // check if config item path item was received if (line.size() == 0) { stream->end_sequence(); return; } // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } // remove payload if (gdtm->_body->_conf->_payload != nullptr) gdtm->_body->_conf->_payload->unlink(1); // set params if (gdtm->_body->_conf->_params == nullptr) { gdtm->_body->_conf->set_params(); p = gdtm->_body->_conf->_params; // set children, allocate more for (int i = 0; i < 1; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = gdtm->_body->_conf->_params; int cc = p->children.size(); if (cc < 1) { // set children, allocate more for (int i = cc; i < 1; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 1) { // remove extra children if used in some other session, only 2 // needed for (int i = 1; i < cc; i++) p->get_child(i)->unlink(1); } } // check if user requested node exists config::ConfigItem *tmp_cfg_root = (*config->get_definition_root())(line.c_str()); // node exists if (tmp_cfg_root != nullptr) { // set node notification if (cfg_notify) { // check if notification exists config::CfgNotification *cfg_ntf = config->get_notification(&line); if (cfg_ntf == nullptr) { // create new notification handler cfg_ntf = new config::GDTCfgNotification(&line); config->add_notification(cfg_ntf); } // create ntf user id config::GDTCfgNtfUser ntf_usr(client); if ((in_msg->_header->_source->_id != nullptr) && (in_msg->_header->_source->_id->has_linked_data(*in_sess))) { tmp_val = (char *)in_msg->_header ->_source ->_id ->linked_node ->tlv ->value; tmp_val_l = in_msg->_header ->_source ->_id ->linked_node ->tlv ->value_length; std::string tmp_str(tmp_val, tmp_val_l); // set registered user id if (tmp_str.size() <= sizeof(ntf_usr.user_id)) memcpy(ntf_usr.user_id, tmp_str.c_str(), tmp_str.size()); } // set registered user type tmp_val = (char *)in_msg->_header ->_source ->_type ->linked_node ->tlv ->value; tmp_val_l = in_msg->_header ->_source ->_type ->linked_node ->tlv ->value_length; std::string tmp_str(tmp_val, tmp_val_l); if (tmp_str.size() <= sizeof(ntf_usr.user_type)) memcpy(ntf_usr.user_type, tmp_str.c_str(), tmp_str.size()); // unregister user if previously registered cfg_ntf->unreg_user(&ntf_usr); // register new node user cfg_ntf->reg_user(&ntf_usr); } // flatten node structure to list config::Config::flatten(tmp_cfg_root, &ac_res); // get result size, convert to big endian ac_res_count = htobe32(ac_res.children.size()); // set result action gdtm->_body ->_conf ->_action ->set_linked_data(1, (unsigned char *)&ca_cfg_result, 1); // cfg item count gdtm->_body ->_conf ->_params ->get_child(0) ->_id ->set_linked_data(1, (unsigned char *)&stream_next.pt_cfg_item_count, sizeof(uint32_t)); gdtm->_body ->_conf ->_params ->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&ac_res_count, sizeof(uint32_t)); // include bodu *include_body = true; // continue stream->continue_sequence(); if (ac_res.children.empty()) stream->end_sequence(); // node does not exist } else { // node does not exist stream->end_sequence(); } } // prepare notifictions void NewStream::prepare_notifications() { // ****** notify ************* // flatten node structure to list config::ConfigItem tmp_res; config::Config::flatten(config->get_definition_root(), &tmp_res); // remove unmodified nodes, only interested in modified nodes unsigned int i = 0; while (i < tmp_res.children.size()) { if (tmp_res.children[i]->node_state == config::CONFIG_NS_READY) tmp_res.children.erase(tmp_res.children.begin() + i); else ++i; } config::ConfigItem *tmp_item = nullptr; bool exists; std::string tmp_full_path; std::string tmp_str; // loop list for (i = 0; i < tmp_res.children.size(); i++) { tmp_item = tmp_res.children[i]; // check if node has been modified if (tmp_item->node_state != config::CONFIG_NS_READY) { // get full node path config::Config::get_parent_line(tmp_item, &tmp_full_path); tmp_full_path.append(tmp_item->name); // get users (check parent nodes) while (tmp_item != nullptr) { // get notification config::Config::get_parent_line(tmp_item, &tmp_str); tmp_str.append(tmp_item->name); config::CfgNotification *cfg_ntf = config->get_notification(&tmp_str); // user found if (cfg_ntf != nullptr) { // gdt notification auto gdtn = (config::GDTCfgNotification *)cfg_ntf; // add to notification list auto new_cfg_item = new config::ConfigItem(); new_cfg_item->name = tmp_full_path; new_cfg_item->value = tmp_res.children[i]->new_value; new_cfg_item->node_state = tmp_res.children[i]->node_state; new_cfg_item->node_type = tmp_res.children[i]->node_type; gdtn->ntf_cfg_lst.children.push_back(new_cfg_item); // ready to send gdtn->ready = true; // check if client was already added to notification client // list exists = false; for (unsigned int j = 0; j < stream_done.ntfy_lst.size(); j++) if (stream_done.ntfy_lst[j] == gdtn) { exists = true; break; } // add to list if needed, notifications processed after // commit (Stream done event) if (!exists) stream_done.ntfy_lst.push_back(gdtn); } // level up (parent) tmp_item = tmp_item->parent; } } } tmp_res.children.clear(); // ****** notify ************* } // new stream, send auto completed line in first packet void NewStream::process_enter(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); gdt::GDTClient *client = stream->get_client(); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); tmp_size = 0; res_size = 0; error_count = 0; err_index = -1; last_found = nullptr; res_index = 0; line_stream_lc = 0; cm_mode = config::CONFIG_MT_UNKNOWN; tmp_node_lst.children.clear(); ac_res.children.clear(); line_stream.str(""); line_stream.clear(); line_stream.seekg(0, std::ios::beg); char *tmp_val = nullptr; int tmp_val_l = 0; asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; // current path cli_path = ""; config->generate_path(config->get_definition_wn(&cfg_user_id)->wnode, &cli_path); // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } c = gdtm->_body->_conf; // remove payload if (c->_payload != nullptr) c->_payload->unlink(1); // set params if (c->_params == nullptr) { c->set_params(); p = gdtm->_body->_conf->_params; // set children, allocate more for (int i = 0; i < 5; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = c->_params; int cc = p->children.size(); if (cc < 5) { // set children, allocate more for (int i = cc; i < 5; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 5) { // remove extra children if used in some other session, only 2 // needed for (int i = 5; i < cc; i++) p->get_child(i)->unlink(1); } } // get line if (!in_msg->_body) goto process_tokens; // check for config message if (!c->has_linked_data(*in_sess)) goto process_tokens; // check for params part if (!c->_params) goto process_tokens; if (!c->_params->has_linked_data(*in_sess)) goto process_tokens; p = c->_params; // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for current session if (!p->get_child(i)->has_linked_data(*in_sess)) continue; // check for value if (!p->get_child(i)->_value) continue; // check if value exists in current session if (!p->get_child(i)->_value->has_linked_data(*in_sess)) continue; // check if child exists if (!p->get_child(i)->_value->get_child(0)) continue; // check if child exists in current // sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // check param id, convert from big endian to host auto param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // set tmp values tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // match param switch (be32toh(*param_id)) { // config item count case asn1::ParameterType::_pt_mink_config_ac_line: line.clear(); line.append(tmp_val, tmp_val_l); mink::CURRENT_DAEMON->log(mink::LLT_DEBUG, "cmd line received: [%s]", line.c_str()); break; default: break; } } process_tokens: // tokenize mink_utils::tokenize(&line, tmp_lst, 50, &tmp_size, true); // pretend bool pretend = (config->get_transaction_owner() != cfg_user_id && config->transaction_started() ? true : false); // auto complete config->auto_complete(&cm_mode, config::CONFIG_ACM_ENTER, config->get_cmd_tree(), config->get_definition_wn(&cfg_user_id)->wnode, tmp_lst, tmp_size, &ac_res, &res_size, &last_found, &error_count, tmp_err, pretend, &tmp_node_lst); if (pretend) { switch (cm_mode) { case config::CONFIG_MT_SET: case config::CONFIG_MT_EDIT: case config::CONFIG_MT_DEL: tmp_err[error_count].clear(); tmp_err[error_count].assign("Transaction started by other user, " "cannot execute intrusive operation!"); ++error_count; break; default: break; } } // replace current line with auto completed values line.clear(); for (int i = 0; i < tmp_size; i++) { line.append(tmp_lst[i]); if (i < res_size) line.append(" "); else break; } // process results if (ac_res.children.empty()) goto set_values; // delete mode if (cm_mode == config::CONFIG_MT_DEL) { // single result if (ac_res.children.size() == 1) { // check if single item is really only one ITEM node (last one // from input and one from ac_res should match) if (tmp_lst[tmp_size - 1] == ac_res.children[ac_res.children.size() - 1]->name) { // item if (ac_res.children[0]->node_type == config::CONFIG_NT_ITEM) { if(pretend) goto set_values; // start transaction config->start_transaction(&cfg_user_id); // mark as deleted ac_res.children[0]->node_state = config::CONFIG_NS_DELETED; // replicate auto cfg_daemons = (std::vector<std::string *> *)mink::CURRENT_DAEMON->get_param(2); for (unsigned int i = 0; i < cfg_daemons->size(); i++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client("routingd"), (*cfg_daemons)[i]->c_str(), &cfg_user_id); } } else if (ac_res.children[0]->node_type == config::CONFIG_NT_BLOCK) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot delete non template block node \""); tmp_err[error_count].append(ac_res.children[0]->parent->name); tmp_err[error_count].append("\"!"); ++error_count; } // check if single item is in fact only single child of // template node that was set for deletion } else { config::ConfigItem *tmp_item = nullptr; // check if parent is block item if (ac_res.children[0]->parent->node_type != config::CONFIG_NT_BLOCK) goto set_values; tmp_item = ac_res.children[0]->parent; // only allow deletion of template based node if (!tmp_item->parent) goto set_values; if (tmp_item->parent->children.size() <= 1) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot delete non template block node \""); tmp_err[error_count].append(ac_res.children[0]->parent->name); tmp_err[error_count].append("\"!"); ++error_count; goto set_values; } // check if template if (!tmp_item->parent->children[0]->is_template) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot delete non template block node \""); tmp_err[error_count].append(ac_res.children[0]->parent->name); tmp_err[error_count].append("\"!"); ++error_count; goto set_values; } // loop all template based nodes, try to // match for (unsigned int i = 1; i < tmp_item->parent->children.size(); i++){ if (tmp_item->parent->children[i]->is_template) continue; if (tmp_item->parent->children[i] != tmp_item) continue; if(pretend) break; // start transaction config->start_transaction(&cfg_user_id); // mark as deleted tmp_item->parent ->children[i] ->node_state = config::CONFIG_NS_DELETED; // replicate auto cfg_daemons = (std::vector<std::string *>*)mink::CURRENT_DAEMON->get_param(2); for (unsigned int j = 0; j < cfg_daemons->size(); j++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client("routingd"), (*cfg_daemons)[j]->c_str(), &cfg_user_id); } } } // multiple results } else if (!ac_res.children.empty()) { config::ConfigItem *tmp_item = nullptr; // check if parent is block item if (ac_res.children[0]->parent ->node_type != config::CONFIG_NT_BLOCK) goto set_values; tmp_item = ac_res.children[0]->parent; // only allow deletion of template based node if (!tmp_item->parent) goto set_values; if (tmp_item->parent->children.size() >= 1) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot delete non template block node \""); tmp_err[error_count].append(ac_res.children[0]->parent->name); tmp_err[error_count].append("\"!"); ++error_count; goto set_values; } // check if template if (!tmp_item->parent->children[0]->is_template) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot delete non template block node \""); tmp_err[error_count].append(ac_res.children[0]->parent->name); tmp_err[error_count].append("\"!"); ++error_count; goto set_values; } // loop all template based nodes, try to match for (unsigned int i = 1; i < tmp_item->parent->children.size(); i++) { if (tmp_item->parent->children[i]->is_template) continue; if (tmp_item->parent->children[i] != tmp_item) continue; if(pretend) break; // start transaction config->start_transaction(&cfg_user_id); // mark as deleted tmp_item->parent ->children[i] ->node_state = config::CONFIG_NS_DELETED; // replicate auto cfg_daemons = (std::vector<std::string *>*)mink::CURRENT_DAEMON->get_param(2); for (unsigned int j = 0; j < cfg_daemons->size(); j++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client( "routingd"), (*cfg_daemons)[j]->c_str(), &cfg_user_id); } break; } } // special commands } else if (cm_mode == config::CONFIG_MT_CMD) { if (ac_res.children.size() < 1) goto set_values; // cmd without params if (ac_res.children[0]->node_type == config::CONFIG_NT_CMD) { if (ac_res.children[0]->name == "configuration") { int tmp_sz = 0; // get date size line_stream_lc = config->get_config_lc(config->get_definition_wn(&cfg_user_id)->wnode); // get data config->show_config(config->get_definition_wn(&cfg_user_id)->wnode, 0, &tmp_sz, false, &line_stream); } else if (ac_res.children[0]->name == "commands") { // get date size line_stream_lc = config->get_commands_lc(config->get_definition_wn(&cfg_user_id)->wnode); // get data config->show_commands(config->get_definition_wn(&cfg_user_id)->wnode, 0, &line_stream); } else if (ac_res.children[0]->name == "top") { if (!pretend) { // set current cfg path config->get_definition_wn(&cfg_user_id)->wnode = config->get_definition_root(); // regenerate cli path cli_path = ""; } else { tmp_err[error_count].clear(); tmp_err[error_count].assign( "Transaction started by other user, cannot " "execute intrusive operation!"); ++error_count; } } else if (ac_res.children[0]->name == "up") { if (!pretend) { if (!config->get_definition_wn(&cfg_user_id) ->wnode->parent) goto set_values; // set current cfg path config->get_definition_wn(&cfg_user_id)->wnode = config->get_definition_wn(&cfg_user_id) ->wnode->parent; // regenerate cli path cli_path = ""; // generate cfg path config->generate_path(config->get_definition_wn(&cfg_user_id)->wnode, &cli_path); } else { tmp_err[error_count].clear(); tmp_err[error_count].assign( "Transaction started by other user, cannot " "execute intrusive operation!"); ++error_count; } } else if (ac_res.children[0]->name == "discard") { if (!pretend) { // set current definition path to top level config->reset_all_wns(); // regenerate cli path cli_path = ""; // generate prompt config->discard(config->get_definition_root()); // end transaction config->end_transaction(); // replicate auto cfg_daemons = (std::vector<std::string *> *)mink::CURRENT_DAEMON->get_param(2); for (unsigned int i = 0; i < cfg_daemons->size(); i++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client("routingd"), (*cfg_daemons)[i]->c_str(), &cfg_user_id); } } else { tmp_err[error_count].clear(); tmp_err[error_count].assign( "Transaction started by other user, cannot " "execute intrusive operation!"); ++error_count; } } // cmd with params } else if (ac_res.children[0]->node_type == config::CONFIG_NT_PARAM) { if (!ac_res.children[0]->parent) goto set_values; if (ac_res.children[0]->parent->node_type != config::CONFIG_NT_CMD) goto set_values; if (ac_res.children[0]->parent->name == "commit") { if(pretend){ tmp_err[error_count].clear(); tmp_err[error_count].assign( "Transaction started by other user, " "cannot execute intrusive operation!"); ++error_count; goto set_values; } if (config->commit(config->get_definition_root(), true) > 0) { // set current definition path to top // level config->reset_all_wns(); // regenerate cli path cli_path = ""; // generate prompt // get rollback count DIR *dir; int cn = 0; std::stringstream tmp_str; dir = opendir("./commit-log"); // if dir if (dir != nullptr) { dirent *ent; // get dir contents while ((ent = readdir(dir)) != nullptr) { if (strncmp(ent->d_name, ".rollback", 9) == 0) ++cn; } // close dir closedir(dir); } tmp_str << "./commit-log/.rollback." << cn << ".pmcfg"; // save rollback std::ofstream ofs(tmp_str.str().c_str(), std::ios::out | std::ios::binary); if (ofs.is_open()) { // save current config excluding // uncommitted changes config->show_config(config->get_definition_root(), 0, &tmp_size, false, &ofs, true, &ac_res.children[0]->new_value); ofs.close(); // prepare notifications prepare_notifications(); // commit new configuration config->commit(config->get_definition_root(), false); // sort config->sort(config->get_definition_root()); // update current configuration // contents file std::ofstream orig_fs( ((std::string *) mink::CURRENT_DAEMON->get_param(1)) ->c_str(), std::ios::out | std::ios::binary); if (orig_fs.is_open()) { config->show_config(config->get_definition_root(), 0, &tmp_size, false, &orig_fs, false, nullptr); orig_fs.close(); } // end transaction config->end_transaction(); // replicate auto cfg_daemons = (std::vector<std::string *> *)mink::CURRENT_DAEMON->get_param(2); for (unsigned int i = 0; i < cfg_daemons->size(); i++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client("routingd"), (*cfg_daemons)[i]->c_str(), &cfg_user_id); } } else { tmp_err[error_count].clear(); tmp_err[error_count].assign("Cannot create rollback " "configuration!"); ++error_count; } } // clear value ac_res.children[0]->new_value = ""; // rollback } else if (ac_res.children[0]->parent->name == "rollback") { std::string tmp_path; std::stringstream istr(ac_res.children[0]->new_value); int rev_num = -1; istr >> rev_num; bool rev_found = false; dirent **fnames; int n = scandir("./commit-log/", &fnames, mink_utils::_ac_rollback_revision_filter, mink_utils::_ac_rollback_revision_sort); if(pretend){ tmp_err[error_count].clear(); tmp_err[error_count].assign( "Transaction started by other user, " "cannot execute intrusive operation!"); ++error_count; goto set_values; } if (ac_res.children[0]->new_value == "") { tmp_err[error_count].clear(); tmp_err[error_count].assign( "Rollback revision not defined!"); ++error_count; goto rollback_clear_value; } if (n <= 0) { tmp_err[error_count].clear(); tmp_err[error_count].assign("Cannot find rollback " "information!"); ++error_count; goto rollback_clear_value; } for (int i = 0; i < n; i++) { if (rev_num == i) { rev_found = true; tmp_path = "./commit-log/"; tmp_path.append(fnames[i]->d_name); } free(fnames[i]); } free(fnames); // no revision found if (!rev_found) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot find rollback " "revision '"); tmp_err[error_count].append(ac_res.children[0]->new_value); tmp_err[error_count].append("'!"); ++error_count; goto rollback_clear_value; } tmp_size = 0; // err check tmp_size = mink_utils::get_file_size(tmp_path.c_str()); if (tmp_size == 0) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot find rollback " "revision '"); tmp_err[error_count].append(tmp_path); tmp_err[error_count].append("'!"); ++error_count; } else { char *tmp_file_buff = new char[tmp_size + 1]; memset(tmp_file_buff, 0, tmp_size + 1); mink_utils::load_file(tmp_path.c_str(), tmp_file_buff, &tmp_size); line_stream << "Loading rollback " "configuration..." << std::endl; ++line_stream_lc; antlr::MinkParser *pmp = antlr::create_parser(); pANTLR3_INPUT_STREAM input = pmp->input; pminkLexer lxr = pmp->lexer; pANTLR3_COMMON_TOKEN_STREAM tstream = pmp->tstream; pminkParser psr = pmp->parser; minkParser_inputConfig_return_struct ast_cfg; auto cfg_cnt = new config::ConfigItem(); // reset error state lxr->pLexer->rec->state->errorCount = 0; psr->pParser->rec->state->errorCount = 0; input->reuse(input, (unsigned char *)tmp_file_buff, tmp_size, (unsigned char *)"file_stream"); // token stream tstream->reset(tstream); // ast ast_cfg = psr->inputConfig(psr); // err check int err_c = lxr->pLexer ->rec ->getNumberOfSyntaxErrors(lxr->pLexer->rec); err_c += psr->pParser ->rec ->getNumberOfSyntaxErrors(psr->pParser->rec); if (err_c > 0) { tmp_err[error_count].clear(); tmp_err[error_count].assign("Invalid " "rollback " "configuration " "file syntax!"); ++error_count; } else { line_stream << "Done" << std::endl; ++line_stream_lc; // set current // definition path to // top level config->reset_all_wns(); // regenerate cli path cli_path = ""; // get structure antlr::process_config(ast_cfg.tree, cfg_cnt); // validate if (!config->validate(config->get_definition_root(), cfg_cnt)) { tmp_err[error_count].clear(); tmp_err[error_count].assign( "Invalid/undefined " "rollback configuration " "file contents!"); ++error_count; goto rollback_free_parser; } // prepare for // config data // replacement config->replace_prepare(config->get_definition_root()); // merge new data line_stream << "Merging " "rollback " "configurati" "on file..." << std::endl; ++line_stream_lc; int res = config->merge(config->get_definition_root(), cfg_cnt, true); // err check if (res != 0) { tmp_err[error_count].clear(); tmp_err[error_count].assign("Cannot merge " "configuration" " file contents!"); ++error_count; } else { line_stream << "Done" << std::endl; line_stream << "Committing rollback" << " configuration..." << std::endl; line_stream_lc += 2; // prepare // notifications prepare_notifications(); // commit new // config config->commit(config->get_definition_root(), false); // update // current // configuration // contents file std::ofstream orig_fs(((std::string *)mink::CURRENT_DAEMON->get_param(1)) ->c_str(), std::ios::out | std::ios::binary); if (orig_fs.is_open()) { config->show_config(config->get_definition_root(), 0, &tmp_size, false, &orig_fs, false, nullptr); orig_fs.close(); } // sort config->sort(config->get_definition_root()); // end // transaction config->end_transaction(); // replicate auto cfg_daemons = (std::vector<std::string *> *)mink::CURRENT_DAEMON->get_param(2); for (unsigned int i = 0; i < cfg_daemons->size(); i++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client("routingd"), (*cfg_daemons)[i]->c_str(), &cfg_user_id); } line_stream << "Done" << std::endl; ++line_stream_lc; } } rollback_free_parser: // free mem delete cfg_cnt; delete[] tmp_file_buff; antlr::free_mem(pmp); } rollback_clear_value: // clear value ac_res.children[0]->new_value = ""; // save conf } else if (ac_res.children[0]->parent->name == "save") { if (ac_res.children[0]->new_value == "") { tmp_err[error_count].clear(); tmp_err[error_count].assign("Filename not defined!"); ++error_count; goto set_values; } std::ofstream ofs(ac_res.children[0]->new_value.c_str(), std::ios::out | std::ios::binary); if (ofs.is_open()) { line_stream << "Saving configuration to \"" << ac_res.children[0]->new_value << "\"..." << std::endl; ++line_stream_lc; config->show_config(config->get_definition_wn(&cfg_user_id)->wnode, 0, &tmp_size, false, &ofs, false, nullptr); ofs.close(); line_stream << "Done" << std::endl; ++line_stream_lc; } else { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot create file \""); tmp_err[error_count].append(ac_res.children[0]->new_value); tmp_err[error_count].append("\""); ++error_count; } // clear value ac_res.children[0]->new_value = ""; // load conf } else if (ac_res.children[0]->parent->name == "load") { if (pretend) { tmp_err[error_count].clear(); tmp_err[error_count].assign( "Transaction started by other user, " "cannot execute intrusive operation!"); ++error_count; goto set_values; } if (ac_res.children[0]->new_value == "") { tmp_err[error_count].clear(); tmp_err[error_count].assign("Filename not defined!"); ++error_count; goto set_values; } tmp_size = 0; // err tmp_size = mink_utils::get_file_size(ac_res.children[0]->new_value.c_str()); if (tmp_size == 0) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot find file \""); tmp_err[error_count].append(ac_res.children[0]->new_value); tmp_err[error_count].append("\""); ++error_count; } else { char *tmp_file_buff = new char[tmp_size + 1]; memset(tmp_file_buff, 0, tmp_size + 1); mink_utils::load_file(ac_res.children[0]->new_value.c_str(), tmp_file_buff, &tmp_size); line_stream << "Loading new configuration " "file \"" << ac_res.children[0]->new_value << "\"..." << std::endl; ++line_stream_lc; antlr::MinkParser *pmp = antlr::create_parser(); pANTLR3_INPUT_STREAM input = pmp->input; pminkLexer lxr = pmp->lexer; pANTLR3_COMMON_TOKEN_STREAM tstream = pmp->tstream; pminkParser psr = pmp->parser; minkParser_inputConfig_return_struct ast_cfg; auto cfg_cnt = new config::ConfigItem(); // reset error state lxr->pLexer->rec->state->errorCount = 0; psr->pParser->rec->state->errorCount = 0; input->reuse(input, (unsigned char *)tmp_file_buff, tmp_size, (unsigned char *)"file_stream"); // token stream tstream->reset(tstream); // ast ast_cfg = psr->inputConfig(psr); int res = 0; // err check int err_c = lxr->pLexer ->rec ->getNumberOfSyntaxErrors(lxr->pLexer->rec); err_c += psr->pParser ->rec ->getNumberOfSyntaxErrors(psr->pParser->rec); if (err_c > 0) { tmp_err[error_count].clear(); tmp_err[error_count].assign("Invalid configuration " "file syntax!"); ++error_count; goto save_free_parser; } line_stream << "Done" << std::endl; ++line_stream_lc; // get structure antlr::process_config(ast_cfg.tree, cfg_cnt); // validate if (!config->validate(config->get_definition_root(), cfg_cnt)) { tmp_err[error_count].clear(); tmp_err[error_count].assign("Invalid/undefined " "configuration file " "contents!"); ++error_count; goto save_free_parser; } // prepare for config data // replacement config->replace_prepare(config->get_definition_root()); // merge new data line_stream << "Merging new " "configuration " "file..." << std::endl; ++line_stream_lc; res = config->merge(config->get_definition_root(), cfg_cnt, true); // err check if (res != 0) { tmp_err[error_count].clear(); tmp_err[error_count].assign("Cannot merge " "configuration " "file " "contents!"); ++error_count; } else { line_stream << "Done" << std::endl; ++line_stream_lc; // start transaction config->start_transaction(&cfg_user_id); } save_free_parser: // free mem delete cfg_cnt; delete[] tmp_file_buff; antlr::free_mem(pmp); } // clear value ac_res.children[0]->new_value = ""; } } // edit mode } else if (cm_mode == config::CONFIG_MT_EDIT) { if(!last_found) goto set_values; if (last_found->node_type != config::CONFIG_NT_BLOCK) { tmp_err[error_count].clear(); tmp_err[error_count].append("Cannot navigate to non block mode \""); tmp_err[error_count].append(last_found->name); tmp_err[error_count].append("\"!"); ++error_count; goto set_values; } if(pretend) goto set_values; // set current cfg path config->get_definition_wn(&cfg_user_id)->wnode = last_found; // regenerate cli path cli_path = ""; // generate cfg path config->generate_path(config->get_definition_wn(&cfg_user_id)->wnode, &cli_path); // show mode } else if (cm_mode == config::CONFIG_MT_SHOW) { // sitch to TAB mode, send config items ac_mode = config::CONFIG_ACM_TAB; // set mode } else if (cm_mode == config::CONFIG_MT_SET) { if(pretend) goto set_values; // do nothing, errors already present in tmp_err config->start_transaction(&cfg_user_id); // replicate auto cfg_daemons = (std::vector<std::string *> *)mink::CURRENT_DAEMON->get_param(2); for (unsigned int i = 0; i < cfg_daemons->size(); i++) { config::replicate(line.c_str(), client->get_session() ->get_registered_client("routingd"), (*cfg_daemons)[i]->c_str(), &cfg_user_id); } } set_values: // set values c->_action->set_linked_data(1, (unsigned char *)&ca_cfg_result, 1); // ac lline p->get_child(0) ->_id ->set_linked_data(1, (unsigned char *)&pt_mink_config_ac_line, sizeof(int)); p->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)line.c_str(), line.size()); // cli path p->get_child(1) ->_id ->set_linked_data(1, (unsigned char *)&pt_mink_config_cli_path, sizeof(int)); p->get_child(1) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)cli_path.c_str(), cli_path.size()); // error count err_index = error_count - 1; error_count = htobe32(error_count); p->get_child(2) ->_id ->set_linked_data(1, (unsigned char *)&pt_mink_config_ac_err_count, sizeof(int)); p->get_child(2) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&error_count, sizeof(int)); // line count line_stream_lc = htobe32(line_stream_lc); p->get_child(3) ->_id ->set_linked_data(1, (unsigned char *)&pt_mink_config_cfg_line_count, sizeof(int)); p->get_child(3) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&line_stream_lc, sizeof(int)); // cm mode p->get_child(4) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_cm_mode, sizeof(uint32_t)); p->get_child(4) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&cm_mode, 1); // include body *include_body = true; // continue stream->continue_sequence(); } // new stream, send auto completed line in first packet void NewStream::process_tab(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); auto in_msg = (asn1::GDTMessage *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG); auto in_sess = (uint64_t *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_IN_MSG_ID); tmp_size = 0; res_size = 0; error_count = 0; err_index = -1; last_found = nullptr; res_index = 0; cm_mode = config::CONFIG_MT_UNKNOWN; tmp_node_lst.children.clear(); ac_res.children.clear(); line_stream.str(""); line_stream.clear(); line_stream.seekg(0, std::ios::beg); char *tmp_val = nullptr; int tmp_val_l = 0; asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } c = gdtm->_body->_conf; // remove payload if (gdtm->_body->_conf->_payload != nullptr) gdtm->_body->_conf->_payload->unlink(1); // set params if (gdtm->_body->_conf->_params == nullptr) { gdtm->_body->_conf->set_params(); p = c->_params; // set children, allocate more for (int i = 0; i < 2; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = c->_params; int cc = p->children.size(); if (cc < 2) { // set children, allocate more for (int i = cc; i < 2; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 2) { // remove extra children if used in some other session, only 2 // needed for (int i = 2; i < cc; i++) p->get_child(i)->unlink(1); } } // get line if (!in_msg->_body) goto tokenize; // check for config message if (!c->has_linked_data(*in_sess)) goto tokenize; // check for params part if (!c->_params) goto tokenize; if (!c->_params->has_linked_data(*in_sess)) goto tokenize; p = c->_params; // process params for (unsigned int i = 0; i < p->children.size(); i++) { // check for current session if (!p->get_child(i)->has_linked_data(*in_sess)) continue; // check for value if (!p->get_child(i)->_value) continue; // check if value exists in current session if (!p->get_child(i) ->_value ->has_linked_data(*in_sess)) continue; // check if child exists if (!p->get_child(i) ->_value ->get_child(0)) continue; // check if child exists in current // sesion if (!p->get_child(i) ->_value ->get_child(0) ->has_linked_data(*in_sess)) continue; // check param id, convert from big endian to host auto param_id = (uint32_t *)p->get_child(i) ->_id ->linked_node ->tlv ->value; // set tmp values tmp_val = (char *)p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value; tmp_val_l = p->get_child(i) ->_value ->get_child(0) ->linked_node ->tlv ->value_length; // match param switch (be32toh(*param_id)) { // config item count case asn1::ParameterType::_pt_mink_config_ac_line: line.clear(); line.append(tmp_val, tmp_val_l); break; default: break; } } tokenize: // tokenize mink_utils::tokenize(&line, tmp_lst, 50, &tmp_size, true); // auto complete config->auto_complete(&cm_mode, config::CONFIG_ACM_TAB, config->get_cmd_tree(), config->get_definition_wn(&cfg_user_id)->wnode, tmp_lst, tmp_size, &ac_res, &res_size, &last_found, &error_count, tmp_err, false, &tmp_node_lst); // replace current line with auto completed values line.clear(); for (int i = 0; i < tmp_size; i++) { line.append(tmp_lst[i]); if (i < res_size) line.append(" "); else break; } // set values c->_action->set_linked_data(1, (unsigned char *)&ca_cfg_result, 1); // ac line p->get_child(0) ->_id ->set_linked_data(1, (unsigned char *)&pt_mink_config_ac_line, sizeof(uint32_t)); p->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)line.c_str(), line.size()); // cm mode p->get_child(1) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_cm_mode, sizeof(uint32_t)); p->get_child(1) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&cm_mode, 1); // include bodu *include_body = true; // continue stream->continue_sequence(); } StreamNext::StreamNext() : cfg_res(nullptr), new_stream(nullptr) { // big endian parameter ids pt_cfg_item_name = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_name); pt_cfg_item_path = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_path); pt_cfg_item_desc = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_desc); pt_cfg_item_ns = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_ns); pt_cfg_item_value = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_value); pt_cfg_item_nvalue = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_nvalue); pt_cfg_item_nt = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_nt); pt_cfg_cfg_line = htobe32(asn1::ParameterType::_pt_mink_config_cfg_line); pt_cfg_cfg_error = htobe32(asn1::ParameterType::_pt_mink_config_cfg_ac_err); pt_cfg_item_count = htobe32(asn1::ParameterType::_pt_mink_config_cfg_item_count); } // TAB stream next void StreamNext::process_tab(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; // more results if (new_stream->res_index < new_stream->ac_res.children.size()) { // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } // remove payload if (gdtm->_body->_conf->_payload != nullptr) gdtm->_body->_conf->_payload->unlink(1); // set params if (gdtm->_body->_conf->_params == nullptr) { gdtm->_body->_conf->set_params(); p = gdtm->_body->_conf->_params; // set children, allocate more for (int i = 0; i < 6; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = gdtm->_body->_conf->_params; int cc = p->children.size(); if (cc < 6) { // set children, allocate more for (int i = cc; i < 6; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 6) { // remove extra children if used in some other session, only 2 // needed for (int i = 6; i < cc; i++) p->get_child(i)->unlink(1); } } c = gdtm->_body->_conf; // set result action c->_action->set_linked_data(1, (unsigned char *)&new_stream->ca_cfg_result, 1); // item name p->get_child(0) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_name, sizeof(uint32_t)); p->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->ac_res.children[new_stream->res_index] ->name.c_str(), new_stream->ac_res.children[new_stream->res_index] ->name.size()); // item desc p->get_child(1) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_desc, sizeof(uint32_t)); p->get_child(1) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->ac_res.children[new_stream->res_index] ->desc.c_str(), new_stream->ac_res.children[new_stream->res_index] ->desc.size()); // node state p->get_child(2) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_ns, sizeof(uint32_t)); p->get_child(2) ->_value ->get_child(0) ->set_linked_data(1,(unsigned char *)&new_stream->ac_res.children[new_stream->res_index] ->node_state, 1); // node value p->get_child(3) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_value, sizeof(uint32_t)); p->get_child(3) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->ac_res.children[new_stream->res_index] ->value.c_str(), new_stream->ac_res.children[new_stream->res_index] ->value.size()); // node new value p->get_child(4) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_nvalue, sizeof(uint32_t)); p->get_child(4) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->ac_res.children[new_stream->res_index] ->new_value.c_str(), new_stream->ac_res.children[new_stream->res_index] ->new_value.size()); // node type p->get_child(5) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_nt, sizeof(uint32_t)); p->get_child(5) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&new_stream->ac_res.children[new_stream->res_index] ->node_type, 1); // include body *include_body = true; // continue stream->continue_sequence(); // next result item ++new_stream->res_index; // finished } else { // end sequence stream->end_sequence(); // free temp nodes and clear res buffer new_stream->ac_res.children.clear(); std::all_of(new_stream->tmp_node_lst.children.cbegin(), new_stream->tmp_node_lst.children.cend(), [](const config::ConfigItem *ci) { delete ci; return true; }); new_stream->tmp_node_lst.children.clear(); } } // GET stream next void StreamNext::process_get(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; // more results if (new_stream->res_index < new_stream->ac_res.children.size()) { // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } // remove payload if (gdtm->_body->_conf->_payload != nullptr) gdtm->_body->_conf->_payload->unlink(1); // set params if (gdtm->_body->_conf->_params == nullptr) { gdtm->_body->_conf->set_params(); p = gdtm->_body->_conf->_params; // set children, allocate more for (int i = 0; i < 3; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = gdtm->_body->_conf->_params; int cc = p->children.size(); if (cc < 3) { // set children, allocate more for (int i = cc; i < 3; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 3) { // remove extra children if used in some other session, only 2 // needed for (int i = 3; i < cc; i++) p->get_child(i)->unlink(1); } } c = gdtm->_body->_conf; // set result action c->_action->set_linked_data(1, (unsigned char *)&new_stream->ca_cfg_result, 1); // item path // get full path and save to tmp_node_lst config::Config::get_parent_line(new_stream->ac_res.children[new_stream->res_index], &new_stream->tmp_node_lst.name); new_stream->tmp_node_lst.name.append(new_stream->ac_res.children[new_stream->res_index]->name); p->get_child(0)->_id->set_linked_data(1, (unsigned char *)&pt_cfg_item_path, sizeof(uint32_t)); p->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->tmp_node_lst.name.c_str(), new_stream->tmp_node_lst.name.size()); // node value p->get_child(1) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_value, sizeof(uint32_t)); p->get_child(1) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->ac_res.children[new_stream->res_index] ->value.c_str(), new_stream->ac_res.children[new_stream->res_index] ->value.size()); // node type p->get_child(2) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_item_nt, sizeof(uint32_t)); p->get_child(2) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)&new_stream->ac_res.children[new_stream->res_index] ->node_type, 1); // include body *include_body = true; // continue stream->continue_sequence(); // next result item ++new_stream->res_index; // finished } else { // end sequence stream->end_sequence(); // free temp nodes and clear res buffer new_stream->ac_res.children.clear(); } } // ENTER stream next void StreamNext::process_enter(gdt::GDTCallbackArgs *args) { auto stream = (gdt::GDTStream *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_STREAM); asn1::GDTMessage *gdtm = stream->get_gdt_message(); auto include_body = (bool *)args->get_arg(gdt::GDT_CB_INPUT_ARGS, gdt::GDT_CB_ARG_BODY); asn1::ConfigMessage *c = nullptr; asn1::Parameters *p = nullptr; // results if (getline(new_stream->line_stream, new_stream->line_buffer)) { // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } // remove payload if (gdtm->_body->_conf->_payload != nullptr) gdtm->_body->_conf->_payload->unlink(1); // set params if (gdtm->_body->_conf->_params == nullptr) { gdtm->_body->_conf->set_params(); p = gdtm->_body->_conf->_params; // set children, allocate more for (int i = 0; i < 1; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = gdtm->_body->_conf->_params; int cc = p->children.size(); if (cc < 1) { // set children, allocate more for (int i = cc; i < 1; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 1) { // remove extra children if used in some other session, only 2 // needed for (int i = 1; i < cc; i++) p->get_child(i)->unlink(1); } } c = gdtm->_body->_conf; // set result action c->_action->set_linked_data(1, (unsigned char *)&new_stream->ca_cfg_result, 1); // line p->get_child(0)->_id->set_linked_data(1, (unsigned char *)&pt_cfg_cfg_line, sizeof(uint32_t)); p->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->line_buffer.c_str(), new_stream->line_buffer.size()); // include body *include_body = true; // continue stream->continue_sequence(); // errors } else if (new_stream->err_index >= 0) { // prepare body if (gdtm->_body != nullptr) { gdtm->_body->unlink(1); gdtm->_body->_conf->set_linked_data(1); } else { gdtm->set_body(); gdtm->prepare(); } // remove payload if (gdtm->_body->_conf->_payload != nullptr) gdtm->_body->_conf->_payload->unlink(1); // set params if (gdtm->_body->_conf->_params == nullptr) { gdtm->_body->_conf->set_params(); p = gdtm->_body->_conf->_params; // set children, allocate more for (int i = 0; i < 1; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); // unlink params before setting new ones } else { p = gdtm->_body->_conf->_params; int cc = p->children.size(); if (cc < 1) { // set children, allocate more for (int i = cc; i < 1; i++) { p->set_child(i); p->get_child(i)->set_value(); p->get_child(i)->_value->set_child(0); } // prepare gdtm->prepare(); } else if (cc > 1) { // remove extra children if used in some other session, only 2 // needed for (int i = 1; i < cc; i++) p->get_child(i)->unlink(1); } } c = gdtm->_body->_conf; // set result action c->_action->set_linked_data(1, (unsigned char *)&new_stream->ca_cfg_result, 1); // error line p->get_child(0) ->_id ->set_linked_data(1, (unsigned char *)&pt_cfg_cfg_error, sizeof(uint32_t)); p->get_child(0) ->_value ->get_child(0) ->set_linked_data(1, (unsigned char *)new_stream->tmp_err[new_stream->err_index].c_str(), new_stream->tmp_err[new_stream->err_index].size()); // include body *include_body = true; // continue stream->continue_sequence(); // dec error index --new_stream->err_index; // finished } else { // end sequence stream->end_sequence(); // free temp nodes and clear res buffer new_stream->ac_res.children.clear(); std::all_of(new_stream->tmp_node_lst.children.cbegin(), new_stream->tmp_node_lst.children.cend(), [](const config::ConfigItem *ci) { delete ci; return true; }); new_stream->tmp_node_lst.children.clear(); } } // stream next, send config item nodes after auto completed line void StreamNext::run(gdt::GDTCallbackArgs *args) { // mink daemons if (new_stream->config_action == asn1::ConfigAction::_ca_cfg_get) { process_get(args); // CLI } else { switch (new_stream->ac_mode) { case config::CONFIG_ACM_TAB: process_tab(args); break; case config::CONFIG_ACM_ENTER: process_enter(args); break; default: break; } } }
39.176821
112
0.442215
[ "vector" ]
07ee053d23c43f6722706145345d6895d0da07e2
3,568
cpp
C++
src/cpp/ray.cpp
Byron/rust-tracer
f16522fbd01fb1361ac4b94746e3d46539a54355
[ "BSD-3-Clause" ]
16
2015-02-14T14:52:50.000Z
2022-01-05T15:27:41.000Z
src/cpp/ray.cpp
Byron/rust-tracer
f16522fbd01fb1361ac4b94746e3d46539a54355
[ "BSD-3-Clause" ]
10
2015-02-02T10:30:50.000Z
2015-04-09T12:44:07.000Z
src/cpp/ray.cpp
Byron/rust-tracer
f16522fbd01fb1361ac4b94746e3d46539a54355
[ "BSD-3-Clause" ]
null
null
null
#include <vector> #include <iostream> #include <limits> #include <cmath> #include "stdlib.h" using namespace std; numeric_limits<float> real; float delta = sqrt(real.epsilon()), infinity = real.infinity(); struct Vec { float x, y, z; Vec(float x2, float y2, float z2) : x(x2), y(y2), z(z2) {} }; Vec operator+(const Vec &a, const Vec &b) { return Vec(a.x+b.x, a.y+b.y, a.z+b.z); } Vec operator-(const Vec &a, const Vec &b) { return Vec(a.x-b.x, a.y-b.y, a.z-b.z); } Vec operator*(float a, const Vec &b) { return Vec(a*b.x, a*b.y, a*b.z); } float dot(const Vec &a, const Vec &b) { return a.x*b.x + a.y*b.y + a.z*b.z; } Vec unitise(const Vec &a) { return (1 / sqrt(dot(a, a))) * a; } typedef pair<float, Vec> Hit; struct Ray { Vec orig, dir; Ray(const Vec &o, const Vec &d) : orig(o), dir(d) {} }; struct Scene { virtual ~Scene() {}; virtual void intersect(Hit &, const Ray &) const = 0; }; struct Sphere : public Scene { Vec center; float radius; Sphere(Vec c, float r) : center(c), radius(r) {} ~Sphere() {} inline float ray_sphere(const Ray &ray) const { Vec v = center - ray.orig; float b = dot(v, ray.dir), disc = b*b - dot(v, v) + radius * radius; if (disc < 0) return infinity; float d = sqrt(disc), t2 = b + d; if (t2 < 0) return infinity; float t1 = b - d; return (t1 > 0 ? t1 : t2); } void intersect(Hit &hit, const Ray &ray) const { float lambda = ray_sphere(ray); if (lambda >= hit.first) return; hit.first = lambda; hit.second = unitise(ray.orig + lambda*ray.dir - center); } }; typedef vector<Scene *> Scenes; struct Group : public Scene { Sphere bound; Scenes child; Group(Sphere b, Scenes c) : bound(b), child(c) {} ~Group() { for (Scenes::const_iterator it=child.begin(); it!=child.end(); ++it) delete *it; } void intersect(Hit &hit, const Ray &ray) const { float l = bound.ray_sphere(ray); if (l >= hit.first) return; for (Scenes::const_iterator it=child.begin(); it!=child.end(); ++it) { (*it)->intersect(hit, ray); } } }; inline void intersect(const Ray &ray, const Scene &s, Hit& hit) { s.intersect(hit, ray); } inline float ray_trace(const Vec &light, const Ray &ray, const Scene &s) { Hit hit(infinity, Vec(0, 0, 0)); intersect(ray, s, hit); if (hit.first == infinity) return 0; float g = dot(hit.second, light); if (g >= 0) return 0.; Vec p = ray.orig + hit.first*ray.dir + delta*hit.second; hit.first = infinity; intersect(Ray(p, -1. * light), s, hit); return hit.first < infinity ? 0 : -g; } Scene *create(int level, const Vec &c, float r) { Scene *s = new Sphere(c, r); if (level == 1) return s; Scenes child; child.reserve(5); child.push_back(s); float rn = 3*r/sqrt(12.); for (int dz=-1; dz<=1; dz+=2) for (int dx=-1; dx<=1; dx+=2) child.push_back(create(level-1, c + rn*Vec(dx, 1, dz), r/2)); return new Group(Sphere(c, 3*r), child); } int main(int argc, char *argv[]) { int level = 8, w = 1024, h = 768, ss = 4; if (argc == 2) level = atoi(argv[1]); Vec light = unitise(Vec(-1, -3, 2)); Scene *s(create(level, Vec(0, -1, 0), 1)); cout << "P5\n" << w << " " << h << "\n255\n"; for (int y=h-1; y>=0; --y) for (int x=0; x<w; ++x) { float g=0; for (int dx=0; dx<ss; ++dx) for (int dy=0; dy<ss; ++dy) { Vec dir(unitise(Vec(x+dx*1./ss-w/2., y+dy*1./ss-h/2., w))); g += ray_trace(light, Ray(Vec(0, 0, -4), dir), *s); } cout << char(int(.5 + 255. * g / (ss*ss))); } delete s; return 0; }
27.236641
77
0.575673
[ "vector" ]
07f1331dee2480a380cbc3f453beba6aa607f87d
1,026
cpp
C++
src/teacher.cpp
RichardoMrMu/gsoap-onvif
76a0aadd426aedd8c212467caeb029133a06eb9a
[ "MIT" ]
3
2021-09-15T12:08:25.000Z
2022-02-23T06:21:29.000Z
src/teacher.cpp
RichardoMrMu/gsoap-onvif
76a0aadd426aedd8c212467caeb029133a06eb9a
[ "MIT" ]
null
null
null
src/teacher.cpp
RichardoMrMu/gsoap-onvif
76a0aadd426aedd8c212467caeb029133a06eb9a
[ "MIT" ]
1
2022-03-18T11:07:07.000Z
2022-03-18T11:07:07.000Z
#include "teacher.hpp" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; using namespace wl; void TeaAnalyser::SetReader(const wl::CameraConfig& config ) { LOG(INFO) << "Test HIKIPCameraReader."; std::string url = "rtsp://" + config.username + ":" + config.password + "@" + config.ip + "/mpeg4/ch1/sub/av_stream"; reader_.reset(new OpenCVCameraReader(url)); ptzer_.reset(new Ptz(config)); } void TeaAnalyser::Run() { fs::Timer timer; //std::vector<int> PresetTokens = {1,2}; while (!cam_is_stop_) { timer.tic(); for(auto &PresetToken:PresetTokens){ // goto one preset ptzer_->GotoPreset(PresetToken); wait(1300); // get one frame reader_->Next(&frame_); //save one frame std::string frame_path = "/blackboard.jpg"; cv::imwrite(frame_path, frame_.img); timer.toc(); LOG(INFO) << "frame : " << frame_.frame_id << " cost: " << timer.total_time(); } } }
20.52
80
0.655945
[ "vector" ]
07f36604085b475ce12af034e4f2aa48c193f6e5
1,491
cpp
C++
p567_Permutation_in_String/p567.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p567_Permutation_in_String/p567.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
p567_Permutation_in_String/p567.cpp
Song1996/Leetcode
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include <stack> #include <queue> #include <map> #include <string> #include <cassert> #include <stdlib.h> #include <fstream> #include <algorithm> #include <cmath> using namespace std; class Solution { public: vector<int> mem; bool checkInclusion(string s1, string s2) { int l = s1.length(); if(s2.length()<l) return false; mem.clear(); mem.resize(26,0); for(int i = 0; i < l; i++) mem[s1[i]-'a']++; for(int i = 0; i < l; i++) mem[s2[i]-'a']--; int n = 0; for(int i = 0; i < 26; i++) if(mem[i]!=0) n++; if(n==0) return true; for(int i = l; i < s2.length(); i++) { if(s2[i-l]==s2[i]) continue; mem[s2[i-l]-'a']++; mem[s2[i]-'a']--; if(mem[s2[i-l]-'a']==0) n--; else if(mem[s2[i-l]-'a']==1) n++; if(mem[s2[i]-'a']==0) n--; else if(mem[s2[i]-'a']==-1) n++; if(n==0) return true; } return false; } }; int main() { Solution s; string s1, s2; s1 = "ab", s2 = "eidbaooo"; printf("%s\n",s.checkInclusion(s1,s2)?"true":"false"); s1= "ab", s2 = "eidboaoo"; printf("%s\n",s.checkInclusion(s1,s2)?"true":"false"); s1 = "trinitrophenylmethylnitramine"; s2 = "dinitrophenylhydrazinetrinitrophenylmethylnitramine"; //s2 = "trinitrophenylmethylnitramine"; printf("%s\n",s.checkInclusion(s1,s2)?"true":"false"); return 0; }
28.673077
63
0.52448
[ "vector" ]
07f4567d59fde94e69851042556961d355fdc259
11,913
cpp
C++
dbms/src/Storages/DeltaMerge/SSTFilesToBlockInputStream.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Storages/DeltaMerge/SSTFilesToBlockInputStream.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Storages/DeltaMerge/SSTFilesToBlockInputStream.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, 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 <Interpreters/Context.h> #include <Poco/File.h> #include <RaftStoreProxyFFI/ColumnFamily.h> #include <Storages/DeltaMerge/DMVersionFilterBlockInputStream.h> #include <Storages/DeltaMerge/DeltaMergeStore.h> #include <Storages/DeltaMerge/File/DMFile.h> #include <Storages/DeltaMerge/File/DMFileBlockOutputStream.h> #include <Storages/DeltaMerge/PKSquashingBlockInputStream.h> #include <Storages/DeltaMerge/SSTFilesToBlockInputStream.h> #include <Storages/StorageDeltaMerge.h> #include <Storages/Transaction/PartitionStreams.h> #include <Storages/Transaction/ProxyFFI.h> #include <Storages/Transaction/Region.h> #include <Storages/Transaction/SSTReader.h> #include <Storages/Transaction/TMTContext.h> #include <common/logger_useful.h> namespace DB { namespace ErrorCodes { extern const int ILLFORMAT_RAFT_ROW; } // namespace ErrorCodes namespace DM { SSTFilesToBlockInputStream::SSTFilesToBlockInputStream( // RegionPtr region_, const SSTViewVec & snaps_, const TiFlashRaftProxyHelper * proxy_helper_, DecodingStorageSchemaSnapshotConstPtr schema_snap_, Timestamp gc_safepoint_, bool force_decode_, TMTContext & tmt_, size_t expected_size_) : region(std::move(region_)) , snaps(snaps_) , proxy_helper(proxy_helper_) , schema_snap(std::move(schema_snap_)) , tmt(tmt_) , gc_safepoint(gc_safepoint_) , expected_size(expected_size_) , log(&Poco::Logger::get("SSTFilesToBlockInputStream")) , force_decode(force_decode_) { } SSTFilesToBlockInputStream::~SSTFilesToBlockInputStream() = default; void SSTFilesToBlockInputStream::readPrefix() { for (UInt64 i = 0; i < snaps.len; ++i) { auto & snapshot = snaps.views[i]; switch (snapshot.type) { case ColumnFamilyType::Default: default_cf_reader = std::make_unique<SSTReader>(proxy_helper, snapshot); break; case ColumnFamilyType::Write: write_cf_reader = std::make_unique<SSTReader>(proxy_helper, snapshot); break; case ColumnFamilyType::Lock: lock_cf_reader = std::make_unique<SSTReader>(proxy_helper, snapshot); break; } } process_keys.default_cf = 0; process_keys.write_cf = 0; process_keys.lock_cf = 0; } void SSTFilesToBlockInputStream::readSuffix() { // There must be no data left when we write suffix assert(!write_cf_reader || !write_cf_reader->remained()); assert(!default_cf_reader || !default_cf_reader->remained()); assert(!lock_cf_reader || !lock_cf_reader->remained()); // reset all SSTReaders and return without writting blocks any more. write_cf_reader.reset(); default_cf_reader.reset(); lock_cf_reader.reset(); } Block SSTFilesToBlockInputStream::read() { std::string loaded_write_cf_key; while (write_cf_reader && write_cf_reader->remained()) { // To decode committed rows from key-value pairs into block, we need to load // all need key-value pairs from default and lock column families. // Check the MVCC (key-format and transaction model) for details // https://en.pingcap.com/blog/2016-11-17-mvcc-in-tikv#mvcc // To ensure correctness, when loading key-values pairs from the default and // the lock column family, we will load all key-values which rowkeys are equal // or less that the last rowkey from the write column family. { BaseBuffView key = write_cf_reader->key(); BaseBuffView value = write_cf_reader->value(); region->insert(ColumnFamilyType::Write, TiKVKey(key.data, key.len), TiKVValue(value.data, value.len)); ++process_keys.write_cf; if (process_keys.write_cf % expected_size == 0) { loaded_write_cf_key.clear(); loaded_write_cf_key.assign(key.data, key.len); } } // Notice: `key`, `value` are string-view-like object, should never use after `next` called write_cf_reader->next(); if (process_keys.write_cf % expected_size == 0) { const DecodedTiKVKey rowkey = RecordKVFormat::decodeTiKVKey(TiKVKey(std::move(loaded_write_cf_key))); // Batch the loading from other CFs until we need to decode data loadCFDataFromSST(ColumnFamilyType::Default, &rowkey); loadCFDataFromSST(ColumnFamilyType::Lock, &rowkey); auto block = readCommitedBlock(); if (block.rows() != 0) return block; // else continue to decode key-value from write CF. } } // Load all key-value pairs from other CFs loadCFDataFromSST(ColumnFamilyType::Default, nullptr); loadCFDataFromSST(ColumnFamilyType::Lock, nullptr); // All uncommitted data are saved in `region`, decode the last committed rows. return readCommitedBlock(); } void SSTFilesToBlockInputStream::loadCFDataFromSST(ColumnFamilyType cf, const DecodedTiKVKey * const rowkey_to_be_included) { SSTReader * reader; size_t * p_process_keys = &process_keys.default_cf; DecodedTiKVKey * last_loaded_rowkey = &default_last_loaded_rowkey; if (cf == ColumnFamilyType::Default) { reader = default_cf_reader.get(); p_process_keys = &process_keys.default_cf; last_loaded_rowkey = &default_last_loaded_rowkey; } else if (cf == ColumnFamilyType::Lock) { reader = lock_cf_reader.get(); p_process_keys = &process_keys.lock_cf; last_loaded_rowkey = &lock_last_loaded_rowkey; } else throw Exception("Unknown cf, should not happen!"); // Simply read to the end of SST file if (rowkey_to_be_included == nullptr) { while (reader && reader->remained()) { BaseBuffView key = reader->key(); BaseBuffView value = reader->value(); // TODO: use doInsert to avoid locking region->insert(cf, TiKVKey(key.data, key.len), TiKVValue(value.data, value.len)); reader->next(); (*p_process_keys) += 1; } #ifndef NDEBUG LOG_FMT_DEBUG(log, "Done loading all kvpairs from [CF={}] [offset={}] [write_cf_offset={}] ", CFToName(cf), (*p_process_keys), process_keys.write_cf); #endif return; } size_t process_keys_offset_end = process_keys.write_cf; while (reader && reader->remained()) { // If we have load all keys that less than or equal to `rowkey_to_be_included`, done. // We keep an assumption that rowkeys are memory-comparable and they are asc sorted in the SST file if (!last_loaded_rowkey->empty() && *last_loaded_rowkey > *rowkey_to_be_included) { #ifndef NDEBUG LOG_FMT_DEBUG( log, "Done loading from [CF={}] [offset={}] [write_cf_offset={}] [last_loaded_rowkey={}] [rowkey_to_be_included={}]", CFToName(cf), (*p_process_keys), process_keys.write_cf, Redact::keyToDebugString(last_loaded_rowkey->data(), last_loaded_rowkey->size()), (rowkey_to_be_included ? Redact::keyToDebugString(rowkey_to_be_included->data(), rowkey_to_be_included->size()) : "<end>")); #endif break; } // Let's try to load keys until process_keys_offset_end while (reader && reader->remained() && *p_process_keys < process_keys_offset_end) { { BaseBuffView key = reader->key(); BaseBuffView value = reader->value(); // TODO: use doInsert to avoid locking region->insert(cf, TiKVKey(key.data, key.len), TiKVValue(value.data, value.len)); (*p_process_keys) += 1; if (*p_process_keys == process_keys_offset_end) { *last_loaded_rowkey = RecordKVFormat::decodeTiKVKey(TiKVKey(key.data, key.len)); } } // Notice: `key`, `value` are string-view-like object, should never use after `next` called reader->next(); } // Update the end offset. // If there are no more key-value, the outer while loop will be break. // Else continue to read next batch from current CF. process_keys_offset_end += expected_size; } } Block SSTFilesToBlockInputStream::readCommitedBlock() { if (is_decode_cancelled) return {}; try { // Read block from `region`. If the schema has been updated, it will // throw an exception with code `ErrorCodes::REGION_DATA_SCHEMA_UPDATED` return GenRegionBlockDataWithSchema(region, schema_snap, gc_safepoint, force_decode, tmt); } catch (DB::Exception & e) { if (e.code() == ErrorCodes::ILLFORMAT_RAFT_ROW) { // br or lighting may write illegal data into tikv, stop decoding. LOG_FMT_WARNING(log, "Got error while reading region committed cache: {}. Stop decoding rows into DTFiles and keep uncommitted data in region.", e.displayText()); // Cancel the decoding process. // Note that we still need to scan data from CFs and keep them in `region` is_decode_cancelled = true; return {}; } else throw; } } /// Methods for BoundedSSTFilesToBlockInputStream BoundedSSTFilesToBlockInputStream::BoundedSSTFilesToBlockInputStream( // SSTFilesToBlockInputStreamPtr child, const ColId pk_column_id_, const DecodingStorageSchemaSnapshotConstPtr & schema_snap) : pk_column_id(pk_column_id_) , _raw_child(std::move(child)) { const bool is_common_handle = schema_snap->is_common_handle; // Initlize `mvcc_compact_stream` // First refine the boundary of blocks. Note that the rows decoded from SSTFiles are sorted by primary key asc, timestamp desc // (https://github.com/tikv/tikv/blob/v5.0.1/components/txn_types/src/types.rs#L103-L108). // While DMVersionFilter require rows sorted by primary key asc, timestamp asc, so we need an extra sort in PKSquashing. auto stream = std::make_shared<PKSquashingBlockInputStream</*need_extra_sort=*/true>>(_raw_child, pk_column_id, is_common_handle); mvcc_compact_stream = std::make_unique<DMVersionFilterBlockInputStream<DM_VERSION_FILTER_MODE_COMPACT>>( stream, *(schema_snap->column_defines), _raw_child->gc_safepoint, is_common_handle); } void BoundedSSTFilesToBlockInputStream::readPrefix() { mvcc_compact_stream->readPrefix(); } void BoundedSSTFilesToBlockInputStream::readSuffix() { mvcc_compact_stream->readSuffix(); } Block BoundedSSTFilesToBlockInputStream::read() { return mvcc_compact_stream->read(); } SSTFilesToBlockInputStream::ProcessKeys BoundedSSTFilesToBlockInputStream::getProcessKeys() const { return _raw_child->process_keys; } const RegionPtr BoundedSSTFilesToBlockInputStream::getRegion() const { return _raw_child->region; } std::tuple<size_t, size_t, UInt64> // BoundedSSTFilesToBlockInputStream::getMvccStatistics() const { return std::make_tuple( mvcc_compact_stream->getEffectiveNumRows(), mvcc_compact_stream->getNotCleanRows(), mvcc_compact_stream->getGCHintVersion()); } } // namespace DM } // namespace DB
37.93949
174
0.676152
[ "object", "model" ]
07f8c7dd1ea9aacc66a1cfb6da8922911d08152b
1,335
cpp
C++
modules/task_1/zhafyarov_o_graham_pass/main.cpp
egorshul/pp_2021_spring_engineers
833868c757648149a152ff0913c5e3905cd56176
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/zhafyarov_o_graham_pass/main.cpp
egorshul/pp_2021_spring_engineers
833868c757648149a152ff0913c5e3905cd56176
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/zhafyarov_o_graham_pass/main.cpp
egorshul/pp_2021_spring_engineers
833868c757648149a152ff0913c5e3905cd56176
[ "BSD-3-Clause" ]
1
2021-03-29T14:29:42.000Z
2021-03-29T14:29:42.000Z
// Copyright 2021 Zhafyarov Oleg #include <gtest/gtest.h> #include <vector> #include <algorithm> #include "./graham_pass.h" TEST(Sequential, Test1) { std::vector<point> vec = {{1, 5}, {4, 8}, {8, 2}, {9, 3}, {1, 8}, {7, 7}}; std::vector<size_t> result; int count = 0; result = GrahamPass(vec, &count); std::vector<size_t> compare = { 0, 2, 3, 5, 1, 4 }; ASSERT_EQ(compare, result); } TEST(Sequential, Test2) { std::vector<point> vec = { {1, 5}, {4, 8}, {8, 2}, {9, 3}, {1, 8}, {7, 7}, {5, 5}, {2, 1}, {11, 9} }; std::vector<size_t> result; int count = 0; result = GrahamPass(vec, &count); std::vector<size_t> compare = { 0, 7, 2, 3, 8, 4 }; ASSERT_EQ(compare, result); } TEST(Sequential, Test3) { std::vector<point> vec = { {1, 1}, {1, 4}, {4, 1}, {4, 4}, {2, 2}}; std::vector<size_t> result; int count = 0; int count_tmp = 4; result = GrahamPass(vec, &count); ASSERT_EQ(count, count_tmp); } TEST(Sequential, Test4) { ASSERT_ANY_THROW(std::vector<point> vec = RandomVector(-1)); } TEST(Sequential, Test5) { int size = 50; int count = 0; std::vector<point> vec = RandomVector(size); std::vector<size_t> result; result = GrahamPass(vec, &count); ASSERT_GT(count, 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.673077
76
0.602247
[ "vector" ]
07fbb36a9a8174c1afe76de2ba774836cca44dd3
9,049
cc
C++
Dragon/src/operators/arithmetic/dot_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
212
2015-07-05T07:57:17.000Z
2022-02-27T01:55:35.000Z
Dragon/src/operators/arithmetic/dot_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
6
2016-07-07T14:31:56.000Z
2017-12-12T02:21:15.000Z
Dragon/src/operators/arithmetic/dot_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
71
2016-03-24T09:02:41.000Z
2021-06-03T01:52:41.000Z
#include "operators/arithmetic/dot_op.h" #include "core/workspace.h" #include "utils/math_functions.h" namespace dragon { template <class Context> template <typename T> void DotOp<Context>::DotRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, CPUContext>(); Ydata[0] = math::Dot<T, Context>(input(0).count(), X1data, X2data); } template <class Context> template <typename T> void DotOp<Context>::GemmRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, Context>(); math::Gemm<T, Context>(transA ? CblasTrans : CblasNoTrans, transB ? CblasTrans : CblasNoTrans, M, N1, K1, 1.0, X1data, X2data, 0.0, Ydata); } template <class Context> template <typename T> void DotOp<Context>::GemvRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, Context>(); math::Gemv<T, Context>(transA ? CblasTrans : CblasNoTrans, M, N1, 1.0, X1data, X2data, 0.0, Ydata); } template <class Context> void DotOp<Context>::RunOnDevice() { if (input(0).ndim() == 1 && input(1).ndim() == 1) { CHECK_EQ(input(0).dim(0), input(1).dim(0)) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); output(0)->Reshape(vector<TIndex>(1, 1)); if (input(0).template IsType<float>()) DotRunWithType<float>(); else LOG(FATAL) << "Unsupported input types."; } else if (input(0).ndim() >= 2 && input(1).ndim() == 2) { TIndex m = input(0).count() / input(0).dim(-1), k = input(0).dim(-1); M = transA ? k : m; K1 = transA ? m : k; K2 = transB ? input(1).dim(1) : input(1).dim(0); N1 = transB ? input(1).dim(0) : input(1).dim(1); CHECK_EQ(K1, K2) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); vector<TIndex> dims = input(0).dims(); dims[dims.size() - 1] = N1; output(0)->Reshape(dims); if (input(0).template IsType<float>()) GemmRunWithType<float>(); #ifdef WITH_CUDA_FP16 else if (input(0).template IsType<float16>()) GemmRunWithType<float16>(); #endif else LOG(FATAL) << "Unsupported input types."; } else if (input(0).ndim() >= 2 && input(1).ndim() == 1) { TIndex m = input(0).count() / input(0).dim(-1), k = input(0).dim(-1); M = transA ? k : m; N1 = transA ? m : k; N2 = input(1).dim(0); CHECK_EQ(N1, N2) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); vector<TIndex> dims = input(0).dims(); dims.pop_back(); output(0)->Reshape(dims); if (input(0).template IsType<float>()) GemvRunWithType<float>(); #ifdef WITH_CUDA_FP16 else if (input(0).template IsType<float16>()) GemvRunWithType<float16>(); #endif else LOG(FATAL) << "Unsupported input types."; } else { LOG(FATAL) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); } } DEPLOY_CPU(Dot); #ifdef WITH_CUDA DEPLOY_CUDA(Dot); #endif OPERATOR_SCHEMA(Dot).NumInputs(2).NumOutputs(1); template <class Context> template <typename T> void DotGradientOp<Context>::DotRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* dYdata = input(2).template data<T, CPUContext>(); auto* dX1data = output(0)->template mutable_data<T, Context>(); auto* dX2data = output(1)->template mutable_data<T, Context>(); this->ctx().template Copy<T, Context, Context>(output(0)->count(), dX1data, X2data); this->ctx().template Copy<T, Context, Context>(output(1)->count(), dX2data, X1data); math::MulScalar<T, Context>(output(0)->count(), dYdata[0], dX1data); math::MulScalar<T, Context>(output(1)->count(), dYdata[0], dX2data); } template <class Context> template <typename T> void DotGradientOp<Context>::GemmRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* dYdata = input(2).template data<T, Context>(); auto* dX1data = output(0)->template mutable_data<T, Context>(); auto* dX2data = output(1)->template mutable_data<T, Context>(); math::Gemm<T, Context>(CblasNoTrans, transB ? CblasNoTrans : CblasTrans, M, K1, N1, 1.0, dYdata, X2data, 0.0, dX1data); math::Gemm<T, Context>(transA ? CblasNoTrans : CblasTrans, CblasNoTrans, K1, N1, M, 1.0, X1data, dYdata, 0.0, dX2data); } template <class Context> template <typename T> void DotGradientOp<Context>::GemvRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* dYdata = input(2).template data<T, Context>(); auto* dX1data = output(0)->template mutable_data<T, Context>(); auto* dX2data = output(1)->template mutable_data<T, Context>(); math::Gemm<T, Context>(CblasNoTrans, CblasNoTrans, M, N1, 1, 1.0, dYdata, X2data, 0.0, dX1data); math::Gemv<T, Context>(transA ? CblasNoTrans : CblasTrans, M, N1, 1.0, X1data, dYdata, 0.0, dX2data); } template <class Context> void DotGradientOp<Context>::RunOnDevice() { output(0)->ReshapeLike(input(0)); output(1)->ReshapeLike(input(1)); if (input(0).ndim() == 1 && input(1).ndim() == 1) { CHECK_EQ(input(0).dim(0), input(1).dim(0)) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); if (input(0).template IsType<float>()) DotRunWithType<float>(); else LOG(FATAL) << "Unsupported input types."; } else if (input(0).ndim() >= 2 && input(1).ndim() == 2) { TIndex m = input(0).count() / input(0).dim(-1), k = input(0).dim(-1); M = transA ? k : m; K1 = transA ? m : k; K2 = transB ? input(1).dim(1) : input(1).dim(0); N1 = transB ? input(1).dim(0) : input(1).dim(1); CHECK_EQ(K1, K2) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); if (input(0).template IsType<float>()) GemmRunWithType<float>(); #ifdef WITH_CUDA_FP16 else if (input(0).template IsType<float16>()) GemmRunWithType<float16>(); #endif else LOG(FATAL) << "Unsupported input types."; } else if (input(0).ndim() >= 2 && input(1).ndim() == 1) { TIndex m = input(0).count() / input(0).dim(-1), k = input(0).dim(-1); M = transA ? k : m; N1 = transA ? m : k; N2 = input(1).dim(0); CHECK_EQ(N1, N2) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); if (input(0).template IsType<float>()) GemvRunWithType<float>(); #ifdef WITH_CUDA_FP16 else if (input(0).template IsType<float16>()) GemvRunWithType<float16>(); #endif else LOG(FATAL) << "Unsupported input types."; } else { LOG(FATAL) << "\nTensor(" << input(0).name() << "): " << input(0).dim_string() << " can not Dot with Tensor" << "(" << input(1).name() << "): " << input(1).dim_string(); } } template <class Context> void DotGradientOp<Context>::ShareGradient() { for (int i = 0; i < OutputSize(); i++) { if (output(i)->name() != "ignore") { Tensor* dX = ws()->GetBuffer("Grad"); ws()->CreateAvatar(output(i), dX); break; } } } DEPLOY_CPU(DotGradient); #ifdef WITH_CUDA DEPLOY_CUDA(DotGradient); #endif OPERATOR_SCHEMA(DotGradient).NumInputs(3).NumOutputs(2); class GetDotGradient final : public GradientMakerBase { public: GRADIENT_MAKER_CTOR(GetDotGradient); vector<OperatorDef> MakeDefs() override { return SingleDef(def.type() + "Gradient", "", vector<string> {I(0), I(1), GO(0)}, vector<string> {GI(0), GI(1)}); } }; REGISTER_GRADIENT(Dot, GetDotGradient); } // namespace dragon
43.296651
88
0.569124
[ "vector" ]
580389b0b865bea21253db629a2f528095c94ec3
2,152
cpp
C++
src/kafka/kafka.cpp
halivor/php-flame
5674bcb11838cfcfdaf4d0211bd3b062945775d3
[ "MIT" ]
null
null
null
src/kafka/kafka.cpp
halivor/php-flame
5674bcb11838cfcfdaf4d0211bd3b062945775d3
[ "MIT" ]
null
null
null
src/kafka/kafka.cpp
halivor/php-flame
5674bcb11838cfcfdaf4d0211bd3b062945775d3
[ "MIT" ]
null
null
null
#include "../coroutine.h" #include "kafka.h" #include "_consumer.h" #include "consumer.h" #include "_producer.h" #include "producer.h" #include "message.h" namespace flame { namespace kafka { void declare(php::extension_entry& ext) { ext .function<consume>("flame\\kafka\\consume", { {"options", php::TYPE::ARRAY}, {"topics", php::TYPE::ARRAY}, }) .function<produce>("flame\\kafka\\produce", { {"options", php::TYPE::ARRAY}, {"topics", php::TYPE::ARRAY}, });; consumer::declare(ext); producer::declare(ext); message::declare(ext); } php::value consume(php::parameters& params) { php::array config = params[0]; php::array topics = params[1]; std::shared_ptr<coroutine> co = coroutine::current; // 建立连接 php::object obj(php::class_entry<consumer>::entry()); consumer* ptr = static_cast<consumer*>(php::native(obj)); ptr->cs_.reset(new _consumer(config, topics)); // 订阅并初始化消费过程 ptr->cs_->exec([co, ptr] (rd_kafka_t* conn, rd_kafka_resp_err_t& e) -> rd_kafka_message_t* { e = ptr->cs_->subscribe_wk(); return nullptr; }, [co, obj] (rd_kafka_t* conn, rd_kafka_message_t* msg, rd_kafka_resp_err_t e) { if(e != RD_KAFKA_RESP_ERR_NO_ERROR) { co->fail((boost::format("failed to subscribe topics: %d") % e).str()); }else{ co->resume(std::move(obj)); } }); return coroutine::async(); } php::value produce(php::parameters& params) { php::array config = params[0]; php::array topics = params[1]; std::shared_ptr<coroutine> co = coroutine::current; // 建立连接 php::object obj(php::class_entry<producer>::entry()); producer* ptr = static_cast<producer*>(php::native(obj)); ptr->pd_.reset(new _producer(config, topics)); return std::move(obj); } php::array convert(rd_kafka_headers_t* headers) { return nullptr; } rd_kafka_headers_t* convert(php::array headers) { return nullptr; } } }
32.606061
100
0.578067
[ "object" ]
5808951fab3c82e794d81c7f91efb6b044797882
2,353
cpp
C++
project/OFEC_sc2/instance/algorithm/multi_objective/nsgaii_sbx/nsgaii_sbx.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/multi_objective/nsgaii_sbx/nsgaii_sbx.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/multi_objective/nsgaii_sbx/nsgaii_sbx.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "NSGAII_SBX.h" #include "../../../../../core/problem/continuous/continuous.h" #ifdef OFEC_DEMO #include "../../../../../../ui/buffer/continuous/buffer_cont_MOP.h" extern unique_ptr<Demo::scene> Demo::msp_buffer; #endif namespace OFEC { NSGAII_SBX_pop::NSGAII_SBX_pop(size_t size_pop) : SBX_pop<>(size_pop) {} void NSGAII_SBX_pop::initialize() { SBX_pop::initialize(); for (auto& i : this->m_inds) m_offspring.emplace_back(*i); for (auto& i : this->m_inds) m_offspring.emplace_back(*i); } EvalTag NSGAII_SBX_pop::evolve() { if (this->m_inds.size() % 2 != 0) throw myexcept("population size should be even @NSGAII_SBXRealMu::evolve()"); EvalTag tag = EvalTag::Normal; for (size_t i = 0; i < this->m_inds.size(); i += 2) { std::vector<size_t> p(2); p[0] = tournament_selection(); do { p[1] = tournament_selection(); } while (p[1] == p[0]); crossover(p[0], p[1], m_offspring[i], m_offspring[i + 1]); mutate(m_offspring[i]); mutate(m_offspring[i + 1]); } for (auto& i : m_offspring) { tag = i.evaluate(); if (tag != EvalTag::Normal) break; } for (size_t i = 0; i < this->m_inds.size(); ++i) m_offspring[i+ this->m_inds.size()] = *this->m_inds[i]; survivor_selection(this->m_inds, m_offspring); m_iter++; return tag; } NSGAII_SBX::NSGAII_SBX(param_map & v) : algorithm(v.at("algorithm name")), m_pop(v.at("population size")) {} void NSGAII_SBX::initialize() { m_pop.set_cr(0.9); m_pop.set_mr(1.0 / CONTINUOUS_CAST->variable_size()); m_pop.set_eta(20, 20); m_pop.initialize(); m_pop.evaluate(); #ifdef OFEC_DEMO vector<vector<Solution<>*>> pops(1); for (size_t i = 0; i < m_pop.size(); ++i) pops[0].emplace_back(&m_pop[i].solut()); dynamic_cast<Demo::buffer_cont_MOP*>(Demo::msp_buffer.get())->updateBuffer_(&pops); #endif } void NSGAII_SBX::run_() { while (!terminating()) { m_pop.evolve(); #ifdef OFEC_DEMO vector<vector<Solution<>*>> pops(1); for (size_t i = 0; i < m_pop.size(); ++i) pops[0].emplace_back(&m_pop[i].solut()); dynamic_cast<Demo::buffer_cont_MOP*>(Demo::msp_buffer.get())->updateBuffer_(&pops); #endif } } void NSGAII_SBX::record() { size_t evals = CONTINUOUS_CAST->evaluations(); Real IGD = CONTINUOUS_CAST->get_optima().IGD_to_PF(m_pop); measure::get_measure()->record(global::ms_global.get(), evals, IGD); } }
32.232877
109
0.657034
[ "vector" ]
580a444b0df06a416d009f19e7e1d364d379624d
2,357
cpp
C++
backup/2/leetcode/c++/archive/15.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/leetcode/c++/archive/15.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/leetcode/c++/archive/15.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! class Solution { public: vector<vector<int>> threeSum(vector<int> &nums) { sort(nums.begin(), nums.end()); int n = nums.size(); vector<vector<int>> solutions; if (n == 0) { return solutions; } int pre_num1 = nums[0] - 1, pre_num2, pre_num3; int num1, num2, num3; for (int i = 0; i <= n - 3; i++) { num1 = nums[i]; if (num1 == pre_num1) { continue; } pre_num1 = num1; int start = i + 1; int end = n - 1; num2 = nums[start]; num3 = nums[end]; while (start < end) { int sum = num1 + num2 + num3; bool move_start = false; bool move_end = false; if (sum == 0) { solutions.push_back(vector<int>{num1, num2, num3}); move_start = true; move_end = true; } else if (sum < 0) { move_start = true; } else { move_end = true; } if (move_start) { pre_num2 = num2; while (start < end) { start++; num2 = nums[start]; if (num2 != pre_num2) { break; } } } if (move_end) { pre_num3 = num3; while (start < end) { end--; num3 = nums[end]; if (num3 != pre_num3) { break; } } } } } return solutions; } };
36.828125
345
0.420874
[ "vector" ]
580ce5459ed6ba89f707f5dede616d161a5d9b79
34,976
cxx
C++
osprey/be/cg/NVISA/exp_loadstore.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/NVISA/exp_loadstore.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/NVISA/exp_loadstore.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2005-2008 NVIDIA Corporation. All rights reserved. */ /* This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. */ /* CGEXP routines for loads and stores */ #include <map> #include "elf_stuff.h" #include "defs.h" #include "em_elf.h" #include "erglob.h" #include "erbe.h" #include "tracing.h" #include "config.h" #include "config_debug.h" #include "xstats.h" #include "topcode.h" #include "tn.h" #include "cg_flags.h" #include "targ_isa_enums.h" #include "targ_isa_lits.h" #include "op.h" #include "stblock.h" #include "data_layout.h" #include "strtab.h" #include "symtab.h" #include "cg.h" #include "cgexp.h" #include "cgexp_internals.h" #include "cgemit.h" // for CG_emit_non_gas_syntax #include "be_symtab.h" #include "whirl2ops.h" std::map<pair<UINT,INT64>, TN*> st_to_tn_map; void Exp_Ldst_Init (void) { st_to_tn_map.clear(); } static const TOP load_top[11] = { TOP_ld_qualifier_space_s8, TOP_ld_qualifier_space_s16, TOP_ld_qualifier_space_s32, TOP_ld_qualifier_space_s64, TOP_ld_qualifier_space_u8, TOP_ld_qualifier_space_u16, TOP_ld_qualifier_space_u32, TOP_ld_qualifier_space_u64, TOP_ld_qualifier_space_f32, TOP_ld_qualifier_space_f64 }; static const TOP loado_top[11] = { TOP_ld_qualifier_space_s8_o, TOP_ld_qualifier_space_s16_o, TOP_ld_qualifier_space_s32_o, TOP_ld_qualifier_space_s64_o, TOP_ld_qualifier_space_u8_o, TOP_ld_qualifier_space_u16_o, TOP_ld_qualifier_space_u32_o, TOP_ld_qualifier_space_u64_o, TOP_ld_qualifier_space_f32_o, TOP_ld_qualifier_space_f64_o }; static const TOP loadr_top[11] = { TOP_ld_qualifier_space_s8_r, TOP_ld_qualifier_space_s16_r, TOP_ld_qualifier_space_s32_r, TOP_ld_qualifier_space_s64_r, TOP_ld_qualifier_space_u8_r, TOP_ld_qualifier_space_u16_r, TOP_ld_qualifier_space_u32_r, TOP_ld_qualifier_space_u64_r, TOP_ld_qualifier_space_f32_r, TOP_ld_qualifier_space_f64_r }; static const TOP load32_top[11] = { TOP_ld_qualifier_space_s8_b32, TOP_ld_qualifier_space_s16_b32, TOP_UNDEFINED, TOP_UNDEFINED, TOP_ld_qualifier_space_u8_b32, TOP_ld_qualifier_space_u16_b32, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP load32o_top[11] = { TOP_ld_qualifier_space_s8_b32_o, TOP_ld_qualifier_space_s16_b32_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_ld_qualifier_space_u8_b32_o, TOP_ld_qualifier_space_u16_b32_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP load32r_top[11] = { TOP_ld_qualifier_space_s8_b32_r, TOP_ld_qualifier_space_s16_b32_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_ld_qualifier_space_u8_b32_r, TOP_ld_qualifier_space_u16_b32_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP loade_top[11] = { TOP_ld_qualifier_space_s8_a64, TOP_ld_qualifier_space_s16_a64, TOP_ld_qualifier_space_s32_a64, TOP_ld_qualifier_space_s64_a64, TOP_ld_qualifier_space_u8_a64, TOP_ld_qualifier_space_u16_a64, TOP_ld_qualifier_space_u32_a64, TOP_ld_qualifier_space_u64_a64, TOP_ld_qualifier_space_f32_a64, TOP_ld_qualifier_space_f64_a64 }; static const TOP loadeo_top[11] = { TOP_ld_qualifier_space_s8_a64_o, TOP_ld_qualifier_space_s16_a64_o, TOP_ld_qualifier_space_s32_a64_o, TOP_ld_qualifier_space_s64_a64_o, TOP_ld_qualifier_space_u8_a64_o, TOP_ld_qualifier_space_u16_a64_o, TOP_ld_qualifier_space_u32_a64_o, TOP_ld_qualifier_space_u64_a64_o, TOP_ld_qualifier_space_f32_a64_o, TOP_ld_qualifier_space_f64_a64_o }; static const TOP loader_top[11] = { TOP_ld_qualifier_space_s8_a64_r, TOP_ld_qualifier_space_s16_a64_r, TOP_ld_qualifier_space_s32_a64_r, TOP_ld_qualifier_space_s64_a64_r, TOP_ld_qualifier_space_u8_a64_r, TOP_ld_qualifier_space_u16_a64_r, TOP_ld_qualifier_space_u32_a64_r, TOP_ld_qualifier_space_u64_a64_r, TOP_ld_qualifier_space_f32_a64_r, TOP_ld_qualifier_space_f64_a64_r }; static const TOP loade32_top[11] = { TOP_ld_qualifier_space_s8_b32_a64, TOP_ld_qualifier_space_s16_b32_a64, TOP_UNDEFINED, TOP_UNDEFINED, TOP_ld_qualifier_space_u8_b32_a64, TOP_ld_qualifier_space_u16_b32_a64, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP loade32o_top[11] = { TOP_ld_qualifier_space_s8_b32_a64_o, TOP_ld_qualifier_space_s16_b32_a64_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_ld_qualifier_space_u8_b32_a64_o, TOP_ld_qualifier_space_u16_b32_a64_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP loade32r_top[11] = { TOP_ld_qualifier_space_s8_b32_a64_r, TOP_ld_qualifier_space_s16_b32_a64_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_ld_qualifier_space_u8_b32_a64_r, TOP_ld_qualifier_space_u16_b32_a64_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP store_top[11] = { TOP_st_qualifier_space_s8, TOP_st_qualifier_space_s16, TOP_st_qualifier_space_s32, TOP_st_qualifier_space_s64, TOP_st_qualifier_space_u8, TOP_st_qualifier_space_u16, TOP_st_qualifier_space_u32, TOP_st_qualifier_space_u64, TOP_st_qualifier_space_f32, TOP_st_qualifier_space_f64 }; static const TOP storeo_top[11] = { TOP_st_qualifier_space_s8_o, TOP_st_qualifier_space_s16_o, TOP_st_qualifier_space_s32_o, TOP_st_qualifier_space_s64_o, TOP_st_qualifier_space_u8_o, TOP_st_qualifier_space_u16_o, TOP_st_qualifier_space_u32_o, TOP_st_qualifier_space_u64_o, TOP_st_qualifier_space_f32_o, TOP_st_qualifier_space_f64_o }; static const TOP storer_top[11] = { TOP_st_qualifier_space_s8_r, TOP_st_qualifier_space_s16_r, TOP_st_qualifier_space_s32_r, TOP_st_qualifier_space_s64_r, TOP_st_qualifier_space_u8_r, TOP_st_qualifier_space_u16_r, TOP_st_qualifier_space_u32_r, TOP_st_qualifier_space_u64_r, TOP_st_qualifier_space_f32_r, TOP_st_qualifier_space_f64_r }; static const TOP store32_top[11] = { TOP_st_qualifier_space_s8_b32, TOP_st_qualifier_space_s16_b32, TOP_UNDEFINED, TOP_UNDEFINED, TOP_st_qualifier_space_u8_b32, TOP_st_qualifier_space_u16_b32, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP store32o_top[11] = { TOP_st_qualifier_space_s8_b32_o, TOP_st_qualifier_space_s16_b32_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_st_qualifier_space_u8_b32_o, TOP_st_qualifier_space_u16_b32_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP store32r_top[11] = { TOP_st_qualifier_space_s8_b32_r, TOP_st_qualifier_space_s16_b32_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_st_qualifier_space_u8_b32_r, TOP_st_qualifier_space_u16_b32_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP storee_top[11] = { TOP_st_qualifier_space_s8_a64, TOP_st_qualifier_space_s16_a64, TOP_st_qualifier_space_s32_a64, TOP_st_qualifier_space_s64_a64, TOP_st_qualifier_space_u8_a64, TOP_st_qualifier_space_u16_a64, TOP_st_qualifier_space_u32_a64, TOP_st_qualifier_space_u64_a64, TOP_st_qualifier_space_f32_a64, TOP_st_qualifier_space_f64_a64 }; static const TOP storeeo_top[11] = { TOP_st_qualifier_space_s8_a64_o, TOP_st_qualifier_space_s16_a64_o, TOP_st_qualifier_space_s32_a64_o, TOP_st_qualifier_space_s64_a64_o, TOP_st_qualifier_space_u8_a64_o, TOP_st_qualifier_space_u16_a64_o, TOP_st_qualifier_space_u32_a64_o, TOP_st_qualifier_space_u64_a64_o, TOP_st_qualifier_space_f32_a64_o, TOP_st_qualifier_space_f64_a64_o }; static const TOP storeer_top[11] = { TOP_st_qualifier_space_s8_a64_r, TOP_st_qualifier_space_s16_a64_r, TOP_st_qualifier_space_s32_a64_r, TOP_st_qualifier_space_s64_a64_r, TOP_st_qualifier_space_u8_a64_r, TOP_st_qualifier_space_u16_a64_r, TOP_st_qualifier_space_u32_a64_r, TOP_st_qualifier_space_u64_a64_r, TOP_st_qualifier_space_f32_a64_r, TOP_st_qualifier_space_f64_a64_r }; static const TOP storee32_top[11] = { TOP_st_qualifier_space_s8_b32_a64, TOP_st_qualifier_space_s16_b32_a64, TOP_UNDEFINED, TOP_UNDEFINED, TOP_st_qualifier_space_u8_b32_a64, TOP_st_qualifier_space_u16_b32_a64, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP storee32o_top[11] = { TOP_st_qualifier_space_s8_b32_a64_o, TOP_st_qualifier_space_s16_b32_a64_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_st_qualifier_space_u8_b32_a64_o, TOP_st_qualifier_space_u16_b32_a64_o, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static const TOP storee32r_top[11] = { TOP_st_qualifier_space_s8_b32_a64_r, TOP_st_qualifier_space_s16_b32_a64_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_st_qualifier_space_u8_b32_a64_r, TOP_st_qualifier_space_u16_b32_a64_r, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED, TOP_UNDEFINED }; static ISA_ENUM_CLASS_VALUE Space_Enum (VARIANT v, TN *tn) { #ifdef Is_True_On // check if multiple memory spaces were set UINT t = V_memory_space(v); UINT n = 0; while (t != 0) { // count # bits set if ((t & 1) == 1) ++n; t = t >> 1; } if (n > 1) DevWarn("multiple memory spaces set"); #endif if (V_global_mem(v)) return ECV_space_global; else if (V_shared_mem(v)) return ECV_space_shared; else if (V_local_mem(v)) return ECV_space_local; else if (V_const_mem(v)) return ECV_space_const; else if (V_param_mem(v)) return ECV_space_param; else if (TN_has_memory_space(tn)) { if (TN_in_global_mem(tn)) return ECV_space_global; else if (TN_in_shared_mem(tn)) return ECV_space_shared; else if (TN_in_local_mem(tn)) return ECV_space_local; else if (TN_in_const_mem(tn)) return ECV_space_const; else if (TN_in_param_mem(tn)) return ECV_space_param; else FmtAssert(FALSE, ("unknown memory space")); } else return ECV_UNDEFINED; } static inline TOP Pick_Load_Instruction (TYPE_ID mtype, BOOL val_is32, BOOL addr_is64, BOOL use_reg, BOOL has_offset) { if (addr_is64) { if (val_is32) { if (use_reg) return loade32r_top[Mtype_Index(mtype)]; else if (has_offset) return loade32o_top[Mtype_Index(mtype)]; else return loade32_top[Mtype_Index(mtype)]; } else { if (use_reg) return loader_top[Mtype_Index(mtype)]; else if (has_offset) return loadeo_top[Mtype_Index(mtype)]; else return loade_top[Mtype_Index(mtype)]; } } else { if (val_is32) { if (use_reg) return load32r_top[Mtype_Index(mtype)]; else if (has_offset) return load32o_top[Mtype_Index(mtype)]; else return load32_top[Mtype_Index(mtype)]; } else { if (use_reg) return loadr_top[Mtype_Index(mtype)]; else if (has_offset) return loado_top[Mtype_Index(mtype)]; else return load_top[Mtype_Index(mtype)]; } } } static inline TOP Pick_Store_Instruction (TYPE_ID mtype, BOOL val_is32, BOOL addr_is64, BOOL use_reg, BOOL has_offset) { if (addr_is64) { if (val_is32) { if (use_reg) return storee32r_top[Mtype_Index(mtype)]; else if (has_offset) return storee32o_top[Mtype_Index(mtype)]; else return storee32_top[Mtype_Index(mtype)]; } else { if (use_reg) return storeer_top[Mtype_Index(mtype)]; else if (has_offset) return storeeo_top[Mtype_Index(mtype)]; else return storee_top[Mtype_Index(mtype)]; } } else { if (val_is32) { if (use_reg) return store32r_top[Mtype_Index(mtype)]; else if (has_offset) return store32o_top[Mtype_Index(mtype)]; else return store32_top[Mtype_Index(mtype)]; } else { if (use_reg) return storer_top[Mtype_Index(mtype)]; else if (has_offset) return storeo_top[Mtype_Index(mtype)]; else return store_top[Mtype_Index(mtype)]; } } } static void Set_TN_Memory_Space_From_Variant (TN *tn, VARIANT v, TN *base) { // need to track which memory space an address register is associated with, // so know what to issue when indirecting. if (V_global_mem(v)) { Set_TN_in_global_mem(tn); } else if (V_shared_mem(v)) { Set_TN_in_shared_mem(tn); } else if (V_param_mem(v)) { Set_TN_in_param_mem(tn); } else if (V_local_mem(v)) { Set_TN_in_local_mem(tn); } else if (V_const_mem(v)) { Set_TN_in_const_mem(tn); } else if (TN_has_memory_space(base)) { Set_TN_memory_space(tn, TN_memory_space(base)); } else FmtAssert(FALSE, ("NYI: tn memory type")); } void Expand_Load (OPCODE opcode, TN *result, TN *base, TN *ofst, VARIANT v, OPS *ops) { TOP top; const TYPE_ID dtype = OPCODE_desc(opcode); const TYPE_ID rtype = OPCODE_rtype(opcode); TN *dresult = result; BOOL need_convert = FALSE; BOOL val_is32 = FALSE; BOOL addr_is64; BOOL use_reg; BOOL has_offset; TN *space_tn = Gen_Enum_TN(Space_Enum(v,base)); TN *qualifier_tn; switch (Space_Enum(v,base)) { case ECV_space_global: case ECV_space_shared: break; default: // ignore volatile on these memories Reset_V_volatile(v); } if (V_volatile(v)) qualifier_tn = Gen_Enum_TN(ECV_qualifier_volatile); else qualifier_tn = Gen_Enum_TN(ECV_qualifier_none); Is_True(TN_size(result) >= MTYPE_byte_size(rtype), ("load won't fit in result")); // check if need convert after load if (dtype != rtype && MTYPE_is_integral(rtype)) { if ((rtype == MTYPE_U4 || rtype == MTYPE_I4) && MTYPE_byte_size(dtype) < MTYPE_byte_size(rtype)) { // special-case ability to load small value into 32-bit reg // if given something like U4U2LDID. val_is32 = TRUE; } else { // will need convert after load, so size tmp on dtype. dresult = Build_TN_Of_Mtype (dtype); need_convert = TRUE; } } Is_True (TN_is_constant(ofst), ("Expand_Load: Illegal offset TN")); if (TN_is_symbol(base)) { use_reg = FALSE; addr_is64 = (MTYPE_RegisterSize(ST_mtype(TN_var(base))) == 8); if (TN_has_value(ofst) && TN_value(ofst) == 0 && TN_is_symbol(base) && Is_Simple_Type(ST_type(TN_var(base)))) { // ld name has_offset = FALSE; } else { // ld name[ofst] has_offset = TRUE; } } else { // ld [reg+offset] use_reg = TRUE; has_offset = TRUE; addr_is64 = (TN_register_class(base) == ISA_REGISTER_CLASS_integer64); } top = Pick_Load_Instruction (dtype, val_is32, addr_is64, use_reg, has_offset); FmtAssert(top != TOP_UNDEFINED, ("no topcode")); if (has_offset) Build_OP (top, dresult, qualifier_tn, space_tn, base, ofst, ops); else Build_OP (top, dresult, qualifier_tn, space_tn, base, ops); if (TN_enum(space_tn) == ECV_space_shared) { // mark if came from ld.shared, // so can later replace this and use grf directly Set_TN_from_shared_load(dresult); } if (need_convert) { Expand_Convert (result, rtype, dresult, dtype, ops); } // set tn space if looks like an address load if (rtype == Pointer_Mtype) { Set_TN_Memory_Space_From_Variant (result, v, base); } } void Expand_Store (TYPE_ID mtype, TN *src, TN *base, TN *ofst, VARIANT v, OPS *ops) { TOP top; BOOL val_is32 = FALSE; BOOL addr_is64; BOOL use_reg; BOOL has_offset; TN *space_tn = Gen_Enum_TN(Space_Enum(v,base)); TN *qualifier_tn; switch (Space_Enum(v,base)) { case ECV_space_global: case ECV_space_shared: break; default: // ignore volatile on these memories Reset_V_volatile(v); } if (V_volatile(v)) qualifier_tn = Gen_Enum_TN(ECV_qualifier_volatile); else qualifier_tn = Gen_Enum_TN(ECV_qualifier_none); if (TN_size(src) != MTYPE_byte_size(mtype)) { const TYPE_ID regtype = Mtype_Of_TN(src); if ((regtype == MTYPE_U4 || regtype == MTYPE_I4) && MTYPE_byte_size(mtype) < MTYPE_byte_size(regtype)) { // special-case ability to load small value into 32-bit reg // if given something like U4U2LDID. val_is32 = TRUE; } else { // insert size convert TN *tmp = Build_TN_Of_Mtype (mtype); Expand_Convert (tmp, mtype, src, Mtype_Of_TN(src), ops); src = tmp; } } Is_True (TN_is_constant(ofst), ("Expand_Store: Illegal offset TN")); if (TN_is_symbol(base)) { use_reg = FALSE; addr_is64 = (MTYPE_RegisterSize(ST_mtype(TN_var(base))) == 8); if (TN_has_value(ofst) && TN_value(ofst) == 0 && TN_is_symbol(base) && Is_Simple_Type(ST_type(TN_var(base)))) { // st name has_offset = FALSE; } else { // st name[ofst] has_offset = TRUE; } } else { // st *(reg+ofst) use_reg = TRUE; has_offset = TRUE; addr_is64 = (TN_register_class(base) == ISA_REGISTER_CLASS_integer64); } top = Pick_Store_Instruction (mtype, val_is32, addr_is64, use_reg, has_offset); FmtAssert(top != TOP_UNDEFINED, ("no topcode")); if (has_offset) Build_OP (top, qualifier_tn, space_tn, base, ofst, src, ops); else Build_OP (top, qualifier_tn, space_tn, base, src, ops); } void Expand_Lda (TN *dest, TN *src, OPS *ops) { FmtAssert(FALSE, ("NYI")); } static void Expand_Lda (TYPE_ID mtype, TN *dest, TN *base, TN *ofst, VARIANT v, OPS *ops) { // lda doesn't really need to know memory type, // as it is a link-time constant. // So instead of doing ld r, &sym // just do mov r, &sym. FmtAssert(mtype == Pointer_Mtype, ("unexpected mtype")); Is_True (TN_is_constant(ofst), ("Expand_Load: Illegal offset TN")); ST *sym = TN_var(base); if (ST_sclass(sym) == SCLASS_PSTATIC) { // mangle local names so unique (in case inline multiple local shared vars) // but only if name has not already been mangled. char buf[80]; char *p = ST_name(sym); sprintf(buf, "%d", (INT) ST_ofst(sym)); p += strlen(p) - strlen(buf); if (strncmp(ST_name(sym), "__cuda_", 7) == 0 && strcmp(p, buf) == 0) // ofst matches ; // reuse existing name else Set_ST_name(sym, Save_Str2i ("__cuda_", ST_name(sym), (INT) ST_ofst(sym))); } if (TN_has_value(ofst) && TN_value(ofst) == 0) Build_OP (Is_Target_64bit() ? TOP_mov_u64_a : TOP_mov_u32_a, dest, base, ops); else Build_OP (Is_Target_64bit() ? TOP_mov_u64_ao : TOP_mov_u32_ao, dest, base, ofst, ops); Set_TN_Memory_Space_From_Variant (dest, v, base); } static OPCODE OPCODE_make_signed_op(OPERATOR op, TYPE_ID rtype, TYPE_ID desc, BOOL is_signed) { if (MTYPE_is_signed(rtype) != is_signed) rtype = MTYPE_complement(rtype); if (MTYPE_is_signed(desc) != is_signed) desc = MTYPE_complement(desc); return OPCODE_make_op(op, rtype, desc); } static void Expand_Composed_Load ( OPCODE op, TN *result, TN *base, TN *disp, VARIANT variant, OPS *ops) { return Expand_Load( op, result, base, disp, variant, ops ); } void Expand_Misaligned_Load ( OPCODE op, TN *result, TN *base, TN *disp, VARIANT variant, OPS *ops) { ErrMsgSrcpos(EC_Unaligned_Memory, current_srcpos); } static void Expand_Composed_Store (TYPE_ID mtype, TN *obj, TN *base, TN *disp, VARIANT variant, OPS *ops) { return Expand_Store( mtype, obj, base, disp, variant, ops ); } void Expand_Misaligned_Store (TYPE_ID mtype, TN *obj_tn, TN *base_tn, TN *disp_tn, VARIANT variant, OPS *ops) { ErrMsgSrcpos(EC_Unaligned_Memory, current_srcpos); } // recognize some special symbols and create specific tns for them static TN* Get_TN_For_Predefined_Symbol (ST *sym, INT64 ofst) { INT index = 0; if (ofst == 0) index += 0; else if (ofst == 4) index += 1; else if (ofst == 8) index += 2; else FmtAssert(FALSE, ("unexpected offset %lld with symbol %s", ofst, ST_name(sym) )); if (strcmp(ST_name(sym), "threadIdx") == 0) { return Tid_TN(index); } else if (strcmp(ST_name(sym), "blockDim") == 0) { return Ntid_TN(index); } else if (strcmp(ST_name(sym), "blockIdx") == 0) { return Ctaid_TN(index); } else if (strcmp(ST_name(sym), "gridDim") == 0) { return Nctaid_TN(index); } else if (strcmp(ST_name(sym), "warpSize") == 0) { // this is evil hack: change name of st to ptx name Set_ST_name(sym, Save_Str("WARP_SZ")); return Gen_Symbol_TN(sym, 0, 0); } else if (strcmp(ST_name(sym), "WARP_SZ") == 0) { return Gen_Symbol_TN(sym, 0, 0); } else { return NULL; // not a recognized symbol } } static void Exp_Ldst ( OPCODE opcode, TN *tn, ST *sym, INT64 ofst, BOOL indirect_call, BOOL is_store, BOOL is_load, OPS *ops, VARIANT variant) { ST* base_sym = NULL; INT64 base_ofst = 0; TN* base_tn = NULL; TN* ofst_tn = NULL; TN* tmp_tn = NULL; const BOOL is_lda = (!is_load && !is_store); OPS newops = OPS_EMPTY; OP* op = NULL; if (Trace_Exp2) { fprintf(TFile, "exp_ldst %s: ", OPCODE_name(opcode)); if (tn) Print_TN(tn,FALSE); if (is_store) fprintf(TFile, " -> "); else fprintf(TFile, " <- "); if (ST_class(sym) != CLASS_CONST) fprintf(TFile, "%lld (%s)\n", ofst, ST_name(sym)); else fprintf(TFile, "%lld ()\n", ofst); } if (TY_is_volatile(ST_type(sym)) && ! V_volatile(variant)) DevWarn("not marked volatile?"); Allocate_Object(sym); /* make sure sym is allocated */ Set_BE_ST_referenced(sym); Base_Symbol_And_Offset_For_Addressing (sym, ofst, &base_sym, &base_ofst); if (base_sym == SP_Sym || base_sym == FP_Sym) { base_tn = (base_sym == SP_Sym) ? SP_TN : FP_TN; if (sym == base_sym) { // can have direct reference to SP or FP, // e.g. if actual stored to stack. FmtAssert( false, ("stack pointer nyi: probably an unexpected call or intrinsic") ); } else { /* Because we'd like to see symbol name in .s file, * still reference the symbol rather than the sp/fp base. * Do put in the offset from the symbol. * We put the symbol in the TN and then * let cgemit replace symbol with the final offset. * We generate a SW reg, <sym>, <SP> rather than SW reg,<sym> * because cgemit and others expect a separate tn for the * offset and base. */ // Most locals will become pregs, but sometimes WOPT leaves some, // and hw doesn't have real stack. // So either put in .local area or in preg. if (CG_opt_level > 0 // for -O0 use locals && !ST_addr_saved(sym) // Casts to a larger size will have addr_saved set in adjust_addr. // && !ST_addr_passed(sym) // if we allow calls may need to check for addr_passed, // but right now the adjust_addr routine doesn't recompute // addr_passed, only addr_saved. && !TY_has_union(ST_type(sym)) ) // can't pick register type if union { // safe to put in register. // have to create mapping from st_index,offset to tn. std::map<pair<UINT,INT64>,TN*>::iterator it; // use sym mtype; may convert to smaller use mtype. TYPE_ID sym_mtype = Mtype_For_Type_Offset(ST_type(sym),ofst); // Mtype_Of_TN always returns unsigned, // but want to preserve sign-ness of operation. TYPE_ID tn_mtype = Mtype_TransferSign(sym_mtype, Mtype_Of_TN(tn)); TN *symtn; FmtAssert(!is_lda, ("lda but not addr used?")); it = st_to_tn_map.find( pair<UINT,INT64>(ST_index(sym), ofst) ); if (it == st_to_tn_map.end()) { // create new tn symtn = Build_TN_Of_Mtype(sym_mtype); st_to_tn_map.insert( pair<pair<UINT,INT64>,TN*>( pair<UINT,INT64>(ST_index(sym), ofst), symtn) ); DevWarn("map local %d,%d to tn%d", ST_index(sym), (INT)ofst, TN_number(symtn)); } else { symtn = it->second; } // Do copy of tn<->symtn, but check for size mismatches, // e.g. U4U2LDID of 32bit tn, or U1STID, or U4U4LDID of 64bit tn if (is_store) { // copy tn -> symtn // check for case of needing convert for different sizes, // because Exp_COPY lacks proper mtype info. if (TN_size(symtn) != TN_size(tn)) { // sizes don't match, so do convert rather than simple copy Expand_Convert (symtn, sym_mtype, tn, tn_mtype, &newops); } else { Exp_COPY (symtn, tn, &newops); } is_store = FALSE; // so don't do it again } else if (is_load) { // copy symtn -> tn // check for case of needing convert for different sizes, // because Exp_COPY lacks proper mtype info. if (TN_size(symtn) != TN_size(tn)) { // sizes don't match, so do convert rather than simple copy Expand_Convert (tn, tn_mtype, symtn, sym_mtype, &newops); } else { Exp_COPY (tn, symtn, &newops); } is_load = FALSE; // so don't do it again } } else if (CGEXP_auto_as_static) { // put in .local area (like a static). // Note that this doesn't work for recursion, // but we don't support that yet. // Inlining could cause multiple stack variables of // same name, with different stack offsets, but we need // unique names for pstatic since accessed by name. // So suffix names with offset. DevWarn("convert stack variable %s to static local", ST_name(sym)); Set_ST_sclass(sym, SCLASS_PSTATIC); if (ST_is_value_parm(sym)) Clear_ST_is_value_parm(sym); Set_ST_in_local_mem(sym); Set_V_local_mem(variant); Set_ST_name(sym, Save_Str2i ("__cuda_", ST_name(sym), (INT) ST_ofst(sym))); Set_ST_base(sym, sym); Set_ST_ofst(sym, 0); // reallocate object so know to emit it // (note that this leaves stack allocated, // but that's okay since we ignore stack). Allocate_Object(sym); base_tn = Gen_Symbol_TN (sym, 0, 0); ofst_tn = Gen_Literal_TN (ofst, 4); } else { FmtAssert(FALSE, ("stack variables not supported")); } } } else if (ST_sclass(sym) == SCLASS_COMMON || ST_sclass(sym) == SCLASS_FSTATIC || ST_sclass(sym) == SCLASS_PSTATIC || ST_sclass(sym) == SCLASS_UGLOBAL || ST_sclass(sym) == SCLASS_DGLOBAL) { ofst_tn = Gen_Literal_TN (ofst, 4); base_tn = Gen_Symbol_TN (sym, 0, 0); if (V_memory_space(variant)) { // use existing variant info (global ptr) } else if (ST_in_global_mem(sym)) { Set_V_global_mem(variant); } else if (ST_in_shared_mem(sym)) { Set_V_shared_mem(variant); } else if (ST_in_local_mem(sym)) { Set_V_local_mem(variant); } else if (ST_in_constant_mem(sym)) { Set_V_const_mem(variant); } else if (ST_in_texture_mem(sym)) { if (tn != NULL) { if (Trace_Exp2) fprintf(TFile,"replace tn home with texture ldid\n"); // don't emit the load, just set the home of the result // which will later be used by the texture asm. Set_TN_home (tn, WN_CreateLdid (opcode,ofst,sym,ST_type(sym))); Set_TN_in_texture_mem(tn); return; } else FmtAssert(FALSE, ("texture variable NYI")); } else if (ST_is_initialized(sym) && (ST_sclass(sym) == SCLASS_PSTATIC) || (ST_sclass(sym) == SCLASS_FSTATIC)) { // assume is initialized local; // put initialization into const memory Set_ST_in_constant_mem(sym); Set_V_const_mem(variant); } else FmtAssert(FALSE, ("variable not in memory space")); } else if (ST_sclass(sym) == SCLASS_FORMAL) { // formals in global entry must be put in param space ofst_tn = Gen_Literal_TN (ofst, 4); base_tn = Gen_Symbol_TN (sym, 0, 0); Set_V_param_mem(variant); } else if (ST_sclass(sym) == SCLASS_EXTERN) { base_tn = Get_TN_For_Predefined_Symbol(sym, ofst); FmtAssert (base_tn != NULL, ("unrecognized extern symbol: %s", ST_name(sym))); if (is_load) { if (TN_is_symbol(base_tn)) { // must be constant symbol like WARP_SZ Expand_Mtype_Immediate (tn, base_tn, OPCODE_rtype(opcode), &newops); } else { // TID is really a register, // so turn load of tid into a move/convert. // CUDA says these are 32bits, but NVISA says they are 16 bits, // so generate a convert Expand_Convert (tn, OPCODE_rtype(opcode), base_tn, MTYPE_U2, &newops); } is_load = FALSE; // so nothing else done } else FmtAssert(FALSE, ("NYI")); } else { FmtAssert(FALSE, ("NYI")); } if (is_store) { if (V_align_all(variant) == 0) Expand_Store (OPCODE_desc(opcode), tn, base_tn, ofst_tn, variant, &newops); else Expand_Misaligned_Store (OPCODE_desc(opcode), tn, base_tn, ofst_tn, variant, &newops); } else if (is_load) { if (V_align_all(variant) == 0) Expand_Load (opcode, tn, base_tn, ofst_tn, variant, &newops); else Expand_Misaligned_Load (opcode, tn, base_tn, ofst_tn, variant, &newops); } else if (is_lda) { Expand_Lda (OPCODE_rtype(opcode), tn, base_tn, ofst_tn, variant, &newops); // Expand_Add (tn, ofst_tn, base_tn, OPCODE_rtype(opcode), &newops); } FOR_ALL_OPS_OPs (&newops, op) { if (is_load && ST_is_constant(sym) && OP_load(op)) { // If we expanded a load of a constant, // nothing else can alias with the loads // we have generated. Set_OP_no_alias(op); } if (Trace_Exp2) { fprintf(TFile, "exp_ldst into "); Print_OP (op); } } /* Add the new OPs to the end of the list passed in */ OPS_Append_Ops(ops, &newops); } void Exp_Lda ( TYPE_ID mtype, TN *tgt_tn, ST *sym, INT64 ofst, OPERATOR call_opr, OPS *ops) { OPCODE opcode = OPCODE_make_op(OPR_LDA, mtype, MTYPE_V); Exp_Ldst (opcode, tgt_tn, sym, ofst, (call_opr == OPR_ICALL), FALSE, FALSE, ops, V_NONE); } void Exp_Load ( TYPE_ID rtype, TYPE_ID desc, TN *tgt_tn, ST *sym, INT64 ofst, OPS *ops, VARIANT variant) { OPCODE opcode = OPCODE_make_op (OPR_LDID, rtype, desc); Exp_Ldst (opcode, tgt_tn, sym, ofst, FALSE, FALSE, TRUE, ops, variant); } void Exp_Store ( TYPE_ID mtype, TN *src_tn, ST *sym, INT64 ofst, OPS *ops, VARIANT variant) { OPCODE opcode = OPCODE_make_op(OPR_STID, MTYPE_V, mtype); Exp_Ldst (opcode, src_tn, sym, ofst, FALSE, TRUE, FALSE, ops, variant); } static ISA_ENUM_CLASS_VALUE Pick_Prefetch_Hint (VARIANT variant) { UINT32 pf_flags = V_pf_flags(variant); FmtAssert(FALSE, ("NYI")); } void Exp_Prefetch (TOP opc, TN* src1, TN* src2, VARIANT variant, OPS* ops) { FmtAssert(opc == TOP_UNDEFINED, ("Prefetch opcode should be selected in Exp_Prefetch")); const UINT32 pf_flags = V_pf_flags(variant); const ISA_ENUM_CLASS_VALUE pfhint = Pick_Prefetch_Hint(variant); TOP top; FmtAssert(FALSE, ("NYI")); } /* ====================================================================== * Exp_Extract_Bits * ======================================================================*/ void Exp_Extract_Bits (TYPE_ID rtype, TYPE_ID desc, UINT bit_offset, UINT bit_size, TN *tgt_tn, TN *src_tn, OPS *ops) { INT64 src_val; BOOL is_double = MTYPE_is_size_double (rtype); /* The constant supports only matching host and target endianness and 32bit ints * * Ideally the whirl simplifier should catch these constant cases, * but it doesn't, so special-case it here. */ if (TN_Can_Use_Constant_Value (src_tn, desc, &src_val) && (!is_double)) { if (MTYPE_is_signed (rtype)) { /* ISO/ANSI C doesn't mandate sign extension must happen with a shift right. * All compilers do this but be warned it's not mandatory. */ INT32 val = ((INT32) src_val) << (MTYPE_bit_size (rtype) - bit_offset - bit_size); val = val >> (MTYPE_bit_size (rtype) - bit_size); Expand_Mtype_Immediate (tgt_tn, Gen_Literal_TN(val,4), rtype, ops); } else { UINT32 bit_mask = ((-1U) >> (MTYPE_bit_size(desc) - bit_size)) << bit_offset; UINT32 val = src_val & bit_mask; val = val >> bit_offset; Expand_Mtype_Immediate (tgt_tn, Gen_Literal_TN(val,4), rtype, ops); } } else { /* Extract via Shift Left + (signed) ? Arithmetic Shift Right : Shift Right */ TN *tmp1_tn = Build_TN_Like (tgt_tn); INT32 left_shift_amt = MTYPE_bit_size (rtype) - bit_offset - bit_size; Expand_Shift ( tmp1_tn, src_tn, Gen_Literal_TN(left_shift_amt, 4), rtype, shift_left, ops ); INT32 right_shift_amt = MTYPE_bit_size(rtype) - bit_size; Expand_Shift ( tgt_tn, tmp1_tn, Gen_Literal_TN(right_shift_amt, 4), rtype, MTYPE_is_signed(rtype) ? shift_aright : shift_lright, ops ); } } /* ====================================================================== * Exp_Deposit_Bits - deposit src2_tn into a field of src1_tn returning * the result in tgt_tn. * ======================================================================*/ void Exp_Deposit_Bits (TYPE_ID rtype, TYPE_ID desc, UINT bit_offset, UINT bit_size, TN *tgt_tn, TN *src1_tn, TN *src2_tn, OPS *ops) { // since nvisa can handle large masks, do and-mask rather than shifts FmtAssert( bit_size != 0, ("size of bit field cannot be 0")); FmtAssert( MTYPE_bit_size(desc) == 32, ("NYI: deposit_bits for non-word size")); TN *tmp1_tn = Build_TN_Like(tgt_tn); TN *tmp2_tn = Build_TN_Like(tgt_tn); UINT src2_mask = (1 << bit_size) - 1; UINT src1_mask = ~(src2_mask << bit_offset); INT64 src1_val; INT64 src2_val; UINT val; if (TN_Can_Use_Constant_Value (src1_tn, desc, &src1_val)) { val = src1_val; val = val & src1_mask; tmp1_tn = Gen_Literal_TN (val, 4); } else { Expand_Binary_And( tmp1_tn, src1_tn, Gen_Literal_TN(src1_mask,4), rtype, ops); } if (TN_Can_Use_Constant_Value (src2_tn, desc, &src2_val)) { val = src2_val; val = val & src2_mask; val = val << bit_offset; tmp2_tn = Gen_Literal_TN (val, 4); } else { Expand_Binary_And( tmp2_tn, src2_tn, Gen_Literal_TN(src2_mask,4), rtype, ops); Expand_Shift( tmp2_tn, tmp2_tn, Gen_Literal_TN(bit_offset, 4), rtype, shift_left, ops); } if (TN_is_constant(tmp1_tn) && TN_has_value(tmp1_tn) && TN_is_constant(tmp2_tn) && TN_has_value(tmp2_tn)) { // both operands are constant src1_val = TN_value(tmp1_tn); src2_val = TN_value(tmp2_tn); src1_val = src1_val | src2_val; val = src1_val; Expand_Mtype_Immediate (tgt_tn, Gen_Literal_TN(val,4), rtype, ops); } else { Expand_Binary_Or( tgt_tn, tmp1_tn, tmp2_tn, rtype, ops); } } void Expand_Lda_Label (TN *dest, TN *lab, OPS *ops) { Expand_Mtype_Immediate(dest, lab, Mtype_Of_TN(dest), ops); }
32.718428
104
0.698736
[ "object" ]
58113fc339301c09eefc2900ed9f63d25c7ee4ad
3,345
cpp
C++
phxqueue/config/consumerconfig.cpp
huayl/phxqueue
733ada547a3b483b536cc3d401766af7b4c17dbe
[ "Apache-2.0" ]
2,032
2017-09-12T02:29:42.000Z
2022-03-23T07:14:56.000Z
phxqueue/config/consumerconfig.cpp
huayl/phxqueue
733ada547a3b483b536cc3d401766af7b4c17dbe
[ "Apache-2.0" ]
57
2017-09-12T03:36:39.000Z
2020-12-16T08:59:09.000Z
phxqueue/config/consumerconfig.cpp
huayl/phxqueue
733ada547a3b483b536cc3d401766af7b4c17dbe
[ "Apache-2.0" ]
370
2017-09-12T03:09:04.000Z
2022-03-13T14:01:55.000Z
/* Tencent is pleased to support the open source community by making PhxQueue available. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <https://opensource.org/licenses/BSD-3-Clause> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "phxqueue/config/consumerconfig.h" #include "phxqueue/comm.h" namespace phxqueue { namespace config { using namespace std; class ConsumerConfig::ConsumerConfigImpl { public: ConsumerConfigImpl() {} virtual ~ConsumerConfigImpl() {} map<uint64_t, shared_ptr<proto::Consumer>> addr2consumer; }; ConsumerConfig::ConsumerConfig() : impl_(new ConsumerConfigImpl()) { assert(impl_); } ConsumerConfig::~ConsumerConfig() {} comm::RetCode ConsumerConfig::ReadConfig(proto::ConsumerConfig &proto) { // sample proto.Clear(); proto::Consumer *consumer = nullptr; comm::proto::Addr *addr = nullptr; consumer = proto.add_consumers(); consumer->set_scale(100); consumer->add_consumer_group_ids(1); consumer->add_consumer_group_ids(2); addr = consumer->mutable_addr(); addr->set_ip("127.0.0.1"); addr->set_port(8001); consumer = proto.add_consumers(); consumer->set_scale(100); consumer->add_consumer_group_ids(1); consumer->add_consumer_group_ids(2); addr = consumer->mutable_addr(); addr->set_ip("127.0.0.1"); addr->set_port(8002); consumer = proto.add_consumers(); consumer->set_scale(100); consumer->add_consumer_group_ids(1); consumer->add_consumer_group_ids(2); addr = consumer->mutable_addr(); addr->set_ip("127.0.0.1"); addr->set_port(8003); return comm::RetCode::RET_OK; } comm::RetCode ConsumerConfig::Rebuild() { bool need_check = NeedCheck(); impl_->addr2consumer.clear(); auto &&proto = GetProto(); for (int i{0}; i < proto.consumers_size(); ++i) { const auto &consumer(proto.consumers(i)); if (need_check) PHX_ASSERT(impl_->addr2consumer.end() == impl_->addr2consumer.find(comm::utils::EncodeAddr(consumer.addr())), ==, true); impl_->addr2consumer.emplace(comm::utils::EncodeAddr(consumer.addr()), make_shared<proto::Consumer>(consumer)); } return comm::RetCode::RET_OK; } comm::RetCode ConsumerConfig::GetAllConsumer(std::vector<shared_ptr<const proto::Consumer>> &consumers) const { for (auto &&it : impl_->addr2consumer) { consumers.push_back(it.second); } return comm::RetCode::RET_OK; } comm::RetCode ConsumerConfig::GetConsumerByAddr(const comm::proto::Addr &addr, shared_ptr<const proto::Consumer> &consumer) const { auto &&encoded_addr = comm::utils::EncodeAddr(addr); auto &&it = impl_->addr2consumer.find(encoded_addr); if (impl_->addr2consumer.end() == it) return comm::RetCode::RET_ERR_RANGE_ADDR; consumer = it->second; return comm::RetCode::RET_OK; } } // namespace config } // namespace phxqueue
30.409091
305
0.707324
[ "vector" ]
58118d40d6bfc6f86ba859e0dc069d57c7fc88ef
5,315
cc
C++
Code/Components/Services/ingest/current/ingestpipeline/mssink/GenericSubstitutionRule.cc
steve-ord/askapsoft
21b9df1b393b973ec312591efad7ee2b8c974811
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Services/ingest/current/ingestpipeline/mssink/GenericSubstitutionRule.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/ingest/current/ingestpipeline/mssink/GenericSubstitutionRule.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file GenericSubstitutionRule.cc /// /// @copyright (c) 2012 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Max Voronkov <maxim.voronkov@csiro.au> // ASKAPsoft includes #include "ingestpipeline/mssink/GenericSubstitutionRule.h" #include "askap/AskapUtil.h" #include "askap/AskapError.h" // it would be nice to get all MPI stuff in a single place, but ingest is already MPI-heavy throughout #include <mpi.h> // std includes #include <vector> #include <algorithm> #include <functional> namespace askap { namespace cp { namespace ingest { /// @brief constructor /// @details /// @param[in] kw keyword string to represent /// @param[in] val integer value /// @param[in] config configuration class GenericSubstitutionRule::GenericSubstitutionRule(const std::string &kw, int val, const Configuration &config) : itsKeyword(kw), itsValue(val), itsNProcs(config.nprocs()), itsRank(config.rank()), itsRankIndependent(true) { ASKAPASSERT(itsRank < itsNProcs); ASKAPASSERT(itsNProcs > 0); } // implementation of interface mentods /// @brief obtain keywords handled by this object /// @details This method returns a set of string keywords /// (without leading % sign in our implementation, but in general this /// can be just logical full-string keyword, we don't have to limit ourselves /// to particular single character tags) which this class recognises. Any of these /// keyword can be passed to operator() once the object is initialised /// @return set of keywords this object recognises std::set<std::string> GenericSubstitutionRule::keywords() const { std::set<std::string> result; result.insert(itsKeyword); return result; } /// @brief initialise the object /// @details This is the only place where MPI calls may happen. Therefore, /// initialisation has to be done at the appropriate time in the program. /// It is also expected that only substitution rules which are actually needed /// will be initialised and used. So construction/destruction should be a light /// operation. In this method, the implementations are expected to provide a /// mechanism to obtain values for all keywords handled by this object. void GenericSubstitutionRule::initialise() { if (itsNProcs > 1) { // distributed case, need to aggregate values. Otherwise, the field has already been setup with true std::vector<int> individualValues(itsNProcs, 0); individualValues[itsRank] = itsValue; const int response = MPI_Allreduce(MPI_IN_PLACE, (void*)individualValues.data(), individualValues.size(), MPI_INT, MPI_SUM, MPI_COMM_WORLD); ASKAPCHECK(response == MPI_SUCCESS, "Erroneous response from MPI_Allreduce = "<<response); // now individualValues are consistent on all ranks, so check the values itsRankIndependent = (std::find_if(individualValues.begin(), individualValues.end(), std::bind2nd(std::not_equal_to<int>(), itsValue)) == individualValues.end()); } } /// @brief obtain value of a particular keyword /// @details This is the main access method which is supposed to be called after /// initialise(). /// @param[in] kw keyword to access, must be from the set returned by keywords /// @return value of the requested keyword /// @note An exception may be thrown if the initialise() method is not called /// prior to an attempt to access the value. std::string GenericSubstitutionRule::operator()(const std::string &kw) const { ASKAPCHECK(kw == itsKeyword, "Attempted to obtain keyword '"<<kw<<"' out of GenericSubstitutionRule set up with '"<<itsKeyword<<"'"); return utility::toString(itsValue); } /// @brief check if values are rank-independent /// @details The implementation of this interface should evaluate a flag and return it /// in this method to show whether the value for a particular keyword is /// rank-independent or not. This is required to encapsulate all MPI related calls in /// the initialise. Sometimes, the value of the flag can be known up front, e.g. if /// the value is the result of gather-scatter operation or if it is based on rank number. /// @param[in] kw keyword to check the flag for /// @return true, if the given keyword has the same value for all ranks bool GenericSubstitutionRule::isRankIndependent() const { return itsRankIndependent; }; }; }; };
42.52
136
0.730574
[ "object", "vector" ]
5817e01ea7628b95a50ee55dfca6ef0a4efb8abf
2,384
cpp
C++
solutions/LeetCode/C++/135.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/135.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/135.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ 12ms class Solution { public: int candy(vector<int>& ratings) { int length = ratings.size(); vector<int> candies(length, 0); int cur_max = 0; int prev = -1; for(int i = 0; i < length; ++i) { if (ratings[i] > prev) { ++cur_max; candies[i] = cur_max; } else { cur_max = 1; candies[i] = cur_max; } prev = ratings[i]; } cur_max = 0; prev = -1; for(int i = length - 1; i >= 0; --i) { if (ratings[i] > prev) { ++cur_max; candies[i] = max(cur_max, candies[i]); } else { cur_max = 1; candies[i] = max(candies[i], cur_max); } prev = ratings[i]; } return accumulate(candies.begin(), candies.end(), 0); } }; auto ___ = []() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); return 0; }(); __________________________________________________________________________________________________ 9964 kb class Solution { public: int candy(vector<int>& ratings) { const int n = ratings.size(); int total = 1; int prev = 1; int countDown = 0; for (int i = 1; i < n; i++) { if (ratings[i] >= ratings[i - 1]) { if (countDown > 0) { total += countDown * (countDown + 1) / 2; if (prev <= countDown) { total += countDown + 1 - prev; } countDown = 0; prev = 1; } if (ratings[i] == ratings[i - 1]) { prev = 1; } else { prev++; } total += prev; } else { countDown++; } } if (countDown > 0) { total += countDown * (countDown + 1) / 2; if (prev <= countDown) { total += countDown + 1 - prev; } } return total; } }; __________________________________________________________________________________________________
29.073171
98
0.448406
[ "vector" ]
581d14382676cfdc10230ad41a31d2d289f5260b
11,740
cc
C++
RecoTauTag/RecoTau/plugins/PFTauPrimaryVertexProducer.cc
trackerpro/cmssw
3e05774a180a5f4cdc70b713bd711c23f9364765
[ "Apache-2.0" ]
1
2019-03-09T19:47:49.000Z
2019-03-09T19:47:49.000Z
RecoTauTag/RecoTau/plugins/PFTauPrimaryVertexProducer.cc
trackerpro/cmssw
3e05774a180a5f4cdc70b713bd711c23f9364765
[ "Apache-2.0" ]
null
null
null
RecoTauTag/RecoTau/plugins/PFTauPrimaryVertexProducer.cc
trackerpro/cmssw
3e05774a180a5f4cdc70b713bd711c23f9364765
[ "Apache-2.0" ]
1
2019-03-19T13:44:54.000Z
2019-03-19T13:44:54.000Z
/* class PFTauPrimaryVertexProducer * EDProducer of the * authors: Ian M. Nugent * This work is based on the impact parameter work by Rosamaria Venditti and reconstructing the 3 prong taus. * The idea of the fully reconstructing the tau using a kinematic fit comes from * Lars Perchalla and Philip Sauerland Theses under Achim Stahl supervision. This * work was continued by Ian M. Nugent and Vladimir Cherepanov. * Thanks goes to Christian Veelken and Evan Klose Friis for their help and suggestions. */ #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/Exception.h" #include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" #include "TrackingTools/Records/interface/TransientTrackRecord.h" #include "RecoVertex/VertexPrimitives/interface/TransientVertex.h" #include "RecoVertex/AdaptiveVertexFit/interface/AdaptiveVertexFitter.h" #include "RecoTauTag/RecoTau/interface/RecoTauVertexAssociator.h" #include "DataFormats/TauReco/interface/PFTau.h" #include "DataFormats/TauReco/interface/PFTauFwd.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/MuonReco/interface/MuonFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/GsfTrackReco/interface/GsfTrack.h" #include "DataFormats/GsfTrackReco/interface/GsfTrackFwd.h" #include "DataFormats/Common/interface/RefToBase.h" #include "DataFormats/EgammaCandidates/interface/Electron.h" #include "DataFormats/EgammaCandidates/interface/ElectronFwd.h" #include "DataFormats/Common/interface/Association.h" #include "DataFormats/Common/interface/AssociationVector.h" #include "DataFormats/Common/interface/RefProd.h" #include "DataFormats/TauReco/interface/PFTauDiscriminator.h" #include "CommonTools/Utils/interface/StringCutObjectSelector.h" #include <memory> #include <TFormula.h> #include <memory> using namespace reco; using namespace edm; using namespace std; class PFTauPrimaryVertexProducer final : public edm::stream::EDProducer<> { public: enum Alg{useInputPV=0, useFontPV}; struct DiscCutPair{ DiscCutPair():discr_(nullptr),cutFormula_(nullptr){} ~DiscCutPair(){delete cutFormula_;} const reco::PFTauDiscriminator* discr_; edm::EDGetTokenT<reco::PFTauDiscriminator> inputToken_; double cut_; TFormula* cutFormula_; }; typedef std::vector<DiscCutPair*> DiscCutPairVec; explicit PFTauPrimaryVertexProducer(const edm::ParameterSet& iConfig); ~PFTauPrimaryVertexProducer() override; void produce(edm::Event&,const edm::EventSetup&) override; private: edm::InputTag PFTauTag_; edm::EDGetTokenT<std::vector<reco::PFTau> >PFTauToken_; edm::InputTag ElectronTag_; edm::EDGetTokenT<std::vector<reco::Electron> >ElectronToken_; edm::InputTag MuonTag_; edm::EDGetTokenT<std::vector<reco::Muon> >MuonToken_; edm::InputTag PVTag_; edm::EDGetTokenT<reco::VertexCollection> PVToken_; edm::InputTag beamSpotTag_; edm::EDGetTokenT<reco::BeamSpot> beamSpotToken_; int Algorithm_; edm::ParameterSet qualityCutsPSet_; bool useBeamSpot_; bool useSelectedTaus_; bool RemoveMuonTracks_; bool RemoveElectronTracks_; DiscCutPairVec discriminators_; std::unique_ptr<StringCutObjectSelector<reco::PFTau> > cut_; std::unique_ptr<tau::RecoTauVertexAssociator> vertexAssociator_; }; PFTauPrimaryVertexProducer::PFTauPrimaryVertexProducer(const edm::ParameterSet& iConfig): PFTauTag_(iConfig.getParameter<edm::InputTag>("PFTauTag")), PFTauToken_(consumes<std::vector<reco::PFTau> >(PFTauTag_)), ElectronTag_(iConfig.getParameter<edm::InputTag>("ElectronTag")), ElectronToken_(consumes<std::vector<reco::Electron> >(ElectronTag_)), MuonTag_(iConfig.getParameter<edm::InputTag>("MuonTag")), MuonToken_(consumes<std::vector<reco::Muon> >(MuonTag_)), PVTag_(iConfig.getParameter<edm::InputTag>("PVTag")), PVToken_(consumes<reco::VertexCollection>(PVTag_)), beamSpotTag_(iConfig.getParameter<edm::InputTag>("beamSpot")), beamSpotToken_(consumes<reco::BeamSpot>(beamSpotTag_)), Algorithm_(iConfig.getParameter<int>("Algorithm")), qualityCutsPSet_(iConfig.getParameter<edm::ParameterSet>("qualityCuts")), useBeamSpot_(iConfig.getParameter<bool>("useBeamSpot")), useSelectedTaus_(iConfig.getParameter<bool>("useSelectedTaus")), RemoveMuonTracks_(iConfig.getParameter<bool>("RemoveMuonTracks")), RemoveElectronTracks_(iConfig.getParameter<bool>("RemoveElectronTracks")) { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::vector<edm::ParameterSet> discriminators =iConfig.getParameter<std::vector<edm::ParameterSet> >("discriminators"); // Build each of our cuts for(auto const& pset : discriminators) { DiscCutPair* newCut = new DiscCutPair(); newCut->inputToken_ =consumes<reco::PFTauDiscriminator>(pset.getParameter<edm::InputTag>("discriminator")); if ( pset.existsAs<std::string>("selectionCut") ) newCut->cutFormula_ = new TFormula("selectionCut", pset.getParameter<std::string>("selectionCut").data()); else newCut->cut_ = pset.getParameter<double>("selectionCut"); discriminators_.push_back(newCut); } // Build a string cut if desired if (iConfig.exists("cut")) cut_.reset(new StringCutObjectSelector<reco::PFTau>(iConfig.getParameter<std::string>( "cut" ))); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// produces<edm::AssociationVector<PFTauRefProd, std::vector<reco::VertexRef> > >(); produces<VertexCollection>("PFTauPrimaryVertices"); vertexAssociator_.reset(new tau::RecoTauVertexAssociator(qualityCutsPSet_,consumesCollector())); } PFTauPrimaryVertexProducer::~PFTauPrimaryVertexProducer(){} void PFTauPrimaryVertexProducer::produce(edm::Event& iEvent,const edm::EventSetup& iSetup){ // Obtain Collections edm::ESHandle<TransientTrackBuilder> transTrackBuilder; iSetup.get<TransientTrackRecord>().get("TransientTrackBuilder",transTrackBuilder); edm::Handle<std::vector<reco::PFTau> > Tau; iEvent.getByToken(PFTauToken_,Tau); edm::Handle<std::vector<reco::Electron> > Electron; iEvent.getByToken(ElectronToken_,Electron); edm::Handle<std::vector<reco::Muon> > Mu; iEvent.getByToken(MuonToken_,Mu); edm::Handle<reco::VertexCollection > PV; iEvent.getByToken(PVToken_,PV); edm::Handle<reco::BeamSpot> beamSpot; iEvent.getByToken(beamSpotToken_,beamSpot); // Set Association Map auto AVPFTauPV = std::make_unique<edm::AssociationVector<PFTauRefProd, std::vector<reco::VertexRef>>>(PFTauRefProd(Tau)); auto VertexCollection_out = std::make_unique<VertexCollection>(); reco::VertexRefProd VertexRefProd_out = iEvent.getRefBeforePut<reco::VertexCollection>("PFTauPrimaryVertices"); // Load each discriminator for(auto& disc : discriminators_) { edm::Handle<reco::PFTauDiscriminator> discr; iEvent.getByToken(disc->inputToken_, discr); disc->discr_ = &(*discr); } // Set event for VerexAssociator if needed if(useInputPV==Algorithm_) vertexAssociator_->setEvent(iEvent); // For each Tau Run Algorithim if(Tau.isValid()){ for(reco::PFTauCollection::size_type iPFTau = 0; iPFTau < Tau->size(); iPFTau++) { reco::PFTauRef tau(Tau, iPFTau); reco::Vertex thePV; if(useInputPV==Algorithm_){ thePV =(*( vertexAssociator_->associatedVertex(*tau))); } else if(useFontPV==Algorithm_){ thePV=PV->front(); } /////////////////////// // Check if it passed all the discrimiantors bool passed(true); for(auto const& disc : discriminators_) { // Check this discriminator passes bool passedDisc = true; if ( disc->cutFormula_ )passedDisc = (disc->cutFormula_->Eval((*disc->discr_)[tau]) > 0.5); else passedDisc = ((*disc->discr_)[tau] > disc->cut_); if ( !passedDisc ){passed = false; break;} } if (passed && cut_.get()){passed = (*cut_)(*tau);} if (passed){ std::vector<reco::TrackBaseRef> SignalTracks; for(reco::PFTauCollection::size_type jPFTau = 0; jPFTau < Tau->size(); jPFTau++) { if(useSelectedTaus_ || iPFTau==jPFTau){ reco::PFTauRef RefPFTau(Tau, jPFTau); /////////////////////////////////////////////////////////////////////////////////////////////// // Get tracks from PFTau daugthers const std::vector<edm::Ptr<reco::PFCandidate> > cands = RefPFTau->signalPFChargedHadrCands(); for (std::vector<edm::Ptr<reco::PFCandidate> >::const_iterator iter = cands.begin(); iter!=cands.end(); iter++){ if(iter->get()->trackRef().isNonnull()) SignalTracks.push_back(reco::TrackBaseRef(iter->get()->trackRef())); else if(iter->get()->gsfTrackRef().isNonnull()){SignalTracks.push_back(reco::TrackBaseRef(((iter)->get()->gsfTrackRef())));} } } } // Get Muon tracks if(RemoveMuonTracks_){ if(Mu.isValid()) { for(reco::MuonCollection::size_type iMuon = 0; iMuon< Mu->size(); iMuon++){ reco::MuonRef RefMuon(Mu, iMuon); if(RefMuon->track().isNonnull()) SignalTracks.push_back(reco::TrackBaseRef(RefMuon->track())); } } } // Get Electron Tracks if(RemoveElectronTracks_){ if(Electron.isValid()) { for(reco::ElectronCollection::size_type iElectron = 0; iElectron<Electron->size(); iElectron++){ reco::ElectronRef RefElectron(Electron, iElectron); if(RefElectron->track().isNonnull()) SignalTracks.push_back(reco::TrackBaseRef(RefElectron->track())); } } } /////////////////////////////////////////////////////////////////////////////////////////////// // Get Non-Tau tracks reco::TrackCollection nonTauTracks; for(std::vector<reco::TrackBaseRef>::const_iterator vtxTrkRef=thePV.tracks_begin();vtxTrkRef<thePV.tracks_end();vtxTrkRef++){ bool matched = false; for (unsigned int sigTrk = 0; sigTrk < SignalTracks.size(); sigTrk++) { if ( (*vtxTrkRef) == SignalTracks[sigTrk] ) { matched = true; } } if ( !matched ) nonTauTracks.push_back(**vtxTrkRef); } /////////////////////////////////////////////////////////////////////////////////////////////// // Refit the vertex TransientVertex transVtx; std::vector<reco::TransientTrack> transTracks; for (reco::TrackCollection::iterator iter=nonTauTracks.begin(); iter!=nonTauTracks.end(); ++iter){ transTracks.push_back(transTrackBuilder->build(*iter)); } bool FitOk(true); if ( transTracks.size() >= 2 ) { AdaptiveVertexFitter avf; avf.setWeightThreshold(0.1); //weight per track. allow almost every fit, else --> exception try { if ( !useBeamSpot_ ){ transVtx = avf.vertex(transTracks); } else { transVtx = avf.vertex(transTracks, *beamSpot); } } catch (...) { FitOk = false; } } else FitOk = false; if ( FitOk ) thePV = transVtx; } VertexRef VRef = reco::VertexRef(VertexRefProd_out, VertexCollection_out->size()); VertexCollection_out->push_back(thePV); AVPFTauPV->setValue(iPFTau, VRef); } } iEvent.put(std::move(VertexCollection_out),"PFTauPrimaryVertices"); iEvent.put(std::move(AVPFTauPV)); } DEFINE_FWK_MODULE(PFTauPrimaryVertexProducer);
42.846715
160
0.7046
[ "vector" ]
581f6a8aaaf291626c1da3fa6362095cf66bcf84
34,770
cc
C++
nox/src/nox/netapps/storage/dht-impl.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
28
2015-02-04T13:59:25.000Z
2021-12-29T03:44:47.000Z
nox/src/nox/netapps/storage/dht-impl.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
552
2015-01-05T18:25:54.000Z
2022-03-16T18:51:13.000Z
nox/src/nox/netapps/storage/dht-impl.cc
ayjazz/OESS
deadc504d287febc7cbd7251ddb102bb5c8b1f04
[ "Apache-2.0" ]
25
2015-02-04T18:48:20.000Z
2020-06-18T15:51:05.000Z
/* Copyright 2008 (C) Nicira, Inc. * * This file is part of NOX. * * NOX 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. * * NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>. */ #include "dht-impl.hh" #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/variant/get.hpp> #include "vlog.hh" using namespace std; using namespace vigil; using namespace vigil::applications::storage; static Vlog_module lg("dht-impl"); DHT_entry::DHT_entry() : next_tid(0) { } DHT_entry::DHT_entry(const Reference& id_) : id(id_), next_tid(0) { } DHT_entry::~DHT_entry() { } void DHT_entry::put_trigger(DHT_ptr& ring,const Reference& current_row, const Trigger_function& f, const Async_storage::Put_trigger_callback& cb) { if (!(id == current_row)) { ring->dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Row modified since retrieval."), Trigger_id("", Reference(),-1))); return; } Trigger_id tid = ring->trigger_instance(id, next_tid++); Trigger_map& triggers = nonsticky_triggers; triggers[tid] = f; ring->dispatcher->post(boost::bind(cb, Result(), tid)); } const Result DHT_entry::remove_trigger(DHT_ptr& ring, const Trigger_id& tid) { if (!(id == tid.ref)) { /* Trigger modified, a likely race condition between the trigger invocation and application. */ return Result(Result::CONCURRENT_MODIFICATION, "Row modified since trigger insertion."); } nonsticky_triggers.erase(tid); return Result(); } void Index_DHT_entry::get(const Content_DHT_ptr& content_ring, Context& ctxt, const Async_storage::Get_callback& cb) const { if (refs.empty()) { content_ring->dispatcher->post (boost::bind(cb, Result(Result::NO_MORE_ROWS, "No more rows."), ctxt, Row())); return; } const Reference& ref = refs[0]; //lg.dbg("id = %s, get index entry for %s", id.str().c_str(), // ref.str().c_str()); ctxt.index_row = id; content_ring->dispatcher->post(boost::bind(&Content_DHT::get, content_ring, content_ring, ctxt, ref, true, cb)); } void Index_DHT_entry::get_next(const Content_DHT_ptr& content_ring, Context& ctxt, const Async_storage::Get_callback& cb) const { /* Check the index entry has not been modified since the first get(). */ if (!(ctxt.index_row == id)) { content_ring->dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Index modified while iterating."), ctxt, Row())); return; } References::const_iterator j = refs.begin(); for (; j != refs.end() && !(ctxt.current_row == *j); ++j); if (j != refs.end()) { ++j; }; /* Attempt to get the next row. */ if (j != refs.end()) { content_ring->dispatcher->post (boost::bind(&Content_DHT::get, content_ring, content_ring, ctxt, *j, true, cb)); } else { content_ring->dispatcher->post (boost::bind(cb, Result(Result::NO_MORE_ROWS, "No more rows."), ctxt, Row())); } } void Index_DHT_entry::put(Index_DHT_ptr& index_ring, const Reference& ref, const Row& row, const Trigger_function& tfunc, const Index_updated_callback& cb, const Trigger_reason reason) { //lg.dbg("id = %s, Adding index entry for %s", id.str().c_str(), // ref.str().c_str()); /* Delete the previous reference to the primary row, if it exists. */ /*for (References::iterator i = refs.begin(); i != refs.end(); ++i) { if (i->guid == ref.guid && *i < ref) { refs.erase(i); break; } }*/ /* Store the reference and execute triggers */ refs.push_back(ref); id.version++; /* Enqueue the triggers for invocation */ BOOST_FOREACH(Trigger_map::value_type t, nonsticky_triggers) { index_ring->dispatcher->post(boost::bind(t.second, t.first, row, reason)); } nonsticky_triggers.clear(); /* Replace any previous primary triggers */ /* Reference_trigger_def_map new_primary_triggers; BOOST_FOREACH(Reference_trigger_def_map::value_type t, primary_triggers) { if (!(t.first.guid == ref.guid && t.first < ref)) { new_primary_triggers.insert(t); } } primary_triggers = new_primary_triggers;*/ /* Install the new trigger for the primary row */ Trigger_id tid = index_ring->trigger_instance(id, next_tid++); primary_triggers[ref] = make_pair(tid, tfunc); index_ring->dispatcher->post (boost::bind(cb, pair<Trigger_id, Trigger_function> (tid, boost::bind(&Index_DHT::primary_deleted_callback, index_ring, index_ring, _1, _2, row, id.guid, ref)))); } void Index_DHT_entry::modify(Index_DHT_ptr& index_ring, const Reference& prev_ref, const Reference& ref, const Row& prev_row, const Row& row, const Trigger_function& tfunc, const Index_updated_callback& cb, const Trigger_reason reason) { //lg.dbg("id %s, Modifying index entry for prev %s, now %s", id.str().c_str(), // prev_ref.str().c_str(), // ref.str().c_str()); /* Delete the previous reference to the primary row, if it exists. */ References::iterator i = refs.begin(); for (; i != refs.end(); ++i) { if (*i == prev_ref) { refs.erase(i); break; } } /* Store the new reference and execute triggers */ refs.push_back(ref); id.version++; //lg.dbg("refs # = %d", refs.size()); /* Enqueue the triggers for invocation */ BOOST_FOREACH(Trigger_map::value_type t, nonsticky_triggers) { index_ring->dispatcher->post(boost::bind(t.second, t.first, prev_row, reason)); } nonsticky_triggers.clear(); /* Remove any previous row related primary triggers */ Reference_trigger_def_map new_primary_triggers; BOOST_FOREACH(Reference_trigger_def_map::value_type t, primary_triggers) { if (!(t.first == prev_ref)) { new_primary_triggers.insert(t); } } primary_triggers = new_primary_triggers; /* Install the new trigger for the primary row */ Trigger_id tid = index_ring->trigger_instance(id, next_tid++); primary_triggers[ref] = make_pair(tid, tfunc); index_ring->dispatcher->post (boost::bind(cb, pair<Trigger_id, Trigger_function> (tid, boost::bind(&Index_DHT::primary_deleted_callback, index_ring, index_ring, _1, _2, row, id.guid, ref)))); } const Result Index_DHT_entry::remove(Index_DHT_ptr& index_ring, const Reference& ref, const Row& row, const Trigger_reason reason) { //lg.dbg("id %s, Removing index entry for %s", id.str().c_str(), // ref.str().c_str()); /* Remove the reference and enqueue the all triggers for invocation */ References::iterator i = refs.begin(); for (; i != refs.end(); ++i) { if (*i == ref) break; } if (i == refs.end()) { return Result(Result::CONCURRENT_MODIFICATION, "Reference does not exist anymore."); } refs.erase(i); id.version++; BOOST_FOREACH(Trigger_map::value_type t, nonsticky_triggers) { index_ring->dispatcher->post(boost::bind(t.second, t.first, row, reason)); } /* Invoke only primary triggers matching to the removed primary row reference. */ Reference_trigger_def_map new_primary_triggers; BOOST_FOREACH(Reference_trigger_def_map::value_type t, primary_triggers) { if (t.first == ref) { index_ring->dispatcher->post(boost::bind(t.second.second, t.second.first, row, reason)); } else { new_primary_triggers.insert(t); } } primary_triggers = new_primary_triggers; nonsticky_triggers.clear(); return Result(); } bool Index_DHT_entry::empty() { return nonsticky_triggers.empty() && refs.empty(); } void Content_DHT_entry::get(const Content_DHT_ptr& content_ring, Context& ctxt, const Reference& id_, const bool exact_match, const Async_storage::Get_callback& cb) const { /* If version mismatch, index DHT is in inconsistent state momentarily. Caller should re-try if caller told so. */ if (!(id == id_) && exact_match) { content_ring->dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Row modified since its retrieval/" "index creation."), ctxt, Row())); return; } ctxt.initial_row = id; ctxt.current_row = id; content_ring->dispatcher->post(boost::bind(cb, Result(), ctxt, row)); } void Content_DHT_entry::get_next(const Content_DHT_ptr& content_ring, Context& ctxt, const Async_storage::Get_callback& cb) const { ctxt.current_row = id; content_ring->dispatcher->post(boost::bind(cb, Result(), ctxt, row)); } typedef map<GUID, boost::function<void()> > Table_GUID_update_function_map; typedef map<DHT_name, Table_GUID_update_function_map> GUID_update_function_map; const Result Content_DHT_entry::put(Content_DHT_ptr& content_ring, const Context& ctxt, const GUID_index_ring_map& new_sguids, const Row& row_) { /* Check the version, i.e., that no one inserted a row between. */ if (!(id == ctxt.current_row)) { return Result(Result::CONCURRENT_MODIFICATION, "Row modified since retrieval."); } Trigger_map t(nonsticky_triggers.begin(), nonsticky_triggers.end()); nonsticky_triggers.clear(); /* Update the row content and wipe any index triggers. */ Reference prev = id; id.version++; row = row_; sguids = new_sguids; assert(index_triggers.empty()); GUID_update_function_map updates; /* Create new index entries and their corresponding triggers. */ BOOST_FOREACH(GUID_index_ring_map::value_type j, new_sguids) { const DHT_name& index_name = j.first; Index_DHT_ptr& index_ring = j.second.first; const GUID& sguid = j.second.second; Trigger_function tfunc = boost::bind(&Content_DHT:: index_entry_deleted_callback, content_ring, content_ring, id, _1, _2); Index_updated_callback cb = boost::bind(&Content_DHT:: index_entry_updated_callback, content_ring, id, index_name, sguid, row, _1); updates[index_name][sguid] = boost::bind(&Index_DHT::put, index_ring, index_ring, sguid, id, row, tfunc, cb, INSERT); } //assert(new_sguids.size() == updates.size()); /* Execute the index updates */ BOOST_FOREACH(GUID_update_function_map::value_type i, updates) { BOOST_FOREACH(Table_GUID_update_function_map::value_type j, i.second) { content_ring->dispatcher->post(j.second); } } /* Execute application level index triggers. */ BOOST_FOREACH(Trigger_map::value_type i, t) { content_ring->dispatcher->post(boost::bind(i.second,i.first, row, INSERT)); } /* Invoke table triggers */ content_ring->invoke_table_triggers(row, INSERT); return Result(); } const Result Content_DHT_entry::modify(Content_DHT_ptr& content_ring, Context& ctxt, const GUID_index_ring_map& new_sguids, const Row& row_) { /* Check the version */ if (!(id == ctxt.current_row)) { return Result(Result::CONCURRENT_MODIFICATION, "Row modified since its retrieval."); } Trigger_map t(nonsticky_triggers.begin(), nonsticky_triggers.end()); nonsticky_triggers.clear(); /* Update the row content and wipe any index triggers. */ const Reference prev_id = id; const Row prev_row = row; id.version++; row = row_; ctxt.current_row = id; index_triggers.clear(); GUID_update_function_map updates; //lg.dbg("Modifying row %s, %d, %d", prev_id.str().c_str(), // sguids.size(), new_sguids.size()); /* Compute the sets */ BOOST_FOREACH(GUID_index_ring_map::value_type j, new_sguids) { const DHT_name& index_name = j.first; Index_DHT_ptr& index_ring = j.second.first; const GUID& sguid = j.second.second; if (!(sguids[index_name].second == sguid)) { /* New index entry */ Trigger_function tfunc = boost::bind(&Content_DHT::index_entry_deleted_callback, content_ring, content_ring, id, _1, _2); Index_updated_callback cb = boost::bind(&Content_DHT::index_entry_updated_callback, content_ring, id, index_name, sguid, row, _1); updates[index_name][sguid] = boost::bind(&Index_DHT::put, index_ring,index_ring, sguid, id, row, tfunc, cb, MODIFY); //lg.dbg("----> putting index %s for %s", sguid.str().c_str(), // id.str().c_str()); /* Remove the earlier index entry with different sguid */ const GUID& prev_sguid = sguids[index_name].second; cb = boost::bind(&Content_DHT::index_entry_updated_callback, content_ring, id, index_name, prev_sguid, prev_row, _1); updates[index_name][prev_sguid] = boost::bind(&Index_DHT::remove, index_ring, index_ring, prev_sguid, prev_id, prev_row, cb, MODIFY); //lg.dbg("----> removing index %s for %s", prev_sguid.str().c_str(), // prev_id.str().c_str()); } else { /* Modified index entry */ Trigger_function tfunc = boost::bind(&Content_DHT::index_entry_deleted_callback, content_ring, content_ring, id, _1, _2); Index_updated_callback cb = boost::bind(&Content_DHT::index_entry_updated_callback, content_ring, id, index_name, sguid, prev_row, _1); /* boost::bind supports max. 10 parameters by default, hence the std::vector usage. */ std::vector<Reference> t; t.push_back(prev_id); t.push_back(id); updates[index_name][sguid] = boost::bind(&Index_DHT::modify, index_ring, index_ring, sguid, t, prev_row, row, tfunc, cb, MODIFY); //lg.dbg("----> modifying index %s", sguid.str().c_str()); } sguids.erase(index_name); } /* Replace the current index guid set. */ sguids = new_sguids; /* Invoke the index_updates */ BOOST_FOREACH(GUID_update_function_map::value_type i, updates) { BOOST_FOREACH(Table_GUID_update_function_map::value_type j, i.second) { content_ring->dispatcher->post(j.second); } } /* Invoke row triggers */ BOOST_FOREACH(Trigger_map::value_type i, t) { content_ring->dispatcher->post(boost::bind(i.second, i.first, prev_row, MODIFY)); } /* Invoke table triggers */ content_ring->invoke_table_triggers(prev_row, MODIFY); return Result(); } const Result Content_DHT_entry::remove(Content_DHT_ptr& content_ring, const Reference& ref) { /* Check the version */ if (!(id == ref)) return Result(Result::CONCURRENT_MODIFICATION, "Row modified since its retrieval."); const Reference prev_id = id; id.version++; ///* Gather all triggers to invoke */ Trigger_map t(nonsticky_triggers.begin(), nonsticky_triggers.end()); //t.insert(index_triggers.begin(), index_triggers.end()); nonsticky_triggers.clear(); index_triggers.clear(); /* Invoke triggers in increasing GUID order. */ BOOST_FOREACH(Trigger_map::value_type i, t) { content_ring->dispatcher->post(boost::bind(i.second, i.first, row, REMOVE)); } GUID_update_function_map updates; /* Remove index entries */ BOOST_FOREACH(GUID_index_ring_map::value_type j, sguids) { const DHT_name& index_name = j.first; Index_DHT_ptr& index_ring = j.second.first; const GUID& sguid = j.second.second; Index_updated_callback cb = boost::bind(&Content_DHT::index_entry_updated_callback, content_ring, id, index_name, sguid, row, _1); updates[index_name][sguid] = boost::bind(&Index_DHT::remove, index_ring, index_ring, sguid, prev_id, row, cb, REMOVE); } /* Invoke the index_updates */ BOOST_FOREACH(GUID_update_function_map::value_type i, updates) { BOOST_FOREACH(Table_GUID_update_function_map::value_type j, i.second) { content_ring->dispatcher->post(j.second); } } /* Invoke table triggers */ content_ring->invoke_table_triggers(row, REMOVE); /* Remove the row content */ row.clear(); return Result(); } void Content_DHT_entry::index_entry_updated_callback(const Reference& ref, const Index_name& index_name, const GUID& sguid, const Row& row, const Trigger_definition& tdef) { if (!(id == ref)) { return; } //const Trigger_map::size_type size_before = index_triggers.size(); Trigger_id tid(index_name, Reference(0, sguid), 0); index_triggers[tid] = tdef.second; /* Confirm the trigger was inserted properly. */ // assert(size_before + 1 == index_triggers.size()); } bool Content_DHT_entry::empty() { return nonsticky_triggers.empty() && index_triggers.empty() && row.empty(); } DHT::DHT(const DHT_name& n, const container::Component* c) : dispatcher(c), name(n) { } DHT::~DHT() { } Trigger_id DHT::trigger_instance(const Reference& ref, const int tid) { return Trigger_id(name, ref, tid); } Content_DHT::Content_DHT(const DHT_name& name_, const container::Component* c_) : DHT(name_, c_), next_tid(0) { } void Content_DHT::get(Content_DHT_ptr& this_, Context& ctxt, const Reference& id, const bool exact_match, const Async_storage::Get_callback& cb) const { const_iterator j = exact_match ? find(id.guid) : lower_bound(id.guid); /* If nothing found DHT, the ring must be empty (if wildcard GUID reference given) or no specific entry found (if exact match GUID given). */ if (j == end()) { if (exact_match) { dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Can't find specified row"), Context(), Row())); } else { dispatcher->post (boost::bind(cb, Result(Result::NO_MORE_ROWS), Context(), Row())); } return; } j->second.get(this_, ctxt, id, exact_match, cb); } void Content_DHT::get_next(Content_DHT_ptr& this_, Context& ctxt, const Async_storage::Get_callback& cb) const { /* Search for the next and wrap as necessary. */ const_iterator i = upper_bound(ctxt.current_row.guid); if (i == end()) { i = lower_bound(GUID()); if (i == end()) { dispatcher->post (boost::bind(cb, Result(Result::NO_MORE_ROWS, "End of rows."), ctxt, Row())); return; } } /* If the initial GUID is found again, the iteration is complete. */ if (i->first == ctxt.initial_row.guid) { dispatcher->post (boost::bind(cb, Result(Result::NO_MORE_ROWS, "End of rows."), ctxt, Row())); return; } /* If the next GUID would be pass the initial GUID, while the previous wasn't, the iteration must be complete too. */ if (ctxt.current_row.guid < ctxt.initial_row.guid && !(i->first < ctxt.initial_row.guid)) { dispatcher->post (boost::bind(cb, Result(Result::NO_MORE_ROWS, "End of rows."), ctxt, Row())); return; } return i->second.get_next(this_, ctxt, cb); } void Content_DHT::put(Content_DHT_ptr& this_, const GUID_index_ring_map& new_sguids, const Row& row, const Async_storage::Put_callback& cb) { Context ctxt(name); Row row_ = row; /* Generate a new GUID for a new row, if necessary */ if (row_.find("GUID") == row_.end()) { row_["GUID"] = GUID::random(); } try { ctxt.current_row = Reference(0, boost::get<GUID>(row_["GUID"])); } catch (const boost::bad_get& e) { dispatcher->post (boost::bind(cb, Result(Result::INVALID_ROW_OR_QUERY, "GUID given with invalid type."), GUID())); return; } //Co_scoped_mutex l(&mutex); /* Update the content ring and invoke the triggers, if success. */ iterator r = find(ctxt.current_row.guid); if (r == end()) { Content_DHT_entry e = Content_DHT_entry(ctxt.current_row, row_); const Result result = e.put(this_, ctxt, new_sguids, row_); (*this)[ctxt.current_row.guid] = e; dispatcher->post(boost::bind(cb, result, ctxt.current_row.guid)); } else { dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Row does exist."), GUID())); } } void Content_DHT::modify(Content_DHT_ptr& this_, const Context& ctxt, const GUID_index_ring_map& new_sguids, const Row& row, const Async_storage::Modify_callback& cb) { //Co_scoped_mutex l(&mutex); /* Update the content ring and let the entry trigger any callbacks. */ iterator r = find(ctxt.current_row.guid); if (r == end()) { dispatcher->post(boost::bind(cb,Result(Result::CONCURRENT_MODIFICATION, "Row removed since retrieval."), Context(ctxt))); return; } Context new_ctxt(ctxt); const Result result = r->second.modify(this_, new_ctxt, new_sguids, row); dispatcher->post(boost::bind(cb, result, new_ctxt)); } void Content_DHT::remove(Content_DHT_ptr& this_, const Context& ctxt, const Async_storage::Remove_callback& cb) { internal_remove(this_, ctxt.current_row, cb); } void Content_DHT::internal_remove(Content_DHT_ptr& this_, const Reference& current_row, const Async_storage::Remove_callback& cb) { //Co_scoped_mutex l(&mutex); iterator r = find(current_row.guid); if (r == end()) { dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Row removed since retrieval."))); return; } const Result result = r->second.remove(this_, current_row); if (r->second.empty()) { erase(current_row.guid); } else { /* The entry removal isn't empty yet, can't wipe it. */ } dispatcher->post(boost::bind(cb, result)); } void Content_DHT::put_trigger(DHT_ptr& this_, const Context& ctxt, const Trigger_function& f, const Async_storage::Put_trigger_callback& cb) { //Co_scoped_mutex l(&mutex); /* Update the content ring and let the entry trigger any callbacks. */ iterator r = find(ctxt.current_row.guid); if (r == end()) { dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Row removed since retrieval."), Trigger_id("", Reference(),-1))); return; } r->second.put_trigger(this_, ctxt.current_row, f, cb); } void Content_DHT::put_trigger(const bool sticky, const Trigger_function& f, const Async_storage::Put_trigger_callback& cb) { //Co_scoped_mutex l(&mutex); Trigger_id tid(name, next_tid++); if (sticky) { sticky_table_triggers[tid] = f; } else { nonsticky_table_triggers[tid] = f; } dispatcher->post(boost::bind(cb, Result(), tid)); } void Content_DHT::remove_trigger(DHT_ptr& this_, const Trigger_id& tid, const Async_storage::Remove_callback& cb) { //Co_scoped_mutex l(&mutex); if (tid.for_table) { sticky_table_triggers.erase(tid); nonsticky_table_triggers.erase(tid); dispatcher->post(boost::bind(cb, Result())); } else { iterator r = find(tid.ref.guid); if (r == end()) { /* Trigger removed, a likely race condition between the trigger invocation and application. Ignore. */ dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Row " "removed since trigger creation."))); } else { const Result result = r->second.remove_trigger(this_, tid); dispatcher->post(boost::bind(cb, result)); } } } void Content_DHT::invoke_table_triggers(const Row& row, const Trigger_reason reason) { /* Gather table triggers to invoke */ BOOST_FOREACH(Trigger_map::value_type v, sticky_table_triggers) { dispatcher->post(boost::bind(v.second, v.first, row, reason)); } BOOST_FOREACH(Trigger_map::value_type v,nonsticky_table_triggers) { dispatcher->post(boost::bind(v.second, v.first, row, reason)); } nonsticky_table_triggers.clear(); } void Content_DHT::index_entry_updated_callback(const Reference& ref, const Index_name& index_name, const GUID& sguid, const Row& row, const Trigger_definition& tdef) { /* If there's no trigger, this was due to remove(). */ if (tdef.second.empty()) return; //Co_scoped_mutex l(&mutex); iterator r = find(ref.guid); if (r == end()) { // XXX: unnecessary? /* Primary entry doesn't exist anymore and hence, the trigger should be invoked immediately as well. */ //dispatcher->post(boost::bind(tdef.second, tdef.first, row, REMOVE)); return; } r->second.index_entry_updated_callback(ref, index_name, sguid, row, tdef); } static void callback_1(Result) { /* Ignore the result */ } void Content_DHT::index_entry_deleted_callback(Content_DHT_ptr& this_, const Reference& ref, const Trigger_id& tid, const Row& row) { /* Ignore the result of the operation; if nothing wasn't deleted, the trigger invocation was merely delayed on its way or something. */ internal_remove(this_, ref, &callback_1); } Index_DHT::Index_DHT(const DHT_name& name_, const container::Component* c_) : DHT(name_, c_) { } void Index_DHT::get(const Content_DHT_ptr& content_ring, Context& ctxt, const Reference& id, const Async_storage::Get_callback& cb) const { //Co_scoped_mutex l(&mutex); /* If nothing found, it must be a miss. */ const const_iterator i = find(id.guid); ctxt.index_row = id; if (i == end()) { dispatcher->post(boost::bind(cb, Result(Result::NO_MORE_ROWS, "No more rows."), ctxt, Row())); return; } /* Find the content row pointed by the index entry */ const Index_DHT_entry& index_entry = i->second; index_entry.get(content_ring, ctxt, cb); } void Index_DHT::get_next(const Content_DHT_ptr& content_ring, Context& ctxt, const Async_storage::Get_callback& cb) const{ /* If no index entry found, the DHT must be momentarily in inconsistent state. Let the application resolve the conflict. */ //Co_scoped_mutex l(&mutex); const_iterator i = find(ctxt.index_row.guid); if (i == end()) { dispatcher->post (boost::bind(cb, Result(Result::CONCURRENT_MODIFICATION, "Index modified while iterating."), ctxt, Row())); return; } i->second.get_next(content_ring, ctxt, cb); } static void callback_2(const Trigger_definition&) { /* Ignore */ } void Index_DHT::primary_deleted_callback(Index_DHT_ptr& this_, const Trigger_id&, const Row&, const Row& row, const GUID& sguid, const Reference& ref) { /* Ignore the result of the operation; if nothing wasn't deleted, the trigger invocation was merely delayed on its way or something. */ remove(this_, sguid, ref, row, &callback_2, REMOVE); } void Index_DHT::put(Index_DHT_ptr& this_, const GUID& sguid, const Reference& ref, const Row& row, const Trigger_function& tfunc, const Index_updated_callback& cb, const Trigger_reason reason) { //Co_scoped_mutex l(&mutex); //lg.dbg("putting index %s, now %s", sguid.str().c_str(), // ref.str().c_str()); iterator r = find(sguid); if (r == end()) { Index_DHT_entry entry = Index_DHT_entry(Reference(0, sguid)); entry.put(this_, ref, row, tfunc, cb, reason); (*this)[sguid] = entry; } else { r->second.put(this_, ref, row, tfunc, cb, reason); } } void Index_DHT::modify(Index_DHT_ptr& this_, const GUID& sguid, const std::vector<Reference>& t, const Row& prev_row, const Row& new_row, const Trigger_function& tfunc, const Index_updated_callback& cb, const Trigger_reason reason) { //Co_scoped_mutex l(&mutex); const Reference& prev_ref = t[0]; const Reference& ref = t[1]; //lg.dbg("modifying index %s, prev %s, now %s", sguid.str().c_str(), // prev_ref.str().c_str(), ref.str().c_str()); iterator r = find(sguid); if (r == end()) { Index_DHT_entry entry = Index_DHT_entry(Reference(0, sguid)); entry.put(this_, ref, new_row, tfunc, cb, reason); (*this)[sguid] = entry; } else { r->second.modify(this_, prev_ref, ref, prev_row, new_row, tfunc, cb, reason); } } void Index_DHT::remove(Index_DHT_ptr& this_, const GUID& sguid, const Reference& ref, const Row& row, const Index_updated_callback& cb, const Trigger_reason reason) { //Co_scoped_mutex l(&mutex); //lg.dbg("removing index %s, now %s", sguid.str().c_str(), // ref.str().c_str()); iterator r = find(sguid); if (r == end()) { /* Nothing to do. */ dispatcher->post(boost::bind(cb, pair<Trigger_id, Trigger_function>())); return; } Index_DHT_entry& entry = r->second; entry.remove(this_, ref, row, reason); if (entry.empty()) { /* No more references left. */ erase(r); } else { /* Entry has still content. Don't wipe it. */ } dispatcher->post(boost::bind(cb, pair<Trigger_id, Trigger_function>())); } void Index_DHT::put_trigger(DHT_ptr& this_, const Context& ctxt, const Trigger_function& f, const Async_storage::Put_trigger_callback& cb) { //Co_scoped_mutex l(&mutex); /* If necessary create a hash entry where to insert the trigger. */ iterator i = find(ctxt.index_row.guid); if (i == end()) { (*this)[ctxt.index_row.guid] = Index_DHT_entry(ctxt.index_row); i = find(ctxt.index_row.guid); } i->second.put_trigger(this_, ctxt.index_row, f, cb); } void Index_DHT::remove_trigger(DHT_ptr& this_, const Trigger_id& tid, const Async_storage::Remove_trigger_callback& cb) { //Co_scoped_mutex l(&mutex); iterator r = find(tid.ref.guid); if (r == end()) { /* Trigger removed, a likely race condition between the trigger invocation and application. Ignore. */ } else { r->second.remove_trigger(this_, tid); } dispatcher->post(boost::bind(cb, Result())); }
35.771605
85
0.573569
[ "vector" ]
5823d3cb8663201b856b7600da7d1e019ee85b08
8,829
cpp
C++
minescape/components/cmp_rope.cpp
jonathan-sung/minescape
2ed228dc0371d6da4d3a9619bb63dc8ac71b9c5f
[ "Apache-2.0" ]
null
null
null
minescape/components/cmp_rope.cpp
jonathan-sung/minescape
2ed228dc0371d6da4d3a9619bb63dc8ac71b9c5f
[ "Apache-2.0" ]
null
null
null
minescape/components/cmp_rope.cpp
jonathan-sung/minescape
2ed228dc0371d6da4d3a9619bb63dc8ac71b9c5f
[ "Apache-2.0" ]
null
null
null
#include "cmp_rope.h" #include <engine.h> #include <SFML/Window/Mouse.hpp> #include <SFML/Graphics/Vertex.hpp> #include <system_physics.h> #include "cmp_physics.h" #include <Box2D/Box2D.h> #include <system_renderer.h> #include "Box2D/Common/b2Math.h" #include "LevelSystem.h" #include "cmp_player_physics.h" #include "../game.h" using namespace std; RopeComponent::RopeComponent(Entity* p, float maxlength, float delay) :Component(p) { buttonPressed = false; ropeState = RopeState::Ready; ropeMaxLength = maxlength; _usable = true; _delay = delay; launchSpeed = 500; impulseTime = 0.01f; } void RopeComponent::updateClickPos() { //get window relative mouse coordinates Vector2i mousePos = Mouse::getPosition(Engine::GetWindow()); clickPos = Engine::GetWindow().mapPixelToCoords(mousePos); } bool RopeComponent::mouseClick() { if (Mouse::isButtonPressed(Mouse::Button::Left)) { if (!buttonPressed) { buttonPressed = true; return true; } else { return false; } } else { if (buttonPressed) { buttonPressed = false; } return false; } } void RopeComponent::setDirectionVector(Vector2f initialPos, Vector2f targetPos) { //set distance to direction vector directionVector = Vector2f( targetPos.x - initialPos.x, targetPos.y - initialPos.y); //get the length float directionVectorLength = length(directionVector); //divide by the length to get size 1 vector directionVector = Vector2f(directionVector.x / directionVectorLength, directionVector.y / directionVectorLength); } bool RopeComponent::isTouchingWall() { if (ls::getTileAt(currentEndPointPosition) == ls::WALL) return true; else return false; } void RopeComponent::createRopeJoint() { //create joint definition //set the first body auto pyco = _parent->GetCompatibleComponent<PhysicsComponent>(); _pbody = pyco[0].get()->getFixture()->GetBody(); _pbody->SetGravityScale(1.0f); rjDef.bodyA = _pbody; //world vector of the direction of rope launch b2Vec2 directionBVec = b2Vec2(directionVector.x, -directionVector.y); directionBVec.Normalize(); //create the second body definition b2BodyDef endbodydef; //set position to player + direction b2Vec2 offset = b2Vec2(directionBVec.x * (ropeCurrentLength * Physics::physics_scale_inv), directionBVec.y * (ropeCurrentLength * Physics::physics_scale_inv)); endbodydef.position = rjDef.bodyA->GetPosition() + (offset); //make the body static endbodydef.type = b2BodyType::b2_staticBody; //create second body _endBody = Physics::GetWorld()->CreateBody(&endbodydef); //set the second body rjDef.bodyB = _endBody; //make it a rope joint rjDef.type = b2JointType::e_ropeJoint; rjDef.localAnchorA = b2Vec2(0, 0); rjDef.localAnchorB = b2Vec2(0, 0); rjDef.collideConnected = false; //set the maximum length rjDef.maxLength = ropeMaxLength * Physics::physics_scale_inv; //create joint in world auto joint = Physics::GetWorld().get()->CreateJoint(&rjDef); //set it to instance ropeJoint = joint; } void RopeComponent::disposeOfJoint() { try { Physics::GetWorld().get()->DestroyJoint(ropeJoint); } catch (exception e) { cout << "Rope is already disposed of" << endl; } } void RopeComponent::update(double dt) { if (!_usable) { if (ropeState == RopeState::Latched) { disposeOfJoint(); ropeState = RopeState::Withdrawing; } else { delaytimer = _delay; ropeState = RopeState::Unusable; } auto pl = _parent->get_components<PlayerPhysicsComponent>()[0]; if (pl != NULL) { _usable = pl.get()->isCollidable(); } } switch (ropeState) { //rope is ready to be used case RopeState::Ready: { //prepare for rope firing animation currentEndPointPosition = _parent->getPosition(); //on mouse click if (mouseClick()) { SoundEngine::fx_rope_shoot.play(); //handle calculation for rope firing updateClickPos(); //set the direction vector setDirectionVector(_parent->getPosition(), clickPos); //fire rope ropeState = RopeState::InAir; } else if (Engine::keyPressed[Engine::Action2] && sf::Joystick::isConnected(0)) { Vector2i joystickpos = Vector2i(sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::U), sf::Joystick::getAxisPosition(0, sf::Joystick::Axis::V)); clickPos = Vector2f(joystickpos.x * ropeMaxLength, joystickpos.y * ropeMaxLength); //set the direction vector setDirectionVector(_parent->getPosition(), clickPos); //fire rope ropeState = RopeState::InAir; } break; } case RopeState::InAir: { initialRopePosition = _parent->getPosition(); if (length(currentEndPointPosition - initialRopePosition) < ropeMaxLength) { currentEndPointPosition += Vector2f(directionVector.x * launchSpeed * dt, directionVector.y * launchSpeed * dt); } else ropeState = RopeState::Withdrawing; if (isTouchingWall()) { cout << "touched" << endl; finalRopePosition = currentEndPointPosition; ropeCurrentLength = length(finalRopePosition - initialRopePosition); //create the rope joint createRopeJoint(); Vector2f addedImpulse = Vector2f(0, 0); SoundEngine::fx_rope_hit.play(); ropeState = RopeState::Latched; } break; } case RopeState::Latched: { initialRopePosition = _parent->getPosition(); //not touching the ground if (!_parent->get_components<PlayerPhysicsComponent>()[0].get()->isGrounded()) { if (impulseTimer < 0) { impulseTimer = impulseTime; //get the direction vector Vector2f directionVector = Vector2f(finalRopePosition.x - initialRopePosition.x, finalRopePosition.y - initialRopePosition.y); //get the angle float angle = asin(directionVector.y / (sqrt(pow(directionVector.x, 2) + pow(directionVector.y, 2)))); //take 90 degrees angle += b2_pi / 2; //get atan float angleATan = atan(angle); //calculate force impulse forceImpulse = Vector2f(directionVector.x * angleATan, directionVector.y * -angleATan); if (directionVector.y > 0)forceImpulse.y = -forceImpulse.y; //calculate angular force Vector2f appliedAngularForce = Vector2f(forceImpulse.x * dt * b2_pi, forceImpulse.y * dt * b2_pi); bool keyPressed = false; //create added impulse if (Engine::keyPressed[Engine::keybinds::Left]) { keyPressed = true; addedImpulse += Vector2f((directionVector.x > 0 ? -directionVector.x : directionVector.x) * angleATan * 3, (directionVector.y < 0 ? -directionVector.y : directionVector.y) * -angleATan * 3); } else if (Engine::keyPressed[Engine::keybinds::Right]) { keyPressed = true; addedImpulse += Vector2f((directionVector.x > 0 ? directionVector.x : -directionVector.x) * angleATan * 3, (directionVector.y < 0 ? -directionVector.y : directionVector.y) * -angleATan * 3); } //minimise vector addedImpulse = Vector2f(addedImpulse.x * dt, addedImpulse.y * dt); //reduce vector addedImpulse -= Vector2f(addedImpulse.x / 20, addedImpulse.y / 20); _parent->get_components<PlayerPhysicsComponent>()[0].get()->impulse( (keyPressed ? appliedAngularForce + addedImpulse : Vector2f(appliedAngularForce.x * 10, appliedAngularForce.y * 10))); } else { impulseTimer -= dt; } } //once latched make it controllable by player if (Engine::keyPressed[Engine::keybinds::Action1]) { cout << "changing states" << endl; _parent->get_components<PlayerPhysicsComponent>()[0].get()->impulse(Vector2f(0, -5.0f)); disposeOfJoint(); ropeState = RopeState::Withdrawing; } //when player presses jump button go to withdraw and make player jump break; } case RopeState::Withdrawing: { initialRopePosition = _parent->getPosition(); setDirectionVector(_parent->getPosition(), currentEndPointPosition); if (length(currentEndPointPosition - initialRopePosition) > 10.0f) { currentEndPointPosition += Vector2f(-directionVector.x * launchSpeed * dt, -directionVector.y * launchSpeed * dt); } else { //once it has fully reduced go to unusable delaytimer = _delay; ropeState = RopeState::Unusable; } break; } case RopeState::Unusable: { //stay here for a bit (cooldown?) delaytimer -= dt; if (delaytimer <= 0) { //go back to ready ropeState = RopeState::Ready; //reset mouse click for reuse buttonPressed = false; } break; } default: break; } } void RopeComponent::render() { //only render if rope is out if (ropeState == RopeState::InAir || ropeState == RopeState::Latched || ropeState == RopeState::Withdrawing) { //create vertex array (this should be a temporary solution) sf::Vertex ropeLines[] = { sf::Vertex(initialRopePosition), sf::Vertex(currentEndPointPosition) }; //render rope Engine::GetWindow().draw(ropeLines, 2, sf::Lines); } } void RopeComponent::setUsable(bool usable) { _usable = usable; }
26.835866
111
0.702458
[ "render", "vector" ]
58245701a2eda4ff972d1ee76087280966cc4181
6,759
cpp
C++
src/test/shaders.cpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
src/test/shaders.cpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
src/test/shaders.cpp
sweetkristas/swiftly
0b5c2badc88637b8bdaa841a45d1babd8f12a703
[ "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
#include <vector> #include "../asserts.hpp" #include "shaders.hpp" namespace shader { shader::shader(GLenum type, const std::string& name, const std::string& code) : type_(type), shader_(0), name_(name) { ASSERT_LOG(compile(code), "Error compiling shader for " << name_); } bool shader::compile(const std::string& code) { GLint compiled; if(shader_) { glDeleteShader(shader_); shader_ = 0; } ASSERT_LOG(glCreateShader != NULL, "Something bad happened with Glew shader not initialised."); shader_ = glCreateShader(type_); if(shader_ == 0) { std::cerr << "Enable to create shader." << std::endl; return false; } const char* shader_code = code.c_str(); glShaderSource(shader_, 1, &shader_code, NULL); glCompileShader(shader_); glGetShaderiv(shader_, GL_COMPILE_STATUS, &compiled); if(!compiled) { GLint info_len = 0; glGetShaderiv(shader_, GL_INFO_LOG_LENGTH, &info_len); if(info_len > 1) { std::vector<char> info_log; info_log.resize(info_len); glGetShaderInfoLog(shader_, info_log.capacity(), NULL, &info_log[0]); std::string s(info_log.begin(), info_log.end()); std::cerr << "Error compiling shader: " << s << std::endl; } glDeleteShader(shader_); shader_ = 0; return false; } return true; } program_object::program_object() { } program_object::program_object(const std::string& name, const shader& vs, const shader& fs) { init(name, vs, fs); } void program_object::init(const std::string& name, const shader& vs, const shader& fs) { name_ = name; vs_ = vs; fs_ = fs; ASSERT_LOG(link(), "Error linking program: " << name_); } GLuint program_object::get_attribute(const std::string& attr) const { const_actives_map_iterator it = attribs_.find(attr); ASSERT_LOG(it != attribs_.end(), "Attribute \"" << attr << "\" not found in list."); return it->second.location; } GLuint program_object::get_uniform(const std::string& attr) const { const_actives_map_iterator it = uniforms_.find(attr); ASSERT_LOG(it != uniforms_.end(), "Uniform \"" << attr << "\" not found in list."); return it->second.location; } const_actives_map_iterator program_object::get_attribute_iterator(const std::string& attr) const { const_actives_map_iterator it = attribs_.find(attr); ASSERT_LOG(it != attribs_.end(), "Attribute \"" << attr << "\" not found in list."); return it; } const_actives_map_iterator program_object::get_uniform_iterator(const std::string& attr) const { std::map<std::string, actives>::const_iterator it = uniforms_.find(attr); ASSERT_LOG(it != uniforms_.end(), "Uniform \"" << attr << "\" not found in list."); return it; } bool program_object::link() { if(object_) { glDeleteProgram(object_); object_ = 0; } object_ = glCreateProgram(); ASSERT_LOG(object_ != 0, "Unable to create program object."); glAttachShader(object_, vs_.get()); glAttachShader(object_, fs_.get()); glLinkProgram(object_); GLint linked = 0; glGetProgramiv(object_, GL_LINK_STATUS, &linked); if(!linked) { GLint info_len = 0; glGetProgramiv(object_, GL_INFO_LOG_LENGTH, &info_len); if(info_len > 1) { std::vector<char> info_log; info_log.resize(info_len); glGetProgramInfoLog(object_, info_log.capacity(), NULL, &info_log[0]); std::string s(info_log.begin(), info_log.end()); std::cerr << "Error linking object: " << s << std::endl; } glDeleteProgram(object_); object_ = 0; return false; } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); return queryUniforms() && queryAttributes(); } bool program_object::queryUniforms() { GLint active_uniforms; glGetProgramiv(object_, GL_ACTIVE_UNIFORMS, &active_uniforms); GLint uniform_max_len; glGetProgramiv(object_, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniform_max_len); std::vector<char> name; name.resize(uniform_max_len+1); for(int i = 0; i < active_uniforms; i++) { actives u; GLsizei size; glGetActiveUniform(object_, i, name.size(), &size, &u.num_elements, &u.type, &name[0]); u.name = std::string(&name[0], &name[size]); u.location = glGetUniformLocation(object_, u.name.c_str()); ASSERT_LOG(u.location >= 0, "Unable to determine the location of the uniform: " << u.name); uniforms_[u.name] = u; } return true; } bool program_object::queryAttributes() { GLint active_attribs; glGetProgramiv(object_, GL_ACTIVE_ATTRIBUTES, &active_attribs); GLint attributes_max_len; glGetProgramiv(object_, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &attributes_max_len); std::vector<char> name; name.resize(attributes_max_len+1); for(int i = 0; i < active_attribs; i++) { actives a; GLsizei size; glGetActiveAttrib(object_, i, name.size(), &size, &a.num_elements, &a.type, &name[0]); a.name = std::string(&name[0], &name[size]); a.location = glGetAttribLocation(object_, a.name.c_str()); ASSERT_LOG(a.location >= 0, "Unable to determine the location of the attribute: " << a.name); attribs_[a.name] = a; } return true; } void program_object::make_active() { glUseProgram(object_); } void program_object::set_uniform(const_actives_map_iterator it, const GLint* value) { const actives& u = it->second; ASSERT_LOG(value != NULL, "set_uniform(): value is NULL"); switch(u.type) { case GL_INT: case GL_BOOL: case GL_SAMPLER_2D: case GL_SAMPLER_CUBE: glUniform1i(u.location, *value); break; case GL_INT_VEC2: case GL_BOOL_VEC2: glUniform2i(u.location, value[0], value[1]); break; case GL_INT_VEC3: case GL_BOOL_VEC3: glUniform3iv(u.location, u.num_elements, value); break; case GL_INT_VEC4: case GL_BOOL_VEC4: glUniform4iv(u.location, u.num_elements, value); break; default: ASSERT_LOG(false, "Unhandled uniform type: " << it->second.type); } } void program_object::set_uniform(const_actives_map_iterator it, const GLfloat* value) { const actives& u = it->second; ASSERT_LOG(value != NULL, "set_uniform(): value is NULL"); switch(u.type) { case GL_FLOAT: { glUniform1f(u.location, *value); break; } case GL_FLOAT_VEC2: { glUniform2fv(u.location, u.num_elements, value); break; } case GL_FLOAT_VEC3: { glUniform3fv(u.location, u.num_elements, value); break; } case GL_FLOAT_VEC4: { glUniform4fv(u.location, u.num_elements, value); break; } case GL_FLOAT_MAT2: { glUniformMatrix2fv(u.location, u.num_elements, GL_FALSE, value); break; } case GL_FLOAT_MAT3: { glUniformMatrix3fv(u.location, u.num_elements, GL_FALSE, value); break; } case GL_FLOAT_MAT4: { glUniformMatrix4fv(u.location, u.num_elements, GL_FALSE, value); break; } default: ASSERT_LOG(false, "Unhandled uniform type: " << it->second.type); } } }
28.639831
97
0.686492
[ "object", "vector" ]
5826e5d01c5911c584490c6a2c1ad9bc5a12c0af
59,017
cpp
C++
Source/ALSV4_CPP/Private/Character/ALSBaseCharacter.cpp
insomniaunleashed/ALSV4_CPP
14e3c402fa017983ebfdb9971ec8b25b75284fe4
[ "MIT" ]
2
2020-12-15T08:25:22.000Z
2020-12-15T08:25:32.000Z
Source/ALSV4_CPP/Private/Character/ALSBaseCharacter.cpp
snzhkhd/ALSV4_CPP
2835514b59791581a0069e510b7878f0ba1e67c2
[ "MIT" ]
null
null
null
Source/ALSV4_CPP/Private/Character/ALSBaseCharacter.cpp
snzhkhd/ALSV4_CPP
2835514b59791581a0069e510b7878f0ba1e67c2
[ "MIT" ]
null
null
null
// Project: Advanced Locomotion System V4 on C++ // Copyright: Copyright (C) 2020 Doğa Can Yanıkoğlu // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/dyanikoglu/ALSV4_CPP // Original Author: Doğa Can Yanıkoğlu // Contributors: Haziq Fadhil #include "Character/ALSBaseCharacter.h" #include "Character/ALSPlayerController.h" #include "Character/Animation/ALSCharacterAnimInstance.h" #include "Library/ALSMathLibrary.h" #include "Components/CapsuleComponent.h" #include "Components/TimelineComponent.h" #include "Curves/CurveVector.h" #include "Curves/CurveFloat.h" #include "Character/ALSCharacterMovementComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/GameplayStatics.h" #include "TimerManager.h" #include "Net/UnrealNetwork.h" AALSBaseCharacter::AALSBaseCharacter(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer.SetDefaultSubobjectClass<UALSCharacterMovementComponent>(CharacterMovementComponentName)) { PrimaryActorTick.bCanEverTick = true; MantleTimeline = CreateDefaultSubobject<UTimelineComponent>(FName(TEXT("MantleTimeline"))); bUseControllerRotationYaw = 0; bReplicates = true; SetReplicatingMovement(true); } void AALSBaseCharacter::Restart() { Super::Restart(); AALSPlayerController* NewController = Cast<AALSPlayerController>(GetController()); if (NewController) { NewController->OnRestartPawn(this); } } void AALSBaseCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("MoveForward/Backwards", this, &AALSBaseCharacter::PlayerForwardMovementInput); PlayerInputComponent->BindAxis("MoveRight/Left", this, &AALSBaseCharacter::PlayerRightMovementInput); PlayerInputComponent->BindAxis("LookUp/Down", this, &AALSBaseCharacter::PlayerCameraUpInput); PlayerInputComponent->BindAxis("LookLeft/Right", this, &AALSBaseCharacter::PlayerCameraRightInput); PlayerInputComponent->BindAction("JumpAction", IE_Pressed, this, &AALSBaseCharacter::JumpPressedAction); PlayerInputComponent->BindAction("JumpAction", IE_Released, this, &AALSBaseCharacter::JumpReleasedAction); PlayerInputComponent->BindAction("StanceAction", IE_Pressed, this, &AALSBaseCharacter::StancePressedAction); PlayerInputComponent->BindAction("WalkAction", IE_Pressed, this, &AALSBaseCharacter::WalkPressedAction); PlayerInputComponent->BindAction("RagdollAction", IE_Pressed, this, &AALSBaseCharacter::RagdollPressedAction); PlayerInputComponent->BindAction("SelectRotationMode_1", IE_Pressed, this, &AALSBaseCharacter::VelocityDirectionPressedAction); PlayerInputComponent->BindAction("SelectRotationMode_2", IE_Pressed, this, &AALSBaseCharacter::LookingDirectionPressedAction); PlayerInputComponent->BindAction("SprintAction", IE_Pressed, this, &AALSBaseCharacter::SprintPressedAction); PlayerInputComponent->BindAction("SprintAction", IE_Released, this, &AALSBaseCharacter::SprintReleasedAction); PlayerInputComponent->BindAction("AimAction", IE_Pressed, this, &AALSBaseCharacter::AimPressedAction); PlayerInputComponent->BindAction("AimAction", IE_Released, this, &AALSBaseCharacter::AimReleasedAction); PlayerInputComponent->BindAction("CameraAction", IE_Pressed, this, &AALSBaseCharacter::CameraPressedAction); PlayerInputComponent->BindAction("CameraAction", IE_Released, this, &AALSBaseCharacter::CameraReleasedAction); } void AALSBaseCharacter::PostInitializeComponents() { Super::PostInitializeComponents(); MyCharacterMovementComponent = Cast<UALSCharacterMovementComponent>(Super::GetMovementComponent()); } void AALSBaseCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AALSBaseCharacter, TargetRagdollLocation); DOREPLIFETIME_CONDITION(AALSBaseCharacter, ReplicatedCurrentAcceleration, COND_SkipOwner); DOREPLIFETIME_CONDITION(AALSBaseCharacter, ReplicatedControlRotation, COND_SkipOwner); DOREPLIFETIME(AALSBaseCharacter, DesiredGait); DOREPLIFETIME_CONDITION(AALSBaseCharacter, DesiredStance, COND_SkipOwner); DOREPLIFETIME_CONDITION(AALSBaseCharacter, DesiredRotationMode, COND_SkipOwner); DOREPLIFETIME_CONDITION(AALSBaseCharacter, RotationMode, COND_SkipOwner); DOREPLIFETIME_CONDITION(AALSBaseCharacter, OverlayState, COND_SkipOwner); DOREPLIFETIME_CONDITION(AALSBaseCharacter, ViewMode, COND_SkipOwner); } void AALSBaseCharacter::OnBreakfall_Implementation() { Replicated_PlayMontage(GetRollAnimation(), 1.35); } void AALSBaseCharacter::Replicated_PlayMontage_Implementation(UAnimMontage* montage, float track) { // Roll: Simply play a Root Motion Montage. MainAnimInstance->Montage_Play(montage, track); Server_PlayMontage(montage, track); } void AALSBaseCharacter::BeginPlay() { Super::BeginPlay(); // If we're in networked game, disable curved movement bDisableCurvedMovement = !IsNetMode(ENetMode::NM_Standalone); FOnTimelineFloat TimelineUpdated; FOnTimelineEvent TimelineFinished; TimelineUpdated.BindUFunction(this, FName(TEXT("MantleUpdate"))); TimelineFinished.BindUFunction(this, FName(TEXT("MantleEnd"))); MantleTimeline->SetTimelineFinishedFunc(TimelineFinished); MantleTimeline->SetLooping(false); MantleTimeline->SetTimelineLengthMode(TL_TimelineLength); MantleTimeline->AddInterpFloat(MantleTimelineCurve, TimelineUpdated); // Make sure the mesh and animbp update after the CharacterBP to ensure it gets the most recent values. GetMesh()->AddTickPrerequisiteActor(this); // Set the Movement Model SetMovementModel(); // Once, force set variables in anim bp. This ensures anim instance & character starts synchronized FALSAnimCharacterInformation& AnimData = MainAnimInstance->GetCharacterInformationMutable(); MainAnimInstance->Gait = DesiredGait; MainAnimInstance->Stance = DesiredStance; MainAnimInstance->RotationMode = DesiredRotationMode; AnimData.ViewMode = ViewMode; MainAnimInstance->OverlayState = OverlayState; AnimData.PrevMovementState = PrevMovementState; MainAnimInstance->MovementState = MovementState; // Update states to use the initial desired values. SetGait(DesiredGait); SetStance(DesiredStance); SetRotationMode(DesiredRotationMode); SetViewMode(ViewMode); SetOverlayState(OverlayState); if (Stance == EALSStance::Standing) { UnCrouch(); } else if (Stance == EALSStance::Crouching) { Crouch(); } // Set default rotation values. TargetRotation = GetActorRotation(); LastVelocityRotation = TargetRotation; LastMovementInputRotation = TargetRotation; if (GetLocalRole() == ROLE_SimulatedProxy) { MainAnimInstance->SetRootMotionMode(ERootMotionMode::IgnoreRootMotion); } } void AALSBaseCharacter::PreInitializeComponents() { Super::PreInitializeComponents(); MainAnimInstance = Cast<UALSCharacterAnimInstance>(GetMesh()->GetAnimInstance()); if (!MainAnimInstance) { // Animation instance should be assigned if we're not in editor preview checkf(GetWorld()->WorldType == EWorldType::EditorPreview, TEXT("%s doesn't have a valid animation instance assigned. That's not allowed"), *GetName()); } } void AALSBaseCharacter::SetAimYawRate(float NewAimYawRate) { AimYawRate = NewAimYawRate; MainAnimInstance->GetCharacterInformationMutable().AimYawRate = AimYawRate; } void AALSBaseCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Set required values SetEssentialValues(DeltaTime); if (MovementState == EALSMovementState::Grounded) { UpdateCharacterMovement(); UpdateGroundedRotation(DeltaTime); } else if (MovementState == EALSMovementState::InAir) { UpdateInAirRotation(DeltaTime); // Perform a mantle check if falling while movement input is pressed. if (bHasMovementInput) { MantleCheck(FallingTraceSettings); } } else if (MovementState == EALSMovementState::Ragdoll) { RagdollUpdate(DeltaTime); } // Cache values PreviousVelocity = GetVelocity(); PreviousAimYaw = AimingRotation.Yaw; DrawDebugSpheres(); } void AALSBaseCharacter::RagdollStart() { /** When Networked, disables replicate movement reset TargetRagdollLocation and ServerRagdollPull variable and if the host is a dedicated server, change character mesh optimisation option to avoid z-location bug*/ MyCharacterMovementComponent->bIgnoreClientMovementErrorChecksAndCorrection = 1; if (UKismetSystemLibrary::IsDedicatedServer(GetWorld())) { DefVisBasedTickOp = GetMesh()->VisibilityBasedAnimTickOption; GetMesh()->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones; } TargetRagdollLocation = GetMesh()->GetSocketLocation(FName(TEXT("Pelvis"))); ServerRagdollPull = 0; // Step 1: Clear the Character Movement Mode and set the Movement State to Ragdoll GetCharacterMovement()->SetMovementMode(MOVE_None); SetMovementState(EALSMovementState::Ragdoll); // Step 2: Disable capsule collision and enable mesh physics simulation starting from the pelvis. GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision); GetMesh()->SetCollisionObjectType(ECC_PhysicsBody); GetMesh()->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); GetMesh()->SetAllBodiesBelowSimulatePhysics(FName(TEXT("Pelvis")), true, true); // Step 3: Stop any active montages. MainAnimInstance->Montage_Stop(0.2f); SetReplicateMovement(false); } void AALSBaseCharacter::RagdollEnd() { /** Re-enable Replicate Movement and if the host is a dedicated server set mesh visibility based anim tick option back to default*/ if (UKismetSystemLibrary::IsDedicatedServer(GetWorld())) { GetMesh()->VisibilityBasedAnimTickOption = DefVisBasedTickOp; } MyCharacterMovementComponent->bIgnoreClientMovementErrorChecksAndCorrection = 0; SetReplicateMovement(true); if (!MainAnimInstance) { return; } // Step 1: Save a snapshot of the current Ragdoll Pose for use in AnimGraph to blend out of the ragdoll MainAnimInstance->SavePoseSnapshot(FName(TEXT("RagdollPose"))); // Step 2: If the ragdoll is on the ground, set the movement mode to walking and play a Get Up animation. // If not, set the movement mode to falling and update the character movement velocity to match the last ragdoll velocity. if (bRagdollOnGround) { GetCharacterMovement()->SetMovementMode(MOVE_Walking); MainAnimInstance->Montage_Play(GetGetUpAnimation(bRagdollFaceUp), 1.0f, EMontagePlayReturnType::MontageLength, 0.0f, true); } else { GetCharacterMovement()->SetMovementMode(MOVE_Falling); GetCharacterMovement()->Velocity = LastRagdollVelocity; } // Step 3: Re-Enable capsule collision, and disable physics simulation on the mesh. GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); GetMesh()->SetCollisionObjectType(ECC_Pawn); GetMesh()->SetCollisionEnabled(ECollisionEnabled::QueryOnly); GetMesh()->SetAllBodiesSimulatePhysics(false); } void AALSBaseCharacter::Server_SetMeshLocationDuringRagdoll_Implementation(FVector MeshLocation) { TargetRagdollLocation = MeshLocation; } void AALSBaseCharacter::SetMovementState(const EALSMovementState NewState) { if (MovementState != NewState) { PrevMovementState = MovementState; MovementState = NewState; FALSAnimCharacterInformation& AnimData = MainAnimInstance->GetCharacterInformationMutable(); AnimData.PrevMovementState = PrevMovementState; MainAnimInstance->MovementState = MovementState; OnMovementStateChanged(PrevMovementState); } } void AALSBaseCharacter::SetMovementAction(const EALSMovementAction NewAction) { if (MovementAction != NewAction) { const EALSMovementAction Prev = MovementAction; MovementAction = NewAction; MainAnimInstance->MovementAction = MovementAction; OnMovementActionChanged(Prev); } } void AALSBaseCharacter::SetStance(const EALSStance NewStance) { if (Stance != NewStance) { const EALSStance Prev = Stance; Stance = NewStance; MainAnimInstance->Stance = Stance; OnStanceChanged(Prev); } } void AALSBaseCharacter::SetGait(const EALSGait NewGait) { if (Gait != NewGait) { Gait = NewGait; MainAnimInstance->Gait = Gait; } } void AALSBaseCharacter::SetDesiredStance(EALSStance NewStance) { DesiredStance = NewStance; if (GetLocalRole() == ROLE_AutonomousProxy) { Server_SetDesiredStance(NewStance); } } void AALSBaseCharacter::Server_SetDesiredStance_Implementation(EALSStance NewStance) { SetDesiredStance(NewStance); } void AALSBaseCharacter::SetDesiredGait(const EALSGait NewGait) { DesiredGait = NewGait; if (GetLocalRole() == ROLE_AutonomousProxy) { Server_SetDesiredGait(NewGait); } } void AALSBaseCharacter::Server_SetDesiredGait_Implementation(EALSGait NewGait) { SetDesiredGait(NewGait); } void AALSBaseCharacter::SetDesiredRotationMode(EALSRotationMode NewRotMode) { DesiredRotationMode = NewRotMode; if (GetLocalRole() == ROLE_AutonomousProxy) { Server_SetDesiredRotationMode(NewRotMode); } } void AALSBaseCharacter::Server_SetDesiredRotationMode_Implementation(EALSRotationMode NewRotMode) { SetDesiredRotationMode(NewRotMode); } void AALSBaseCharacter::SetRotationMode(const EALSRotationMode NewRotationMode) { if (RotationMode != NewRotationMode) { const EALSRotationMode Prev = RotationMode; RotationMode = NewRotationMode; OnRotationModeChanged(Prev); if (GetLocalRole() == ROLE_AutonomousProxy) { Server_SetRotationMode(NewRotationMode); } } } void AALSBaseCharacter::Server_SetRotationMode_Implementation(EALSRotationMode NewRotationMode) { SetRotationMode(NewRotationMode); } void AALSBaseCharacter::SetViewMode(const EALSViewMode NewViewMode) { if (ViewMode != NewViewMode) { const EALSViewMode Prev = ViewMode; ViewMode = NewViewMode; OnViewModeChanged(Prev); if (GetLocalRole() == ROLE_AutonomousProxy) { Server_SetViewMode(NewViewMode); } } } void AALSBaseCharacter::Server_SetViewMode_Implementation(EALSViewMode NewViewMode) { SetViewMode(NewViewMode); } void AALSBaseCharacter::SetOverlayState(const EALSOverlayState NewState) { if (OverlayState != NewState) { const EALSOverlayState Prev = OverlayState; OverlayState = NewState; OnOverlayStateChanged(Prev); if (GetLocalRole() == ROLE_AutonomousProxy) { Server_SetOverlayState(NewState); } } } void AALSBaseCharacter::Server_SetOverlayState_Implementation(EALSOverlayState NewState) { SetOverlayState(NewState); } void AALSBaseCharacter::EventOnLanded() { const float VelZ = FMath::Abs(GetCharacterMovement()->Velocity.Z); if (bRagdollOnLand && VelZ > RagdollOnLandVelocity) { ReplicatedRagdollStart(); } else if (bBreakfallOnLand && bHasMovementInput && VelZ >= BreakfallOnLandVelocity) { OnBreakfall(); } else { GetCharacterMovement()->BrakingFrictionFactor = bHasMovementInput ? 0.5f : 3.0f; // After 0.5 secs, reset braking friction factor to zero GetWorldTimerManager().SetTimer(OnLandedFrictionResetTimer, this, &AALSBaseCharacter::OnLandFrictionReset, 0.5f, false); } } void AALSBaseCharacter::Multicast_OnLanded_Implementation() { if (!IsLocallyControlled()) { EventOnLanded(); } } void AALSBaseCharacter::EventOnJumped() { // Set the new In Air Rotation to the velocity rotation if speed is greater than 100. InAirRotation = Speed > 100.0f ? LastVelocityRotation : GetActorRotation(); MainAnimInstance->OnJumped(); } void AALSBaseCharacter::Server_MantleStart_Implementation(float MantleHeight, const FALSComponentAndTransform& MantleLedgeWS, EALSMantleType MantleType) { Multicast_MantleStart(MantleHeight, MantleLedgeWS, MantleType); } void AALSBaseCharacter::Multicast_MantleStart_Implementation(float MantleHeight, const FALSComponentAndTransform& MantleLedgeWS, EALSMantleType MantleType) { if (!IsLocallyControlled()) { MantleStart(MantleHeight, MantleLedgeWS, MantleType); } } void AALSBaseCharacter::Server_PlayMontage_Implementation(UAnimMontage* montage, float track) { Multicast_PlayMontage(montage, track); } void AALSBaseCharacter::Multicast_PlayMontage_Implementation(UAnimMontage* montage, float track) { if (!IsLocallyControlled()) { // Roll: Simply play a Root Motion Montage. MainAnimInstance->Montage_Play(montage, track); } } void AALSBaseCharacter::Multicast_OnJumped_Implementation() { if (!IsLocallyControlled()) { EventOnJumped(); } } void AALSBaseCharacter::Server_RagdollStart_Implementation() { Multicast_RagdollStart(); } void AALSBaseCharacter::Multicast_RagdollStart_Implementation() { RagdollStart(); } void AALSBaseCharacter::Server_RagdollEnd_Implementation(FVector CharacterLocation) { Multicast_RagdollEnd(CharacterLocation); } void AALSBaseCharacter::Multicast_RagdollEnd_Implementation(FVector CharacterLocation) { RagdollEnd(); } void AALSBaseCharacter::SetActorLocationAndTargetRotation(FVector NewLocation, FRotator NewRotation) { SetActorLocationAndRotation(NewLocation, NewRotation); TargetRotation = NewRotation; } bool AALSBaseCharacter::MantleCheckGrounded() { return MantleCheck(GroundedTraceSettings); } bool AALSBaseCharacter::MantleCheckFalling() { return MantleCheck(FallingTraceSettings); } void AALSBaseCharacter::SetMovementModel() { const FString ContextString = GetFullName(); FALSMovementStateSettings* OutRow = MovementModel.DataTable->FindRow<FALSMovementStateSettings>(MovementModel.RowName, ContextString); check(OutRow); MovementData = *OutRow; } void AALSBaseCharacter::SetHasMovementInput(bool bNewHasMovementInput) { bHasMovementInput = bNewHasMovementInput; MainAnimInstance->GetCharacterInformationMutable().bHasMovementInput = bHasMovementInput; } FALSMovementSettings AALSBaseCharacter::GetTargetMovementSettings() const { if (RotationMode == EALSRotationMode::VelocityDirection) { if (Stance == EALSStance::Standing) { return MovementData.VelocityDirection.Standing; } if (Stance == EALSStance::Crouching) { return MovementData.VelocityDirection.Crouching; } } else if (RotationMode == EALSRotationMode::LookingDirection) { if (Stance == EALSStance::Standing) { return MovementData.LookingDirection.Standing; } if (Stance == EALSStance::Crouching) { return MovementData.LookingDirection.Crouching; } } else if (RotationMode == EALSRotationMode::Aiming) { if (Stance == EALSStance::Standing) { return MovementData.Aiming.Standing; } if (Stance == EALSStance::Crouching) { return MovementData.Aiming.Crouching; } } // Default to velocity dir standing return MovementData.VelocityDirection.Standing; } bool AALSBaseCharacter::CanSprint() const { // Determine if the character is currently able to sprint based on the Rotation mode and current acceleration // (input) rotation. If the character is in the Looking Rotation mode, only allow sprinting if there is full // movement input and it is faced forward relative to the camera + or - 50 degrees. if (!bHasMovementInput || RotationMode == EALSRotationMode::Aiming) { return false; } const bool bValidInputAmount = MovementInputAmount > 0.9f; if (RotationMode == EALSRotationMode::VelocityDirection) { return bValidInputAmount; } if (RotationMode == EALSRotationMode::LookingDirection) { const FRotator AccRot = ReplicatedCurrentAcceleration.ToOrientationRotator(); FRotator Delta = AccRot - AimingRotation; Delta.Normalize(); return bValidInputAmount && FMath::Abs(Delta.Yaw) < 50.0f; } return false; } void AALSBaseCharacter::SetIsMoving(bool bNewIsMoving) { bIsMoving = bNewIsMoving; MainAnimInstance->GetCharacterInformationMutable().bIsMoving = bIsMoving; } FVector AALSBaseCharacter::GetMovementInput() const { return ReplicatedCurrentAcceleration; } void AALSBaseCharacter::SetMovementInputAmount(float NewMovementInputAmount) { MovementInputAmount = NewMovementInputAmount; MainAnimInstance->GetCharacterInformationMutable().MovementInputAmount = MovementInputAmount; } void AALSBaseCharacter::SetSpeed(float NewSpeed) { Speed = NewSpeed; MainAnimInstance->GetCharacterInformationMutable().Speed = Speed; } float AALSBaseCharacter::GetAnimCurveValue(FName CurveName) const { if (MainAnimInstance) { return MainAnimInstance->GetCurveValue(CurveName); } return 0.0f; } ECollisionChannel AALSBaseCharacter::GetThirdPersonTraceParams(FVector& TraceOrigin, float& TraceRadius) { TraceOrigin = GetActorLocation(); TraceRadius = 10.0f; return ECC_Visibility; } FTransform AALSBaseCharacter::GetThirdPersonPivotTarget() { return GetActorTransform(); } FVector AALSBaseCharacter::GetFirstPersonCameraTarget() { return GetMesh()->GetSocketLocation(FName(TEXT("FP_Camera"))); } void AALSBaseCharacter::GetCameraParameters(float& TPFOVOut, float& FPFOVOut, bool& bRightShoulderOut) const { TPFOVOut = ThirdPersonFOV; FPFOVOut = FirstPersonFOV; bRightShoulderOut = bRightShoulder; } void AALSBaseCharacter::SetAcceleration(const FVector& NewAcceleration) { Acceleration = (NewAcceleration != FVector::ZeroVector || IsLocallyControlled()) ? NewAcceleration : Acceleration / 2; MainAnimInstance->GetCharacterInformationMutable().Acceleration = Acceleration; } void AALSBaseCharacter::RagdollUpdate(float DeltaTime) { // Set the Last Ragdoll Velocity. const FVector NewRagdollVel = GetMesh()->GetPhysicsLinearVelocity(FName(TEXT("root"))); LastRagdollVelocity = (NewRagdollVel != FVector::ZeroVector || IsLocallyControlled()) ? NewRagdollVel : LastRagdollVelocity / 2; // Use the Ragdoll Velocity to scale the ragdoll's joint strength for physical animation. const float SpringValue = FMath::GetMappedRangeValueClamped({0.0f, 1000.0f}, {0.0f, 25000.0f}, LastRagdollVelocity.Size()); GetMesh()->SetAllMotorsAngularDriveParams(SpringValue, 0.0f, 0.0f, false); // Disable Gravity if falling faster than -4000 to prevent continual acceleration. // This also prevents the ragdoll from going through the floor. const bool bEnableGrav = LastRagdollVelocity.Z > -4000.0f; GetMesh()->SetEnableGravity(bEnableGrav); // Update the Actor location to follow the ragdoll. SetActorLocationDuringRagdoll(DeltaTime); } void AALSBaseCharacter::SetActorLocationDuringRagdoll(float DeltaTime) { if (IsLocallyControlled()) { // Set the pelvis as the target location. TargetRagdollLocation = GetMesh()->GetSocketLocation(FName(TEXT("Pelvis"))); if (!HasAuthority()) { Server_SetMeshLocationDuringRagdoll(TargetRagdollLocation); } } // Determine wether the ragdoll is facing up or down and set the target rotation accordingly. const FRotator PelvisRot = GetMesh()->GetSocketRotation(FName(TEXT("Pelvis"))); bRagdollFaceUp = PelvisRot.Roll < 0.0f; const FRotator TargetRagdollRotation(0.0f, bRagdollFaceUp ? PelvisRot.Yaw - 180.0f : PelvisRot.Yaw, 0.0f); // Trace downward from the target location to offset the target location, // preventing the lower half of the capsule from going through the floor when the ragdoll is laying on the ground. const FVector TraceVect(TargetRagdollLocation.X, TargetRagdollLocation.Y, TargetRagdollLocation.Z - GetCapsuleComponent()->GetScaledCapsuleHalfHeight()); FCollisionQueryParams Params; Params.AddIgnoredActor(this); FHitResult HitResult; GetWorld()->LineTraceSingleByChannel(HitResult, TargetRagdollLocation, TraceVect, ECC_Visibility, Params); bRagdollOnGround = HitResult.IsValidBlockingHit(); FVector NewRagdollLoc = TargetRagdollLocation; if (bRagdollOnGround) { const float ImpactDistZ = FMath::Abs(HitResult.ImpactPoint.Z - HitResult.TraceStart.Z); NewRagdollLoc.Z += GetCapsuleComponent()->GetScaledCapsuleHalfHeight() - ImpactDistZ + 2.0f; } if (!IsLocallyControlled()) { ServerRagdollPull = FMath::FInterpTo(ServerRagdollPull, 750, DeltaTime, 0.6); float RagdollSpeed = FVector(LastRagdollVelocity.X, LastRagdollVelocity.Y, 0).Size(); FName RagdollSocketPullName = RagdollSpeed > 300 ? FName(TEXT("spine_03")) : FName(TEXT("pelvis")); GetMesh()->AddForce( (TargetRagdollLocation - GetMesh()->GetSocketLocation(RagdollSocketPullName)) * ServerRagdollPull, RagdollSocketPullName, true); } SetActorLocationAndTargetRotation(bRagdollOnGround ? NewRagdollLoc : TargetRagdollLocation, TargetRagdollRotation); } void AALSBaseCharacter::OnMovementModeChanged(EMovementMode PrevMovementMode, uint8 PreviousCustomMode) { Super::OnMovementModeChanged(PrevMovementMode, PreviousCustomMode); // Use the Character Movement Mode changes to set the Movement States to the right values. This allows you to have // a custom set of movement states but still use the functionality of the default character movement component. if (GetCharacterMovement()->MovementMode == MOVE_Walking || GetCharacterMovement()->MovementMode == MOVE_NavWalking) { SetMovementState(EALSMovementState::Grounded); } else if (GetCharacterMovement()->MovementMode == MOVE_Falling) { SetMovementState(EALSMovementState::InAir); } } void AALSBaseCharacter::OnMovementStateChanged(const EALSMovementState PreviousState) { if (MovementState == EALSMovementState::InAir) { if (MovementAction == EALSMovementAction::None) { // If the character enters the air, set the In Air Rotation and uncrouch if crouched. InAirRotation = GetActorRotation(); if (Stance == EALSStance::Crouching) { UnCrouch(); } } else if (MovementAction == EALSMovementAction::Rolling) { // If the character is currently rolling, enable the ragdoll. ReplicatedRagdollStart(); } } else if (MovementState == EALSMovementState::Ragdoll && PreviousState == EALSMovementState::Mantling) { // Stop the Mantle Timeline if transitioning to the ragdoll state while mantling. MantleTimeline->Stop(); } } void AALSBaseCharacter::OnMovementActionChanged(const EALSMovementAction PreviousAction) { // Make the character crouch if performing a roll. if (MovementAction == EALSMovementAction::Rolling) { Crouch(); } if (PreviousAction == EALSMovementAction::Rolling) { if (DesiredStance == EALSStance::Standing) { UnCrouch(); } else if (DesiredStance == EALSStance::Crouching) { Crouch(); } } } void AALSBaseCharacter::OnStanceChanged(const EALSStance PreviousStance) { } void AALSBaseCharacter::OnRotationModeChanged(EALSRotationMode PreviousRotationMode) { MainAnimInstance->RotationMode = RotationMode; if (RotationMode == EALSRotationMode::VelocityDirection && ViewMode == EALSViewMode::FirstPerson) { // If the new rotation mode is Velocity Direction and the character is in First Person, // set the viewmode to Third Person. SetViewMode(EALSViewMode::ThirdPerson); } } void AALSBaseCharacter::OnGaitChanged(const EALSGait PreviousGait) { } void AALSBaseCharacter::OnViewModeChanged(const EALSViewMode PreviousViewMode) { MainAnimInstance->GetCharacterInformationMutable().ViewMode = ViewMode; if (ViewMode == EALSViewMode::ThirdPerson) { if (RotationMode == EALSRotationMode::VelocityDirection || RotationMode == EALSRotationMode::LookingDirection) { // If Third Person, set the rotation mode back to the desired mode. SetRotationMode(DesiredRotationMode); } } else if (ViewMode == EALSViewMode::FirstPerson && RotationMode == EALSRotationMode::VelocityDirection) { // If First Person, set the rotation mode to looking direction if currently in the velocity direction mode. SetRotationMode(EALSRotationMode::LookingDirection); } } void AALSBaseCharacter::OnOverlayStateChanged(const EALSOverlayState PreviousState) { MainAnimInstance->OverlayState = OverlayState; } void AALSBaseCharacter::OnStartCrouch(float HalfHeightAdjust, float ScaledHalfHeightAdjust) { Super::OnStartCrouch(HalfHeightAdjust, ScaledHalfHeightAdjust); SetStance(EALSStance::Crouching); } void AALSBaseCharacter::OnEndCrouch(float HalfHeightAdjust, float ScaledHalfHeightAdjust) { Super::OnEndCrouch(HalfHeightAdjust, ScaledHalfHeightAdjust); SetStance(EALSStance::Standing); } void AALSBaseCharacter::OnJumped_Implementation() { Super::OnJumped_Implementation(); if (IsLocallyControlled()) { EventOnJumped(); } if (HasAuthority()) { Multicast_OnJumped(); } } void AALSBaseCharacter::Landed(const FHitResult& Hit) { Super::Landed(Hit); if (IsLocallyControlled()) { EventOnLanded(); } if (HasAuthority()) { Multicast_OnLanded(); } } void AALSBaseCharacter::OnLandFrictionReset() { // Reset the braking friction GetCharacterMovement()->BrakingFrictionFactor = 0.0f; } void AALSBaseCharacter::SetEssentialValues(float DeltaTime) { if (GetLocalRole() != ROLE_SimulatedProxy) { ReplicatedCurrentAcceleration = GetCharacterMovement()->GetCurrentAcceleration(); ReplicatedControlRotation = GetControlRotation(); EasedMaxAcceleration = GetCharacterMovement()->GetMaxAcceleration(); } else { EasedMaxAcceleration = GetCharacterMovement()->GetMaxAcceleration() != 0 ? GetCharacterMovement()->GetMaxAcceleration() : EasedMaxAcceleration / 2; } // Interp AimingRotation to current control rotation for smooth character rotation movement. Decrease InterpSpeed // for slower but smoother movement. AimingRotation = FMath::RInterpTo(AimingRotation, ReplicatedControlRotation, DeltaTime, 30); // These values represent how the capsule is moving as well as how it wants to move, and therefore are essential // for any data driven animation system. They are also used throughout the system for various functions, // so I found it is easiest to manage them all in one place. const FVector CurrentVel = GetVelocity(); // Set the amount of Acceleration. SetAcceleration((CurrentVel - PreviousVelocity) / DeltaTime); // Determine if the character is moving by getting it's speed. The Speed equals the length of the horizontal (x y) // velocity, so it does not take vertical movement into account. If the character is moving, update the last // velocity rotation. This value is saved because it might be useful to know the last orientation of movement // even after the character has stopped. SetSpeed(CurrentVel.Size2D()); SetIsMoving(Speed > 1.0f); if (bIsMoving) { LastVelocityRotation = CurrentVel.ToOrientationRotator(); } // Determine if the character has movement input by getting its movement input amount. // The Movement Input Amount is equal to the current acceleration divided by the max acceleration so that // it has a range of 0-1, 1 being the maximum possible amount of input, and 0 being none. // If the character has movement input, update the Last Movement Input Rotation. SetMovementInputAmount(ReplicatedCurrentAcceleration.Size() / EasedMaxAcceleration); SetHasMovementInput(MovementInputAmount > 0.0f); if (bHasMovementInput) { LastMovementInputRotation = ReplicatedCurrentAcceleration.ToOrientationRotator(); } // Set the Aim Yaw rate by comparing the current and previous Aim Yaw value, divided by Delta Seconds. // This represents the speed the camera is rotating left to right. SetAimYawRate(FMath::Abs((AimingRotation.Yaw - PreviousAimYaw) / DeltaTime)); } void AALSBaseCharacter::UpdateCharacterMovement() { // Set the Allowed Gait const EALSGait AllowedGait = GetAllowedGait(); // Determine the Actual Gait. If it is different from the current Gait, Set the new Gait Event. const EALSGait ActualGait = GetActualGait(AllowedGait); if (ActualGait != Gait) { SetGait(ActualGait); } // Use the allowed gait to update the movement settings. if (bDisableCurvedMovement) { // Don't use curves for movement UpdateDynamicMovementSettingsNetworked(AllowedGait); } else { // Use curves for movement UpdateDynamicMovementSettingsStandalone(AllowedGait); } } void AALSBaseCharacter::UpdateDynamicMovementSettingsStandalone(EALSGait AllowedGait) { // Get the Current Movement Settings. CurrentMovementSettings = GetTargetMovementSettings(); const float NewMaxSpeed = CurrentMovementSettings.GetSpeedForGait(AllowedGait); // Update the Acceleration, Deceleration, and Ground Friction using the Movement Curve. // This allows for fine control over movement behavior at each speed (May not be suitable for replication). const float MappedSpeed = GetMappedSpeed(); const FVector CurveVec = CurrentMovementSettings.MovementCurve->GetVectorValue(MappedSpeed); // Update the Character Max Walk Speed to the configured speeds based on the currently Allowed Gait. MyCharacterMovementComponent->SetMaxWalkingSpeed(NewMaxSpeed); GetCharacterMovement()->MaxAcceleration = CurveVec.X; GetCharacterMovement()->BrakingDecelerationWalking = CurveVec.Y; GetCharacterMovement()->GroundFriction = CurveVec.Z; } void AALSBaseCharacter::UpdateDynamicMovementSettingsNetworked(EALSGait AllowedGait) { // Get the Current Movement Settings. CurrentMovementSettings = GetTargetMovementSettings(); const float NewMaxSpeed = CurrentMovementSettings.GetSpeedForGait(AllowedGait); // Update the Character Max Walk Speed to the configured speeds based on the currently Allowed Gait. if (IsLocallyControlled() || HasAuthority()) { if (GetCharacterMovement()->MaxWalkSpeed != NewMaxSpeed) { MyCharacterMovementComponent->SetMaxWalkingSpeed(NewMaxSpeed); } } else { GetCharacterMovement()->MaxWalkSpeed = NewMaxSpeed; } } void AALSBaseCharacter::UpdateGroundedRotation(float DeltaTime) { if (MovementAction == EALSMovementAction::None) { const bool bCanUpdateMovingRot = ((bIsMoving && bHasMovementInput) || Speed > 150.0f) && !HasAnyRootMotion(); if (bCanUpdateMovingRot) { const float GroundedRotationRate = CalculateGroundedRotationRate(); if (RotationMode == EALSRotationMode::VelocityDirection) { // Velocity Direction Rotation SmoothCharacterRotation({0.0f, LastVelocityRotation.Yaw, 0.0f}, 800.0f, GroundedRotationRate, DeltaTime); } else if (RotationMode == EALSRotationMode::LookingDirection) { // Looking Direction Rotation float YawValue; if (Gait == EALSGait::Sprinting) { YawValue = LastVelocityRotation.Yaw; } else { // Walking or Running.. const float YawOffsetCurveVal = MainAnimInstance->GetCurveValue(FName(TEXT("YawOffset"))); YawValue = AimingRotation.Yaw + YawOffsetCurveVal; } SmoothCharacterRotation({0.0f, YawValue, 0.0f}, 500.0f, GroundedRotationRate, DeltaTime); } else if (RotationMode == EALSRotationMode::Aiming) { const float ControlYaw = AimingRotation.Yaw; SmoothCharacterRotation({0.0f, ControlYaw, 0.0f}, 1000.0f, 20.0f, DeltaTime); } } else { // Not Moving if ((ViewMode == EALSViewMode::ThirdPerson && RotationMode == EALSRotationMode::Aiming) || ViewMode == EALSViewMode::FirstPerson) { LimitRotation(-100.0f, 100.0f, 20.0f, DeltaTime); } // Apply the RotationAmount curve from Turn In Place Animations. // The Rotation Amount curve defines how much rotation should be applied each frame, // and is calculated for animations that are animated at 30fps. const float RotAmountCurve = MainAnimInstance->GetCurveValue(FName(TEXT("RotationAmount"))); if (FMath::Abs(RotAmountCurve) > 0.001f) { if (GetLocalRole() == ROLE_AutonomousProxy) { TargetRotation.Yaw = UKismetMathLibrary::NormalizeAxis( TargetRotation.Yaw + (RotAmountCurve * (DeltaTime / (1.0f / 30.0f)))); SetActorRotation(TargetRotation); } else { AddActorWorldRotation({0, RotAmountCurve * (DeltaTime / (1.0f / 30.0f)), 0}); } TargetRotation = GetActorRotation(); } } } else if (MovementAction == EALSMovementAction::Rolling) { // Rolling Rotation if (bHasMovementInput) { SmoothCharacterRotation({0.0f, LastMovementInputRotation.Yaw, 0.0f}, 0.0f, 2.0f, DeltaTime); } } // Other actions are ignored... } void AALSBaseCharacter::UpdateInAirRotation(float DeltaTime) { if (RotationMode == EALSRotationMode::VelocityDirection || RotationMode == EALSRotationMode::LookingDirection) { // Velocity / Looking Direction Rotation SmoothCharacterRotation({0.0f, InAirRotation.Yaw, 0.0f}, 0.0f, 5.0f, DeltaTime); } else if (RotationMode == EALSRotationMode::Aiming) { // Aiming Rotation SmoothCharacterRotation({0.0f, AimingRotation.Yaw, 0.0f}, 0.0f, 15.0f, DeltaTime); InAirRotation = GetActorRotation(); } } void AALSBaseCharacter::MantleStart(float MantleHeight, const FALSComponentAndTransform& MantleLedgeWS, EALSMantleType MantleType) { // Step 1: Get the Mantle Asset and use it to set the new Mantle Params. const FALSMantleAsset& MantleAsset = GetMantleAsset(MantleType); MantleParams.AnimMontage = MantleAsset.AnimMontage; MantleParams.PositionCorrectionCurve = MantleAsset.PositionCorrectionCurve; MantleParams.StartingOffset = MantleAsset.StartingOffset; MantleParams.StartingPosition = FMath::GetMappedRangeValueClamped({MantleAsset.LowHeight, MantleAsset.HighHeight}, { MantleAsset.LowStartPosition, MantleAsset.HighStartPosition }, MantleHeight); MantleParams.PlayRate = FMath::GetMappedRangeValueClamped({MantleAsset.LowHeight, MantleAsset.HighHeight}, {MantleAsset.LowPlayRate, MantleAsset.HighPlayRate}, MantleHeight); // Step 2: Convert the world space target to the mantle component's local space for use in moving objects. MantleLedgeLS.Component = MantleLedgeWS.Component; MantleLedgeLS.Transform = MantleLedgeWS.Transform * MantleLedgeWS.Component->GetComponentToWorld().Inverse(); // Step 3: Set the Mantle Target and calculate the Starting Offset // (offset amount between the actor and target transform). MantleTarget = MantleLedgeWS.Transform; MantleActualStartOffset = UALSMathLibrary::TransfromSub(GetActorTransform(), MantleTarget); // Step 4: Calculate the Animated Start Offset from the Target Location. // This would be the location the actual animation starts at relative to the Target Transform. FVector RotatedVector = MantleTarget.GetRotation().Vector() * MantleParams.StartingOffset.Y; RotatedVector.Z = MantleParams.StartingOffset.Z; const FTransform StartOffset(MantleTarget.Rotator(), MantleTarget.GetLocation() - RotatedVector, FVector::OneVector); MantleAnimatedStartOffset = UALSMathLibrary::TransfromSub(StartOffset, MantleTarget); // Step 5: Clear the Character Movement Mode and set the Movement State to Mantling GetCharacterMovement()->SetMovementMode(MOVE_None); SetMovementState(EALSMovementState::Mantling); // Step 6: Configure the Mantle Timeline so that it is the same length as the // Lerp/Correction curve minus the starting position, and plays at the same speed as the animation. // Then start the timeline. float MinTime = 0.0f; float MaxTime = 0.0f; MantleParams.PositionCorrectionCurve->GetTimeRange(MinTime, MaxTime); MantleTimeline->SetTimelineLength(MaxTime - MantleParams.StartingPosition); MantleTimeline->SetPlayRate(MantleParams.PlayRate); MantleTimeline->PlayFromStart(); // Step 7: Play the Anim Montaget if valid. if (IsValid(MantleParams.AnimMontage)) { MainAnimInstance->Montage_Play(MantleParams.AnimMontage, MantleParams.PlayRate, EMontagePlayReturnType::MontageLength, MantleParams.StartingPosition, false); } } bool AALSBaseCharacter::MantleCheck(const FALSMantleTraceSettings& TraceSettings, EDrawDebugTrace::Type DebugType) { // Step 1: Trace forward to find a wall / object the character cannot walk on. const FVector& CapsuleBaseLocation = UALSMathLibrary::GetCapsuleBaseLocation(2.0f, GetCapsuleComponent()); FVector TraceStart = CapsuleBaseLocation + GetPlayerMovementInput() * -30.0f; TraceStart.Z += (TraceSettings.MaxLedgeHeight + TraceSettings.MinLedgeHeight) / 2.0f; const FVector TraceEnd = TraceStart + (GetPlayerMovementInput() * TraceSettings.ReachDistance); const float HalfHeight = 1.0f + ((TraceSettings.MaxLedgeHeight - TraceSettings.MinLedgeHeight) / 2.0f); UWorld* World = GetWorld(); check(World); FCollisionQueryParams Params; Params.AddIgnoredActor(this); FHitResult HitResult; // ECC_GameTraceChannel2 -> Climbable World->SweepSingleByChannel(HitResult, TraceStart, TraceEnd, FQuat::Identity, ECC_GameTraceChannel2, FCollisionShape::MakeCapsule(TraceSettings.ForwardTraceRadius, HalfHeight), Params); if (!HitResult.IsValidBlockingHit() || GetCharacterMovement()->IsWalkable(HitResult)) { // Not a valid surface to mantle return false; } if (HitResult.GetComponent() != nullptr) { UPrimitiveComponent* PrimitiveComponent = HitResult.GetComponent(); if (PrimitiveComponent && PrimitiveComponent->GetComponentVelocity().Size() > AcceptableVelocityWhileMantling) { // The surface to mantle moves too fast return false; } } const FVector InitialTraceImpactPoint = HitResult.ImpactPoint; const FVector InitialTraceNormal = HitResult.ImpactNormal; // Step 2: Trace downward from the first trace's Impact Point and determine if the hit location is walkable. FVector DownwardTraceEnd = InitialTraceImpactPoint; DownwardTraceEnd.Z = CapsuleBaseLocation.Z; DownwardTraceEnd += InitialTraceNormal * -15.0f; FVector DownwardTraceStart = DownwardTraceEnd; DownwardTraceStart.Z += TraceSettings.MaxLedgeHeight + TraceSettings.DownwardTraceRadius + 1.0f; World->SweepSingleByChannel(HitResult, DownwardTraceStart, DownwardTraceEnd, FQuat::Identity, ECC_GameTraceChannel2, FCollisionShape::MakeSphere(TraceSettings.DownwardTraceRadius), Params); if (!GetCharacterMovement()->IsWalkable(HitResult)) { // Not a valid surface to mantle return false; } const FVector DownTraceLocation(HitResult.Location.X, HitResult.Location.Y, HitResult.ImpactPoint.Z); UPrimitiveComponent* HitComponent = HitResult.GetComponent(); // Step 3: Check if the capsule has room to stand at the downward trace's location. // If so, set that location as the Target Transform and calculate the mantle height. const FVector& CapsuleLocationFBase = UALSMathLibrary::GetCapsuleLocationFromBase( DownTraceLocation, 2.0f, GetCapsuleComponent()); const bool bCapsuleHasRoom = UALSMathLibrary::CapsuleHasRoomCheck(GetCapsuleComponent(), CapsuleLocationFBase, 0.0f, 0.0f); if (!bCapsuleHasRoom) { // Capsule doesn't have enough room to mantle return false; } const FTransform TargetTransform( (InitialTraceNormal * FVector(-1.0f, -1.0f, 0.0f)).ToOrientationRotator(), CapsuleLocationFBase, FVector::OneVector); const float MantleHeight = (CapsuleLocationFBase - GetActorLocation()).Z; // Step 4: Determine the Mantle Type by checking the movement mode and Mantle Height. EALSMantleType MantleType; if (MovementState == EALSMovementState::InAir) { MantleType = EALSMantleType::FallingCatch; } else { MantleType = MantleHeight > 125.0f ? EALSMantleType::HighMantle : EALSMantleType::LowMantle; } // Step 5: If everything checks out, start the Mantle FALSComponentAndTransform MantleWS; MantleWS.Component = HitComponent; MantleWS.Transform = TargetTransform; MantleStart(MantleHeight, MantleWS, MantleType); Server_MantleStart(MantleHeight, MantleWS, MantleType); return true; } // This function is called by "MantleTimeline" using BindUFunction in the AALSBaseCharacter::BeginPlay during the default settings initalization. void AALSBaseCharacter::MantleUpdate(float BlendIn) { // Step 1: Continually update the mantle target from the stored local transform to follow along with moving objects MantleTarget = UALSMathLibrary::MantleComponentLocalToWorld(MantleLedgeLS); // Step 2: Update the Position and Correction Alphas using the Position/Correction curve set for each Mantle. const FVector CurveVec = MantleParams.PositionCorrectionCurve ->GetVectorValue( MantleParams.StartingPosition + MantleTimeline->GetPlaybackPosition()); const float PositionAlpha = CurveVec.X; const float XYCorrectionAlpha = CurveVec.Y; const float ZCorrectionAlpha = CurveVec.Z; // Step 3: Lerp multiple transforms together for independent control over the horizontal // and vertical blend to the animated start position, as well as the target position. // Blend into the animated horizontal and rotation offset using the Y value of the Position/Correction Curve. const FTransform TargetHzTransform(MantleAnimatedStartOffset.GetRotation(), { MantleAnimatedStartOffset.GetLocation().X, MantleAnimatedStartOffset.GetLocation().Y, MantleActualStartOffset.GetLocation().Z }, FVector::OneVector); const FTransform& HzLerpResult = UKismetMathLibrary::TLerp(MantleActualStartOffset, TargetHzTransform, XYCorrectionAlpha); // Blend into the animated vertical offset using the Z value of the Position/Correction Curve. const FTransform TargetVtTransform(MantleActualStartOffset.GetRotation(), { MantleActualStartOffset.GetLocation().X, MantleActualStartOffset.GetLocation().Y, MantleAnimatedStartOffset.GetLocation().Z }, FVector::OneVector); const FTransform& VtLerpResult = UKismetMathLibrary::TLerp(MantleActualStartOffset, TargetVtTransform, ZCorrectionAlpha); const FTransform ResultTransform(HzLerpResult.GetRotation(), { HzLerpResult.GetLocation().X, HzLerpResult.GetLocation().Y, VtLerpResult.GetLocation().Z }, FVector::OneVector); // Blend from the currently blending transforms into the final mantle target using the X // value of the Position/Correction Curve. const FTransform& ResultLerp = UKismetMathLibrary::TLerp( UALSMathLibrary::TransfromAdd(MantleTarget, ResultTransform), MantleTarget, PositionAlpha); // Initial Blend In (controlled in the timeline curve) to allow the actor to blend into the Position/Correction // curve at the midoint. This prevents pops when mantling an object lower than the animated mantle. const FTransform& LerpedTarget = UKismetMathLibrary::TLerp(UALSMathLibrary::TransfromAdd(MantleTarget, MantleActualStartOffset), ResultLerp, BlendIn); // Step 4: Set the actors location and rotation to the Lerped Target. SetActorLocationAndTargetRotation(LerpedTarget.GetLocation(), LerpedTarget.GetRotation().Rotator()); } void AALSBaseCharacter::MantleEnd() { // Set the Character Movement Mode to Walking GetCharacterMovement()->SetMovementMode(MOVE_Walking); } float AALSBaseCharacter::GetMappedSpeed() const { // Map the character's current speed to the configured movement speeds with a range of 0-3, // with 0 = stopped, 1 = the Walk Speed, 2 = the Run Speed, and 3 = the Sprint Speed. // This allows us to vary the movement speeds but still use the mapped range in calculations for consistent results const float LocWalkSpeed = CurrentMovementSettings.WalkSpeed; const float LocRunSpeed = CurrentMovementSettings.RunSpeed; const float LocSprintSpeed = CurrentMovementSettings.SprintSpeed; if (Speed > LocRunSpeed) { return FMath::GetMappedRangeValueClamped({LocRunSpeed, LocSprintSpeed}, {2.0f, 3.0f}, Speed); } if (Speed > LocWalkSpeed) { return FMath::GetMappedRangeValueClamped({LocWalkSpeed, LocRunSpeed}, {1.0f, 2.0f}, Speed); } return FMath::GetMappedRangeValueClamped({0.0f, LocWalkSpeed}, {0.0f, 1.0f}, Speed); } EALSGait AALSBaseCharacter::GetAllowedGait() const { // Calculate the Allowed Gait. This represents the maximum Gait the character is currently allowed to be in, // and can be determined by the desired gait, the rotation mode, the stance, etc. For example, // if you wanted to force the character into a walking state while indoors, this could be done here. if (Stance == EALSStance::Standing) { if (RotationMode != EALSRotationMode::Aiming) { if (DesiredGait == EALSGait::Sprinting) { return CanSprint() ? EALSGait::Sprinting : EALSGait::Running; } return DesiredGait; } } // Crouching stance & Aiming rot mode has same behaviour if (DesiredGait == EALSGait::Sprinting) { return EALSGait::Running; } return DesiredGait; } EALSGait AALSBaseCharacter::GetActualGait(EALSGait AllowedGait) const { // Get the Actual Gait. This is calculated by the actual movement of the character, and so it can be different // from the desired gait or allowed gait. For instance, if the Allowed Gait becomes walking, // the Actual gait will still be running untill the character decelerates to the walking speed. const float LocWalkSpeed = CurrentMovementSettings.WalkSpeed; const float LocRunSpeed = CurrentMovementSettings.RunSpeed; if (Speed > LocRunSpeed + 10.0f) { if (AllowedGait == EALSGait::Sprinting) { return EALSGait::Sprinting; } return EALSGait::Running; } if (Speed >= LocWalkSpeed + 10.0f) { return EALSGait::Running; } return EALSGait::Walking; } void AALSBaseCharacter::SmoothCharacterRotation(FRotator Target, float TargetInterpSpeed, float ActorInterpSpeed, float DeltaTime) { // Interpolate the Target Rotation for extra smooth rotation behavior TargetRotation = FMath::RInterpConstantTo(TargetRotation, Target, DeltaTime, TargetInterpSpeed); SetActorRotation( FMath::RInterpTo(GetActorRotation(), TargetRotation, DeltaTime, ActorInterpSpeed)); } float AALSBaseCharacter::CalculateGroundedRotationRate() const { // Calculate the rotation rate by using the current Rotation Rate Curve in the Movement Settings. // Using the curve in conjunction with the mapped speed gives you a high level of control over the rotation // rates for each speed. Increase the speed if the camera is rotating quickly for more responsive rotation. const float MappedSpeedVal = GetMappedSpeed(); const float CurveVal = CurrentMovementSettings.RotationRateCurve->GetFloatValue(MappedSpeedVal); const float ClampedAimYawRate = FMath::GetMappedRangeValueClamped({0.0f, 300.0f}, {1.0f, 3.0f}, AimYawRate); return CurveVal * ClampedAimYawRate; } void AALSBaseCharacter::LimitRotation(float AimYawMin, float AimYawMax, float InterpSpeed, float DeltaTime) { // Prevent the character from rotating past a certain angle. FRotator Delta = AimingRotation - GetActorRotation(); Delta.Normalize(); const float RangeVal = Delta.Yaw; if (RangeVal < AimYawMin || RangeVal > AimYawMax) { const float ControlRotYaw = AimingRotation.Yaw; const float TargetYaw = ControlRotYaw + (RangeVal > 0.0f ? AimYawMin : AimYawMax); SmoothCharacterRotation({0.0f, TargetYaw, 0.0f}, 0.0f, InterpSpeed, DeltaTime); } } void AALSBaseCharacter::GetControlForwardRightVector(FVector& Forward, FVector& Right) const { const FRotator ControlRot(0.0f, AimingRotation.Yaw, 0.0f); Forward = GetInputAxisValue("MoveForward/Backwards") * UKismetMathLibrary::GetForwardVector(ControlRot); Right = GetInputAxisValue("MoveRight/Left") * UKismetMathLibrary::GetRightVector(ControlRot); } FVector AALSBaseCharacter::GetPlayerMovementInput() const { FVector Forward = FVector::ZeroVector; FVector Right = FVector::ZeroVector; GetControlForwardRightVector(Forward, Right); return (Forward + Right).GetSafeNormal(); } void AALSBaseCharacter::PlayerForwardMovementInput(float Value) { if (MovementState == EALSMovementState::Grounded || MovementState == EALSMovementState::InAir) { // Default camera relative movement behavior const float Scale = UALSMathLibrary::FixDiagonalGamepadValues(Value, GetInputAxisValue("MoveRight/Left")).Key; const FRotator DirRotator(0.0f, AimingRotation.Yaw, 0.0f); AddMovementInput(UKismetMathLibrary::GetForwardVector(DirRotator), Scale); } } void AALSBaseCharacter::PlayerRightMovementInput(float Value) { if (MovementState == EALSMovementState::Grounded || MovementState == EALSMovementState::InAir) { // Default camera relative movement behavior const float Scale = UALSMathLibrary::FixDiagonalGamepadValues(GetInputAxisValue("MoveForward/Backwards"), Value) .Value; const FRotator DirRotator(0.0f, AimingRotation.Yaw, 0.0f); AddMovementInput(UKismetMathLibrary::GetRightVector(DirRotator), Scale); } } void AALSBaseCharacter::PlayerCameraUpInput(float Value) { AddControllerPitchInput(LookUpDownRate * Value); } void AALSBaseCharacter::PlayerCameraRightInput(float Value) { AddControllerYawInput(LookLeftRightRate * Value); } void AALSBaseCharacter::JumpPressedAction() { // Jump Action: Press "Jump Action" to end the ragdoll if ragdolling, check for a mantle if grounded or in air, // stand up if crouching, or jump if standing. if (MovementAction == EALSMovementAction::None) { if (MovementState == EALSMovementState::Grounded) { if (bHasMovementInput) { if (MantleCheckGrounded()) { return; } } if (Stance == EALSStance::Standing) { Jump(); } else if (Stance == EALSStance::Crouching) { UnCrouch(); } } else if (MovementState == EALSMovementState::InAir) { MantleCheckFalling(); } else if (MovementState == EALSMovementState::Ragdoll) { ReplicatedRagdollEnd(); } } } void AALSBaseCharacter::JumpReleasedAction() { StopJumping(); } void AALSBaseCharacter::SprintPressedAction() { SetDesiredGait(EALSGait::Sprinting); } void AALSBaseCharacter::SprintReleasedAction() { SetDesiredGait(EALSGait::Running); } void AALSBaseCharacter::AimPressedAction() { // AimAction: Hold "AimAction" to enter the aiming mode, release to revert back the desired rotation mode. SetRotationMode(EALSRotationMode::Aiming); } void AALSBaseCharacter::AimReleasedAction() { if (ViewMode == EALSViewMode::ThirdPerson) { SetRotationMode(DesiredRotationMode); } else if (ViewMode == EALSViewMode::FirstPerson) { SetRotationMode(EALSRotationMode::LookingDirection); } } void AALSBaseCharacter::CameraPressedAction() { UWorld* World = GetWorld(); check(World); CameraActionPressedTime = World->GetTimeSeconds(); GetWorldTimerManager().SetTimer(OnCameraModeSwapTimer, this, &AALSBaseCharacter::OnSwitchCameraMode, ViewModeSwitchHoldTime, false); } void AALSBaseCharacter::CameraReleasedAction() { if (ViewMode == EALSViewMode::FirstPerson) { // Don't swap shoulders on first person mode return; } UWorld* World = GetWorld(); check(World); if (World->GetTimeSeconds() - CameraActionPressedTime < ViewModeSwitchHoldTime) { // Switch shoulders SetRightShoulder(!bRightShoulder); GetWorldTimerManager().ClearTimer(OnCameraModeSwapTimer); // Prevent mode change } } void AALSBaseCharacter::OnSwitchCameraMode() { // Switch camera mode if (ViewMode == EALSViewMode::FirstPerson) { SetViewMode(EALSViewMode::ThirdPerson); } else if (ViewMode == EALSViewMode::ThirdPerson) { SetViewMode(EALSViewMode::FirstPerson); } } void AALSBaseCharacter::StancePressedAction() { // Stance Action: Press "Stance Action" to toggle Standing / Crouching, double tap to Roll. if (MovementAction != EALSMovementAction::None) { return; } UWorld* World = GetWorld(); check(World); const float PrevStanceInputTime = LastStanceInputTime; LastStanceInputTime = World->GetTimeSeconds(); if (LastStanceInputTime - PrevStanceInputTime <= RollDoubleTapTimeout) { // Roll Replicated_PlayMontage(GetRollAnimation(), 1.15f); if (Stance == EALSStance::Standing) { SetDesiredStance(EALSStance::Crouching); } else if (Stance == EALSStance::Crouching) { SetDesiredStance(EALSStance::Standing); } return; } if (MovementState == EALSMovementState::Grounded) { if (Stance == EALSStance::Standing) { SetDesiredStance(EALSStance::Crouching); Crouch(); } else if (Stance == EALSStance::Crouching) { SetDesiredStance(EALSStance::Standing); UnCrouch(); } } // Notice: MovementState == EALSMovementState::InAir case is removed } void AALSBaseCharacter::WalkPressedAction() { if (DesiredGait == EALSGait::Walking) { SetDesiredGait(EALSGait::Running); } else if (DesiredGait == EALSGait::Running) { SetDesiredGait(EALSGait::Walking); } } void AALSBaseCharacter::RagdollPressedAction() { // Ragdoll Action: Press "Ragdoll Action" to toggle the ragdoll state on or off. if (GetMovementState() == EALSMovementState::Ragdoll) { ReplicatedRagdollEnd(); } else { ReplicatedRagdollStart(); } } void AALSBaseCharacter::VelocityDirectionPressedAction() { // Select Rotation Mode: Switch the desired (default) rotation mode to Velocity or Looking Direction. // This will be the mode the character reverts back to when un-aiming SetDesiredRotationMode(EALSRotationMode::VelocityDirection); SetRotationMode(EALSRotationMode::VelocityDirection); } void AALSBaseCharacter::LookingDirectionPressedAction() { SetDesiredRotationMode(EALSRotationMode::LookingDirection); SetRotationMode(EALSRotationMode::LookingDirection); } void AALSBaseCharacter::ReplicatedRagdollStart() { if (HasAuthority()) { Multicast_RagdollStart(); } else { Server_RagdollStart(); } } void AALSBaseCharacter::ReplicatedRagdollEnd() { if (HasAuthority()) { Multicast_RagdollEnd(GetActorLocation()); } else { Server_RagdollEnd(GetActorLocation()); } } void AALSBaseCharacter::OnRep_RotationMode(EALSRotationMode PrevRotMode) { OnRotationModeChanged(PrevRotMode); } void AALSBaseCharacter::OnRep_ViewMode(EALSViewMode PrevViewMode) { OnViewModeChanged(PrevViewMode); } void AALSBaseCharacter::OnRep_OverlayState(EALSOverlayState PrevOverlayState) { OnOverlayStateChanged(PrevOverlayState); }
33.211593
145
0.752969
[ "mesh", "object", "vector", "model", "transform" ]
582b0effd41caf82d4ba2f049f8757bcfa345b89
771
cpp
C++
src/base/auth/OneOfAuth.cpp
edwardstock/wsserver
4fb834252e95431f4fe14a2a120e76524a586d7c
[ "Apache-2.0" ]
1
2018-06-23T10:33:38.000Z
2018-06-23T10:33:38.000Z
src/base/auth/OneOfAuth.cpp
scatter-server/scatter
4fb834252e95431f4fe14a2a120e76524a586d7c
[ "Apache-2.0" ]
null
null
null
src/base/auth/OneOfAuth.cpp
scatter-server/scatter
4fb834252e95431f4fe14a2a120e76524a586d7c
[ "Apache-2.0" ]
1
2018-12-14T04:06:16.000Z
2018-12-14T04:06:16.000Z
/*! * wsserver. 2018 * * \author Eduard Maximovich <edward.vstock@gmail.com> * \link https://github.com/edwardstock */ #include "OneOfAuth.h" // OneOfAuth wss::OneOfAuth::OneOfAuth(std::vector<std::unique_ptr<wss::Auth>> &&data) : types(std::move(data)) { } std::string wss::OneOfAuth::getType() { return "oneOf"; } void wss::OneOfAuth::performAuth(wss::web::Request &request) const { for (auto &auth: types) { auth->performAuth(request); } } bool wss::OneOfAuth::validateAuth(const wss::web::Request &request) const { for (auto &auth: types) { if (auth->validateAuth(request)) { return true; } } return false; } std::string wss::OneOfAuth::getLocalValue() const { return Auth::getLocalValue(); }
23.363636
100
0.635538
[ "vector" ]
5837ff3359b36c38443fd78564e5fe292aa3aca2
62,261
cpp
C++
src/cc/passes/JITTableRuntimePass.cpp
Morpheus-compiler/bcc
8fe73498a0942b4fc42215b60ddda4203b045bd9
[ "Apache-2.0" ]
null
null
null
src/cc/passes/JITTableRuntimePass.cpp
Morpheus-compiler/bcc
8fe73498a0942b4fc42215b60ddda4203b045bd9
[ "Apache-2.0" ]
null
null
null
src/cc/passes/JITTableRuntimePass.cpp
Morpheus-compiler/bcc
8fe73498a0942b4fc42215b60ddda4203b045bd9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Morpheus Authors * * Author: Sebastiano Miano <mianosebastiano@gmail.com> * * 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 "JITTableRuntimePass.h" #include <map> #include <string> #include <unistd.h> #include <utility> #include <vector> #include <algorithm> #include <regex> #include <iostream> #include <map> #include <set> #include <iomanip> #include <sstream> #include <algorithm> #include <functional> #include <linux/bpf.h> #include <cc/api/BPFTable.h> #include <cc/libbpf/src/bpf.h> #include <llvm/Pass.h> #include <llvm/IR/Function.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/Module.h> #include <llvm/IR/ValueMap.h> #include <llvm/IR/DebugInfo.h> #include "llvm/IR/InstrTypes.h" #include "llvm/Support/raw_ostream.h" #include <llvm/Transforms/Utils/BasicBlockUtils.h> #include <llvm/Transforms/Utils/ValueMapper.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Value.h> #include <llvm/IR/Type.h> #include <llvm/IR/IRPrintingPasses.h> #include "nlohmann/json.hpp" #include "bpf_module.h" #include "table_storage.h" #include "jhash.h" #include "utils.h" #include "DynamicMapOptAnalysisPass.h" #include "BPFMapInstrumentationPass.h" #include "builder/irbuilderbpf.h" /***************************************** * Pass implementation *****************************************/ /* An arbitrary initial parameter */ #define JHASH_FUNC_NAME "jhash_" #ifndef JHASH_INITVAL #define JHASH_INITVAL 0xdeadbeef #endif #define JHASH_INITVAL_INT 3735928559 // We should put a limit on the size of entries that can be offloaded // into the eBPF code. Otherwise the stack grows and we risk our optimized // program to be rejected #define DYN_OPT_KEY_SIZE_LIMIT 1024 #define DYN_OPT_LEAF_SIZE_LIMIT 512 using namespace llvm; namespace ebpf { char JITTableRuntimePass::ID; JITTableRuntimePass::JITTableRuntimePass(std::string id, std::string func_name, ebpf::TableStorage *ts, ebpf::fake_fd_map_def &fake_fd_map, std::vector<ebpf::TableDesc *> &tables, std::map<int, TableDesc> &original_maps_to_guards, std::map<int, TableDesc> &original_maps_to_instrumented_maps, std::vector<std::string> &offloaded_entries_list) : FunctionPass(ID), bpf_module_id_(std::move(id)), func_name_(std::move(func_name)), ts_(ts), fake_fd_map_(fake_fd_map), tables_(tables), original_maps_to_guards_(original_maps_to_guards), original_maps_to_instrumented_maps_(original_maps_to_instrumented_maps), offloaded_entries_list_(offloaded_entries_list) {} JITTableRuntimePass::~JITTableRuntimePass() = default; // Called once for each module, before the calls on the basic blocks. // We could use doFinalization to clear RNG, but that's not needed. bool JITTableRuntimePass::doInitialization(Module &M) { // I want the same seed to better debugability. In the future it should be changed with time(NULL) srand(5678); // srand(time(NULL)); return false; } // Called for each basic block of the module bool JITTableRuntimePass::runOnFunction(Function &pfn) { auto &dynamic_opt_compiler = MorpheusCompiler::getInstance(); bool modified = false; if (pfn.getName() != func_name_) { // I will skip all the functions that I am not interested in return false; } spdlog::get("Morpheus")->trace("[JIT Pass] Processing function: {}", pfn.getName().str()); LLVMContext &ctx_ = pfn.getContext(); for (auto bb = pfn.begin(); bb != pfn.end(); bb++) { for (auto instruction = bb->begin(); instruction != bb->end(); instruction++) { bool is_map_in_map_lookup = false; int map_in_map_fd = -1; // The getBPFMapLookup call will return the pointer to the instruction containing the real // helper call, but only if the call is a bpf_map_lookup_elem. Otherwise the call // will return nullptr. // In addition, this function will check if the input instruction is a llvm.bpf.pseudo // call, and then it will go two instructions after to find the helper call. auto helperInstruction = dyn_opt::utils::getCompleteBPFMapLookupCallInst(*instruction); if (helperInstruction == nullptr) { continue; } auto bpfPseudoCallInst = dyn_opt::utils::findPseudoFromHelperInstr(*helperInstruction); if (bpfPseudoCallInst == nullptr) { // There is still a case that we have to consider here. // When the lookup is a reference to an map obtained from the ARRAY_OF_MAPS. // In this case, I read the debug information where I can find the ARRAY_OF_MAP table FD associated // and read the corresponding entries. map_in_map_fd = dyn_opt::utils::getMapInMapFDFromDebugInfo(*helperInstruction); if (map_in_map_fd > 0) { is_map_in_map_lookup = true; spdlog::get("Morpheus")->trace("[JIT Pass] This lookup is referring to a BPF_MAP_IN_MAP with fd: {}", map_in_map_fd); bpfPseudoCallInst = helperInstruction; } else { continue; } } // auto bpfPseudoCallInst = dyn_cast_or_null<CallInst>(&(*instruction)); // assert(bpfPseudoCallInst != nullptr && "Detected BPF call instruction is NULL"); ebpf::TableDesc *table = nullptr; std::vector<int> nested_map_fds; if (is_map_in_map_lookup && map_in_map_fd > 0) { std::tie(nested_map_fds, table) = dyn_opt::utils::getNestedMapInMapTable(ctx_, map_in_map_fd, bpf_module_id_, ts_, fake_fd_map_, tables_); if (dyn_opt::utils::nestedMapIsReadOnly(*helperInstruction)) { table->is_read_only = true; } else { table->is_read_only = false; } } else { auto *ci = dyn_opt::utils::getBPFPseudoTableFd(*bpfPseudoCallInst); table = getTableByFD(*ci); } if (table == nullptr) continue; //assert(table != nullptr && "Trying to get a table that does not exist!"); spdlog::get("Morpheus")->debug("[JIT Pass] Reading runtime values of the map: {} (fd: {}), type: {}", table->name, (int) table->fd, dyn_opt::utils::table_type_id_to_string_name(table->type)); // First of all I need to understand the type of map that it is using, // in order to apply different type of optimizations. if (table->type == BPF_MAP_TYPE_HASH || table->type == BPF_MAP_TYPE_LRU_HASH || table->type == BPF_MAP_TYPE_ARRAY || table->type == BPF_MAP_TYPE_LPM_TRIE || table->type == BPF_MAP_TYPE_ARRAY_OF_MAPS) { auto genericTable = ebpf::BPFTable(*table); spdlog::get("Morpheus")->debug("[JIT Pass] We are dealing with a {}", dyn_opt::utils::table_type_id_to_string_name(table->type)); spdlog::get("Morpheus")->trace("[JIT Pass] Key desc: {}", table->key_desc); spdlog::get("Morpheus")->trace("[JIT Pass] Leaf desc: {}", table->leaf_desc); if (table->leaf_size >= DYN_OPT_LEAF_SIZE_LIMIT || table->key_size >= DYN_OPT_KEY_SIZE_LIMIT) { continue; } if (table->name == "index64" || table->name == "ctl_array" || table->name == "dp_rules") continue; std::vector<std::pair<std::string, std::string>> values; // This should read all the entries, but for very large map it will take a lot of time // TODO: improve with batch reading! if (is_map_in_map_lookup && nested_map_fds.size() > 0) { dyn_opt::utils::readEntriesFromNestedTables(values, nested_map_fds, *table, dynamic_opt_compiler.getMaxOffloadedEntries()*50); if (values.size() == 0) { spdlog::get("Morpheus")->trace("[JIT Pass] Skip offloading if all values are null in the nested array of maps"); continue; } } else if (table->type == BPF_MAP_TYPE_ARRAY_OF_MAPS) { spdlog::get("Morpheus")->trace("[JIT Pass] Read entries from array of maps"); BPFArrayOfMapTable arrayOfMapTable(*table); std::vector<int> array_of_map_values = arrayOfMapTable.get_table_offline(); for (uint i = 0; i < array_of_map_values.size(); i++) { // We are not interested on empty values if (array_of_map_values[i] == 0) continue; std::string string_key = int_to_hex(static_cast<uint32_t>(i)); std::string string_value = int_to_hex(static_cast<uint32_t>(array_of_map_values[i])); values.push_back(std::make_pair(string_key, string_value)); } } else { genericTable.get_table_offline(values, dynamic_opt_compiler.getMaxOffloadedEntries()*50); } spdlog::get("Morpheus")->debug("[JIT Pass] Size of runtime value is {}", values.size()); // Here we are gonna optimize the map based on runtime values. // To avoid inconsistency problems I am going to insert a guard that checks the version // of the offloaded value. // If the version does not match, fall back to the "normal" (and slower) path. // There are two options here when the map is empty. The first one is to insert a guard; in this // case, the inconsistency is reduced since there is always the right path in the program // The other option is to substitute the value directly; in this case, we could exploit the DCE // to eliminate some checks/paths into the code. // In my opinion, it is better to distinguish the type of map used in the data plane. // Configurations map could use the DCE while other maps, which can be potentially written by the // data plane, should be always optimized with a guard. // I leave here the old code for reference. // I am splitting the block before the call to the llvm.bpf.pseudo call // The new created block will be the default block of the switch-case statement // But all the instructions after the helper call will be moved to another block that will be // the continuation of the original one. // What is happening here is the following: // Before: // BeforePseudo // llvm.bpf.pseudo(1, map_fd); // bitcastInstruction // helperCallInstruction // Tail // After: // BeforePseudo // LoadInstruction(key) // Switch(key): // Case value: CaseNBlock // Default: // llvm.bpf.pseudo(1, map_fd); // bitcastInstruction // helperCallInstruction // PhiInstruction(Default, CaseNBlock...) // Tail BasicBlock *Default = SplitBlock(bpfPseudoCallInst->getParent(), bpfPseudoCallInst); auto afterHelperInst = helperInstruction->getNextNode(); BasicBlock *Tail = SplitBlock(afterHelperInst->getParent(), afterHelperInst); if (dynamic_opt_compiler.get_config().enable_debug_printk) { builder::IRBuilderBPF IRB(Default->getFirstNonPHI()); IRB.CreateTracePrintk("Map: " + table->name + " -> Default branch hit!\n"); } std::vector<std::pair<Value *, BasicBlock *> > CaseValues; SwitchInst *switchInst = nullptr; if (values.empty()) { spdlog::get("Morpheus")->debug("[JIT Pass] Map is empty, replacing with null value!!!"); BasicBlock *successGuardBB; if (dynamic_opt_compiler.get_config().enable_guard && (!table->is_read_only || !dynamic_opt_compiler.isMapROAcrossModules(table->fd))) { spdlog::get("Morpheus")->debug("[JIT Pass] Creating guard for this map since it is not real-only!!!"); successGuardBB = createGuardForTable(ctx_, *table, bb->getTerminator(), Tail, Default); auto final_value = std::make_pair(ConstantPointerNull::get(Type::getInt8PtrTy(ctx_)), successGuardBB); CaseValues.emplace_back(std::move(final_value)); } else { /* * This is for the dead code elimination. * I remove all the instructions (that are already dead) * referencing that table, which is empty. */ while (Default->getFirstNonPHI() != helperInstruction) { Default->getFirstNonPHI()->eraseFromParent(); } BasicBlock::iterator ii(helperInstruction); helperInstruction->replaceAllUsesWith(ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx_))); // ReplaceInstWithValue(bb->getInstList(), ii, // ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx_))); instruction = bb->begin(); continue; } } else { spdlog::get("Morpheus")->debug("[JIT Pass] Map is NOT empty, offloading the existing values!!!"); auto leaf_desc = nlohmann::json::parse(table->leaf_desc); nlohmann::json struct_desc; AllocaInst *alloca_struct = nullptr; if (!leaf_desc.is_array()) { // The leaf of this map is a simple element struct_desc = leaf_desc; alloca_struct = createAllocaForSimpleLeafValues(ctx_, pfn, table->leaf_desc, table->leaf_size); } else { // The leaf contained in this map is a struct, let's extract the needed information struct_desc = leaf_desc[1]; // An allocaInstruction is placed on top of the main block of the current function // This is IMPORTANT because if the instruction is not placed on top of this block // the compiler crashes (and it is damn hard to understand why) alloca_struct = createAllocaForStructLeafValues(ctx_, pfn, table->leaf_desc, table->leaf_size); } // What I am gonna do before JIT compiling the entries into the code is to insert the // guards to protect the values when the corresponding maps are updated // What I do now is to insert a guard for the entire map, then every time the map // is update the guards is also updated. However, another possibility is to // insert a guard for each value of the map. E.g., if we have a map whose update // rate is high but the most used entries (i.e., the one offloaded) are not updated // then it makes sense to have a per-value guard. // This may be achieved by using a per-CPU map equals to the optimized map and use the guard // as the value for each key of this map (that is accessed using the original key). // What is happening here is the following: // Before: // BeforePseudo // llvm.bpf.pseudo(1, map_fd); // bitcastInstruction // helperCallInstruction // Tail // After: // BeforePseudo // guard = BPFLookupGuardMap() // if (guard == vN) goto OptBB; // else goto Default; // OptBB: // LoadInstruction(key) // Switch(key): // Case value: CaseNBlock // Default: // llvm.bpf.pseudo(1, map_fd); // bitcastInstruction // helperCallInstruction // PhiInstruction(Default, CaseNBlock...) // Tail BasicBlock *OptBB = bb->splitBasicBlock(bb->getTerminator()); if (dynamic_opt_compiler.get_config().enable_guard && (!table->is_read_only || !dynamic_opt_compiler.isMapROAcrossModules(table->fd))) { spdlog::get("Morpheus")->debug("[JIT Pass] Creating guard for this map since it is not real-only!!!"); createGuardForTable(ctx_, *table, bb->getTerminator(), OptBB, Default); } //Let's start building before the terminator of the original basic block builder::IRBuilderBPF IRB(OptBB->getTerminator()); Value *key_value = nullptr; auto key_desc = nlohmann::json::parse(table->key_desc); nlohmann::json key_struct_desc; if (!key_desc.is_array()) { key_struct_desc = key_desc; // First of all, let me extract the key value from the lookup call auto real_key_value = dyn_opt::utils::getKeyValueFromLookupHelperCall(*helperInstruction); assert(real_key_value != nullptr); // First, let's load the key into a variable and then create the switch comparison key_value = IRB.CreateLoad(real_key_value, "key_value"); } else { // The leaf contained in this map is a struct, let's extract the needed information key_struct_desc = key_desc[1]; // We are dealing with a complex key, composed of different elements // The solution that I want to apply now is to perform the jhash of the key // and compare it with the pre-computed values, so that they can be injected Function *jhash_func = pfn.getParent()->getFunction(JHASH_FUNC_NAME); assert(jhash_func != nullptr && "Unable to find function 'jhash_' into the module"); std::vector<Value *> args; // First argument is the pointer to the key (struct) args.push_back(dyn_opt::utils::getKeyPtrFromLookupHelperCall(*helperInstruction)); args.push_back(ConstantInt::get(Type::getInt32Ty(ctx_), table->key_size)); args.push_back(ConstantInt::get(Type::getInt32Ty(ctx_), JHASH_INITVAL_INT)); key_value = IRB.CreateCall(jhash_func, args); } if (dynamic_opt_compiler.get_config().enable_debug_printk) { IRB.CreateTracePrintkOneArg("Map: " + table->name + " -> Key value: %u!\n", key_value); } switchInst = SwitchInst::Create(key_value, Default, 0); ReplaceInstWithInst(OptBB->getTerminator(), switchInst); // If the table is not empty, I will go through the map values // and I will modify the code accordingly in order to JIT compile the // values directly into the code. std::vector<std::string> topEntries; unsigned int num_cases = 0; // If the size of the current values in the map is less than the maximum number of // entries that can be offloaded we can skip the instrumentation step. // However, if the map is an LPM it is better to keep the result of the instrumentation // since with the last one we can get the real most accessed entries that can be // for instance the /32 addresses, while in the map we may have less specific entries (e.g., /24). if (values.size() > dynamic_opt_compiler.getMaxOffloadedEntries() || table->type == BPF_MAP_TYPE_LPM_TRIE) { // topEntries = getEntriesFromInstrumentedMap(table->fd, dynamic_opt_compiler.getMaxOffloadedEntries()); topEntries = getEntriesFromInstrumentedMap(table->fd, table->max_entries); if (topEntries.empty()) { spdlog::get("Morpheus")->trace("No runtime entries found in the instrumented map for map: {}", table->name); goto createPhi; } else { spdlog::get("Morpheus")->debug("Found {} TOP Entries", topEntries.size()); } for (auto &topKey : topEntries) { // First of all, let's find the corresponding entries in the list of values auto it = std::find_if(values.begin(), values.end(), [&](const std::pair<std::string, std::string> &val) { return (topKey == val.first); }); std::pair<std::string, std::string> entry; if (it == values.end()) { // Try to lookup the value in the map with the one included in the instrumented // map. This is possible if in the LPM we store a value that is less specific // than the one used to perform the lookup spdlog::get("Morpheus")->debug("[JIT Pass] Top entry not found in the values. Try to lookup in the map"); std::string map_value; ebpf::StatusTuple res(-1); if (is_map_in_map_lookup && nested_map_fds.size() > 0) { for (auto &fd : nested_map_fds) { res = dyn_opt::utils::get_value_from_map(fd, topKey, map_value, *table); if (res.code() == 0) { break; } } } else { res = genericTable.get_value(topKey, map_value); } if (res.code() != 0) { spdlog::get("Morpheus")->trace("[JIT Pass] Map does not contain a value for key: {}", topKey); map_value.erase(); entry = std::make_pair(topKey, map_value); } else { entry = std::make_pair(topKey, map_value); } } else { entry = *it; } spdlog::get("Morpheus")->trace("[JIT Pass] Top entry key from map: {}", entry.first); spdlog::get("Morpheus")->trace("[JIT Pass] Top entry leaf from map: {}", entry.second); auto key_constant = getKeyConstantValue(ctx_, key_struct_desc, table->key_size, entry.first); auto final_value = createCaseBlockForEntry(bb->getContext(), bb->getParent(), Tail, table->name, alloca_struct, entry, struct_desc, table->leaf_size, table->type); // Now I should add the new block as case to the switch instruction switchInst->addCase(key_constant, std::get<1>(final_value)); CaseValues.emplace_back(std::move(final_value)); num_cases++; offloaded_entries_list_.push_back(entry.first); if (num_cases == dynamic_opt_compiler.getMaxOffloadedEntries()) { break; } } } for (auto &entry : values) { /* * Now I do not want to JIT all the values. We should put an upper-bound that * now is fixed but maybe in a second moment it is decided at runtime. */ // TODO: This value of dynamic_opt_compiler.getMaxOffloadedEntries() could be dynamic depending on various conditions if (num_cases >= dynamic_opt_compiler.getMaxOffloadedEntries() || topEntries.size() > 0) break; if (std::find(topEntries.begin(), topEntries.end(), entry.first) != topEntries.end()) continue; spdlog::get("Morpheus")->trace("[JIT Pass] Key from map: {}", entry.first); spdlog::get("Morpheus")->trace("[JIT Pass] Leaf from map: {}", entry.second); auto key_constant = getKeyConstantValue(ctx_, key_struct_desc, table->key_size, entry.first); auto final_value = createCaseBlockForEntry(bb->getContext(), bb->getParent(), Tail, table->name, alloca_struct, entry, struct_desc, table->leaf_size, table->type); // Now I should add the new block as case to the switch instruction switchInst->addCase(key_constant, std::get<1>(final_value)); CaseValues.emplace_back(std::move(final_value)); num_cases++; offloaded_entries_list_.push_back(entry.first); } } createPhi: createAndAddPhiNode(pfn, *Tail, CaseValues, helperInstruction); // Before we finish, I want to mark the current helper as optimized so that we cannot apply the // manipulation again MDNode *N = MDNode::get(ctx_, MDString::get(ctx_, "true")); helperInstruction->setMetadata("opt.hasBeenProcessed", N); if (values.size() <= CaseValues.size() && table->is_read_only && dynamic_opt_compiler.isMapROAcrossModules(table->fd) && table->type != BPF_MAP_TYPE_LPM_TRIE) { spdlog::get("Morpheus")->info("Performing DCE for this table, since the entries are small."); /* * This is for the dead code elimination. * I remove all the instructions (that are already dead) * referencing that table. * In this case, if we do not match the entries we should substitute * the map result with null, in order to simulate the entry not found. */ while (Default->getFirstNonPHI() != helperInstruction) { Default->getFirstNonPHI()->eraseFromParent(); } //TODO: What I want to do here is to replace the instruction with the key value //that is shared among all the entries BasicBlock::iterator ii(helperInstruction); // helperInstruction->replaceAllUsesWith(ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx_))); ReplaceInstWithValue(helperInstruction->getParent()->getInstList(), ii, ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx_))); } modified = true; /* Since I made some modifications on the function I update the iterator with the position of * the last block generated (Tail) */ bb = Tail->getIterator(); instruction = bb->begin(); } else { spdlog::get("Morpheus")->debug("[JIT Pass] This type of map is currently not supported"); } } } #if LLVM_VERSION_MAJOR >= 9 EliminateUnreachableBlocks(pfn); #endif return modified; } std::vector<std::string> JITTableRuntimePass::getEntriesFromInstrumentedMap(int originalMapFd, uint max_entries) { spdlog::get("Morpheus")->trace("[JIT Pass] getEntriesFromInstrumentedMap called with fd: {}", originalMapFd); if (original_maps_to_instrumented_maps_.find(originalMapFd) == original_maps_to_instrumented_maps_.end()) return std::vector<std::string>(); std::vector<std::string> entries; TableDesc &instMapDesc = original_maps_to_instrumented_maps_[originalMapFd]; assert(instMapDesc.leaf_size == sizeof(uint64_t) && "Undefined format of instrumented map!"); // if (instMapDesc.type == BPF_MAP_TYPE_PERCPU_ARRAY) { // auto table = BPFPercpuArrayTable<uint64_t>(instMapDesc); // auto values = table.get_table_offline(); // // std::sort(values.begin(), values.end(), [](const std::vector<uint64_t> &lhs, const std::vector<uint64_t> &rhs) { // return std::accumulate(lhs.begin(), lhs.end(), 0) > std::accumulate(rhs.begin(), rhs.end(), 0); // }); // // for (size_t i = 0; i < values.size(); i++) { // if (i > max_entries) break; // entries.push_back(std::to_string(std::accumulate(values[i].begin(), values[i].end(), 0))); // } // // } else // if (instMapDesc.type == BPF_MAP_TYPE_PERCPU_HASH || instMapDesc.type == BPF_MAP_TYPE_PERCPU_ARRAY) { if (instMapDesc.type == BPF_MAP_TYPE_LRU_PERCPU_HASH || instMapDesc.type == BPF_MAP_TYPE_PERCPU_HASH) { auto table = BPFTable(instMapDesc); std::vector<std::pair<std::string, std::vector<std::string>>> values; int instrumented_map_fd = instMapDesc.fd; spdlog::get("Morpheus")->trace("[JIT Pass] getEntriesFromInstrumentedMap: Reading values from instrumented map {}", instrumented_map_fd); StatusTuple rc = table.get_table_offline_percpu(values); if (rc.code() != 0) { spdlog::get("Morpheus")->error("Error while reading instrumented map: {}", rc.msg()); } if (values.size() == 0) { spdlog::get("Morpheus")->trace("[JIT Pass] getEntriesFromInstrumentedMap: Got empty map from instrumented values"); } else { spdlog::get("Morpheus")->trace("[JIT Pass] getEntriesFromInstrumentedMap: Got {} instrumented values", values.size()); } // entries = dyn_opt::utils::getTopEntriesFromInstrumentedEntriesPerCPU(values, max_entries); entries = dyn_opt::utils::getTopEntriesFromInstrumentedEntries(values, max_entries); } else { spdlog::get("Morpheus")->trace("[JIT Pass] Unsupported instrumented map. Skipping!"); return std::vector<std::string>(); } return entries; } BasicBlock *JITTableRuntimePass::createGuardForTable(llvm::LLVMContext &context, TableDesc &table, llvm::Instruction *insertBefore, llvm::BasicBlock *IfTrue, llvm::BasicBlock *ifFalse) { int guard_fd = 0; // First of all, we need to create the guard table if it does not exist if (original_maps_to_guards_.find(table.fd) != original_maps_to_guards_.end()) { // The guard map already exists, we need to extract the fd guard_fd = original_maps_to_guards_[table.fd].fd; } else { // We need to create the guard map and allocate a new FD to it guard_fd = createGuardMap(table); assert(guard_fd > 0 && "[JIT Pass] Error while creating the guard map"); } struct bpf_map_info info = {}; uint32_t info_len = sizeof(info); bpf_obj_get_info(guard_fd, &info, &info_len); spdlog::get("Morpheus")->debug("[JIT Pass] Guard for table: {} has been created with fd: {}/{}", table.name, guard_fd, info.id); auto guard_table = BPFPercpuArrayTable<uint64_t>(original_maps_to_guards_[table.fd]); std::vector<uint64_t> guard_map_value(BPFTable::get_possible_cpu_count(), 0); auto res = guard_table.update_value(0, guard_map_value); assert(res.code() == 0 && "[JIT Pass] Unable to get current value from guard map"); builder::IRBuilderBPF builder(insertBefore); // First, let's allocate the fixed key with index 0, which is used to lookup // into the per-CPU guard map auto alloca_key = builder.CreateAllocaBPF(Type::getInt32Ty(context)); builder.CreateStore(builder.getInt32(0), alloca_key); auto guard_value = builder.CreateGuardMapLookupElem(guard_fd, Type::getInt64Ty(context), alloca_key, ifFalse, MorpheusCompiler::getInstance().get_config().enable_debug_printk); auto guard_cmp_res = builder.CreateICmpEQ(guard_value, builder.getInt64(guard_map_value[0])); builder.CreateCondBr(guard_cmp_res, IfTrue, ifFalse); return builder.GetInsertBlock(); } int JITTableRuntimePass::createGuardMap(TableDesc &original_map) { int fd, map_type, key_size, value_size, max_entries, map_flags; const char *map_name; // The type of the guard map is always a per-cpu array map_type = BPF_MAP_TYPE_PERCPU_ARRAY; // The name of the guard map is equal to the original name + "_guard" // TODO: This should be improved to avoid that the program uses the same name for another map // But I do not know if this can be actually a problem auto original_map_name = original_map.name; original_map_name.resize(5); map_name = std::string(original_map_name + "_g").c_str(); // WARNING: The size of the array map cannot be less than an integer // otherwise the map is not loaded key_size = sizeof(int); // At the same time, the size of the value inside the guard map is // just 1B; in this way we are creating maps with up to 256 different // versions, which sounds quite reasonable to me. // Unfortunately, it is not possible to set values that are not aligned to 8B value_size = sizeof(uint64_t); // The max number of entries is 1 since this map contains only the guard value max_entries = 1; // I will copy the same flags as the original maps // TODO: Check if this is correct or it is better to put the flags to 0 // Setting the same flags as the original one can be a problem when we try to // optimize maps such as LPM Tries that use different flags and we copy them into a different // map type (i.e., LRU_MAP) //map_flags = original_map.flags; map_flags = 0; struct bpf_create_map_attr attr = {}; attr.map_type = (enum bpf_map_type) map_type; attr.name = map_name; attr.key_size = key_size; attr.value_size = value_size; attr.max_entries = max_entries; attr.map_flags = map_flags; fd = bcc_create_map_xattr(&attr, true); if (fd < 0) { spdlog::get("Morpheus")->error("could not open bpf map: {}, error: {}", map_name, strerror(errno)); return -1; } // Let's create the corresponding BPFTable, which is easier to manipulate TableDesc desc = TableDesc(std::string(map_name), FileDesc(fd), map_type, key_size, value_size, max_entries, map_flags); original_maps_to_guards_.emplace(original_map.fd, std::move(desc)); auto guard_table = BPFPercpuArrayTable<uint64_t>(original_maps_to_guards_[original_map.fd]); std::vector<uint64_t> guard_init_value(BPFTable::get_possible_cpu_count(), 0); auto res = guard_table.update_value(0, guard_init_value); assert(res.code() == 0 && "[JIT Pass] Unable to initialize guard map"); return fd; } AllocaInst *JITTableRuntimePass::createAllocaForSimpleLeafValues(LLVMContext &ctx, Function &mainFunction, std::string &leafDesc, size_t &leafSize) { IRBuilder<> IRB(&mainFunction.front().getInstList().front()); auto leaf = nlohmann::json::parse(leafDesc); assert(!leaf.is_array() && "The leaf values are not in the expected JSON format (not array)"); // TODO: What is missing here is the proper creation of the alloca struct with the correct types auto struct_elem = leaf.get<std::string>(); Type *type = dyn_opt::utils::getCorrectTypeGivenDescription(ctx, struct_elem, leafSize); return IRB.CreateAlloca(type); } AllocaInst *JITTableRuntimePass::createAllocaForStructLeafValues(LLVMContext &ctx, Function &mainFunction, std::string &leafDesc, size_t &leafSize) { IRBuilder<> IRB(&mainFunction.front().getInstList().front()); auto leaf = nlohmann::json::parse(leafDesc); assert(leaf.is_array() && "The leaf values are not in the expected JSON format (array)"); // The first element is the name of the struct auto struct_name = leaf[0].get<std::string>(); auto struct_elem = leaf[1]; Type *struct_type = nullptr; auto final_str_name = "struct." + struct_name; if (struct_type == nullptr) { struct_type = StructType::create(ctx, struct_name); std::vector<Type *> members; // TODO: What is missing here is the proper creation of the alloca struct with the correct types for (auto &elem : struct_elem) { std::string value_name = elem[0]; std::string value_type = elem[1]; if (value_type.find("bpf_spin_lock") != std::string::npos) { assert(false && "Spin lock found in the struct definition"); continue; } if (elem.size() == 3 && elem[2].is_array()) { // The element is an array, we should allocate the proper type unsigned int array_size = elem[2][0]; auto type = ArrayType::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), array_size); members.push_back(type); } else { members.push_back(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize)); } } dyn_cast<StructType>(struct_type)->setBody(members); } std::string alloca_name = struct_name + std::to_string(rand() % 255) + "_alloca"; auto alloca_struct = IRB.CreateAlloca(struct_type, nullptr, alloca_name); // IMPORTANT: Without this memset, the system crashes because the value could // be used to perform a lookup or update in the map and, if not initialized, can raise an error IRB.CREATE_MEMSET(alloca_struct, IRB.getInt8(0), leafSize, 1); //IRB.CreateMemSet(alloca_struct, IRB.getInt8(0), leafSize, 1); return alloca_struct; } bool JITTableRuntimePass::isSimpleKey(std::string &keyDesc) { auto key = nlohmann::json::parse(keyDesc); // If the description of the key is an array then we are dealing with complex // keys that are made of a struct of elements return !key.is_array(); } llvm::ConstantInt * JITTableRuntimePass::getKeyConstantValue(LLVMContext &ctx, nlohmann::json &keyDesc, size_t &keySize, std::string &keyValue) { uint32_t key = 0; IntegerType *key_type = nullptr; if (!keyDesc.is_array()) { bool signed_int = true; auto key_string = keyDesc.get<std::string>(); if (key_string.find("unsigned") != std::string::npos) signed_int = false; if (signed_int) { key = std::stoi(keyValue, nullptr, 16); } else { key = std::stoul(keyValue, nullptr, 16); } key_type = dyn_opt::utils::getKeyType(ctx, key_string, keySize); assert((key_type != nullptr) && "The key in this map is not currently supported!"); } else { auto key_value = nlohmann::json::parse(getJsonFromLeafValues(keyValue)); assert(key_value.is_array() && "Unexpected format in the key values!"); unsigned char key_array[keySize]; unsigned int pos = 0; for (unsigned int i = 0; i < keyDesc.size(); i++) { assert(keyDesc[i].is_array() && "Wrong format of the element description"); std::string value_name = keyDesc[i][0]; std::string value_type = keyDesc[i][1]; bool is_type_array = false; // bool is_type_union = false; unsigned int array_size = 1; if (keyDesc.size() > 2) { auto third_param = keyDesc[i][2]; if (third_param.is_array()) { is_type_array = true; } else if (third_param.is_string() && third_param.get<std::string>() == "union") { assert(false && "Unions are not supported right now! :("); } else { assert(false && "Unknown third parameter in the key description"); } } // if (is_type_union) { // parseUnionKeyType(value_type); // } bool signed_int = true; if (value_name.find("__pad_end") != std::string::npos) { assert(value_type.find("char") != std::string::npos && "Final padding is not a char"); auto padding_desc = keyDesc[i][2]; assert(padding_desc.is_array() && "Found __pad_end but I was not able to read the value"); unsigned int padding_size = padding_desc.at(0); for (unsigned int j = 0; j < padding_size; j++) { key_array[pos] = 0; pos++; } continue; } if (value_type.find("unsigned") != std::string::npos) signed_int = false; if (is_type_array) { array_size = keyDesc[i][2].at(0); } for (unsigned int j = 0; j < array_size; j++) { nlohmann::ordered_json value; if (key_value[i].is_string()) { value = key_value[i]; } else if (key_value[i].is_array() && key_value[i][j].is_string()) { value = key_value[i][j]; } else { assert(false && "Unexpected value while parsing the key"); } if (value_type.find("long long") != std::string::npos) { // It is a 64bit integer if (signed_int) { int64_t real_value = std::stoll(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } else { uint64_t real_value = std::stoull(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } } else if (value_type.find("long") != std::string::npos || value_type.find("int") != std::string::npos) { // It is a 32bit integer if (signed_int) { int32_t real_value = std::stol(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } else { uint32_t real_value = std::stoul(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } } else if (value_type.find("short") != std::string::npos) { // It is a 16bit integer if (signed_int) { int16_t real_value = std::stoi(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } else { uint16_t real_value = std::stoul(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } } else if (value_type.find("char") != std::string::npos) { // It is a 8bit integer if (signed_int) { int8_t real_value = std::stoi(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } else { uint8_t real_value = std::stoul(value.get<std::string>(), nullptr, 16); std::copy(static_cast<const char *>(static_cast<const void *>(&real_value)), static_cast<const char *>(static_cast<const void *>(&real_value)) + sizeof(real_value), key_array + pos); pos += sizeof(real_value); } } else { assert(false && "Unable to recognize type of the key"); } } } // end for assert(pos == keySize && "Error while calculating the correct size of the key structure"); // Now let's calculate the result of the jhash //key = jhash_words(reinterpret_cast<const uint32_t *>(key_array), keySize, JHASH_INITVAL); // TODO: Check if there is a collision in the hash of the offloaded entries. key = jhash_bytes((void *) key_array, keySize, JHASH_INITVAL); spdlog::get("Morpheus")->trace("[JIT Pass] Calculated jhash with value: {}", key); key_type = IntegerType::getInt32Ty(ctx); } return ConstantInt::get(key_type, key, false); } std::pair<Value *, BasicBlock *> JITTableRuntimePass::createCaseBlockForEntry(LLVMContext &ctx, Function *parent, BasicBlock *insertBefore, std::string &tableName, AllocaInst *allocaStruct, std::pair<std::string, std::string> &value, nlohmann::json &structDesc, size_t &leafSize, int tableType) { BasicBlock *CaseBlock = BasicBlock::Create(ctx, "", parent, insertBefore); BranchInst *branchInst = BranchInst::Create(insertBefore, CaseBlock); builder::IRBuilderBPF IRBCase(branchInst); Value *final_value = nullptr; if (MorpheusCompiler::getInstance().get_config().enable_debug_printk) { IRBCase.CreateTracePrintk("Map: " + tableName + " -> Optimized branch hit for key " + value.first + "!\n"); } if (tableType == BPF_MAP_TYPE_ARRAY_OF_MAPS) { auto map_id = std::stoul(value.second, nullptr, 16); auto map_fd = bpf_map_get_fd_by_id(map_id); if (map_fd < 0) { spdlog::get("Morpheus")->error("[JITTableRuntimePass] Error while retrieving map fd for array of maps"); assert(false && "Runtime error while retrieving map fd"); } spdlog::get("Morpheus")->trace("[JITTableRuntimePass] Dealing with Array of Maps. Map entry value is: {}, and fd is: {}", map_id, map_fd); auto map_fd_value = IRBCase.CreateBpfPseudoCall(map_fd); //auto value_ptr = CreateIntToPtr(getInt64(0), getInt8PtrTy()); final_value = IRBCase.CreateIntToPtr(map_fd_value, IntegerType::getInt8PtrTy(ctx)); //final_value = IRBCase.CreateBitCast(map_fd_value, IntegerType::getInt8PtrTy(ctx)); return std::make_pair(final_value, CaseBlock); } std::string value_copy = value.second; value_copy.erase(std::remove(value_copy.begin(), value_copy.end(), '"'), value_copy.end()); if (value.second.empty() || value_copy.empty()) { spdlog::get("Morpheus")->trace("[JITTableRuntimePass] Setting value pointer to NULL for entry: {}", value.first); // Table for that key is empty final_value = ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx)); } else { if (structDesc.is_array()) { // The leaf is a struct std::string tmp_string = getJsonFromLeafValues(value.second); spdlog::get("Morpheus")->trace("[JITTableRuntimePass] The string returned from getJsonFromLeafValues is: {}", tmp_string); auto leaf_value = nlohmann::json::parse(getJsonFromLeafValues(value.second)); assert(leaf_value.is_array() && "Unexpected format in the leaf values!"); // We are dealing with a struct, it should be safe to do this cast StructType *struct_type = dyn_cast_or_null<StructType>(allocaStruct->getType()); if (struct_type == nullptr) { assert(false && "Error while processing struct in offloaded values"); } for (unsigned int i = 0, j = 0; i < structDesc.size(); i++) { assert(structDesc[i].is_array() && "Wrong format of the element description"); std::string value_name = structDesc[i][0]; std::string value_type = structDesc[i][1]; if (value_name.find("__pad") != std::string::npos || value_type.find("bpf_spin_lock") != std::string::npos) { spdlog::get("Morpheus")->trace("Skip this entry, it is just padding or a bpf_spin_lock"); continue; } auto signed_int = true; if (value_type.find("unsigned") != std::string::npos || value_type.find("char") != std::string::npos) signed_int = false; auto gep_value = IRBCase.CreateStructGEP(allocaStruct, i, value_name); if (structDesc[i].size() == 3 && structDesc[i][2].is_array()) { spdlog::get("Morpheus")->trace("[JITTableRuntimePass] We are inside an array"); // We have an array in this case as an entry in the struct //unsigned int array_size = structDesc[i][2][0]; std::vector<Constant *> vect; // ArrayType *array_type = dyn_cast_or_null<ArrayType>(struct_type->elements()[i]); // assert(array_type != nullptr && "This field should be an array type"); assert(leaf_value[j].is_array() && "Unexpected format for the leaf values!"); if (value_type == "char" && leaf_value[j].size() == 1) { uint32_t string_size = structDesc[i][2].at(0).get<uint32_t>(); std::string string_to_offload = std::string(string_size, 0); std::string original_string = leaf_value[j].get<std::string>(); string_to_offload.replace(0, original_string.length(), original_string); // We have a string to allocate spdlog::get("Morpheus")->trace("[JITTableRuntimePass] We need to allocate a string of size {} in this case: {}", string_to_offload.length(), string_to_offload); std::vector<llvm::Constant *> chars(string_to_offload.size()); for(unsigned int i = 0; i < string_to_offload.size(); i++) { chars[i] = ConstantInt::get(IntegerType::getInt8Ty(ctx), string_to_offload[i]); } auto init = ConstantArray::get(ArrayType::get(IntegerType::getInt8Ty(ctx), chars.size()), chars); IRBCase.CreateStore(init, gep_value); } else { for (auto &elem : leaf_value[j]) { if (value_type.find("long long") != std::string::npos) { // It is a 64bit integer if (signed_int) { int64_t real_value = std::stoll(elem.get<std::string>(), nullptr, 16); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); } else { uint64_t real_value = std::stoull(elem.get<std::string>(), nullptr, 16); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); } } else if (value_type.find("long") != std::string::npos || value_type.find("int") != std::string::npos) { // It is a 32bit integer if (signed_int) { int32_t real_value = std::stol(elem.get<std::string>(), nullptr, 16); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); } else { uint32_t real_value = std::stoul(elem.get<std::string>(), nullptr, 16); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); } } else if (value_type.find("short") != std::string::npos) { if (signed_int) { int16_t real_value = std::stoi(elem.get<std::string>(), nullptr, 16); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); // vect.push_back(ConstantInt::get(array_type->getArrayElementType(), real_value)); } else { uint16_t real_value = std::stoul(elem.get<std::string>(), nullptr, 16); // vect.push_back(ConstantInt::get(array_type->getArrayElementType(), real_value)); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); } } else if (value_type.find("char") != std::string::npos) { if (signed_int) { int8_t real_value = std::stoi(elem.get<std::string>(), nullptr, 16); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); // vect.push_back(ConstantInt::get(array_type->getArrayElementType(), real_value)); } else { uint8_t real_value = std::stoul(elem.get<std::string>(), nullptr, 16); // vect.push_back(ConstantInt::get(array_type->getArrayElementType(), real_value)); vect.push_back( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value)); } } else { assert(false && "Unable to recognize type of the key"); } } // Allocate the array with the values auto llvm_array = ConstantArray::get( ArrayType::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), vect.size()), vect); // auto llvm_array = ConstantArray::get(array_type, vect); IRBCase.CreateStore(llvm_array, gep_value); } } else { if (value_type.find("long long") != std::string::npos) { // It is a 64bit integer if (signed_int) { int64_t real_value = std::stoll(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); } else { uint64_t real_value = std::stoull(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); } } else if (value_type.find("long") != std::string::npos || value_type.find("int") != std::string::npos) { // It is a 32bit integer if (signed_int) { int32_t real_value = std::stol(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); } else { uint32_t real_value = std::stoul(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); } } else if (value_type.find("short") != std::string::npos) { if (signed_int) { int16_t real_value = std::stoi(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); // IRBCase.CreateStore(ConstantInt::get(struct_type->elements()[i], real_value), gep_value); } else { uint16_t real_value = std::stoul(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); // IRBCase.CreateStore(ConstantInt::get(struct_type->elements()[i], real_value), gep_value); } } else if (value_type.find("char") != std::string::npos) { if (signed_int) { int8_t real_value = std::stoi(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); // IRBCase.CreateStore(ConstantInt::get(struct_type->elements()[i], real_value), gep_value); } else { uint8_t real_value = std::stoul(leaf_value[j].get<std::string>(), nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), gep_value); // IRBCase.CreateStore(ConstantInt::get(struct_type->elements()[i], real_value), gep_value); } } else { assert(false && "Unable to recognize type of the key"); } } j++; } } else { //TODO: Fix this with the correct stoul depending on type auto value_type = structDesc.get<std::string>(); auto real_value = std::stoul(value.second, nullptr, 16); IRBCase.CreateStore( ConstantInt::get(dyn_opt::utils::getCorrectTypeGivenDescription(ctx, value_type, leafSize), real_value), allocaStruct); } final_value = IRBCase.CreateBitCast(allocaStruct, IntegerType::getInt8PtrTy(ctx)); } return std::make_pair(final_value, CaseBlock); } std::string JITTableRuntimePass::getJsonFromLeafValues(const std::string &values) { const std::regex quotes(R"QUOTES("([^"]*)")QUOTES"); const std::regex re(R"(([^\[\]\s\{\}]+)(?=\s))"); const std::regex re1(R"(([^\[\s\{\}]+)(?=\s[^\]|\}]))"); const std::regex substitution(R"("0xffff")"); std::smatch m; std::string old_string; if (std::regex_search(values, m, quotes)) { old_string = m[1]; } std::string first_pass = std::regex_replace(values, quotes, R"(0xffff)"); std::string second_pass = std::regex_replace(first_pass, re, R"("$1")"); std::string third_pass = std::regex_replace(second_pass, re1, R"($1,)"); if (old_string.length() > 0) { old_string = ebpf::dyn_opt::utils::escape_json(old_string); old_string = "\"" + old_string + "\""; third_pass = std::regex_replace(third_pass, substitution, old_string); } std::replace(third_pass.begin(), third_pass.end(), '{', '['); std::replace(third_pass.begin(), third_pass.end(), '}', ']'); return third_pass; } void JITTableRuntimePass::createAndAddPhiNode(Function &pFunction, BasicBlock &insertInto, std::vector<std::pair<Value *, BasicBlock *>> &caseValues, CallInst *helperInstruction) { ValueToValueMapTy vMap; DebugInfoFinder DIFinder; if (caseValues.empty()) return; PHINode *Phi = nullptr; // Finally, I create a PHY node that contains all the results of the previous if-else blocks Phi = PHINode::Create(helperInstruction->getType(), 0); insertInto.getInstList().insert(insertInto.getFirstInsertionPt(), Phi); vMap[helperInstruction] = Phi; DIFinder.processInstruction(*pFunction.getParent(), *helperInstruction); for (DISubprogram *ISP : DIFinder.subprograms()) vMap.MD()[ISP].reset(ISP); for (DICompileUnit *CU : DIFinder.compile_units()) vMap.MD()[CU].reset(CU); for (DIType *Type : DIFinder.types()) vMap.MD()[Type].reset(Type); dyn_opt::utils::remapInstructionsInFunction(pFunction, vMap); for (auto &value : caseValues) { Phi->addIncoming(std::get<0>(value), std::get<1>(value)); } //IMPORTANT: If I do not put this instruction here, it may be replaced by the others Phi->addIncoming(helperInstruction, helperInstruction->getParent()); } template< typename T > std::string JITTableRuntimePass::int_to_hex( T i ) { std::stringstream stream; stream << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2) << std::hex << i; return stream.str(); } // Called once for each module, before the calls on the basic blocks. // We could use doFinalization to clear RNG, but that's not needed. bool JITTableRuntimePass::doFinalization(Module &M) { // Let's remove the jhash function from this module, otherwise it raises a compilation error // Function *jhash_func = M.getFunction(JHASH_FUNC_NAME); // // if (jhash_func != nullptr) { // jhash_func->replaceAllUsesWith(UndefValue::get((Type*)jhash_func->getType())); // // jhash_func->eraseFromParent(); // } return false; } TableDesc *JITTableRuntimePass::getTableByFD(llvm::ConstantInt &pInt) { return dyn_opt::utils::getTableByFD(pInt, bpf_module_id_, ts_, fake_fd_map_, tables_); } Pass *JITTableRuntimePass::createJITTableRuntimePass(std::string id, std::string func_name, ebpf::TableStorage *ts, ebpf::fake_fd_map_def &fake_fd_map, std::vector<ebpf::TableDesc *> &tables, std::map<int, TableDesc> &original_maps_to_guards, std::map<int, TableDesc> &original_maps_to_instrumented_maps, std::vector<std::string> &offloaded_entries_list) { return new JITTableRuntimePass(std::move(id), std::move(func_name), ts, fake_fd_map, tables, original_maps_to_guards, original_maps_to_instrumented_maps, offloaded_entries_list); } } //namespace ebpf
47.856264
172
0.609129
[ "vector" ]
583cbe81f6b63600a1d997f8c4f01efd080b7eff
32,176
hpp
C++
src/gfcc/contrib/cd_ccsd_cs_ann.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
null
null
null
src/gfcc/contrib/cd_ccsd_cs_ann.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
null
null
null
src/gfcc/contrib/cd_ccsd_cs_ann.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
null
null
null
#include "diis.hpp" #include "ccsd_util.hpp" #include "ga/macdecls.h" #include "ga/ga-mpi.h" using namespace tamm; bool debug = false; TiledIndexSpace o_alpha,v_alpha,o_beta,v_beta; Tensor<double> f1_aa_oo , f1_aa_ov , f1_aa_vo , f1_aa_vv , f1_bb_oo , f1_bb_ov , f1_bb_vo , f1_bb_vv , chol3d_aa_oo, chol3d_aa_ov, chol3d_aa_vo, chol3d_aa_vv, chol3d_bb_oo, chol3d_bb_ov, chol3d_bb_vo, chol3d_bb_vv, t1_aa , t1_bb , t2_aaaa , t2_abab , t2_bbbb , r1_aa , r1_bb , r2_aaaa , r2_abab , r2_bbbb , i0_atmp , i0_btmp , _a004_aaaa , _a004_abab , _a004_bbbb , _a01 , _a01_aa , _a01_bb , _a02 , _a02_aa , _a02_bb , _a03_aa , _a03_bb , _a03_aa_vo , _a03_bb_vo , _a04_aa , _a04_bb , _a05_aa , _a05_bb , _a007 , _a001_aa , _a001_bb , _a017_aa , _a017_bb , _a006_aa , _a006_bb , _a008_aa , _a008_bb , _a009_aa , _a009_bb , _a019_aaaa , _a019_abab , _a019_abba , _a019_baba , _a019_bbbb , _a020_aaaa , _a020_baba , _a020_abab , _a020_baab , _a020_bbbb , _a020_abba , _a021_aa , _a021_bb , _a022_aaaa , _a022_abab , _a022_bbbb ; Tensor<double> dt1_full, dt2_full; Tensor<double> t2_baba, t2_abba, t2_baab, i0_temp, t2_aaaa_temp; template<typename T> void ccsd_e_cs(/* ExecutionContext &ec, */ Scheduler& sch, const TiledIndexSpace& MO, const TiledIndexSpace& CI, Tensor<T>& de, const Tensor<T>& t1_aa, const Tensor<T>& t2_abab) { auto [cind] = CI.labels<1>("all"); auto [p1_va, p2_va] = v_alpha.labels<2>("all"); auto [p1_vb] = v_beta.labels<1>("all"); auto [h1_oa, h2_oa] = o_alpha.labels<2>("all"); auto [h1_ob] = o_beta.labels<1>("all"); sch (t2_aaaa_temp()=0) .exact_copy(t2_aaaa(p1_va, p2_va, h1_oa, h2_oa), t2_abab(p1_va, p2_va, h1_oa, h2_oa)) (t2_aaaa_temp() = t2_aaaa(), "t2_aaaa_temp() = t2_aaaa()") (t2_aaaa(p1_va,p2_va,h1_oa,h2_oa) += -1.0 * t2_aaaa_temp(p2_va,p1_va,h1_oa,h2_oa), "t2_aaaa(p1_va,p2_va,h1_oa,h2_oa) += -1.0 * t2_aaaa_temp(p2_va,p1_va,h1_oa,h2_oa)") (t2_aaaa_temp(p1_va,p2_va,h1_oa,h2_oa) += 1.0 * t2_aaaa(p2_va,p1_va,h2_oa,h1_oa), "t2_aaaa_temp(p1_va,p2_va,h1_oa,h2_oa) += 1.0 * t2_aaaa(p2_va,p1_va,h2_oa,h1_oa)") (_a01(cind) = t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h1_oa, p1_va, cind), "_a01(cind) = t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h1_oa, p1_va, cind)") (_a02_aa(h1_oa, h2_oa, cind) = t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h2_oa, p1_va, cind), "_a02_aa(h1_oa, h2_oa, cind) = t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h2_oa, p1_va, cind)") (_a03_aa(h2_oa, p2_va, cind) = t2_aaaa_temp(p2_va, p1_va, h2_oa, h1_oa) * chol3d_aa_ov(h1_oa, p1_va, cind), "_a03_aa(h2_oa, p2_va, cind) = t2_aaaa_temp(p2_va, p1_va, h2_oa, h1_oa) * chol3d_aa_ov(h1_oa, p1_va, cind)") (de() = 2.0 * _a01() * _a01(), "de() = 2.0 * _a01() * _a01()") (de() += -1.0 * _a02_aa(h1_oa, h2_oa, cind) * _a02_aa(h2_oa, h1_oa, cind), "de() += -1.0 * _a02_aa(h1_oa, h2_oa, cind) * _a02_aa(h2_oa, h1_oa, cind)") (de() += 1.0 * _a03_aa(h1_oa, p1_va, cind) * chol3d_aa_ov(h1_oa, p1_va, cind), "de() += 1.0 * _a03_aa(h1_oa, p1_va, cind) * chol3d_aa_ov(h1_oa, p1_va, cind)") ; } template<typename T> void ccsd_t1_cs(/* ExecutionContext& ec, */ Scheduler& sch, const TiledIndexSpace& MO,const TiledIndexSpace& CI, Tensor<T>& i0_aa, const Tensor<T>& t1_aa, const Tensor<T>& t2_abab) { auto [cind] = CI.labels<1>("all"); auto [p2] = MO.labels<1>("virt"); auto [h1] = MO.labels<1>("occ"); auto [p1_va, p2_va] = v_alpha.labels<2>("all"); auto [p1_vb] = v_beta.labels<1>("all"); auto [h1_oa, h2_oa] = o_alpha.labels<2>("all"); auto [h1_ob] = o_beta.labels<1>("all"); sch (i0_aa(p2_va, h1_oa) = 1.0 * f1_aa_ov(h1_oa, p2_va), "i0_aa(p2_va, h1_oa) = 1.0 * f1_aa_ov(h1_oa, p2_va)") (_a01_aa(h2_oa, h1_oa, cind) = 1.0 * t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h2_oa, p1_va, cind), "_a01_aa(h2_oa, h1_oa, cind) = 1.0 * t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h2_oa, p1_va, cind)") // ovm (_a02(cind) = 2.0 * t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h1_oa, p1_va, cind), "_a02(cind) = 2.0 * t1_aa(p1_va, h1_oa) * chol3d_aa_ov(h1_oa, p1_va, cind)") // ovm // (_a02(cind) = 2.0 * _a01_aa(h1_oa, h1_oa, cind)) (_a05_aa(h2_oa, p1_va) = -1.0 * chol3d_aa_ov(h1_oa, p1_va, cind) * _a01_aa(h2_oa, h1_oa, cind), "_a05_aa(h2_oa, p1_va) = -1.0 * chol3d_aa_ov(h1_oa, p1_va, cind) * _a01_aa(h2_oa, h1_oa, cind)") // o2vm .exact_copy(_a05_bb(h1_ob,p1_vb),_a05_aa(h1_ob,p1_vb)) (_a03_aa_vo(p1_va, h1_oa, cind) = -1.0 * t2_aaaa_temp(p1_va, p2_va, h1_oa, h2_oa) * chol3d_aa_ov(h2_oa, p2_va, cind), "_a03_aa_vo(p1_va, h1_oa, cind) = -1.0 * t2_aaaa_temp(p1_va, p2_va, h1_oa, h2_oa) * chol3d_aa_ov(h2_oa, p2_va, cind)") // o2v2m (_a04_aa(h2_oa, h1_oa) = 1.0 * chol3d_aa_ov(h2_oa, p1_va, cind) * _a03_aa_vo(p1_va, h1_oa, cind), "_a04_aa(h2_oa, h1_oa) = 1.0 * chol3d_aa_ov(h2_oa, p1_va, cind) * _a03_aa_vo(p1_va, h1_oa, cind)") // o2vm (i0_aa(p2_va, h1_oa) += 1.0 * t1_aa(p2_va, h2_oa) * _a04_aa(h2_oa, h1_oa), "i0_aa(p2_va, h1_oa) += 1.0 * t1_aa(p2_va, h2_oa) * _a04_aa(h2_oa, h1_oa)") // o2v (i0_aa(p1_va, h2_oa) += 1.0 * chol3d_aa_ov(h2_oa, p1_va, cind) * _a02(cind), "i0_aa(p1_va, h2_oa) += 1.0 * chol3d_aa_ov(h2_oa, p1_va, cind) * _a02(cind)") // ovm (i0_aa(p1_va, h2_oa) += 1.0 * t2_aaaa_temp(p1_va, p2_va, h2_oa, h1_oa) * _a05_aa(h1_oa, p2_va), "i0_aa(p1_va, h2_oa) += 1.0 * t2_aaaa_temp(p1_va, p2_va, h2_oa, h1_oa) * _a05_aa(h1_oa, p2_va)") (i0_aa(p2_va, h1_oa) += -1.0 * chol3d_aa_vv(p2_va, p1_va, cind) * _a03_aa_vo(p1_va, h1_oa, cind), "i0_aa(p2_va, h1_oa) += -1.0 * chol3d_aa_vv(p2_va, p1_va, cind) * _a03_aa_vo(p1_va, h1_oa, cind)") // ov2m (_a03_aa_vo(p2_va, h2_oa, cind) += -1.0 * t1_aa(p1_va, h2_oa) * chol3d_aa_vv(p2_va, p1_va, cind), "_a03_aa_vo(p2_va, h2_oa, cind) += -1.0 * t1_aa(p1_va, h2_oa) * chol3d_aa_vv(p2_va, p1_va, cind)") // ov2m (i0_aa(p1_va, h2_oa) += -1.0 * _a03_aa_vo(p1_va, h2_oa, cind) * _a02(cind), "i0_aa(p1_va, h2_oa) += -1.0 * _a03_aa_vo(p1_va, h2_oa, cind) * _a02(cind)") // ovm (_a03_aa_vo(p2_va, h1_oa, cind) += -1.0 * t1_aa(p2_va, h1_oa) * _a02(cind), "_a03_aa_vo(p2_va, h1_oa, cind) += -1.0 * t1_aa(p2_va, h1_oa) * _a02(cind)") // ovm (_a03_aa_vo(p2_va, h1_oa, cind) += 1.0 * t1_aa(p2_va, h2_oa) * _a01_aa(h2_oa, h1_oa, cind), "_a03_aa_vo(p2_va, h1_oa, cind) += 1.0 * t1_aa(p2_va, h2_oa) * _a01_aa(h2_oa, h1_oa, cind)") // o2vm (_a01_aa(h2_oa, h1_oa, cind) += 1.0 * chol3d_aa_oo(h2_oa, h1_oa, cind), "_a01_aa(h2_oa, h1_oa, cind) += 1.0 * chol3d_aa_oo(h2_oa, h1_oa, cind)") // o2m (i0_aa(p2_va, h1_oa) += 1.0 * _a01_aa(h2_oa, h1_oa, cind) * _a03_aa_vo(p2_va, h2_oa, cind), "i0_aa(p2_va, h1_oa) += 1.0 * _a01_aa(h2_oa, h1_oa, cind) * _a03_aa_vo(p2_va, h2_oa, cind)") // o2vm (i0_aa(p2_va, h1_oa) += -1.0 * t1_aa(p2_va, h2_oa) * f1_aa_oo(h2_oa, h1_oa), "i0_aa(p2_va, h1_oa) += -1.0 * t1_aa(p2_va, h2_oa) * f1_aa_oo(h2_oa, h1_oa)") // o2v (i0_aa(p2_va, h1_oa) += 1.0 * t1_aa(p1_va, h1_oa) * f1_aa_vv(p2_va, p1_va), "i0_aa(p2_va, h1_oa) += 1.0 * t1_aa(p1_va, h1_oa) * f1_aa_vv(p2_va, p1_va)") // ov2 ; } template<typename T> void ccsd_t2_cs(/* ExecutionContext& ec, */ Scheduler& sch, const TiledIndexSpace& MO,const TiledIndexSpace& CI, Tensor<T>& i0_abab, const Tensor<T>& t1_aa, Tensor<T>& t2_abab) { auto [cind] = CI.labels<1>("all"); auto [p3, p4] = MO.labels<2>("virt"); auto [h1, h2] = MO.labels<2>("occ"); auto [p1_va, p2_va, p3_va] = v_alpha.labels<3>("all"); auto [p1_vb, p2_vb] = v_beta.labels<2>("all"); auto [h1_oa, h2_oa, h3_oa] = o_alpha.labels<3>("all"); auto [h1_ob, h2_ob] = o_beta.labels<2>("all"); sch (_a017_aa(p1_va, h2_oa, cind) = -1.0 * t2_aaaa_temp(p1_va, p2_va, h2_oa, h1_oa) * chol3d_aa_ov(h1_oa, p2_va, cind), "_a017_aa(p1_va, h2_oa, cind) = -1.0 * t2_aaaa_temp(p1_va, p2_va, h2_oa, h1_oa) * chol3d_aa_ov(h1_oa, p2_va, cind)") (_a006_aa(h2_oa, h1_oa) = -1.0 * chol3d_aa_ov(h2_oa, p2_va, cind) * _a017_aa(p2_va, h1_oa, cind), "_a006_aa(h2_oa, h1_oa) = -1.0 * chol3d_aa_ov(h2_oa, p2_va, cind) * _a017_aa(p2_va, h1_oa, cind)") (_a007(cind) = 2.0 * chol3d_aa_ov(h1_oa, p1_va, cind) * t1_aa(p1_va, h1_oa), "_a007(cind) = 2.0 * chol3d_aa_ov(h1_oa, p1_va, cind) * t1_aa(p1_va, h1_oa)") (_a009_aa(h1_oa, h2_oa, cind) = 1.0 * chol3d_aa_ov(h1_oa, p1_va, cind) * t1_aa(p1_va, h2_oa), "_a009_aa(h1_oa, h2_oa, cind) = 1.0 * chol3d_aa_ov(h1_oa, p1_va, cind) * t1_aa(p1_va, h2_oa)") (_a021_aa(p2_va, p1_va, cind) = -0.5 * chol3d_aa_ov(h1_oa, p1_va, cind) * t1_aa(p2_va, h1_oa), "_a021_aa(p2_va, p1_va, cind) = -0.5 * chol3d_aa_ov(h1_oa, p1_va, cind) * t1_aa(p2_va, h1_oa)") (_a021_aa(p2_va, p1_va, cind) += 0.5 * chol3d_aa_vv(p2_va, p1_va, cind), "_a021_aa(p2_va, p1_va, cind) += 0.5 * chol3d_aa_vv(p2_va, p1_va, cind)") (_a017_aa(p1_va, h2_oa, cind) += -2.0 * t1_aa(p2_va, h2_oa) * _a021_aa(p1_va, p2_va, cind), "_a017_aa(p1_va, h2_oa, cind) += -2.0 * t1_aa(p2_va, h2_oa) * _a021_aa(p1_va, p2_va, cind)") (_a008_aa(h2_oa, h1_oa, cind) = 1.0 * _a009_aa(h2_oa, h1_oa, cind), "_a008_aa(h2_oa, h1_oa, cind) = 1.0 * _a009_aa(h2_oa, h1_oa, cind)") (_a009_aa(h2_oa, h1_oa, cind) += 1.0 * chol3d_aa_oo(h2_oa, h1_oa, cind), "_a009_aa(h2_oa, h1_oa, cind) += 1.0 * chol3d_aa_oo(h2_oa, h1_oa, cind)") .exact_copy(_a009_bb(h2_ob,h1_ob,cind),_a009_aa(h2_ob,h1_ob,cind)) .exact_copy(_a021_bb(p2_vb,p1_vb,cind),_a021_aa(p2_vb,p1_vb,cind)) (_a001_aa(p1_va, p2_va) = -2.0 * _a021_aa(p1_va, p2_va, cind) * _a007(cind), "_a001_aa(p1_va, p2_va) = -2.0 * _a021_aa(p1_va, p2_va, cind) * _a007(cind)") (_a001_aa(p1_va, p2_va) += -1.0 * _a017_aa(p1_va, h2_oa, cind) * chol3d_aa_ov(h2_oa, p2_va, cind), "_a001_aa(p1_va, p2_va) += -1.0 * _a017_aa(p1_va, h2_oa, cind) * chol3d_aa_ov(h2_oa, p2_va, cind)") (_a006_aa(h2_oa, h1_oa) += 1.0 * _a009_aa(h2_oa, h1_oa, cind) * _a007(cind), "_a006_aa(h2_oa, h1_oa) += 1.0 * _a009_aa(h2_oa, h1_oa, cind) * _a007(cind)") (_a006_aa(h3_oa, h1_oa) += -1.0 * _a009_aa(h2_oa, h1_oa, cind) * _a008_aa(h3_oa, h2_oa, cind), "_a006_aa(h3_oa, h1_oa) += -1.0 * _a009_aa(h2_oa, h1_oa, cind) * _a008_aa(h3_oa, h2_oa, cind)") (_a019_abab(h2_oa, h1_ob, h1_oa, h2_ob) = 0.25 * _a009_aa(h2_oa, h1_oa, cind) * _a009_bb(h1_ob, h2_ob, cind), "_a019_abab(h2_oa, h1_ob, h1_oa, h2_ob) = 0.25 * _a009_aa(h2_oa, h1_oa, cind) * _a009_bb(h1_ob, h2_ob, cind)") (_a020_aaaa(p2_va, h2_oa, p1_va, h1_oa) = -2.0 * _a009_aa(h2_oa, h1_oa, cind) * _a021_aa(p2_va, p1_va, cind), "_a020_aaaa(p2_va, h2_oa, p1_va, h1_oa) = -2.0 * _a009_aa(h2_oa, h1_oa, cind) * _a021_aa(p2_va, p1_va, cind)") .exact_copy(_a020_baba(p2_vb, h2_oa, p1_vb, h1_oa),_a020_aaaa(p2_vb, h2_oa, p1_vb, h1_oa)) (_a020_aaaa(p1_va, h3_oa, p3_va, h2_oa) += 0.5 * _a004_aaaa(p2_va, p3_va, h3_oa, h1_oa) * t2_aaaa(p1_va,p2_va,h1_oa,h2_oa), "_a020_aaaa(p1_va, h3_oa, p3_va, h2_oa) += 0.5 * _a004_aaaa(p2_va, p3_va, h3_oa, h1_oa) * t2_aaaa(p1_va,p2_va,h1_oa,h2_oa)") (_a020_baab(p1_vb, h2_oa, p1_va, h2_ob) = -0.5 * _a004_aaaa(p2_va, p1_va, h2_oa, h1_oa) * t2_abab(p2_va,p1_vb,h1_oa,h2_ob), "_a020_baab(p1_vb, h2_oa, p1_va, h2_ob) = -0.5 * _a004_aaaa(p2_va, p1_va, h2_oa, h1_oa) * t2_abab(p2_va,p1_vb,h1_oa,h2_ob)") (_a020_baba(p1_vb, h1_oa, p2_vb, h2_oa) += 0.5 * _a004_abab(p1_va, p2_vb, h1_oa, h1_ob) * t2_abab(p1_va,p1_vb,h2_oa,h1_ob), "_a020_baba(p1_vb, h1_oa, p2_vb, h2_oa) += 0.5 * _a004_abab(p1_va, p2_vb, h1_oa, h1_ob) * t2_abab(p1_va,p1_vb,h2_oa,h1_ob)") (_a017_aa(p1_va, h2_oa, cind) += 1.0 * t1_aa(p1_va, h1_oa) * chol3d_aa_oo(h1_oa, h2_oa, cind), "_a017_aa(p1_va, h2_oa, cind) += 1.0 * t1_aa(p1_va, h1_oa) * chol3d_aa_oo(h1_oa, h2_oa, cind)") (_a017_aa(p1_va, h2_oa, cind) += -1.0 * chol3d_aa_ov(h2_oa, p1_va, cind), "_a017_aa(p1_va, h2_oa, cind) += -1.0 * chol3d_aa_ov(h2_oa, p1_va, cind)") (_a001_aa(p2_va, p1_va) += -1.0 * f1_aa_vv(p2_va, p1_va), "_a001_aa(p2_va, p1_va) += -1.0 * f1_aa_vv(p2_va, p1_va)") (_a006_aa(h2_oa, h1_oa) += 1.0 * f1_aa_oo(h2_oa, h1_oa), "_a006_aa(h2_oa, h1_oa) += 1.0 * f1_aa_oo(h2_oa, h1_oa)") (_a006_aa(h2_oa, h1_oa) += 1.0 * t1_aa(p1_va, h1_oa) * f1_aa_ov(h2_oa, p1_va), "_a006_aa(h2_oa, h1_oa) += 1.0 * t1_aa(p1_va, h1_oa) * f1_aa_ov(h2_oa, p1_va)") .exact_copy(_a017_bb(p1_vb, h1_ob, cind), _a017_aa(p1_vb, h1_ob, cind)) .exact_copy(_a006_bb(h1_ob, h2_ob), _a006_aa(h1_ob, h2_ob)) .exact_copy(_a001_bb(p1_vb, p2_vb), _a001_aa(p1_vb, p2_vb)) .exact_copy(_a021_bb(p1_vb, p2_vb, cind), _a021_aa(p1_vb, p2_vb, cind)) .exact_copy(_a020_bbbb(p1_vb, h1_ob, p2_vb, h2_ob), _a020_aaaa(p1_vb, h1_ob, p2_vb, h2_ob)) (i0_abab(p1_va, p2_vb, h2_oa, h1_ob) = 1.0 * _a020_bbbb(p2_vb, h2_ob, p1_vb, h1_ob) * t2_abab(p1_va, p1_vb, h2_oa, h2_ob), "i0_abab(p1_va, p2_vb, h2_oa, h1_ob) = 1.0 * _a020_bbbb(p2_vb, h2_ob, p1_vb, h1_ob) * t2_abab(p1_va, p1_vb, h2_oa, h2_ob)") (i0_abab(p2_va, p1_vb, h2_oa, h1_ob) += 1.0 * _a020_baab(p1_vb, h1_oa, p1_va, h1_ob) * t2_aaaa(p2_va, p1_va, h2_oa, h1_oa), "i0_abab(p2_va, p1_vb, h2_oa, h1_ob) += 1.0 * _a020_baab(p1_vb, h1_oa, p1_va, h1_ob) * t2_aaaa(p2_va, p1_va, h2_oa, h1_oa)") (i0_abab(p1_va, p1_vb, h2_oa, h1_ob) += 1.0 * _a020_baba(p1_vb, h1_oa, p2_vb, h2_oa) * t2_abab(p1_va, p2_vb, h1_oa, h1_ob), "i0_abab(p1_va, p1_vb, h2_oa, h1_ob) += 1.0 * _a020_baba(p1_vb, h1_oa, p2_vb, h2_oa) * t2_abab(p1_va, p2_vb, h1_oa, h1_ob)") .exact_copy(i0_temp(p1_vb,p1_va,h2_ob,h1_oa),i0_abab(p1_vb,p1_va,h2_ob,h1_oa)) (i0_abab(p1_va, p1_vb, h2_oa, h1_ob) += 1.0 * i0_temp(p1_vb, p1_va, h1_ob, h2_oa), "i0_abab(p1_va, p1_vb, h2_oa, h1_ob) += 1.0 * i0_temp(p1_vb, p1_va, h1_ob, h2_oa)") (i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += 1.0 * _a017_aa(p1_va, h1_oa, cind) * _a017_bb(p1_vb, h2_ob, cind), "i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += 1.0 * _a017_aa(p1_va, h1_oa, cind) * _a017_bb(p1_vb, h2_ob, cind)") (_a022_abab(p1_va,p2_vb,p2_va,p1_vb) = 1.0 * _a021_aa(p1_va,p2_va,cind) * _a021_bb(p2_vb,p1_vb,cind), "_a022_abab(p1_va,p2_vb,p2_va,p1_vb) = 1.0 * _a021_aa(p1_va,p2_va,cind) * _a021_bb(p2_vb,p1_vb,cind)") (i0_abab(p1_va, p2_vb, h1_oa, h2_ob) += 4.0 * _a022_abab(p1_va, p2_vb, p2_va, p1_vb) * t2_abab(p2_va,p1_vb,h1_oa,h2_ob), "i0_abab(p1_va, p2_vb, h1_oa, h2_ob) += 4.0 * _a022_abab(p1_va, p2_vb, p2_va, p1_vb) * t2_abab(p2_va,p1_vb,h1_oa,h2_ob)") (_a019_abab(h2_oa, h1_ob, h1_oa, h2_ob) += 0.25 * _a004_abab(p1_va, p2_vb, h2_oa, h1_ob) * t2_abab(p1_va,p2_vb,h1_oa,h2_ob), "_a019_abab(h2_oa, h1_ob, h1_oa, h2_ob) += 0.25 * _a004_abab(p1_va, p2_vb, h2_oa, h1_ob) * t2_abab(p1_va,p2_vb,h1_oa,h2_ob)") (i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += 4.0 * _a019_abab(h2_oa, h1_ob, h1_oa, h2_ob) * t2_abab(p1_va, p1_vb, h2_oa, h1_ob), "i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += 4.0 * _a019_abab(h2_oa, h1_ob, h1_oa, h2_ob) * t2_abab(p1_va, p1_vb, h2_oa, h1_ob)") (i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += -1.0 * t2_abab(p1_va, p2_vb, h1_oa, h2_ob) * _a001_bb(p1_vb, p2_vb), "i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += -1.0 * t2_abab(p1_va, p2_vb, h1_oa, h2_ob) * _a001_bb(p1_vb, p2_vb)") (i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += -1.0 * t2_abab(p2_va, p1_vb, h1_oa, h2_ob) * _a001_aa(p1_va, p2_va), "i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += -1.0 * t2_abab(p2_va, p1_vb, h1_oa, h2_ob) * _a001_aa(p1_va, p2_va)") (i0_abab(p1_va, p1_vb, h2_oa, h1_ob) += -1.0 * t2_abab(p1_va, p1_vb, h1_oa, h1_ob) * _a006_aa(h1_oa, h2_oa), "i0_abab(p1_va, p1_vb, h2_oa, h1_ob) += -1.0 * t2_abab(p1_va, p1_vb, h1_oa, h1_ob) * _a006_aa(h1_oa, h2_oa)") (i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += -1.0 * t2_abab(p1_va, p1_vb, h1_oa, h1_ob) * _a006_bb(h1_ob, h2_ob), "i0_abab(p1_va, p1_vb, h1_oa, h2_ob) += -1.0 * t2_abab(p1_va, p1_vb, h1_oa, h1_ob) * _a006_bb(h1_ob, h2_ob)") ; } template<typename T> std::tuple<double,double> cd_ccsd_cs_driver(SystemData sys_data, ExecutionContext& ec, const TiledIndexSpace& MO, const TiledIndexSpace& CI, Tensor<T>& t1_aa, Tensor<T>& t2_abab, Tensor<T>& d_f1, Tensor<T>& r1_aa, Tensor<T>& r2_abab, std::vector<Tensor<T>>& d_r1s, std::vector<Tensor<T>>& d_r2s, std::vector<Tensor<T>>& d_t1s, std::vector<Tensor<T>>& d_t2s, std::vector<T>& p_evl_sorted, Tensor<T>& cv3d, bool ccsd_restart=false, std::string out_fp="",bool computeTData=false) { int maxiter = sys_data.options_map.ccsd_options.ccsd_maxiter; int ndiis = sys_data.options_map.ccsd_options.ndiis; double thresh = sys_data.options_map.ccsd_options.threshold; bool writet = sys_data.options_map.ccsd_options.writet; int writet_iter = sys_data.options_map.ccsd_options.writet_iter; double zshiftl = sys_data.options_map.ccsd_options.lshift; bool profile = sys_data.options_map.ccsd_options.profile_ccsd; double residual = 0.0; double energy = 0.0; int niter = 0; const TAMM_SIZE n_occ_alpha = static_cast<TAMM_SIZE>(sys_data.n_occ_alpha); const TAMM_SIZE n_vir_alpha = static_cast<TAMM_SIZE>(sys_data.n_vir_alpha); std::string t1file = out_fp+".t1amp"; std::string t2file = out_fp+".t2amp"; std::cout.precision(15); const TiledIndexSpace &O = MO("occ"); const TiledIndexSpace &V = MO("virt"); auto [cind] = CI.labels<1>("all"); const int otiles = O.num_tiles(); const int vtiles = V.num_tiles(); const int oatiles = MO("occ_alpha").num_tiles(); const int obtiles = MO("occ_beta").num_tiles(); const int vatiles = MO("virt_alpha").num_tiles(); const int vbtiles = MO("virt_beta").num_tiles(); o_alpha = {MO("occ"), range(oatiles)}; v_alpha = {MO("virt"), range(vatiles)}; o_beta = {MO("occ"), range(obtiles,otiles)}; v_beta = {MO("virt"), range(vbtiles,vtiles)}; auto [p1_va, p2_va] = v_alpha.labels<2>("all"); auto [p1_vb, p2_vb] = v_beta.labels<2>("all"); auto [h3_oa, h4_oa] = o_alpha.labels<2>("all"); auto [h3_ob, h4_ob] = o_beta.labels<2>("all"); Tensor<T> d_e{}; t2_aaaa = {{v_alpha,v_alpha,o_alpha,o_alpha},{2,2}}; _a004_aaaa = {{v_alpha,v_alpha,o_alpha,o_alpha},{2,2}}; _a004_abab = {{v_alpha,v_beta,o_alpha,o_beta},{2,2}}; f1_aa_oo = {{o_alpha,o_alpha},{1,1}}; f1_aa_ov = {{o_alpha,v_alpha},{1,1}}; f1_aa_vv = {{v_alpha,v_alpha},{1,1}}; f1_bb_oo = {{o_beta,o_beta},{1,1}}; f1_bb_ov = {{o_beta,v_beta},{1,1}}; f1_bb_vv = {{v_beta,v_beta},{1,1}}; chol3d_aa_oo = {{o_alpha,o_alpha,CI},{1,1}}; chol3d_aa_ov = {{o_alpha,v_alpha,CI},{1,1}}; chol3d_aa_vv = {{v_alpha,v_alpha,CI},{1,1}}; chol3d_bb_oo = {{o_beta,o_beta,CI},{1,1}}; chol3d_bb_ov = {{o_beta,v_beta,CI},{1,1}}; chol3d_bb_vv = {{v_beta,v_beta,CI},{1,1}}; _a01 = {CI}; _a02_aa = {{o_alpha,o_alpha,CI},{1,1}}; _a03_aa = {{o_alpha,v_alpha,CI},{1,1}}; t2_aaaa_temp = {v_alpha,v_alpha,o_alpha,o_alpha}; i0_temp = {v_beta,v_alpha,o_beta,o_alpha}; //Intermediates //T1 _a02 = {CI}; _a01_aa = {{o_alpha,o_alpha,CI},{1,1}}; _a03_aa_vo = {{v_alpha,o_alpha,CI},{1,1}}; _a04_aa = {{o_alpha,o_alpha},{1,1}}; _a05_aa = {{o_alpha,v_alpha},{1,1}}; _a05_bb = {{o_beta,v_beta},{1,1}}; //T2 _a007 = {CI}; _a017_aa = {{v_alpha,o_alpha,CI},{1,1}}; _a017_bb = {{v_beta,o_beta,CI},{1,1}}; _a006_aa = {{o_alpha,o_alpha},{1,1}}; _a006_bb = {{o_beta,o_beta},{1,1}}; _a009_aa = {{o_alpha,o_alpha,CI},{1,1}}; _a009_bb = {{o_beta,o_beta,CI},{1,1}}; _a021_aa = {{v_alpha,v_alpha,CI},{1,1}}; _a021_bb = {{v_beta,v_beta,CI},{1,1}}; _a008_aa = {{o_alpha,o_alpha,CI},{1,1}}; _a001_aa = {{v_alpha,v_alpha},{1,1}}; _a001_bb = {{v_beta,v_beta},{1,1}}; _a019_abab = {{o_alpha,o_beta,o_alpha,o_beta},{2,2}}; _a020_aaaa = {{v_alpha,o_alpha,v_alpha,o_alpha},{2,2}}; _a020_baab = {{v_beta,o_alpha,v_alpha,o_beta},{2,2}}; _a020_baba = {{v_beta,o_alpha,v_beta,o_alpha},{2,2}}; _a020_bbbb = {{v_beta,o_beta,v_beta,o_beta},{2,2}}; _a022_abab = {{v_alpha,v_beta,v_alpha,v_beta},{2,2}}; double total_ccsd_mem = sum_tensor_sizes(t1_aa,t2_abab,d_f1,r1_aa,r2_abab,cv3d, t2_aaaa, f1_aa_oo, f1_aa_ov, f1_aa_vv, f1_bb_oo, f1_bb_ov, f1_bb_vv, chol3d_aa_oo, chol3d_aa_ov, chol3d_aa_vv, chol3d_bb_oo, chol3d_bb_ov, chol3d_bb_vv, _a004_aaaa,_a004_abab, d_e,i0_temp,t2_aaaa_temp,_a01,_a02_aa,_a03_aa); for(size_t ri=0;ri<d_r1s.size();ri++) total_ccsd_mem += sum_tensor_sizes(d_r1s[ri],d_r2s[ri],d_t1s[ri],d_t2s[ri]); //Intermediates double total_ccsd_mem_tmp = sum_tensor_sizes(_a02, _a01_aa,_a03_aa_vo,_a04_aa,_a05_aa,_a05_bb, _a007,_a001_aa,_a001_bb,_a017_aa,_a017_bb, _a006_aa,_a006_bb,_a009_aa,_a009_bb,_a021_aa,_a021_bb,_a008_aa, _a019_abab,_a020_aaaa,_a020_baba, _a020_baab,_a020_bbbb,_a022_abab); if(!ccsd_restart) total_ccsd_mem += total_ccsd_mem_tmp; if(ec.pg().rank()==0) { std::cout << "Total CPU memory required for Closed Shell Cholesky CCSD calculation: " << std::setprecision(5) << total_ccsd_mem << " GiB" << std::endl << std::endl; } Scheduler sch{ec}; sch.allocate(t2_aaaa, f1_aa_oo, f1_aa_ov, f1_aa_vv, f1_bb_oo, f1_bb_ov, f1_bb_vv, chol3d_aa_oo, chol3d_aa_ov, chol3d_aa_vv, chol3d_bb_oo, chol3d_bb_ov, chol3d_bb_vv); sch.allocate(_a004_aaaa,_a004_abab); sch.allocate(d_e,i0_temp,t2_aaaa_temp,_a01,_a02_aa,_a03_aa); sch (chol3d_aa_oo(h3_oa,h4_oa,cind) = cv3d(h3_oa,h4_oa,cind)) (chol3d_aa_ov(h3_oa,p2_va,cind) = cv3d(h3_oa,p2_va,cind)) (chol3d_aa_vv(p1_va,p2_va,cind) = cv3d(p1_va,p2_va,cind)) (chol3d_bb_oo(h3_ob,h4_ob,cind) = cv3d(h3_ob,h4_ob,cind)) (chol3d_bb_ov(h3_ob,p1_vb,cind) = cv3d(h3_ob,p1_vb,cind)) (chol3d_bb_vv(p1_vb,p2_vb,cind) = cv3d(p1_vb,p2_vb,cind)) (f1_aa_oo(h3_oa,h4_oa) = d_f1(h3_oa,h4_oa)) (f1_aa_ov(h3_oa,p2_va) = d_f1(h3_oa,p2_va)) (f1_aa_vv(p1_va,p2_va) = d_f1(p1_va,p2_va)) (f1_bb_oo(h3_ob,h4_ob) = d_f1(h3_ob,h4_ob)) (f1_bb_ov(h3_ob,p1_vb) = d_f1(h3_ob,p1_vb)) (f1_bb_vv(p1_vb,p2_vb) = d_f1(p1_vb,p2_vb)); if(!ccsd_restart) { { //allocate all intermediates sch.allocate(_a02, _a01_aa,_a03_aa_vo,_a04_aa,_a05_aa,_a05_bb); //T1 //T2 sch.allocate(_a007,_a001_aa,_a001_bb,_a017_aa,_a017_bb, _a006_aa,_a006_bb,_a009_aa,_a009_bb,_a021_aa,_a021_bb,_a008_aa, _a019_abab,_a020_aaaa,_a020_baba, _a020_baab,_a020_bbbb,_a022_abab ); sch.execute(); } sch (r1_aa() = 0) (r2_abab() = 0) (_a004_aaaa(p1_va, p2_va, h4_oa, h3_oa) = 1.0 * chol3d_aa_ov(h4_oa, p1_va, cind) * chol3d_aa_ov(h3_oa, p2_va, cind)) .exact_copy(_a004_abab(p1_va, p1_vb, h3_oa, h3_ob), _a004_aaaa(p1_va, p1_vb, h3_oa, h3_ob)) ; #ifdef USE_TALSH sch.execute(ExecutionHW::GPU); #else sch.execute(); #endif Tensor<T> d_r1_residual{}, d_r2_residual{}; Tensor<T>::allocate(&ec,d_r1_residual, d_r2_residual); for(int titer = 0; titer < maxiter; titer += ndiis) { for(int iter = titer; iter < std::min(titer + ndiis, maxiter); iter++) { const auto timer_start = std::chrono::high_resolution_clock::now(); niter = iter; int off = iter - titer; sch ((d_t1s[off])() = t1_aa()) ((d_t2s[off])() = t2_abab()) .execute(); ccsd_e_cs(/* ec, */sch, MO, CI, d_e, t1_aa, t2_abab); ccsd_t1_cs(/* ec, */sch, MO, CI, r1_aa, t1_aa, t2_abab); ccsd_t2_cs(/* ec, */sch, MO, CI, r2_abab, t1_aa, t2_abab); #ifdef USE_TALSH sch.execute(ExecutionHW::GPU, profile); #else sch.execute(ExecutionHW::CPU, profile); #endif std::tie(residual, energy) = rest_cs(ec, MO, r1_aa, r2_abab, t1_aa, t2_abab, d_e, d_r1_residual, d_r2_residual, p_evl_sorted, zshiftl, n_occ_alpha, n_vir_alpha); update_r2(ec, r2_abab()); sch((d_r1s[off])() = r1_aa()) ((d_r2s[off])() = r2_abab()) .execute(); const auto timer_end = std::chrono::high_resolution_clock::now(); auto iter_time = std::chrono::duration_cast<std::chrono::duration<double>>((timer_end - timer_start)).count(); iteration_print(sys_data, ec.pg(), iter, residual, energy, iter_time); if(writet && ( ((iter+1)%writet_iter == 0) || (residual < thresh) ) ) { write_to_disk(t1_aa,t1file); write_to_disk(t2_abab,t2file); } if(residual < thresh) { break; } } if(residual < thresh || titer + ndiis >= maxiter) { break; } if(ec.pg().rank() == 0) { std::cout << " MICROCYCLE DIIS UPDATE:"; std::cout.width(21); std::cout << std::right << std::min(titer + ndiis, maxiter) + 1; std::cout.width(21); std::cout << std::right << "5" << std::endl; } std::vector<std::vector<Tensor<T>>> rs{d_r1s, d_r2s}; std::vector<std::vector<Tensor<T>>> ts{d_t1s, d_t2s}; std::vector<Tensor<T>> next_t{t1_aa, t2_abab}; diis<T>(ec, rs, ts, next_t); } if(profile) { std::string profile_csv = out_fp + "_profile.csv"; std::ofstream pds(profile_csv, std::ios::out); if(!pds) std::cerr << "Error opening file " << profile_csv << std::endl; std::string header = "ID;Level;OP;total_op_time_min;total_op_time_max;total_op_time_avg;"; header += "get_time_min;get_time_max;get_time_avg;gemm_time_min;"; header += "gemm_time_max;gemm_time_avg;acc_time_min;acc_time_max;acc_time_avg"; pds << header << std::endl; pds << ec.get_profile_data().str() << std::endl; pds.close(); } //deallocate all intermediates sch.deallocate(_a02, _a01_aa,_a03_aa_vo,_a04_aa,_a05_aa,_a05_bb); sch.deallocate(_a007,_a001_aa,_a001_bb,_a017_aa,_a017_bb, _a006_aa,_a006_bb,_a009_aa,_a009_bb,_a021_aa,_a021_bb,_a008_aa, _a019_abab,_a020_aaaa,_a020_baba, _a020_baab,_a020_bbbb,_a022_abab ); //t2 sch.deallocate(d_r1_residual, d_r2_residual); } //no restart else { ccsd_e_cs(/* ec, */sch, MO, CI, d_e, t1_aa, t2_abab); #ifdef USE_TALSH sch.execute(ExecutionHW::GPU, profile); #else sch.execute(ExecutionHW::CPU, profile); #endif energy = get_scalar(d_e); residual = 0.0; } sys_data.ccsd_corr_energy = energy; if(ec.pg().rank() == 0) { sys_data.results["output"]["CCSD"]["n_iterations"] = niter+1; sys_data.results["output"]["CCSD"]["final_energy"]["correlation"] = energy; sys_data.results["output"]["CCSD"]["final_energy"]["total"] = sys_data.scf_energy+energy; write_json_data(sys_data,"CCSD"); } sch.deallocate(i0_temp,t2_aaaa_temp,_a01,_a02_aa,_a03_aa); sch.deallocate(d_e,_a004_aaaa,_a004_abab); sch.deallocate(f1_aa_oo, f1_aa_ov, f1_aa_vv, f1_bb_oo, f1_bb_ov, f1_bb_vv, chol3d_aa_oo, chol3d_aa_ov, chol3d_aa_vv, chol3d_bb_oo, chol3d_bb_ov, chol3d_bb_vv).execute(); if(computeTData) { Tensor<T> d_t1 = dt1_full; Tensor<T> d_t2 = dt2_full; IndexVector perm1 = {1,0,3,2}; IndexVector perm2 = {0,1,3,2}; IndexVector perm3 = {1,0,2,3}; t1_bb = Tensor<T>{{v_beta,o_beta} ,{1,1}}; t2_bbbb = Tensor<T>{{v_beta,v_beta, o_beta,o_beta} ,{2,2}}; t2_baba = Tensor<T>{{v_beta,v_alpha,o_beta,o_alpha} ,{2,2}}; t2_abba = Tensor<T>{{v_alpha,v_beta,o_beta,o_alpha} ,{2,2}}; t2_baab = Tensor<T>{{v_beta,v_alpha,o_alpha,o_beta} ,{2,2}}; sch.allocate(t1_bb,t2_bbbb,t2_baba,t2_abba,t2_baab) .exact_copy(t1_bb(p1_vb,h3_ob), t1_aa(p1_vb,h3_ob)) .exact_copy(t2_bbbb(p1_vb,p2_vb,h3_ob,h4_ob), t2_aaaa(p1_vb,p2_vb,h3_ob,h4_ob)).execute(); // .exact_copy(t2_baba(p1_vb,p2_va,h3_ob,h4_oa), t2_abab(p1_vb,p2_va,h3_ob,h4_oa),true,1.0,perm) // .exact_copy(t2_abba(p1_va,p2_vb,h3_ob,h4_oa), t2_abab(p1_va,p2_vb,h3_ob,h4_oa),true,-1.0) // .exact_copy(t2_baab(p1_vb,p2_va,h3_oa,h4_ob), t2_abab(p1_vb,p2_va,h3_oa,h4_ob),true,-1.0) sch.exact_copy(t2_baba,t2_abab,true, 1.0,perm1); sch.exact_copy(t2_abba,t2_abab,true,-1.0,perm2); sch.exact_copy(t2_baab,t2_abab,true,-1.0,perm3); sch(d_t1(p1_va,h3_oa) = t1_aa(p1_va,h3_oa)) (d_t1(p1_vb,h3_ob) = t1_bb(p1_vb,h3_ob)) (d_t2(p1_va,p2_va,h3_oa,h4_oa) = t2_aaaa(p1_va,p2_va,h3_oa,h4_oa)) (d_t2(p1_va,p2_vb,h3_oa,h4_ob) = t2_abab(p1_va,p2_vb,h3_oa,h4_ob)) (d_t2(p1_vb,p2_vb,h3_ob,h4_ob) = t2_bbbb(p1_vb,p2_vb,h3_ob,h4_ob)) (d_t2(p1_vb,p2_va,h3_ob,h4_oa) = t2_baba(p1_vb,p2_va,h3_ob,h4_oa)) (d_t2(p1_va,p2_vb,h3_ob,h4_oa) = t2_abba(p1_va,p2_vb,h3_ob,h4_oa)) (d_t2(p1_vb,p2_va,h3_oa,h4_ob) = t2_baab(p1_vb,p2_va,h3_oa,h4_ob)) .deallocate(t1_bb,t2_bbbb,t2_baba,t2_abba,t2_baab) .execute(); } sch.deallocate(t2_aaaa).execute(); return std::make_tuple(residual,energy); }
54.90785
142
0.583696
[ "vector" ]
584fa0d62a51ca347b13a08aa0f657873b74a5c1
2,169
cpp
C++
python/biograph/variants/apply_edges.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
16
2021-07-14T23:32:31.000Z
2022-03-24T16:25:15.000Z
python/biograph/variants/apply_edges.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-20T20:39:47.000Z
2021-09-16T20:57:59.000Z
python/biograph/variants/apply_edges.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-15T19:38:35.000Z
2022-01-31T19:24:56.000Z
#include "python/biograph/variants/apply_edges.h" #include "python/biograph/variants/assembly.h" #include "python/biograph/variants/par_pipeline.h" #include "python/common.h" using namespace pybind11; using namespace variants; class __attribute__((visibility("hidden"))) apply_edges_py : public apply_edges_step { public: apply_edges_py(pipeline_step_t output, object on_assembly_edges) : apply_edges_step(std::move(output)), m_on_assembly_edges(on_assembly_edges) {} ~apply_edges_py() { flush(); }; void on_assembly_edges(optional_aoffset reference_pos, const std::vector<assembly_ptr>& left_edges, const std::vector<assembly_ptr>& inserts, const std::vector<assembly_ptr>& right_edges) override { gil_scoped_acquire gil; m_on_assembly_edges(reference_pos, left_edges, inserts, right_edges); } private: object m_on_assembly_edges; }; class __attribute__((visibility("hidden"))) apply_edges_generator : public par_asm_pipeline_wrapper { public: apply_edges_generator(object input, object on_assembly_edges); void init(); void on_input(assembly_ptr a) override; void on_input_done() override; private: object m_on_assembly_edges; std::unique_ptr<apply_edges_py> m_apply_edges; }; apply_edges_generator::apply_edges_generator(object input, object on_assembly_edges) : par_asm_pipeline_wrapper(input), m_on_assembly_edges(on_assembly_edges) {} void apply_edges_generator::init() { m_apply_edges.reset(new apply_edges_py(make_pipeline_output(), m_on_assembly_edges)); } void apply_edges_generator::on_input(assembly_ptr a) { m_apply_edges->add(std::move(a)); } void apply_edges_generator::on_input_done() { m_apply_edges.reset(); } void bind_apply_edges(module& m) { define_pipeline_generator<apply_edges_generator, object /* input */, object /* on_assembly_edges */>(m, "apply_edges", "ApplyEdgesGenerator", arg("input"), arg("on_assembly_edges"), R"DOC(how does this work?)DOC"); }
36.15
100
0.701706
[ "object", "vector" ]
5850ed757b33ade2ea6d2ef7bff956b2f53d61b6
8,804
hpp
C++
src/alignment/core/impl/BasicAlignmentContainer.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
9
2016-09-30T05:44:35.000Z
2020-09-03T19:40:06.000Z
src/alignment/core/impl/BasicAlignmentContainer.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
10
2017-05-05T14:55:16.000Z
2022-01-24T18:21:51.000Z
src/alignment/core/impl/BasicAlignmentContainer.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
1
2020-12-05T21:33:27.000Z
2020-12-05T21:33:27.000Z
/***************************************************************************** * * * PLAST : Parallel Local Alignment Search Tool * * Version 2.3, released November 2015 * * Copyright (c) 2009-2015 Inria-Cnrs-Ens * * * * PLAST is free software; you can redistribute it and/or modify it under * * the Affero GPL ver 3 License, that is compatible with the GNU General * * Public License * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * Affero GPL ver 3 License for more details. * *****************************************************************************/ /** \file BasicAlignmentContainer.hpp * \brief Implementation of IAlignmentContainer * \date 07/11/2011 * \author edrezen */ #ifndef _BASIC_ALIGNMENT_CONTAINER_HPP_ #define _BASIC_ALIGNMENT_CONTAINER_HPP_ /********************************************************************************/ #include <alignment/core/impl/AbstractAlignmentContainer.hpp> #include <map> /********************************************************************************/ namespace alignment { namespace core { namespace impl { /********************************************************************************/ /** \brief Default implementation of IAlignmentContainer interface for gap alignments * * This implementation stores information in three hierarchical levels: * - 1) query level * - 2) subject level * - 3) alignment level * * The purpose here is to store the information in an efficient way both in terms of * - memory * - speed for inserting/accessing information. * * The insertion of a new item (ie. an Alignment instance) is done as follow: * - 1) we look for the query node matching the query of the alignment to be inserted. * If no query sequence node is found, a new one is added. * - 2) we look for the subject node matching the subject of the alignment to be inserted. * If no subject sequence node is found, a new one is added. * - 3) having found (or created) a couple [query node, subject node], we check that the * alignment to be inserted doesn't already exist (through isInContainer method). * * This scheme means that we have 3 searches before inserting an alignment: * - search at query level (level 1) * - search at subject level (level 2) * - search at alignment level (level 3) * * The concern is then to minimize the searching time. We use therefore for levels 1 and 2 * std::map structures whose 'find' method has a logarithmic complexity in size. * * The level 3 is a simple std::list which is surely not the best choice: indeed, our * 'isInContainer' method is the corresponding 'find' method with a specific sort criteria, * so the complexity is roughly linear. It is mainly due to historical design concerns about * the visitor interface of IAlignmentContainer instances had to provide a list of Alignments * (see IAlignmentContainerVisitor::visitAlignment method). * * This point can be an issue when many alignments can be found for one sequences couple * [query,subject], which can be the case when using option -max-database-size with a huge * value on huge databases. An improvement would be to modify the visitor API by providing * an iterator instead of the list itself, and so we could also use search-optimized structure. * Note however that it would be tricky because of some visitors implementations that are allowed * to modify the alignments list they receive (like shrinker visitors). */ class BasicAlignmentContainer : public AbstractAlignmentContainer { public: /** Constructor. */ BasicAlignmentContainer (size_t nbHitPerQuery=0, size_t nbHspPerHit=0); /** Desctructor. */ ~BasicAlignmentContainer (); /** \copydoc AbstractAlignmentContainer::doesExist(const Alignment&) */ bool doesExist (const Alignment& align); /** \copydoc AbstractAlignmentContainer::doesExist */ bool doesExist ( const indexation::ISeedOccurrence* subjectOccur, const indexation::ISeedOccurrence* queryOccur, u_int32_t bandSize ); /** \copydoc AbstractAlignmentContainer::insertFirstLevel */ bool insertFirstLevel (const database::ISequence* sequence); /** \copydoc IAlignmentResult::doesFirstLevelExists */ bool doesFirstLevelExists (const database::ISequence* sequence); /** \copydoc AbstractAlignmentContainer::getFirstLevelNumber */ u_int32_t getFirstLevelNumber () { return _containerLevel1.size(); } /** \copydoc IAlignmentContainer::getSecondLevelNumber */ u_int32_t getSecondLevelNumber (); /** \copydoc AbstractAlignmentContainer::insert(Alignment&,void*) */ bool insert (Alignment& align, void* context); /** \copydoc AbstractAlignmentContainer::merge */ void merge (const std::vector<IAlignmentContainer*> containers); /** \copydoc AbstractAlignmentContainer::accept */ void accept (IAlignmentContainerVisitor* visitor); /** \copydoc AbstractAlignmentContainer::shrink */ void shrink (); /** \copydoc AbstractAlignmentContainer::getContainer */ std::list<Alignment>* getContainer ( const database::ISequence* seqLevel1, const database::ISequence* seqLevel2 ); protected: typedef std::list<Alignment> ContainerLevel3; /** Define a key for the maps. Note that a sequence is identified both by its id and its * containing database. It is important for composite databases (like 6 reading frames * databases) where one can have several distinct sequences with the same id but belonging * to distinct databases. */ typedef std::pair <database::ISequenceDatabase*, u_int32_t> Key; typedef std::pair<database::ISequence*,ContainerLevel3*> ValueLevel2; typedef std::map <Key, ValueLevel2> ContainerLevel2; typedef std::pair<database::ISequence*,ContainerLevel2*> ValueLevel1; typedef std::map <Key, ValueLevel1> ContainerLevel1; ContainerLevel1 _containerLevel1; /** */ virtual bool isInContainer ( ContainerLevel3* container, const misc::Range32& sbjRange, const misc::Range32& qryRange, char delta = 0 ) { bool found = false; if (container != 0) { for (ContainerLevel3::iterator it = container->begin(); !found && it != container->end(); it++) { found = (*it).getRange(Alignment::SUBJECT).includes (sbjRange,delta) && (*it).getRange(Alignment::QUERY).includes (qryRange,delta); } } return found; } u_int32_t _nbSeqLevel1; u_int32_t _nbSeqLevel2; /** */ size_t _nbHitPerQuery; size_t _nbHspPerHit; /** */ friend struct SortHitsFunctor; }; /********************************************************************************/ /** \brief Default implementation of IAlignmentContainer interface for gap alignments * * It inherits from BasicAlignmentContainer. * * There are two differences between these classes: * - we don't need any synchronization in this class (we do it by deleting the synchronizer in the constructor) * - the isInContainer always returns false here (ie. we accept all alignments). * * About the second point, this should be improved by removing redundant alignments having same anchoring bounds * (see what blast does in this case). */ class BasicAlignmentContainerBis : public BasicAlignmentContainer { public: /** Constructor. */ BasicAlignmentContainerBis (size_t nbHitPerQuery, size_t nbHspPerHit) : BasicAlignmentContainer (nbHitPerQuery, nbHspPerHit) { if (_synchro != 0) { delete _synchro; _synchro=0;} } protected: /** */ virtual bool isInContainer ( ContainerLevel3* container, const misc::Range32& sbjRange, const misc::Range32& qryRange, char delta = 0 ) { return false; } }; /********************************************************************************/ }}} /* end of namespaces. */ /********************************************************************************/ #endif /* _BASIC_ALIGNMENT_CONTAINER_HPP_ */
40.200913
114
0.614153
[ "vector" ]
58553133a39b4fc91aae2a862cfba651643523dc
3,744
cpp
C++
src/tex_op/to_worley.cpp
cewbost/texgen
f572ea5590457f37b72286c50c020eee25bddc78
[ "MIT" ]
null
null
null
src/tex_op/to_worley.cpp
cewbost/texgen
f572ea5590457f37b72286c50c020eee25bddc78
[ "MIT" ]
null
null
null
src/tex_op/to_worley.cpp
cewbost/texgen
f572ea5590457f37b72286c50c020eee25bddc78
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdlib> #include "to_common.h" #include "../tex_op.h" #include "../worley.h" namespace { float _distFunc(float x, float y) { return std::sqrt(x * x + y * y); } using Map = Worley<float, _distFunc, 4>; template<int mask, int oct> void _writeSDFMapWorker(Texture* dest, Map& map, float range, int from, int to) { int x_offset, y_offset; map.getResolution(&x_offset, &y_offset); x_offset /= 4; y_offset /= 4; for(int y = from; y < to; ++y) { for(int x = 0; x < (int)dest->width; ++x) { float read = map.get<oct>(x + x_offset, y + y_offset) / range; if(read > 1.) read = 1.; if(mask & 1) dest->get(x, y)[0] = read; if(mask & 2) dest->get(x, y)[1] = read; if(mask & 4) dest->get(x, y)[2] = read; if(mask & 8) dest->get(x, y)[3] = read; } } } template<int oct> void _writeSDFMapHelper( int mask, Texture* dest, Map& map, float range, int from, int to) { switch(mask) { case 0x1: _writeSDFMapWorker<0x1, oct>(dest, map, range, from, to); break; case 0x2: _writeSDFMapWorker<0x2, oct>(dest, map, range, from, to); break; case 0x3: _writeSDFMapWorker<0x3, oct>(dest, map, range, from, to); break; case 0x4: _writeSDFMapWorker<0x4, oct>(dest, map, range, from, to); break; case 0x5: _writeSDFMapWorker<0x5, oct>(dest, map, range, from, to); break; case 0x6: _writeSDFMapWorker<0x6, oct>(dest, map, range, from, to); break; case 0x7: _writeSDFMapWorker<0x7, oct>(dest, map, range, from, to); break; case 0x8: _writeSDFMapWorker<0x8, oct>(dest, map, range, from, to); break; case 0x9: _writeSDFMapWorker<0x9, oct>(dest, map, range, from, to); break; case 0xa: _writeSDFMapWorker<0xa, oct>(dest, map, range, from, to); break; case 0xb: _writeSDFMapWorker<0xb, oct>(dest, map, range, from, to); break; case 0xc: _writeSDFMapWorker<0xc, oct>(dest, map, range, from, to); break; case 0xd: _writeSDFMapWorker<0xd, oct>(dest, map, range, from, to); break; case 0xe: _writeSDFMapWorker<0xe, oct>(dest, map, range, from, to); break; case 0xf: _writeSDFMapWorker<0xf, oct>(dest, map, range, from, to); break; } } void _writeSDFMap(Texture* dest, Map& map, std::array<int, 4>& mask, float range, int from, int to) { //channel masks per octave int oct_masks[4] = {0, 0, 0, 0}; for(int i = 0; i < 4; ++i) if(mask[i] != 0) oct_masks[mask[i] - 1] |= (1 << i); if(oct_masks[0] != 0) _writeSDFMapHelper<0>(oct_masks[0], dest, map, range, from, to); if(oct_masks[1] != 0) _writeSDFMapHelper<1>(oct_masks[1], dest, map, range, from, to); if(oct_masks[2] != 0) _writeSDFMapHelper<2>(oct_masks[2], dest, map, range, from, to); if(oct_masks[3] != 0) _writeSDFMapHelper<3>(oct_masks[3], dest, map, range, from, to); } } namespace TexOp { void makeCellNoise(Texture* tex, std::vector<std::pair<double, double>>& point_set, float range, std::array<int, 4>& mask) { //create the map Map map(tex->width * 2, tex->height * 2); for(auto& point: point_set) { double x = point.first * tex->width; double y = point.second * tex->height; map.insertPoint(x, y); map.insertPoint(x + tex->width, y); map.insertPoint(x, y + tex->height); map.insertPoint(x + tex->width, y + tex->height); } map.generateDistances(); if(range > 0) range *= tex->width < tex->height? tex->width : tex->height; else range = -range; //writing operations _launchThreads(tex->height, _writeSDFMap, tex, std::ref(map), std::ref(mask), range); } }
33.132743
89
0.597222
[ "vector" ]
58564da29be9bdd13b52e766782bc82750ec2091
571
cpp
C++
AtCoder/RandomProblem/4Adjacent.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2017-10-25T13:33:27.000Z
2017-10-25T13:33:27.000Z
AtCoder/RandomProblem/4Adjacent.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
null
null
null
AtCoder/RandomProblem/4Adjacent.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2018-01-22T08:06:11.000Z
2018-01-22T08:06:11.000Z
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; typedef set<int> si; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; int t; map<int, int> m; cin >> n; while (n--) { cin >> t; if (t % 4 == 0) m[4]++; else if (t & 1) m[1]++; else m[2]++; } if (m[1] <= m[4] || (m[1] <= m[4] + 1 && !m[2])) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
16.794118
50
0.511384
[ "vector" ]
5857951bf0c82ea2663f7fa252f59be325d39026
26,461
cpp
C++
ortc/services/cpp/services_RUDPPacket.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2016-10-12T09:16:32.000Z
2016-10-13T03:49:47.000Z
ortc/services/cpp/services_RUDPPacket.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2017-11-24T09:18:45.000Z
2017-11-24T09:20:53.000Z
ortc/services/cpp/services_RUDPPacket.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2014, Hookflash Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <ortc/services/RUDPPacket.h> #include <ortc/services/IHelper.h> #include <zsLib/Exception.h> #include <zsLib/Stringize.h> #if (defined _LINUX || defined __QNX__) #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #endif //_LINUX #define ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES (12) namespace ortc { namespace services { ZS_DECLARE_SUBSYSTEM(ortc_services_rudp) } } namespace ortc { namespace services { using zsLib::string; namespace internal { //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark (helpers) #pragma mark //----------------------------------------------------------------------- String convertToHex(const BYTE *buffer, size_t bufferLengthInBytes); //----------------------------------------------------------------------- static size_t dwordBoundary(size_t length) { if (0 == (length % sizeof(DWORD))) return length; return length + (sizeof(DWORD) - (length % sizeof(DWORD))); } static QWORD getNumberWithHint(DWORD number, QWORD hint) { number &= 0xFFFFFF; // only 24 bits are valid #if UINT_MAX <= 0xFFFFFFFF QWORD temp = 1; temp = (temp << 48)-1; temp = (temp << 24); QWORD upper = (hint & temp); #else QWORD upper = (hint & 0xFFFFFFFFFF000000); #endif QWORD merged = (upper | ((QWORD)number)); if (merged < hint) { // two possibe - because it is in fact a lower or because it should have wrapped QWORD higher = ((upper + 0x1000000) | ((QWORD)number)); QWORD diff1 = higher - hint; QWORD diff2 = hint - merged; // which ever is closer to the hint is likely to be the correct value return (diff1 < diff2 ? higher : merged); } // merged is higher, but maybe it should be lower because it wrapped... if (upper < 0x1000000) return merged; // could not have wrapped if the upper isn't beyond 24 bits in size QWORD lower = ((upper - 0x1000000) | ((QWORD)number)); QWORD diff1 = hint - lower; QWORD diff2 = merged - hint; // which ever is closer to the hint value is likely to be the correct value return (diff1 < diff2 ? lower : merged); } //----------------------------------------------------------------------- static bool logicalXOR(bool value1, bool value2) { return (0 != ((value1 ? 1 : 0) ^ (value2 ? 1 : 0))); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark RUDPPacket #pragma mark //------------------------------------------------------------------------- RUDPPacketPtr RUDPPacket::create() { RUDPPacketPtr pThis(make_shared<RUDPPacket>()); pThis->mLogObject = NULL; pThis->mLogObjectID = 0; pThis->mChannelNumber = 0; pThis->mSequenceNumber = 0; pThis->mFlags = 0; pThis->mGSNR = 0; pThis->mGSNFR = 0; pThis->mVectorFlags = 0; pThis->mVectorLengthInBytes = 0; memset(&(pThis->mVector[0]), 0, sizeof(pThis->mVector)); pThis->mData = NULL; pThis->mDataLengthInBytes = 0; return pThis; } //------------------------------------------------------------------------- RUDPPacketPtr RUDPPacket::clone() { RUDPPacketPtr pThis(make_shared<RUDPPacket>()); pThis->mLogObject = mLogObject; pThis->mLogObjectID = mLogObjectID; pThis->mChannelNumber = mChannelNumber; pThis->mSequenceNumber = mSequenceNumber; pThis->mFlags = mFlags; pThis->mGSNR = mGSNR; pThis->mGSNFR = mGSNFR; pThis->mVectorFlags = mVectorFlags; pThis->mVectorLengthInBytes = mVectorLengthInBytes; memcpy(&(pThis->mVector[0]), &(mVector[0]), sizeof(pThis->mVector)); pThis->mData = mData; pThis->mDataLengthInBytes = mDataLengthInBytes; return pThis; } //------------------------------------------------------------------------- RUDPPacketPtr RUDPPacket::parseIfRUDP( const BYTE *packet, size_t packetLengthInBytes ) { ZS_THROW_INVALID_USAGE_IF(!packet) if (packetLengthInBytes < ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES) return RUDPPacketPtr(); // does not meet the minimum size expectations so it can't be RUDP WORD channelNumber = IHelper::getBE16(&(((WORD *)packet)[0])); if ((channelNumber < LegalChannelNumber_StartRange) || (channelNumber > LegalChannelNumber_EndRange)) { ZS_LOG_INSANE(Log::Params("not RUDP packet as not within legal channel range", "RUDPPacket") + ZS_PARAM("channel", channelNumber)) return RUDPPacketPtr(); } WORD dataLength = IHelper::getBE16(&(((WORD *)packet)[1])); BYTE flags = packet[sizeof(WORD)+sizeof(WORD)]; DWORD sequenceNumber = IHelper::getBE32(&(((DWORD *)packet)[1])) & 0xFFFFFF; // lower 24bits are valid only DWORD gsnr = IHelper::getBE32(&(((DWORD *)packet)[2])) & 0xFFFFFF; // lower 24bits are valid only DWORD gsnfr = gsnr; BYTE vectorSize = 0; BYTE vectorFlags = 0; bool eqFlag = (0 != (flags & Flag_EQ_GSNREqualsGSNFR)); if (!eqFlag) { if (packetLengthInBytes < ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + sizeof(DWORD)) return RUDPPacketPtr(); // does not meet the minimum size expectations so it can't be RUDP vectorSize = (packet[sizeof(DWORD)*3]) & (0x7F); vectorFlags = (packet[sizeof(DWORD)*3]) & (0x80); gsnfr = IHelper::getBE32(&(((DWORD *)packet)[3])) & 0xFFFFFF; // lower 24bits are valid only } // has to have enough room to contain vector, extended header and all data if (packetLengthInBytes < ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + ((!eqFlag) ? sizeof(DWORD) : 0) + internal::dwordBoundary(vectorSize) + ((size_t)dataLength)) return RUDPPacketPtr(); // does not meet the minimum size expectations so it can't be RUDP // this appears to be RUDP RUDPPacketPtr pThis = create(); pThis->mChannelNumber = channelNumber; pThis->mSequenceNumber = sequenceNumber; pThis->mFlags = flags; pThis->mGSNR = gsnr; pThis->mGSNFR = gsnfr; pThis->mVectorFlags = vectorFlags; pThis->mVectorLengthInBytes = vectorSize; if (0 != vectorSize) { memcpy(&(pThis->mVector[0]), &(packet[sizeof(DWORD)*4]), vectorSize); } if (0 != dataLength) { pThis->mData = &(packet[ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + ((!eqFlag) ? sizeof(DWORD) : 0) + internal::dwordBoundary(vectorSize)]); pThis->mDataLengthInBytes = dataLength; } pThis->log(Log::Trace, "parse"); return pThis; } //------------------------------------------------------------------------- SecureByteBlockPtr RUDPPacket::packetize() const { log(Log::Trace, "packetize"); ZS_THROW_BAD_STATE_IF(mDataLengthInBytes > 0xFFFF) bool eqFlag = (0 != (mFlags & Flag_EQ_GSNREqualsGSNFR)); ZS_THROW_BAD_STATE_IF(eqFlag && ((mGSNR & 0xFFFFFF) != (mGSNFR & 0xFFFFFF))) // they must match if the EQ flag is set to true or this is illegal size_t length = ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + ((!eqFlag) ? sizeof(DWORD) : 0) + internal::dwordBoundary(mVectorLengthInBytes) + mDataLengthInBytes; SecureByteBlockPtr outBuffer(make_shared<SecureByteBlock>(length)); BYTE *packet = *outBuffer; memset(packet, 0, length); // make sure to set the entire packet to "0" so all defaults are appropriately set // put in channel number and length IHelper::setBE16(&(((WORD *)packet)[0]), mChannelNumber); IHelper::setBE16(&(((WORD *)packet)[1]), mDataLengthInBytes); IHelper::setBE32(&(((DWORD *)packet)[1]), mSequenceNumber & 0xFFFFFF); IHelper::setBE32(&((packet[sizeof(DWORD)])), mFlags); IHelper::setBE32(&(((DWORD *)packet)[2]), mGSNR & 0xFFFFFF); if (!eqFlag) { IHelper::setBE32(&(((DWORD *)packet)[3]), mGSNFR & 0xFFFFFF); ZS_THROW_BAD_STATE_IF(mVectorLengthInBytes > 0x7F) // can only have from 0..127 bytes in the vector maximum (packet[sizeof(DWORD)*3]) = (mVectorLengthInBytes & 0x7F); (packet[sizeof(DWORD)*3]) = (packet[sizeof(DWORD)*3]) | (mVectorFlags & 0x80); // add the vector parity flag // copy in the vector if it is present if (0 != mVectorLengthInBytes) { ZS_THROW_BAD_STATE_IF(mVectorLengthInBytes > 0x7F) // this is illegal memcpy(&(packet[ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + sizeof(DWORD)]), &(mVector[0]), mVectorLengthInBytes); } } if (0 != mDataLengthInBytes) { ZS_THROW_BAD_STATE_IF(NULL == mData) // cannot have set a length but forgot to specify the pointer memcpy(&(packet[ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + ((!eqFlag) ? sizeof(DWORD) : 0) + internal::dwordBoundary(mVectorLengthInBytes)]), &(mData[0]), mDataLengthInBytes); } return outBuffer; } //------------------------------------------------------------------------- bool RUDPPacket::isFlagSet(Flags flag) const { return (flag == (mFlags & flag)); } //------------------------------------------------------------------------- bool RUDPPacket::isFlagSet(VectorFlags flag) const { return (flag == (mVectorFlags & flag)); } //------------------------------------------------------------------------- void RUDPPacket::setFlag(Flags flag) { mFlags |= flag; } //------------------------------------------------------------------------- void RUDPPacket::setFlag(VectorFlags flag) { mVectorFlags |= flag; } //------------------------------------------------------------------------- void RUDPPacket::setFlag(Flags flag, bool on) { if (on) setFlag(flag); else clearFlag(flag); } //------------------------------------------------------------------------- void RUDPPacket::setFlag(VectorFlags flag, bool on) { if (on) setFlag(flag); else clearFlag(flag); } //------------------------------------------------------------------------- void RUDPPacket::clearFlag(Flags flag) { mFlags = (mFlags & (0xFF ^ flag)); } //------------------------------------------------------------------------- void RUDPPacket::clearFlag(VectorFlags flag) { mVectorFlags = (mVectorFlags & (0xFF ^ flag)); } //------------------------------------------------------------------------- QWORD RUDPPacket::getSequenceNumber(QWORD hintLastSequenceNumber) const { return internal::getNumberWithHint(mSequenceNumber, hintLastSequenceNumber); } //------------------------------------------------------------------------- QWORD RUDPPacket::getGSNR(QWORD hintLastGSNR) const { return internal::getNumberWithHint(mGSNR, hintLastGSNR); } //------------------------------------------------------------------------- QWORD RUDPPacket::getGSNFR(QWORD hintLastGSNFR) const { return internal::getNumberWithHint(mGSNFR, hintLastGSNFR); } //------------------------------------------------------------------------- void RUDPPacket::setSequenceNumber(QWORD sequenceNumber) { mSequenceNumber = ((DWORD)(sequenceNumber & 0xFFFFFF)); } //------------------------------------------------------------------------- void RUDPPacket::setGSN( QWORD gsnr, QWORD gsnfr ) { // if they are equal then we need to set the EQ flag if (gsnr == gsnfr) setFlag(Flag_EQ_GSNREqualsGSNFR); else clearFlag(Flag_EQ_GSNREqualsGSNFR); mGSNR = ((DWORD)(gsnr & 0xFFFFFF)); mGSNFR = ((DWORD)(gsnfr & 0xFFFFFF)); } size_t RUDPPacket::getRoomAvailableForData(size_t maxPacketLengthInBytes) const { bool eqFlag = (0 != (mFlags & Flag_EQ_GSNREqualsGSNFR)); ZS_THROW_BAD_STATE_IF(eqFlag & ((mGSNR & 0xFFFFFF) != (mGSNFR & 0xFFFFFF))) // they must match if the EQ flag is set to true or this is illegal size_t length = ORTC_SERVICES_MINIMUM_PACKET_LENGTH_IN_BYTES + ((!eqFlag) ? sizeof(DWORD) : 0) + internal::dwordBoundary(mVectorLengthInBytes); if (length > maxPacketLengthInBytes) return 0; return maxPacketLengthInBytes - length; } //------------------------------------------------------------------------- void RUDPPacket::vectorEncoderStart( VectorEncoderState &outVectorState, QWORD gsnr, QWORD gsnfr, bool xoredParityToGSNFR ) { ZS_THROW_INVALID_ASSUMPTION_IF(0x7F > sizeof(mVector)) vectorEncoderStart(outVectorState, gsnr, gsnfr, xoredParityToGSNFR, &(mVector[0]), 0x7F); } //------------------------------------------------------------------------- void RUDPPacket::vectorEncoderStart( VectorEncoderState &outVectorState, QWORD gsnr, QWORD gsnfr, bool xoredParityToGSNFR, BYTE *vector, size_t vectorLengthInBytes ) { ZS_THROW_INVALID_USAGE_IF(NULL == vector) outVectorState.mLastState = VectorState_Received; outVectorState.mXORedParityToNow = xoredParityToGSNFR; outVectorState.mVector = vector; outVectorState.mVectorFilledLengthInBytes = 0; outVectorState.mMaxVectorSizeInBytes = vectorLengthInBytes; outVectorState.mGSNR = gsnr; outVectorState.mGSNFR = gsnfr; outVectorState.mCurrentSequenceNumber = gsnfr; } //------------------------------------------------------------------------- bool RUDPPacket::vectorEncoderAdd( VectorEncoderState &ioVectorState, VectorStates vectorState, bool packetParityIfReceived ) { ZS_THROW_INVALID_ASSUMPTION_IF(NULL == ioVectorState.mVector) ZS_THROW_INVALID_USAGE_IF(VectorState_NoMoreData == vectorState) ++(ioVectorState.mCurrentSequenceNumber); if (ioVectorState.mCurrentSequenceNumber >= ioVectorState.mGSNR) { // we never encode to (or beyond) the GSNR as it is completely pointless! return false; } if (0 == ioVectorState.mVectorFilledLengthInBytes) { if (0 == ioVectorState.mMaxVectorSizeInBytes) return false; // why would you do this?? give us a vector size of "0"?? seems rather silly to me... // this is a special case where we need to allocate the first BYTE for the first time ioVectorState.mVector[0] = vectorState; ioVectorState.mVector[0] |= 1; // now has a RLE of 1 if (vectorState != VectorState_NotReceived) ioVectorState.mXORedParityToNow = internal::logicalXOR(ioVectorState.mXORedParityToNow, packetParityIfReceived); ioVectorState.mVectorFilledLengthInBytes = 1; ioVectorState.mLastState = vectorState; return true; } if ((ioVectorState.mLastState != vectorState) || ((ioVectorState.mVector[0] & 0x3F) == 0x3F)) { // in the RLE we only have room up to 3F for each BYTE encoded (ie. a RLE of 63) // we need to add another BYTE to the vector - but is there room? if (ioVectorState.mVectorFilledLengthInBytes >= ioVectorState.mMaxVectorSizeInBytes) return false; // there is no more room! sorry! // there is room, grab the next BYTE and use it ++(ioVectorState.mVector); // point to the next position in the vector ioVectorState.mVector[0] = vectorState; ioVectorState.mVector[0] |= 1; // now has a RLE of 1 if (vectorState != VectorState_NotReceived) ioVectorState.mXORedParityToNow = internal::logicalXOR(ioVectorState.mXORedParityToNow, packetParityIfReceived); ++(ioVectorState.mVectorFilledLengthInBytes); ioVectorState.mLastState = vectorState; return true; } // we have room and we are not changing states... ioVectorState.mVector[0] = (ioVectorState.mVector[0] & 0xC0) | ((ioVectorState.mVector[0] & 0x3F) + 1); // add one to the RLE if (vectorState != VectorState_NotReceived) ioVectorState.mXORedParityToNow = internal::logicalXOR(ioVectorState.mXORedParityToNow, packetParityIfReceived); return true; } //------------------------------------------------------------------------- void RUDPPacket::vectorEncoderFinalize(VectorEncoderState &ioVectorState) { ZS_THROW_INVALID_ASSUMPTION_IF(NULL == ioVectorState.mVector) bool xorParity = false; size_t vectorLengthInBytes = 0; vectorEncoderFinalize(ioVectorState, xorParity, vectorLengthInBytes); setFlag(Flag_VP_VectorParity, xorParity); mVectorLengthInBytes = static_cast<decltype(mVectorLengthInBytes)>(vectorLengthInBytes); } //------------------------------------------------------------------------- void RUDPPacket::vectorEncoderFinalize( VectorEncoderState &ioVectorState, bool &outXORVectorParityFlag, size_t &outVectorLengthInBytes ) { ZS_THROW_INVALID_ASSUMPTION_IF(NULL == ioVectorState.mVector) outXORVectorParityFlag = ioVectorState.mXORedParityToNow; outVectorLengthInBytes = 0; do { if (0 == ioVectorState.mVectorFilledLengthInBytes) { // you never even added any packets to the vector break; } if (ioVectorState.mGSNFR == ioVectorState.mGSNR) { // nothing was encoded since both packets have effectively been received break; } if (1 == ioVectorState.mVectorFilledLengthInBytes) { // detect a special case where all packets are missing between the GSNR and the GSNFR as we don't need a vector to encode that if (ioVectorState.mLastState == VectorState_NotReceived) { // no need for a vector when all packets from the GSNFR to the GSNR are the missing break; } } // in all other cases you wanted a vector so now you have one... outVectorLengthInBytes = ioVectorState.mVectorFilledLengthInBytes; } while (false); } //------------------------------------------------------------------------- void RUDPPacket::vectorDecoderStart(VectorDecoderState &ioVectorState) const { ZS_THROW_INVALID_ASSUMPTION_IF(mVectorLengthInBytes > sizeof(mVector)) vectorDecoderStart(ioVectorState, &(mVector[0]), mVectorLengthInBytes, mGSNR, mGSNFR); } //------------------------------------------------------------------------- void RUDPPacket::vectorDecoderStart( VectorDecoderState &outVectorState, const BYTE *vector, size_t vectorLengthInBytes, QWORD gsnr, QWORD gsnfr ) { outVectorState.mVector = vector; outVectorState.mVectorFilledLengthInBytes = vectorLengthInBytes; outVectorState.mConsumedRLE = 0; memset(&(outVectorState.mSpecialCaseVector[0]), 0, sizeof(outVectorState.mSpecialCaseVector)); if ((gsnr != gsnfr) && (0 == vectorLengthInBytes)) { // this is a special case vector where we will fill the packet with not received outVectorState.mSpecialCaseVector[0] = VectorState_NotReceived; outVectorState.mSpecialCaseVector[0] = (outVectorState.mSpecialCaseVector[0] | ((gsnr - gsnfr - 1) & 0x3F)); outVectorState.mVector = &(outVectorState.mSpecialCaseVector[0]); outVectorState.mVectorFilledLengthInBytes = 1; } } //------------------------------------------------------------------------- RUDPPacket::VectorStates RUDPPacket::vectorDecoderGetNextPacketState(VectorDecoderState &ioVectorState) { if (NULL == ioVectorState.mVector) return VectorState_NoMoreData; if (0 == ioVectorState.mVectorFilledLengthInBytes) return VectorState_NoMoreData; // filled length down to zero means no more data is available if (0 == ((ioVectorState.mVector[0]) & 0x3F)) return VectorState_NoMoreData; // zero size means there are no more RLE data available (this shouldn't happen typically) VectorStates state = static_cast<VectorStates>(ioVectorState.mVector[0] & 0xC0); ++ioVectorState.mConsumedRLE; if (ioVectorState.mConsumedRLE >= static_cast<size_t>(((ioVectorState.mVector[0]) & 0x3F))) { // pull the next BYTE off the queue... ++ioVectorState.mVector; --ioVectorState.mVectorFilledLengthInBytes; ioVectorState.mConsumedRLE = 0; } return state; } //------------------------------------------------------------------------- void RUDPPacket::log( Log::Level level, Log::Params inParams ) const { if (ZS_GET_LOG_LEVEL() < level) return; // scope: log message { Log::Params params(NULL, mLogObject ? mLogObject : "RUDPPacket"); params << inParams; if (0 != mLogObjectID) { if (inParams.object()) { params << ZS_PARAM("original object", mLogObject); params << ZS_PARAM("original id", mLogObjectID); } else { params << ZS_PARAM("id", mLogObjectID); } } params << ZS_PARAM("channel", mChannelNumber) << ZS_PARAM("sequence number", mSequenceNumber) << ZS_PARAM("flags", + string(((UINT)mFlags), 16)) << ZS_PARAM("GSNR", mGSNR); if (!isFlagSet(Flag_EQ_GSNREqualsGSNFR)) { params << ZS_PARAM("GSNFR", mGSNFR); } params << ZS_PARAM("vector flags", string(((UINT)mVectorFlags), 16)); if (0 != mVectorLengthInBytes) { params << ZS_PARAM("vector length", mVectorLengthInBytes); params << ZS_PARAM("vector", internal::convertToHex(&(mVector[0]), mVectorLengthInBytes)); } if (0 != mDataLengthInBytes) { params << ZS_PARAM("data length", mDataLengthInBytes); } String flagStr; if (isFlagSet(Flag_PS_ParitySending)) { flagStr += "(ps)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_PG_ParityGSNR)) { flagStr += "(pg)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_XP_XORedParityToGSNFR)) { flagStr += "(xp)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_DP_DuplicatePacket)) { flagStr += "(dp)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_EC_ECNPacket)) { flagStr += "(ec)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_EQ_GSNREqualsGSNFR)) { flagStr += "(eq)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_AR_ACKRequired)) { flagStr += "(ar)"; } else { flagStr += "(--)"; } if (isFlagSet(Flag_VP_VectorParity)) { flagStr += "(vp)"; } else { flagStr += "(--)"; } params << ZS_PARAM("flag details", flagStr); ZS_LOG(Basic, params) } } } }
40.771957
264
0.549979
[ "object", "vector" ]
58598d018c43363c3ab0642c778db8e41a6ef037
1,298
cpp
C++
Sign_Detection_And_Recognization/header.cpp
duyndh/DigitalRace-MyModules
e7c3939090808bf632484cba47c8910283880def
[ "MIT" ]
null
null
null
Sign_Detection_And_Recognization/header.cpp
duyndh/DigitalRace-MyModules
e7c3939090808bf632484cba47c8910283880def
[ "MIT" ]
null
null
null
Sign_Detection_And_Recognization/header.cpp
duyndh/DigitalRace-MyModules
e7c3939090808bf632484cba47c8910283880def
[ "MIT" ]
1
2018-04-10T02:55:00.000Z
2018-04-10T02:55:00.000Z
#include "header.h" // WARNING: should only be used once because of ycrcb equalization void get_mask(const Mat &hsv, Mat &mask, string colors) { mask = Mat::zeros(mask.rows, mask.cols, CV_8UC1); Mat tmp_mask(mask.rows, mask.cols, CV_8UC1); if (colors.find("blue") != std::string::npos) { inRange(hsv, LOW_HSV_BLUE, HIG_HSV_BLUE, tmp_mask); bitwise_or(mask, tmp_mask, mask); } if (colors.find("red") != std::string::npos) { Mat tmp_mask1(mask.rows, mask.cols, CV_8UC1); Mat tmp_mask2(mask.rows, mask.cols, CV_8UC1); inRange(hsv, LOW_HSV_RED1, HIG_HSV_RED1, tmp_mask1); inRange(hsv, LOW_HSV_RED2, HIG_HSV_RED2, tmp_mask2); bitwise_or(tmp_mask1, tmp_mask2, tmp_mask); bitwise_or(mask, tmp_mask, mask); } if (colors.find("green") != std::string::npos) { inRange(hsv, LOW_HSV_GREEN, HIG_HSV_GREEN, tmp_mask); bitwise_or(mask, tmp_mask, mask); } Mat kernel = Mat::ones(KERNEL_SIZE, KERNEL_SIZE, CV_8UC1); dilate(mask, mask, kernel); morphologyEx(mask, mask, MORPH_CLOSE, kernel); } void hist_equalize(Mat &img) { Mat ycrcb; cvtColor(img, ycrcb, CV_BGR2YCrCb); vector<Mat> chanels(3); split(ycrcb, chanels); Ptr<CLAHE> clahe = createCLAHE(2.0, Size(8, 8)); clahe->apply(chanels[0], chanels[0]); merge(chanels, ycrcb); cvtColor(ycrcb, img, CV_YCrCb2BGR); }
27.041667
66
0.708012
[ "vector" ]
5859c64e5436667193b90dfe49bf991c0a43e7ea
1,132
hpp
C++
Game/Game.hpp
caslarui/LOOP
0ef3e4c60965f186830cc891a4a429e8f51dd44d
[ "MIT" ]
null
null
null
Game/Game.hpp
caslarui/LOOP
0ef3e4c60965f186830cc891a4a429e8f51dd44d
[ "MIT" ]
null
null
null
Game/Game.hpp
caslarui/LOOP
0ef3e4c60965f186830cc891a4a429e8f51dd44d
[ "MIT" ]
null
null
null
// // Created by caslarui on 16.12.2019. // #ifndef LOOP_GAME_HPP #define LOOP_GAME_HPP #include <fstream> #include <iostream> #include <queue> #include "Map/Map.hpp" #include "Characters/Heroes/Hero.hpp" #define print(chr, times) for(int i = 0; i < times; ++i) std::cout << chr; std::cout<<std::endl; #define assert(msg) if (Game::onDebug) {msg} typedef struct Buffer { Hero* mHero = nullptr; int mGainedXp = 0; Buffer(Hero &other, int xp) { mHero = &other; mGainedXp = xp; } } Buffer; class Game { public: explicit Game(const std::string&); void start(); void finish(const std::string&); void update(); static bool onDebug; private: void heroStats(); void battle(Hero&, Hero&, int); void printBattle(Hero&, Hero&); // Array where im saving all the Heroes. std::vector<Hero*> mHeroes; // Queue of moves std::queue<char> mMovesBuffer; std::string mInputPath; // Array where im saving a pointer to a Hero and the gained XP std::queue<Buffer> mXpBuffer; // Number of rounds. int mRounds; }; #endif //LOOP_GAME_HPP
17.968254
96
0.634276
[ "vector" ]
585d18d0974964bb5845eeba37ca577100b73d5e
17,498
cpp
C++
third_party/WebKit/Source/core/editing/iterators/TextIteratorTextNodeHandler.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/editing/iterators/TextIteratorTextNodeHandler.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/editing/iterators/TextIteratorTextNodeHandler.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/editing/iterators/TextIteratorTextNodeHandler.h" #include <algorithm> #include "core/dom/FirstLetterPseudoElement.h" #include "core/editing/iterators/TextIteratorTextState.h" #include "core/layout/LayoutTextFragment.h" #include "core/layout/line/InlineTextBox.h" #include "core/layout/line/RootInlineBox.h" namespace blink { TextIteratorTextNodeHandler::TextIteratorTextNodeHandler( const TextIteratorBehavior& behavior, TextIteratorTextState* text_state) : behavior_(behavior), text_state_(*text_state) {} bool TextIteratorTextNodeHandler::HandleRemainingTextRuns() { if (ShouldProceedToRemainingText()) ProceedToRemainingText(); // Handle remembered text box if (text_box_) { HandleTextBox(); return text_state_.PositionNode(); } // Handle remembered pre-formatted text node. if (!needs_handle_pre_formatted_text_node_) return false; HandlePreFormattedTextNode(); return text_state_.PositionNode(); } bool TextIteratorTextNodeHandler::ShouldHandleFirstLetter( const LayoutText& layout_text) const { if (handled_first_letter_) return false; if (!layout_text.IsTextFragment()) return false; const LayoutTextFragment& text_fragment = ToLayoutTextFragment(layout_text); return offset_ < static_cast<int>(text_fragment.TextStartOffset()); } static bool HasVisibleTextNode(LayoutText* layout_object) { if (layout_object->Style()->Visibility() == EVisibility::kVisible) return true; if (!layout_object->IsTextFragment()) return false; LayoutTextFragment* fragment = ToLayoutTextFragment(layout_object); if (!fragment->IsRemainingTextLayoutObject()) return false; DCHECK(fragment->GetFirstLetterPseudoElement()); LayoutObject* pseudo_element_layout_object = fragment->GetFirstLetterPseudoElement()->GetLayoutObject(); return pseudo_element_layout_object && pseudo_element_layout_object->Style()->Visibility() == EVisibility::kVisible; } void TextIteratorTextNodeHandler::HandlePreFormattedTextNode() { // TODO(xiaochengh): Get rid of repeated computation of these fields. LayoutText* const layout_object = text_node_->GetLayoutObject(); const String str = layout_object->GetText(); needs_handle_pre_formatted_text_node_ = false; if (last_text_node_ended_with_collapsed_space_ && HasVisibleTextNode(layout_object)) { if (!behavior_.CollapseTrailingSpace() || (offset_ > 0 && str[offset_ - 1] == ' ')) { SpliceBuffer(kSpaceCharacter, text_node_, 0, offset_, offset_); needs_handle_pre_formatted_text_node_ = true; return; } } if (ShouldHandleFirstLetter(*layout_object)) { HandleTextNodeFirstLetter(ToLayoutTextFragment(layout_object)); if (first_letter_text_) { const String first_letter = first_letter_text_->GetText(); const unsigned run_start = offset_; const bool stops_in_first_letter = end_offset_ <= static_cast<int>(first_letter.length()); const unsigned run_end = stops_in_first_letter ? end_offset_ : first_letter.length(); EmitText(text_node_, first_letter_text_, run_start, run_end); first_letter_text_ = nullptr; text_box_ = 0; offset_ = run_end; if (!stops_in_first_letter) needs_handle_pre_formatted_text_node_ = true; return; } // We are here only if the DOM and/or layout trees are broken. // For robustness, we should stop processing this node. NOTREACHED(); return; } if (layout_object->Style()->Visibility() != EVisibility::kVisible && !IgnoresStyleVisibility()) return; DCHECK_GE(static_cast<unsigned>(offset_), layout_object->TextStartOffset()); const unsigned run_start = offset_ - layout_object->TextStartOffset(); const unsigned str_length = str.length(); const unsigned end = end_offset_ - layout_object->TextStartOffset(); const unsigned run_end = std::min(str_length, end); if (run_start >= run_end) return; EmitText(text_node_, text_node_->GetLayoutObject(), run_start, run_end); } void TextIteratorTextNodeHandler::HandleTextNodeInRange(Text* node, int start_offset, int end_offset) { DCHECK(node); DCHECK_GE(start_offset, 0); // TODO(editing-dev): Add the following DCHECK once we stop assuming equal // number of code units in DOM string and LayoutText::GetText(). Currently // violated by // - external/wpt/innerText/getter.html // - fast/css/case-transform.html // DCHECK_LE(end_offset, static_cast<int>(node->data().length())); // TODO(editing-dev): Stop passing in |start_offset == end_offset|. DCHECK_LE(start_offset, end_offset); text_node_ = node; offset_ = start_offset; end_offset_ = end_offset; handled_first_letter_ = false; first_letter_text_ = nullptr; LayoutText* layout_object = text_node_->GetLayoutObject(); String str = layout_object->GetText(); // handle pre-formatted text if (!layout_object->Style()->CollapseWhiteSpace()) { HandlePreFormattedTextNode(); return; } if (layout_object->FirstTextBox()) text_box_ = layout_object->FirstTextBox(); const bool should_handle_first_letter = ShouldHandleFirstLetter(*layout_object); if (should_handle_first_letter) HandleTextNodeFirstLetter(ToLayoutTextFragment(layout_object)); if (!layout_object->FirstTextBox() && str.length() > 0 && !should_handle_first_letter) { if (layout_object->Style()->Visibility() == EVisibility::kVisible || IgnoresStyleVisibility()) { last_text_node_ended_with_collapsed_space_ = true; // entire block is collapsed space } return; } if (first_letter_text_) layout_object = first_letter_text_; // Used when text boxes are out of order (Hebrew/Arabic w/ embeded LTR text) if (layout_object->ContainsReversedText()) { sorted_text_boxes_.clear(); for (InlineTextBox* text_box : InlineTextBoxesOf(*layout_object)) { sorted_text_boxes_.push_back(text_box); } std::sort(sorted_text_boxes_.begin(), sorted_text_boxes_.end(), InlineTextBox::CompareByStart); sorted_text_boxes_position_ = 0; text_box_ = sorted_text_boxes_.IsEmpty() ? 0 : sorted_text_boxes_[0]; } HandleTextBox(); } void TextIteratorTextNodeHandler::HandleTextNodeStartFrom(Text* node, int start_offset) { HandleTextNodeInRange(node, start_offset, node->GetLayoutObject()->TextStartOffset() + node->GetLayoutObject()->GetText().length()); } void TextIteratorTextNodeHandler::HandleTextNodeEndAt(Text* node, int end_offset) { HandleTextNodeInRange(node, 0, end_offset); } void TextIteratorTextNodeHandler::HandleTextNodeWhole(Text* node) { HandleTextNodeStartFrom(node, 0); } // Restore the collapsed space for copy & paste. See http://crbug.com/318925 size_t TextIteratorTextNodeHandler::RestoreCollapsedTrailingSpace( InlineTextBox* next_text_box, size_t subrun_end) { if (next_text_box || !text_box_->Root().NextRootBox() || text_box_->Root().LastChild() != text_box_) return subrun_end; const LayoutText* layout_object = first_letter_text_ ? first_letter_text_ : text_node_->GetLayoutObject(); const String& text = layout_object->GetText(); if (text.EndsWith(' ') == 0 || subrun_end != text.length() - 1 || text[subrun_end - 1] == ' ') return subrun_end; // If there is the leading space in the next line, we don't need to restore // the trailing space. // Example: <div style="width: 2em;"><b><i>foo </i></b> bar</div> InlineBox* first_box_of_next_line = text_box_->Root().NextRootBox()->FirstChild(); if (!first_box_of_next_line) return subrun_end + 1; Node* first_node_of_next_line = first_box_of_next_line->GetLineLayoutItem().GetNode(); if (!first_node_of_next_line || first_node_of_next_line->nodeValue()[0] != ' ') return subrun_end + 1; return subrun_end; } void TextIteratorTextNodeHandler::HandleTextBox() { LayoutText* layout_object = first_letter_text_ ? first_letter_text_ : text_node_->GetLayoutObject(); const unsigned text_start_offset = layout_object->TextStartOffset(); if (layout_object->Style()->Visibility() != EVisibility::kVisible && !IgnoresStyleVisibility()) { text_box_ = nullptr; } else { String str = layout_object->GetText(); // Start and end offsets in |str|, i.e., str[start..end - 1] should be // emitted (after handling whitespace collapsing). const unsigned start = offset_ - layout_object->TextStartOffset(); const unsigned end = static_cast<unsigned>(end_offset_) - text_start_offset; while (text_box_) { const unsigned text_box_start = text_box_->Start(); const unsigned run_start = std::max(text_box_start, start); // Check for collapsed space at the start of this run. InlineTextBox* first_text_box = layout_object->ContainsReversedText() ? (sorted_text_boxes_.IsEmpty() ? 0 : sorted_text_boxes_[0]) : layout_object->FirstTextBox(); const bool need_space = last_text_node_ended_with_collapsed_space_ || (text_box_ == first_text_box && text_box_start == run_start && run_start > 0); if (need_space && !layout_object->Style()->IsCollapsibleWhiteSpace( text_state_.LastCharacter()) && text_state_.LastCharacter()) { if (run_start > 0 && str[run_start - 1] == ' ') { unsigned space_run_start = run_start - 1; while (space_run_start > 0 && str[space_run_start - 1] == ' ') --space_run_start; EmitText(text_node_, layout_object, space_run_start, space_run_start + 1); } else { SpliceBuffer(kSpaceCharacter, text_node_, 0, run_start, run_start); } return; } const unsigned text_box_end = text_box_start + text_box_->Len(); const unsigned run_end = std::min(text_box_end, end); // Determine what the next text box will be, but don't advance yet InlineTextBox* next_text_box = nullptr; if (layout_object->ContainsReversedText()) { if (sorted_text_boxes_position_ + 1 < sorted_text_boxes_.size()) next_text_box = sorted_text_boxes_[sorted_text_boxes_position_ + 1]; } else { next_text_box = text_box_->NextTextBox(); } // FIXME: Based on the outcome of crbug.com/446502 it's possible we can // remove this block. The reason we new it now is because BIDI and // FirstLetter seem to have different ideas of where things can split. // FirstLetter takes the punctuation + first letter, and BIDI will // split out the punctuation and possibly reorder it. if (next_text_box && !(next_text_box->GetLineLayoutItem().IsEqual(layout_object))) { text_box_ = 0; return; } DCHECK(!next_text_box || next_text_box->GetLineLayoutItem().IsEqual(layout_object)); if (run_start < run_end) { // Handle either a single newline character (which becomes a space), // or a run of characters that does not include a newline. // This effectively translates newlines to spaces without copying the // text. if (str[run_start] == '\n') { // We need to preserve new lines in case of PreLine. // See bug crbug.com/317365. if (layout_object->Style()->WhiteSpace() == EWhiteSpace::kPreLine) { SpliceBuffer('\n', text_node_, 0, run_start, run_start); } else { SpliceBuffer(kSpaceCharacter, text_node_, 0, run_start, run_start + 1); } offset_ = text_start_offset + run_start + 1; } else { size_t subrun_end = str.find('\n', run_start); if (subrun_end == kNotFound || subrun_end > run_end) { subrun_end = run_end; subrun_end = RestoreCollapsedTrailingSpace(next_text_box, subrun_end); } offset_ = text_start_offset + subrun_end; EmitText(text_node_, layout_object, run_start, subrun_end); } // If we are doing a subrun that doesn't go to the end of the text box, // come back again to finish handling this text box; don't advance to // the next one. if (static_cast<unsigned>(text_state_.PositionEndOffset()) < text_box_end + text_start_offset) return; if (behavior_.DoesNotEmitSpaceBeyondRangeEnd()) { // If the subrun went to the text box end and this end is also the end // of the range, do not advance to the next text box and do not // generate a space, just stop. if (text_box_end == end) { text_box_ = nullptr; return; } } // Advance and return const unsigned next_run_start = next_text_box ? next_text_box->Start() : str.length(); if (next_run_start > run_end) { last_text_node_ended_with_collapsed_space_ = true; // collapsed space between runs or at the end } text_box_ = next_text_box; if (layout_object->ContainsReversedText()) ++sorted_text_boxes_position_; return; } // Advance and continue text_box_ = next_text_box; if (layout_object->ContainsReversedText()) ++sorted_text_boxes_position_; } } if (ShouldProceedToRemainingText()) { ProceedToRemainingText(); HandleTextBox(); } } bool TextIteratorTextNodeHandler::ShouldProceedToRemainingText() const { if (text_box_ || !remaining_text_box_) return false; return offset_ < end_offset_; } void TextIteratorTextNodeHandler::ProceedToRemainingText() { text_box_ = remaining_text_box_; remaining_text_box_ = 0; first_letter_text_ = nullptr; offset_ = text_node_->GetLayoutObject()->TextStartOffset(); } void TextIteratorTextNodeHandler::HandleTextNodeFirstLetter( LayoutTextFragment* layout_object) { handled_first_letter_ = true; if (!layout_object->IsRemainingTextLayoutObject()) return; FirstLetterPseudoElement* first_letter_element = layout_object->GetFirstLetterPseudoElement(); if (!first_letter_element) return; LayoutObject* pseudo_layout_object = first_letter_element->GetLayoutObject(); if (pseudo_layout_object->Style()->Visibility() != EVisibility::kVisible && !IgnoresStyleVisibility()) return; LayoutObject* first_letter = pseudo_layout_object->SlowFirstChild(); sorted_text_boxes_.clear(); remaining_text_box_ = text_box_; CHECK(first_letter && first_letter->IsText()); first_letter_text_ = ToLayoutText(first_letter); text_box_ = first_letter_text_->FirstTextBox(); } bool TextIteratorTextNodeHandler::FixLeadingWhiteSpaceForReplacedElement( Node* parent) { // This is a hacky way for white space fixup in legacy layout. With LayoutNG, // we can get rid of this function. if (behavior_.CollapseTrailingSpace()) { if (text_node_) { String str = text_node_->GetLayoutObject()->GetText(); if (last_text_node_ended_with_collapsed_space_ && offset_ > 0 && str[offset_ - 1] == ' ') { SpliceBuffer(kSpaceCharacter, parent, text_node_, 1, 1); return true; } } } else if (last_text_node_ended_with_collapsed_space_) { SpliceBuffer(kSpaceCharacter, parent, text_node_, 1, 1); return true; } return false; } void TextIteratorTextNodeHandler::ResetCollapsedWhiteSpaceFixup() { // This is a hacky way for white space fixup in legacy layout. With LayoutNG, // we can get rid of this function. last_text_node_ended_with_collapsed_space_ = false; } void TextIteratorTextNodeHandler::SpliceBuffer(UChar c, Node* text_node, Node* offset_base_node, int text_start_offset, int text_end_offset) { text_state_.SpliceBuffer(c, text_node, offset_base_node, text_start_offset, text_end_offset); ResetCollapsedWhiteSpaceFixup(); } void TextIteratorTextNodeHandler::EmitText(Node* text_node, LayoutText* layout_object, int text_start_offset, int text_end_offset) { String string = behavior_.EmitsOriginalText() ? layout_object->OriginalText() : layout_object->GetText(); if (behavior_.EmitsSpaceForNbsp()) string.Replace(kNoBreakSpaceCharacter, kSpaceCharacter); text_state_.EmitText(text_node, text_start_offset + layout_object->TextStartOffset(), text_end_offset + layout_object->TextStartOffset(), string, text_start_offset, text_end_offset); ResetCollapsedWhiteSpaceFixup(); } } // namespace blink
37.956616
80
0.669619
[ "transform" ]
585dc8877bcccc5123e2ca25b83ebe232cc0b8e0
3,816
hpp
C++
Viewer/ecflowUI/src/ServerList.hpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/ServerList.hpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/ServerList.hpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. //============================================================================ #ifndef SERVERLIST_HPP_ #define SERVERLIST_HPP_ #include <string> #include <vector> #include <QDateTime> class ServerItem; class ServerList; class ServerListObserver { public: ServerListObserver() = default; virtual ~ServerListObserver() = default; virtual void notifyServerListChanged()=0; virtual void notifyServerListFavouriteChanged(ServerItem*)=0; }; class ServerListTmpItem { public: ServerListTmpItem() = default; ServerListTmpItem(const std::string& name,const std::string& host, const std::string& port) : name_(name), host_(host), port_(port) {} explicit ServerListTmpItem(ServerItem* item); ServerListTmpItem(const ServerListTmpItem& ) = default; const std::string& name() const {return name_;} const std::string& host() const {return host_;} const std::string& port() const {return port_;} protected: std::string name_; std::string host_; std::string port_; }; class ServerListSyncChangeItem { public: enum ChangeType {AddedChange,RemovedChange, MatchChange, SetSysChange,UnsetSysChange}; ServerListSyncChangeItem(const ServerListTmpItem& sys,const ServerListTmpItem& local,ChangeType type) : sys_(sys), local_(local), type_(type) {} const ServerListTmpItem& sys() const {return sys_;} const ServerListTmpItem& local() const {return local_;} ChangeType type() const {return type_;} ServerListTmpItem sys_; ServerListTmpItem local_; ChangeType type_; }; class ServerList { public: int count() const {return static_cast<int>(items_.size());} ServerItem* itemAt(int); ServerItem* find(const std::string& name); ServerItem* find(const std::string& name, const std::string& host, const std::string& port); //Can be added or changed only via these static methods ServerItem* add(const std::string& name,const std::string& host,const std::string& port, const std::string& user, bool favorite, bool ssl, bool saveIt); void remove(ServerItem*); void reset(ServerItem*,const std::string& name,const std::string& host,const std::string& port, const std::string& user, bool ssl); void setFavourite(ServerItem*,bool); std::string uniqueName(const std::string&); void init(); void save(); void rescan(); void syncSystemFile(); bool hasSystemFile() const; const std::vector<ServerListSyncChangeItem*>& syncChange() const {return syncChange_;} bool hasSyncChange() const {return !syncChange_.empty();} QDateTime syncDate() const {return syncDate_;} void addObserver(ServerListObserver*); void removeObserver(ServerListObserver*); static ServerList* instance(); protected: ServerList() = default; ~ServerList() = default; static ServerList* instance_; bool load(); bool readRcFile(); void clearSyncChange(); bool checkItemToAdd(const std::string& name,const std::string& host,const std::string& port, bool checkDuplicate,std::string& errStr); void broadcastChanged(); void broadcastChanged(ServerItem*); std::vector<ServerItem*> items_; std::string localFile_; std::string systemFile_; std::vector<ServerListObserver*> observers_; std::vector<ServerListSyncChangeItem*> syncChange_; QDateTime syncDate_; }; #endif
30.528
117
0.68999
[ "vector" ]
58735bdedacd348328e9c478ebf4554f5bc26ba6
17,349
cc
C++
src/kudu/integration-tests/dns_alias-itest.cc
Kekdeng/kudu
958248adf3ea70f12ab033e0041bfc5c922956af
[ "Apache-2.0" ]
1,538
2016-08-08T22:34:30.000Z
2022-03-29T05:23:36.000Z
src/kudu/integration-tests/dns_alias-itest.cc
Kekdeng/kudu
958248adf3ea70f12ab033e0041bfc5c922956af
[ "Apache-2.0" ]
17
2017-05-18T16:05:14.000Z
2022-03-18T22:17:13.000Z
src/kudu/integration-tests/dns_alias-itest.cc
Kekdeng/kudu
958248adf3ea70f12ab033e0041bfc5c922956af
[ "Apache-2.0" ]
612
2016-08-12T04:09:37.000Z
2022-03-29T16:57:46.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. #include <cstdint> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> #include <gflags/gflags_declare.h> #include <gtest/gtest.h> #include "kudu/client/client.h" #include "kudu/gutil/stl_util.h" #include "kudu/gutil/strings/join.h" #include "kudu/gutil/strings/split.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/integration-tests/cluster_itest_util.h" #include "kudu/integration-tests/cluster_verifier.h" #include "kudu/integration-tests/test_workload.h" #include "kudu/mini-cluster/external_mini_cluster.h" #include "kudu/mini-cluster/mini_cluster.h" #include "kudu/rpc/rpc_controller.h" #include "kudu/tserver/tserver.pb.h" #include "kudu/tserver/tserver_service.proxy.h" #include "kudu/util/metrics.h" #include "kudu/util/monotime.h" #include "kudu/util/net/net_util.h" #include "kudu/util/net/sockaddr.h" #include "kudu/util/net/socket.h" #include "kudu/util/pb_util.h" #include "kudu/util/status.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" DECLARE_bool(client_use_unix_domain_sockets); DECLARE_string(dns_addr_resolution_override); DECLARE_string(host_for_tests); METRIC_DECLARE_counter(rpc_connections_accepted_unix_domain_socket); METRIC_DECLARE_entity(server); using kudu::client::KuduClient; using kudu::client::KuduTabletServer; using kudu::cluster::ExternalDaemon; using kudu::cluster::ExternalMiniCluster; using kudu::cluster::ExternalMiniClusterOptions; using kudu::pb_util::SecureShortDebugString; using std::string; using std::unique_ptr; using std::vector; using strings::Split; using strings::Substitute; namespace kudu { namespace itest { namespace { constexpr const char* kTServerHostPrefix = "tserver.host"; constexpr const char* kMasterHostPrefix = "master.host"; } // anonymous namespace class DnsAliasITest : public KuduTest { public: void SetUp() override { SetUpCluster(); } // TODO(awong): more plumbing is needed to allow the server to be restarted // bound to a different address with the webserver, so just disable it. void SetUpCluster(vector<string> extra_master_flags = { "--webserver_enabled=false" }, vector<string> extra_tserver_flags = { "--webserver_enabled=false" }) { ExternalMiniClusterOptions opts; opts.num_masters = 3; opts.num_tablet_servers = 3; opts.extra_master_flags = std::move(extra_master_flags); opts.extra_tserver_flags = std::move(extra_tserver_flags); opts.master_alias_prefix = kMasterHostPrefix; opts.tserver_alias_prefix = kTServerHostPrefix; cluster_.reset(new ExternalMiniCluster(std::move(opts))); ASSERT_OK(cluster_->Start()); FLAGS_dns_addr_resolution_override = cluster_->dns_overrides(); ASSERT_OK(cluster_->CreateClient(nullptr, &client_)); } void TearDown() override { NO_FATALS(cluster_->AssertNoCrashes()); } // Get the new DNS override string when restarting the last node of the given // daemon type with the given reserved address. string GetNewOverridesFlag(ExternalMiniCluster::DaemonType node_type, const Sockaddr& new_addr) { int master_end_idx = cluster_->num_masters(); int tserver_end_idx = cluster_->num_tablet_servers(); bool is_master = node_type == ExternalMiniCluster::DaemonType::MASTER; if (is_master) { --master_end_idx; } else { --tserver_end_idx; } vector<string> new_overrides; new_overrides.reserve(cluster_->num_masters() + cluster_->num_tablet_servers()); for (int i = 0; i < master_end_idx; i++) { new_overrides.emplace_back(Substitute("$0.$1=$2", kMasterHostPrefix, i, cluster_->master(i)->bound_rpc_addr().ToString())); } for (int i = 0; i < tserver_end_idx; i++) { new_overrides.emplace_back( Substitute("$0.$1=$2", kTServerHostPrefix, i, cluster_->tablet_server(i)->bound_rpc_addr().ToString())); } new_overrides.emplace_back( Substitute("$0.$1=$2", is_master ? kMasterHostPrefix : kTServerHostPrefix, is_master ? master_end_idx : tserver_end_idx, new_addr.ToString())); return JoinStrings(new_overrides, ","); } // Adds the appropriate flags for the given daemon to be restarted bound to // the given address. void SetUpDaemonForNewAddr(const Sockaddr& new_addr, const string& new_overrides_str, ExternalDaemon* daemon) { HostPort new_ip_hp(new_addr.host(), new_addr.port()); daemon->SetRpcBindAddress(new_ip_hp); daemon->mutable_flags()->emplace_back("--rpc_reuseport=true"); daemon->mutable_flags()->emplace_back( Substitute("--dns_addr_resolution_override=$0", new_overrides_str)); } // Sets the flags on all nodes in the cluster, except for the last node of // the given 'node_type', which is expected to have been restarted with the // appropriate flags. void SetFlagsOnRemainingCluster(ExternalMiniCluster::DaemonType node_type, const string& new_overrides_str) { int master_end_idx = cluster_->num_masters(); int tserver_end_idx = cluster_->num_tablet_servers(); if (node_type == ExternalMiniCluster::DaemonType::MASTER) { --master_end_idx; } else { --tserver_end_idx; } for (int i = 0; i < master_end_idx; i++) { ASSERT_OK(cluster_->SetFlag( cluster_->master(i), "dns_addr_resolution_override", new_overrides_str)); } for (int i = 0; i < tserver_end_idx; i++) { ASSERT_OK(cluster_->SetFlag( cluster_->tablet_server(i), "dns_addr_resolution_override", new_overrides_str)); } } protected: unique_ptr<ExternalMiniCluster> cluster_; client::sp::shared_ptr<KuduClient> client_; }; TEST_F(DnsAliasITest, TestBasic) { // Based on the mini-cluster setup, the client should report the aliases. auto master_addrs_str = client_->GetMasterAddresses(); vector<string> master_addrs = Split(master_addrs_str, ","); ASSERT_EQ(cluster_->num_masters(), master_addrs.size()) << master_addrs_str; for (const auto& master_addr : master_addrs) { ASSERT_STR_CONTAINS(master_addr, kMasterHostPrefix); // Try resolving a numeric IP. This should fail, since the returned values // should be aliased. Sockaddr addr; Status s = addr.ParseString(master_addr, 0); ASSERT_FALSE(s.ok()); } vector<KuduTabletServer*> tservers; ElementDeleter deleter(&tservers); ASSERT_OK(client_->ListTabletServers(&tservers)); for (const auto* tserver : tservers) { ASSERT_STR_CONTAINS(tserver->hostname(), kTServerHostPrefix); // Try resolving a numeric IP. This should fail, since the returned values // should be aliased. Sockaddr addr; Status s = addr.ParseString(tserver->hostname(), 0); ASSERT_FALSE(s.ok()); } // Running a test worload should succeed. Have the workload perform both // scans and writes to exercise the aliasing codepaths of each. TestWorkload w(cluster_.get()); w.set_num_write_threads(1); w.set_num_read_threads(3); w.set_num_replicas(3); w.Setup(); w.Start(); while (w.rows_inserted() < 10) { SleepFor(MonoDelta::FromMilliseconds(10)); } w.StopAndJoin(); } class DnsAliasWithUnixSocketsITest : public DnsAliasITest { public: void SetUp() override { // Configure --host_for_tests in this process so the test client will think // it's local to a tserver. FLAGS_host_for_tests = Substitute("$0.$1", kTServerHostPrefix, kTServerIdxWithLocalClient); FLAGS_client_use_unix_domain_sockets = true; SetUpCluster({ "--rpc_listen_on_unix_domain_socket=true" }, { "--rpc_listen_on_unix_domain_socket=true" }); } protected: const int kTServerIdxWithLocalClient = 0; }; TEST_F(DnsAliasWithUnixSocketsITest, TestBasic) { TestWorkload w(cluster_.get()); w.set_num_write_threads(1); w.set_num_read_threads(3); w.set_num_replicas(3); w.Setup(); w.Start(); while (w.rows_inserted() < 10) { SleepFor(MonoDelta::FromMilliseconds(10)); } w.StopAndJoin(); for (int i = 0; i < cluster_->num_tablet_servers(); i++) { int64_t unix_connections = 0; // Curl doesn't know about our DNS aliasing, so resolve the address and // fetch the metric from the proper address. vector<Sockaddr> addrs; ASSERT_OK(cluster_->tablet_server(i)->bound_http_hostport().ResolveAddresses(&addrs)); ASSERT_EQ(1, addrs.size()); const auto& addr = addrs[0]; ASSERT_OK(GetInt64Metric(HostPort(addr.host(), addr.port()), &METRIC_ENTITY_server, nullptr, &METRIC_rpc_connections_accepted_unix_domain_socket, "value", &unix_connections)); if (i == kTServerIdxWithLocalClient) { ASSERT_LT(0, unix_connections); } else { ASSERT_EQ(0, unix_connections); } } } // These tests depend on restarted servers being assigned a new IP address. On // MacOS, tservers are all assigned the same address, so don't run them there. #if defined(__linux__) // Regression test for KUDU-1620, wherein consensus proxies don't eventually // succeed when the address changes but the host/ports stays the same. TEST_F(DnsAliasITest, Kudu1620) { TestWorkload w(cluster_.get()); w.set_num_replicas(3); w.set_num_write_threads(1); w.Setup(); w.Start(); while (w.rows_inserted() < 10) { SleepFor(MonoDelta::FromMilliseconds(10)); } w.StopAndJoin(); // Shut down a tablet server and start one up at a different IP. auto* tserver = cluster_->tablet_server(cluster_->num_tablet_servers() - 1); tserver->Shutdown(); unique_ptr<Socket> reserved_socket; ASSERT_OK(cluster_->ReserveDaemonSocket(cluster::ExternalMiniCluster::DaemonType::TSERVER, 3, kDefaultBindMode, &reserved_socket, tserver->bound_rpc_hostport().port())); Sockaddr new_addr; ASSERT_OK(reserved_socket->GetSocketAddress(&new_addr)); // Once we start having the other servers communicate with the new tserver, // ksck should return healthy. auto new_overrides_str = GetNewOverridesFlag(ExternalMiniCluster::DaemonType::TSERVER, new_addr); SetUpDaemonForNewAddr(new_addr, new_overrides_str, tserver); ASSERT_OK(tserver->Restart()); // Running ksck should fail because the existing servers are still trying to // communicate with the old port. ClusterVerifier v(cluster_.get()); Status s = v.RunKsck(); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); SetFlagsOnRemainingCluster(ExternalMiniCluster::DaemonType::TSERVER, new_overrides_str); // Our test thread still thinks the old alias is still valid, so our ksck // should fail. s = v.RunKsck(); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); // Once we set the DNS aliases in the test thread, ksck should succeed. FLAGS_dns_addr_resolution_override = new_overrides_str; ASSERT_EVENTUALLY([&] { ASSERT_OK(v.RunKsck()); }); } // Master-side regression test for KUDU-1620. Masters instantiate consensus // proxies to get the UUIDs of its peers. With KUDU-1620 resolved, the proxy // used should be able to re-resolve and retry upon failure, rather than // retrying at the same address. TEST_F(DnsAliasITest, TestMasterReresolveOnStartup) { const int last_master_idx = cluster_->num_masters() - 1; auto* master = cluster_->master(last_master_idx); // Shut down and prepare the node that we're going to give a new address. master->Shutdown(); unique_ptr<Socket> reserved_socket; ASSERT_OK(cluster_->ReserveDaemonSocket(cluster::ExternalMiniCluster::DaemonType::MASTER, 3, kDefaultBindMode, &reserved_socket, master->bound_rpc_hostport().port())); Sockaddr new_addr; ASSERT_OK(reserved_socket->GetSocketAddress(&new_addr)); auto new_overrides_str = GetNewOverridesFlag(ExternalMiniCluster::DaemonType::MASTER, new_addr); SetUpDaemonForNewAddr(new_addr, new_overrides_str, master); // Shut down the other masters so we can test what happens when they come // back up. for (int i = 0; i < last_master_idx; i++) { cluster_->master(i)->Shutdown(); } for (int i = 0; i < last_master_idx; i++) { ASSERT_OK(cluster_->master(i)->Restart()); } // Since the rest of the cluster doesn't know about the address, ksck will // fail. ClusterVerifier v(cluster_.get()); Status s = v.RunKsck(); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); // Even upon setting the DNS overrides on the rest of the nodes, since the // master hasn't started, we should still see an error. SetFlagsOnRemainingCluster(ExternalMiniCluster::DaemonType::MASTER, new_overrides_str); s = v.RunKsck(); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); FLAGS_dns_addr_resolution_override = new_overrides_str; s = v.RunKsck(); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); // Upon restarting the node, the other masters should be able to resolve and // connect to it. ASSERT_OK(master->Restart()); ASSERT_EVENTUALLY([&] { ASSERT_OK(v.RunKsck()); }); } // Regression test for KUDU-1885, wherein tserver proxies on the masters don't // eventually succeed when the tserver's address changes. TEST_F(DnsAliasITest, Kudu1885) { // First, wait for all tablet servers to report to the masters. ASSERT_EVENTUALLY([&] { vector<KuduTabletServer*> tservers; ElementDeleter deleter(&tservers); ASSERT_OK(client_->ListTabletServers(&tservers)); ASSERT_EQ(cluster_->num_tablet_servers(), tservers.size()); }); auto* tserver = cluster_->tablet_server(cluster_->num_tablet_servers() - 1); // Shut down a tablet server so we can start it up with a different address. tserver->Shutdown(); unique_ptr<Socket> reserved_socket; ASSERT_OK(cluster_->ReserveDaemonSocket(cluster::ExternalMiniCluster::DaemonType::TSERVER, 3, kDefaultBindMode, &reserved_socket, tserver->bound_rpc_hostport().port())); Sockaddr new_addr; ASSERT_OK(reserved_socket->GetSocketAddress(&new_addr)); auto new_overrides_str = GetNewOverridesFlag(ExternalMiniCluster::DaemonType::TSERVER, new_addr); SetUpDaemonForNewAddr(new_addr, new_overrides_str, tserver); // Create several tables. Based on Kudu's tablet placement algorithm, some // should be assigned to the tserver with a new address. This will start some // tasks on the master to send requests to tablet servers (some of which will // fail because of the down server). // NOTE: master's will wait up to --tserver_unresponsive_timeout_ms before // stopping replica placement on the down server. By default, this is 60 // seconds, so we can proceed expecting placement on the down tserver. for (int i = 0; i < 10; i++) { TestWorkload w(cluster_.get()); w.set_table_name(Substitute("default.table_$0", i)); w.set_num_replicas(1); // Some tablet creations will initially fail until we restart the down // server, so have our client not wait for creation to finish. w.set_wait_for_create(false); w.Setup(); } ASSERT_OK(tserver->Restart()); // Allow the rest of the cluster to start seeing the re-addressed server. SetFlagsOnRemainingCluster(ExternalMiniCluster::DaemonType::TSERVER, new_overrides_str); FLAGS_dns_addr_resolution_override = new_overrides_str; ClusterVerifier v(cluster_.get()); ASSERT_EVENTUALLY([&] { ASSERT_OK(v.RunKsck()); }); // Ensure there's no funny business with the tserver coming up at a new // address -- we should have the same number of tablet servers. vector<KuduTabletServer*> tservers; ElementDeleter deleter(&tservers); ASSERT_OK(client_->ListTabletServers(&tservers)); ASSERT_EQ(cluster_->num_tablet_servers(), tservers.size()); // Some tablets should be assigned to the tablet we re-addressed, and the // create tablet requests from the masters should have been routed as // appropriate. auto tserver_proxy = cluster_->tserver_proxy(cluster_->num_tablet_servers() - 1); tserver::ListTabletsRequestPB req; req.set_need_schema_info(false); tserver::ListTabletsResponsePB resp; rpc::RpcController controller; ASSERT_OK(tserver_proxy->ListTablets(req, &resp, &controller)); ASSERT_FALSE(resp.has_error()) << SecureShortDebugString(resp.error()); ASSERT_GT(resp.status_and_schema_size(), 0); } #endif } // namespace itest } // namespace kudu
39.882759
99
0.713701
[ "vector" ]
5873a8547ea2a47c42a96391d1e96d9db1e9dcfe
9,343
cpp
C++
libs/Picture.cpp
OberKnirps/PictureToWood
a41408d3c87fa35836be1c681a968492f062941e
[ "MIT" ]
null
null
null
libs/Picture.cpp
OberKnirps/PictureToWood
a41408d3c87fa35836be1c681a968492f062941e
[ "MIT" ]
null
null
null
libs/Picture.cpp
OberKnirps/PictureToWood
a41408d3c87fa35836be1c681a968492f062941e
[ "MIT" ]
null
null
null
// // Created by fabian on 17.05.21. // #include "Picture.hpp" using namespace cv; /** * Filtered version of the image. */ void picture::show() const { for (const auto & pair : this->images) { if(not pair.img.empty()){ namedWindow("Image", WINDOW_AUTOSIZE); imshow( "Image", pair.img_filter); waitKey ( 10000);//TODO replace with better solution for waiting } else{ std::cout << "No image to show."; } } } /** * Load the Image specified by path into the picture object, replacing the current images and replacing the name with the new file name. * @param path Absolute path or relative path from the working directory. */ picture::picture(const std::string &path, unsigned int dpi, int filter_type, double filter_ratio) { this->images.resize(1); try { String file_path = samples::findFile(path); this->origImage.img = imread(file_path, IMREAD_COLOR); this->origImage.img_gray = imread(file_path, IMREAD_GRAYSCALE); this->origImage.mask = cv::Mat(this->origImage.img.rows,this->origImage.img.cols,CV_8U,255); this->origDPI = dpi; this->currentDPI = dpi; this->filterType = filter_type; this->name = file_path.substr(file_path.find_last_of('/')+1, file_path.find_first_of('.') - file_path.find_last_of('/')-1); this->filter_ratio = filter_ratio; updateImageSet(); }catch (const std::exception& e) { std::cout << "Could not read image because of:\n" << e.what(); } } /** * Updates the imageset of the object */ void picture::updateImageSet() { images[0].img = origImage.img.clone() ; images[0].img_gray = origImage.img_gray.clone() ; //scale image if(currentDPI != origDPI){ double scale = (double) currentDPI/origDPI; if(scale>1.0){ resize(this->images[0].img, this->images[0].img, Size(), scale, scale, cv::INTER_CUBIC); resize(this->images[0].img_gray, this->images[0].img_gray, Size(), scale, scale, cv::INTER_CUBIC); }else{ resize(this->images[0].img, this->images[0].img, Size(), scale, scale, cv::INTER_AREA); resize(this->images[0].img_gray, this->images[0].img_gray, Size(), scale, scale, cv::INTER_AREA); } } //create filter switch(this->filterType){ case 0: { Mat sobelX; Mat sobelY; Sobel(images[0].img_gray, sobelX, CV_16S, 1, 0, 3); Sobel(images[0].img_gray, sobelY, CV_16S, 0, 1, 3); // converting back to CV_8U Mat absX; Mat absY; convertScaleAbs(sobelX, absX); convertScaleAbs(sobelY, absY); addWeighted(absX, 0.5, absY, 0.5, 0, images[0].img_filter); break; } case 1: Canny(images[0].img_gray, images[0].img_filter, 255 / 3, 255); break; case 2: { Mat filter16S; Laplacian(images[0].img_gray, filter16S, CV_16S); convertScaleAbs(filter16S, images[0].img_filter); break; } default: std::cout << "Ignoring filter"; break; } images[0].img_filter = images[0].img_filter * this->filter_ratio + images[0].img_gray * (1-this->filter_ratio); images[0].mask = Mat(images[0].img_gray.rows, images[0].img_gray.cols , images[0].img_gray.type(), 255); } /** * Creates rotations of the original image. * @param n Number of rotations that should be added to standard rotation. */ void picture::addRotations(int n) { this->images.resize(n); auto src = images[0].img; auto src_gray = images[0].img_gray; auto src_filter = images[0].img_filter; auto src_mask = images[0].mask; for (int i = 1; i <images.size(); i++) { auto &pair = images[i]; double angle = i*360.0/n; // get rotation matrix for rotating the image around its center in pixel coordinates cv::Point2f center((src.cols-1)/2.0, (src.rows-1)/2.0); cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0); // determine bounding rectangle, center not relevant cv::Rect2f bbox = cv::RotatedRect(cv::Point2f(), src.size(), angle).boundingRect2f(); // adjust transformation matrix rot.at<double>(0,2) += bbox.width/2.0 - src.cols/2.0; rot.at<double>(1,2) += bbox.height/2.0 - src.rows/2.0; cv::warpAffine(src, pair.img, rot, bbox.size()); cv::warpAffine(src_gray, pair.img_gray, rot, bbox.size()); cv::warpAffine(src_filter, pair.img_filter, rot, bbox.size()); cv::warpAffine(src_mask, pair.mask, rot, bbox.size()); } } /** * Updates the masks of all rotations. */ void picture::updateMasks() { auto src = images[0].mask; for (int i = 1; i < images.size(); i++) { auto &pair = images[i]; double angle = i * 360.0 / images.size(); // get rotation matrix for rotating the image around its center in pixel coordinates cv::Point2f center((src.cols - 1) / 2.0, (src.rows - 1) / 2.0); cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0); // determine bounding rectangle, center not relevant cv::Rect2f bbox = cv::RotatedRect(cv::Point2f(), src.size(), angle).boundingRect2f(); // adjust transformation matrix rot.at<double>(0, 2) += bbox.width / 2.0 - src.cols / 2.0; rot.at<double>(1, 2) += bbox.height / 2.0 - src.rows / 2.0; cv::warpAffine(src, pair.mask, rot, bbox.size()); } } /** * Scales the images and updates the rotations */ void picture::scaleTo(unsigned int dpi) { this->currentDPI = dpi; updateImageSet(); addRotations(images.size()); } /** * Performs histogram matching based on the given histogram * @param targetHist Histogram that should be matched. * @param channel Color channel that should be used for histogram matching. * @param ratio Ratio between original color values and histogram matched color values. */ void picture::transformHistTo(cv::Mat targetHist, int channel, double ratio) { auto &s = this->origImage.img; int channels[] = {channel}; int histSize[] = {255}; float r[] = {0,256}; const float *ranges[] = {r}; cv::Mat inputHist; cv::calcHist(&s, 1, channels, cv::Mat(), inputHist, 1, histSize, ranges, true, false); //normalize cv::normalize(targetHist, targetHist, 1, 0, cv::NORM_L1); cv::normalize(inputHist, inputHist, 1, 0, cv::NORM_L1); //generate cdfs std::vector<double> cdf_t(256); std::vector<double> cdf_i(256); cdf_t[0] = targetHist.at<float>(0); cdf_i[0] = inputHist.at<float>(0); for (int j = 0; j < 256; j++) { cdf_t[j + 1] += cdf_t[j] + targetHist.at<float>(j + 1); cdf_i[j + 1] += cdf_i[j] + inputHist.at<float>(j + 1); } std::vector<uchar> T_target(256); std::vector<uchar> T_input(256); for (int j = 0; j<256; j++) { T_target[j] = floor(255 * cdf_t[j]); T_input[j] = floor(255 * cdf_i[j]); } //create mapping std::vector<int> map(256); for (int i = 0; i < 256; ++i) { int diff = abs(T_input[i]-T_target[0]); map[i] = 0; for (int j = 0; j < 256; ++j) { if(abs(T_input[i]-T_target[j])<diff){ map[i] = j; diff = abs(T_input[i]-T_target[j]); } } } //apply map cv::Mat workingChannel; cv::Mat origChannel; cv::extractChannel(this->origImage.img, workingChannel,channel); cv::extractChannel(this->origImage.img, origChannel,channel); workingChannel.forEach<uchar>( [map](uchar &x, const int * position){ x= map[x]; }); workingChannel = workingChannel*ratio+origChannel*(1-ratio); cv::insertChannel(workingChannel,this->origImage.img, channel); cvtColor(this->origImage.img, this->origImage.img_gray, cv::COLOR_BGR2GRAY); this->updateImageSet(); } /** * Removes pixel of a certain color from the image and adds them to the mask. * @param color Color that should be part of the mask */ void picture::addColorToMask(Vec3b color) { for(int i = 0; i < this->origImage.img.rows; i++) { const cv::Vec3b *Pi = this->origImage.img.ptr<cv::Vec3b >(i); auto *Mi = this->origImage.mask.ptr<uchar>(i); for(int j = 0; j < this->origImage.img.cols; j++) if(Pi[j] == color) { Mi[j] = 0; } } this->images[0].mask = images[0].mask.clone(); cv::resize(this->origImage.mask,this->images[0].mask, cv::Size(images[0].mask.cols,images[0].mask.rows)); updateMasks(); } /** * Creates a combined histogram of a list of images. * @param picList List of images. * @param channel Color channel that should be used for histogram creation. * @returns Cumulative Histogram of the images. */ cv::Mat cumulativeHist(std::vector<picture> &picList, int channel) { cv::Mat hist; for (auto &p : picList) { auto &s = p.origImage.img; int channels[] = {channel}; int histSize[] = {255}; float r[] = {0,256}; const float *ranges[] = {r}; cv::calcHist(&s,1,channels,cv::Mat(),hist,1,histSize, ranges, true, true); } return hist; }
34.476015
136
0.597346
[ "object", "vector" ]
5873e7f3ae532dde47c8e60d550b1fb157b87448
5,024
cpp
C++
NaoTHSoccer/Source/Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/SampleSet.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
15
2015-01-12T10:46:29.000Z
2022-03-28T05:13:14.000Z
NaoTHSoccer/Source/Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/SampleSet.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
2
2019-01-20T21:07:50.000Z
2020-01-22T14:00:28.000Z
NaoTHSoccer/Source/Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/SampleSet.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
5
2018-02-07T18:18:10.000Z
2019-10-15T17:01:41.000Z
/** * @file SampleSet.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of class SampleSet */ #include <algorithm> #include "SampleSet.h" #include "Tools/Debug/NaoTHAssert.h" #include "Tools/Math/Common.h" void SampleSet::sort(bool descending) { if(samples.size() > 1) { quicksort(descending?1:-1, 0, ((int)samples.size())-1); } } void SampleSet::quicksort(int d, int low, int high) { int i = low; int j = high; Sample help; /* compare value */ double z = samples[(low + high) / 2].likelihood*d; /* partition */ do { /* find member above ... */ while(samples[i].likelihood*d > z) i++; /* find element below ... */ while(samples[j].likelihood*d < z) j--; if(i <= j) { /* swap two elements */ help = samples[i]; samples[i] = samples[j]; samples[j] = help; i++; j--; }//end if } while(i <= j); /* recurse */ if(low < j) { quicksort(d, low, j); } if(i < high) { quicksort(d, i, high); } }//end quicksort void SampleSet::normalize(double offset) { double sum = 0.0; for(size_t i = 0; i < samples.size(); i++) { samples[i].likelihood = samples[i].likelihood; sum += samples[i].likelihood; } if(sum == 0) { return; } double offset_sum = 1.0+offset*(double)samples.size(); for(size_t i = 0; i < samples.size(); i++) { samples[i].likelihood = ((samples[i].likelihood/sum) + offset)/offset_sum; } }//end normalize void SampleSet::resetLikelihood() { double likelihood = 1.0/static_cast<double>(samples.size()); setLikelihood(likelihood); } void SampleSet::setLikelihood(double v) { for(size_t i = 0; i < samples.size(); i++) { samples[i].likelihood = v; } } Sample SampleSet::meanOfLargestCluster(Moments2<2>& moments) const { ASSERT(samples.size() > 0); // TODO: make it better std::vector<int> cluster(samples.size()); int maxIndex = 0; double maxNumber = 0; for(size_t i = 0; i < samples.size(); i++) { if(samples[i].cluster >= 0 && samples[i].cluster < (int)samples.size()) { int idx = samples[i].cluster; cluster[idx]++; if(maxNumber < cluster[idx]) { maxIndex = idx; maxNumber = cluster[idx]; } }//end if }//end for return meanOfCluster(moments, maxIndex); }//end meanOfLargestCluster Sample SampleSet::meanOfCluster(Moments2<2>& moments, int idx) const { ASSERT(samples.size() > 0); Vector2d averageTranslation; Vector2d averageRotation; double numberOfSamples = 0; // calculate the covariance of the largest cluster for(size_t i = 0; i < samples.size(); i++) { const Sample& sample = samples[i]; if(sample.cluster == idx) { averageTranslation += sample.translation; averageRotation.x += cos(sample.rotation); averageRotation.y += sin(sample.rotation); moments.add(sample.translation); numberOfSamples++; } } Sample result; result.cluster = idx; if(numberOfSamples > 0) { result.translation = averageTranslation/numberOfSamples; result.rotation = (averageRotation/numberOfSamples).angle(); } return result; }//end meanOfCluster const Sample& SampleSet::getMostLikelySample() const { ASSERT(samples.size() > 0); double maxLikelihood = samples[0].likelihood; int maxIdx = 0; for(size_t i = 1; i < samples.size(); i++) { if(maxLikelihood < samples[i].likelihood) { maxLikelihood = samples[i].likelihood; maxIdx = (int)i; } } return samples[maxIdx]; } void SampleSet::drawCluster(DrawingCanvas2D& canvas, unsigned int clusterId) const { ASSERT(samples.size() > 0); for (size_t i = 0; i < samples.size(); i++) { if (samples[i].cluster == (int)clusterId) { canvas.pen("FFFFFF", 20); } else { canvas.pen("000000", 20); } canvas.drawArrow(samples[i].translation.x, samples[i].translation.y, samples[i].translation.x + 100*cos(samples[i].rotation), samples[i].translation.y + 100*sin(samples[i].rotation)); } } void SampleSet::drawImportance(DrawingCanvas2D& canvas, bool /*arrows*/) const { ASSERT(samples.size() > 0); // normalize the colors (black: less importent, red more importent) double minValue = samples[0].likelihood; double maxValue = samples[0].likelihood; for (size_t i = 1; i < samples.size(); i++) { maxValue = std::max(samples[i].likelihood, maxValue); minValue = std::min(samples[i].likelihood, minValue); } double colorDiff = log(maxValue) - log(minValue); for (size_t i = 0; i < samples.size(); i++) { Color color; if(colorDiff > 0) { color[0] = Math::clamp((log(samples[i].likelihood) - log(minValue))/colorDiff,0.0,1.0); } canvas.pen(color, 20); canvas.drawArrow(samples[i].translation.x, samples[i].translation.y, samples[i].translation.x + 100*cos(samples[i].rotation), samples[i].translation.y + 100*sin(samples[i].rotation)); } }
23.045872
93
0.624005
[ "vector" ]
5880b52ff72f0e9a0124fb0086992f1b1cf3ca43
734
cpp
C++
DataStructures/整数拆分.cpp
Yurzi/Jlu-C-OJ
1bbf0532ded06b31e6516f90270760f11ccb1b3c
[ "MIT" ]
7
2020-11-02T13:15:36.000Z
2021-07-06T05:09:55.000Z
DataStructures/整数拆分.cpp
Yurzi/Jlu-C-OJ
1bbf0532ded06b31e6516f90270760f11ccb1b3c
[ "MIT" ]
null
null
null
DataStructures/整数拆分.cpp
Yurzi/Jlu-C-OJ
1bbf0532ded06b31e6516f90270760f11ccb1b3c
[ "MIT" ]
null
null
null
#include<iostream> #include<queue> using namespace std; int n=0;int k=0; int count=0; vector<int> res; int toslove(int x,int _k,int q,int sum){ if(_k==0){ if(sum==n){ ++count; for (int i=0;i<res.size();++i) { printf("%d",res[i]); if(i<res.size()-1)printf(" "); } printf("\n"); return 0; }else{ return 0; } } for(int i=q;i<=x/_k;++i){ res.push_back(i); toslove(x-i,_k-1,i,sum+i); res.pop_back(); } return 0; } int main(int argc, char const *argv[]) { scanf("%d %d",&n,&k); toslove(n,k,1,0); printf("%d\n",count); return 0; }
17.47619
46
0.433243
[ "vector" ]
58831de2c2bb62b11005f6767c6eb67ade332543
2,243
cpp
C++
Greedy Algorithmic Paradigm/Activity Selection Problem.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Greedy Algorithmic Paradigm/Activity Selection Problem.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Greedy Algorithmic Paradigm/Activity Selection Problem.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// We'll greedily select those activities which END first. /*==============================================================================================================*/ // Problem: I AM VERY BUSY // Contest: SPOJ - Classical // URL: https://www.spoj.com/problems/BUSYMAN/ // Memory Limit: 1536 MB // Time Limit: 1000 ms // Parsed on: 16-11-2020 14:33:57 IST (UTC+05:30) // Author: kapil_choudhary #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int mod = 1e9+7; class myComparator{ public: bool operator()(pair<int, int> &p1, pair<int, int> &p2){ if(p1.second == p2.second){ return p1.first < p2.first; } return p1.second < p2.second; } }; void solve() { int n; cin >> n; vpii v(n); for(int i = 0; i < n; i++){ int start, end; cin >> start >> end; v[i] = {start, end}; } sort(v.begin(), v.end(), myComparator()); int res = 1, end_prev = v[0].second; for(int i = 1; i < n; i++){ if(v[i].first >= end_prev){ res++; end_prev = v[i].second; } } cout << res << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); int t = 1; cin >> t; while(t--) { solve(); } return 0; } // Time complexity: O(n x log(n)) (for 1 test case) // Space complexity: O(1) /****************************************************************************************************/ // NOTE: Using similar concepts following can also be solved ---> // https://www.geeksforgeeks.org/maximum-trains-stoppage-can-provided/
23.861702
114
0.574231
[ "vector" ]
5885a6f789c7ab6b153ccaf6f1adb6ae6a5699f5
8,941
cpp
C++
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/tools/dbbuilder/dbbuilder.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/tools/dbbuilder/dbbuilder.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/tools/dbbuilder/dbbuilder.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (C) 2014 InfiniDB, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /******************************************************************************* * $Id: dbbuilder.cpp 2101 2013-01-21 14:12:52Z rdempsey $ * *******************************************************************************/ #include <stdio.h> #include <unistd.h> #include <cerrno> #include <stdexcept> using namespace std; #include <boost/algorithm/string.hpp> #include "mcsconfig.h" #include "dbbuilder.h" #include "systemcatalog.h" #include "liboamcpp.h" #include "configcpp.h" #include "IDBPolicy.h" using namespace oam; using namespace dmlpackageprocessor; using namespace dmlpackage; using namespace idbdatafile; #include "objectidmanager.h" using namespace execplan; #include "installdir.h" string tmpDir; string logFile; enum BUILD_OPTION { SYSCATALOG_ONLY = 7, //Create systables only }; namespace { int setUp() { #ifndef _MSC_VER string cmd = "/bin/rm -f " + logFile + " >/dev/null 2>&1"; int rc = system(cmd.c_str()); cmd = "/bin/touch -f " + logFile + " >/dev/null 2>&1"; rc = system(cmd.c_str()); #endif return rc; } int checkNotThere(WriteEngine::FID fid) { WriteEngine::FileOp fileOp; return (fileOp.existsOIDDir(fid) ? -1 : 0); } void usage() { cerr << "Usage: dbbuilder [-h|f] function" << endl << " -h Display this help info" << endl << " -f Necessary to use any fcn other than 7" << endl << " fcn" << endl << " 7 Build system tables only" << endl << endl << "WARNING! Using this tool improperly can render your database unusable!" << endl ; } const unsigned sysCatalogErr = logging::M0060; void errorHandler(const unsigned mid, const string& src, const string& msg, bool isCritErr = true) { logging::LoggingID lid(19); logging::MessageLog ml(lid); logging::Message::Args args; logging::Message message(mid); if (isCritErr) { args.add(string("error")); args.add(msg); message.format( args ); ml.logCriticalMessage(message ); cout << src << " was not successful. " << msg << endl; } else { args.add(string("status")); args.add(msg); message.format( args ); ml.logInfoMessage(message ); cout << src << " was not completed. " << msg << endl; } } } int main(int argc, char* argv[]) { int buildOption; int c; std::string schema("tpch"); Oam oam; bool fFlg = false; int rc = 0; opterr = 0; while ((c = getopt(argc, argv, "u:fh")) != EOF) switch (c) { case 'u': schema = optarg; break; case 'f': fFlg = true; break; case 'h': case '?': default: usage(); return (c == 'h' ? 0 : 1); break; } if ((argc - optind) < 1) { usage(); return 1; } oamModuleInfo_t t; bool parentOAMModuleFlag = false; //get local module info; validate running on Active Parent OAM Module try { t = oam.getModuleInfo(); parentOAMModuleFlag = boost::get<4>(t); } catch (exception&) { parentOAMModuleFlag = true; } if ( !parentOAMModuleFlag ) { cerr << "Exiting, dbbuilder can only be run on the Active " "Parent OAM Module" << endl; return 1; } logFile = string(MCSLOGDIR) + "/install/dbbuilder.status"; buildOption = atoi(argv[optind++]); if (buildOption != 7 && !fFlg) { usage(); return 1; } if ( buildOption == SYSCATALOG_ONLY ) { if ( setUp() ) { cerr << "setUp() call error " << endl; } bool canWrite = true; if (access(logFile.c_str(), W_OK) != 0) canWrite = false; try { if (checkNotThere(1001) != 0) { string cmd = "echo 'FAILED: buildOption=" + oam.itoa(buildOption) + "' > " + logFile; if (canWrite) { rc = system(cmd.c_str()); } else { cerr << cmd << endl; } errorHandler(sysCatalogErr, "Build system catalog", "System catalog appears to exist. It will remain intact " "for reuse. The database is not recreated.", false); return 1; } //@bug5554, make sure IDBPolicy matches the Columnstore.xml config try { string calpontConfigFile(std::string(MCSSYSCONFDIR) + "/columnstore/Columnstore.xml"); config::Config* sysConfig = config::Config::makeConfig(calpontConfigFile.c_str()); string tmp = sysConfig->getConfig("Installation", "DBRootStorageType"); if (boost::iequals(tmp, "hdfs")) { // HDFS is configured if (!IDBPolicy::useHdfs()) // error install plugin throw runtime_error("HDFS is not enabled, installPlugin may have failed."); else if (!IDBFileSystem::getFs(IDBDataFile::HDFS).filesystemIsUp()) throw runtime_error("HDFS FS is NULL, check env variables."); } } catch (const exception& ex) { string cmd(string("echo 'FAILED: ") + ex.what() + "' > " + logFile); if (canWrite) rc = system(cmd.c_str()); else cerr << cmd << endl; errorHandler(sysCatalogErr, "Build system catalog", ex.what(), false); return 1; } catch (...) { string cmd = "echo 'FAILED: HDFS checking.' > " + logFile; if (canWrite) rc = system(cmd.c_str()); else cerr << cmd << endl; errorHandler(sysCatalogErr, "Build system catalog", "HDFS check failed.", false); return 1; } //create an initial oid bitmap file { ObjectIDManager oidm; } SystemCatalog sysCatalog; sysCatalog.build(); std::string cmd = "echo 'OK: buildOption=" + oam.itoa(buildOption) + "' > " + logFile; if (canWrite) rc = system(cmd.c_str()); else #ifdef _MSC_VER (void)0; #else cerr << cmd << endl; #endif cmd = "save_brm"; if (canWrite) { rc = system(cmd.c_str()); if (rc != 0) { ostringstream os; os << "Warning: running " << cmd << " failed. This is usually non-fatal."; cerr << os.str() << endl; errorHandler(sysCatalogErr, "Save BRM", os.str()); } } else cerr << cmd << endl; return 0; } catch (exception& ex) { string cmd = "echo 'FAILED: buildOption=" + oam.itoa(buildOption) + "' > " + logFile; if (canWrite) rc = system(cmd.c_str()); else cerr << cmd << endl; errorHandler(sysCatalogErr, "Build system catalog", ex.what()); } catch (...) { string cmd = "echo 'FAILED: buildOption=" + oam.itoa(buildOption) + "' > " + logFile; if (canWrite) rc = system(cmd.c_str()); else cerr << cmd << endl; string err("Caught unknown exception!"); errorHandler(sysCatalogErr, "Build system catalog", err); } } else { usage(); return 1; } return 1; } // vim:ts=4 sw=4:
26.219941
102
0.489319
[ "render" ]
58868a7b42d8f7eb3f24641c2a78e22bb3bd7763
7,015
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Geometry/Topology/SEGMENT_MESH.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
PhysBAM/Public_Library/PhysBAM_Geometry/Topology/SEGMENT_MESH.cpp
uwgraphics/PhysicsBasedModeling-Core
dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b
[ "BSD-3-Clause" ]
null
null
null
PhysBAM/Public_Library/PhysBAM_Geometry/Topology/SEGMENT_MESH.cpp
uwgraphics/PhysicsBasedModeling-Core
dbc65b8e93b1a3d69fcc82aba06d28dc6c0adb8b
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2002-2009, Robert Bridson, Ronald Fedkiw, Jon Gretarsson, Geoffrey Irving, Sergey Koltakov, Nipun Kwatra, Frank Losasso, Neil Molino, Eftychios Sifakis, Jerry Talton. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class SEGMENT_MESH //##################################################################### #include <PhysBAM_Tools/Data_Structures/UNION_FIND.h> #include <PhysBAM_Geometry/Topology/POINT_SIMPLEX_MESH.h> #include <PhysBAM_Geometry/Topology/SEGMENT_MESH.h> using namespace PhysBAM; //##################################################################### // Constructor //##################################################################### SEGMENT_MESH:: SEGMENT_MESH() :connected_segments(0),ordered_loop_nodes(0),boundary_mesh(0) {} //##################################################################### // Constructor //##################################################################### SEGMENT_MESH:: SEGMENT_MESH(const int number_nodes_input,const ARRAY<VECTOR<int,2> >& segment_list) :SIMPLEX_MESH<1>(number_nodes_input,segment_list),connected_segments(0),ordered_loop_nodes(0),boundary_mesh(0) {} //##################################################################### // Constructor //##################################################################### SEGMENT_MESH:: SEGMENT_MESH(const SEGMENT_MESH& segment_mesh) :SIMPLEX_MESH<1>(segment_mesh),connected_segments(0),ordered_loop_nodes(0),boundary_mesh(0) {} //##################################################################### // Destructor //##################################################################### SEGMENT_MESH:: ~SEGMENT_MESH() { delete connected_segments;delete ordered_loop_nodes; } //##################################################################### // Function Delete_Auxiliary_Structures //##################################################################### void SEGMENT_MESH:: Delete_Auxiliary_Structures() { SIMPLEX_MESH<1>::Delete_Auxiliary_Structures(); delete connected_segments;connected_segments=0;delete ordered_loop_nodes;ordered_loop_nodes=0; } //##################################################################### // Function Refresh_Auxiliary_Structures //##################################################################### void SEGMENT_MESH:: Refresh_Auxiliary_Structures() { SIMPLEX_MESH<1>::Refresh_Auxiliary_Structures(); if(connected_segments) Initialize_Connected_Segments();if(ordered_loop_nodes) Initialize_Ordered_Loop_Nodes(); } //##################################################################### // Function Initialize_Connected_Segments //##################################################################### void SEGMENT_MESH:: Initialize_Connected_Segments() { delete connected_segments;connected_segments=new ARRAY<ARRAY<VECTOR<int,2> > >; UNION_FIND<> union_find(number_nodes);Add_Connectivity(union_find); ARRAY<int> buckets; for(int s=1;s<=elements.m;s++){ int bucket=union_find.Find(elements(s)(1)); int index=buckets.Find(bucket); if(!index){ connected_segments->Append(ARRAY<VECTOR<int,2> >()); buckets.Append(bucket); index=connected_segments->m;} (*connected_segments)(index).Append(elements(s));} } //##################################################################### // Function Initialize_Ordered_Loop_Nodes //##################################################################### void SEGMENT_MESH:: Initialize_Ordered_Loop_Nodes() { delete ordered_loop_nodes;ordered_loop_nodes=new ARRAY<ARRAY<int> >; bool created_neighbor_nodes=false,created_connected_segments=false; if(!neighbor_nodes){Initialize_Neighbor_Nodes();created_neighbor_nodes=true;} if(!connected_segments){Initialize_Connected_Segments();created_connected_segments=true;} for(int i=1;i<=connected_segments->m;i++){ for(int j=1;j<=(*connected_segments)(i).m;j++)for(int k=1;k<=2;k++)if((*neighbor_nodes)((*connected_segments)(i)(j)(k)).m!=2) goto not_closed; ordered_loop_nodes->Append(ARRAY<int>()); {int start_node=(*connected_segments)(i)(1)(1),curr_node=(*connected_segments)(i)(1)(2); ordered_loop_nodes->Last().Append(start_node); do{ int previous_node=ordered_loop_nodes->Last().Last(),neighbor1=(*neighbor_nodes)(curr_node)(1),neighbor2=(*neighbor_nodes)(curr_node)(2); ordered_loop_nodes->Last().Append(curr_node); curr_node=previous_node==neighbor1?neighbor2:neighbor1;} while(curr_node!=start_node);} not_closed: continue;} if(created_neighbor_nodes){delete neighbor_nodes;neighbor_nodes=0;} if(created_connected_segments){delete connected_segments;connected_segments=0;} } //##################################################################### // Function Initialize_Straight_Mesh //##################################################################### void SEGMENT_MESH:: Initialize_Straight_Mesh(const int number_of_points,bool loop) { Clean_Memory(); number_nodes=number_of_points; elements.Exact_Resize(number_of_points-!loop); for(int i=1;i<number_of_points;i++)elements(i).Set(i,i+1); if(loop)elements(number_of_points).Set(number_of_points,1); } //##################################################################### // Function Initialize_Boundary_Mesh //##################################################################### void SEGMENT_MESH:: Initialize_Boundary_Mesh() { delete boundary_mesh; boundary_mesh=new T_BOUNDARY_MESH(); ARRAY<VECTOR<int,dimension> >& boundary_elements=boundary_mesh->elements; ARRAY<bool>& boundary_directions=boundary_mesh->directions; bool incident_elements_defined=incident_elements!=0; if(!incident_elements_defined) Initialize_Incident_Elements(); for(int i=1;i<=incident_elements->m;++i){ ARRAY<int>& current_incident_elements=(*incident_elements)(i); if(current_incident_elements.m==1){ boundary_elements.Append(VECTOR<int,dimension>(i)); boundary_directions.Append(elements(current_incident_elements(1)).x!=i);}} boundary_elements.Compact();boundary_directions.Compact(); boundary_mesh->number_nodes=number_nodes; if(incident_elements_defined){delete incident_elements;incident_elements=0;} } //##################################################################### // Function Assert_Consistent //##################################################################### bool SEGMENT_MESH:: Assert_Consistent() const { if(connected_segments && ordered_loop_nodes) assert(connected_segments->m==ordered_loop_nodes->m); return SIMPLEX_MESH<1>::Assert_Consistent(); } //#####################################################################
47.080537
179
0.557234
[ "vector" ]
588c9c48608e90703f242f66fe69f8248793e99c
1,407
cpp
C++
Medium/partition-list.cpp
AnanyaDas162/Leetcode-Solutions
00f3982f2a48cc7ef3341565b237a1f9637d26f5
[ "MIT" ]
1
2021-11-21T16:04:59.000Z
2021-11-21T16:04:59.000Z
Medium/partition-list.cpp
AnanyaDas162/Leetcode-Solutions
00f3982f2a48cc7ef3341565b237a1f9637d26f5
[ "MIT" ]
null
null
null
Medium/partition-list.cpp
AnanyaDas162/Leetcode-Solutions
00f3982f2a48cc7ef3341565b237a1f9637d26f5
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector <int> v1, v2; ListNode* partition(ListNode* head, int x) { ListNode *temp = head; while (temp){ if (temp -> val < x){ v1.push_back(temp -> val); } else{ v2.push_back(temp -> val); } temp = temp -> next; } head = NULL; ListNode *tail = NULL; for (int i = 0; i < v1.size(); i ++){ ListNode *newnode = new ListNode (v1[i]); if (head == NULL){ head = newnode; tail = newnode; } else{ tail -> next = newnode; tail = newnode; } } for (int i = 0; i < v2.size(); i ++){ ListNode *newnode = new ListNode (v2[i]); if (head == NULL){ head = newnode; tail = newnode; } else{ tail -> next = newnode; tail = newnode; } } return head; } };
27.588235
63
0.38877
[ "vector" ]
588d97b9cc754790e490b882cfa73359fb3b8787
6,354
cpp
C++
src/blockslideshowscreen.cpp
ant512/EarthShakerDS
c23920bb96652570616059ee4b807e82617c2385
[ "MIT" ]
null
null
null
src/blockslideshowscreen.cpp
ant512/EarthShakerDS
c23920bb96652570616059ee4b807e82617c2385
[ "MIT" ]
null
null
null
src/blockslideshowscreen.cpp
ant512/EarthShakerDS
c23920bb96652570616059ee4b807e82617c2385
[ "MIT" ]
null
null
null
#include "barrierblock.h" #include "barriercontrolblock.h" #include "beanblock.h" #include "bitmapserver.h" #include "blockslideshowscreen.h" #include "boulderblock.h" #include "bubbleblock.h" #include "constants.h" #include "diamondblock.h" #include "doorblock.h" #include "extralifeblock.h" #include "fireblock.h" #include "gravityinversionblock.h" #include "spectrumcolours.h" #include "teleportblock.h" #include "wetsoilblock.h" BlockSlideshowScreen::BlockSlideshowScreen(WoopsiGfx::Graphics* gfx) : ScreenBase(NULL, gfx) { _block = new TeleportBlock(0, 0, NULL); _timer = 0; _state = SCREEN_STATE_DOOR_ERASE; } BlockSlideshowScreen::~BlockSlideshowScreen() { delete _block; } void BlockSlideshowScreen::moveToNextState() { switch (_state) { case SCREEN_STATE_TELEPORT: _state = SCREEN_STATE_TELEPORT_ERASE; break; case SCREEN_STATE_TELEPORT_ERASE: _state = SCREEN_STATE_BEAN; break; case SCREEN_STATE_BEAN: _state = SCREEN_STATE_BEAN_ERASE; break; case SCREEN_STATE_BEAN_ERASE: _state = SCREEN_STATE_EXTRA_LIFE; break; case SCREEN_STATE_EXTRA_LIFE: _state = SCREEN_STATE_EXTRA_LIFE_ERASE; break; case SCREEN_STATE_EXTRA_LIFE_ERASE: _state = SCREEN_STATE_DIAMOND; break; case SCREEN_STATE_DIAMOND: _state = SCREEN_STATE_DIAMOND_ERASE; break; case SCREEN_STATE_DIAMOND_ERASE: _state = SCREEN_STATE_BUBBLE; break; case SCREEN_STATE_BUBBLE: _state = SCREEN_STATE_BUBBLE_ERASE; break; case SCREEN_STATE_BUBBLE_ERASE: _state = SCREEN_STATE_FIRE; break; case SCREEN_STATE_FIRE: _state = SCREEN_STATE_FIRE_ERASE; break; case SCREEN_STATE_FIRE_ERASE: _state = SCREEN_STATE_GRAVITY; break; case SCREEN_STATE_GRAVITY: _state = SCREEN_STATE_GRAVITY_ERASE; break; case SCREEN_STATE_GRAVITY_ERASE: _state = SCREEN_STATE_BARRIER; break; case SCREEN_STATE_BARRIER: _state = SCREEN_STATE_BARRIER_ERASE; break; case SCREEN_STATE_BARRIER_ERASE: _state = SCREEN_STATE_BARRIER_CONTROLLER; break; case SCREEN_STATE_BARRIER_CONTROLLER: _state = SCREEN_STATE_BARRIER_CONTROLLER_ERASE; break; case SCREEN_STATE_BARRIER_CONTROLLER_ERASE: _state = SCREEN_STATE_BOULDER; break; case SCREEN_STATE_BOULDER: _state = SCREEN_STATE_BOULDER_ERASE; break; case SCREEN_STATE_BOULDER_ERASE: _state = SCREEN_STATE_DOOR; break; case SCREEN_STATE_DOOR: _state = SCREEN_STATE_DOOR_ERASE; break; case SCREEN_STATE_DOOR_ERASE: _state = SCREEN_STATE_WET_SOIL; break; case SCREEN_STATE_WET_SOIL: _state = SCREEN_STATE_WET_SOIL_ERASE; break; case SCREEN_STATE_WET_SOIL_ERASE: _state = SCREEN_STATE_TELEPORT; break; } } void BlockSlideshowScreen::getNextBlock() { if (_block != NULL) { delete _block; _block = NULL; } switch (_state) { case SCREEN_STATE_BARRIER: _block = new BarrierBlock(0, 0, NULL); _blockName.setText("Forcefield"); _blockDescription.setText("Blocks the path"); break; case SCREEN_STATE_BARRIER_CONTROLLER: _block = new BarrierControlBlock(0, 0, NULL); _blockName.setText("Forcefield Controller"); _blockDescription.setText("Crush to disable forcefields"); break; case SCREEN_STATE_BEAN: _block = new BeanBlock(0, 0, NULL); _blockName.setText("Jelly Bean"); _blockDescription.setText("Collect for extra time"); break; case SCREEN_STATE_BOULDER: _block = new BoulderBlock(0, 0, NULL); _blockName.setText("Boulder"); _blockDescription.setText("Dangerous when falling"); break; case SCREEN_STATE_BUBBLE: _block = new BubbleBlock(0, 0, NULL); _blockName.setText("Bubble"); _blockDescription.setText("Extinguishes fires"); break; case SCREEN_STATE_DIAMOND: _block = new DiamondBlock(0, 0, NULL); _blockName.setText("Diamond"); _blockDescription.setText("Collect to progress"); break; case SCREEN_STATE_DOOR: _block = new DoorBlock(0, 0, NULL); _blockName.setText("Door"); _blockDescription.setText("Enter here to exit level"); break; case SCREEN_STATE_EXTRA_LIFE: _block = new ExtraLifeBlock(0, 0, NULL); _blockName.setText("Elixir"); _blockDescription.setText("Collect for an extra life"); break; case SCREEN_STATE_FIRE: _block = new FireBlock(0, 0, NULL); _blockName.setText("Fire"); _blockDescription.setText("Dangerous to touch"); break; case SCREEN_STATE_GRAVITY: _block = new GravityInversionBlock(0, 0, NULL); _blockName.setText("Gravity Inverter"); _blockDescription.setText("Swaps gravity direction"); break; case SCREEN_STATE_TELEPORT: _block = new TeleportBlock(0, 0, NULL); _blockName.setText("Teleporter"); _blockDescription.setText("Teleport to a new place"); break; case SCREEN_STATE_WET_SOIL: _block = new WetSoilBlock(0, 0, NULL); _blockName.setText("Wet Soil"); _blockDescription.setText("Soil that can fall"); break; default: break; } } void BlockSlideshowScreen::iterate() { switch (_state) { case SCREEN_STATE_TELEPORT_ERASE: case SCREEN_STATE_BEAN_ERASE: case SCREEN_STATE_EXTRA_LIFE_ERASE: case SCREEN_STATE_DIAMOND_ERASE: case SCREEN_STATE_BUBBLE_ERASE: case SCREEN_STATE_FIRE_ERASE: case SCREEN_STATE_GRAVITY_ERASE: case SCREEN_STATE_BARRIER_ERASE: case SCREEN_STATE_BARRIER_CONTROLLER_ERASE: case SCREEN_STATE_BOULDER_ERASE: case SCREEN_STATE_DOOR_ERASE: case SCREEN_STATE_WET_SOIL_ERASE: _bottomGfx->drawFilledRect(0, 0, 256, 192, COLOUR_BLACK); _timer = 0; moveToNextState(); getNextBlock(); break; default: ++_timer; if (_timer % ANIMATION_TIME == 0) { _block->animate(); _block->render(BLOCK_DISPLAY_X, BLOCK_DISPLAY_Y, _bottomGfx); _bottomGfx->drawText((SCREEN_WIDTH - _font.getStringWidth(_blockName)) / 2, 144, &_font, _blockName, 0, _blockName.getLength(), COLOUR_WHITE); _bottomGfx->drawText((SCREEN_WIDTH - _font.getStringWidth(_blockDescription)) / 2, 160, &_font, _blockDescription, 0, _blockDescription.getLength(), COLOUR_CYAN); } if (_timer == BLOCK_DISPLAY_TIME) moveToNextState(); break; } } bool BlockSlideshowScreen::isRunning() const { return true; }
29.281106
167
0.723481
[ "render" ]
589730583bd6094df00a2898b5b4f138097e07c0
322
cc
C++
test/vector_copy_test.cc
mayhemheroes/cista
c889baf253081571913b88b26ad30be0104a82cd
[ "MIT" ]
843
2019-01-03T11:33:00.000Z
2022-03-27T08:09:46.000Z
test/vector_copy_test.cc
mayhemheroes/cista
c889baf253081571913b88b26ad30be0104a82cd
[ "MIT" ]
58
2019-01-03T20:32:02.000Z
2022-01-31T17:25:42.000Z
test/vector_copy_test.cc
mayhemheroes/cista
c889baf253081571913b88b26ad30be0104a82cd
[ "MIT" ]
63
2019-01-04T03:00:04.000Z
2022-03-30T20:01:22.000Z
#include "doctest.h" #ifdef SINGLE_HEADER #include "cista.h" #else #include "cista/containers/vector.h" #endif TEST_CASE("to_tuple") { namespace data = cista::offset; data::vector<uint32_t> a; a.emplace_back(1u); a.emplace_back(2u); a.emplace_back(3u); data::vector<uint32_t> b; b = a; CHECK(a == b); }
16.1
36
0.673913
[ "vector" ]
58a1af35ec1c791a9b8b00519f2ffddc6d26f7b2
619
cpp
C++
gfg/longest-increasing-subsequence.cpp
rishabhiitbhu/hackerrank
acc300851c81a29472177f15fd8b56ebebe853ea
[ "MIT" ]
null
null
null
gfg/longest-increasing-subsequence.cpp
rishabhiitbhu/hackerrank
acc300851c81a29472177f15fd8b56ebebe853ea
[ "MIT" ]
null
null
null
gfg/longest-increasing-subsequence.cpp
rishabhiitbhu/hackerrank
acc300851c81a29472177f15fd8b56ebebe853ea
[ "MIT" ]
1
2020-01-30T06:47:09.000Z
2020-01-30T06:47:09.000Z
#include <iostream> #include <vector> using namespace std; int main(){ int t, n, i, j, k, max; cin>>t; for(i=0;i<t;i++){ cin>>n; int arr[n]; int LIS[n]; for(j=0;j<n;j++){ cin>>arr[j]; } for(j=0;j<n;j++){ // cout<<"\nj = "<<j<<endl; max = 0; for(k=j-1;k>=0;k--){ if(LIS[k] > max && arr[j] > arr[k]) max = LIS[k]; } // cout<<"max = "<<max<<endl; LIS[j] = (max!=0) ? max + 1 : 1; // cout<<"LIS = "<<LIS[j]<<endl; } max=0; for(j=0;j<n;j++){ if(max<LIS[j]) max=LIS[j]; } cout<<max<<endl; } return 0; }
16.289474
57
0.407108
[ "vector" ]
58ac1d81018bd7b51651496eaea2302484d0f57b
2,362
cpp
C++
Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/IO/mitkUSNavigationLoggingBackend.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/IO/mitkUSNavigationLoggingBackend.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/IO/mitkUSNavigationLoggingBackend.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. 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 or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSNavigationLoggingBackend.h" #include <mitkCommon.h> mitk::USNavigationLoggingBackend::USNavigationLoggingBackend() { } mitk::USNavigationLoggingBackend::~USNavigationLoggingBackend() { if ( m_OutputStream.is_open() ) { m_OutputStream.close(); } } void mitk::USNavigationLoggingBackend::SetOutputFileName(std::string filename) { if ( m_OutputStream.is_open() ) { m_OutputStream.close(); } m_OutputStream.open(filename.c_str()); if ( ! m_OutputStream.is_open() ) { MITK_ERROR("USNavigationLoggingBackend") << "File '" << filename << "' cannot be opened for logging."; mitkThrow() << "File '" << filename << "' cannot be opened for logging."; } } void mitk::USNavigationLoggingBackend::ProcessMessage(const mbilog::LogMessage& logMessage) { if ( m_OutputStream.is_open()) {this->FormatSmart(m_OutputStream, logMessage);} if (logMessage.category == "USNavigationLogging") { m_lastNavigationMessages.push_back(logMessage.message); m_allNavigationMessages.push_back(logMessage.message); } } std::vector<std::string> mitk::USNavigationLoggingBackend::GetNavigationMessages() { return m_lastNavigationMessages; } void mitk::USNavigationLoggingBackend::WriteCSVFileWithNavigationMessages(std::string filename) { std::ofstream csvStream; csvStream.open(filename.c_str()); if ( ! csvStream.is_open() ) {MITK_ERROR("USNavigationLoggingBackend") << "File '" << filename << "' cannot be opened for logging."; return;} for (int i = 0; i < m_allNavigationMessages.size(); i++) { csvStream << m_allNavigationMessages.at(i) << "\n"; } csvStream.close(); } void mitk::USNavigationLoggingBackend::ClearNavigationMessages() { m_lastNavigationMessages = std::vector<std::string>(); } mbilog::OutputType mitk::USNavigationLoggingBackend::GetOutputType() const { return mbilog::File; }
29.898734
143
0.699831
[ "vector" ]
58b05bcc306fa98d3fe419c8870647d70e08f56e
8,167
h++
C++
deps/wheels/include/wheels/overload.h++
picanumber/named-operator
71910f8af4c55260629e6bd423981aa27c0ed2e5
[ "Apache-2.0" ]
1
2015-10-22T09:01:04.000Z
2015-10-22T09:01:04.000Z
deps/wheels/include/wheels/overload.h++
picanumber/named-operator
71910f8af4c55260629e6bd423981aa27c0ed2e5
[ "Apache-2.0" ]
null
null
null
deps/wheels/include/wheels/overload.h++
picanumber/named-operator
71910f8af4c55260629e6bd423981aa27c0ed2e5
[ "Apache-2.0" ]
null
null
null
// Wheels - various C++ utilities // // Written in 2012 by Martinho Fernandes <martinho.fernandes@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Overloaded function object #ifndef WHEELS_OVERLOAD_HPP #define WHEELS_OVERLOAD_HPP #include "meta.h++" #include "detail/config.h++" #include <boost/preprocessor/repetition/enum.hpp> namespace wheels { namespace overload_detail { template <typename Fun> class simple_overload_element : Fun { public: simple_overload_element() = default; template <typename T, DisableIf<is_related<simple_overload_element, T>> = _> explicit simple_overload_element(T&& t) : Fun(std::forward<T>(t)) {} using Fun::operator(); }; template <typename Ret, typename... Args> class simple_overload_element<Ret(*)(Args...)> { using fun_type = Ret(*)(Args...); public: simple_overload_element() = delete; template <typename T, DisableIf<is_related<simple_overload_element, T>> = _> explicit simple_overload_element(T&& t) : fun_ptr(std::forward<T>(t)) {} Ret operator()(Args... args) const { return fun_ptr(std::forward<Args>(args)...); } private: fun_type fun_ptr; }; template <typename Class, typename Ret> class simple_overload_element<Ret Class::*> { using mem_obj_type = Ret Class::*; public: simple_overload_element() = delete; template <typename T, DisableIf<is_related<simple_overload_element, T>> = _> explicit simple_overload_element(T&& t) : mem_obj_ptr(std::forward<T>(t)) {} template <typename C, EnableIf<Any<is_related<Class, C>, std::is_base_of<Class, C>>> = _> WithQualificationsOf<C, Ret> operator()(C&& c) const { return std::forward<C>(c).*mem_obj_ptr; } mem_obj_type mem_obj_ptr; }; template <typename T, typename Signature> struct mem_fun_overload_element_impl; template <typename T> struct mem_fun_overload_element { using type = mem_fun_overload_element_impl<T, RemoveFunctionQualifiers<T>>; }; template <typename T> using overload_element = Invoke<Conditional< std::is_member_function_pointer<T>, mem_fun_overload_element<T>, identity<simple_overload_element<T>> >>; template <typename Class, typename Signature, typename Ret, typename... Args> class mem_fun_overload_element_impl<Signature Class::*, Ret (Class::*)(Args...)> { using mem_fun_type = Signature Class::*; using qualifiers = FromFunctionQualifiers<Signature>; public: mem_fun_overload_element_impl() = delete; template <typename T, DisableIf<is_related<mem_fun_overload_element_impl, T>> = _> explicit mem_fun_overload_element_impl(T&& t) : mem_fun_ptr(std::forward<T>(t)) {} template <typename Qualifiers = qualifiers, DisableIf<std::is_reference<Qualifiers>> = _> Ret operator()(WithCvOf<qualifiers, Class>& c, Args&&... args) const { return (c.*mem_fun_ptr)(std::forward<Args>(args)...); } template <typename Qualifiers = qualifiers, DisableIf<std::is_reference<Qualifiers>> = _> Ret operator()(WithCvOf<qualifiers, Class>&& c, Args&&... args) const { return (std::move(c).*mem_fun_ptr)(std::forward<Args>(args)...); } template <typename Qualifiers = qualifiers, EnableIf<std::is_reference<Qualifiers>> = _> Ret operator()(WithQualificationsOf<qualifiers, Class> c, Args&&... args) const { return (std::forward<WithQualificationsOf<qualifiers, Class>>(c).*mem_fun_ptr)(std::forward<Args>(args)...); } Ret operator()(WithCvOf<RemoveReference<qualifiers>, Class>* c, Args&&... args) const { return (c->*mem_fun_ptr)(std::forward<Args>(args)...); } private: mem_fun_type mem_fun_ptr; }; template <typename... Funs> class overload_impl {}; template <typename Fun> class overload_impl<Fun> : overload_element<Decay<Fun>> { using element_type = overload_element<Decay<Fun>>; public: overload_impl() = default; template <typename T, DisableIf<is_related<overload_impl, T>> = _> explicit overload_impl(T&& t) : element_type(std::forward<T>(t)) {} using element_type::operator(); }; template <typename Head, typename... Tail> class overload_impl<Head, Tail...> : overload_element<Decay<Head>>, overload_impl<Tail...> { using head_type = overload_element<Decay<Head>>; using tail_type = overload_impl<Tail...>; public: overload_impl() = default; template <typename H, typename... T, DisableIf<is_related<overload_impl, H>> = _> explicit overload_impl(H&& h, T&&... t) : head_type(std::forward<H>(h)) , tail_type(std::forward<T>(t)...) {} using head_type::operator(); using tail_type::operator(); }; } // namespace overload_detail template <typename... Funs> class overload : overload_detail::overload_impl<Funs...> { using impl_type = overload_detail::overload_impl<Funs...>; public: overload() = default; template <typename... T, DisableIf<is_related<overload, PackHead<T...>>> = _> explicit overload(T&&... t) : impl_type(std::forward<T>(t)...) {} using impl_type::operator(); }; template <typename... Funs, typename Overload = overload<Decay<Funs>...> > Overload make_overload(Funs&&... funs) { return Overload { std::forward<Funs>(funs)... }; } #ifndef WHEELS_MAKE_OVERLOAD_MAX_ARITY # define WHEELS_MAKE_OVERLOAD_MAX_ARITY 17 #endif // WHEELS_MAKE_OVERLOAD_MAX_ARITY #define WHEELS_OVERLOAD_PASTE(A, B, TEXT) TEXT #define WHEELS_OVERLOAD(NAME) BOOST_PP_ENUM(WHEELS_MAKE_OVERLOAD_MAX_ARITY, WHEELS_OVERLOAD_PASTE, NAME) template <typename Head, typename... Tail, EnableIf<Any<is_function_pointer<Decay<Head>> , std::is_member_pointer<Head>>> = _, typename Overload = overload<Head, Tail...>> Overload make_overload(Decay<Head> head, Decay<Tail>... tail, WHEELS_OVERLOAD(Decay<Head> = nullptr)) { return Overload { head, tail... }; } template <typename Result, typename... Funs> struct visitor : overload<Funs...> { using fun_type = overload<Funs...>; public: using result_type = Result; template <typename... T, DisableIf<is_related<visitor, PackHead<T...>>> = _> explicit visitor(T&&... t) : fun_type(std::forward<T>(t)...) {} using fun_type::operator(); }; template <typename Result = void, typename... Funs, typename Visitor = visitor<Result, Decay<Funs>...> > Visitor make_visitor(Funs&&... funs) { return Visitor { std::forward<Funs>(funs)... }; } } // namespace wheels #endif // WHEELS_OVERLOAD_HPP
37.635945
124
0.580507
[ "object" ]
58bc9fec8a2d58bfb1f0c201ee5d8adb579c50cd
6,662
cpp
C++
src/LP_Evaluator.cpp
LukasLeonardKoening/Licence-Plate-Evaluator
0d82c86e42a67f95a75d9e69de36900d62e59fc2
[ "MIT" ]
null
null
null
src/LP_Evaluator.cpp
LukasLeonardKoening/Licence-Plate-Evaluator
0d82c86e42a67f95a75d9e69de36900d62e59fc2
[ "MIT" ]
null
null
null
src/LP_Evaluator.cpp
LukasLeonardKoening/Licence-Plate-Evaluator
0d82c86e42a67f95a75d9e69de36900d62e59fc2
[ "MIT" ]
null
null
null
#include "LP_Evaluator.h" #include <fstream> #include <iostream> #include <sstream> #include <algorithm> /* MessageQueue Definitions */ template<typename T> T MessageQueue<T>::receive() { // Protect work by a unique lock std::unique_lock<std::mutex> unique_lock(_mutex); // Wait until message is available _cond.wait(unique_lock, [this] { return !_queue.empty(); }); // Return message (using move semantics) auto msg = std::move(_queue.back()); _queue.erase(_queue.end()); return msg; } template<typename T> void MessageQueue<T>::send(T &&msg) { // Protect work by a lock guard std::lock_guard<std::mutex> lock(_mutex); // Add message to queue _queue.push_back(std::move(msg)); // Notify condition variable _cond.notify_one(); } /* LicencePlateEvaluator definitions */ // Constructor LicencePlateEvaluator::LicencePlateEvaluator(string database_file) { _results = std::make_shared<MessageQueue<LicencePlateEvaluationResult>>(); threads.emplace_back(std::thread(&LicencePlateEvaluator::update, this, database_file)); } // Destructor LicencePlateEvaluator::~LicencePlateEvaluator() { std::for_each(threads.begin(), threads.end(), [](std::thread &t) { t.join(); }); } // Creates thread for the update void LicencePlateEvaluator::updateDatabase(string database_file) { threads.emplace_back(std::thread(&LicencePlateEvaluator::update, this, database_file)); } // Update the database with new licence plates from file void LicencePlateEvaluator::update(string database_file) { // Protect operation with a lock std::lock_guard<std::mutex> database_lock(mutex_database); // Usage of a mutex for output protection mutex_cout.lock(); std::cout << "[INFO]: Updating database..." << std::endl; mutex_cout.unlock(); // Clean up database database.clear(); // Declare needed variables std::ifstream databaseIN; string line; int counter = 0; // Open filestream and check the operation databaseIN.open(database_file); if (!databaseIN) { mutex_cout.lock(); std::cerr << "[ERROR]: Database could not be opened!" << std::endl; mutex_cout.unlock(); return; } // Read database line by line while(getline(databaseIN,line)) { // Lineformat: "XXX-XX-XXXX 0 0 0 0" // LP number, stolen, wanted, weapon, criminal std::vector<string> components; std::stringstream inputstream(line); // Extract components string temp; while (inputstream >> temp) { components.push_back(temp); } // Save data to local database LP_Entry entry(components[0], false, false, false, false); if (components[1] == "1") { entry.setStolenState(true); } if (components[2] == "1") { entry.setWantedState(true); } if (components[3] == "1") { entry.setWeaponState(true); } if (components[4] == "1") { entry.setKnownCriminalState(true); } this->database.push_back(entry); counter++; } mutex_cout.lock(); std::cout << "[INFO]: " << counter << " vehicles added from database." << std::endl; std::cout << "[INFO]: Database successfully updated!" << std::endl; mutex_cout.unlock(); } // Create thread for each evaluation void LicencePlateEvaluator::evaluateLicencePlate(LicencePlateDetection lp) { threads.emplace_back(std::thread(&LicencePlateEvaluator::evaluate, this, lp)); } // Evaluate a detected licence plate void LicencePlateEvaluator::evaluate(LicencePlateDetection lp) { // Check if accuracy/certainty of detection is high enough if (lp.getAccuracy() >= 0.75) { // Check database for licence plate LicencePlateEvaluationResult result(lp, UNKNOWN); mutex_database.lock(); for (int i=0; i < database.size(); i++) { // if licence plate is in database if (database[i].getTotalNumber() == lp.getTotalNumber()) { // Check if stop is required if (database[i].evalStopRequried()) { result.setState(STOP_NOTRISKY); // Check if stop could be risky if (database[i].evalRiskyStop()) { result.setState(STOP_RISKY); } } else { result.setState(NORMAL); } } } mutex_database.unlock(); // Add result to the _result message queue auto f_queue = std::async(std::launch::async, &MessageQueue<LicencePlateEvaluationResult>::send, _results, std::move(result)); f_queue.wait(); } else { mutex_cout.lock(); std::cout << "[INFO]: Accurcy of " << lp.getTotalNumber() << " too low to evaluate." << std::endl; mutex_cout.unlock(); // Add result to the _result message queue LicencePlateEvaluationResult result(lp, UNKNOWN); auto f_queue = std::async(std::launch::async, &MessageQueue<LicencePlateEvaluationResult>::send, _results, std::move(result)); f_queue.wait(); } } // Create thread to run evaluator not in main thread void LicencePlateEvaluator::runEvaluator() { threads.emplace_back(std::thread(&LicencePlateEvaluator::run, this)); } // Run the Evaluator and wait for results void LicencePlateEvaluator::run() { while(true) { // Check results every 1/10th second std::this_thread::sleep_for(std::chrono::milliseconds(100)); auto result = this->_results->receive(); mutex_cout.lock(); switch (result.getState()) { case STOP_NOTRISKY: std::cout << "[ATTENTION]: Vehicle with licence plate '" << result.getDetection().getTotalNumber() << "' is marked as stolen or wanted! Risk of stop is low!"; break; case STOP_RISKY: std::cout << "[ATTENTION]: Vehicle with licence plate '" << result.getDetection().getTotalNumber() << "' is marked as stolen or wanted! Risk of stop is HIGH!"; break; case NORMAL: std::cout << "[INFO]: Vehicle with licence plate '" << result.getDetection().getTotalNumber() << "' is known but not marked."; break; case UNKNOWN: std::cout << "[INFO]: Vehicle with licence plate '" << result.getDetection().getTotalNumber() << "' is unknown."; break; default: break; } std::cout << std::endl; mutex_cout.unlock(); } }
34.697917
175
0.611828
[ "vector" ]
58c8f37cdd99648c3b7ae16ab2c5a59fa629e897
589
hpp
C++
game.hpp
KonradCzerw/p2plug
0574e922f2c32be033c77cd187acc5ccc1dbed31
[ "MIT" ]
1
2021-07-24T21:26:54.000Z
2021-07-24T21:26:54.000Z
game.hpp
KonradCzerw/p2plug
0574e922f2c32be033c77cd187acc5ccc1dbed31
[ "MIT" ]
null
null
null
game.hpp
KonradCzerw/p2plug
0574e922f2c32be033c77cd187acc5ccc1dbed31
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> enum SourceGameVersion { SourceGame_Unknown = 0, SourceGame_Portal2 = 1 }; class Game { protected: SourceGameVersion version = SourceGame_Unknown; public: virtual ~Game() = default; virtual void LoadOffsets() = 0; virtual const char* Version(); virtual const float Tickrate() = 0; inline bool Is(int game) { return this->version & game; } inline SourceGameVersion GetVersion() { return this->version; } static Game* CreateNew(); static std::string VersionToString(int version); static std::vector<std::string> mapNames; };
21.814815
64
0.733447
[ "vector" ]
58d792ed5988ad67a8a62d1ee6ed5eee0de98d5b
1,465
cpp
C++
CSES/Graph_Algorithms/longest_flight_route.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
14
2019-08-14T00:43:10.000Z
2021-12-16T05:43:31.000Z
CSES/Graph_Algorithms/longest_flight_route.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
null
null
null
CSES/Graph_Algorithms/longest_flight_route.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
6
2020-12-30T03:30:17.000Z
2022-03-11T03:40:02.000Z
#include <bits/stdc++.h> #define endl "\n" using namespace std; int N, M, dp[100000], deg[100000]; vector<int> graph[100000], rgraph[100000]; bool rch[100000]; void dfs(int id){ if(rch[id]) return; rch[id] = true; for(int i : graph[id]){ dfs(i); } } int32_t main(){ cin.tie(0) -> sync_with_stdio(0); cin >> N >> M; for(int i = 0; i < M; i++){ int a, b; cin >> a >> b; graph[a-1].push_back(b-1); deg[b-1]++; rgraph[b-1].push_back(a-1); } dfs(0); for(int i = 0; i < N; i++){ if(!rch[i]){ for(int j : graph[i]){ deg[j]--; } } } fill_n(&dp[0], 100000, -2); queue<int> q; q.push(0); dp[0] = 0; while(!q.empty()){ int id = q.front(); q.pop(); for(int i : graph[id]){ dp[i] = max(dp[i], dp[id]+1); if(!--deg[i]){ q.push(i); } } } stack<int> ans; int v = N-1; if(dp[v] == -2){ cout << "IMPOSSIBLE" << endl; return 0; } while(true){ ans.push(v); for(int i : rgraph[v]){ if(dp[i] == dp[v]-1){ v = i; goto bad_practice; } } break; bad_practice:; } cout << ans.size() << endl; while(!ans.empty()){ cout << ans.top() + 1 << " "; ans.pop(); } cout << endl; }
20.068493
42
0.395904
[ "vector" ]
58d8e0df41ce71a1982108b2ab6e969038b33cc2
4,084
cc
C++
CMC040/cmcfun/outp_finish.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
1
2018-10-17T08:53:17.000Z
2018-10-17T08:53:17.000Z
CMC040/cmcfun/outp_finish.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
null
null
null
CMC040/cmcfun/outp_finish.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
null
null
null
//! \file //! \brief Close Out Any Open Report // %SBTTL "OUTP_FINISH" // %IDENT "V3.6a Calico" //// // Source: ../../CMC030/cmcfun/source/outp_finish.bas // Translated from Basic to C++ using btran // on Monday, January 08, 2018 at 12:38:19 // #include <iostream> #include <cstdlib> #include <cstring> #include <unistd.h> #include "basicfun.h" #include "smg/lib.h" #include "preferences.h" #include "cmcfun.h" #include "scopedef.h" #include "database.h" #include "cmcfun/report.h" #include "utl/utl_reportx.h" extern scope_struct scope; //! //! Abstract:HELP //! .b //! .lm +5 //! This subroutine finishes up any REPORT currently open //! .lm -5 //! //! Parameters: //! //! UTL_REPORTX //! The created file that closes any other reports. //! //! Returned value //! It finishes up any report that may still //! be currently open. //! //! Example: //! //! CALL OUTP_FINISH(UTL_REPORTX) //! //! AUTHOR: //! //! 02/23/87 - Kevin Handy //! void outp_finish( utl_reportx_cdd &utl_reportx) { std::vector<std::string> junk; std::string key_name; std::string lib_name; std::string printfinish; std::string prog_name; long smg_status; long st; long temp; std::string tolocal; std::string toscreen; // // Set up variables we will probibly need // writ_string(utl_reportx.printfinish, printfinish); writ_string(utl_reportx.tolocal, tolocal); writ_string(utl_reportx.toscreen, toscreen); // // Finish off report // // ** Converted from a select statement ** // // Display // if (utl_reportx.printto == OUTP_TODISPLAY) { utl_reportx.autoscroll = 0; if (utl_reportx.stat == 0) { reloop:; outp_line("", utl_reportx, junk, "", -12345); utl_reportx.autoscroll = 0; // ** Converted from a select statement ** // // An exit type of key // if ((scope.scope_exit == SMG$K_TRM_F10) || (scope.scope_exit == SMG$K_TRM_CTRLZ) || (scope.scope_exit == 3) || (scope.scope_exit == SMG$K_TRM_F8) || (scope.scope_exit == SMG$K_TRM_DO)) { // // All other keys cause a reloop // } else { goto reloop; } } // // Erase display screen // smg_status = smg$delete_virtual_display(utl_reportx.window); // // Spool // } else if (utl_reportx.printto == OUTP_TOSPOOL) { utl_reportx.chan << printfinish << std::endl; utl_reportx.chan.close(); outp_spool(utl_reportx); // // File // } else if (utl_reportx.printto == OUTP_TOFILE) { utl_reportx.chan << printfinish << std::endl; utl_reportx.chan.close(); // // Word Processing, S2020, DIF // } else if ((utl_reportx.printto == OUTP_TOWP) || (utl_reportx.printto == OUTP_TO2020) || (utl_reportx.printto == OUTP_TOPL)) { utl_reportx.chan.close(); // // Device // } else if (utl_reportx.printto == OUTP_TODEVICE) { utl_reportx.chan << printfinish << std::endl; outp_formff(utl_reportx); utl_reportx.chan.close(); // // Local printer // } else if (utl_reportx.printto == OUTP_TOLOCAL) { utl_reportx.chan << tolocal << printfinish; outp_formff(utl_reportx); utl_reportx.chan << toscreen; utl_reportx.chan.close(); // // Documentation // } else if (utl_reportx.printto == OUTP_TODOCUMENT) { utl_reportx.chan.close(); prog_name = boost::trim_right_copy(utl_reportx.pronam); // // Create key name // key_name = boost::trim_right_copy(prog_name) + "$" + "REPORT"; // // Create library name // temp = ((prog_name + "_").find("_", 0) + 1); lib_name = std::string("SIC:WINDOWS_") + prog_name.substr(0, temp - 1); // // Plop it into library // st = libr_3insert(lib_name, utl_reportx.defout, key_name); // // Delete the file (hope for only one) // smg_status = lib$delete_file(boost::trim_right_copy(utl_reportx.defout) + ";*"); } // // Erase display (option and message) // if (scope.smg_option.win) { smg_status = smg$erase_display(scope.smg_option); } if (scope.smg_message.win) { smg_status = smg$erase_display(scope.smg_message); } // // Change the width // smg_status = smg$change_pbd_characteristics(scope.smg_pbid, 80); }
20.626263
82
0.651077
[ "vector" ]