text
string
size
int64
token_count
int64
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <unity/lib/extensions/option_info.hpp> #include <boost/lexical_cast.hpp> namespace turi { namespace option_handling { flexible_type option_info::to_dictionary() const { flex_dict n; n.push_back({"description", description}); n.push_back({"default_value", default_value}); switch(parameter_type) { case REAL: { n.push_back({"parameter_type", "REAL"}); n.push_back({"lower_bound", lower_bound}); n.push_back({"upper_bound", upper_bound}); break; } case INTEGER: { n.push_back({"parameter_type", "INTEGER"}); n.push_back({"lower_bound", lower_bound}); n.push_back({"upper_bound", upper_bound}); break; } case BOOL: { n.push_back({"parameter_type", "BOOL"}); break; } case CATEGORICAL: { n.push_back({"parameter_type", "CATEGORICAL"}); flex_list a; for (const flexible_type& v : allowed_values) { a.push_back(v); } n.push_back({"possible_values", a}); break; } case STRING: { n.push_back({"parameter_type", "STRING"}); break; } case FLEXIBLE_TYPE: { n.push_back({"parameter_type", "DYNAMIC"}); break; } } return n; } flexible_type option_info::interpret_value(const flexible_type& value) const { std::string sep_char = (value.get_type() == flex_type_enum::STRING) ? "'" : ""; flexible_type ret_v; switch(parameter_type) { case option_info::REAL: { bool value_type_okay = false; switch(value.get_type()) { case flex_type_enum::INTEGER: ret_v = double(value); value_type_okay = true; break; case flex_type_enum::FLOAT: ret_v = value; value_type_okay = true; break; case flex_type_enum::STRING: { try { ret_v = boost::lexical_cast<double>(value.get<flex_string>()); value_type_okay = true; } catch(const boost::bad_lexical_cast&) { value_type_okay = false; } break; } case flex_type_enum::UNDEFINED: ret_v = default_value; value_type_okay = true; break; default: value_type_okay = false; break; } if(!value_type_okay) { std::ostringstream msg; msg << "Expected numeric value for option '" << name << "'. Cannot cast " << sep_char << value << sep_char << " to a numeric value."; log_and_throw(msg.str()); } if( (!(double(ret_v) >= lower_bound)) || (!(double(ret_v) <= upper_bound))) { std::ostringstream msg; msg << "Option '" << name << "' must be in the range [" << lower_bound << ", " << upper_bound << "]."; log_and_throw(msg.str()); } break; } case option_info::INTEGER: { bool value_type_okay = false; switch(value.get_type()) { case flex_type_enum::INTEGER: ret_v = value; value_type_okay = true; break; case flex_type_enum::FLOAT: ret_v = int64_t(value.get<double>()); if(double(ret_v) != value.get<double>()) value_type_okay = false; else value_type_okay = true; break; case flex_type_enum::STRING: { try { ret_v = boost::lexical_cast<int64_t>(value.get<flex_string>()); value_type_okay = true; } catch(const boost::bad_lexical_cast&) { value_type_okay = false; } break; } case flex_type_enum::UNDEFINED: ret_v = default_value; value_type_okay = true; break; default: value_type_okay = false; break; } if(!value_type_okay) { std::ostringstream msg; msg << "Expected integer value for option '" << name << "'. Cannot cast " << sep_char << value << sep_char << " to an integer value."; log_and_throw(msg.str()); } if( (!(flex_int(ret_v) >= lower_bound)) || (!(flex_int(ret_v) <= upper_bound))) { std::ostringstream msg; msg << "Option '" << name << "' must be in the range [" << lower_bound << ", " << upper_bound << "]."; log_and_throw(msg.str()); } break; } case option_info::BOOL: { bool value_type_okay = false; switch(value.get_type()) { case flex_type_enum::INTEGER: if(value.get<flex_int>() == 0) { ret_v = false; value_type_okay = true; } else if (value.get<flex_int>() == 1) { ret_v = true; value_type_okay = true; } else { value_type_okay = false; } break; case flex_type_enum::FLOAT: if(value.get<flex_float>() == 0.0) { ret_v = false; value_type_okay = true; } else if (value.get<flex_float>() == 1.0) { ret_v = true; value_type_okay = true; } else { value_type_okay = false; } break; case flex_type_enum::STRING: { static const std::map<std::string, bool> okay_values = { {"1", true}, {"True", true}, {"T", true}, {"true", true}, {"Y", true}, {"y", true}, {"yes", true}, {"0", false}, {"False", false}, {"F", false}, {"false", false}, {"N", false}, {"n", false}, {"no", false} }; auto it = okay_values.find(value.get<flex_string>()); if(it != okay_values.end()) { ret_v = it->second; value_type_okay = true; } else { value_type_okay = false; } } case flex_type_enum::UNDEFINED: ret_v = default_value; value_type_okay = true; break; default: value_type_okay = false; break; } if(!value_type_okay) { std::ostringstream msg; msg << "Expected boolean value for option '" << name << sep_char << "'. Cannot interpret " << sep_char << value << sep_char << " as True or False."; log_and_throw(msg.str()); } break; } case option_info::CATEGORICAL: { DASSERT_EQ(std::set<flexible_type>(allowed_values.begin(), allowed_values.end()).count(default_value), 1); bool is_okay = false; for(const auto& okay_v : allowed_values) { if(value == okay_v) { is_okay = true; break; } } if(!is_okay){ std::ostringstream msg; msg << "Option '" << name << "' must be one of ("; for(size_t i = 0; i < allowed_values.size()-1; i++){ msg << sep_char << allowed_values[i] << sep_char << ", "; } msg << "or " << sep_char << allowed_values[allowed_values.size()-1] << sep_char << ")."; log_and_throw(msg.str()); } ret_v = value; break; } case option_info::STRING: ret_v = value; // Maybe more on this later? break; case option_info::FLEXIBLE_TYPE: ret_v = value; break; default: log_and_throw("Internal error. Option type un-implemented"); break; } return ret_v; } /** * Check to make sure that the options satisfy the requirements. */ void option_info::check_value(const flexible_type& value) const { interpret_value(value); } /** * Save */ void option_info::save(turi::oarchive& oarc) const { oarc << name << description << default_value << parameter_type << lower_bound << upper_bound << allowed_values; } /** * Load */ void option_info::load(turi::iarchive& iarc) { iarc >> name >> description >> default_value >> parameter_type >> lower_bound >> upper_bound >> allowed_values; } }}
8,874
2,736
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= // // #ifndef GPSTK_RACROTATION_HPP #define GPSTK_RACROTATION_HPP // gpstk #include "Triple.hpp" #include "Matrix.hpp" #include "Vector.hpp" #include "Xvt.hpp" namespace gpstk { /// @ingroup MathGroup //@{ class RACRotation : public gpstk::Matrix<double> { public: // Constructors RACRotation( const gpstk::Triple& SVPositionVector, const gpstk::Triple& SVVelocityVector); RACRotation(const gpstk::Xvt& xvt); // Methods gpstk::Vector<double> convertToRAC( const gpstk::Vector<double>& inV ); gpstk::Triple convertToRAC( const gpstk::Triple& inVec ); gpstk::Xvt convertToRAC( const gpstk::Xvt& in ); // Utilities protected: void compute( const gpstk::Triple& SVPositionVector, const gpstk::Triple& SVVelocityVector); }; //@} } #endif
2,612
777
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> combis; vector<int> combi; dfs(0, n, k, &combi, &combis); return combis; } private: void dfs(int pre, int n, int k, vector<int> * combi, vector<vector<int>> * combis) { if (static_cast<int>(combi->size()) == k) { combis->push_back(*combi); } else { for(int nxt = pre + 1; nxt <= n; ++nxt) { combi->push_back(nxt); dfs(nxt, n, k, combi, combis); combi->pop_back(); } } } };
623
221
#include<iostream> #include<unistd.h> #include<cstdlib> #include<fstream> using namespace std; // int k=1; int main() { cout<<endl<<endl<<endl; int n=15; double temp[n][n]; ifstream f1; f1.open("data.txt"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { f1>>temp[i][j]; } } // cout<<"temp matrix"; f1.close(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(temp[i][j] >= 0.83 && i!=j && temp[i][j]!=2 && temp[i][j]!=1) { cout<<"New Road suggested from '"<<i<<"' to '"<<j<<"' (Average Congestion : "<<temp[i][j]<<" )"<<endl; } } } // system("cat data.txt"); return 0; }
765
323
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/render_widget_host_delegate.h" #include "build/build_config.h" #include "components/rappor/public/sample.h" #include "content/browser/renderer_host/render_view_host_delegate_view.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "ui/gfx/geometry/rect.h" namespace content { KeyboardEventProcessingResult RenderWidgetHostDelegate::PreHandleKeyboardEvent( const NativeWebKeyboardEvent& event) { return KeyboardEventProcessingResult::NOT_HANDLED; } bool RenderWidgetHostDelegate::HandleWheelEvent( const blink::WebMouseWheelEvent& event) { return false; } bool RenderWidgetHostDelegate::PreHandleGestureEvent( const blink::WebGestureEvent& event) { return false; } BrowserAccessibilityManager* RenderWidgetHostDelegate::GetRootBrowserAccessibilityManager() { return nullptr; } BrowserAccessibilityManager* RenderWidgetHostDelegate::GetOrCreateRootBrowserAccessibilityManager() { return nullptr; } // If a delegate does not override this, the RenderWidgetHostView will // assume it is the sole platform event consumer. RenderWidgetHostInputEventRouter* RenderWidgetHostDelegate::GetInputEventRouter() { return nullptr; } // If a delegate does not override this, the RenderWidgetHostView will // assume its own RenderWidgetHost should consume keyboard events. RenderWidgetHostImpl* RenderWidgetHostDelegate::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { return receiving_widget; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetRenderWidgetHostWithPageFocus() { return nullptr; } bool RenderWidgetHostDelegate::IsFullscreenForCurrentTab() const { return false; } blink::WebDisplayMode RenderWidgetHostDelegate::GetDisplayMode( RenderWidgetHostImpl* render_widget_host) const { return blink::kWebDisplayModeBrowser; } bool RenderWidgetHostDelegate::HasMouseLock( RenderWidgetHostImpl* render_widget_host) { return false; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetMouseLockWidget() { return nullptr; } bool RenderWidgetHostDelegate::RequestKeyboardLock(RenderWidgetHostImpl* host, bool esc_key_locked) { return false; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetKeyboardLockWidget() { return nullptr; } TextInputManager* RenderWidgetHostDelegate::GetTextInputManager() { return nullptr; } bool RenderWidgetHostDelegate::IsHidden() { return false; } RenderViewHostDelegateView* RenderWidgetHostDelegate::GetDelegateView() { return nullptr; } RenderWidgetHostImpl* RenderWidgetHostDelegate::GetFullscreenRenderWidgetHost() const { return nullptr; } bool RenderWidgetHostDelegate::OnUpdateDragCursor() { return false; } bool RenderWidgetHostDelegate::IsWidgetForMainFrame(RenderWidgetHostImpl*) { return false; } bool RenderWidgetHostDelegate::AddDomainInfoToRapporSample( rappor::Sample* sample) { sample->SetStringField("Domain", "Unknown"); return false; } void RenderWidgetHostDelegate::UpdateUrlForUkmSource( ukm::UkmRecorder* service, ukm::SourceId ukm_source_id) {} gfx::Size RenderWidgetHostDelegate::GetAutoResizeSize() { return gfx::Size(); } WebContents* RenderWidgetHostDelegate::GetAsWebContents() { return nullptr; } bool RenderWidgetHostDelegate::IsShowingContextMenuOnPage() const { return false; } } // namespace content
3,595
1,027
// Copyright 2013 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 "ash/wm/lock_state_controller.h" #include <algorithm> #include <string> #include <utility> #include "ash/accessibility/accessibility_controller.h" #include "ash/cancel_mode.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/public/interfaces/shutdown.mojom.h" #include "ash/session/session_controller.h" #include "ash/shell.h" #include "ash/shell_delegate.h" #include "ash/shell_port.h" #include "ash/shutdown_controller.h" #include "ash/shutdown_reason.h" #include "ash/wallpaper/wallpaper_controller.h" #include "ash/wm/session_state_animator.h" #include "ash/wm/session_state_animator_impl.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/strings/string_util.h" #include "base/sys_info.h" #include "base/timer/timer.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "ui/aura/window_tree_host.h" #include "ui/views/controls/menu/menu_controller.h" #include "ui/wm/core/compound_event_filter.h" #define UMA_HISTOGRAM_LOCK_TIMES(name, sample) \ UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, \ base::TimeDelta::FromMilliseconds(1), \ base::TimeDelta::FromSeconds(50), 100) namespace ash { namespace { // ASan/TSan/MSan instrument each memory access. This may slow the execution // down significantly. #if defined(MEMORY_SANITIZER) // For MSan the slowdown depends heavily on the value of msan_track_origins GYP // flag. The multiplier below corresponds to msan_track_origins=1. constexpr int kTimeoutMultiplier = 6; #elif defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) constexpr int kTimeoutMultiplier = 2; #else constexpr int kTimeoutMultiplier = 1; #endif constexpr int kMaxShutdownSoundDurationMs = 1500; // Amount of time to wait for our lock requests to be honored before giving up. constexpr int kLockFailTimeoutMs = 8000 * kTimeoutMultiplier; // When the button has been held continuously from the unlocked state, amount of // time that we wait after the screen locker window is shown before starting the // pre-shutdown animation. constexpr int kLockToShutdownTimeoutMs = 150; // Additional time (beyond kFastCloseAnimMs) to wait after starting the // fast-close shutdown animation before actually requesting shutdown, to give // the animation time to finish. constexpr int kShutdownRequestDelayMs = 50; } // namespace // static const int LockStateController::kPreLockContainersMask = SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS | SessionStateAnimator::SHELF; LockStateController::LockStateController( ShutdownController* shutdown_controller) : animator_(new SessionStateAnimatorImpl()), shutdown_controller_(shutdown_controller), scoped_session_observer_(this), weak_ptr_factory_(this) { DCHECK(shutdown_controller_); Shell::GetPrimaryRootWindow()->GetHost()->AddObserver(this); } LockStateController::~LockStateController() { Shell::GetPrimaryRootWindow()->GetHost()->RemoveObserver(this); } void LockStateController::StartLockAnimation() { if (animating_lock_) return; can_cancel_lock_animation_ = true; StartCancellablePreLockAnimation(); } void LockStateController::StartLockThenShutdownAnimation( ShutdownReason shutdown_reason) { shutdown_after_lock_ = true; shutdown_reason_ = shutdown_reason; StartLockAnimation(); } void LockStateController::StartShutdownAnimation(ShutdownReason reason) { shutdown_reason_ = reason; StartCancellableShutdownAnimation(); } void LockStateController::StartLockAnimationAndLockImmediately() { if (animating_lock_) return; StartImmediatePreLockAnimation(true /* request_lock_on_completion */); } void LockStateController::LockWithoutAnimation() { if (animating_lock_) return; animating_lock_ = true; post_lock_immediate_animation_ = true; animator_->StartAnimation(kPreLockContainersMask, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_LOCK_ANIMATION_STARTED); Shell::Get()->session_controller()->LockScreen(); } bool LockStateController::LockRequested() { return lock_fail_timer_.IsRunning(); } bool LockStateController::ShutdownRequested() { return shutting_down_; } bool LockStateController::CanCancelLockAnimation() { return can_cancel_lock_animation_; } void LockStateController::CancelLockAnimation() { if (!CanCancelLockAnimation()) return; shutdown_after_lock_ = false; animating_lock_ = false; CancelPreLockAnimation(); } bool LockStateController::CanCancelShutdownAnimation() { return pre_shutdown_timer_.IsRunning() || shutdown_after_lock_ || lock_to_shutdown_timer_.IsRunning(); } void LockStateController::CancelShutdownAnimation() { if (!CanCancelShutdownAnimation()) return; if (lock_to_shutdown_timer_.IsRunning()) { lock_to_shutdown_timer_.Stop(); return; } if (shutdown_after_lock_) { shutdown_after_lock_ = false; return; } animator_->StartAnimation( SessionStateAnimator::ROOT_CONTAINER, SessionStateAnimator::ANIMATION_UNDO_GRAYSCALE_BRIGHTNESS, SessionStateAnimator::ANIMATION_SPEED_REVERT_SHUTDOWN); pre_shutdown_timer_.Stop(); } void LockStateController::OnStartingLock() { if (shutting_down_ || system_is_locked_) return; if (animating_lock_) return; StartImmediatePreLockAnimation(false /* request_lock_on_completion */); } void LockStateController::RequestShutdown(ShutdownReason reason) { if (shutting_down_) return; shutting_down_ = true; shutdown_reason_ = reason; ShellPort* port = ShellPort::Get(); port->HideCursor(); port->LockCursor(); animator_->StartAnimation( SessionStateAnimator::ROOT_CONTAINER, SessionStateAnimator::ANIMATION_GRAYSCALE_BRIGHTNESS, SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN); StartRealShutdownTimer(true); } void LockStateController::OnLockScreenHide(base::OnceClosure callback) { StartUnlockAnimationBeforeUIDestroyed(std::move(callback)); } void LockStateController::SetLockScreenDisplayedCallback( base::OnceClosure callback) { DCHECK(lock_screen_displayed_callback_.is_null()); lock_screen_displayed_callback_ = std::move(callback); } void LockStateController::OnHostCloseRequested(aura::WindowTreeHost* host) { Shell::Get()->session_controller()->RequestSignOut(); } void LockStateController::OnChromeTerminating() { // If we hear that Chrome is exiting but didn't request it ourselves, all we // can really hope for is that we'll have time to clear the screen. // This is also the case when the user signs off. if (!shutting_down_) { shutting_down_ = true; Shell* shell = Shell::Get(); if (shell->cursor_manager()) { shell->cursor_manager()->HideCursor(); shell->cursor_manager()->LockCursor(); } animator_->StartAnimation(SessionStateAnimator::kAllNonRootContainersMask, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); } } void LockStateController::OnLockStateChanged(bool locked) { DCHECK((lock_fail_timer_.IsRunning() && lock_duration_timer_ != nullptr) || (!lock_fail_timer_.IsRunning() && lock_duration_timer_ == nullptr)); VLOG(1) << "OnLockStateChanged called with locked: " << locked << ", shutting_down_: " << shutting_down_ << ", system_is_locked_: " << system_is_locked_ << ", lock_fail_timer_.IsRunning(): " << lock_fail_timer_.IsRunning(); if (shutting_down_ || (system_is_locked_ == locked)) return; system_is_locked_ = locked; if (locked) { StartPostLockAnimation(); lock_fail_timer_.Stop(); if (lock_duration_timer_) { UMA_HISTOGRAM_LOCK_TIMES("Ash.WindowManager.Lock.Success", lock_duration_timer_->Elapsed()); lock_duration_timer_.reset(); } } else { StartUnlockAnimationAfterUIDestroyed(); } } void LockStateController::OnLockFailTimeout() { UMA_HISTOGRAM_LOCK_TIMES("Ash.WindowManager.Lock.Timeout", lock_duration_timer_->Elapsed()); lock_duration_timer_.reset(); DCHECK(!system_is_locked_); LOG(FATAL) << "Screen lock took too long; crashing intentionally"; } void LockStateController::StartLockToShutdownTimer() { DCHECK(shutdown_reason_); shutdown_after_lock_ = false; lock_to_shutdown_timer_.Stop(); lock_to_shutdown_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kLockToShutdownTimeoutMs), this, &LockStateController::OnLockToShutdownTimeout); } void LockStateController::OnLockToShutdownTimeout() { DCHECK(system_is_locked_); StartCancellableShutdownAnimation(); } void LockStateController::StartPreShutdownAnimationTimer() { pre_shutdown_timer_.Stop(); pre_shutdown_timer_.Start( FROM_HERE, animator_->GetDuration(SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN), this, &LockStateController::OnPreShutdownAnimationTimeout); } void LockStateController::OnPreShutdownAnimationTimeout() { VLOG(1) << "OnPreShutdownAnimationTimeout"; shutting_down_ = true; Shell* shell = Shell::Get(); if (shell->cursor_manager()) shell->cursor_manager()->HideCursor(); StartRealShutdownTimer(false); } void LockStateController::StartRealShutdownTimer(bool with_animation_time) { base::TimeDelta duration = base::TimeDelta::FromMilliseconds(kShutdownRequestDelayMs); if (with_animation_time) { duration += animator_->GetDuration(SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN); } // Play and get shutdown sound duration from chrome in |sound_duration|. And // start real shutdown after a delay of |duration|. Shell::Get()->accessibility_controller()->PlayShutdownSound(base::BindOnce( [](base::WeakPtr<LockStateController> self, base::TimeDelta duration, base::TimeDelta sound_duration) { if (!self) return; sound_duration = std::min( sound_duration, base::TimeDelta::FromMilliseconds(kMaxShutdownSoundDurationMs)); duration = std::max(duration, sound_duration); self->real_shutdown_timer_.Start( FROM_HERE, duration, self.get(), &LockStateController::OnRealPowerTimeout); }, weak_ptr_factory_.GetWeakPtr(), duration)); } void LockStateController::OnRealPowerTimeout() { VLOG(1) << "OnRealPowerTimeout"; DCHECK(shutting_down_); DCHECK(shutdown_reason_); // Shut down or reboot based on device policy. shutdown_controller_->ShutDownOrReboot(*shutdown_reason_); } void LockStateController::StartCancellableShutdownAnimation() { Shell* shell = Shell::Get(); // Hide cursor, but let it reappear if the mouse moves. if (shell->cursor_manager()) shell->cursor_manager()->HideCursor(); animator_->StartAnimation( SessionStateAnimator::ROOT_CONTAINER, SessionStateAnimator::ANIMATION_GRAYSCALE_BRIGHTNESS, SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN); StartPreShutdownAnimationTimer(); } void LockStateController::StartImmediatePreLockAnimation( bool request_lock_on_completion) { VLOG(1) << "StartImmediatePreLockAnimation " << request_lock_on_completion; animating_lock_ = true; StoreUnlockedProperties(); PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS, request_lock_on_completion); DispatchCancelMode(); ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_LOCK_ANIMATION_STARTED); } void LockStateController::StartCancellablePreLockAnimation() { animating_lock_ = true; StoreUnlockedProperties(); VLOG(1) << "StartCancellablePreLockAnimation"; PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_UNDOABLE, true); DispatchCancelMode(); ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_PRELOCK_ANIMATION_STARTED); } void LockStateController::PreLockAnimation( SessionStateAnimator::AnimationSpeed speed, bool request_lock_on_completion) { Shell::Get()->wallpaper_controller()->PrepareWallpaperForLockScreenChange( true); base::Closure next_animation_starter = base::Bind(&LockStateController::PreLockAnimationFinished, weak_ptr_factory_.GetWeakPtr(), request_lock_on_completion); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_LIFT, speed); animation_sequence->StartAnimation(SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_OUT, speed); // Hide the screen locker containers so we can raise them later. animator_->StartAnimation(SessionStateAnimator::LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); AnimateWallpaperAppearanceIfNecessary(speed, animation_sequence); animation_sequence->EndSequence(); } void LockStateController::CancelPreLockAnimation() { VLOG(1) << "CancelPreLockAnimation"; Shell::Get()->wallpaper_controller()->PrepareWallpaperForLockScreenChange( false); base::Closure next_animation_starter = base::Bind(&LockStateController::LockAnimationCancelled, weak_ptr_factory_.GetWeakPtr()); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_UNDO_LIFT, SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS); animation_sequence->StartAnimation( SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN, SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS); AnimateWallpaperHidingIfNecessary( SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS, animation_sequence); animation_sequence->EndSequence(); } void LockStateController::StartPostLockAnimation() { VLOG(1) << "StartPostLockAnimation"; base::Closure next_animation_starter = base::Bind(&LockStateController::PostLockAnimationFinished, weak_ptr_factory_.GetWeakPtr()); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_RAISE_TO_SCREEN, post_lock_immediate_animation_ ? SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE : SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); // Show the lock screen shelf. This is a no-op if views-based shelf is // disabled, since shelf is in NonLockScreenContainersContainer. animation_sequence->StartAnimation( SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN, post_lock_immediate_animation_ ? SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE : SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); animation_sequence->EndSequence(); } void LockStateController::StartUnlockAnimationBeforeUIDestroyed( base::OnceClosure callback) { VLOG(1) << "StartUnlockAnimationBeforeUIDestroyed"; animator_->StartAnimationWithCallback( SessionStateAnimator::LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_LIFT, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS, std::move(callback)); // Hide the lock screen shelf. This is a no-op if views-based shelf is // disabled, since shelf is in NonLockScreenContainersContainer. animator_->StartAnimation(SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_OUT, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); } void LockStateController::StartUnlockAnimationAfterUIDestroyed() { VLOG(1) << "StartUnlockAnimationAfterUIDestroyed"; base::Closure next_animation_starter = base::Bind(&LockStateController::UnlockAnimationAfterUIDestroyedFinished, weak_ptr_factory_.GetWeakPtr()); SessionStateAnimator::AnimationSequence* animation_sequence = animator_->BeginAnimationSequence(next_animation_starter); animation_sequence->StartAnimation( SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS, SessionStateAnimator::ANIMATION_DROP, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); animation_sequence->StartAnimation( SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN, SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS); AnimateWallpaperHidingIfNecessary( SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS, animation_sequence); animation_sequence->EndSequence(); } void LockStateController::LockAnimationCancelled() { can_cancel_lock_animation_ = false; RestoreUnlockedProperties(); } void LockStateController::PreLockAnimationFinished(bool request_lock) { VLOG(1) << "PreLockAnimationFinished"; can_cancel_lock_animation_ = false; // Don't do anything (including starting the lock-fail timer) if the screen // was already locked while the animation was going. if (system_is_locked_) { DCHECK(!request_lock) << "Got request to lock already-locked system " << "at completion of pre-lock animation"; return; } if (request_lock) { if (shutdown_after_lock_) { base::RecordAction( base::UserMetricsAction("Accel_LockScreen_PowerButton")); } else { base::RecordAction( base::UserMetricsAction("Accel_LockScreen_LockButton")); } chromeos::DBusThreadManager::Get() ->GetSessionManagerClient() ->RequestLockScreen(); } base::TimeDelta timeout = base::TimeDelta::FromMilliseconds(kLockFailTimeoutMs); // TODO(derat): Remove this scaling after October 2017 when daisy (Samsung // Chromebook XE303) is unsupported. if (base::SysInfo::GetStrippedReleaseBoard() == "daisy") timeout *= 2; lock_fail_timer_.Start(FROM_HERE, timeout, this, &LockStateController::OnLockFailTimeout); lock_duration_timer_.reset(new base::ElapsedTimer()); } void LockStateController::PostLockAnimationFinished() { animating_lock_ = false; post_lock_immediate_animation_ = false; VLOG(1) << "PostLockAnimationFinished"; ShellPort::Get()->OnLockStateEvent( LockStateObserver::EVENT_LOCK_ANIMATION_FINISHED); if (!lock_screen_displayed_callback_.is_null()) std::move(lock_screen_displayed_callback_).Run(); CHECK(!views::MenuController::GetActiveInstance()); if (shutdown_after_lock_) { shutdown_after_lock_ = false; StartLockToShutdownTimer(); } } void LockStateController::UnlockAnimationAfterUIDestroyedFinished() { Shell::Get()->wallpaper_controller()->PrepareWallpaperForLockScreenChange( false); RestoreUnlockedProperties(); } void LockStateController::StoreUnlockedProperties() { if (!unlocked_properties_) { unlocked_properties_.reset(new UnlockedStateProperties()); unlocked_properties_->wallpaper_is_hidden = animator_->IsWallpaperHidden(); } if (unlocked_properties_->wallpaper_is_hidden) { // Hide wallpaper so that it can be animated later. animator_->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_HIDE_IMMEDIATELY, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); animator_->ShowWallpaper(); } } void LockStateController::RestoreUnlockedProperties() { if (!unlocked_properties_) return; if (unlocked_properties_->wallpaper_is_hidden) { animator_->HideWallpaper(); // Restore wallpaper visibility. animator_->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_FADE_IN, SessionStateAnimator::ANIMATION_SPEED_IMMEDIATE); } unlocked_properties_.reset(); } void LockStateController::AnimateWallpaperAppearanceIfNecessary( SessionStateAnimator::AnimationSpeed speed, SessionStateAnimator::AnimationSequence* animation_sequence) { if (unlocked_properties_.get() && unlocked_properties_->wallpaper_is_hidden) { animation_sequence->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_FADE_IN, speed); } } void LockStateController::AnimateWallpaperHidingIfNecessary( SessionStateAnimator::AnimationSpeed speed, SessionStateAnimator::AnimationSequence* animation_sequence) { if (unlocked_properties_.get() && unlocked_properties_->wallpaper_is_hidden) { animation_sequence->StartAnimation(SessionStateAnimator::WALLPAPER, SessionStateAnimator::ANIMATION_FADE_OUT, speed); } } } // namespace ash
21,696
6,762
/* Copyright (C) 2020 Christoph Theis */ #include "stdafx.h" #include <wx/progdlg.h> #include <wx/xrc/xh_aui.h> #include "tt32App.h" #include "MainFrm.h" #include "ChildFrm.h" #include "FormViewEx.h" #include "ImportOnlineEntries.h" #include "ItemCtrl.h" #include "Profile.h" #include "InfoSystem.h" #include "CpListStore.h" #include "PlListStore.h" #include "IdStore.h" #include "Request.h" #include "Rec.h" #include "Res.h" #if __has_include("../Crypt/crypt.h") # include "../Crypt/crypt.h" #else # include "../Crypt/crypt_template.h" #endif static int defaultType = TT_REGULAR; static int defaultTable = TT_ITTF; // Muss hier stehen, weil es sonst nicht compiliert static const wxString versionNumber = "21.09"; static const wxString version = "Version " + versionNumber; static wxString licensee = " Christoph Theis"; static wxString copyright = "(C) Christoph Theis 2021"; static wxString expire = ""; wxProgressDialog * CTT32App::m_progressDialog = NULL; IMPLEMENT_APP(CTT32App) Profile ttProfile; InfoSystem infoSystem; CTT32App::~CTT32App() { } bool CTT32App::OnInit() { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // Create Mutex fuer Inno Setup CreateMutex(NULL, FALSE, wxT("TTM")); wxTheApp->SetAppName("TTM"); static const wxChar ps = wxFileName::GetPathSeparator(); if (!wxApp::OnInit()) return false; // INI-File suchen wxString iniDir = wxGetCwd(); // Default: aktuelles Verzeichnis wxString iniFile = iniDir + ps + TT_PROFILE; // Wenn nicht: Common App Data if (!wxFile::Exists(iniFile)) iniFile = wxStandardPaths::Get().GetConfigDir() + ps + TT_PROFILE; // Wenn nicht: User App Data if (!wxFile::Exists(iniFile)) iniFile = wxStandardPaths::Get().GetUserLocalDataDir() + ps + TT_PROFILE; // Wenn nicht: User Local App Data if (!wxFile::Exists(iniFile)) iniFile = wxStandardPaths::Get().GetUserLocalDataDir() + ps + TT_PROFILE; if (!wxFile::Exists(iniFile)) { infoSystem.Fatal(wxT("Cannot locate \"tt32.ini\" file")); } wxSetWorkingDirectory(iniFile.SubString(0, iniFile.Len() - wxStrlen(TT_PROFILE) - 2)); // Resourcen bestimmen wxString xrcPath = GetResourcesPath(); if (!wxFile::Exists(xrcPath + "/" TT_XRCFILE)) infoSystem.Fatal(wxT("Cannot locate resource file \"%S\", exiting"), TT_XRCFILE); wxLocale::AddCatalogLookupPathPrefix(xrcPath); ttProfile.Open(iniFile.data()); int langId = wxLocale::GetSystemLanguage(); wxString lang = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE, wxT("en_US")); if (wxLocale::FindLanguageInfo(lang) != NULL) langId = wxLocale::FindLanguageInfo(lang)->Language; m_locale.Init((wxLanguage) langId, wxLOCALE_DONT_LOAD_DEFAULT); m_locale.AddCatalog("ttm"); m_locale.AddCatalog("wxstd"); #if 0 // Lizenzueberpruefung wxString licenseFileName = wxGetCwd() + ps + "license.ini"; licensee = ""; expire = ""; if (!CheckLicenseCode(licenseFileName)) { // Warnung nur, wenn es kein "last open" gibt: // Ansonsten haben Clients, die keine Lizenz brauchen, immer eine Warnung zu Beginn. if (ttProfile.GetString(PRF_OPEN, PRF_LAST).IsEmpty()) infoSystem.Information(_("The license is not valid! You are allowed to use existing tournaments but you cannot create new ones.")); } else if (HasLicenseExpired(licenseFileName)) { infoSystem.Information( _("Your license has expired! You are allowed to use existing tournaments but you cannot create new ones.")); } else { ReadLicense(licenseFileName); } #endif // Setup von [Raster] if (!ttProfile.GetFirstKey(PRF_RASTER)) { ttProfile.AddString(PRF_RASTER, PRF_RASTER_TINY, wxT("Arial, 6, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_SMALL, wxT("Arial, 8, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_MEDIUM, wxT("Arial, 9, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_NORMAL, wxT("Arial, 10, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_PAGE, wxT("Arial, 10, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_GROUP, wxT("Arial, 12, 0, 0, 0, 400, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_COMP, wxT("Arial, 14, 0, 0, 0, 800, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_NORMALB, wxT("Arial, 10, 0, 0, 0, 700, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_MEDIUMB, wxT("Arial, 9, 0, 0, 0, 700, 0, 0, 0")); ttProfile.AddString(PRF_RASTER, PRF_RASTER_SMALLB, wxT("Arial, 8, 0, 0, 0, 700, 0, 0, 0")); } if (!ttProfile.GetFirstKey(PRF_REPORTS)) { ttProfile.AddString(PRF_REPORTS, wxT("Registration"), _("Registration")); // ttProfile.AddString(PRF_REPORTS, wxT("TeamEntries"), _("List of Team Players")); ttProfile.AddString(PRF_REPORTS, wxT("PlayerlistPerName"), _("List of Players Sorted by Name")); ttProfile.AddString(PRF_REPORTS, wxT("PlayerlistPerNumber"), _("List of Players Sorted by Number")); ttProfile.AddString(PRF_REPORTS, wxT("Participants"), _("List of Players with their Events")); ttProfile.AddString(PRF_REPORTS, wxT("Entries"), _("Participants per Event")); ttProfile.AddString(PRF_REPORTS, wxT("ChampionshipEntries"), _("Participants in Championship")); ttProfile.AddString(PRF_REPORTS, wxT("ConsolationEntries"), _("Participants in Consolation")); ttProfile.AddString(PRF_REPORTS, wxT("PartnerMissing"), _("Players with Partner Missing")); } if ( wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("Ranking"))) == 0 ) { ttProfile.DeleteString(PRF_REPORTS, wxT("RankingSingle")); ttProfile.DeleteString(PRF_REPORTS, wxT("RankingDouble")); ttProfile.DeleteString(PRF_REPORTS, wxT("RankingTeam")); ttProfile.AddString(PRF_REPORTS, wxT("Ranking"), _("Ranking by Association")); } if ( wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("WorldRanking"))) == 0 ) ttProfile.AddString(PRF_REPORTS, wxT("WorldRanking"), _("International Ranking")); if ( wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("MatchList"))) == 0 ) ttProfile.AddString(PRF_REPORTS, wxT("MatchList"), _("List of Matches")); if (wxStrlen(ttProfile.GetString(PRF_REPORTS, wxT("FinalStandings"))) == 0) ttProfile.AddString(PRF_REPORTS, wxT("FinalStandings"), _("Final Standings")); // Init image handler ::wxInitAllImageHandlers(); // Init der Resourcen wxXmlResource::Get()->InitAllHandlers(); wxXmlResource::Get()->AddHandler(new CItemCtrlXmlResourceHandler()); wxXmlResource::Get()->AddHandler(new wxAuiXmlHandler()); wxXmlResource::Get()->Load(xrcPath + "/" TT_XRCFILE); m_pMainWnd = (CMainFrame *) wxXmlResource::Get()->LoadObject(NULL, "MainFrame", "wxMDIParentFrame"); m_pMainWnd->SetIcon(wxIcon("main")); SetMenuBar("NOMenuBar"); m_pMainWnd->Maximize(true); m_pMainWnd->GetEventHandler()->ProcessEvent(wxInitDialogEvent()); m_pMainWnd->Show(true); OpenLastTournament(); Connect(IDC_PROGRESSBAR_STEP, wxThreadEventHandler(CTT32App::OnProgressBarStep), NULL, this); Connect(IDC_PROGRESSBAR_EXIT, wxThreadEventHandler(CTT32App::OnProgressBarExit), NULL, this); return true; } int CTT32App::OnExit() { return 0; } // ----------------------------------------------------------------------- class CUpdateViewEvent : public wxCommandEvent { public: CUpdateViewEvent(const CRequest &req) : wxCommandEvent(IDC_UPDATEVIEW) { SetClientData(new CRequest(req)); } ~CUpdateViewEvent() {delete (CRequest *) GetClientData();} }; void CTT32App::NotifyChange(CRequest &req) { if (wxTheApp == nullptr) return; wxTheApp->QueueEvent(new CUpdateViewEvent(req)); } void CTT32App::CommitChanges() { } void CTT32App::AbortChanges() { } class CTT32Thread : public wxThread { public: CTT32Thread(unsigned (*func)(void *arg), void *arg) : wxThread(wxTHREAD_JOINABLE), m_func(func), m_arg(arg) { Create(); } virtual ExitCode Entry() { int rc = (*m_func)(m_arg); CTT32App::ProgressBarExit(rc); return (ExitCode) rc; } void *m_arg; unsigned (*m_func)(void *arg); }; class CProgressDialog : public wxProgressDialog { public: CProgressDialog(const wxString &title, long count, wxWindow *parent, wxThread *thread, bool indefinite) : wxProgressDialog(title, title, count > 0 ? count : 100, parent), m_thread(thread), m_indefinite(indefinite), m_step(0) { if (thread) thread->Run(); if (m_indefinite) { timer.SetOwner(this); timer.Start(50); Connect(wxEVT_TIMER, wxTimerEventHandler(CProgressDialog::OnTimer), NULL, this); Connect(wxEVT_SHOW, wxShowEventHandler(CProgressDialog::OnShow), NULL, this); } } CProgressDialog::~CProgressDialog() { } public: bool Update(int value, const wxString &msg = wxEmptyString, bool *skip = 0) { if (!m_indefinite) return wxProgressDialog::Update(value, msg, skip); else if (!msg.IsEmpty() && msg != GetMessage()) return wxProgressDialog::Update(0, msg, skip); else return Pulse(); } bool IsIndefinite() const {return m_indefinite;} int IncrementCounter() { return ++m_step;} private: void OnTimer(wxTimerEvent &evt) { if (!m_thread || !m_thread->IsAlive()) timer.Stop(); else Pulse(); } void OnShow(wxShowEvent &evt) { if (!evt.IsShown()) { if (timer.IsRunning()) timer.Stop(); m_thread->Wait(); delete m_thread; m_thread = NULL; } } wxTimer timer; wxThread *m_thread; bool m_indefinite; int m_step; }; bool CTT32App::ProgressBarThread(unsigned (*func)(void * arg), void *arg, const wxString &buf, long count, bool indefinite) { if (m_progressDialog) { if (m_progressDialog->IsShown()) return false; } delete m_progressDialog; m_progressDialog = new CProgressDialog( buf, count, CTT32App::instance()->m_pMainWnd, new CTT32Thread(func, arg), indefinite); return true; } // wxProgressDialog::Update ruft DispatchEvent / YieldFor auf, das wiederum die naechsten Events verarbeiten wuerde // Ausgenommen davon sind Events der Category USER_INPUT aber nicht THREAD. Daher eine eigene Klase bauen, // die GetEventCategory entsprechend ueberlaedt class MyThreadEvent : public wxThreadEvent { public: MyThreadEvent(wxEventType evtType = wxEVT_THREAD, int id = wxID_ANY) : wxThreadEvent(evtType, id) {} wxEventCategory GetEventCategory() const{return wxEVT_CATEGORY_USER_INPUT;} wxEvent * Clone() const {return new MyThreadEvent(*this);} }; // Step progress bar void CTT32App::ProgressBarStep() { if (wxTheApp == nullptr) return; wxGetApp().AddPendingEvent(MyThreadEvent(IDC_PROGRESSBAR_STEP)); } void CTT32App::ProgressBarExit(int retCode) { if (wxTheApp == nullptr) return; wxGetApp().AddPendingEvent(MyThreadEvent(IDC_PROGRESSBAR_EXIT)); } void CTT32App::OnProgressBarStep(wxThreadEvent &) { if (m_progressDialog) { int val = ((CProgressDialog *) m_progressDialog)->IncrementCounter(); if (val <= m_progressDialog->GetRange()) m_progressDialog->Update(val); else OutputDebugString(wxT("OnProgressBarStep called to many times")); } } void CTT32App::SetProgressBarText(const wxString &text) { if (m_progressDialog) m_progressDialog->Update(0, text); } void CTT32App::OnProgressBarExit(wxThreadEvent &) { if (!m_progressDialog) return; // Ich loesche m_progressDialog, Destruktor oder Update koennten aber wiederum Exit aufrufen wxProgressDialog *tmp = m_progressDialog; m_progressDialog = NULL; if (tmp) tmp->Update(tmp->GetRange()); delete(tmp); } wxPanel * CTT32App::OpenView(const wxString &title, const wxChar *xrcName, ...) { va_list vaList; va_start(vaList, xrcName); return OpenViewChildFrame("ChildFrame", title, xrcName, vaList); } wxPanel * CTT32App::OpenViewNoResize(const wxString &title, const wxChar *xrcName, ...) { va_list vaList; va_start(vaList, xrcName); return OpenViewChildFrame("ChildFrameNoResize", title, xrcName, vaList); } wxPanel * CTT32App::OpenViewChildFrame(const wxString &childFrame, const wxString &title, const wxChar *xrcName, va_list vaList) { CChildFrame *child = (CChildFrame *) wxXmlResource::Get()->LoadObject(m_pMainWnd, childFrame, "wxMDIChildFrame"); CFormViewEx *panel = (CFormViewEx *) wxXmlResource::Get()->LoadPanel(child, xrcName); if (!panel) { delete child; return NULL; } child->SetTitle(title); child->SetIcon(wxIcon("child")); child->SetClientSize(panel->GetSize()); child->SetSize(panel->GetSize()); // child->CenterOnParent(); // panel->RestoreSettings(); panel->GetEventHandler()->ProcessEvent(wxInitDialogEvent()); panel->Edit(vaList); va_end(vaList); child->Show(); return panel; } wxPanel * CTT32App::OpenDialog(bool modal, const wxString &title, const wxChar *xrcName, ...) { va_list vaList; va_start(vaList, xrcName); wxDialog *child = new wxDialog(m_pMainWnd, wxID_ANY, title); CFormViewEx *panel = NULL; if ( !(panel = (CFormViewEx *) wxXmlResource::Get()->LoadPanel(child, xrcName)) ) { delete child; return NULL; } child->SetIcon(wxIcon("child")); child->SetClientSize(panel->GetSize()); child->SetSize(panel->GetSize()); panel->GetEventHandler()->ProcessEvent(wxInitDialogEvent()); panel->Edit(vaList); va_end(vaList); if (modal) child->ShowModal(); else child->Show(); return panel; } // ----------------------------------------------------------------------- void CTT32App::ShowHtmlDialog(const wxString &filename) { wxFileName file; file.SetFullName(filename); // Falls nicht im cwd dann beim Exe suchen (default bei Installation) if (!file.Exists()) file.SetPath(wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath()); // Falls auch nicht dort, dann aus workspace (aktuellste Version) if (!file.Exists()) { // file.SetPath("\\user\\cht\\wxTTM\\src\\Resources"); wxFileName exe = wxFileName(wxStandardPaths::Get().GetExecutablePath()); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.AppendDir("Resources"); wxString path = exe.GetPath(); file.SetPath(path); } if (file.Exists()) wxLaunchDefaultBrowser(file.GetFullPath()); } // ----------------------------------------------------------------------- void CTT32App::ShowAboutDialog() { wxAboutDialogInfo info; info.SetName(wxT("TTM")); info.SetDescription(_T("Table Tennis Manager")); info.SetCopyright(copyright); info.SetVersion(version); info.SetWebSite("http://downloads.ttm.co.at/ttm/changes.html", _("View changes")); #if 0 if (!expire.IsEmpty()) { int day = wxAtoi(expire.c_str()) % 100; int mon = (wxAtoi(expire.c_str()) / 100) % 100; int year = wxAtoi(expire.c_str()) / 10000; struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_year = year - 1900; tm.tm_mon = mon-1; tm.tm_mday = day; wxString expireStr = wxDateTime(tm).FormatDate(); info.SetLicense(wxString::Format(_("Licensed by %s. License expires %s"), licensee, expireStr.c_str())); } else { info.SetLicense(wxString::Format(_("Unlicensed copy"))); } #endif ::wxAboutBox(info, m_pMainWnd); } // ----------------------------------------------------------------------- // Turnierspezifische Einstellungen bool CTT32App::GetPrintCombinedScoresheet() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_COMBINED_SCORESHEET, 0) ? true : false; } void CTT32App::SetPrintCombinedScoresheet(bool set) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_COMBINED_SCORESHEET, set ? 1 : 0); } bool CTT32App::GetPrintKONamesBold() const { return false; } int CTT32App::GetPrintAssociation() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION, 1); } void CTT32App::SetPrintAssociation(int set) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION, set); } int CTT32App::GetPrintAssociationTeam() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_TEAM, 1); } void CTT32App::SetPrintAssociationTeam(int set) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_TEAM, set); } int CTT32App::GetPrintNationNameWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_NAME_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_NATION_NAME_WIDTH, -1); return ret; } void CTT32App::SetPrintNationNameWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_NAME_WIDTH, width); } int CTT32App::GetPrintNationDescWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_DESC_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_NATION_DESC_WIDTH, -1); return ret; } void CTT32App::SetPrintNationDescWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_DESC_WIDTH, width); } int CTT32App::GetPrintNationRegionWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_REGION_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_NATION_REGION_WIDTH, -1); return ret; } void CTT32App::SetPrintNationRegionWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_NATION_REGION_WIDTH, width); } int CTT32App::GetPrintTeamNameWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_TEAM_NAME_WIDTH, -2); if (ret == -2) ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_TEAM_NAME_WIDTH, -1); return ret; } void CTT32App::SetPrintTeamNameWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_TEAM_NAME_WIDTH, width); } int CTT32App::GetPrintStartNrWidth() const { // -1 means "auto" int ret = ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_PLNR_WIDTH, -2); if (ret == -2) // Undefined, try global ret = ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_PRINT_PLNR_WIDTH, -1); return ret; } void CTT32App::SetPrintStartNrWidth(int width) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_PLNR_WIDTH, width); } bool CTT32App::GetPrintPreview() const { if ( ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PREVIEW, 0) ) return true; return false; } void CTT32App::SetPrintPreview(bool state) const { ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PREVIEW, state ? 1 : 0); if (state) ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PDF, 0); } bool CTT32App::GetPrintPdf() const { if ( ttProfile.GetInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PDF, 0) ) return true; return false; } void CTT32App::SetPrintPdf(bool state) const { ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PDF, state ? 1 : 0); if (state) ttProfile.AddInt(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_PREVIEW, 0); } double CTT32App::GetPrintCaptionMarginKO() const { return ((double) ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_PRINT_CAPTIONMARGINKO, 100)) / 100.; } void CTT32App::SetPrintCaptionMarginKO(double margin) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_PRINT_CAPTIONMARGINKO, std::floor(100. * margin)); } wxString CTT32App::GetDateFormat() const { wxString format = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_DATESTRING); if (format.IsEmpty()) format = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_DATESTRING, wxT("%a, %d %b")); // %d %b %y return format; } wxString CTT32App::GetTimeFormat() const { wxString format = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TIMESTRING); if (format.IsEmpty()) format = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_TIMESTRING, wxT("%H:%M")); return format; } // ----------------------------------------------------------------------- wxString CTT32App::GetTournament() const { return tournament; } wxString CTT32App::GetPath() const { return wxString(ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_PATH)); } wxString CTT32App::GetBackupPath() const { return wxString(ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPPATH)); } void CTT32App::SetBackupPath(const wxString &path) { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPPATH, path); } int CTT32App::GetBackupTime() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPTIME, 30); } void CTT32App::SetBackupTime(int t) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPTIME, t); } bool CTT32App::GetBackupAppendTimestamp() const { return ttProfile.GetBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPAPPENDTIMESTAMP, false); } void CTT32App::SetBackupAppendTimestamp(bool a) { ttProfile.AddBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPAPPENDTIMESTAMP, a); } bool CTT32App::GetBackupKeepLast() const { // Make sure at least one if "append timestamp" and "keep last" is set return ttProfile.GetBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPLAST, !GetBackupAppendTimestamp()); } void CTT32App::SetBackupKeepLast(bool a) { ttProfile.AddBool(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPLAST, a); } int CTT32App::GetBackupKeepNofItems() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPNOFITEMS, 0); } void CTT32App::SetBackupKeepNofItems(int a) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_BACKUPKEEPNOFITEMS, a); } void CTT32App::SetDefaultCP(const wxString &cpName) const { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_DEFCP, cpName); ((CMainFrame *) m_pMainWnd)->SetDefaultCP(cpName); } void CTT32App::SetDefaultGR(const wxString &grName) const { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_DEFGR, grName); ((CMainFrame *) m_pMainWnd)->SetDefaultGR(grName); } void CTT32App::SetDefaultNA(const wxString &naName) const { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_DEFNA, naName); ((CMainFrame *) m_pMainWnd)->SetDefaultNA(naName); } wxString CTT32App::GetDefaultCP() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_DEFCP); } wxString CTT32App::GetDefaultGR() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_DEFGR); } wxString CTT32App::GetDefaultNA() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_DEFNA); } void CTT32App::SetType(short type, bool writeDB) { if (type == GetType()) return; if (writeDB) IdStore::SetType(type); ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TYPE, type); } short CTT32App::GetType() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TYPE); } short CTT32App::GetDefaultType() const { return defaultType; } void CTT32App::SetTable(short table, bool writeDB) { if (table == GetTable()) return; if (writeDB) IdStore::SetTable(table); ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TABLE, table); } short CTT32App::GetTable() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TABLE); } short CTT32App::GetDefaultTable() const { return defaultTable; } void CTT32App::SetReportTitle(const wxString &title, bool writeDB) const { wxString oldTitle = GetReportTitle(); if (!oldTitle.IsEmpty() && !title.IsEmpty() && !wxStrcoll(oldTitle, title)) return; if (writeDB) IdStore::SetReportTitle(title); ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_STRTITLE, title); } wxString CTT32App::GetReportTitle() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_STRTITLE); } void CTT32App::SetReportSubtitle(const wxString &subtitle, bool writeDB) const { wxString oldSubTitle = GetReportSubtitle(); if (oldSubTitle.IsEmpty() && subtitle.IsEmpty() && !wxStrcoll(oldSubTitle, subtitle)) return; if (writeDB) IdStore::SetReportSubtitle(subtitle); ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_STRSUBTITLE, subtitle); } wxString CTT32App::GetReportSubtitle() const { return ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_STRSUBTITLE); } bool CTT32App::GetPrintBanner() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTBANNER, 0) != 0; } void CTT32App::SetPrintBanner(bool printBanner) const { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTBANNER, printBanner ? 1 : 0); } bool CTT32App::GetPrintLogo() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLOGO, 0) != 0; } void CTT32App::SetPrintLogo(bool printLogo) const { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLOGO, printLogo? 1 : 0); } bool CTT32App::GetPrintSponsor() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSPONSOR, 0) != 0; } void CTT32App::SetPrintSponsor(bool printSponsor) const { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSPONSOR, printSponsor ? 1 : 0); } wxString CTT32App::GetPrintLanguage() const { wxString printLang = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLANG); if (!printLang) printLang = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE); return printLang; } void CTT32App::SetPrintLanguage(const wxString &printLang) { ttProfile.AddString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTLANG, printLang); } bool CTT32App::GetPrintScaleToPaperSize() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSCALEPAPER, 0) != 0; } void CTT32App::SetPrintScaleToPaperSize(bool printScale) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_PRINTSCALEPAPER, printScale ? 1 : 0); } wxString CTT32App::GetLanguage() const { wxString lang = ttProfile.GetString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE); if (!lang) lang = wxLocale(wxLocale::GetSystemLanguage()).GetCanonicalName(); return lang; } void CTT32App::SetLanguage(const wxString &lang) { ttProfile.AddString(PRF_GLOBAL_SETTINGS, PRF_SETTINGS_LANGUAGE, lang); const wxLanguageInfo *info = wxLocale::FindLanguageInfo(lang); wxTranslations *trans = new wxTranslations(); if (info) trans->SetLanguage(info->CanonicalName); wxTranslations::Set(trans); } bool CTT32App::GetPrintPlayersSignature() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREPLSIG, 1) != 0; } void CTT32App::SetPrintPlayersSignature(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREPLSIG, f ? 1 : 0); if (writeDB) IdStore::SetPrintPlayersSignature(f); } bool CTT32App::GetPrintScoreCoaches() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORECOACHES, 1) != 0; } void CTT32App::SetPrintScoreCoaches(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORECOACHES, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreCoaches(f); } bool CTT32App::GetPrintScoreUmpires() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRES, 1) != 0; } void CTT32App::SetPrintScoreUmpires(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRES, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreUmpires(f); } bool CTT32App::GetPrintScoreExtras() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREEXTRAS, 0) != 0; } bool CTT32App::GetPrintScoreUmpireName() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRENAME, 1) != 0; } void CTT32App::SetPrintScoreUmpireName(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREUMPIRENAME, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreUmpireName(f); } void CTT32App::SetPrintScoreExtras(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREEXTRAS, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreExtras(f); } bool CTT32App::GetPrintScoreStartEnd() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESTARTENDTIME, 0) != 0; } void CTT32App::SetPrintScoreStartEnd(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESTARTENDTIME, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreRemarks(f); } bool CTT32App::GetPrintScoreRemarks() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREREMARKS, 0) != 0; } void CTT32App::SetPrintScoreRemarks(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCOREREMARKS, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreRemarks(f); } bool CTT32App::GetPrintScoreServiceTimeout() const { return ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESERVICETIMEOUT, 0) != 0; } void CTT32App::SetPrintScoreServiceTimeout(bool f, bool writeDB) { ttProfile.AddInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_SCORESERVICETIMEOUT, f ? 1 : 0); if (writeDB) IdStore::SetPrintScoreServiceTimeout(f); } void CTT32App::SetOvFgColor(const wxString &which, const wxColor &color) { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxString result; bool found = false; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { found = true; wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); result += which; result += ":"; result += ColorToString(color); result += " "; if (sa.GetCount() > 1) result += sa[1]; else result += ColorToString(wxNullColour); result += ";"; } else result += tmp + ";"; } if (!found) { result += which; result += ":"; result += color.GetAsString(wxC2S_HTML_SYNTAX); result += " "; result += ColorToString(wxNullColour); result += ";"; } ttProfile.AddString(PRF_SETTINGS, PRF_OVLIST_COLORS, result); } wxColor CTT32App::GetOvFgColor(const wxString &which) const { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxColor result = wxNullColour; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); if (sa.GetCount() > 0) result = StringToColor(sa[0]); break; } } return result; } void CTT32App::SetOvBkColor(const wxString &which, const wxColor &color) { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxString result; bool found = false; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { found = true; wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); result += which; result += ":"; if (sa.GetCount() > 0) result += sa[0]; else result += ColorToString(wxNullColour); result += " "; result += ColorToString(color); result += ";"; } else result += tmp + ";"; } if (!found) { result += which; result += ":"; result += ColorToString(wxNullColour); result += " "; result += ColorToString(color); result += ";"; } ttProfile.AddString(PRF_SETTINGS, PRF_OVLIST_COLORS, result); } wxColor CTT32App::GetOvBkColor(const wxString &which) const { wxArrayString colors = wxStringTokenize(ttProfile.GetString(PRF_SETTINGS, PRF_OVLIST_COLORS, ""), ";"); wxColor result = wxNullColour; for (size_t i = 0; i < colors.GetCount(); i++) { wxString tmp = colors[i]; if (tmp.StartsWith(which + ":")) { wxArrayString sa = wxStringTokenize(tmp.Mid(which.Length() + 1), " "); if (sa.GetCount() > 1) result = StringToColor(sa[1]); break; } } return result; } // ----------------------------------------------------------------------- bool CTT32App::CreateTournament( const wxString &name, const wxString &database, const wxString &server, bool windowsAuthentication, const wxString &user, const wxString &passwd, short type, short table) { #if 0 if (expire.IsEmpty()) { if (server.IsEmpty() || TTDbse::IsLocalAddress(server)) { infoSystem.Error(_("No valid license found")); return false; } } #endif if (name == "") { infoSystem.Error(_("Illegal tournament name")); return false; } if (database == "") { infoSystem.Error(_("Illegal database name")); return false; } static const char chars[] = "abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"; for (const char *ptr = database.data(); *ptr; ptr++) { if (strchr(chars, *ptr) == NULL) { infoSystem.Error(_("Illegal database name")); return false; } } CloseTournament(); if (!TTDbse::instance()->CreateDatabase(database, server, windowsAuthentication, user, passwd, type, table)) return false; char *tmp = _getcwd(NULL, _MAX_PATH); wxString dir = wxString(tmp) + "\\" + database; free(tmp); // Falls es eine remote DB war _mkdir(dir.data()); m_pMainWnd->SetTitle(wxT("TTM - ") + name); // Update TT32.ini wxString connStr = TTDbse::instance()->GetConnectionString(); ttProfile.AddString(PRF_TURNIER, name.data(), connStr.data()); ttProfile.AddString(PRF_OPEN, PRF_LAST, name.data()); ttProfile.AddString(name.data(), PRF_PATH, database.data()); // SetXXX will das Turnier haben. tournament = name; SetMenuBar("ITTFMenuBar"); // Nur in lokaler DB auch in DB schreiben, sonst nur in ini file SetType(type, TTDbse::IsLocalAddress(server)); SetTable(table, TTDbse::IsLocalAddress(server)); ((CMainFrame *) m_pMainWnd)->SetDefaultCP(GetDefaultCP()); ((CMainFrame *) m_pMainWnd)->SetDefaultGR(GetDefaultGR()); ((CMainFrame *) m_pMainWnd)->SetDefaultNA(GetDefaultNA()); if (TTDbse::IsLocalAddress(server)) { Connect(wxEVT_TIMER, wxTimerEventHandler(CTT32App::OnTimer), NULL, this); m_backupTimer.Start(GetBackupTime() * 60 * 1000, false); } return true; } bool CTT32App::OpenTournament(const wxString &name) { CloseTournament(); wxString tmp = ttProfile.GetString(PRF_TURNIER, name); if (tmp.IsEmpty()) return false; wxString connStr = tmp; wxString server = TTDbse::GetServer(connStr); wxString database = TTDbse::GetDatabase(connStr); bool throwError = !TTDbse::IsLocalAddress(server); throwError |= database.IsEmpty(); throwError |= _taccess(ttProfile.GetString(name, PRF_PATH).t_str(), 00) != 0; short type = 0; short table = 0; if (!TTDbse::instance()->OpenDatabase(connStr, throwError)) { if (throwError) return false; // Nochmals lesen, tmp ist eine statische Variable in ttProfile tmp = ttProfile.GetString(PRF_TURNIER, name); type = ttProfile.GetInt(name, PRF_SETTINGS_TYPE); table = ttProfile.GetInt(name, PRF_SETTINGS_TABLE); bool trustedConn = TTDbse::GetWindowsAuthentication(connStr); wxString user = trustedConn ? TTDbse::GetUser(connStr) : wxEmptyString; wxString pwd = trustedConn ? TTDbse::GetPassword(connStr) : wxEmptyString; TTDbse::instance()->DetachDatabase(connStr, false); if (!TTDbse::instance()->CreateDatabase(database, server, trustedConn, user, pwd, type, table)) return false; } m_pMainWnd->SetTitle(wxT("TTM - ") + name); ttProfile.AddString(PRF_OPEN, PRF_LAST, name); tournament = name; type = IdStore::GetType(); table = IdStore::GetTable(); if (table == 0) { // Tabelle steht noch nicht in der DB if (ttProfile.GetInt(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TABLE) == -1) { // Auch nicht im Profile, also ermitteln CpListStore cp; cp.SelectAll(); cp.Next(); cp.Close(); short newType = defaultType; if (cp.cpYear == 0) newType = defaultType; else if (cp.cpYear < 1970) newType = TT_SCI; else if (cp.cpYear > 1990) newType = TT_YOUTH; wxString oldType = ttProfile.GetString(PRF_LOCAL_SETTINGS, PRF_SETTINGS_TYPE); if (!oldType) { IdStore::SetType(newType); IdStore::SetTable(defaultTable); } else if (!wxStrcmp(wxT("SCI"), oldType)) { IdStore::SetType(newType); IdStore::SetTable(TT_ITTF); } else if (!wxStrcmp(wxT("DTTB"), oldType)) { IdStore::SetType(newType); IdStore::SetTable(TT_DTTB); } else { IdStore::SetType(newType); IdStore::SetTable(TT_ITTF); } IdStore::SetReportTitle(GetReportTitle()); IdStore::SetReportSubtitle(GetReportSubtitle()); } } // Intern cachen, ohne in die DB zu schreiben SetType(IdStore::GetType(), false); SetTable(IdStore::GetTable(), false); SetReportTitle(IdStore::GetReportTitle().data(), false); SetReportSubtitle(IdStore::GetReportSubtitle().data(), false); SetPrintScoreExtras(IdStore::GetPrintScoreExtras(), false); SetPrintPlayersSignature(IdStore::GetPrintPlayersSignature(), false); SetPrintScoreRemarks(IdStore::GetPrintScoreRemarks(), false); SetPrintScoreCoaches(IdStore::GetPrintScoreCoaches(), false); SetPrintScoreUmpires(IdStore::GetPrintScoreUmpires(), false); SetPrintScoreServiceTimeout(IdStore::GetPrintScoreServiceTimeout(), false); SetMenuBar("ITTFMenuBar"); ((CMainFrame *) m_pMainWnd)->SetDefaultCP(GetDefaultCP()); ((CMainFrame *) m_pMainWnd)->SetDefaultGR(GetDefaultGR()); ((CMainFrame *) m_pMainWnd)->SetDefaultNA(GetDefaultNA()); if (connStr.find(wxString("localhost")) != wxString::npos) { Connect(wxEVT_TIMER, wxTimerEventHandler(CTT32App::OnTimer), NULL, this); m_backupTimer.Start(GetBackupTime() * 60 * 1000, false); } return true; } bool CTT32App::OpenLastTournament() { wxString tour = ttProfile.GetString(PRF_OPEN, PRF_LAST); if (!tour.IsEmpty()) return OpenTournament(tour); return false; } bool CTT32App::CloseTournament() { wxWindowList list = m_pMainWnd->GetChildren(); for (wxWindowList::iterator it = list.begin(); it != list.end(); it++) (*it)->Close(); m_pMainWnd->SetTitle(wxT("TTM")); // ttProfile.DeleteString(PRF_OPEN, PRF_LAST); tournament = ""; SetMenuBar("NOMenuBar"); if (m_backupTimer.IsRunning()) { Disconnect(wxEVT_TIMER, wxTimerEventHandler(CTT32App::OnTimer), NULL, this); m_backupTimer.Stop(); } TTDbse::instance()->CloseDatabase(); return true; } bool CTT32App::DetachTournament(const wxString &name, bool deleteDir) { wxString tmp = ttProfile.GetString(PRF_TURNIER, name.data()); if (!tmp) return false; if (name == tournament) CloseTournament(); wxString connStr = tmp; // Wenn es eine lokale DB ist, im Server austragen. if (TTDbse::IsLocalAddress(TTDbse::GetServer(connStr))) { // Im Fehlerfall das ini-File belassen if (!TTDbse::instance()->DetachDatabase(connStr)) return false; } if (deleteDir) { wxString dir = ttProfile.GetString(name, PRF_PATH); if (!dir.IsEmpty()) wxFileName::Rmdir(dir, wxPATH_RMDIR_RECURSIVE); ttProfile.DeleteSection(name); } ttProfile.DeleteString(PRF_TURNIER, name); return true; } void CTT32App::ImportOnlineEntries() { CImportOnlineEntries::Import(); } // ----------------------------------------------------------------------- void CTT32App::BackupDatabase() { time_t t = time(NULL); struct tm *tm = localtime(&t); wxChar tmp[16]; wxSprintf(tmp, "-%04d%02d%02dT%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min); wxString name = GetDatabase() + tmp + ".bak"; wxFileDialog fileDlg( m_pMainWnd, _("Backup Database"), GetPath(), name, "Backup Files (*.bak)|*.bak|All Files (*.*)|*.*||", wxFD_SAVE); if (fileDlg.ShowModal() != wxID_OK) return; name = fileDlg.GetPath(); wxFileName saveName(name); // Filename fuer Backup wxFileName tmpName(name); // Filename, wie er an die DB uebergeben wird wxFileName dbPath(GetPath()); // Pfad, wo das DB-File liegt saveName.Normalize(); tmpName.Normalize(); dbPath.Normalize(); // dbPath ist ein Verzeichnis, GetFullPath also der komplette Name // tmpName ist ein Dateiname, GetPath also das Verzeichnis ohne Dateiname und -erweiterung if (tmpName.GetPath() != dbPath.GetFullPath()) { tmpName = wxFileName(GetPath(), wxString("tmp-") + fileDlg.GetFilename()).GetFullPath(); tmpName.Normalize(); } m_pMainWnd->SetCursor(wxCURSOR_WAIT); bool res = TTDbse::instance()->BackupDatabase(tmpName.GetFullPath()); // Falls eine temp. Kopie im DB-Verzeichnis gemacht wurde if (res && tmpName != saveName) { wxCopyFile(tmpName.GetFullPath(), saveName.GetFullPath()); wxRemoveFile(tmpName.GetFullPath()); } // Ebenfalls Kopie im alternativen Verzeichnis wxString backupPath = GetBackupPath(); if (!backupPath.IsEmpty() && backupPath != saveName.GetPath()) { wxFileName fn(backupPath, saveName.GetFullName()); if (fn.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) wxCopyFile(saveName.GetFullPath(), fn.GetFullPath(), true); } m_pMainWnd->SetCursor(wxCURSOR_DEFAULT); if (res) infoSystem.Information(_("Backup successful")); } void CTT32App::RestoreDatabase() { wxString name = GetDatabase() + ".bak"; wxFileName tmpName(GetPath(), name); tmpName.Normalize(); wxFileDialog fileDlg( m_pMainWnd, _("Backup Database"), GetPath(), name, "Backup Files (*.bak)|*.bak|All Files (*.*)|*.*||", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (fileDlg.ShowModal() != wxID_OK) return; name = fileDlg.GetPath(); if (name != tmpName.GetFullPath()) { tmpName = wxFileName(GetPath(), wxString("tmp-") + fileDlg.GetFilename()); tmpName.Normalize(); wxCopyFile(name, tmpName.GetFullPath()); } m_pMainWnd->SetCursor(wxCURSOR_WAIT); bool res = TTDbse::instance()->RestoreDatabase(tmpName.GetFullPath(), GetPath()); wxRemoveFile(tmpName.GetFullPath()); m_pMainWnd->SetCursor(wxCURSOR_DEFAULT); if (res) infoSystem.Information(_("Restore successful")); } // ----------------------------------------------------------------------- void CTT32App::OnTimer(wxTimerEvent &evt) { wxChar tmp[16]; *tmp = 0; if (GetBackupAppendTimestamp()) { // Zeitstempel anhaengen, wenn so gewuenscht time_t t = time(NULL); struct tm *tm = localtime(&t); wxSprintf(tmp, "-%04d%02d%02dT%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min); } wxChar ps = wxFileName::GetPathSeparator(); wxString path = GetPath(); if (!wxFileName(path).IsAbsolute()) path = wxGetCwd() + ps + GetPath(); // move <database>.<n>.bak to <database>.<n+1>.bak if (CTT32App::GetBackupKeepLast() && CTT32App::instance()->GetBackupKeepNofItems() > 0) { std::vector<wxString> pathes; pathes.push_back(path); if (!GetBackupPath().IsEmpty()) pathes.push_back(GetBackupPath()); for (auto path : pathes) { // Numerierung beginnt bei 0 int nof = CTT32App::GetBackupKeepNofItems() - 1; { // Remove last file wxString ext = wxString::Format(".%d.bak", nof); wxFileName fn(path, GetDatabase() + tmp + ext); if (fn.Exists()) wxRemoveFile(fn.GetFullPath()); } while (nof--) { // Move files to next number wxString extf = wxString::Format(".%d.bak", nof); wxString extt = wxString::Format(".%d.bak", nof + 1); wxFileName fnf(path, GetDatabase() + tmp + extf); wxFileName fnt(path, GetDatabase() + tmp + extt); if (fnf.Exists()) wxRenameFile(fnf.GetFullPath(), fnt.GetFullPath(), true); } { // Move current file to first number wxFileName fnf(path, GetDatabase() + tmp + ".bak"); wxFileName fnt(path, GetDatabase() + tmp + ".0.bak"); if (fnf.Exists()) wxRenameFile(fnf.GetFullPath(), fnt.GetFullPath(), true); } } } // Backup Database m_pMainWnd->SetCursor(wxCURSOR_WAIT); TTDbse::instance()->BackupDatabase(wxFileName(path, GetDatabase() + tmp + ".bak").GetFullPath()); m_pMainWnd->SetCursor(wxCURSOR_DEFAULT); wxString backupPath = GetBackupPath(); if (!backupPath.IsEmpty()) { wxFileName fn(backupPath, GetDatabase() + tmp + ".bak"); if (fn.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) wxCopyFile(wxFileName(path, GetDatabase() + tmp + ".bak").GetFullPath(), fn.GetFullPath(), true); } } // ----------------------------------------------------------------------- wxString CTT32App::GetResourcesPath() const { wxFileName file; file.SetFullName(TT_XRCFILE); // Falls nicht im cwd dann beim Exe suchen (default bei Installation) if (!file.Exists()) file.SetPath(wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath()); // Falls auch nicht dort, dann aus workspace (aktuellste Version) if (!file.Exists()) { // file.SetPath("\\user\\cht\\wxTTM\\src\\Resources"); wxFileName exe = wxFileName(wxStandardPaths::Get().GetExecutablePath()); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.RemoveLastDir(); exe.AppendDir("Resources"); wxString path = exe.GetPath(); file.SetPath(path); } if (file.Exists()) return file.GetPath(); return ""; } // ----------------------------------------------------------------------- bool CTT32App::IsLicenseValid() const { #if 0 wxString name = wxGetCwd() + wxFileName::GetPathSeparator() + "License.ini"; return CheckLicenseCode(name) && !HasLicenseExpired(name); #else return true; #endif } bool CTT32App::CheckLicenseCode(const wxString &name) const { #if 0 char tmpLicensee[256]; char tmpExpires[256]; char buffer[512]; char code[64]; GetPrivateProfileStringA("License", "licensee", "", tmpLicensee, sizeof(tmpLicensee), name); GetPrivateProfileStringA("License", "expires", "", tmpExpires, sizeof(tmpExpires), name); GetPrivateProfileStringA("License", "code", "", code, sizeof(code), name); strcpy(buffer, tmpLicensee); strcat(buffer, tmpExpires); long tmp = crypt(buffer); return (tmp == atol(code)); #else return true; #endif } bool CTT32App::HasLicenseExpired(const wxString &name) const { #if 0 char tmpExpires[256]; GetPrivateProfileStringA("License", "expires", "", tmpExpires, sizeof(tmpExpires), name); wxString exp = tmpExpires; if (exp.IsEmpty()) return true; time_t t = time(0); struct tm *tm = localtime(&t); int day = wxAtoi(exp.c_str()) % 100; int mon = (wxAtoi(exp.c_str()) / 100) % 100; int year = wxAtoi(exp.c_str()) / 10000; if (tm->tm_year + 1900 > year) return true; else if (tm->tm_year + 1900 < year) return false; if (tm->tm_mon + 1 > mon) return true; else if (tm->tm_mon + 1 < mon) return false; if (tm->tm_mday > day) return true; return false; #else return false; #endif } // ----------------------------------------------------------------------- void CTT32App::CheckForUpdate() { wxURL url("http://downloads.ttm.co.at/ttm/current.txt"); if (url.GetError() == wxURL_NOERR) { wxString newVersionNumnber; wxInputStream *in = url.GetInputStream(); if (in && in->IsOk()) { wxStringOutputStream sos(&newVersionNumnber); in->Read(sos); newVersionNumnber.Trim(); if (newVersionNumnber > versionNumber) { wxDialog * dlg = wxXmlResource::Get()->LoadDialog(m_pMainWnd, "UpdateAvailable"); // Aus seltsamen Gruenden hat der Close-Button nicht die "affirmative ID" dlg->FindWindow("Close")->SetId(dlg->GetAffirmativeId()); dlg->ShowModal(); } else { infoSystem.Information(_("You are using the latest version of TTM")); } return; } } // Irgend ein Fehler ist aufgetreten infoSystem.Error(_("Could not determine the current version of TTM")); } // ----------------------------------------------------------------------- void CTT32App::InstallLicense() { wxString name = "License.ini"; wxFileDialog fileDlg( m_pMainWnd, _("Install License"), wxStandardPaths::Get().GetDocumentsDir(), name, "License Files (*.ini)|*.ini|All Files (*.*)|*.*||", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (fileDlg.ShowModal() != wxID_OK) return; name = fileDlg.GetPath(); if (!CheckLicenseCode(name)) { infoSystem.Error(_("The license is not valid")); } else if (HasLicenseExpired(name)) { infoSystem.Error(_("The license has expired")); } else if (!::wxCopyFile(name, "License.ini")) { infoSystem.Error(_("Could not copy license file")); } else { infoSystem.Information(_("License file was copied")); ReadLicense(wxGetCwd() + wxFileName::GetPathSeparator() + "License.ini"); } } void CTT32App::ReadLicense(const wxString &name) { // Check License file // Wenn die Lizenz nicht gueltig ist, gelten die hart codierten defaults fuer // Licensee und expire if (wxFile::Exists(name)) { char tmpLicensee[256]; char tmpExpires[256]; char buffer[512]; char code[64]; GetPrivateProfileStringA("License", "licensee", "", tmpLicensee, sizeof(tmpLicensee), name); GetPrivateProfileStringA("License", "expires", "", tmpExpires, sizeof(tmpExpires), name); GetPrivateProfileStringA("License", "code", "", code, sizeof(code), name); strcpy(buffer, tmpLicensee); strcat(buffer, tmpExpires); if (crypt(buffer) == atol(code)) { licensee = tmpLicensee; expire = tmpExpires; defaultType = GetPrivateProfileIntA("Defaults", "Type", TT_REGULAR, name); defaultTable = GetPrivateProfileIntA("Defaults", "Table", -1, name); if (defaultTable == -1) defaultTable = GetPrivateProfileIntA("Defaults", "TableMode", -1, name); if (defaultTable == -1) defaultTable = GetPrivateProfileIntA("Defaults", "GroupMode", -1, name); if (defaultTable == -1) defaultTable = TT_ITTF; } else { licensee = ""; expire = ""; } } else { licensee = ""; expire = ""; } } wxString CTT32App::ColorToString(const wxColor &color) const { if (color == wxNullColour || !color.IsOk()) return "default"; return color.GetAsString(wxC2S_HTML_SYNTAX); } wxColor CTT32App::StringToColor(const wxString &name) const { if (name == "default") return wxNullColour; else return wxColor(name); } void CTT32App::SetMenuBar(const wxString &menuBar) { // m_pMainWnd->SetWindowMenu(NULL); m_pMainWnd->SetMenuBar(wxXmlResource::Get()->LoadMenuBar(menuBar)); }
51,281
19,961
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); DoOperation(OperationInitContext, &currentContext, NULL); UpdateLabels(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_DecrimentBtn_clicked() { DoOperation(OperationDecrement, &currentContext, NULL); UpdateLabels(); } void MainWindow::on_IncrementBtn_clicked() { DoOperation(OperationIncrement, &currentContext, NULL); UpdateLabels(); } void MainWindow::on_ResetBtn_clicked() { AppParameters *parameters = (AppParameters *) malloc(sizeof(AppParameters)); if (parameters != NULL) { parameters->newValue = ui->lineEdit->text().toInt(); DoOperation(OperationReset, &currentContext, parameters); UpdateLabels(); free(parameters); } else { //TODO написать что случилась ошибка. } } void MainWindow::UpdateLabels() { ui->label->setText(QString::number(currentContext.currentValue) + " - текущее значение"); ui->ClicksLabel->setText(QString::number(currentContext.clickCount) + " кликов"); }
1,186
377
#include "insertion_sort.h" void InsertionSort::Sort(vector<int> &A) { int n = A.size(); for (int i = 0; i < n; i++) { // 假設 A[0... i-1] 已經排好了。 for (int j = i; j > 0; j--) { if (A[j] < A[j - 1]) { Swap(A[j], A[j - 1]); } else { break; } } } } SorterFactoryRegistrar<Sorter, InsertionSort> InsertionSort::_;
360
171
#include "baseline.h" #include "load_data.h" #include "cb_dsv_loader.h" #include "data_provider_builders.h" #include <catboost/libs/column_description/cd_parser.h> #include <catboost/libs/helpers/exception.h> #include <catboost/libs/helpers/int_cast.h> #include <catboost/libs/logging/logging.h> #include <util/datetime/base.h> namespace NCB { TDataProviderPtr ReadDataset( const TPathWithScheme& poolPath, const TPathWithScheme& pairsFilePath, // can be uninited const TPathWithScheme& groupWeightsFilePath, // can be uninited const TPathWithScheme& timestampsFilePath, // can be uninited const TPathWithScheme& baselineFilePath, // can be uninited const TPathWithScheme& featureNamesPath, // can be uninited const NCatboostOptions::TColumnarPoolFormatParams& columnarPoolFormatParams, const TVector<ui32>& ignoredFeatures, EObjectsOrder objectsOrder, TDatasetSubset loadSubset, TMaybe<TVector<NJson::TJsonValue>*> classLabels, NPar::TLocalExecutor* localExecutor ) { CB_ENSURE_INTERNAL(!baselineFilePath.Inited() || classLabels, "ClassLabels must be specified if baseline file is specified"); if (classLabels) { UpdateClassLabelsFromBaselineFile(baselineFilePath, *classLabels); } auto datasetLoader = GetProcessor<IDatasetLoader>( poolPath, // for choosing processor // processor args TDatasetLoaderPullArgs { poolPath, TDatasetLoaderCommonArgs { pairsFilePath, groupWeightsFilePath, baselineFilePath, timestampsFilePath, featureNamesPath, classLabels ? **classLabels : TVector<NJson::TJsonValue>(), columnarPoolFormatParams.DsvFormat, MakeCdProviderFromFile(columnarPoolFormatParams.CdFilePath), ignoredFeatures, objectsOrder, 10000, // TODO: make it a named constant loadSubset, localExecutor } } ); THolder<IDataProviderBuilder> dataProviderBuilder = CreateDataProviderBuilder( datasetLoader->GetVisitorType(), TDataProviderBuilderOptions{}, loadSubset, localExecutor ); CB_ENSURE_INTERNAL( dataProviderBuilder, "Failed to create data provider builder for visitor of type " << datasetLoader->GetVisitorType() ); datasetLoader->DoIfCompatible(dynamic_cast<IDatasetVisitor*>(dataProviderBuilder.Get())); return dataProviderBuilder->GetResult(); } TDataProviderPtr ReadDataset( const TPathWithScheme& poolPath, const TPathWithScheme& pairsFilePath, // can be uninited const TPathWithScheme& groupWeightsFilePath, // can be uninited const TPathWithScheme& timestampsFilePath, // can be uninited const TPathWithScheme& baselineFilePath, // can be uninited const TPathWithScheme& featureNamesPath, // can be uninited const NCatboostOptions::TColumnarPoolFormatParams& columnarPoolFormatParams, const TVector<ui32>& ignoredFeatures, EObjectsOrder objectsOrder, int threadCount, bool verbose, TMaybe<TVector<NJson::TJsonValue>*> classLabels ) { NPar::TLocalExecutor localExecutor; localExecutor.RunAdditionalThreads(threadCount - 1); TSetLoggingVerboseOrSilent inThisScope(verbose); TDataProviderPtr dataProviderPtr = ReadDataset( poolPath, pairsFilePath, groupWeightsFilePath, timestampsFilePath, baselineFilePath, featureNamesPath, columnarPoolFormatParams, ignoredFeatures, objectsOrder, TDatasetSubset::MakeColumns(), classLabels, &localExecutor ); return dataProviderPtr; } TDataProviderPtr ReadDataset( THolder<ILineDataReader> poolReader, const TPathWithScheme& pairsFilePath, // can be uninited const TPathWithScheme& groupWeightsFilePath, // can be uninited const TPathWithScheme& timestampsFilePath, // can be uninited const TPathWithScheme& baselineFilePath, // can be uninited const TPathWithScheme& featureNamesPath, // can be uninited const NCB::TDsvFormatOptions& poolFormat, const TVector<TColumn>& columnsDescription, // TODO(smirnovpavel): TVector<EColumn> const TVector<ui32>& ignoredFeatures, EObjectsOrder objectsOrder, TMaybe<TVector<NJson::TJsonValue>*> classLabels, NPar::TLocalExecutor* localExecutor ) { const auto loadSubset = TDatasetSubset::MakeColumns(); THolder<IDataProviderBuilder> dataProviderBuilder = CreateDataProviderBuilder( EDatasetVisitorType::RawObjectsOrder, TDataProviderBuilderOptions{}, loadSubset, localExecutor ); CB_ENSURE_INTERNAL( dataProviderBuilder, "Failed to create data provider builder for visitor of type RawObjectsOrder"; ); TCBDsvDataLoader datasetLoader( TLineDataLoaderPushArgs { std::move(poolReader), TDatasetLoaderCommonArgs { pairsFilePath, groupWeightsFilePath, baselineFilePath, timestampsFilePath, featureNamesPath, classLabels ? **classLabels : TVector<NJson::TJsonValue>(), poolFormat, MakeCdProviderFromArray(columnsDescription), ignoredFeatures, objectsOrder, 10000, // TODO: make it a named constant loadSubset, localExecutor } } ); datasetLoader.DoIfCompatible(dynamic_cast<IDatasetVisitor*>(dataProviderBuilder.Get())); return dataProviderBuilder->GetResult(); } TDataProviders ReadTrainDatasets( const NCatboostOptions::TPoolLoadParams& loadOptions, EObjectsOrder objectsOrder, bool readTestData, TDatasetSubset trainDatasetSubset, TMaybe<TVector<NJson::TJsonValue>*> classLabels, NPar::TLocalExecutor* const executor, TProfileInfo* const profile ) { if (readTestData) { loadOptions.Validate(); } else { loadOptions.ValidateLearn(); } TDataProviders dataProviders; if (loadOptions.LearnSetPath.Inited()) { CATBOOST_DEBUG_LOG << "Loading features..." << Endl; auto start = Now(); dataProviders.Learn = ReadDataset( loadOptions.LearnSetPath, loadOptions.PairsFilePath, loadOptions.GroupWeightsFilePath, loadOptions.TimestampsFilePath, loadOptions.BaselineFilePath, loadOptions.FeatureNamesPath, loadOptions.ColumnarPoolFormatParams, loadOptions.IgnoredFeatures, objectsOrder, trainDatasetSubset, classLabels, executor ); CATBOOST_DEBUG_LOG << "Loading features time: " << (Now() - start).Seconds() << Endl; if (profile) { profile->AddOperation("Build learn pool"); } } dataProviders.Test.resize(0); if (readTestData) { CATBOOST_DEBUG_LOG << "Loading test..." << Endl; for (int testIdx = 0; testIdx < loadOptions.TestSetPaths.ysize(); ++testIdx) { const NCB::TPathWithScheme& testSetPath = loadOptions.TestSetPaths[testIdx]; const NCB::TPathWithScheme& testPairsFilePath = testIdx == 0 ? loadOptions.TestPairsFilePath : NCB::TPathWithScheme(); const NCB::TPathWithScheme& testGroupWeightsFilePath = testIdx == 0 ? loadOptions.TestGroupWeightsFilePath : NCB::TPathWithScheme(); const NCB::TPathWithScheme& testTimestampsFilePath = testIdx == 0 ? loadOptions.TestTimestampsFilePath : NCB::TPathWithScheme(); const NCB::TPathWithScheme& testBaselineFilePath = testIdx == 0 ? loadOptions.TestBaselineFilePath : NCB::TPathWithScheme(); TDataProviderPtr testDataProvider = ReadDataset( testSetPath, testPairsFilePath, testGroupWeightsFilePath, testTimestampsFilePath, testBaselineFilePath, loadOptions.FeatureNamesPath, loadOptions.ColumnarPoolFormatParams, loadOptions.IgnoredFeatures, objectsOrder, TDatasetSubset::MakeColumns(), classLabels, executor ); dataProviders.Test.push_back(std::move(testDataProvider)); if (profile && (testIdx + 1 == loadOptions.TestSetPaths.ysize())) { profile->AddOperation("Build test pool"); } } } return dataProviders; } } // NCB
9,581
2,540
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "CPP_Tutorial.h" #include "Kismet/GameplayStatics.h" #include "Blueprint/UserWidget.h" #include "CPP_TutorialGameMode.h" #include "CPP_TutorialCharacter.h" #include "SpawnVolume.h" ACPP_TutorialGameMode::ACPP_TutorialGameMode() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } DecayRate = .01f; } void ACPP_TutorialGameMode::BeginPlay() { Super::BeginPlay(); // find all spawn volume Actors TArray<AActor*> foundActors; UGameplayStatics::GetAllActorsOfClass(GetWorld(), ASpawnVolume::StaticClass(), foundActors); for (auto actor : foundActors) { ASpawnVolume* spawnVolumeActor = Cast<ASpawnVolume>(actor); if (spawnVolumeActor) { _spawnVolumeActors.AddUnique(spawnVolumeActor); } } SetCurrentState(BatteryPlayState::Playing); // set the score to beat ACPP_TutorialCharacter* MyCharacter = Cast<ACPP_TutorialCharacter>(UGameplayStatics::GetPlayerPawn(this, 0)); if (MyCharacter) { PowerToWin = (MyCharacter->GetInitialPower()) * 1.25f; } if (HUDWidgetClass != nullptr) { CurrentWidget = CreateWidget<UUserWidget>(GetWorld(), HUDWidgetClass); if (CurrentWidget != nullptr) { CurrentWidget->AddToViewport(); } } } void ACPP_TutorialGameMode::Tick(float DeltaTime) { Super::Tick(DeltaTime); ACPP_TutorialCharacter* MyCharacter = Cast<ACPP_TutorialCharacter>(UGameplayStatics::GetPlayerPawn(this, 0)); if (MyCharacter) { if (MyCharacter->GetCurrentPower() > PowerToWin) { SetCurrentState(BatteryPlayState::Won); } else if (MyCharacter->GetCurrentPower() > 0) { MyCharacter->UpdatePower(-DeltaTime * DecayRate * (MyCharacter->GetInitialPower())); } else { SetCurrentState(BatteryPlayState::GameOver); } } } void ACPP_TutorialGameMode::SetCurrentState(BatteryPlayState newState) { _currentState = newState; _handleNewState(_currentState); } void ACPP_TutorialGameMode::_handleNewState(BatteryPlayState newState) { auto setVolumesActiveState = [&](bool valueToSet) { for (auto volume : _spawnVolumeActors) { volume->SetSpawningActive(valueToSet); } }; switch (newState) { case BatteryPlayState::Playing: { setVolumesActiveState(true); break; } case BatteryPlayState::Won: { setVolumesActiveState(false); break; } case BatteryPlayState::GameOver: { setVolumesActiveState(false); APlayerController* PlayerController = UGameplayStatics::GetPlayerController(this, 0); if (PlayerController) { PlayerController->SetCinematicMode(true, false, false, true, true); } ACharacter* MyCharacter = UGameplayStatics::GetPlayerCharacter(this, 0); if (MyCharacter) { MyCharacter->GetMesh()->SetSimulatePhysics(true); MyCharacter->GetMovementComponent()->MovementState.bCanJump = false; } break; } case BatteryPlayState::Unknown: default: break; } }
3,084
1,196
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt /* This mex file will create a MATLAB function called example_mex_class. If you call it with no arguments it will output the MATLAB .m code to create a MATLAB wrapper class. Paste that code into a .m file. Then you will be able to work with this C++ class directly in MATLAB. */ #include <iostream> #include <dlib/matrix.h> using namespace std; using namespace dlib; class example_class { public: // The class must have a default constructor. It's also the only kind of constructor // you can call from MATLAB. example_class() { xx.set_size(3,2); xx = 1; } // The rest of the member functions that you want to bind have to return void and // generally have the same syntax limitations as regular mex funcitons. void do_stuff(const matrix_colmajor& x) { cout << "in do_stuff" << endl; cout << x << endl; xx = x; } void do_other_stuff(int x) { cout << "in do_other_stuff" << endl; cout << "x: " << x << endl; } void print_state() { cout << xx << endl; } // saveobj() and load_obj() are special functions. If you provide these then you will // be able to save() and load() your objects using MATLAB's built in object // serialization. void saveobj(matrix_colmajor& state) { // save this object's state to state. state = xx; } void load_obj(const matrix_colmajor& state) { xx = state; } private: matrix_colmajor xx; }; // Just tell the mex wrapper the name of your class and list the methods you want to bind. #define MEX_CLASS_NAME example_class #define MEX_CLASS_METHODS do_stuff, do_other_stuff, print_state, saveobj, load_obj #include "mex_wrapper.cpp"
1,873
597
// os_frt.cpp /* * FRT - A Godot platform targeting single board computers * Copyright (c) 2017-2019 Emanuele Fornara * * 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <unistd.h> #include "core/version.h" #include "core/os/os.h" #include "core/os/input.h" #include "core/os/file_access.h" #include "drivers/unix/os_unix.h" #include "servers/visual_server.h" #include "servers/visual/rasterizer.h" #include "servers/audio/audio_driver_dummy.h" #include "servers/visual/visual_server_raster.h" #include "drivers/alsa/audio_driver_alsa.h" #include "drivers/pulseaudio/audio_driver_pulseaudio.h" #include "main/main.h" #include "main/input_default.h" #include "main/performance.h" #include "core/print_string.h" #define VIDEO_DRIVER_GLES2 0 #define VIDEO_DRIVER_GLES3 1 #if VERSION_MAJOR == 2 #define VIDEO_DRIVER_COUNT 1 #include "platform/x11/joystick_linux.h" #include "servers/visual/visual_server_wrap_mt.h" #include "servers/audio/audio_server_sw.h" #include "servers/audio/sample_manager_sw.h" #include "servers/spatial_sound/spatial_sound_server_sw.h" #include "servers/spatial_sound_2d/spatial_sound_2d_server_sw.h" #include "servers/physics_server.h" #include "servers/physics/physics_server_sw.h" #include "servers/physics_2d/physics_2d_server_sw.h" #include "servers/physics_2d/physics_2d_server_wrap_mt.h" #include "drivers/gles2/rasterizer_gles2.h" static int event_id = 0; class InputModifierStateSetter { private: InputModifierState &mod; public: InputModifierStateSetter(InputModifierState &m) : mod(m) {} void set_shift(bool v) { mod.shift = v; } void set_control(bool v) { mod.control = v; } void set_alt(bool v) { mod.alt = v; } void set_metakey(bool v) { mod.meta = v; } }; class InputEventKeySetter : public InputModifierStateSetter { private: InputEvent &event; public: InputEventKeySetter(InputEvent &ev) : InputModifierStateSetter(ev.key.mod), event(ev) { event.type = InputEvent::KEY; event.device = 0; } void set_pressed(bool v) { event.key.pressed = v; } void set_scancode(uint32_t v) { event.key.scancode = v; } void set_unicode(uint32_t v) { event.key.unicode = v; } void set_echo(bool v) { event.key.echo = v; } }; class InputEventMouseMotionSetter : public InputModifierStateSetter { private: InputEvent &event; public: InputEventMouseMotionSetter(InputEvent &ev) : InputModifierStateSetter(ev.mouse_motion.mod), event(ev) { event.type = InputEvent::MOUSE_MOTION; event.device = 0; } void set_button_mask(int v) { event.mouse_motion.button_mask = v; } void set_position(const Vector2 &v) { event.mouse_motion.x = v.x; event.mouse_motion.y = v.y; } void set_global_position(const Vector2 &v) { event.mouse_motion.global_x = v.x; event.mouse_motion.global_y = v.y; } void set_speed(const Vector2 &v) { event.mouse_motion.speed_x = v.x; event.mouse_motion.speed_y = v.y; } void set_relative(const Vector2 &v) { event.mouse_motion.relative_x = v.x; event.mouse_motion.relative_y = v.y; } }; class InputEventMouseButtonSetter : public InputModifierStateSetter { private: InputEvent &event; public: InputEventMouseButtonSetter(InputEvent &ev) : InputModifierStateSetter(ev.mouse_button.mod), event(ev) { event.type = InputEvent::MOUSE_BUTTON; event.device = 0; } void set_button_mask(int v) { event.mouse_button.button_mask = v; } void set_position(const Vector2 &v) { event.mouse_button.x = v.x; event.mouse_button.y = v.y; } void set_global_position(const Vector2 &v) { event.mouse_button.global_x = v.x; event.mouse_button.global_y = v.y; } void set_pressed(bool v) { event.mouse_button.pressed = v; } void set_button_index(int v) { event.mouse_button.button_index = v; } void set_doubleclick(bool v) { event.mouse_button.doubleclick = v; } }; class InputModifierRef { private: InputModifierStateSetter setter; public: InputModifierRef(InputModifierStateSetter &s) : setter(s) {} InputModifierStateSetter *operator->() { return &setter; } }; template <typename T> class InputEventRef { private: InputEvent event; T setter; InputModifierRef mod; public: InputEventRef() : setter(event), mod(setter) { event.ID = ++event_id; }; void instance() {} operator InputEvent() { return event; } operator InputModifierRef() { return mod; } T *operator->() { return &setter; } }; #define INPUT_MODIFIER_REF InputModifierRef #define INPUT_EVENT_REF(t) InputEventRef<t##Setter> #include "core/globals.h" #define PROJECT_SETTINGS \ Globals *project_settings = Globals::get_singleton(); #elif VERSION_MAJOR == 3 #define VIDEO_DRIVER_COUNT 2 #include "platform/x11/joypad_linux.h" #include "drivers/gles3/rasterizer_gles3.h" #define FRT_DL_SKIP #include "drivers/gles2/rasterizer_gles2.h" typedef AudioDriverManager AudioDriverManagerSW; typedef AudioDriver AudioDriverSW; #define set_mouse_pos set_mouse_position #define get_mouse_pos get_mouse_position #define get_mouse_speed get_last_mouse_speed #define has has_setting #define FRT_MOCK_GODOT_INPUT_MODIFIER_STATE #define INPUT_MODIFIER_REF Ref<InputEventWithModifiers> #define INPUT_EVENT_REF(t) Ref<t> #define joystick_linux JoypadLinux #include "core/project_settings.h" #define PROJECT_SETTINGS \ ProjectSettings *project_settings = ProjectSettings::get_singleton(); #else #error "unhandled godot version" #endif #include "frt.h" #include "bits/mouse_virtual.h" using namespace frt; namespace frt { extern const char *perfmon_filename; extern const char *extract_resource_name; } static class PerfMon { private: FILE *f; char sep; void init_separator() { char s[32]; snprintf(s, sizeof(s), "%f", 2.5); s[sizeof(s) - 1] = '\0'; sep = strchr(s, ',') ? ';' : ','; } public: PerfMon() : f(0) {} ~PerfMon() { cleanup(); } bool is_valid() { return f; } void init() { if (!perfmon_filename) return; if (!(f = fopen(perfmon_filename, "w"))) return; init_separator(); Performance *p = Performance::get_singleton(); fprintf(f, "time/ticks_ms"); for (int i = 0; i < Performance::MONITOR_MAX; i++) fprintf(f, "%c%s", sep, p->get_monitor_name(Performance::Monitor(i)).ascii().get_data()); fprintf(f, "\n"); } void iteration(uint32_t t) { if (!f) return; Performance *p = Performance::get_singleton(); fprintf(f, "%u", (unsigned int)t); for (int i = 0; i < Performance::MONITOR_MAX; i++) fprintf(f, "%c%f", sep, p->get_monitor(Performance::Monitor(i))); fprintf(f, "\n"); } void cleanup() { if (f) fclose(f); f = 0; } } perfmon; class OS_FRT : public OS_Unix, public Runnable { private: App *app; Param *disable_meta_keys_param; Param *exit_on_shiftenter_param; Env *env; Vec2 screen_size; ContextGL *context_gl; VisualServer *visual_server; VideoMode current_videomode; int current_video_driver; List<String> args; MainLoop *main_loop; #ifdef PULSEAUDIO_ENABLED AudioDriverPulseAudio driver_pulseaudio; #endif #ifdef ALSA_ENABLED AudioDriverALSA driver_alsa; #endif AudioDriverDummy driver_dummy; int audio_driver_index; Point2 mouse_pos; Point2 last_mouse_pos; bool last_mouse_pos_valid; MouseMode mouse_mode; int mouse_state; bool grab; #if VERSION_MAJOR == 2 PhysicsServer *physics_server; Physics2DServer *physics_2d_server; Rasterizer *rasterizer; AudioServerSW *audio_server; SampleManagerMallocSW *sample_manager; SpatialSoundServerSW *spatial_sound_server; SpatialSound2DServerSW *spatial_sound_2d_server; #endif int event_id; InputDefault *input; #ifdef JOYDEV_ENABLED joystick_linux *joystick; #endif MouseVirtual mouse_virtual; uint64_t last_click; public: int get_video_driver_count() const { return VIDEO_DRIVER_COUNT; } int get_current_video_driver() const { return current_video_driver; } const char *get_video_driver_name(int driver) const { if (driver == VIDEO_DRIVER_GLES3) return "GLES3"; else return "GLES2"; } OS::VideoMode get_default_video_mode() const { return OS::VideoMode(screen_size.x, screen_size.y, true, false, true); } int get_audio_driver_count() const { return AudioDriverManagerSW::get_driver_count(); } const char *get_audio_driver_name(int driver) const { AudioDriverSW *driver_ = AudioDriverManagerSW::get_driver(driver); ERR_FAIL_COND_V(!driver_, ""); return driver_->get_name(); } bool _check_internal_feature_support(const String &feature) { if (current_video_driver == VIDEO_DRIVER_GLES3 && feature == "etc2") return true; return feature == "pc" || feature == "etc"; } #if VERSION_MAJOR >= 3 String get_config_path() const { if (has_environment("XDG_CONFIG_HOME")) return get_environment("XDG_CONFIG_HOME"); if (has_environment("HOME")) return get_environment("HOME").plus_file(".config"); return "."; } String get_data_path() const { if (has_environment("XDG_DATA_HOME")) return get_environment("XDG_DATA_HOME"); if (has_environment("HOME")) return get_environment("HOME").plus_file(".local/share"); return get_config_path(); } String get_cache_path() const { if (has_environment("XDG_CACHE_HOME")) return get_environment("XDG_CACHE_HOME"); if (has_environment("HOME")) return get_environment("HOME").plus_file(".cache"); return get_config_path(); } #endif void extract_resource_fatal(const char *msg) { fatal("failed extracting resource '%s': %s.", extract_resource_name, msg); } void extract_resource_if_requested() { const char *s = extract_resource_name; if (!s) return; if (!isalnum(*s)) extract_resource_fatal("invalid name"); for (int i = 0; s[i]; i++) if (!isalnum(*s) && !strchr(".-_", *s)) extract_resource_fatal("invalid name"); String name = "res://frt/"; name += s; if (!FileAccess::exists(name)) extract_resource_fatal("not found"); FileAccess *in = FileAccess::open(name, FileAccess::READ); if (!in) extract_resource_fatal("failed opening resource"); int len = in->get_len(); uint8_t *buf = new uint8_t[len]; // memory "leak" is fine here if (!buf) extract_resource_fatal("failed allocating memory"); int n = in->get_buffer(buf, len); if (n != len) extract_resource_fatal("failed reading resource"); in->close(); FileAccess *out = FileAccess::open(s, FileAccess::WRITE); if (!out) extract_resource_fatal("failed opening output file"); out->store_buffer(buf, len); out->close(); exit(0); } void get_project_frt_params() { PROJECT_SETTINGS String name; const int n = app->get_n_of_params(); for (int i = 0; i < n; i++) { Param *p = app->get_param(i); if (p->source == Param::CommandLine) continue; name = "frt/"; name += p->name; if (!project_settings->has(name)) continue; p->source = Param::ProjectSettings; Value &v = p->value; switch (v.t) { case Value::Bool: v.u.b = bool(project_settings->get(name)); break; case Value::Int: v.u.i = int(project_settings->get(name)); break; case Value::Float: v.u.f = float(project_settings->get(name)); break; case Value::String: { String s = String(project_settings->get(name)); v.u.s = strdup(s.ascii()); // TODO: keep track and dealloc string copy } break; } } } bool disable_meta_keys() { return disable_meta_keys_param->value.u.b; } bool exit_on_shiftenter() { return exit_on_shiftenter_param->value.u.b; } #if VERSION_MAJOR == 2 void #else Error #endif initialize(const VideoMode &desired, int video_driver, int audio_driver) { get_project_frt_params(); extract_resource_if_requested(); args = OS::get_singleton()->get_cmdline_args(); current_videomode = desired; main_loop = 0; Vec2 view(current_videomode.width, current_videomode.height); int gl_version = video_driver == VIDEO_DRIVER_GLES3 ? 3 : 2; context_gl = env->video->create_the_gl_context(gl_version, view); context_gl->initialize(); #if VERSION_MAJOR == 2 rasterizer = memnew(RasterizerGLES2); visual_server = memnew(VisualServerRaster(rasterizer)); if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) visual_server = memnew(VisualServerWrapMT( visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); #else if (video_driver == VIDEO_DRIVER_GLES3) { RasterizerGLES3::register_config(); RasterizerGLES3::make_current(); current_video_driver = VIDEO_DRIVER_GLES3; } else { RasterizerGLES2::register_config(); RasterizerGLES2::make_current(); current_video_driver = VIDEO_DRIVER_GLES2; } visual_server = memnew(VisualServerRaster); #endif // TODO: Audio Module AudioDriverManagerSW::get_driver(audio_driver)->set_singleton(); audio_driver_index = audio_driver; if (AudioDriverManagerSW::get_driver(audio_driver)->init() != OK) { audio_driver_index = -1; for (int i = 0; i < AudioDriverManagerSW::get_driver_count(); i++) { if (i == audio_driver) continue; AudioDriverManagerSW::get_driver(i)->set_singleton(); if (AudioDriverManagerSW::get_driver(i)->init() == OK) { audio_driver_index = i; break; } } } #if VERSION_MAJOR == 2 sample_manager = memnew(SampleManagerMallocSW); audio_server = memnew(AudioServerSW(sample_manager)); audio_server->init(); spatial_sound_server = memnew(SpatialSoundServerSW); spatial_sound_server->init(); spatial_sound_2d_server = memnew(SpatialSound2DServerSW); spatial_sound_2d_server->init(); ERR_FAIL_COND(!visual_server); #else if (!visual_server) return FAILED; #endif visual_server->init(); #if VERSION_MAJOR == 2 physics_server = memnew(PhysicsServerSW); physics_server->init(); physics_2d_server = memnew(Physics2DServerSW); physics_2d_server->init(); #endif input = memnew(InputDefault); #ifdef JOYDEV_ENABLED joystick = memnew(joystick_linux(input)); #endif last_click = 0; #if VERSION_MAJOR == 2 _ensure_data_dir(); #else #if VERSION_MINOR < 3 _ensure_user_data_dir(); #endif return OK; #endif } void finalize() { if (main_loop) memdelete(main_loop); main_loop = NULL; #if VERSION_MAJOR == 2 spatial_sound_server->finish(); memdelete(spatial_sound_server); spatial_sound_2d_server->finish(); memdelete(spatial_sound_2d_server); memdelete(sample_manager); audio_server->finish(); memdelete(audio_server); visual_server->finish(); #else // VERSION_MAJOR == 3 for (int i = 0; i < get_audio_driver_count(); i++) AudioDriverManager::get_driver(i)->finish(); #endif memdelete(visual_server); #if VERSION_MAJOR == 2 memdelete(rasterizer); physics_server->finish(); memdelete(physics_server); physics_2d_server->finish(); memdelete(physics_2d_server); #endif #ifdef JOYDEV_ENABLED memdelete(joystick); #endif memdelete(input); args.clear(); } void set_mouse_show(bool show) {} void set_mouse_grab(bool grab) { this->grab = grab; } bool is_mouse_grab_enabled() const { return grab; } int get_mouse_button_state() const { return mouse_state; } Point2 get_mouse_pos() const { return mouse_pos; } void set_mouse_mode(MouseMode mode) { mouse_mode = mode; } OS::MouseMode get_mouse_mode() const { return mouse_mode; } void set_window_title(const String &title) { env->video->set_title(title.utf8().get_data()); } void set_video_mode(const VideoMode &video_mode, int screen) {} OS::VideoMode get_video_mode(int screen) const { return current_videomode; } Size2 get_window_size() const { return Vector2(current_videomode.width, current_videomode.height); } void get_fullscreen_mode_list(List<VideoMode> *list, int screen) const {} MainLoop *get_main_loop() const { return main_loop; } void delete_main_loop() { if (main_loop) memdelete(main_loop); main_loop = 0; } void set_main_loop(MainLoop *main_loop) { this->main_loop = main_loop; input->set_main_loop(main_loop); } bool can_draw() const { return true; }; String get_name() #if (VERSION_MAJOR == 3) && (VERSION_MINOR >= 2) const #endif { return "FRT"; } void move_window_to_foreground() {} void set_cursor_shape(CursorShape shape) {} void set_custom_mouse_cursor(const RES&, OS::CursorShape, const Vector2&) {} void release_rendering_thread() { context_gl->release_current(); } void make_rendering_thread() { context_gl->make_current(); } void swap_buffers() { context_gl->swap_buffers(); } uint32_t unicode_fallback(int gd_code, bool pressed, const InputModifierState &st) { if (st.alt || st.control || st.meta || !pressed) return 0; if (gd_code >= 'A' && gd_code <= 'Z') return st.shift ? gd_code : gd_code + ('a' - 'A'); if (gd_code >= ' ' && gd_code <= '~') return gd_code; return 0; } void get_key_modifier_state(INPUT_MODIFIER_REF mod, InputModifierState *st = 0) { InputModifierState state; if (env->keyboard) { env->keyboard->get_modifier_state(state); } else { state.shift = false; state.control = false; state.alt = false; state.meta = false; } mod->set_shift(state.shift); mod->set_control(state.control); mod->set_alt(state.alt); mod->set_metakey(state.meta); if (st) *st = state; } void process_keyboard_event(int key, bool pressed, uint32_t unicode, bool echo) { INPUT_EVENT_REF(InputEventKey) k; k.instance(); InputModifierState st; get_key_modifier_state(k, &st); k->set_pressed(pressed); k->set_scancode(key); if (unicode) k->set_unicode(unicode); else k->set_unicode(unicode_fallback(key, pressed, st)); k->set_echo(echo); input->parse_input_event(k); } void process_mouse_motion(int x, int y) { mouse_pos.x = x; mouse_pos.y = y; if (!last_mouse_pos_valid) { last_mouse_pos = mouse_pos; last_mouse_pos_valid = true; } Vector2 rel = mouse_pos - last_mouse_pos; last_mouse_pos = mouse_pos; INPUT_EVENT_REF(InputEventMouseMotion) mm; mm.instance(); get_key_modifier_state(mm); mm->set_button_mask(mouse_state); mm->set_position(mouse_pos); mm->set_global_position(mouse_pos); mm->set_speed(input->get_mouse_speed()); mm->set_relative(rel); input->set_mouse_pos(mouse_pos); input->parse_input_event(mm); } void process_mouse_button(int index, bool pressed) { int bit = (1 << (index - 1)); if (pressed) mouse_state |= bit; else mouse_state &= ~bit; INPUT_EVENT_REF(InputEventMouseButton) mb; mb.instance(); get_key_modifier_state(mb); mb->set_button_mask(mouse_state); mb->set_position(mouse_pos); mb->set_global_position(mouse_pos); mb->set_button_index(index); mb->set_pressed(pressed); if (index == 1 && pressed) { const uint64_t t = get_ticks_usec(); const uint64_t dt = t - last_click; if (dt < 300000) { last_click = 0; mb->set_doubleclick(true); } else { last_click = t; } } input->parse_input_event(mb); } struct KeyboardHandler : Keyboard::Handler { OS_FRT *instance; Keyboard *keyboard; void handle_keyboard_key(int gd_code, bool pressed, uint32_t unicode, bool echo) { if (!instance->disable_meta_keys()) { InputModifierState st; keyboard->get_modifier_state(st); if (st.meta && instance->handle_meta(gd_code, pressed)) return; } if (instance->exit_on_shiftenter()) { InputModifierState st; keyboard->get_modifier_state(st); if (st.shift && pressed && (gd_code == GD_KEY_RETURN || gd_code == GD_KEY_ENTER)) App::instance()->quit(); } instance->process_keyboard_event(gd_code, pressed, unicode, echo); } } keyboard_handler; struct MouseHandler : Mouse::Handler { OS_FRT *instance; Video *video; void handle_mouse_button(Mouse::Button button, bool pressed) { int index; switch (button) { case Mouse::Left: index = 1; break; case Mouse::Middle: index = 3; break; case Mouse::Right: index = 2; break; case Mouse::WheelUp: index = BUTTON_WHEEL_UP; break; case Mouse::WheelDown: index = BUTTON_WHEEL_DOWN; break; default: return; } instance->process_mouse_button(index, pressed); } void handle_mouse_motion(Vec2 pos) { Vec2 view = video->move_pointer(pos); instance->process_mouse_motion(view.x, view.y); } } mouse_handler; bool dispatch_handle_meta(int gd_code, bool pressed) { // keep it simple: hard-coded order should be fine if (env->mouse && env->mouse->handle_meta(gd_code, pressed)) return true; if (env->keyboard && env->keyboard->handle_meta(gd_code, pressed)) return true; if (env->video && env->video->handle_meta(gd_code, pressed)) return true; return false; } void run() { if (!main_loop) return; disable_meta_keys_param = app->get_param("disable_meta_keys"); exit_on_shiftenter_param = app->get_param("exit_on_shiftenter"); keyboard_handler.instance = this; keyboard_handler.keyboard = env->keyboard; mouse_handler.instance = this; mouse_handler.video = env->video; if (env->keyboard && !env->mouse) { mouse_virtual.probe(); env->mouse = &mouse_virtual; } if (env->mouse) { env->mouse->set_size(screen_size); Vec2 pos = env->mouse->get_pos(); env->video->move_pointer(pos); } // mouse set_handler first to increase the chances of RETURN release if (env->mouse) { env->mouse->set_handler(&mouse_handler); } if (env->keyboard) { env->keyboard->set_handler(&keyboard_handler); } main_loop->init(); perfmon.init(); while (app->is_running()) { app->dispatch_events(); #ifdef JOYDEV_ENABLED #if VERSION_MAJOR == 2 event_id = joystick->process_joysticks(event_id); #else joystick->process_joypads(); #endif #endif if (Main::iteration() == true) break; if (perfmon.is_valid()) perfmon.iteration(get_ticks_msec()); }; perfmon.cleanup(); main_loop->finish(); } bool is_joy_known(int p_device) { return input->is_joy_mapped(p_device); } String get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } OS_FRT() { current_video_driver = VIDEO_DRIVER_GLES2; #ifdef PULSEAUDIO_ENABLED AudioDriverManagerSW::add_driver(&driver_pulseaudio); #endif #ifdef ALSA_ENABLED AudioDriverManagerSW::add_driver(&driver_alsa); #endif if (AudioDriverManagerSW::get_driver_count() == 0) AudioDriverManagerSW::add_driver(&driver_dummy); mouse_mode = MOUSE_MODE_VISIBLE; mouse_state = 0; grab = false; }; // Module const char *get_id() const { return "frt_os_unix"; } bool probe() { return true; } void cleanup() {} bool handle_meta(int gd_code, bool pressed) { switch (gd_code) { case 'Q': if (env->video->provides_quit()) return false; else app->quit(); break; default: return dispatch_handle_meta(gd_code, pressed); } return true; } // Runnable void setup_env(Env *env) { app = App::instance(); this->env = env; if (!env->video) fatal("no video module available."); screen_size = env->video->get_screen_size(); } void run_() { run(); } int get_exit_code_() { return get_exit_code(); } }; FRT_REGISTER(OS_FRT)
23,939
9,754
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // DO NOT EDIT! This file was generated by CustomTasks.DependencyPropertyCodeGen #include "pch.h" #include "common.h" #include "ToggleSplitButton.h" CppWinRTActivatableClassWithDPFactory(ToggleSplitButton) GlobalDependencyProperty ToggleSplitButtonProperties::s_IsCheckedProperty{ nullptr }; ToggleSplitButtonProperties::ToggleSplitButtonProperties() : m_isCheckedChangedEventSource{static_cast<ToggleSplitButton*>(this)} { EnsureProperties(); } void ToggleSplitButtonProperties::EnsureProperties() { SplitButton::EnsureProperties(); if (!s_IsCheckedProperty) { s_IsCheckedProperty = InitializeDependencyProperty( L"IsChecked", winrt::name_of<bool>(), winrt::name_of<winrt::ToggleSplitButton>(), false /* isAttached */, ValueHelper<bool>::BoxedDefaultValue(), winrt::PropertyChangedCallback(&OnPropertyChanged)); } } void ToggleSplitButtonProperties::ClearProperties() { s_IsCheckedProperty = nullptr; SplitButton::ClearProperties(); } void ToggleSplitButtonProperties::OnPropertyChanged( winrt::DependencyObject const& sender, winrt::DependencyPropertyChangedEventArgs const& args) { auto owner = sender.as<winrt::ToggleSplitButton>(); winrt::get_self<ToggleSplitButton>(owner)->OnPropertyChanged(args); } void ToggleSplitButtonProperties::IsChecked(bool value) { static_cast<ToggleSplitButton*>(this)->SetValue(s_IsCheckedProperty, ValueHelper<bool>::BoxValueIfNecessary(value)); } bool ToggleSplitButtonProperties::IsChecked() { return ValueHelper<bool>::CastOrUnbox(static_cast<ToggleSplitButton*>(this)->GetValue(s_IsCheckedProperty)); } winrt::event_token ToggleSplitButtonProperties::IsCheckedChanged(winrt::TypedEventHandler<winrt::ToggleSplitButton, winrt::ToggleSplitButtonIsCheckedChangedEventArgs> const& value) { return m_isCheckedChangedEventSource.add(value); } void ToggleSplitButtonProperties::IsCheckedChanged(winrt::event_token const& token) { m_isCheckedChangedEventSource.remove(token); }
2,321
643
// Copyright (C) 2017, Christopher N. Hume. All rights reserved. // // 2017-07-04 CNHume Created LCSRecord subclass // 2015-01-23 CNHume Created file // #include "LCSRecord.h" // // Delta formatter // uint32_t LCSRecord::Show(shared_ptr<Delta> deltas, const RECORDS& r1, const RECORDS& r2, const string& label1, const string& label2) { uint32_t ndelta = 0; // # of deltas for (auto next = deltas; next != nullptr; next = dynamic_pointer_cast<Delta>(next->next)) { Series(ndelta, label1, r1, next->begin1, next->end1, label2, r2, next->begin2, next->end2); ndelta++; } return ndelta; } // Write both sides of a Delta in series void LCSRecord::Series(uint32_t counter, const string& label1, const RECORDS& r1, uint32_t begin1, uint32_t end1, const string& label2, const RECORDS& r2, uint32_t begin2, uint32_t end2) { Side("<<<<<", counter, label1, r1, begin1, end1); Side(">>>>>", counter, label2, r2, begin2, end2); } void LCSRecord::Side(string emblem, uint32_t counter, const string& label, const RECORDS& list, uint32_t begin, uint32_t end) { Head(emblem, counter, label, begin, end); Body(list, begin, end); } void LCSRecord::Head(string emblem, uint32_t counter, const string& label, uint32_t begin, uint32_t end) { if (begin < end) { cout << emblem << " " << counter + 1 << " " << label << " [" << begin << ":" << end << "] " << emblem << endl; } } void LCSRecord::Body(const RECORDS& records, uint32_t begin, uint32_t end) { for (auto index = begin; index < end; index++) cout << records[index] << endl; }
1,613
640
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usdSkel/skinningQuery.h" #include "pxr/usd/usd/attribute.h" #include "pxr/usd/usd/prim.h" #include "pxr/usd/usd/relationship.h" #include "pxr/usd/usdGeom/boundable.h" #include "pxr/usd/usdGeom/primvar.h" #include "pxr/usd/usdSkel/utils.h" PXR_NAMESPACE_OPEN_SCOPE UsdSkelSkinningQuery::UsdSkelSkinningQuery() : _valid(false), _numInfluencesPerComponent(1), _interpolation(UsdGeomTokens->constant) {} UsdSkelSkinningQuery::UsdSkelSkinningQuery( const UsdPrim& prim, const VtTokenArray& skelJointOrder, const UsdAttribute& jointIndices, const UsdAttribute& jointWeights, const UsdAttribute& geomBindTransform, const UsdAttribute& joints) : _prim(prim), _valid(false), _numInfluencesPerComponent(1), _interpolation(UsdGeomTokens->constant), _jointIndicesPrimvar(jointIndices), _jointWeightsPrimvar(jointWeights), _geomBindTransformAttr(geomBindTransform) { VtTokenArray jointOrder; if (joints && joints.Get(&jointOrder)) { _jointOrder = jointOrder; _mapper = std::make_shared<UsdSkelAnimMapper>(skelJointOrder, jointOrder); } if(!jointIndices) { TF_WARN("'jointIndices' is invalid."); return; } if(!jointWeights) { TF_WARN("jointWeights' is invalid."); return; } // Validate joint influences. int indicesElementSize = _jointIndicesPrimvar.GetElementSize(); int weightsElementSize = _jointWeightsPrimvar.GetElementSize(); if(indicesElementSize != weightsElementSize) { TF_WARN("JointIndices element size (%d) != " "jointWeights element size (%d).", indicesElementSize, weightsElementSize); return; } if(indicesElementSize <= 0) { TF_WARN("Invalid element size [%d]: element size must " "be greater than zero.", indicesElementSize); return; } TfToken indicesInterpolation = _jointIndicesPrimvar.GetInterpolation(); TfToken weightsInterpolation = _jointWeightsPrimvar.GetInterpolation(); if(indicesInterpolation != weightsInterpolation) { TF_WARN("JointIndices interpolation (%s) != " "jointWeights interpolation (%s).", indicesInterpolation.GetText(), weightsInterpolation.GetText()); return; } if(indicesInterpolation != UsdGeomTokens->constant && indicesInterpolation != UsdGeomTokens->vertex) { TF_WARN("Invalid interpolation (%s) for joint influences: " "interpolation must be either 'constant' or 'vertex'.", indicesInterpolation.GetText()); return; } // Valid joint influences, to the extent that we can validate here. // Any further validation of joint influences requires the actual // indices/weights to be read in, which we won't do here. _numInfluencesPerComponent = indicesElementSize; _interpolation = indicesInterpolation; _valid = true; } bool UsdSkelSkinningQuery::IsRigidlyDeformed() const { return _interpolation == UsdGeomTokens->constant; } bool UsdSkelSkinningQuery::GetJointOrder(VtTokenArray* jointOrder) const { if(jointOrder) { if(_jointOrder) { *jointOrder = *_jointOrder; } return true; } else { TF_CODING_ERROR("'jointOrder' pointer is null."); return false; } } bool UsdSkelSkinningQuery::GetTimeSamples(std::vector<double>* times) const { return GetTimeSamplesInInterval(GfInterval::GetFullInterval(), times); } bool UsdSkelSkinningQuery::GetTimeSamplesInInterval(const GfInterval& interval, std::vector<double>* times) const { if(!times) { TF_CODING_ERROR("'times' pointer is null."); return false; } // TODO: Use Usd_MergeTimeSamples if it becomes public. std::vector<double> tmpTimes; for(const auto& pv : {_jointIndicesPrimvar, _jointWeightsPrimvar}) { if(pv.GetTimeSamplesInInterval(interval, &tmpTimes)) { times->insert(times->end(), tmpTimes.begin(), tmpTimes.end()); } } if(_geomBindTransformAttr.GetTimeSamplesInInterval(interval, &tmpTimes)) { times->insert(times->end(), tmpTimes.begin(), tmpTimes.end()); } std::sort(times->begin(), times->end()); times->erase(std::unique(times->begin(), times->end()), times->end()); return true; } bool UsdSkelSkinningQuery::ComputeJointInfluences(VtIntArray* indices, VtFloatArray* weights, UsdTimeCode time) const { TRACE_FUNCTION(); if(!TF_VERIFY(IsValid(), "invalid skinning query") || !TF_VERIFY(_jointIndicesPrimvar) || !TF_VERIFY(_jointWeightsPrimvar)) { return false; } if(_jointIndicesPrimvar.ComputeFlattened(indices, time) && _jointWeightsPrimvar.ComputeFlattened(weights, time)) { if(indices->size() != weights->size()) { TF_WARN("Size of jointIndices [%zu] != size of " "jointWeights [%zu].", indices->size(), weights->size()); return false; } if(!TF_VERIFY(_numInfluencesPerComponent > 0)) { return false; } if(indices->size()%_numInfluencesPerComponent != 0) { TF_WARN("unexpected size of jointIndices and jointWeights " "arrays [%zu]: size must be a multiple of the number of " "influences per component (%d).", indices->size(), _numInfluencesPerComponent); return false; } if(IsRigidlyDeformed() && indices->size() != static_cast<size_t>(_numInfluencesPerComponent)) { TF_WARN("Unexpected size of jointIndices and jointWeights " "arrays [%zu]: joint influences are defined with 'constant'" " interpolation, so the array size must be equal to the " "element size (%d).", indices->size(), _numInfluencesPerComponent); return false; } return true; } return false; } bool UsdSkelSkinningQuery::ComputeVaryingJointInfluences(size_t numPoints, VtIntArray* indices, VtFloatArray* weights, UsdTimeCode time) const { TRACE_FUNCTION(); if(ComputeJointInfluences(indices, weights, time)) { if(IsRigidlyDeformed()) { if(!UsdSkelExpandConstantInfluencesToVarying(indices, numPoints) || !UsdSkelExpandConstantInfluencesToVarying(weights, numPoints)) { return false; } if(!TF_VERIFY(indices->size() == weights->size())) return false; } else if(indices->size() != numPoints*_numInfluencesPerComponent) { TF_WARN("Unexpected size of jointIndices and jointWeights " "arrays [%zu]: varying influences should be sized to " "numPoints [%zu] * numInfluencesPerComponent [%d].", indices->size(), numPoints, _numInfluencesPerComponent); return false; } return true; } return false; } bool UsdSkelSkinningQuery::ComputeSkinnedPoints(const VtMatrix4dArray& xforms, VtVec3fArray* points, UsdTimeCode time) const { TRACE_FUNCTION(); if(!points) { TF_CODING_ERROR("'points' pointer is null."); return false; } VtIntArray jointIndices; VtFloatArray jointWeights; if(ComputeVaryingJointInfluences(points->size(), &jointIndices, &jointWeights, time)) { // If the binding site has a custom joint ordering, the query will have // a mapper that should be used to reorder transforms // (skel order -> binding order) VtMatrix4dArray orderedXforms(xforms); if(_mapper) { if(!_mapper->Remap(xforms, &orderedXforms)) { return false; } } GfMatrix4d geomBindXform = GetGeomBindTransform(time); return UsdSkelSkinPointsLBS(geomBindXform, orderedXforms, jointIndices, jointWeights, _numInfluencesPerComponent, points); } return false; } bool UsdSkelSkinningQuery::ComputeSkinnedTransform(const VtMatrix4dArray& xforms, GfMatrix4d* xform, UsdTimeCode time) const { TRACE_FUNCTION(); if(!xform) { TF_CODING_ERROR("'xform' pointer is null."); return false; } if(!IsRigidlyDeformed()) { TF_CODING_ERROR("Attempted to skin a transform, but " "joint influences are not constant."); return false; } VtIntArray jointIndices; VtFloatArray jointWeights; if(ComputeJointInfluences(&jointIndices, &jointWeights, time)) { // If the binding site has a custom joint ordering, the query will have // a mapper that should be used to reorder transforms // (skel order -> binding order) VtMatrix4dArray orderedXforms(xforms); if(_mapper) { if(!_mapper->Remap(xforms, &orderedXforms)) { return false; } } GfMatrix4d geomBindXform = GetGeomBindTransform(time); return UsdSkelSkinTransformLBS(geomBindXform, orderedXforms, jointIndices, jointWeights, xform); } return false; } USDSKEL_API float UsdSkelSkinningQuery::ComputeExtentsPadding( const VtMatrix4dArray& skelRestXforms, const UsdGeomBoundable& boundable) const { // Don't use default time; properties may be keyed (and still unvarying) // We do, however, expect the computed quantity to not be time varying. UsdTimeCode time = UsdTimeCode::EarliestTime(); VtVec3fArray boundableExtent; if(boundable && boundable.GetExtentAttr().Get(&boundableExtent, time) && boundableExtent.size() == 2) { VtVec3fArray jointsExtent; if(UsdSkelComputeJointsExtent(skelRestXforms, &jointsExtent)) { GfRange3d range = GfBBox3d(GfRange3d(boundableExtent[0], boundableExtent[1]), GetGeomBindTransform(time)).ComputeAlignedRange(); GfVec3f minDiff = jointsExtent[0] - GfVec3f(range.GetMin()); GfVec3f maxDiff = GfVec3f(range.GetMax()) - jointsExtent[1]; float padding = 0.0f; for(int i = 0; i < 3; ++i) { padding = std::max(padding, minDiff[i]); padding = std::max(padding, maxDiff[i]); } return padding; } } return 0.0f; } GfMatrix4d UsdSkelSkinningQuery::GetGeomBindTransform(UsdTimeCode time) const { // Geom bind transform attr is optional. GfMatrix4d xform; if(!_geomBindTransformAttr || !_geomBindTransformAttr.Get(&xform, time)) { xform.SetIdentity(); } return xform; } std::string UsdSkelSkinningQuery::GetDescription() const { if(IsValid()) { return TfStringPrintf("UsdSkelSkinningQuery <%s>", _prim.GetPath().GetText()); } return "invalid UsdSkelSkinningQuery"; } PXR_NAMESPACE_CLOSE_SCOPE
12,720
3,893
/*=================================================================== 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 "mitkVolumeMapperVtkSmart3D.h" #include "mitkTransferFunctionProperty.h" #include "mitkTransferFunctionInitializer.h" #include "mitkLevelWindowProperty.h" #include <mitkImageVtkAccessor.h> #include <vtkObjectFactory.h> #include <vtkRenderingOpenGL2ObjectFactory.h> #include <vtkRenderingVolumeOpenGL2ObjectFactory.h> #include <vtkColorTransferFunction.h> #include <vtkPiecewiseFunction.h> void mitk::VolumeMapperVtkSmart3D::initialize() { mitk::Image *input = const_cast<mitk::Image *>(static_cast<const mitk::Image *>(this->GetDataNode()->GetData())); int displayedComponent = 0; this->GetDataNode()->GetIntProperty("Image.Displayed Component", displayedComponent); int numberOfComponents = input->GetPixelType().GetNumberOfComponents(); int timeStep = 0; this->GetDataNode()->GetIntProperty("Image.Displayed Timestep", timeStep); int numberOfTimeSteps = input->GetTimeSteps(); if (!m_Volume->GetMapper() || (numberOfTimeSteps > 1 && timeStep != m_LastTimeStep) || (numberOfComponents > 1 && displayedComponent != m_LastComponent)) { createMapper(GetInputImage()); createVolume(); createVolumeProperty(); } } void mitk::VolumeMapperVtkSmart3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { initialize(); bool value; this->GetDataNode()->GetBoolProperty("volumerendering", value, renderer); if (!value) { m_Volume->VisibilityOff(); return; } else { m_Volume->VisibilityOn(); } UpdateTransferFunctions(renderer); UpdateRenderMode(renderer); this->Modified(); } vtkProp* mitk::VolumeMapperVtkSmart3D::GetVtkProp(mitk::BaseRenderer *renderer) { initialize(); return m_Volume; } void mitk::VolumeMapperVtkSmart3D::ApplyProperties(vtkActor *actor, mitk::BaseRenderer *renderer) { } void mitk::VolumeMapperVtkSmart3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { // GPU_INFO << "SetDefaultProperties"; node->AddProperty("volumerendering", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.usemip", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.cpu.ambient", mitk::FloatProperty::New(0.10f), renderer, overwrite); node->AddProperty("volumerendering.cpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.cpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.cpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); node->AddProperty("volumerendering.usegpu", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.useray", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.gpu.ambient", mitk::FloatProperty::New(0.25f), renderer, overwrite); node->AddProperty("volumerendering.gpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.gpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.gpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); node->AddProperty("binary", mitk::BoolProperty::New(false), renderer, overwrite); mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(node->GetData()); if (image.IsNotNull() && image->IsInitialized()) { if ((overwrite) || (node->GetProperty("levelwindow", renderer) == nullptr)) { mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; levelwindow.SetAuto(image); levWinProp->SetLevelWindow(levelwindow); node->SetProperty("levelwindow", levWinProp, renderer); } if ((overwrite) || (node->GetProperty("TransferFunction", renderer) == nullptr)) { // add a default transfer function mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(tf); tfInit->SetTransferFunctionMode(0); node->SetProperty("TransferFunction", mitk::TransferFunctionProperty::New(tf.GetPointer())); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::VolumeMapperVtkSmart3D::setClippingPlanes(vtkPlanes* planes) { initialize(); m_SmartVolumeMapper->SetClippingPlanes(planes); } vtkImageData* mitk::VolumeMapperVtkSmart3D::GetInputImage() { mitk::Image *input = const_cast<mitk::Image *>(static_cast<const mitk::Image *>(this->GetDataNode()->GetData())); mitk::ImageVtkAccessor accessor(input); vtkImageData* img = accessor.getVtkImageData(this->GetTimestep()); m_LastTimeStep = this->GetTimestep(); if (input->GetPixelType().GetNumberOfComponents() > 1) { int displayedComponent = 0; this->GetDataNode()->GetIntProperty("Image.Displayed Component", displayedComponent); m_VectorComponentExtractor->SetComponents(displayedComponent); m_VectorComponentExtractor->SetInputData(img); m_VectorComponentExtractor->Modified(); m_VectorComponentExtractor->Update(); img = m_VectorComponentExtractor->GetOutput(); m_LastComponent = displayedComponent; } if (img) { img->SetSpacing(1,1,1); } return img; } void mitk::VolumeMapperVtkSmart3D::createMapper(vtkImageData* imageData) { m_SmartVolumeMapper = vtkSmartPointer<vtkSmartVolumeMapper>::New(); m_SmartVolumeMapper->SetBlendModeToComposite(); m_SmartVolumeMapper->SetInputData(imageData); } void mitk::VolumeMapperVtkSmart3D::createVolume() { m_Volume->VisibilityOff(); m_Volume->SetMapper(m_SmartVolumeMapper); m_Volume->SetProperty(m_VolumeProperty); } void mitk::VolumeMapperVtkSmart3D::createVolumeProperty() { m_VolumeProperty->ShadeOn(); m_VolumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION); } void mitk::VolumeMapperVtkSmart3D::UpdateTransferFunctions(mitk::BaseRenderer *renderer) { vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction; vtkSmartPointer<vtkPiecewiseFunction> gradientTransferFunction; vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction; bool isBinary = false; this->GetDataNode()->GetBoolProperty("binary", isBinary, renderer); if (isBinary) { colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); float rgb[3]; if (!GetDataNode()->GetColor(rgb, renderer)) rgb[0] = rgb[1] = rgb[2] = 1; colorTransferFunction->AddRGBPoint(0, rgb[0], rgb[1], rgb[2]); colorTransferFunction->Modified(); opacityTransferFunction = m_BinaryOpacityTransferFunction; gradientTransferFunction = m_BinaryGradientTransferFunction; } else { mitk::TransferFunctionProperty *transferFunctionProp = dynamic_cast<mitk::TransferFunctionProperty *>(this->GetDataNode()->GetProperty("TransferFunction", renderer)); if (transferFunctionProp) { opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction(); gradientTransferFunction = transferFunctionProp->GetValue()->GetGradientOpacityFunction(); colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction(); } else { opacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); gradientTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New(); } } m_VolumeProperty->SetColor(colorTransferFunction); m_VolumeProperty->SetScalarOpacity(opacityTransferFunction); m_VolumeProperty->SetGradientOpacity(gradientTransferFunction); } void mitk::VolumeMapperVtkSmart3D::UpdateRenderMode(mitk::BaseRenderer *renderer) { bool usegpu = false; bool useray = false; bool usemip = false; this->GetDataNode()->GetBoolProperty("volumerendering.usegpu", usegpu); this->GetDataNode()->GetBoolProperty("volumerendering.useray", useray); this->GetDataNode()->GetBoolProperty("volumerendering.usemip", usemip); if (usegpu) m_SmartVolumeMapper->SetRequestedRenderModeToGPU(); else if (useray) m_SmartVolumeMapper->SetRequestedRenderModeToRayCast(); else m_SmartVolumeMapper->SetRequestedRenderModeToDefault(); int blendMode; if (this->GetDataNode()->GetIntProperty("volumerendering.blendmode", blendMode)) m_SmartVolumeMapper->SetBlendMode(blendMode); else if (usemip) m_SmartVolumeMapper->SetBlendMode(vtkSmartVolumeMapper::MAXIMUM_INTENSITY_BLEND); // shading parameter if (m_SmartVolumeMapper->GetRequestedRenderMode() == vtkSmartVolumeMapper::GPURenderMode) { float value = 0; if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.ambient", value, renderer)) m_VolumeProperty->SetAmbient(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.diffuse", value, renderer)) m_VolumeProperty->SetDiffuse(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.specular", value, renderer)) m_VolumeProperty->SetSpecular(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.specular.power", value, renderer)) m_VolumeProperty->SetSpecularPower(value); } else { float value = 0; if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.ambient", value, renderer)) m_VolumeProperty->SetAmbient(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.diffuse", value, renderer)) m_VolumeProperty->SetDiffuse(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.specular", value, renderer)) m_VolumeProperty->SetSpecular(value); if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.specular.power", value, renderer)) m_VolumeProperty->SetSpecularPower(value); } } mitk::VolumeMapperVtkSmart3D::VolumeMapperVtkSmart3D() : m_VectorComponentExtractor(vtkSmartPointer<vtkImageExtractComponents>::New()), m_LastTimeStep(-1), m_LastComponent(-1) { vtkObjectFactory::RegisterFactory(vtkRenderingOpenGL2ObjectFactory::New()); vtkObjectFactory::RegisterFactory(vtkRenderingVolumeOpenGL2ObjectFactory::New()); m_VolumeProperty = vtkSmartPointer<vtkVolumeProperty>::New(); m_Volume = vtkSmartPointer<vtkVolume>::New(); m_BinaryOpacityTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); m_BinaryOpacityTransferFunction->AddPoint(0, 0.0); m_BinaryOpacityTransferFunction->AddPoint(1, 1.0); m_BinaryGradientTransferFunction = vtkSmartPointer<vtkPiecewiseFunction>::New(); m_BinaryGradientTransferFunction->AddPoint(0.0, 1.0); } mitk::VolumeMapperVtkSmart3D::~VolumeMapperVtkSmart3D() { }
11,229
3,648
///////////////// // OS Includes #include <memory.h> #include <stdlib.h> ////////////// // Includes #include "Clause.h" #include "Random.h" #include "SATInstance.h" #include "SATSolver.h" #include "VariableList.h" ///////////////////////////// // Static Data Initialization ///////////// // Defines ////////////////////////////////////////////////////////////////////////////////////////////////// // Public Methods SATSolver::SATSolver(SATInstance* pSATInstance_, ostream& xOutputStream_) : xOutputStream(xOutputStream_), _pPrimaryVariables(0) { _pInstance = pSATInstance_; _aAssignment = 0; // Set intelligent defaults for runtime parameters: _bFindAll = 1; // default to finding one solution _iMaxSolutions = 1; _fFudgeFactor = .9; _iLearnOrder = 3; _bNoTimeLimit = 0; _iMaxTime = 43200; // 12 hours _bFavorSmallClauses = 1; _bRelevanceBounding = 1; _bPrintStack = 1; _iPrintStackPeriod = 10; _bRestarts = 0; _iRestartIncrement = 0; } SATSolver::~SATSolver() { _xLearnedClauses.vDestroy(); delete _pPrimaryVariables; } relsat_enum SATSolver::eSolve() { time(&_iElapsedTime); _iLastCheckTime = _iElapsedTime; relsat_enum eReturn; _iBranchSelections = _iVariablesLabeled = _iContradictions = 0; if (!_bInitialize()) { eReturn = UNSAT; } else { // Here we do an initial unit propagation to handle base unit clauses. if (_bUnitPropagate()) { eReturn = UNSAT; } else { boolean bFailed_; boolean bReturn; if (_bRestarts) { bReturn = _bRestartLoop(bFailed_); } else { bReturn = _bLoop(bFailed_); } if (bFailed_) { eReturn = TIMEOUT; xOutputStream << "c Timeout." << endl; } else if (bReturn == 1) { eReturn = SAT; } else { eReturn = UNSAT; } } } _vCleanup(); time_t iEnd; time(&iEnd); _iElapsedTime = iEnd - _iElapsedTime; return eReturn; } void SATSolver::vSetPrintStackPeriod(long int iSeconds_) { _iPrintStackPeriod = iSeconds_; _bPrintStack = 1; } void SATSolver::vSetRestartInterval(int iSeconds_) { _iRestartInterval = iSeconds_; _bRestarts = 1; } void SATSolver::vSetRestartIncrement(int iSeconds_) { _iRestartIncrement = iSeconds_; } void SATSolver::vOutputStatusUpdateInterval() { if (_bPrintStack) { xOutputStream << "c Status update interval: " << _iPrintStackPeriod << " seconds." << endl; } } void SATSolver::vOutputWarnings() { xOutputStream << "c Learn order: " << _iLearnOrder << endl; xOutputStream << "c Fudge factor: " << _fFudgeFactor << endl; if (!_bNoTimeLimit) { xOutputStream << "c Solution phase timeout after: " << _iMaxTime << " seconds." << endl; } if (_bRestarts) { xOutputStream << "c Restart interval: " << _iRestartInterval << " seconds." << endl; if (_iRestartIncrement) { xOutputStream << "c Restart interval increment: " << _iRestartIncrement << " seconds." << endl; } if (!_bFindAll) { xOutputStream << "c WARNING: Restarts override model counting. Searching for first solution only." << endl; _bFindAll = 1; _iMaxSolutions = 1; } else { if (_iMaxSolutions == 0) { xOutputStream << "c WARNING: Find all solutions not a valid option when using restarts.\n" << "c Searching for first solution only." << endl; _iMaxSolutions = 1; } } xOutputStream << "c Finding up to " << _iMaxSolutions << " solutions with restarts." << endl; if (_iMaxSolutions > 1) { xOutputStream <<"c WARNING: With restarts, some solutions may be duplicates." << endl; } } else { if (!_bFindAll) { xOutputStream << "c Counting solutions (will output first solution if one exists)..." << endl; #ifdef NO_GMP xOutputStream << "c WARNING: Not using a bignum package. Solution counts may overflow." << endl; #endif } else { if (_iMaxSolutions == 0) { xOutputStream << "c Finding all solutions..." << endl; } else { xOutputStream << "c Finding up to " << _iMaxSolutions << " solutions..." << endl; } } } } ////////////////////////////////////////////////////////////////////////////////////////////////// // Protected Methods ////////////////////////////////////////////////////////////////////////////////////////////////// // Private Methods boolean SATSolver::_bLoop(boolean& bFailed_) { bFailed_ = 0; boolean bReturnValue = 0; while (1) { if (_bTimeLimitExpired()) { bFailed_ = 1; return bReturnValue; } if (_bPrintStackCheck()) { _vPrintStack(); } VariableID eBestID; boolean bZeroFirst; if (_pPrimaryVariables) { eBestID = _eGiveMeTheBest(bZeroFirst, true); } else { eBestID = _eGiveMeTheBest(bZeroFirst, false); } if (eBestID == -1) { bReturnValue = 1; if (_iCurrentVariable == _iVariableCount) { if (_bOutputSolution()) { xOutputStream << "c Solution limit reached. " << endl; return bReturnValue; } } if (_bSpecialBackup()) { xOutputStream << "c All solutions found." << endl; return bReturnValue; } } else { _aVariableStruct[eBestID].bBranch = 1; if (bZeroFirst) { _pUnitVariables0->vAddVariableNoCheck(eBestID); } else { _pUnitVariables1->vAddVariableNoCheck(eBestID); } if (_bUnitPropagate()) { if (_bBackup()) { return bReturnValue; } } } } } boolean SATSolver::_bOutputSolution() { _iSolutionCount++; if (_bFindAll || _iSolutionCount == 1) { // output only first solution found if counting xOutputStream << "Solution " << _iSolutionCount << ": "; for (int i=0; i<_iVariableCount; i++) { assert(_aAssignment[i] != NON_VALUE); if (_aAssignment[i]) { xOutputStream << i+1 << " "; } } xOutputStream << endl; } #ifndef NDEBUG if (_bVerifySolution()) { // xOutputStream << "c Solution verified" << endl; } else { Debug::vErrorReport("Found an invalid solution."); } #endif if (_bFindAll && _iSolutionCount >= _iMaxSolutions && _iMaxSolutions) { return 1; } return 0; } boolean SATSolver::_bVerifySolution() { // returns 1 if solution checks out OK for (int i=0; i<_pInstance->iClauseCount(); i++) { Clause* pTestMe = _pInstance->pClause(i); boolean bSatisfied = 0; for (int j=0; j<pTestMe->iVariableCount(); j++) { VariableID eCheckMe = pTestMe->eConstrainedVariable(j); if (_aAssignment[eCheckMe] && !pTestMe->iIsNegated(j) || !_aAssignment[eCheckMe] && pTestMe->iIsNegated(j)) { bSatisfied = 1; break; } } if (!bSatisfied) { return 0; } } return 1; } VariableStruct* SATSolver::_pBackupToFirstBranch() { //returns 1 if the search is complete. int i=0; while (i< _iCurrentVariable) { if(_aVariableStruct[_aPositionToID[i]].bBranch) { break; } i++; } VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); while (_iCurrentVariable != i) { pWork = &(_aVariableStruct[_eCurrentID]); _vUndoClauseModifications(); pWork->bBranch = 0; _aAssignment[_eCurrentID] = NON_VALUE; pWork->pReason = 0; _iCurrentVariable--; if (_iCurrentVariable != i) { pWork->xUnitClause.vClear(); } if (_iCurrentVariable) { _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } else { _eCurrentID = -1; } } return pWork; } boolean SATSolver::_bRestartLoop(boolean& bFailed_) { bFailed_ = 0; boolean bReturnValue = 0; time(&iLastRestart); time_t now; while (1) { if (_bTimeLimitExpired()) { bFailed_ = 1; return bReturnValue; } if (_bPrintStackCheck()) { _vPrintStack(); } time(&now); if (now - iLastRestart > _iRestartInterval) { _iRestartInterval += _iRestartIncrement; xOutputStream << "c Restarting. Next restart in " << _iRestartInterval << " seconds. " <<endl; VariableStruct* pWork = _pBackupToFirstBranch(); if (_bNonTrivialUnitPropagate(pWork->xUnitClause) || _bUnitPropagate()) { return 0; } time(&iLastRestart); } VariableID eBestID; boolean bZeroFirst; if (_pPrimaryVariables) { eBestID = _eGiveMeTheBest(bZeroFirst, true); } else { eBestID = _eGiveMeTheBest(bZeroFirst, false); } if (eBestID == -1) { bReturnValue = 1; if (_iCurrentVariable == _iVariableCount) { if (_bOutputSolution()) { xOutputStream << "c Solution limit reached. " << endl; return bReturnValue; } } if (_bSpecialBackup()) { xOutputStream << "c All solutions found." << endl; return bReturnValue; } } else { _aVariableStruct[eBestID].bBranch = 1; if (bZeroFirst) { _pUnitVariables0->vAddVariableNoCheck(eBestID); } else { _pUnitVariables1->vAddVariableNoCheck(eBestID); } if (_bUnitPropagate()) { if (_bBackup()) { return bReturnValue; } } } } } VariableID SATSolver::_eGiveMeTheBest(boolean& bZeroFirst, boolean bFavorPrimary) { // Select the best branch variable. assert(_pUnitVariables0->iCount() == 0); assert(_pUnitVariables1->iCount() == 0); double fBest = -1.0; VariableStruct* pWorkStruct; VariableID eID, eID2; int i, j; int iScore0, iScore1; boolean bNoBinary = 1; for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { if (_aBinaryCount0[eID] || _aBinaryCount1[eID]) { bNoBinary = 0; } // Compute iScore0 if (_aBinaryCount0[eID] > 0 && _aScore0[eID] != -1 && _aBinaryCount0[eID] > _aScore0[eID]) { if (_bFastUnitPropagate(eID, 1, iScore0)) { for (j=0; j<i; j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { _aScore0[eID2] = _aBinaryCount0[eID2]; _aScore1[eID2] = _aBinaryCount1[eID2]; } } for (j=i; j<_pGoodList->iCount(); j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { if (_aScore0[eID2] == -1) { _aScore0[eID2] = _aBinaryCount0[eID2]; } if (_aScore1[eID2] == -1) { _aScore1[eID2] = _aBinaryCount1[eID2]; } } } bZeroFirst = 0; return eID; // leads to contradiction } //if (_bFastUnit... } else { iScore0 = _aBinaryCount0[eID]; } // Compute iScore1 if (_aBinaryCount1[eID] > 0 && _aScore1[eID] != -1 && _aBinaryCount1[eID] > _aScore1[eID]) { if (_bFastUnitPropagate(eID, 0, iScore1)) { for (j=0; j<i; j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { _aScore0[eID2] = _aBinaryCount0[eID2]; _aScore1[eID2] = _aBinaryCount1[eID2]; } } for (j=i; j<_pGoodList->iCount(); j++) { eID2 = _pGoodList->iVariable(j); if (_aAssignment[eID2] == NON_VALUE) { if (_aScore0[eID2] == -1) { _aScore0[eID2] = _aBinaryCount0[eID2]; } if (_aScore1[eID2] == -1) { _aScore1[eID2] = _aBinaryCount1[eID2]; } } } bZeroFirst = 1; return eID; // leads to contradiction } // if (_bFastUnit... } else { iScore1 = _aBinaryCount1[eID]; } _aScore[eID] = _iCombineScores(iScore1, iScore0); if (!bFavorPrimary || _pPrimaryVariables->bHasVariable(eID)) { if (_aScore[eID] > fBest) { fBest = _aScore[eID]; } } } // if (...NON_VALUE... } // for (int i=0;... if (bNoBinary) { _vComputeNoBinaryScores(fBest, bFavorPrimary); if (fBest == -2.0 && !bFavorPrimary) { return -1; } else if (fBest == -2.0) { //cout << "Setting primary to false: " << fBest << endl; bFavorPrimary = false; _vComputeNoBinaryScores(fBest, bFavorPrimary); } if (fBest == -2.0) { return -1; } } _iBranchSelections++; try_with_non_primary: // Danger: reusing _pUnitList for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { if (bFavorPrimary) { if (!_pPrimaryVariables->bHasVariable(eID)) { continue; } } if (_aScore[eID] >= fBest * _fFudgeFactor) { //cout << "Adding: " << eID << endl; _pUnitList->vAdd(eID); } } } if (bFavorPrimary && _pUnitList->iCount() == 0) { //cout << "No more primary vars: " << _iVariableCount << endl; // No more primary variables left to label. bFavorPrimary = false; fBest = -2.0; for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { if (_aScore[eID] >= fBest) { fBest = _aScore[eID]; } } } goto try_with_non_primary; } VariableID eReturn = _pUnitList->iVariable(xRandom.iRandom(_pUnitList->iCount())); _pUnitList->vClear(); bZeroFirst = xRandom.iRandom(2); /*bZeroFirst = _aBinaryCount1[eReturn] > _aBinaryCount0[eReturn] ? 0 : 1;*/ memcpy(_aScore0, _aBinaryCount0, _iVariableCount * sizeof(*_aScore1)); memcpy(_aScore1, _aBinaryCount1, _iVariableCount * sizeof(*_aScore0)); //cout << "Returning branch: " << (eReturn+1) << " for loc. " << _iCurrentVariable << endl; return eReturn; } void SATSolver::_vComputeNoBinaryScores(double& fBest, boolean bFavorPrimary) { // Scoring function for when there are no binary clauses. fBest = -2.0; int i; VariableID eID; int iScore0, iScore1; for (i=0; i<_pGoodList->iCount(); i++) { eID = _pGoodList->iVariable(i); if (_aAssignment[eID] == NON_VALUE) { iScore0 = _iScoreClauseList(_aVariableStruct[eID].xPositiveClauses.pEntry(0), _aVariableStruct[eID].xPositiveClauses.pLastEntry()); iScore1 = _iScoreClauseList(_aVariableStruct[eID].xNegativeClauses.pEntry(0), _aVariableStruct[eID].xNegativeClauses.pLastEntry()); _aScore[eID] = _iCombineScores(iScore0, iScore1); if (bFavorPrimary && !_pPrimaryVariables->bHasVariable(eID)) { continue; } if (_aScore[eID] >= fBest) { fBest = _aScore[eID]; } } } } boolean SATSolver::_bInitialize() { // temp stuff _bReverse = 0; // Return 0 if problem is UNSAT due to unary clauses (node-consistency) _iRelevantClauses = 0; _xLearnedClauses.vDestroy(); _iSolutionCount = 0; _eCurrentID = -1; _iCurrentVariable = 0; _xSolutionCount.vSet(1); _xKnownSolutions.vSet(0); _iVariableCount = _pInstance->iVariableCount; _aBinaryCount0 = new long int[_iVariableCount]; _aBinaryCount1 = new long int[_iVariableCount]; _aAssignment = new DomainValue[_pInstance->iVariableCount]; _aVariableStruct = new VariableStruct[_pInstance->iVariableCount]; _aPositionToID = new VariableID[_pInstance->iVariableCount]; _aIDToPosition = new long int[_pInstance->iVariableCount]; _aScore0 = new int[_pInstance->iVariableCount]; _aScore = new double[_pInstance->iVariableCount]; _aScore1 = new int[_pInstance->iVariableCount]; _pUnitVariables0 = new VariableSet(_pInstance->iVariableCount); _pUnitVariables1 = new VariableSet(_pInstance->iVariableCount); _pUnitList = new VariableList(_pInstance->iVariableCount); _pPositiveBackup = new VariableSet(_pInstance->iVariableCount); _pNegativeBackup = new VariableSet(_pInstance->iVariableCount); _pGoodList = new VariableSet(_pInstance->iVariableCount); _pGoodReason = new VariableList(_pInstance->iVariableCount); int i; for (i=0; i< _iVariableCount; i++) { _aAssignment[i] = NON_VALUE; _pGoodList->vAddVariableNoCheck(i); _aBinaryCount0[i] = _aBinaryCount1[i] = _aScore0[i] = _aScore1[i] = 0; } for (i=0; i<_pInstance->iClauseCount(); i++) { Clause* pClause = _pInstance->pClause(i); pClause->vReset(); if (_bInitializeClause(pClause)) { return 0; } } for (i=0; i<_iVariableCount; i++) { _aVariableStruct[i].xPositiveClauses.vSortClausesByLength(); _aVariableStruct[i].xNegativeClauses.vSortClausesByLength(); } return 1; } boolean SATSolver::_bInitializeClause(Clause* pClause_) { // returns 1 if instance is UNSAT if (pClause_->iVariableCount() == 1) { if (_bInitializeUnaryClause(pClause_)) { return 1; } } boolean bIsBinary = (pClause_->iVariableCount() == 2); for (int j=0; j<pClause_->iVariableCount(); j++) { if (pClause_->iIsNegated(j)) { _aVariableStruct[pClause_->eConstrainedVariable(j)].xNegativeClauses.vAddClause(pClause_); if (bIsBinary) { _aBinaryCount0[pClause_->eConstrainedVariable(j)]++; } } else { _aVariableStruct[pClause_->eConstrainedVariable(j)].xPositiveClauses.vAddClause(pClause_); if (bIsBinary) { _aBinaryCount1[pClause_->eConstrainedVariable(j)]++; } } } return 0; } boolean SATSolver::_bInitializeLearnedClause(Clause* pClause_) { // returns 1 if instance is UNSAT // Call to initialize a clause learned during backtracking. for (int j=0; j<pClause_->iPermaCount(); j++) { if (pClause_->iIsNegated(j)) { _aVariableStruct[pClause_->eConstrainedVariable(j)].xNegativeClauses.vAddClause(pClause_); _aBinaryCount0[pClause_->eConstrainedVariable(j)]++; } else { _aVariableStruct[pClause_->eConstrainedVariable(j)].xPositiveClauses.vAddClause(pClause_); _aBinaryCount1[pClause_->eConstrainedVariable(j)]++; } } return 0; } boolean SATSolver::_bInitializeUnaryClause(Clause* pClause_) { // returns 0 if problem is determined to be UNSAT assert(pClause_->iVariableCount() == 1); VariableID eConstrainedVariable = pClause_->eConstrainedVariable(0); if (pClause_->iIsNegated(0)) { if (_pUnitVariables1->bHasVariable(eConstrainedVariable)) { return 1; // problem is UNSAT } if (_aVariableStruct[eConstrainedVariable].pReason == 0) { _pUnitVariables0->vAddVariable(eConstrainedVariable); _aVariableStruct[eConstrainedVariable].pReason = pClause_; } } else { if (_pUnitVariables0->bHasVariable(eConstrainedVariable)) { return 1; // problem is UNSAT } if (_aVariableStruct[eConstrainedVariable].pReason == 0) { _pUnitVariables1->vAddVariable(eConstrainedVariable); _aVariableStruct[eConstrainedVariable].pReason = pClause_; } } return 0; } int SATSolver::_iScoreClauseList(register Clause** pStart_, Clause** const pEnd_) { // Score the clause list based on clause lengths. assumes no clauses are binary. int iCount = 0; for (; pStart_ < pEnd_; pStart_++) { if (!(*pStart_)->bIsSatisfied()) { switch ((*pStart_)->iWorkingLength()) { case 3: iCount += 256; break; case 4: iCount += 16; break; case 5: iCount += 4; break; default: iCount += 1; } } } return iCount; } void SATSolver::_vFastBackupScore() { register Clause** pStart; Clause** pEnd; int i; const int iCount = _pUnitList->iCount(); for (i=0; i<iCount; i++) { VariableID eUndo = _pUnitList->iVariable(i); if (_aAssignment[eUndo]) { pStart = _aVariableStruct[eUndo].xNegativeClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xNegativeClauses.pLastEntry(); _aScore0[eUndo] = -1; // indicate no dead end } else { pStart = _aVariableStruct[eUndo].xPositiveClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xPositiveClauses.pLastEntry(); _aScore1[eUndo] = -1; // indicate no dead end } for (; pStart < pEnd; pStart++) { (*pStart)->iExpand(); } _aAssignment[eUndo] = NON_VALUE; } _pUnitList->vClear(); } void SATSolver::_vFastBackup(const int iToIndex_) { register Clause** pStart; Clause** pEnd; int i; for (i=0; i<iToIndex_; i++) { VariableID eUndo = _pUnitList->iVariable(i); if (_aAssignment[eUndo]) { pStart = _aVariableStruct[eUndo].xNegativeClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xNegativeClauses.pLastEntry(); } else { pStart = _aVariableStruct[eUndo].xPositiveClauses.pEntry(0); pEnd = _aVariableStruct[eUndo].xPositiveClauses.pLastEntry(); } for (; pStart < pEnd; pStart++) { (*pStart)->iExpand(); } _aAssignment[eUndo] = NON_VALUE; } for (; i<_pUnitList->iCount(); i++) { _aAssignment[_pUnitList->iVariable(i)] = NON_VALUE; } _pUnitList->vClear(); } boolean SATSolver::_bFastUnitPropagate(VariableID eWhich_, DomainValue iAssignment_, int& iScore_) { // Return 1 if unit propagation leads to a contradiction. int i,j; Clause **pStart, **pEnd; Clause *pReduceMe; VariableID eID; assert(_pUnitList->iCount() == 0); _pUnitList->vAdd(eWhich_); _aAssignment[eWhich_] = iAssignment_; for (i=0; i<_pUnitList->iCount(); i++) { eID = _pUnitList->iVariable(i); if (_aAssignment[eID] == 0) { pStart = _aVariableStruct[eID].xPositiveClauses.pEntry(0); pEnd = _aVariableStruct[eID].xPositiveClauses.pLastEntry(); } else { pStart = _aVariableStruct[eID].xNegativeClauses.pEntry(0); pEnd = _aVariableStruct[eID].xNegativeClauses.pLastEntry(); } Clause **const pBegin = pStart; for (;pStart < pEnd; pStart++) { pReduceMe = *pStart; if (!pReduceMe->bIsSatisfied()) { switch(pReduceMe->iReduce()) { case 0: // Contradiction! for (; pStart >= pBegin; pStart--) { (*pStart)->iExpand(); } _vFastBackup(i); return 1; case 1: for (j = 0; j < pReduceMe->iPermaCount(); j++) { eID = pReduceMe->eConstrainedVariable(j); if (_aAssignment[eID] == NON_VALUE) { _pUnitList->vAdd(eID); if (pReduceMe->iIsNegated(j)) { _aAssignment[eID] = 0; } else { _aAssignment[eID] = 1; } break; } } } } } // for (;pStart... } // for (i=.n. iScore_ = _pUnitList->iCount(); _vFastBackupScore(); return 0; } boolean SATSolver::_bUnitPropagate() { // Return 1 if unit propagation leads to a contradiction. // Does not back up, does not learn. // Simply leaves the list of contradicting variables intact. VariableStruct* pWork; while(1) { if (_pUnitVariables1->iCount()) { int iWhich = xRandom.iRandom(_pUnitVariables1->iCount()); _vLabelVariable(_pUnitVariables1->iVariable(iWhich), 1); _pUnitVariables1->vRemoveVariable(_eCurrentID); assert(_pGoodList->bHasVariable(_eCurrentID)); pWork = &_aVariableStruct[_eCurrentID]; _vSatisfyWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry())) { return 1; } } else if (_pUnitVariables0->iCount()) { int iWhich = xRandom.iRandom(_pUnitVariables0->iCount()); _vLabelVariable(_pUnitVariables0->iVariable(iWhich), 0); _pUnitVariables0->vRemoveVariable(_eCurrentID); assert(_pGoodList->bHasVariable(_eCurrentID)); pWork = &_aVariableStruct[_eCurrentID]; _vSatisfyWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry())) { return 1; } } else { return 0; } } // while(1); } boolean SATSolver::_bFilterWithClauseList(Clause** pStart_, Clause** pEnd_) { // return 1 if contradiction encountered. boolean bReturn = 0; Clause* pWorkClause; VariableID eContradictionID; Clause* pContradictionReason; int j; for (; pStart_ < pEnd_; pStart_++) { pWorkClause = *pStart_; if (!pWorkClause->bIsSatisfied()) { switch (pWorkClause->iReduce()) { case 2: for (j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]++; } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]++; } } break; case 1: // Find the variable it filters. for (int j = 0; ; j++) { assert(j < pWorkClause->iPermaCount()); VariableID eID = pWorkClause->eConstrainedVariable(j); if (_aAssignment[eID] == NON_VALUE) { if (!_pGoodList->bHasVariable(eID)) { // it's outside the goodlist break; } // we've found the filtering variable if (pWorkClause->iIsNegated(j)) { if (_aVariableStruct[eID].pReason) { if (_pUnitVariables1->bHasVariable(eID)) { // Contradiction! // Can't return immediately because it will confuse the state undoing code eContradictionID = eID; pContradictionReason = pWorkClause; bReturn = 1; } else { assert(_pUnitVariables0->bHasVariable(eID)); _vDecideFilterClause(eID, pWorkClause); } } // if (_...pReason) else { assert(!_pUnitVariables1->bHasVariable(eID)); assert(_pGoodList->bHasVariable(eID)); _pUnitVariables0->vAddVariableNoCheck(eID); _aVariableStruct[eID].pReason = pWorkClause; } } // if (pWorkClause->iIsNegated(j)... else { if (_aVariableStruct[eID].pReason) { if (_pUnitVariables0->bHasVariable(eID)) { // Contradiction! // Can't return immediately because it will confuse the state undoing code eContradictionID = eID; pContradictionReason = pWorkClause; bReturn = 1; } else { assert(_pUnitVariables1->bHasVariable(eID)); _vDecideFilterClause(eID, pWorkClause); } } // if (...pReason... else { assert(!_pUnitVariables0->bHasVariable(eID)); assert(_pGoodList->bHasVariable(eID)); _pUnitVariables1->vAddVariableNoCheck(eID); _aVariableStruct[eID].pReason = pWorkClause; } } break; } } // for (int j= } } } if (bReturn) { _vSetContradiction(eContradictionID, pContradictionReason); } return bReturn; } inline void SATSolver::_vSetContradiction(VariableID eContradictionID_, Clause* pReason_) { _eContradictionID = eContradictionID_; _pContradictionClause1 = pReason_; _pContradictionClause2 = _aVariableStruct[eContradictionID_].pReason; int i; for (i=0; i<_pUnitVariables0->iCount(); i++) { _aVariableStruct[_pUnitVariables0->iVariable(i)].pReason = 0; } _pUnitVariables0->vClear(); for (i=0; i<_pUnitVariables1->iCount(); i++) { _aVariableStruct[_pUnitVariables1->iVariable(i)].pReason = 0; } _pUnitVariables1->vClear(); } void SATSolver::_vSatisfyWithClauseList(register Clause** pStart_, Clause** pEnd_) { Clause* pWorkClause; for (; pStart_ < pEnd_; pStart_++) { pWorkClause = *pStart_; if (!pWorkClause->bIsSatisfied()) { if (pWorkClause->iWorkingLength() == 2 ) { for (int j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount0[pWorkClause->eConstrainedVariable(j)] >= 0); } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount1[pWorkClause->eConstrainedVariable(j)] >= 0); } } } } pWorkClause->vMakeSatisfied(); } } boolean SATSolver::_bCreateBackupClauseFromContradiction() { // Create a new clause representing the nogood derived from the // current contradiction on _eContradictionID. _iContradictions++; _pPositiveBackup->vClear(); _pNegativeBackup->vClear(); int i; for (i=0; i<_pContradictionClause1->iVariableCount(); i++) { if (_pContradictionClause1->iIsNegated(i)) { _pNegativeBackup->vAddVariableNoCheck(_pContradictionClause1->eConstrainedVariable(i)); } else { _pPositiveBackup->vAddVariableNoCheck(_pContradictionClause1->eConstrainedVariable(i)); } } for (i=0; i<_pContradictionClause2->iVariableCount(); i++) { if (_pContradictionClause2->iIsNegated(i)) { _pNegativeBackup->vAddVariable(_pContradictionClause2->eConstrainedVariable(i)); } else { _pPositiveBackup->vAddVariable(_pContradictionClause2->eConstrainedVariable(i)); } } _pPositiveBackup->vRemoveVariable(_eContradictionID); _pNegativeBackup->vRemoveVariable(_eContradictionID); if (!_pContradictionClause1->bIsTemporary() && !_pContradictionClause2->bIsTemporary() && _pPositiveBackup->iCount() + _pNegativeBackup->iCount() >= (_pContradictionClause1->iVariableCount() + _pContradictionClause2->iVariableCount() - 2)) { return 0; } else { return 1; } } inline boolean SATSolver::_bCreateNewBackupClause(boolean bLastReasonTransient_) { Clause* pFailClause2; pFailClause2 = _aVariableStruct[_eCurrentID].pReason; int iOriginalCount = _pNegativeBackup->iCount() + _pPositiveBackup->iCount(); for (int i=0; i<pFailClause2->iVariableCount(); i++) { VariableID eWorkID = pFailClause2->eConstrainedVariable(i); if (pFailClause2->iIsNegated(i)) { _pNegativeBackup->vAddVariable(eWorkID); } else { _pPositiveBackup->vAddVariable(eWorkID); } } _pPositiveBackup->vRemoveVariableCheck(_eCurrentID); _pNegativeBackup->vRemoveVariableCheck(_eCurrentID); if (!bLastReasonTransient_ && !pFailClause2->bIsTemporary() && _pPositiveBackup->iCount() + _pNegativeBackup->iCount() >= (pFailClause2->iVariableCount() + iOriginalCount - 2)) { return 0; } else { return 1; } } inline Clause* SATSolver::_pLearn() { if (_pPositiveBackup->iCount() + _pNegativeBackup->iCount() <= _iLearnOrder) { Clause* pLearn = new Clause(*_pPositiveBackup, *_pNegativeBackup); _xLearnedClauses.vAddClause(pLearn); int i = _iCurrentVariable-1; boolean bFoundFirst = 0; while(i >= 0) { VariableID eID = _aPositionToID[i]; if (_pPositiveBackup->bHasVariable(eID) || _pNegativeBackup->bHasVariable(eID)) { if (!bFoundFirst) { bFoundFirst = 1; } else break; } else if (bFoundFirst && _aVariableStruct[eID].bBranch) { _aVariableStruct[eID].xUnitClause.vAddClause(pLearn); } i--; } _bInitializeLearnedClause(pLearn); return pLearn; } else if (_bRelevanceBounding && _iLearnOrder) { // Learn a temporary clause int i = _iCurrentVariable-1; int iBranches = 0; int iPermaCount = 0; VariableID eResetID; assert(_pUnitVariables0->iCount() == 0); // reusing this VariableSet assert(_pUnitVariables1->iCount() == 0); // reusing this VariableSet for PermaVars while (1) { VariableID eID = _aPositionToID[i]; assert(_aAssignment[eID] != NON_VALUE); if (_pPositiveBackup->bHasVariable(eID) || _pNegativeBackup->bHasVariable(eID)) { if (iPermaCount == _iLearnOrder) { eResetID = eID; break; } if (_aVariableStruct[eID].bBranch) { iBranches++; } _pUnitVariables1->vAddVariableNoCheck(eID); iPermaCount++; } else if (_aVariableStruct[eID].bBranch) { if (iPermaCount > 0) { iBranches++; } if (iPermaCount == 1) { _pUnitVariables0->vAddVariableNoCheck(eID); } } i--; assert(i>=0); } // while //assert(_pUnitVariables1->iCount() == _iLearnOrder); if (iBranches > 0) { Clause* pLearn = new Clause(*_pPositiveBackup, *_pNegativeBackup, *_pUnitVariables1); _bInitializeLearnedClause(pLearn); _aVariableStruct[eResetID].xDeleteList.vAddClause(pLearn); for (int k=0; k<_pUnitVariables0->iCount(); k++) { _aVariableStruct[_pUnitVariables0->iVariable(k)].xUnitClause.vAddClause(pLearn); } _pUnitVariables0->vClear(); _pUnitVariables1->vClear(); _iRelevantClauses++; return pLearn; } _pUnitVariables0->vClear(); _pUnitVariables1->vClear(); } // else return 0; } inline void SATSolver::_vDeleteClauses(ClauseList& rClauseList_) { // Delete these learned clauses since they are no longer relevant VariableStruct* pWork; Clause** pStart = rClauseList_.pEntry(0); Clause** pEnd = rClauseList_.pLastEntry(); for (; pStart < pEnd; pStart++) { Clause* pDeleteMe = *pStart; for (int j=0; j<pDeleteMe->iPermaCount(); j++) { pWork = &(_aVariableStruct[pDeleteMe->eConstrainedVariable(j)]); if (pDeleteMe->iPermaCount() < 3) { if (pDeleteMe->iIsNegated(j)) { pWork->xNegativeClauses.vDeleteClause(pDeleteMe); _aBinaryCount0[pDeleteMe->eConstrainedVariable(j)]--; } else { pWork->xPositiveClauses.vDeleteClause(pDeleteMe); _aBinaryCount1[pDeleteMe->eConstrainedVariable(j)]--; } } else { if (pDeleteMe->iIsNegated(j)) { pWork->xNegativeClauses.vDeleteClause(pDeleteMe); } else { pWork->xPositiveClauses.vDeleteClause(pDeleteMe); } } assert(_aAssignment[pDeleteMe->eConstrainedVariable(j)] == NON_VALUE); } _iRelevantClauses--; delete pDeleteMe; } rClauseList_.vClear(); } inline void SATSolver::_vLabelVariable(VariableID eID_, DomainValue lWhich_) { // Label a variable and make it current. //xOutputStream << "Labeling: " << eID_ << " to " << (int)lWhich_ << endl; assert(_aAssignment[eID_] == NON_VALUE); assert(_iCurrentVariable < _iVariableCount); _aAssignment[eID_] = lWhich_; _aIDToPosition[eID_] = _iCurrentVariable; _aPositionToID[_iCurrentVariable++] = eID_; _eCurrentID = eID_; _iVariablesLabeled++; } boolean SATSolver::_bBackup() { // Returns 1 if the search is complete. start: //^^ We goto start instead of call bBackup() recursively since some compilers don't // properly support tail recursion optimization. //_vLearnBranchClauseFromContradiction(); boolean bLearn = _bCreateBackupClauseFromContradiction(); boolean bLastReasonTransient; if (_pPositiveBackup->iCount() == 0 && _pNegativeBackup->iCount() == 0) { return 1; } Clause* pJustLearned; if (bLearn) { pJustLearned = _pLearn(); if (pJustLearned && !pJustLearned->bIsTemporary()) { bLastReasonTransient = 0; } else { bLastReasonTransient = 1; } } else { bLastReasonTransient = 0; pJustLearned = 0; } VariableStruct* pWork; do { // while (1) pWork = &(_aVariableStruct[_eCurrentID]); if (pWork->pSolutionInfo) { pWork->pSolutionInfo->xSolutionCount.vSet(0); pWork->pReason = new Clause(*_pPositiveBackup, *_pNegativeBackup); delete pWork->pDeleteReason; pWork->pDeleteReason = pWork->pReason; // NASTY UGLY HACK // This hack is needed so that _vCreateGoodReason properly computes the reason. _bReverse = 1; // END NASTY UGLY HACK return _bSpecialBackup(); } _vUndoClauseModifications(); if (_pPositiveBackup->bHasVariable(_eCurrentID) || _pNegativeBackup->bHasVariable(_eCurrentID)) { if (pWork->bBranch) { pWork->bBranch = 0; if (pJustLearned) { pWork->pReason = pJustLearned; } else { // No reason was created by the learning mechanism, so we need to create one. pWork->pReason = new Clause(*_pPositiveBackup, *_pNegativeBackup); delete pWork->pDeleteReason; // we lazily delete any old one if it exists pWork->pDeleteReason = pWork->pReason; } if (_aAssignment[_eCurrentID] == 0) { // try the opposite assignment _pUnitVariables1->vAddVariable(_eCurrentID); } else { _pUnitVariables0->vAddVariable(_eCurrentID); } _aAssignment[_eCurrentID] = NON_VALUE; _iCurrentVariable--; if (_bNonTrivialUnitPropagate(pWork->xUnitClause)) { _eCurrentID = _aPositionToID[_iCurrentVariable-1]; goto start; } VariableID eRemember = _eCurrentID; if (_bUnitPropagate()) { goto start; } return 0; } else { bLearn = _bCreateNewBackupClause(bLastReasonTransient); if (_pPositiveBackup->iCount() == 0 && _pNegativeBackup->iCount() == 0) { return 1; } if (bLearn) { pJustLearned = _pLearn(); if (pJustLearned && !pJustLearned->bIsTemporary()) { bLastReasonTransient = 0; } else { bLastReasonTransient = 1; } } else { bLastReasonTransient = 0; pJustLearned = 0; } } } // if (_pBackupSet->bHasVariable pWork->bBranch = 0; _aAssignment[_eCurrentID] = NON_VALUE; pWork->pReason = 0; pWork->xUnitClause.vClear(); _iCurrentVariable--; assert(_iCurrentVariable != 0); _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } while(1); } void SATSolver::_vCreateGoodReason() { // Create a reason that explains the solution count of the current subproblem. VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); int i; assert(_aAssignment[_eCurrentID] != NON_VALUE); Clause** pStart; Clause** pEnd; pStart = pWork->xNegativeClauses.pEntry(0); pEnd = pWork->xNegativeClauses.pLastEntry(); _vUpdateGoodReason(pStart, pEnd, pWork->pSolutionInfo->xGoodReason); pStart = pWork->xPositiveClauses.pEntry(0); pEnd = pWork->xPositiveClauses.pLastEntry(); _vUpdateGoodReason(pStart, pEnd, pWork->pSolutionInfo->xGoodReason); /* if (_aVariableStruct[_eCurrentID].pReason) { Clause* pReason = _aVariableStruct[_eCurrentID].pReason; for (int i=0; i<pReason->iVariableCount(); i++) { VariableID eID = pReason->eConstrainedVariable(i); if (eID != _eCurrentID && _aAssignment[eID] != NON_VALUE) { pWork->pSolutionInfo->xGoodReason.vAddVariable(pReason->eConstrainedVariable(i)); } } }*/ if (_pGoodReason->eTop() != -1) { assert(_aAssignment[_pGoodReason->eTop()] != NON_VALUE); pWork->pSolutionInfo->xGoodReason.vAddVariable(_pGoodReason->eTop()); } pWork->pSolutionInfo->xGoodReason.vRemoveVariableCheck(_eCurrentID); } void SATSolver::_vUpdateGoodReason(Clause** pStart, Clause** pEnd, VariableSet& xGoodReason_) { VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); int i; VariableID eID, eBest; Clause* pBestUnsatisfied = 0; for (; pStart < pEnd; pStart++) { if ((*pStart)->bLearned()) { // Learned clauses are redundant, so they need not contribute to the reason. continue; } if ((*pStart)->bIsSatisfied()) { // Unlike reasons for contradiction, reasons for a positive solution count must consider // satisfied clauses, since if they were not satisfied, this might reduce the solution // count. int iEarliest = 9999999; for (i=0; i<(*pStart)->iPermaCount(); i++) { eID = (*pStart)->eConstrainedVariable(i); if (eID != _eCurrentID && _aAssignment[eID] != NON_VALUE) { if ((_aAssignment[eID] && !(*pStart)->iIsNegated(i)) || (!_aAssignment[eID] && (*pStart)->iIsNegated(i))) { // found a satisfying var. if (_aIDToPosition[eID] < iEarliest) { iEarliest = _aIDToPosition[eID]; eBest = eID; } } } } // for assert(iEarliest != 9999999); xGoodReason_.vAddVariable(eBest); } else { Clause* pReason = *pStart; //cout << "pReason: "; pReason->vOutput(xOutputStream); cout << endl; for (i=0; i<pReason->iVariableCount(); i++) { VariableID eID = pReason->eConstrainedVariable(i); if (eID != _eCurrentID && _aAssignment[eID] != NON_VALUE) { //cout << "." << (_eCurrentID+1) << "."; xGoodReason_.vAddVariable(pReason->eConstrainedVariable(i)); } } } } } boolean SATSolver::_bSpecialBackup() { // Back up from a state where solutions exist. Returns 1 if there are no more solutions. // WARNING: Convoluted code. There's a bunch of weird stuff going on here which I just // haven't had time to clean up or properly document. VariableStruct* pWork; VariableStruct* pParentWork; VariableID eParentID; do { // while (1) pWork = &(_aVariableStruct[_eCurrentID]); _vUndoClauseModifications(); if (!pWork->pSolutionInfo) { pWork->pSolutionInfo = new SolutionInfo(_iVariableCount); } SolutionInfo* pSolutionInfo = pWork->pSolutionInfo; if (pWork->bBranch && (!_pPrimaryVariables || _pPrimaryVariables->bHasVariable(_eCurrentID))) { // we have backed up to a branch //xOutputStream << "Branch: " << _eCurrentID << endl; assert(!pWork->pReason); pWork->bBranch = 0; _iCurrentVariable--; if (!_bFindAll) { _pGoodReason->vAdd(_eCurrentID); pSolutionInfo->pOldSolutionCount = new BigNum(pSolutionInfo->xSolutionCount); pSolutionInfo->xSolutionCount.vSet(1); _pGoodList->vClear(); _pGoodList->vAppendNoCheck(pSolutionInfo->xGoodList); _pGoodList->vAddVariableNoCheck(_eCurrentID); } assert(_pUnitVariables0->iCount() == 0); assert(_pUnitVariables1->iCount() == 0); if (_aAssignment[_eCurrentID] == 0) { // try the opposite assignment _aAssignment[_eCurrentID] = NON_VALUE; _vLabelVariable(_eCurrentID,1); _vSatisfyWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry())) { return _bBackup(); } } else { _aAssignment[_eCurrentID] = NON_VALUE; _vLabelVariable(_eCurrentID,0); _vSatisfyWithClauseList(pWork->xNegativeClauses.pEntry(0), pWork->xNegativeClauses.pLastEntry()); if (_bFilterWithClauseList(pWork->xPositiveClauses.pEntry(0), pWork->xPositiveClauses.pLastEntry())) { return _bBackup(); } } if (_bNonTrivialUnitPropagate(pWork->xUnitClause)) { return _bBackup(); } if (_bUnitPropagate()) { return _bBackup(); } return 0; } if (_pGoodReason->eTop() == _eCurrentID) { _pGoodReason->ePop(); } if (!_bFindAll) { _vCreateGoodReason(); eParentID = _eFindDeepestID(pWork->pSolutionInfo->xGoodReason); assert(eParentID != _eCurrentID); // Add branch counts together if (pSolutionInfo->pOldSolutionCount) { pSolutionInfo->xSolutionCount += *(pSolutionInfo->pOldSolutionCount); if (pSolutionInfo->xSolutionCount > _xKnownSolutions) { _xKnownSolutions.vSet(pSolutionInfo->xSolutionCount); } delete pSolutionInfo->pOldSolutionCount; pSolutionInfo->pOldSolutionCount = 0; } if (eParentID != -1) { pParentWork = &(_aVariableStruct[eParentID]); if (!pParentWork->pSolutionInfo) { pParentWork->pSolutionInfo = pWork->pSolutionInfo; pParentWork->pSolutionInfo->xGoodList.vAdd(_eCurrentID); } else { pParentWork->pSolutionInfo->xGoodReason.vAppendVariables(pSolutionInfo->xGoodReason); if (!pParentWork->pSolutionInfo->pOldSolutionCount) { pParentWork->pSolutionInfo->xGoodList.vAppend(pSolutionInfo->xGoodList); pParentWork->pSolutionInfo->xGoodList.vAdd(_eCurrentID); } pParentWork->pSolutionInfo->xSolutionCount *= pSolutionInfo->xSolutionCount; if (pParentWork->pSolutionInfo->xSolutionCount > _xKnownSolutions) { _xKnownSolutions.vSet(pParentWork->pSolutionInfo->xSolutionCount); } delete pSolutionInfo; } } else { _xSolutionCount *= pSolutionInfo->xSolutionCount; if (_xSolutionCount > _xKnownSolutions) { _xKnownSolutions.vSet(_xSolutionCount); } delete pSolutionInfo; _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } } else { // Finding all solutions instead of counting pWork->bBranch = 0; if (_iCurrentVariable) { eParentID = _aPositionToID[_iCurrentVariable-1]; pParentWork = &(_aVariableStruct[eParentID]); if (!pParentWork->pSolutionInfo) { pParentWork->pSolutionInfo = pWork->pSolutionInfo; } else { delete pSolutionInfo; } } else { eParentID = -1; delete pSolutionInfo; } } pWork->pSolutionInfo = 0; pWork->bBranch = 0; _aAssignment[_eCurrentID] = NON_VALUE; pWork->pReason = 0; pWork->xUnitClause.vClear(); _iCurrentVariable--; if (_iCurrentVariable == 0) { // the search is complete. assert(_pGoodReason->iCount() == 0); return 1; } _eCurrentID = _aPositionToID[_iCurrentVariable-1]; } while(1); } VariableID SATSolver::_eFindDeepestID(VariableList& xList_) { int iDeepestIndex = -1; VariableID eBest = -1; for (int i=0; i<xList_.iCount(); i++) { VariableID eID = xList_.iVariable(i); if (_aIDToPosition[eID] > iDeepestIndex) { iDeepestIndex = _aIDToPosition[eID]; eBest = eID; } } return eBest; } void SATSolver::_vPrintStack() { int k; int iBranchDepth = 0; for (k=0; k<_iCurrentVariable; k++) { VariableID eWorkID = _aPositionToID[k]; if (_aVariableStruct[eWorkID].bBranch) { iBranchDepth++; } } xOutputStream << "c Stats: BD=" << iBranchDepth << ", BP=" << _iBranchSelections << ", CD=" << _iContradictions << ", LC=" << _xLearnedClauses.iClauseCount() << ", RLC=" << _iRelevantClauses << endl; if (_iSolutionCount && !_bFindAll) { xOutputStream << "c Solutions: "; char* aBuffer = _xKnownSolutions.aToString(); xOutputStream << aBuffer << endl; delete [] aBuffer; } xOutputStream << "c Stack: "; int iNoBranch = 0; for (k=0; k<_iCurrentVariable; k++) { VariableID eWorkID = _aPositionToID[k]; if (_aVariableStruct[eWorkID].bBranch) { xOutputStream << iNoBranch << ' '; //xOutputStream << iNoBranch << " (" << eWorkID+1 << ") "; iNoBranch = 0; } else { iNoBranch++; } } if (iNoBranch) xOutputStream << iNoBranch; xOutputStream << endl; } void SATSolver::_vCleanup() { delete [] _aAssignment; delete [] _aVariableStruct; delete [] _aPositionToID; delete [] _aIDToPosition; delete [] _aScore0; delete [] _aScore1; delete [] _aScore; delete [] _aBinaryCount0; delete [] _aBinaryCount1; delete _pUnitVariables0; delete _pUnitVariables1; delete _pUnitList; delete _pPositiveBackup; delete _pNegativeBackup; delete _pGoodList; delete _pGoodReason; } inline void SATSolver::_vDecideFilterClause(VariableID eID, Clause* pWorkClause) { if (_bFavorSmallClauses && _aVariableStruct[eID].pReason->iVariableCount() > pWorkClause->iVariableCount()) { _aVariableStruct[eID].pReason = pWorkClause; } else { if (xRandom.bRandom()) { _aVariableStruct[eID].pReason = pWorkClause; } } } boolean SATSolver::_bNonTrivialUnitPropagate(ClauseList& xUnitClauses_) { // Returns 1 if contradiction is reached Clause** pStart = xUnitClauses_.pEntry(0); Clause** pEnd = xUnitClauses_.pLastEntry(); for (; pStart < pEnd; pStart++) { Clause* pClause = *pStart; VariableID eUnitVar; int x; for (x=0; ; x++) { assert(x<pClause->iPermaCount()); if (_aAssignment[pClause->eConstrainedVariable(x)] == NON_VALUE) { eUnitVar = pClause->eConstrainedVariable(x); break; } } if (!_pGoodList->bHasVariable(eUnitVar)) { continue; } if (pClause->iIsNegated(x)) { if (!_aVariableStruct[eUnitVar].pReason) { assert(!_pUnitVariables1->bHasVariable(eUnitVar)); _pUnitVariables0->vAddVariableNoCheck(eUnitVar); _aVariableStruct[eUnitVar].pReason = pClause; } else if (_pUnitVariables1->bHasVariable(eUnitVar)) { _vSetContradiction(eUnitVar, pClause); xUnitClauses_.vClear(); return 1; } else { assert(_pUnitVariables0->bHasVariable(eUnitVar)); _vDecideFilterClause(eUnitVar, pClause); } } else { if (!_aVariableStruct[eUnitVar].pReason) { assert(!_pUnitVariables0->bHasVariable(eUnitVar)); _pUnitVariables1->vAddVariableNoCheck(eUnitVar); _aVariableStruct[eUnitVar].pReason = pClause; } else if (_pUnitVariables0->bHasVariable(eUnitVar)) { _vSetContradiction(eUnitVar, pClause); xUnitClauses_.vClear(); return 1; } else { assert(_pUnitVariables1->bHasVariable(eUnitVar)); _vDecideFilterClause(eUnitVar, pClause); } } } xUnitClauses_.vClear(); return 0; } void SATSolver::_vUndoClauseModifications() { Clause** pStart1; Clause** pEnd1; Clause** pStart2; Clause** pEnd2; VariableStruct* pWork = &(_aVariableStruct[_eCurrentID]); if (_aAssignment[_eCurrentID] == 1) { pStart1 = pWork->xNegativeClauses.pEntry(0); pEnd1 = pWork->xNegativeClauses.pLastEntry(); pStart2 = pWork->xPositiveClauses.pEntry(0); pEnd2 = pWork->xPositiveClauses.pLastEntry(); } else { pStart2 = pWork->xNegativeClauses.pEntry(0); pEnd2 = pWork->xNegativeClauses.pLastEntry(); pStart1 = pWork->xPositiveClauses.pEntry(0); pEnd1 = pWork->xPositiveClauses.pLastEntry(); } Clause* pWorkClause; int j; for (;pStart1 < pEnd1; pStart1++) { pWorkClause = *pStart1; if (pWorkClause->iExpand() == 3) { for (j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount0[pWorkClause->eConstrainedVariable(j)] >= 0); } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]--; assert(_aBinaryCount1[pWorkClause->eConstrainedVariable(j)] >= 0); } } } } for (;pStart2 < pEnd2; pStart2++) { pWorkClause = *pStart2; pWorkClause->vMakeUnsatisfied(); if (!pWorkClause->bIsSatisfied()) { if (pWorkClause->iWorkingLength() == 2) { for (j=0; j<pWorkClause->iPermaCount(); j++) { if (pWorkClause->iIsNegated(j)) { _aBinaryCount0[pWorkClause->eConstrainedVariable(j)]++; } else { _aBinaryCount1[pWorkClause->eConstrainedVariable(j)]++; } } } } } _vDeleteClauses(pWork->xDeleteList); } boolean SATSolver::_bTimeLimitExpired() { time_t iCheckTime; if (!_bNoTimeLimit) { time(&iCheckTime); if (iCheckTime - _iElapsedTime >= _iMaxTime) { return 1; } } return 0; } boolean SATSolver::_bPrintStackCheck() { time_t iCheckTime; if (_bPrintStack) { time(&iCheckTime); if (iCheckTime - _iLastCheckTime >= _iPrintStackPeriod) { _iLastCheckTime = iCheckTime; return true; } } return false; }
49,344
19,124
#include "file.hpp" #include "path.hpp" #include "../Optional.hpp" #include "../config.hpp" #include <fstream> #if defined(MT_UNIX) #include <sys/stat.h> #endif #if MT_IS_MSVC #include <windows.h> #endif namespace mt::fs { Optional<std::unique_ptr<std::string>> read_file(const FilePath& path) { std::ifstream ifs(path.str()); if (!ifs) { return NullOpt{}; } auto contents = std::make_unique<std::string>((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return Optional<std::unique_ptr<std::string>>(std::move(contents)); } #if defined(MT_UNIX) bool file_exists(const FilePath& path) { struct stat sb; const int status = stat(path.c_str(), &sb); if (status != 0) { return false; } return (sb.st_mode & S_IFMT) == S_IFREG; } #elif defined(MT_WIN) bool file_exists(const FilePath& path) { return !(INVALID_FILE_ATTRIBUTES == GetFileAttributes(path.c_str()) && GetLastError() == ERROR_FILE_NOT_FOUND); } #else #error "Expected one of Unix or Windows for OS." #endif }
1,088
401
#ifdef ZIMG_X86 #include "common/ccdep.h" #include <immintrin.h> #include "common/align.h" #include "f16c_x86.h" #include "common/x86/sse2_util.h" #include "common/x86/avx_util.h" namespace zimg { namespace depth { void f16c_half_to_float_ivb(const void *src, void *dst, unsigned left, unsigned right) { const uint16_t *src_p = static_cast<const uint16_t *>(src); float *dst_p = static_cast<float *>(dst); unsigned vec_left = ceil_n(left, 8); unsigned vec_right = floor_n(right, 8); if (left != vec_left) { __m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + vec_left - 8))); mm256_store_idxhi_ps(dst_p + vec_left - 8, x, left % 8); } for (unsigned j = vec_left; j < vec_right; j += 8) { __m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + j))); _mm256_store_ps(dst_p + j, x); } if (right != vec_right) { __m256 x = _mm256_cvtph_ps(_mm_load_si128((const __m128i *)(src_p + vec_right))); mm256_store_idxlo_ps(dst_p + vec_right, x, right % 8); } } void f16c_float_to_half_ivb(const void *src, void *dst, unsigned left, unsigned right) { const float *src_p = static_cast<const float *>(src); uint16_t *dst_p = static_cast<uint16_t *>(dst); unsigned vec_left = ceil_n(left, 8); unsigned vec_right = floor_n(right, 8); if (left != vec_left) { __m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + vec_left - 8), 0); mm_store_idxhi_epi16((__m128i *)(dst_p + vec_left - 8), x, left % 8); } for (unsigned j = vec_left; j < vec_right; j += 8) { __m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + j), 0); _mm_store_si128((__m128i *)(dst_p + j), x); } if (right != vec_right) { __m128i x = _mm256_cvtps_ph(_mm256_load_ps(src_p + vec_right), 0); mm_store_idxlo_epi16((__m128i *)(dst_p + vec_right), x, right % 8); } } } // namespace depth } // namespace zimg #endif // ZIMG_X86
1,855
940
// Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_ #define ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_ namespace absl { namespace debug_internal { // Return whether the byte at *addr is readable, without faulting. // Save and restores errno. bool AddressIsReadable(const void *addr); } // namespace debug_internal } // namespace absl #endif // ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_ /* * Copyright 2017 The Abseil Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Allow dynamic symbol lookup for in-memory Elf images. #ifndef ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_ #define ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_ // Including this will define the __GLIBC__ macro if glibc is being // used. #include <climits> // Maybe one day we can rewrite this file not to require the elf // symbol extensions in glibc, but for right now we need them. #ifdef ABSL_HAVE_ELF_MEM_IMAGE #error ABSL_HAVE_ELF_MEM_IMAGE cannot be directly set #endif #if defined(__ELF__) && defined(__GLIBC__) && !defined(__native_client__) && \ !defined(__asmjs__) #define ABSL_HAVE_ELF_MEM_IMAGE 1 #endif #if ABSL_HAVE_ELF_MEM_IMAGE #include <link.h> // for ElfW namespace absl { namespace debug_internal { // An in-memory ELF image (may not exist on disk). class ElfMemImage { public: // Sentinel: there could never be an elf image at this address. static const void *const kInvalidBase; // Information about a single vdso symbol. // All pointers are into .dynsym, .dynstr, or .text of the VDSO. // Do not free() them or modify through them. struct SymbolInfo { const char *name; // E.g. "__vdso_getcpu" const char *version; // E.g. "LINUX_2.6", could be "" // for unversioned symbol. const void *address; // Relocated symbol address. const ElfW(Sym) *symbol; // Symbol in the dynamic symbol table. }; // Supports iteration over all dynamic symbols. class SymbolIterator { public: friend class ElfMemImage; const SymbolInfo *operator->() const; const SymbolInfo &operator*() const; SymbolIterator& operator++(); bool operator!=(const SymbolIterator &rhs) const; bool operator==(const SymbolIterator &rhs) const; private: SymbolIterator(const void *const image, int index); void Update(int incr); SymbolInfo info_; int index_; const void *const image_; }; explicit ElfMemImage(const void *base); void Init(const void *base); bool IsPresent() const { return ehdr_ != nullptr; } const ElfW(Phdr)* GetPhdr(int index) const; const ElfW(Sym)* GetDynsym(int index) const; const ElfW(Versym)* GetVersym(int index) const; const ElfW(Verdef)* GetVerdef(int index) const; const ElfW(Verdaux)* GetVerdefAux(const ElfW(Verdef) *verdef) const; const char* GetDynstr(ElfW(Word) offset) const; const void* GetSymAddr(const ElfW(Sym) *sym) const; const char* GetVerstr(ElfW(Word) offset) const; int GetNumSymbols() const; SymbolIterator begin() const; SymbolIterator end() const; // Look up versioned dynamic symbol in the image. // Returns false if image is not present, or doesn't contain given // symbol/version/type combination. // If info_out is non-null, additional details are filled in. bool LookupSymbol(const char *name, const char *version, int symbol_type, SymbolInfo *info_out) const; // Find info about symbol (if any) which overlaps given address. // Returns true if symbol was found; false if image isn't present // or doesn't have a symbol overlapping given address. // If info_out is non-null, additional details are filled in. bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const; private: const ElfW(Ehdr) *ehdr_; const ElfW(Sym) *dynsym_; const ElfW(Versym) *versym_; const ElfW(Verdef) *verdef_; const ElfW(Word) *hash_; const char *dynstr_; size_t strsize_; size_t verdefnum_; ElfW(Addr) link_base_; // Link-time base (p_vaddr of first PT_LOAD). }; } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE #endif // ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_ /* * Copyright 2017 The Abseil Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Defines ABSL_STACKTRACE_INL_HEADER to the *-inl.h containing * actual unwinder implementation. * This header is "private" to stacktrace.cc. * DO NOT include it into any other files. */ #ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_ #define ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_ // First, test platforms which only support a stub. #if ABSL_STACKTRACE_INL_HEADER #error ABSL_STACKTRACE_INL_HEADER cannot be directly set #elif defined(__native_client__) || defined(__APPLE__) || \ defined(__ANDROID__) || defined(__myriad2__) || defined(asmjs__) || \ defined(__Fuchsia__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_unimplemented-inl.inc" // Next, test for Mips and Windows. // TODO(marmstrong): Mips case, remove the check for ABSL_STACKTRACE_INL_HEADER #elif defined(__mips__) && !defined(ABSL_STACKTRACE_INL_HEADER) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_unimplemented-inl.inc" #elif defined(_WIN32) // windows #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_win32-inl.inc" // Finally, test NO_FRAME_POINTER. #elif !defined(NO_FRAME_POINTER) # if defined(__i386__) || defined(__x86_64__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_x86-inl.inc" # elif defined(__ppc__) || defined(__PPC__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_powerpc-inl.inc" # elif defined(__aarch64__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_aarch64-inl.inc" # elif defined(__arm__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_arm-inl.inc" # endif #else // defined(NO_FRAME_POINTER) # if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_unimplemented-inl.inc" # elif defined(__ppc__) || defined(__PPC__) // Use glibc's backtrace. #define ABSL_STACKTRACE_INL_HEADER \ "stacktrace_internal/stacktrace_generic-inl.inc" # elif defined(__arm__) # error stacktrace without frame pointer is not supported on ARM # endif #endif // NO_FRAME_POINTER #if !defined(ABSL_STACKTRACE_INL_HEADER) #error Not supported yet #endif #endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSO stands for "Virtual Dynamic Shared Object" -- a page of // executable code, which looks like a shared library, but doesn't // necessarily exist anywhere on disk, and which gets mmap()ed into // every process by kernels which support VDSO, such as 2.6.x for 32-bit // executables, and 2.6.24 and above for 64-bit executables. // // More details could be found here: // http://www.trilithium.com/johan/2005/08/linux-gate/ // // VDSOSupport -- a class representing kernel VDSO (if present). // // Example usage: // VDSOSupport vdso; // VDSOSupport::SymbolInfo info; // typedef (*FN)(unsigned *, void *, void *); // FN fn = nullptr; // if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) { // fn = reinterpret_cast<FN>(info.address); // } #ifndef ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ #define ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ #include <atomic> #ifdef ABSL_HAVE_ELF_MEM_IMAGE #ifdef ABSL_HAVE_VDSO_SUPPORT #error ABSL_HAVE_VDSO_SUPPORT cannot be directly set #else #define ABSL_HAVE_VDSO_SUPPORT 1 #endif namespace absl { namespace debug_internal { // NOTE: this class may be used from within tcmalloc, and can not // use any memory allocation routines. class VDSOSupport { public: VDSOSupport(); typedef ElfMemImage::SymbolInfo SymbolInfo; typedef ElfMemImage::SymbolIterator SymbolIterator; // On PowerPC64 VDSO symbols can either be of type STT_FUNC or STT_NOTYPE // depending on how the kernel is built. The kernel is normally built with // STT_NOTYPE type VDSO symbols. Let's make things simpler first by using a // compile-time constant. #ifdef __powerpc64__ enum { kVDSOSymbolType = STT_NOTYPE }; #else enum { kVDSOSymbolType = STT_FUNC }; #endif // Answers whether we have a vdso at all. bool IsPresent() const { return image_.IsPresent(); } // Allow to iterate over all VDSO symbols. SymbolIterator begin() const { return image_.begin(); } SymbolIterator end() const { return image_.end(); } // Look up versioned dynamic symbol in the kernel VDSO. // Returns false if VDSO is not present, or doesn't contain given // symbol/version/type combination. // If info_out != nullptr, additional details are filled in. bool LookupSymbol(const char *name, const char *version, int symbol_type, SymbolInfo *info_out) const; // Find info about symbol (if any) which overlaps given address. // Returns true if symbol was found; false if VDSO isn't present // or doesn't have a symbol overlapping given address. // If info_out != nullptr, additional details are filled in. bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const; // Used only for testing. Replace real VDSO base with a mock. // Returns previous value of vdso_base_. After you are done testing, // you are expected to call SetBase() with previous value, in order to // reset state to the way it was. const void *SetBase(const void *s); // Computes vdso_base_ and returns it. Should be called as early as // possible; before any thread creation, chroot or setuid. static const void *Init(); private: // image_ represents VDSO ELF image in memory. // image_.ehdr_ == nullptr implies there is no VDSO. ElfMemImage image_; // Cached value of auxv AT_SYSINFO_EHDR, computed once. // This is a tri-state: // kInvalidBase => value hasn't been determined yet. // 0 => there is no VDSO. // else => vma of VDSO Elf{32,64}_Ehdr. // // When testing with mock VDSO, low bit is set. // The low bit is always available because vdso_base_ is // page-aligned. static std::atomic<const void *> vdso_base_; // NOLINT on 'long' because these routines mimic kernel api. // The 'cache' parameter may be used by some versions of the kernel, // and should be nullptr or point to a static buffer containing at // least two 'long's. static long InitAndGetCPU(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); static long GetCPUViaSyscall(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); typedef long (*GetCpuFn)(unsigned *cpu, void *cache, // NOLINT 'long'. void *unused); // This function pointer may point to InitAndGetCPU, // GetCPUViaSyscall, or __vdso_getcpu at different stages of initialization. static std::atomic<GetCpuFn> getcpu_fn_; friend int GetCPU(void); // Needs access to getcpu_fn_. VDSOSupport(const VDSOSupport&) = delete; VDSOSupport& operator=(const VDSOSupport&) = delete; }; // Same as sched_getcpu() on later glibc versions. // Return current CPU, using (fast) __vdso_getcpu@LINUX_2.6 if present, // otherwise use syscall(SYS_getcpu,...). // May return -1 with errno == ENOSYS if the kernel doesn't // support SYS_getcpu. int GetCPU(); } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE #endif // ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_ // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This header file defines macros for declaring attributes for functions, // types, and variables. // // These macros are used within Abseil and allow the compiler to optimize, where // applicable, certain function calls. // // This file is used for both C and C++! // // Most macros here are exposing GCC or Clang features, and are stubbed out for // other compilers. // // GCC attributes documentation: // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Variable-Attributes.html // https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Type-Attributes.html // // Most attributes in this file are already supported by GCC 4.7. However, some // of them are not supported in older version of Clang. Thus, we check // `__has_attribute()` first. If the check fails, we check if we are on GCC and // assume the attribute exists on GCC (which is verified on GCC 4.7). // // ----------------------------------------------------------------------------- // Sanitizer Attributes // ----------------------------------------------------------------------------- // // Sanitizer-related attributes are not "defined" in this file (and indeed // are not defined as such in any file). To utilize the following // sanitizer-related attributes within your builds, define the following macros // within your build using a `-D` flag, along with the given value for // `-fsanitize`: // // * `ADDRESS_SANITIZER` + `-fsanitize=address` (Clang, GCC 4.8) // * `MEMORY_SANITIZER` + `-fsanitize=memory` (Clang-only) // * `THREAD_SANITIZER + `-fsanitize=thread` (Clang, GCC 4.8+) // * `UNDEFINED_BEHAVIOR_SANITIZER` + `-fsanitize=undefined` (Clang, GCC 4.9+) // * `CONTROL_FLOW_INTEGRITY` + -fsanitize=cfi (Clang-only) // // Example: // // // Enable branches in the Abseil code that are tagged for ASan: // $ bazel -D ADDRESS_SANITIZER -fsanitize=address *target* // // Since these macro names are only supported by GCC and Clang, we only check // for `__GNUC__` (GCC or Clang) and the above macros. #ifndef ABSL_BASE_ATTRIBUTES_H_ #define ABSL_BASE_ATTRIBUTES_H_ // ABSL_HAVE_ATTRIBUTE // // A function-like feature checking macro that is a wrapper around // `__has_attribute`, which is defined by GCC 5+ and Clang and evaluates to a // nonzero constant integer if the attribute is supported or 0 if not. // // It evaluates to zero if `__has_attribute` is not defined by the compiler. // // GCC: https://gcc.gnu.org/gcc-5/changes.html // Clang: https://clang.llvm.org/docs/LanguageExtensions.html #ifdef __has_attribute #define ABSL_HAVE_ATTRIBUTE(x) __has_attribute(x) #else #define ABSL_HAVE_ATTRIBUTE(x) 0 #endif // ABSL_HAVE_CPP_ATTRIBUTE // // A function-like feature checking macro that accepts C++11 style attributes. // It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6 // (http://en.cppreference.com/w/cpp/experimental/feature_test). If we don't // find `__has_cpp_attribute`, will evaluate to 0. #if defined(__cplusplus) && defined(__has_cpp_attribute) // NOTE: requiring __cplusplus above should not be necessary, but // works around https://bugs.llvm.org/show_bug.cgi?id=23435. #define ABSL_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) #else #define ABSL_HAVE_CPP_ATTRIBUTE(x) 0 #endif // ----------------------------------------------------------------------------- // Function Attributes // ----------------------------------------------------------------------------- // // GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html // Clang: https://clang.llvm.org/docs/AttributeReference.html // ABSL_PRINTF_ATTRIBUTE // ABSL_SCANF_ATTRIBUTE // // Tells the compiler to perform `printf` format std::string checking if the // compiler supports it; see the 'format' attribute in // <http://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html>. // // Note: As the GCC manual states, "[s]ince non-static C++ methods // have an implicit 'this' argument, the arguments of such methods // should be counted from two, not one." #if ABSL_HAVE_ATTRIBUTE(format) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check) \ __attribute__((__format__(__printf__, string_index, first_to_check))) #define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) \ __attribute__((__format__(__scanf__, string_index, first_to_check))) #else #define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check) #define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) #endif // ABSL_ATTRIBUTE_ALWAYS_INLINE // ABSL_ATTRIBUTE_NOINLINE // // Forces functions to either inline or not inline. Introduced in gcc 3.1. #if ABSL_HAVE_ATTRIBUTE(always_inline) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline)) #define ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE 1 #else #define ABSL_ATTRIBUTE_ALWAYS_INLINE #endif #if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_NOINLINE __attribute__((noinline)) #define ABSL_HAVE_ATTRIBUTE_NOINLINE 1 #else #define ABSL_ATTRIBUTE_NOINLINE #endif // ABSL_ATTRIBUTE_NO_TAIL_CALL // // Prevents the compiler from optimizing away stack frames for functions which // end in a call to another function. #if ABSL_HAVE_ATTRIBUTE(disable_tail_calls) #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 1 #define ABSL_ATTRIBUTE_NO_TAIL_CALL __attribute__((disable_tail_calls)) #elif defined(__GNUC__) && !defined(__clang__) #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 1 #define ABSL_ATTRIBUTE_NO_TAIL_CALL \ __attribute__((optimize("no-optimize-sibling-calls"))) #else #define ABSL_ATTRIBUTE_NO_TAIL_CALL #define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 0 #endif // ABSL_ATTRIBUTE_WEAK // // Tags a function as weak for the purposes of compilation and linking. #if ABSL_HAVE_ATTRIBUTE(weak) || (defined(__GNUC__) && !defined(__clang__)) #undef ABSL_ATTRIBUTE_WEAK #define ABSL_ATTRIBUTE_WEAK __attribute__((weak)) #define ABSL_HAVE_ATTRIBUTE_WEAK 1 #else #define ABSL_ATTRIBUTE_WEAK #define ABSL_HAVE_ATTRIBUTE_WEAK 0 #endif // ABSL_ATTRIBUTE_NONNULL // // Tells the compiler either (a) that a particular function parameter // should be a non-null pointer, or (b) that all pointer arguments should // be non-null. // // Note: As the GCC manual states, "[s]ince non-static C++ methods // have an implicit 'this' argument, the arguments of such methods // should be counted from two, not one." // // Args are indexed starting at 1. // // For non-static class member functions, the implicit `this` argument // is arg 1, and the first explicit argument is arg 2. For static class member // functions, there is no implicit `this`, and the first explicit argument is // arg 1. // // Example: // // /* arg_a cannot be null, but arg_b can */ // void Function(void* arg_a, void* arg_b) ABSL_ATTRIBUTE_NONNULL(1); // // class C { // /* arg_a cannot be null, but arg_b can */ // void Method(void* arg_a, void* arg_b) ABSL_ATTRIBUTE_NONNULL(2); // // /* arg_a cannot be null, but arg_b can */ // static void StaticMethod(void* arg_a, void* arg_b) // ABSL_ATTRIBUTE_NONNULL(1); // }; // // If no arguments are provided, then all pointer arguments should be non-null. // // /* No pointer arguments may be null. */ // void Function(void* arg_a, void* arg_b, int arg_c) ABSL_ATTRIBUTE_NONNULL(); // // NOTE: The GCC nonnull attribute actually accepts a list of arguments, but // ABSL_ATTRIBUTE_NONNULL does not. #if ABSL_HAVE_ATTRIBUTE(nonnull) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_NONNULL(arg_index) __attribute__((nonnull(arg_index))) #else #define ABSL_ATTRIBUTE_NONNULL(...) #endif // ABSL_ATTRIBUTE_NORETURN // // Tells the compiler that a given function never returns. #if ABSL_HAVE_ATTRIBUTE(noreturn) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_NORETURN __attribute__((noreturn)) #elif defined(_MSC_VER) #define ABSL_ATTRIBUTE_NORETURN __declspec(noreturn) #else #define ABSL_ATTRIBUTE_NORETURN #endif // ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // // Tells the AddressSanitizer (or other memory testing tools) to ignore a given // function. Useful for cases when a function reads random locations on stack, // calls _exit from a cloned subprocess, deliberately accesses buffer // out of bounds or does other scary things with memory. // NOTE: GCC supports AddressSanitizer(asan) since 4.8. // https://gcc.gnu.org/gcc-4.8/changes.html #if defined(__GNUC__) && defined(ADDRESS_SANITIZER) #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS #endif // ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // // Tells the MemorySanitizer to relax the handling of a given function. All // "Use of uninitialized value" warnings from such functions will be suppressed, // and all values loaded from memory will be considered fully initialized. // This attribute is similar to the ADDRESS_SANITIZER attribute above, but deals // with initialized-ness rather than addressability issues. // NOTE: MemorySanitizer(msan) is supported by Clang but not GCC. #if defined(__GNUC__) && defined(MEMORY_SANITIZER) #define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY #endif // ABSL_ATTRIBUTE_NO_SANITIZE_THREAD // // Tells the ThreadSanitizer to not instrument a given function. // NOTE: GCC supports ThreadSanitizer(tsan) since 4.8. // https://gcc.gnu.org/gcc-4.8/changes.html #if defined(__GNUC__) && defined(THREAD_SANITIZER) #define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread)) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD #endif // ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED // // Tells the UndefinedSanitizer to ignore a given function. Useful for cases // where certain behavior (eg. devision by zero) is being used intentionally. // NOTE: GCC supports UndefinedBehaviorSanitizer(ubsan) since 4.9. // https://gcc.gnu.org/gcc-4.9/changes.html #if defined(__GNUC__) && \ (defined(UNDEFINED_BEHAVIOR_SANITIZER) || defined(ADDRESS_SANITIZER)) #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED \ __attribute__((no_sanitize("undefined"))) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED #endif // ABSL_ATTRIBUTE_NO_SANITIZE_CFI // // Tells the ControlFlowIntegrity sanitizer to not instrument a given function. // See https://clang.llvm.org/docs/ControlFlowIntegrity.html for details. #if defined(__GNUC__) && defined(CONTROL_FLOW_INTEGRITY) #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI __attribute__((no_sanitize("cfi"))) #else #define ABSL_ATTRIBUTE_NO_SANITIZE_CFI #endif // ABSL_HAVE_ATTRIBUTE_SECTION // // Indicates whether labeled sections are supported. Labeled sections are not // supported on Darwin/iOS. #ifdef ABSL_HAVE_ATTRIBUTE_SECTION #error ABSL_HAVE_ATTRIBUTE_SECTION cannot be directly set #elif (ABSL_HAVE_ATTRIBUTE(section) || \ (defined(__GNUC__) && !defined(__clang__))) && \ !defined(__APPLE__) #define ABSL_HAVE_ATTRIBUTE_SECTION 1 // ABSL_ATTRIBUTE_SECTION // // Tells the compiler/linker to put a given function into a section and define // `__start_ ## name` and `__stop_ ## name` symbols to bracket the section. // This functionality is supported by GNU linker. Any function annotated with // `ABSL_ATTRIBUTE_SECTION` must not be inlined, or it will be placed into // whatever section its caller is placed into. // #ifndef ABSL_ATTRIBUTE_SECTION #define ABSL_ATTRIBUTE_SECTION(name) \ __attribute__((section(#name))) __attribute__((noinline)) #endif // ABSL_ATTRIBUTE_SECTION_VARIABLE // // Tells the compiler/linker to put a given variable into a section and define // `__start_ ## name` and `__stop_ ## name` symbols to bracket the section. // This functionality is supported by GNU linker. #ifndef ABSL_ATTRIBUTE_SECTION_VARIABLE #define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) __attribute__((section(#name))) #endif // ABSL_DECLARE_ATTRIBUTE_SECTION_VARS // // A weak section declaration to be used as a global declaration // for ABSL_ATTRIBUTE_SECTION_START|STOP(name) to compile and link // even without functions with ABSL_ATTRIBUTE_SECTION(name). // ABSL_DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's // a no-op on ELF but not on Mach-O. // #ifndef ABSL_DECLARE_ATTRIBUTE_SECTION_VARS #define ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) \ extern char __start_##name[] ABSL_ATTRIBUTE_WEAK; \ extern char __stop_##name[] ABSL_ATTRIBUTE_WEAK #endif #ifndef ABSL_DEFINE_ATTRIBUTE_SECTION_VARS #define ABSL_INIT_ATTRIBUTE_SECTION_VARS(name) #define ABSL_DEFINE_ATTRIBUTE_SECTION_VARS(name) #endif // ABSL_ATTRIBUTE_SECTION_START // // Returns `void*` pointers to start/end of a section of code with // functions having ABSL_ATTRIBUTE_SECTION(name). // Returns 0 if no such functions exist. // One must ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and // link. // #define ABSL_ATTRIBUTE_SECTION_START(name) \ (reinterpret_cast<void *>(__start_##name)) #define ABSL_ATTRIBUTE_SECTION_STOP(name) \ (reinterpret_cast<void *>(__stop_##name)) #else // !ABSL_HAVE_ATTRIBUTE_SECTION #define ABSL_HAVE_ATTRIBUTE_SECTION 0 // provide dummy definitions #define ABSL_ATTRIBUTE_SECTION(name) #define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) #define ABSL_INIT_ATTRIBUTE_SECTION_VARS(name) #define ABSL_DEFINE_ATTRIBUTE_SECTION_VARS(name) #define ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) #define ABSL_ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void *>(0)) #define ABSL_ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void *>(0)) #endif // ABSL_ATTRIBUTE_SECTION // ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC // // Support for aligning the stack on 32-bit x86. #if ABSL_HAVE_ATTRIBUTE(force_align_arg_pointer) || \ (defined(__GNUC__) && !defined(__clang__)) #if defined(__i386__) #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \ __attribute__((force_align_arg_pointer)) #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #elif defined(__x86_64__) #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (1) #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC #else // !__i386__ && !__x86_64 #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC #endif // __i386__ #else #define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC #define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0) #endif // ABSL_MUST_USE_RESULT // // Tells the compiler to warn about unused return values for functions declared // with this macro. The macro must appear as the very first part of a function // declaration or definition: // // Example: // // ABSL_MUST_USE_RESULT Sprocket* AllocateSprocket(); // // This placement has the broadest compatibility with GCC, Clang, and MSVC, with // both defs and decls, and with GCC-style attributes, MSVC declspec, C++11 // and C++17 attributes. // // ABSL_MUST_USE_RESULT allows using cast-to-void to suppress the unused result // warning. For that, warn_unused_result is used only for clang but not for gcc. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425 // // Note: past advice was to place the macro after the argument list. #if ABSL_HAVE_ATTRIBUTE(nodiscard) #define ABSL_MUST_USE_RESULT [[nodiscard]] #elif defined(__clang__) && ABSL_HAVE_ATTRIBUTE(warn_unused_result) #define ABSL_MUST_USE_RESULT __attribute__((warn_unused_result)) #else #define ABSL_MUST_USE_RESULT #endif // ABSL_ATTRIBUTE_HOT, ABSL_ATTRIBUTE_COLD // // Tells GCC that a function is hot or cold. GCC can use this information to // improve static analysis, i.e. a conditional branch to a cold function // is likely to be not-taken. // This annotation is used for function declarations. // // Example: // // int foo() ABSL_ATTRIBUTE_HOT; #if ABSL_HAVE_ATTRIBUTE(hot) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_HOT __attribute__((hot)) #else #define ABSL_ATTRIBUTE_HOT #endif #if ABSL_HAVE_ATTRIBUTE(cold) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_COLD __attribute__((cold)) #else #define ABSL_ATTRIBUTE_COLD #endif // ABSL_XRAY_ALWAYS_INSTRUMENT, ABSL_XRAY_NEVER_INSTRUMENT, ABSL_XRAY_LOG_ARGS // // We define the ABSL_XRAY_ALWAYS_INSTRUMENT and ABSL_XRAY_NEVER_INSTRUMENT // macro used as an attribute to mark functions that must always or never be // instrumented by XRay. Currently, this is only supported in Clang/LLVM. // // For reference on the LLVM XRay instrumentation, see // http://llvm.org/docs/XRay.html. // // A function with the XRAY_ALWAYS_INSTRUMENT macro attribute in its declaration // will always get the XRay instrumentation sleds. These sleds may introduce // some binary size and runtime overhead and must be used sparingly. // // These attributes only take effect when the following conditions are met: // // * The file/target is built in at least C++11 mode, with a Clang compiler // that supports XRay attributes. // * The file/target is built with the -fxray-instrument flag set for the // Clang/LLVM compiler. // * The function is defined in the translation unit (the compiler honors the // attribute in either the definition or the declaration, and must match). // // There are cases when, even when building with XRay instrumentation, users // might want to control specifically which functions are instrumented for a // particular build using special-case lists provided to the compiler. These // special case lists are provided to Clang via the // -fxray-always-instrument=... and -fxray-never-instrument=... flags. The // attributes in source take precedence over these special-case lists. // // To disable the XRay attributes at build-time, users may define // ABSL_NO_XRAY_ATTRIBUTES. Do NOT define ABSL_NO_XRAY_ATTRIBUTES on specific // packages/targets, as this may lead to conflicting definitions of functions at // link-time. // #if ABSL_HAVE_CPP_ATTRIBUTE(clang::xray_always_instrument) && \ !defined(ABSL_NO_XRAY_ATTRIBUTES) #define ABSL_XRAY_ALWAYS_INSTRUMENT [[clang::xray_always_instrument]] #define ABSL_XRAY_NEVER_INSTRUMENT [[clang::xray_never_instrument]] #if ABSL_HAVE_CPP_ATTRIBUTE(clang::xray_log_args) #define ABSL_XRAY_LOG_ARGS(N) \ [[clang::xray_always_instrument, clang::xray_log_args(N)]] #else #define ABSL_XRAY_LOG_ARGS(N) [[clang::xray_always_instrument]] #endif #else #define ABSL_XRAY_ALWAYS_INSTRUMENT #define ABSL_XRAY_NEVER_INSTRUMENT #define ABSL_XRAY_LOG_ARGS(N) #endif // ----------------------------------------------------------------------------- // Variable Attributes // ----------------------------------------------------------------------------- // ABSL_ATTRIBUTE_UNUSED // // Prevents the compiler from complaining about or optimizing away variables // that appear unused. #if ABSL_HAVE_ATTRIBUTE(unused) || (defined(__GNUC__) && !defined(__clang__)) #undef ABSL_ATTRIBUTE_UNUSED #define ABSL_ATTRIBUTE_UNUSED __attribute__((__unused__)) #else #define ABSL_ATTRIBUTE_UNUSED #endif // ABSL_ATTRIBUTE_INITIAL_EXEC // // Tells the compiler to use "initial-exec" mode for a thread-local variable. // See http://people.redhat.com/drepper/tls.pdf for the gory details. #if ABSL_HAVE_ATTRIBUTE(tls_model) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_INITIAL_EXEC __attribute__((tls_model("initial-exec"))) #else #define ABSL_ATTRIBUTE_INITIAL_EXEC #endif // ABSL_ATTRIBUTE_PACKED // // Prevents the compiler from padding a structure to natural alignment #if ABSL_HAVE_ATTRIBUTE(packed) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_ATTRIBUTE_PACKED __attribute__((__packed__)) #else #define ABSL_ATTRIBUTE_PACKED #endif // ABSL_CONST_INIT // // A variable declaration annotated with the `ABSL_CONST_INIT` attribute will // not compile (on supported platforms) unless the variable has a constant // initializer. This is useful for variables with static and thread storage // duration, because it guarantees that they will not suffer from the so-called // "static init order fiasco". // // Example: // // ABSL_CONST_INIT static MyType my_var = MakeMyType(...); // // Note that this attribute is redundant if the variable is declared constexpr. #if ABSL_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization) // NOLINTNEXTLINE(whitespace/braces) #define ABSL_CONST_INIT [[clang::require_constant_initialization]] #else #define ABSL_CONST_INIT #endif // ABSL_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization) #endif // ABSL_BASE_ATTRIBUTES_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: config.h // ----------------------------------------------------------------------------- // // This header file defines a set of macros for checking the presence of // important compiler and platform features. Such macros can be used to // produce portable code by parameterizing compilation based on the presence or // lack of a given feature. // // We define a "feature" as some interface we wish to program to: for example, // a library function or system call. A value of `1` indicates support for // that feature; any other value indicates the feature support is undefined. // // Example: // // Suppose a programmer wants to write a program that uses the 'mmap()' system // call. The Abseil macro for that feature (`ABSL_HAVE_MMAP`) allows you to // selectively include the `mmap.h` header and bracket code using that feature // in the macro: // // // #ifdef ABSL_HAVE_MMAP // #include "sys/mman.h" // #endif //ABSL_HAVE_MMAP // // ... // #ifdef ABSL_HAVE_MMAP // void *ptr = mmap(...); // ... // #endif // ABSL_HAVE_MMAP #ifndef ABSL_BASE_CONFIG_H_ #define ABSL_BASE_CONFIG_H_ // Included for the __GLIBC__ macro (or similar macros on other systems). #include <limits.h> #ifdef __cplusplus // Included for __GLIBCXX__, _LIBCPP_VERSION #include <cstddef> #endif // __cplusplus #if defined(__APPLE__) // Included for TARGET_OS_IPHONE, __IPHONE_OS_VERSION_MIN_REQUIRED, // __IPHONE_8_0. #include <Availability.h> #include <TargetConditionals.h> #endif // ----------------------------------------------------------------------------- // Compiler Feature Checks // ----------------------------------------------------------------------------- // ABSL_HAVE_BUILTIN() // // Checks whether the compiler supports a Clang Feature Checking Macro, and if // so, checks whether it supports the provided builtin function "x" where x // is one of the functions noted in // https://clang.llvm.org/docs/LanguageExtensions.html // // Note: Use this macro to avoid an extra level of #ifdef __has_builtin check. // http://releases.llvm.org/3.3/tools/clang/docs/LanguageExtensions.html #ifdef __has_builtin #define ABSL_HAVE_BUILTIN(x) __has_builtin(x) #else #define ABSL_HAVE_BUILTIN(x) 0 #endif // ABSL_HAVE_TLS is defined to 1 when __thread should be supported. // We assume __thread is supported on Linux when compiled with Clang or compiled // against libstdc++ with _GLIBCXX_HAVE_TLS defined. #ifdef ABSL_HAVE_TLS #error ABSL_HAVE_TLS cannot be directly set #elif defined(__linux__) && (defined(__clang__) || defined(_GLIBCXX_HAVE_TLS)) #define ABSL_HAVE_TLS 1 #endif // There are platforms for which TLS should not be used even though the compiler // makes it seem like it's supported (Android NDK < r12b for example). // This is primarily because of linker problems and toolchain misconfiguration: // Abseil does not intend to support this indefinitely. Currently, the newest // toolchain that we intend to support that requires this behavior is the // r11 NDK - allowing for a 5 year support window on that means this option // is likely to be removed around June of 2021. #if defined(__ANDROID__) && defined(__clang__) #if __has_include(<android/ndk-version.h>) #include <android/ndk-version.h> #endif // TLS isn't supported until NDK r12b per // https://developer.android.com/ndk/downloads/revision_history.html // Since NDK r16, `__NDK_MAJOR__` and `__NDK_MINOR__` are defined in // <android/ndk-version.h>. For NDK < r16, users should define these macros, // e.g. `-D__NDK_MAJOR__=11 -D__NKD_MINOR__=0` for NDK r11. #if defined(__NDK_MAJOR__) && defined(__NDK_MINOR__) && \ ((__NDK_MAJOR__ < 12) || ((__NDK_MAJOR__ == 12) && (__NDK_MINOR__ < 1))) #undef ABSL_HAVE_TLS #endif #endif // defined(__ANDROID__) && defined(__clang__) // ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE // // Checks whether `std::is_trivially_destructible<T>` is supported. // // Notes: All supported compilers using libc++ support this feature, as does // gcc >= 4.8.1 using libstdc++, and Visual Studio. #ifdef ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE #error ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE cannot be directly set #elif defined(_LIBCPP_VERSION) || \ (!defined(__clang__) && defined(__GNUC__) && defined(__GLIBCXX__) && \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) || \ defined(_MSC_VER) #define ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE 1 #endif // ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE // // Checks whether `std::is_trivially_default_constructible<T>` and // `std::is_trivially_copy_constructible<T>` are supported. // ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE // // Checks whether `std::is_trivially_copy_assignable<T>` is supported. // Notes: Clang with libc++ supports these features, as does gcc >= 5.1 with // either libc++ or libstdc++, and Visual Studio. #if defined(ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE) #error ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE cannot be directly set #elif defined(ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE) #error ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE cannot directly set #elif (defined(__clang__) && defined(_LIBCPP_VERSION)) || \ (!defined(__clang__) && defined(__GNUC__) && \ (__GNUC__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1)) && \ (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__))) || \ defined(_MSC_VER) #define ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE 1 #define ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE 1 #endif // ABSL_HAVE_THREAD_LOCAL // // Checks whether C++11's `thread_local` storage duration specifier is // supported. #ifdef ABSL_HAVE_THREAD_LOCAL #error ABSL_HAVE_THREAD_LOCAL cannot be directly set #elif !defined(__apple_build_version__) || \ ((__apple_build_version__ >= 8000042) && \ !(TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0)) // Notes: Xcode's clang did not support `thread_local` until version // 8, and even then not for all iOS < 9.0. #define ABSL_HAVE_THREAD_LOCAL 1 #endif // ABSL_HAVE_INTRINSIC_INT128 // // Checks whether the __int128 compiler extension for a 128-bit integral type is // supported. // // Notes: __SIZEOF_INT128__ is defined by Clang and GCC when __int128 is // supported, except on ppc64 and aarch64 where __int128 exists but has exhibits // a sporadic compiler crashing bug. Nvidia's nvcc also defines __GNUC__ and // __SIZEOF_INT128__ but not all versions actually support __int128. #ifdef ABSL_HAVE_INTRINSIC_INT128 #error ABSL_HAVE_INTRINSIC_INT128 cannot be directly set #elif (defined(__clang__) && defined(__SIZEOF_INT128__) && \ !defined(__ppc64__) && !defined(__aarch64__)) || \ (defined(__CUDACC__) && defined(__SIZEOF_INT128__) && \ __CUDACC_VER__ >= 70000) || \ (!defined(__clang__) && !defined(__CUDACC__) && defined(__GNUC__) && \ defined(__SIZEOF_INT128__)) #define ABSL_HAVE_INTRINSIC_INT128 1 #endif // ABSL_HAVE_EXCEPTIONS // // Checks whether the compiler both supports and enables exceptions. Many // compilers support a "no exceptions" mode that disables exceptions. // // Generally, when ABSL_HAVE_EXCEPTIONS is not defined: // // * Code using `throw` and `try` may not compile. // * The `noexcept` specifier will still compile and behave as normal. // * The `noexcept` operator may still return `false`. // // For further details, consult the compiler's documentation. #ifdef ABSL_HAVE_EXCEPTIONS #error ABSL_HAVE_EXCEPTIONS cannot be directly set. #elif defined(__clang__) // TODO(calabrese) // Switch to using __cpp_exceptions when we no longer support versions < 3.6. // For details on this check, see: // http://releases.llvm.org/3.6.0/tools/clang/docs/ReleaseNotes.html#the-exceptions-macro #if defined(__EXCEPTIONS) && __has_feature(cxx_exceptions) #define ABSL_HAVE_EXCEPTIONS 1 #endif // defined(__EXCEPTIONS) && __has_feature(cxx_exceptions) // Handle remaining special cases and default to exceptions being supported. #elif !(defined(__GNUC__) && (__GNUC__ < 5) && !defined(__EXCEPTIONS)) && \ !(defined(__GNUC__) && (__GNUC__ >= 5) && !defined(__cpp_exceptions)) && \ !(defined(_MSC_VER) && !defined(_CPPUNWIND)) #define ABSL_HAVE_EXCEPTIONS 1 #endif // ----------------------------------------------------------------------------- // Platform Feature Checks // ----------------------------------------------------------------------------- // Currently supported operating systems and associated preprocessor // symbols: // // Linux and Linux-derived __linux__ // Android __ANDROID__ (implies __linux__) // Linux (non-Android) __linux__ && !__ANDROID__ // Darwin (Mac OS X and iOS) __APPLE__ // Akaros (http://akaros.org) __ros__ // Windows _WIN32 // NaCL __native_client__ // AsmJS __asmjs__ // Fuschia __Fuchsia__ // // Note that since Android defines both __ANDROID__ and __linux__, one // may probe for either Linux or Android by simply testing for __linux__. // ABSL_HAVE_MMAP // // Checks whether the platform has an mmap(2) implementation as defined in // POSIX.1-2001. #ifdef ABSL_HAVE_MMAP #error ABSL_HAVE_MMAP cannot be directly set #elif defined(__linux__) || defined(__APPLE__) || defined(__ros__) || \ defined(__native_client__) || defined(__asmjs__) || defined(__Fuchsia__) #define ABSL_HAVE_MMAP 1 #endif // ABSL_HAVE_PTHREAD_GETSCHEDPARAM // // Checks whether the platform implements the pthread_(get|set)schedparam(3) // functions as defined in POSIX.1-2001. #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM #error ABSL_HAVE_PTHREAD_GETSCHEDPARAM cannot be directly set #elif defined(__linux__) || defined(__APPLE__) || defined(__ros__) #define ABSL_HAVE_PTHREAD_GETSCHEDPARAM 1 #endif // ABSL_HAVE_SCHED_YIELD // // Checks whether the platform implements sched_yield(2) as defined in // POSIX.1-2001. #ifdef ABSL_HAVE_SCHED_YIELD #error ABSL_HAVE_SCHED_YIELD cannot be directly set #elif defined(__linux__) || defined(__ros__) || defined(__native_client__) #define ABSL_HAVE_SCHED_YIELD 1 #endif // ABSL_HAVE_SEMAPHORE_H // // Checks whether the platform supports the <semaphore.h> header and sem_open(3) // family of functions as standardized in POSIX.1-2001. // // Note: While Apple provides <semaphore.h> for both iOS and macOS, it is // explicitly deprecated and will cause build failures if enabled for those // platforms. We side-step the issue by not defining it here for Apple // platforms. #ifdef ABSL_HAVE_SEMAPHORE_H #error ABSL_HAVE_SEMAPHORE_H cannot be directly set #elif defined(__linux__) || defined(__ros__) #define ABSL_HAVE_SEMAPHORE_H 1 #endif // ABSL_HAVE_ALARM // // Checks whether the platform supports the <signal.h> header and alarm(2) // function as standardized in POSIX.1-2001. #ifdef ABSL_HAVE_ALARM #error ABSL_HAVE_ALARM cannot be directly set #elif defined(__GOOGLE_GRTE_VERSION__) // feature tests for Google's GRTE #define ABSL_HAVE_ALARM 1 #elif defined(__GLIBC__) // feature test for glibc #define ABSL_HAVE_ALARM 1 #elif defined(_MSC_VER) // feature tests for Microsoft's library #elif defined(__native_client__) #else // other standard libraries #define ABSL_HAVE_ALARM 1 #endif // ABSL_IS_LITTLE_ENDIAN // ABSL_IS_BIG_ENDIAN // // Checks the endianness of the platform. // // Notes: uses the built in endian macros provided by GCC (since 4.6) and // Clang (since 3.2); see // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html. // Otherwise, if _WIN32, assume little endian. Otherwise, bail with an error. #if defined(ABSL_IS_BIG_ENDIAN) #error "ABSL_IS_BIG_ENDIAN cannot be directly set." #endif #if defined(ABSL_IS_LITTLE_ENDIAN) #error "ABSL_IS_LITTLE_ENDIAN cannot be directly set." #endif #if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) #define ABSL_IS_LITTLE_ENDIAN 1 #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define ABSL_IS_BIG_ENDIAN 1 #elif defined(_WIN32) #define ABSL_IS_LITTLE_ENDIAN 1 #else #error "absl endian detection needs to be set up for your compiler" #endif // ABSL_HAVE_STD_ANY // // Checks whether C++17 std::any is available by checking whether <any> exists. #ifdef ABSL_HAVE_STD_ANY #error "ABSL_HAVE_STD_ANY cannot be directly set." #endif #ifdef __has_include #if __has_include(<any>) && __cplusplus >= 201703L #define ABSL_HAVE_STD_ANY 1 #endif #endif // ABSL_HAVE_STD_OPTIONAL // // Checks whether C++17 std::optional is available. #ifdef ABSL_HAVE_STD_OPTIONAL #error "ABSL_HAVE_STD_OPTIONAL cannot be directly set." #endif #ifdef __has_include #if __has_include(<optional>) && __cplusplus >= 201703L #define ABSL_HAVE_STD_OPTIONAL 1 #endif #endif // ABSL_HAVE_STD_STRING_VIEW // // Checks whether C++17 std::string_view is available. #ifdef ABSL_HAVE_STD_STRING_VIEW #error "ABSL_HAVE_STD_STRING_VIEW cannot be directly set." #endif #ifdef __has_include #if __has_include(<string_view>) && __cplusplus >= 201703L #define ABSL_HAVE_STD_STRING_VIEW 1 #endif #endif #endif // ABSL_BASE_CONFIG_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: optimization.h // ----------------------------------------------------------------------------- // // This header file defines portable macros for performance optimization. #ifndef ABSL_BASE_OPTIMIZATION_H_ #define ABSL_BASE_OPTIMIZATION_H_ // ABSL_BLOCK_TAIL_CALL_OPTIMIZATION // // Instructs the compiler to avoid optimizing tail-call recursion. Use of this // macro is useful when you wish to preserve the existing function order within // a stack trace for logging, debugging, or profiling purposes. // // Example: // // int f() { // int result = g(); // ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); // return result; // } #if defined(__pnacl__) #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; } #elif defined(__clang__) // Clang will not tail call given inline volatile assembly. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("") #elif defined(__GNUC__) // GCC will not tail call given inline volatile assembly. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("") #elif defined(_MSC_VER) #include <intrin.h> // The __nop() intrinsic blocks the optimisation. #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __nop() #else #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; } #endif // ABSL_CACHELINE_SIZE // // Explicitly defines the size of the L1 cache for purposes of alignment. // Setting the cacheline size allows you to specify that certain objects be // aligned on a cacheline boundary with `ABSL_CACHELINE_ALIGNED` declarations. // (See below.) // // NOTE: this macro should be replaced with the following C++17 features, when // those are generally available: // // * `std::hardware_constructive_interference_size` // * `std::hardware_destructive_interference_size` // // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html // for more information. #if defined(__GNUC__) // Cache line alignment #if defined(__i386__) || defined(__x86_64__) #define ABSL_CACHELINE_SIZE 64 #elif defined(__powerpc64__) #define ABSL_CACHELINE_SIZE 128 #elif defined(__aarch64__) // We would need to read special register ctr_el0 to find out L1 dcache size. // This value is a good estimate based on a real aarch64 machine. #define ABSL_CACHELINE_SIZE 64 #elif defined(__arm__) // Cache line sizes for ARM: These values are not strictly correct since // cache line sizes depend on implementations, not architectures. There // are even implementations with cache line sizes configurable at boot // time. #if defined(__ARM_ARCH_5T__) #define ABSL_CACHELINE_SIZE 32 #elif defined(__ARM_ARCH_7A__) #define ABSL_CACHELINE_SIZE 64 #endif #endif #ifndef ABSL_CACHELINE_SIZE // A reasonable default guess. Note that overestimates tend to waste more // space, while underestimates tend to waste more time. #define ABSL_CACHELINE_SIZE 64 #endif // ABSL_CACHELINE_ALIGNED // // Indicates that the declared object be cache aligned using // `ABSL_CACHELINE_SIZE` (see above). Cacheline aligning objects allows you to // load a set of related objects in the L1 cache for performance improvements. // Cacheline aligning objects properly allows constructive memory sharing and // prevents destructive (or "false") memory sharing. // // NOTE: this macro should be replaced with usage of `alignas()` using // `std::hardware_constructive_interference_size` and/or // `std::hardware_destructive_interference_size` when available within C++17. // // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html // for more information. // // On some compilers, `ABSL_CACHELINE_ALIGNED` expands to // `__attribute__((aligned(ABSL_CACHELINE_SIZE)))`. For compilers where this is // not known to work, the macro expands to nothing. // // No further guarantees are made here. The result of applying the macro // to variables and types is always implementation-defined. // // WARNING: It is easy to use this attribute incorrectly, even to the point // of causing bugs that are difficult to diagnose, crash, etc. It does not // of itself guarantee that objects are aligned to a cache line. // // Recommendations: // // 1) Consult compiler documentation; this comment is not kept in sync as // toolchains evolve. // 2) Verify your use has the intended effect. This often requires inspecting // the generated machine code. // 3) Prefer applying this attribute to individual variables. Avoid // applying it to types. This tends to localize the effect. #define ABSL_CACHELINE_ALIGNED __attribute__((aligned(ABSL_CACHELINE_SIZE))) #else // not GCC #define ABSL_CACHELINE_SIZE 64 #define ABSL_CACHELINE_ALIGNED #endif // ABSL_PREDICT_TRUE, ABSL_PREDICT_FALSE // // Enables the compiler to prioritize compilation using static analysis for // likely paths within a boolean branch. // // Example: // // if (ABSL_PREDICT_TRUE(expression)) { // return result; // Faster if more likely // } else { // return 0; // } // // Compilers can use the information that a certain branch is not likely to be // taken (for instance, a CHECK failure) to optimize for the common case in // the absence of better information (ie. compiling gcc with `-fprofile-arcs`). #if ABSL_HAVE_BUILTIN(__builtin_expect) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_PREDICT_FALSE(x) (__builtin_expect(x, 0)) #define ABSL_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) #else #define ABSL_PREDICT_FALSE(x) x #define ABSL_PREDICT_TRUE(x) x #endif #endif // ABSL_BASE_OPTIMIZATION_H_ // // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: macros.h // ----------------------------------------------------------------------------- // // This header file defines the set of language macros used within Abseil code. // For the set of macros used to determine supported compilers and platforms, // see absl/base/config.h instead. // // This code is compiled directly on many platforms, including client // platforms like Windows, Mac, and embedded systems. Before making // any changes here, make sure that you're not breaking any platforms. // #ifndef ABSL_BASE_MACROS_H_ #define ABSL_BASE_MACROS_H_ #include <cstddef> // ABSL_ARRAYSIZE() // // Returns the # of elements in an array as a compile-time constant, which can // be used in defining new arrays. If you use this macro on a pointer by // mistake, you will get a compile-time error. // // Note: this template function declaration is used in defining arraysize. // Note that the function doesn't need an implementation, as we only // use its type. namespace absl { namespace macros_internal { template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; } // namespace macros_internal } // namespace absl #define ABSL_ARRAYSIZE(array) \ (sizeof(::absl::macros_internal::ArraySizeHelper(array))) // kLinkerInitialized // // An enum used only as a constructor argument to indicate that a variable has // static storage duration, and that the constructor should do nothing to its // state. Use of this macro indicates to the reader that it is legal to // declare a static instance of the class, provided the constructor is given // the absl::base_internal::kLinkerInitialized argument. // // Normally, it is unsafe to declare a static variable that has a constructor or // a destructor because invocation order is undefined. However, if the type can // be zero-initialized (which the loader does for static variables) into a valid // state and the type's destructor does not affect storage, then a constructor // for static initialization can be declared. // // Example: // // Declaration // explicit MyClass(absl::base_internal:LinkerInitialized x) {} // // // Invocation // static MyClass my_global(absl::base_internal::kLinkerInitialized); namespace absl { namespace base_internal { enum LinkerInitialized { kLinkerInitialized = 0, }; } // namespace base_internal } // namespace absl // ABSL_FALLTHROUGH_INTENDED // // Annotates implicit fall-through between switch labels, allowing a case to // indicate intentional fallthrough and turn off warnings about any lack of a // `break` statement. The ABSL_FALLTHROUGH_INTENDED macro should be followed by // a semicolon and can be used in most places where `break` can, provided that // no statements exist between it and the next switch label. // // Example: // // switch (x) { // case 40: // case 41: // if (truth_is_out_there) { // ++x; // ABSL_FALLTHROUGH_INTENDED; // Use instead of/along with annotations // // in comments // } else { // return x; // } // case 42: // ... // // Notes: when compiled with clang in C++11 mode, the ABSL_FALLTHROUGH_INTENDED // macro is expanded to the [[clang::fallthrough]] attribute, which is analysed // when performing switch labels fall-through diagnostic // (`-Wimplicit-fallthrough`). See clang documentation on language extensions // for details: // http://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough // // When used with unsupported compilers, the ABSL_FALLTHROUGH_INTENDED macro // has no effect on diagnostics. In any case this macro has no effect on runtime // behavior and performance of code. #ifdef ABSL_FALLTHROUGH_INTENDED #error "ABSL_FALLTHROUGH_INTENDED should not be defined." #endif // TODO(zhangxy): Use c++17 standard [[fallthrough]] macro, when supported. #if defined(__clang__) && defined(__has_warning) #if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") #define ABSL_FALLTHROUGH_INTENDED [[clang::fallthrough]] #endif #elif defined(__GNUC__) && __GNUC__ >= 7 #define ABSL_FALLTHROUGH_INTENDED [[gnu::fallthrough]] #endif #ifndef ABSL_FALLTHROUGH_INTENDED #define ABSL_FALLTHROUGH_INTENDED \ do { \ } while (0) #endif // ABSL_DEPRECATED() // // Marks a deprecated class, struct, enum, function, method and variable // declarations. The macro argument is used as a custom diagnostic message (e.g. // suggestion of a better alternative). // // Example: // // class ABSL_DEPRECATED("Use Bar instead") Foo {...}; // ABSL_DEPRECATED("Use Baz instead") void Bar() {...} // // Every usage of a deprecated entity will trigger a warning when compiled with // clang's `-Wdeprecated-declarations` option. This option is turned off by // default, but the warnings will be reported by clang-tidy. #if defined(__clang__) && __cplusplus >= 201103L && defined(__has_warning) #define ABSL_DEPRECATED(message) __attribute__((deprecated(message))) #endif #ifndef ABSL_DEPRECATED #define ABSL_DEPRECATED(message) #endif // ABSL_BAD_CALL_IF() // // Used on a function overload to trap bad calls: any call that matches the // overload will cause a compile-time error. This macro uses a clang-specific // "enable_if" attribute, as described at // http://clang.llvm.org/docs/AttributeReference.html#enable-if // // Overloads which use this macro should be bracketed by // `#ifdef ABSL_BAD_CALL_IF`. // // Example: // // int isdigit(int c); // #ifdef ABSL_BAD_CALL_IF // int isdigit(int c) // ABSL_BAD_CALL_IF(c <= -1 || c > 255, // "'c' must have the value of an unsigned char or EOF"); // #endif // ABSL_BAD_CALL_IF #if defined(__clang__) # if __has_attribute(enable_if) # define ABSL_BAD_CALL_IF(expr, msg) \ __attribute__((enable_if(expr, "Bad call trap"), unavailable(msg))) # endif #endif // ABSL_ASSERT() // // In C++11, `assert` can't be used portably within constexpr functions. // ABSL_ASSERT functions as a runtime assert but works in C++11 constexpr // functions. Example: // // constexpr double Divide(double a, double b) { // return ABSL_ASSERT(b != 0), a / b; // } // // This macro is inspired by // https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/ #if defined(NDEBUG) #define ABSL_ASSERT(expr) (false ? (void)(expr) : (void)0) #else #define ABSL_ASSERT(expr) \ (ABSL_PREDICT_TRUE((expr)) ? (void)0 : [] { assert(false && #expr); }()) #endif #endif // ABSL_BASE_MACROS_H_ /* * Copyright 2017 The Abseil Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* This file defines dynamic annotations for use with dynamic analysis tool such as valgrind, PIN, etc. Dynamic annotation is a source code annotation that affects the generated code (that is, the annotation is not a comment). Each such annotation is attached to a particular instruction and/or to a particular object (address) in the program. The annotations that should be used by users are macros in all upper-case (e.g., ANNOTATE_THREAD_NAME). Actual implementation of these macros may differ depending on the dynamic analysis tool being used. This file supports the following configurations: - Dynamic Annotations enabled (with static thread-safety warnings disabled). In this case, macros expand to functions implemented by Thread Sanitizer, when building with TSan. When not provided an external implementation, dynamic_annotations.cc provides no-op implementations. - Static Clang thread-safety warnings enabled. When building with a Clang compiler that supports thread-safety warnings, a subset of annotations can be statically-checked at compile-time. We expand these macros to static-inline functions that can be analyzed for thread-safety, but afterwards elided when building the final binary. - All annotations are disabled. If neither Dynamic Annotations nor Clang thread-safety warnings are enabled, then all annotation-macros expand to empty. */ #ifndef ABSL_BASE_DYNAMIC_ANNOTATIONS_H_ #define ABSL_BASE_DYNAMIC_ANNOTATIONS_H_ #ifndef DYNAMIC_ANNOTATIONS_ENABLED # define DYNAMIC_ANNOTATIONS_ENABLED 0 #endif #if defined(__native_client__) #include "nacl/dynamic_annotations.h" // Stub out the macros missing from the NaCl version. #ifndef ANNOTATE_CONTIGUOUS_CONTAINER #define ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) #endif #ifndef ANNOTATE_RWLOCK_CREATE_STATIC #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) #endif #ifndef ADDRESS_SANITIZER_REDZONE #define ADDRESS_SANITIZER_REDZONE(name) #endif #ifndef ANNOTATE_MEMORY_IS_UNINITIALIZED #define ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) #endif #else /* !__native_client__ */ #if DYNAMIC_ANNOTATIONS_ENABLED != 0 /* ------------------------------------------------------------- Annotations that suppress errors. It is usually better to express the program's synchronization using the other annotations, but these can be used when all else fails. */ /* Report that we may have a benign race at "pointer", with size "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the point where "pointer" has been allocated, preferably close to the point where the race happens. See also ANNOTATE_BENIGN_RACE_STATIC. */ #define ANNOTATE_BENIGN_RACE(pointer, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \ sizeof(*(pointer)), description) /* Same as ANNOTATE_BENIGN_RACE(address, description), but applies to the memory range [address, address+size). */ #define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description) /* Enable (enable!=0) or disable (enable==0) race detection for all threads. This annotation could be useful if you want to skip expensive race analysis during some period of program execution, e.g. during initialization. */ #define ANNOTATE_ENABLE_RACE_DETECTION(enable) \ AnnotateEnableRaceDetection(__FILE__, __LINE__, enable) /* ------------------------------------------------------------- Annotations useful for debugging. */ /* Report the current thread name to a race detector. */ #define ANNOTATE_THREAD_NAME(name) \ AnnotateThreadName(__FILE__, __LINE__, name) /* ------------------------------------------------------------- Annotations useful when implementing locks. They are not normally needed by modules that merely use locks. The "lock" argument is a pointer to the lock object. */ /* Report that a lock has been created at address "lock". */ #define ANNOTATE_RWLOCK_CREATE(lock) \ AnnotateRWLockCreate(__FILE__, __LINE__, lock) /* Report that a linker initialized lock has been created at address "lock". */ #ifdef THREAD_SANITIZER #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) \ AnnotateRWLockCreateStatic(__FILE__, __LINE__, lock) #else #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) ANNOTATE_RWLOCK_CREATE(lock) #endif /* Report that the lock at address "lock" is about to be destroyed. */ #define ANNOTATE_RWLOCK_DESTROY(lock) \ AnnotateRWLockDestroy(__FILE__, __LINE__, lock) /* Report that the lock at address "lock" has been acquired. is_w=1 for writer lock, is_w=0 for reader lock. */ #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) /* Report that the lock at address "lock" is about to be released. */ #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define ANNOTATE_RWLOCK_CREATE(lock) /* empty */ #define ANNOTATE_RWLOCK_CREATE_STATIC(lock) /* empty */ #define ANNOTATE_RWLOCK_DESTROY(lock) /* empty */ #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */ #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */ #define ANNOTATE_BENIGN_RACE(address, description) /* empty */ #define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */ #define ANNOTATE_THREAD_NAME(name) /* empty */ #define ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ /* These annotations are also made available to LLVM's Memory Sanitizer */ #if DYNAMIC_ANNOTATIONS_ENABLED == 1 || defined(MEMORY_SANITIZER) #define ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \ AnnotateMemoryIsInitialized(__FILE__, __LINE__, address, size) #define ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) \ AnnotateMemoryIsUninitialized(__FILE__, __LINE__, address, size) #else #define ANNOTATE_MEMORY_IS_INITIALIZED(address, size) /* empty */ #define ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED || MEMORY_SANITIZER */ /* TODO(delesley) -- Replace __CLANG_SUPPORT_DYN_ANNOTATION__ with the appropriate feature ID. */ #if defined(__clang__) && (!defined(SWIG)) \ && defined(__CLANG_SUPPORT_DYN_ANNOTATION__) #if DYNAMIC_ANNOTATIONS_ENABLED == 0 #define ANNOTALYSIS_ENABLED #endif /* When running in opt-mode, GCC will issue a warning, if these attributes are compiled. Only include them when compiling using Clang. */ #define ATTRIBUTE_IGNORE_READS_BEGIN \ __attribute((exclusive_lock_function("*"))) #define ATTRIBUTE_IGNORE_READS_END \ __attribute((unlock_function("*"))) #else #define ATTRIBUTE_IGNORE_READS_BEGIN /* empty */ #define ATTRIBUTE_IGNORE_READS_END /* empty */ #endif /* defined(__clang__) && ... */ #if (DYNAMIC_ANNOTATIONS_ENABLED != 0) || defined(ANNOTALYSIS_ENABLED) #define ANNOTATIONS_ENABLED #endif #if (DYNAMIC_ANNOTATIONS_ENABLED != 0) /* Request the analysis tool to ignore all reads in the current thread until ANNOTATE_IGNORE_READS_END is called. Useful to ignore intentional racey reads, while still checking other reads and all writes. See also ANNOTATE_UNPROTECTED_READ. */ #define ANNOTATE_IGNORE_READS_BEGIN() \ AnnotateIgnoreReadsBegin(__FILE__, __LINE__) /* Stop ignoring reads. */ #define ANNOTATE_IGNORE_READS_END() \ AnnotateIgnoreReadsEnd(__FILE__, __LINE__) /* Similar to ANNOTATE_IGNORE_READS_BEGIN, but ignore writes instead. */ #define ANNOTATE_IGNORE_WRITES_BEGIN() \ AnnotateIgnoreWritesBegin(__FILE__, __LINE__) /* Stop ignoring writes. */ #define ANNOTATE_IGNORE_WRITES_END() \ AnnotateIgnoreWritesEnd(__FILE__, __LINE__) /* Clang provides limited support for static thread-safety analysis through a feature called Annotalysis. We configure macro-definitions according to whether Annotalysis support is available. */ #elif defined(ANNOTALYSIS_ENABLED) #define ANNOTATE_IGNORE_READS_BEGIN() \ StaticAnnotateIgnoreReadsBegin(__FILE__, __LINE__) #define ANNOTATE_IGNORE_READS_END() \ StaticAnnotateIgnoreReadsEnd(__FILE__, __LINE__) #define ANNOTATE_IGNORE_WRITES_BEGIN() \ StaticAnnotateIgnoreWritesBegin(__FILE__, __LINE__) #define ANNOTATE_IGNORE_WRITES_END() \ StaticAnnotateIgnoreWritesEnd(__FILE__, __LINE__) #else #define ANNOTATE_IGNORE_READS_BEGIN() /* empty */ #define ANNOTATE_IGNORE_READS_END() /* empty */ #define ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */ #define ANNOTATE_IGNORE_WRITES_END() /* empty */ #endif /* Implement the ANNOTATE_IGNORE_READS_AND_WRITES_* annotations using the more primitive annotations defined above. */ #if defined(ANNOTATIONS_ENABLED) /* Start ignoring all memory accesses (both reads and writes). */ #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ do { \ ANNOTATE_IGNORE_READS_BEGIN(); \ ANNOTATE_IGNORE_WRITES_BEGIN(); \ }while (0) /* Stop ignoring both reads and writes. */ #define ANNOTATE_IGNORE_READS_AND_WRITES_END() \ do { \ ANNOTATE_IGNORE_WRITES_END(); \ ANNOTATE_IGNORE_READS_END(); \ }while (0) #else #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */ #define ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */ #endif /* Use the macros above rather than using these functions directly. */ #include <stddef.h> #ifdef __cplusplus extern "C" { #endif void AnnotateRWLockCreate(const char *file, int line, const volatile void *lock); void AnnotateRWLockCreateStatic(const char *file, int line, const volatile void *lock); void AnnotateRWLockDestroy(const char *file, int line, const volatile void *lock); void AnnotateRWLockAcquired(const char *file, int line, const volatile void *lock, long is_w); /* NOLINT */ void AnnotateRWLockReleased(const char *file, int line, const volatile void *lock, long is_w); /* NOLINT */ void AnnotateBenignRace(const char *file, int line, const volatile void *address, const char *description); void AnnotateBenignRaceSized(const char *file, int line, const volatile void *address, size_t size, const char *description); void AnnotateThreadName(const char *file, int line, const char *name); void AnnotateEnableRaceDetection(const char *file, int line, int enable); void AnnotateMemoryIsInitialized(const char *file, int line, const volatile void *mem, size_t size); void AnnotateMemoryIsUninitialized(const char *file, int line, const volatile void *mem, size_t size); /* Annotations expand to these functions, when Dynamic Annotations are enabled. These functions are either implemented as no-op calls, if no Sanitizer is attached, or provided with externally-linked implementations by a library like ThreadSanitizer. */ void AnnotateIgnoreReadsBegin(const char *file, int line) ATTRIBUTE_IGNORE_READS_BEGIN; void AnnotateIgnoreReadsEnd(const char *file, int line) ATTRIBUTE_IGNORE_READS_END; void AnnotateIgnoreWritesBegin(const char *file, int line); void AnnotateIgnoreWritesEnd(const char *file, int line); #if defined(ANNOTALYSIS_ENABLED) /* When Annotalysis is enabled without Dynamic Annotations, the use of static-inline functions allows the annotations to be read at compile-time, while still letting the compiler elide the functions from the final build. TODO(delesley) -- The exclusive lock here ignores writes as well, but allows IGNORE_READS_AND_WRITES to work properly. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" static inline void StaticAnnotateIgnoreReadsBegin(const char *file, int line) ATTRIBUTE_IGNORE_READS_BEGIN { (void)file; (void)line; } static inline void StaticAnnotateIgnoreReadsEnd(const char *file, int line) ATTRIBUTE_IGNORE_READS_END { (void)file; (void)line; } static inline void StaticAnnotateIgnoreWritesBegin( const char *file, int line) { (void)file; (void)line; } static inline void StaticAnnotateIgnoreWritesEnd( const char *file, int line) { (void)file; (void)line; } #pragma GCC diagnostic pop #endif /* Return non-zero value if running under valgrind. If "valgrind.h" is included into dynamic_annotations.cc, the regular valgrind mechanism will be used. See http://valgrind.org/docs/manual/manual-core-adv.html about RUNNING_ON_VALGRIND and other valgrind "client requests". The file "valgrind.h" may be obtained by doing svn co svn://svn.valgrind.org/valgrind/trunk/include If for some reason you can't use "valgrind.h" or want to fake valgrind, there are two ways to make this function return non-zero: - Use environment variable: export RUNNING_ON_VALGRIND=1 - Make your tool intercept the function RunningOnValgrind() and change its return value. */ int RunningOnValgrind(void); /* ValgrindSlowdown returns: * 1.0, if (RunningOnValgrind() == 0) * 50.0, if (RunningOnValgrind() != 0 && getenv("VALGRIND_SLOWDOWN") == NULL) * atof(getenv("VALGRIND_SLOWDOWN")) otherwise This function can be used to scale timeout values: EXAMPLE: for (;;) { DoExpensiveBackgroundTask(); SleepForSeconds(5 * ValgrindSlowdown()); } */ double ValgrindSlowdown(void); #ifdef __cplusplus } #endif /* ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads. Instead of doing ANNOTATE_IGNORE_READS_BEGIN(); ... = x; ANNOTATE_IGNORE_READS_END(); one can use ... = ANNOTATE_UNPROTECTED_READ(x); */ #if defined(__cplusplus) && defined(ANNOTATIONS_ENABLED) template <typename T> inline T ANNOTATE_UNPROTECTED_READ(const volatile T &x) { /* NOLINT */ ANNOTATE_IGNORE_READS_BEGIN(); T res = x; ANNOTATE_IGNORE_READS_END(); return res; } #else #define ANNOTATE_UNPROTECTED_READ(x) (x) #endif #if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus) /* Apply ANNOTATE_BENIGN_RACE_SIZED to a static variable. */ #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ namespace { \ class static_var ## _annotator { \ public: \ static_var ## _annotator() { \ ANNOTATE_BENIGN_RACE_SIZED(&static_var, \ sizeof(static_var), \ # static_var ": " description); \ } \ }; \ static static_var ## _annotator the ## static_var ## _annotator;\ } // namespace #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ #ifdef ADDRESS_SANITIZER /* Describe the current state of a contiguous container such as e.g. * std::vector or std::string. For more details see * sanitizer/common_interface_defs.h, which is provided by the compiler. */ #include <sanitizer/common_interface_defs.h> #define ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) \ __sanitizer_annotate_contiguous_container(beg, end, old_mid, new_mid) #define ADDRESS_SANITIZER_REDZONE(name) \ struct { char x[8] __attribute__ ((aligned (8))); } name #else #define ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) #define ADDRESS_SANITIZER_REDZONE(name) #endif // ADDRESS_SANITIZER /* Undefine the macros intended only in this file. */ #undef ANNOTALYSIS_ENABLED #undef ANNOTATIONS_ENABLED #undef ATTRIBUTE_IGNORE_READS_BEGIN #undef ATTRIBUTE_IGNORE_READS_END #endif /* !__native_client__ */ #endif /* ABSL_BASE_DYNAMIC_ANNOTATIONS_H_ */ #define ABSL_RAW_CHECK(cond, msg) assert((cond) && (msg)) #define ABSL_RAW_LOG(sev, ...) do {} while(0) // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Produce stack trace. // // There are three different ways we can try to get the stack trace: // // 1) Our hand-coded stack-unwinder. This depends on a certain stack // layout, which is used by gcc (and those systems using a // gcc-compatible ABI) on x86 systems, at least since gcc 2.95. // It uses the frame pointer to do its work. // // 2) The libunwind library. This is still in development, and as a // separate library adds a new dependency, but doesn't need a frame // pointer. It also doesn't call malloc. // // 3) The gdb unwinder -- also the one used by the c++ exception code. // It's obviously well-tested, but has a fatal flaw: it can call // malloc() from the unwinder. This is a problem because we're // trying to use the unwinder to instrument malloc(). // // Note: if you add a new implementation here, make sure it works // correctly when absl::GetStackTrace() is called with max_depth == 0. // Some code may do that. #include <atomic> #if defined(ABSL_STACKTRACE_INL_HEADER) #include ABSL_STACKTRACE_INL_HEADER #else # error Cannot calculate stack trace: will need to write for your environment # include "stacktrace_internal/stacktrace_aarch64-inl.inc" # include "stacktrace_internal/stacktrace_arm-inl.inc" # include "stacktrace_internal/stacktrace_generic-inl.inc" # include "stacktrace_internal/stacktrace_powerpc-inl.inc" # include "stacktrace_internal/stacktrace_unimplemented-inl.inc" # include "stacktrace_internal/stacktrace_win32-inl.inc" # include "stacktrace_internal/stacktrace_x86-inl.inc" #endif namespace absl { namespace { typedef int (*Unwinder)(void**, int*, int, int, const void*, int*); std::atomic<Unwinder> custom; template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT> ABSL_ATTRIBUTE_ALWAYS_INLINE inline int Unwind(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { Unwinder f = &UnwindImpl<IS_STACK_FRAMES, IS_WITH_CONTEXT>; Unwinder g = custom.load(std::memory_order_acquire); if (g != nullptr) f = g; // Add 1 to skip count for the unwinder function itself int size = (*f)(result, sizes, max_depth, skip_count + 1, uc, min_dropped_frames); // To disable tail call to (*f)(...) ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); return size; } } // anonymous namespace int GetStackFrames(void** result, int* sizes, int max_depth, int skip_count) { return Unwind<true, false>(result, sizes, max_depth, skip_count, nullptr, nullptr); } int GetStackFramesWithContext(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { return Unwind<true, true>(result, sizes, max_depth, skip_count, uc, min_dropped_frames); } int GetStackTrace(void** result, int max_depth, int skip_count) { return Unwind<false, false>(result, nullptr, max_depth, skip_count, nullptr, nullptr); } int GetStackTraceWithContext(void** result, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { return Unwind<false, true>(result, nullptr, max_depth, skip_count, uc, min_dropped_frames); } void SetStackUnwinder(Unwinder w) { custom.store(w, std::memory_order_release); } int DefaultStackUnwinder(void** pcs, int* sizes, int depth, int skip, const void* uc, int* min_dropped_frames) { skip++; // For this function Unwinder f = nullptr; if (sizes == nullptr) { if (uc == nullptr) { f = &UnwindImpl<false, false>; } else { f = &UnwindImpl<false, true>; } } else { if (uc == nullptr) { f = &UnwindImpl<true, false>; } else { f = &UnwindImpl<true, true>; } } volatile int x = 0; int n = (*f)(pcs, sizes, depth, skip, uc, min_dropped_frames); x = 1; (void) x; // To disable tail call to (*f)(...) return n; } } // namespace absl // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // base::AddressIsReadable() probes an address to see whether it is readable, // without faulting. #if !defined(__linux__) || defined(__ANDROID__) namespace absl { namespace debug_internal { // On platforms other than Linux, just return true. bool AddressIsReadable(const void* /* addr */) { return true; } } // namespace debug_internal } // namespace absl #else #include <fcntl.h> #include <sys/syscall.h> #include <unistd.h> #include <atomic> #include <cerrno> #include <cstdint> namespace absl { namespace debug_internal { // Pack a pid and two file descriptors into a 64-bit word, // using 16, 24, and 24 bits for each respectively. static uint64_t Pack(uint64_t pid, uint64_t read_fd, uint64_t write_fd) { ABSL_RAW_CHECK((read_fd >> 24) == 0 && (write_fd >> 24) == 0, "fd out of range"); return (pid << 48) | ((read_fd & 0xffffff) << 24) | (write_fd & 0xffffff); } // Unpack x into a pid and two file descriptors, where x was created with // Pack(). static void Unpack(uint64_t x, int *pid, int *read_fd, int *write_fd) { *pid = x >> 48; *read_fd = (x >> 24) & 0xffffff; *write_fd = x & 0xffffff; } // Return whether the byte at *addr is readable, without faulting. // Save and restores errno. Returns true on systems where // unimplemented. // This is a namespace-scoped variable for correct zero-initialization. static std::atomic<uint64_t> pid_and_fds; // initially 0, an invalid pid. bool AddressIsReadable(const void *addr) { int save_errno = errno; // We test whether a byte is readable by using write(). Normally, this would // be done via a cached file descriptor to /dev/null, but linux fails to // check whether the byte is readable when the destination is /dev/null, so // we use a cached pipe. We store the pid of the process that created the // pipe to handle the case where a process forks, and the child closes all // the file descriptors and then calls this routine. This is not perfect: // the child could use the routine, then close all file descriptors and then // use this routine again. But the likely use of this routine is when // crashing, to test the validity of pages when dumping the stack. Beware // that we may leak file descriptors, but we're unlikely to leak many. int bytes_written; int current_pid = getpid() & 0xffff; // we use only the low order 16 bits do { // until we do not get EBADF trying to use file descriptors int pid; int read_fd; int write_fd; uint64_t local_pid_and_fds = pid_and_fds.load(std::memory_order_relaxed); Unpack(local_pid_and_fds, &pid, &read_fd, &write_fd); while (current_pid != pid) { int p[2]; // new pipe if (pipe(p) != 0) { ABSL_RAW_LOG(FATAL, "Failed to create pipe, errno=%d", errno); } fcntl(p[0], F_SETFD, FD_CLOEXEC); fcntl(p[1], F_SETFD, FD_CLOEXEC); uint64_t new_pid_and_fds = Pack(current_pid, p[0], p[1]); if (pid_and_fds.compare_exchange_strong( local_pid_and_fds, new_pid_and_fds, std::memory_order_relaxed, std::memory_order_relaxed)) { local_pid_and_fds = new_pid_and_fds; // fds exposed to other threads } else { // fds not exposed to other threads; we can close them. close(p[0]); close(p[1]); local_pid_and_fds = pid_and_fds.load(std::memory_order_relaxed); } Unpack(local_pid_and_fds, &pid, &read_fd, &write_fd); } errno = 0; // Use syscall(SYS_write, ...) instead of write() to prevent ASAN // and other checkers from complaining about accesses to arbitrary // memory. do { bytes_written = syscall(SYS_write, write_fd, addr, 1); } while (bytes_written == -1 && errno == EINTR); if (bytes_written == 1) { // remove the byte from the pipe char c; while (read(read_fd, &c, 1) == -1 && errno == EINTR) { } } if (errno == EBADF) { // Descriptors invalid. // If pid_and_fds contains the problematic file descriptors we just used, // this call will forget them, and the loop will try again. pid_and_fds.compare_exchange_strong(local_pid_and_fds, 0, std::memory_order_relaxed, std::memory_order_relaxed); } } while (errno == EBADF); errno = save_errno; return bytes_written == 1; } } // namespace debug_internal } // namespace absl #endif // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Allow dynamic symbol lookup in an in-memory Elf image. // #ifdef ABSL_HAVE_ELF_MEM_IMAGE // defined in elf_mem_image.h #include <string.h> #include <cassert> #include <cstddef> // From binutils/include/elf/common.h (this doesn't appear to be documented // anywhere else). // // /* This flag appears in a Versym structure. It means that the symbol // is hidden, and is only visible with an explicit version number. // This is a GNU extension. */ // #define VERSYM_HIDDEN 0x8000 // // /* This is the mask for the rest of the Versym information. */ // #define VERSYM_VERSION 0x7fff #define VERSYM_VERSION 0x7fff namespace absl { namespace debug_internal { namespace { #if __WORDSIZE == 32 const int kElfClass = ELFCLASS32; int ElfBind(const ElfW(Sym) *symbol) { return ELF32_ST_BIND(symbol->st_info); } int ElfType(const ElfW(Sym) *symbol) { return ELF32_ST_TYPE(symbol->st_info); } #elif __WORDSIZE == 64 const int kElfClass = ELFCLASS64; int ElfBind(const ElfW(Sym) *symbol) { return ELF64_ST_BIND(symbol->st_info); } int ElfType(const ElfW(Sym) *symbol) { return ELF64_ST_TYPE(symbol->st_info); } #else const int kElfClass = -1; int ElfBind(const ElfW(Sym) *) { ABSL_RAW_LOG(FATAL, "Unexpected word size"); return 0; } int ElfType(const ElfW(Sym) *) { ABSL_RAW_LOG(FATAL, "Unexpected word size"); return 0; } #endif // Extract an element from one of the ELF tables, cast it to desired type. // This is just a simple arithmetic and a glorified cast. // Callers are responsible for bounds checking. template <typename T> const T *GetTableElement(const ElfW(Ehdr) * ehdr, ElfW(Off) table_offset, ElfW(Word) element_size, size_t index) { return reinterpret_cast<const T*>(reinterpret_cast<const char *>(ehdr) + table_offset + index * element_size); } } // namespace const void *const ElfMemImage::kInvalidBase = reinterpret_cast<const void *>(~0L); ElfMemImage::ElfMemImage(const void *base) { ABSL_RAW_CHECK(base != kInvalidBase, "bad pointer"); Init(base); } int ElfMemImage::GetNumSymbols() const { if (!hash_) { return 0; } // See http://www.caldera.com/developers/gabi/latest/ch5.dynamic.html#hash return hash_[1]; } const ElfW(Sym) *ElfMemImage::GetDynsym(int index) const { ABSL_RAW_CHECK(index < GetNumSymbols(), "index out of range"); return dynsym_ + index; } const ElfW(Versym) *ElfMemImage::GetVersym(int index) const { ABSL_RAW_CHECK(index < GetNumSymbols(), "index out of range"); return versym_ + index; } const ElfW(Phdr) *ElfMemImage::GetPhdr(int index) const { ABSL_RAW_CHECK(index < ehdr_->e_phnum, "index out of range"); return GetTableElement<ElfW(Phdr)>(ehdr_, ehdr_->e_phoff, ehdr_->e_phentsize, index); } const char *ElfMemImage::GetDynstr(ElfW(Word) offset) const { ABSL_RAW_CHECK(offset < strsize_, "offset out of range"); return dynstr_ + offset; } const void *ElfMemImage::GetSymAddr(const ElfW(Sym) *sym) const { if (sym->st_shndx == SHN_UNDEF || sym->st_shndx >= SHN_LORESERVE) { // Symbol corresponds to "special" (e.g. SHN_ABS) section. return reinterpret_cast<const void *>(sym->st_value); } ABSL_RAW_CHECK(link_base_ < sym->st_value, "symbol out of range"); return GetTableElement<char>(ehdr_, 0, 1, sym->st_value) - link_base_; } const ElfW(Verdef) *ElfMemImage::GetVerdef(int index) const { ABSL_RAW_CHECK(0 <= index && static_cast<size_t>(index) <= verdefnum_, "index out of range"); const ElfW(Verdef) *version_definition = verdef_; while (version_definition->vd_ndx < index && version_definition->vd_next) { const char *const version_definition_as_char = reinterpret_cast<const char *>(version_definition); version_definition = reinterpret_cast<const ElfW(Verdef) *>(version_definition_as_char + version_definition->vd_next); } return version_definition->vd_ndx == index ? version_definition : nullptr; } const ElfW(Verdaux) *ElfMemImage::GetVerdefAux( const ElfW(Verdef) *verdef) const { return reinterpret_cast<const ElfW(Verdaux) *>(verdef+1); } const char *ElfMemImage::GetVerstr(ElfW(Word) offset) const { ABSL_RAW_CHECK(offset < strsize_, "offset out of range"); return dynstr_ + offset; } void ElfMemImage::Init(const void *base) { ehdr_ = nullptr; dynsym_ = nullptr; dynstr_ = nullptr; versym_ = nullptr; verdef_ = nullptr; hash_ = nullptr; strsize_ = 0; verdefnum_ = 0; link_base_ = ~0L; // Sentinel: PT_LOAD .p_vaddr can't possibly be this. if (!base) { return; } const intptr_t base_as_uintptr_t = reinterpret_cast<uintptr_t>(base); // Fake VDSO has low bit set. const bool fake_vdso = ((base_as_uintptr_t & 1) != 0); base = reinterpret_cast<const void *>(base_as_uintptr_t & ~1); const char *const base_as_char = reinterpret_cast<const char *>(base); if (base_as_char[EI_MAG0] != ELFMAG0 || base_as_char[EI_MAG1] != ELFMAG1 || base_as_char[EI_MAG2] != ELFMAG2 || base_as_char[EI_MAG3] != ELFMAG3) { assert(false); return; } int elf_class = base_as_char[EI_CLASS]; if (elf_class != kElfClass) { assert(false); return; } switch (base_as_char[EI_DATA]) { case ELFDATA2LSB: { if (__LITTLE_ENDIAN != __BYTE_ORDER) { assert(false); return; } break; } case ELFDATA2MSB: { if (__BIG_ENDIAN != __BYTE_ORDER) { assert(false); return; } break; } default: { assert(false); return; } } ehdr_ = reinterpret_cast<const ElfW(Ehdr) *>(base); const ElfW(Phdr) *dynamic_program_header = nullptr; for (int i = 0; i < ehdr_->e_phnum; ++i) { const ElfW(Phdr) *const program_header = GetPhdr(i); switch (program_header->p_type) { case PT_LOAD: if (!~link_base_) { link_base_ = program_header->p_vaddr; } break; case PT_DYNAMIC: dynamic_program_header = program_header; break; } } if (!~link_base_ || !dynamic_program_header) { assert(false); // Mark this image as not present. Can not recur infinitely. Init(nullptr); return; } ptrdiff_t relocation = base_as_char - reinterpret_cast<const char *>(link_base_); ElfW(Dyn) *dynamic_entry = reinterpret_cast<ElfW(Dyn) *>(dynamic_program_header->p_vaddr + relocation); for (; dynamic_entry->d_tag != DT_NULL; ++dynamic_entry) { ElfW(Xword) value = dynamic_entry->d_un.d_val; if (fake_vdso) { // A complication: in the real VDSO, dynamic entries are not relocated // (it wasn't loaded by a dynamic loader). But when testing with a // "fake" dlopen()ed vdso library, the loader relocates some (but // not all!) of them before we get here. if (dynamic_entry->d_tag == DT_VERDEF) { // The only dynamic entry (of the ones we care about) libc-2.3.6 // loader doesn't relocate. value += relocation; } } else { // Real VDSO. Everything needs to be relocated. value += relocation; } switch (dynamic_entry->d_tag) { case DT_HASH: hash_ = reinterpret_cast<ElfW(Word) *>(value); break; case DT_SYMTAB: dynsym_ = reinterpret_cast<ElfW(Sym) *>(value); break; case DT_STRTAB: dynstr_ = reinterpret_cast<const char *>(value); break; case DT_VERSYM: versym_ = reinterpret_cast<ElfW(Versym) *>(value); break; case DT_VERDEF: verdef_ = reinterpret_cast<ElfW(Verdef) *>(value); break; case DT_VERDEFNUM: verdefnum_ = dynamic_entry->d_un.d_val; break; case DT_STRSZ: strsize_ = dynamic_entry->d_un.d_val; break; default: // Unrecognized entries explicitly ignored. break; } } if (!hash_ || !dynsym_ || !dynstr_ || !versym_ || !verdef_ || !verdefnum_ || !strsize_) { assert(false); // invalid VDSO // Mark this image as not present. Can not recur infinitely. Init(nullptr); return; } } bool ElfMemImage::LookupSymbol(const char *name, const char *version, int type, SymbolInfo *info_out) const { for (const SymbolInfo& info : *this) { if (strcmp(info.name, name) == 0 && strcmp(info.version, version) == 0 && ElfType(info.symbol) == type) { if (info_out) { *info_out = info; } return true; } } return false; } bool ElfMemImage::LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const { for (const SymbolInfo& info : *this) { const char *const symbol_start = reinterpret_cast<const char *>(info.address); const char *const symbol_end = symbol_start + info.symbol->st_size; if (symbol_start <= address && address < symbol_end) { if (info_out) { // Client wants to know details for that symbol (the usual case). if (ElfBind(info.symbol) == STB_GLOBAL) { // Strong symbol; just return it. *info_out = info; return true; } else { // Weak or local. Record it, but keep looking for a strong one. *info_out = info; } } else { // Client only cares if there is an overlapping symbol. return true; } } } return false; } ElfMemImage::SymbolIterator::SymbolIterator(const void *const image, int index) : index_(index), image_(image) { } const ElfMemImage::SymbolInfo *ElfMemImage::SymbolIterator::operator->() const { return &info_; } const ElfMemImage::SymbolInfo& ElfMemImage::SymbolIterator::operator*() const { return info_; } bool ElfMemImage::SymbolIterator::operator==(const SymbolIterator &rhs) const { return this->image_ == rhs.image_ && this->index_ == rhs.index_; } bool ElfMemImage::SymbolIterator::operator!=(const SymbolIterator &rhs) const { return !(*this == rhs); } ElfMemImage::SymbolIterator &ElfMemImage::SymbolIterator::operator++() { this->Update(1); return *this; } ElfMemImage::SymbolIterator ElfMemImage::begin() const { SymbolIterator it(this, 0); it.Update(0); return it; } ElfMemImage::SymbolIterator ElfMemImage::end() const { return SymbolIterator(this, GetNumSymbols()); } void ElfMemImage::SymbolIterator::Update(int increment) { const ElfMemImage *image = reinterpret_cast<const ElfMemImage *>(image_); ABSL_RAW_CHECK(image->IsPresent() || increment == 0, ""); if (!image->IsPresent()) { return; } index_ += increment; if (index_ >= image->GetNumSymbols()) { index_ = image->GetNumSymbols(); return; } const ElfW(Sym) *symbol = image->GetDynsym(index_); const ElfW(Versym) *version_symbol = image->GetVersym(index_); ABSL_RAW_CHECK(symbol && version_symbol, ""); const char *const symbol_name = image->GetDynstr(symbol->st_name); const ElfW(Versym) version_index = version_symbol[0] & VERSYM_VERSION; const ElfW(Verdef) *version_definition = nullptr; const char *version_name = ""; if (symbol->st_shndx == SHN_UNDEF) { // Undefined symbols reference DT_VERNEED, not DT_VERDEF, and // version_index could well be greater than verdefnum_, so calling // GetVerdef(version_index) may trigger assertion. } else { version_definition = image->GetVerdef(version_index); } if (version_definition) { // I am expecting 1 or 2 auxiliary entries: 1 for the version itself, // optional 2nd if the version has a parent. ABSL_RAW_CHECK( version_definition->vd_cnt == 1 || version_definition->vd_cnt == 2, "wrong number of entries"); const ElfW(Verdaux) *version_aux = image->GetVerdefAux(version_definition); version_name = image->GetVerstr(version_aux->vda_name); } info_.name = symbol_name; info_.version = version_name; info_.address = image->GetSymAddr(symbol); info_.symbol = symbol; } } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_ELF_MEM_IMAGE // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Allow dynamic symbol lookup in the kernel VDSO page. // // VDSOSupport -- a class representing kernel VDSO (if present). #ifdef ABSL_HAVE_VDSO_SUPPORT // defined in vdso_support.h #include <fcntl.h> #include <sys/syscall.h> #include <unistd.h> #ifndef AT_SYSINFO_EHDR #define AT_SYSINFO_EHDR 33 // for crosstoolv10 #endif namespace absl { namespace debug_internal { std::atomic<const void *> VDSOSupport::vdso_base_( debug_internal::ElfMemImage::kInvalidBase); std::atomic<VDSOSupport::GetCpuFn> VDSOSupport::getcpu_fn_(&InitAndGetCPU); VDSOSupport::VDSOSupport() // If vdso_base_ is still set to kInvalidBase, we got here // before VDSOSupport::Init has been called. Call it now. : image_(vdso_base_.load(std::memory_order_relaxed) == debug_internal::ElfMemImage::kInvalidBase ? Init() : vdso_base_.load(std::memory_order_relaxed)) {} // NOTE: we can't use GoogleOnceInit() below, because we can be // called by tcmalloc, and none of the *once* stuff may be functional yet. // // In addition, we hope that the VDSOSupportHelper constructor // causes this code to run before there are any threads, and before // InitGoogle() has executed any chroot or setuid calls. // // Finally, even if there is a race here, it is harmless, because // the operation should be idempotent. const void *VDSOSupport::Init() { if (vdso_base_.load(std::memory_order_relaxed) == debug_internal::ElfMemImage::kInvalidBase) { { // Valgrind zaps AT_SYSINFO_EHDR and friends from the auxv[] // on stack, and so glibc works as if VDSO was not present. // But going directly to kernel via /proc/self/auxv below bypasses // Valgrind zapping. So we check for Valgrind separately. if (RunningOnValgrind()) { vdso_base_.store(nullptr, std::memory_order_relaxed); getcpu_fn_.store(&GetCPUViaSyscall, std::memory_order_relaxed); return nullptr; } int fd = open("/proc/self/auxv", O_RDONLY); if (fd == -1) { // Kernel too old to have a VDSO. vdso_base_.store(nullptr, std::memory_order_relaxed); getcpu_fn_.store(&GetCPUViaSyscall, std::memory_order_relaxed); return nullptr; } ElfW(auxv_t) aux; while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) { if (aux.a_type == AT_SYSINFO_EHDR) { vdso_base_.store(reinterpret_cast<void *>(aux.a_un.a_val), std::memory_order_relaxed); break; } } close(fd); } if (vdso_base_.load(std::memory_order_relaxed) == debug_internal::ElfMemImage::kInvalidBase) { // Didn't find AT_SYSINFO_EHDR in auxv[]. vdso_base_.store(nullptr, std::memory_order_relaxed); } } GetCpuFn fn = &GetCPUViaSyscall; // default if VDSO not present. if (vdso_base_.load(std::memory_order_relaxed)) { VDSOSupport vdso; SymbolInfo info; if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) { fn = reinterpret_cast<GetCpuFn>(const_cast<void *>(info.address)); } } // Subtle: this code runs outside of any locks; prevent compiler // from assigning to getcpu_fn_ more than once. getcpu_fn_.store(fn, std::memory_order_relaxed); return vdso_base_.load(std::memory_order_relaxed); } const void *VDSOSupport::SetBase(const void *base) { ABSL_RAW_CHECK(base != debug_internal::ElfMemImage::kInvalidBase, "internal error"); const void *old_base = vdso_base_.load(std::memory_order_relaxed); vdso_base_.store(base, std::memory_order_relaxed); image_.Init(base); // Also reset getcpu_fn_, so GetCPU could be tested with simulated VDSO. getcpu_fn_.store(&InitAndGetCPU, std::memory_order_relaxed); return old_base; } bool VDSOSupport::LookupSymbol(const char *name, const char *version, int type, SymbolInfo *info) const { return image_.LookupSymbol(name, version, type, info); } bool VDSOSupport::LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const { return image_.LookupSymbolByAddress(address, info_out); } // NOLINT on 'long' because this routine mimics kernel api. long VDSOSupport::GetCPUViaSyscall(unsigned *cpu, // NOLINT(runtime/int) void *, void *) { #ifdef SYS_getcpu return syscall(SYS_getcpu, cpu, nullptr, nullptr); #else // x86_64 never implemented sys_getcpu(), except as a VDSO call. errno = ENOSYS; return -1; #endif } // Use fast __vdso_getcpu if available. long VDSOSupport::InitAndGetCPU(unsigned *cpu, // NOLINT(runtime/int) void *x, void *y) { Init(); GetCpuFn fn = getcpu_fn_.load(std::memory_order_relaxed); ABSL_RAW_CHECK(fn != &InitAndGetCPU, "Init() did not set getcpu_fn_"); return (*fn)(cpu, x, y); } // This function must be very fast, and may be called from very // low level (e.g. tcmalloc). Hence I avoid things like // GoogleOnceInit() and ::operator new. ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int GetCPU() { unsigned cpu; int ret_code = (*VDSOSupport::getcpu_fn_)(&cpu, nullptr, nullptr); return ret_code == 0 ? cpu : ret_code; } // We need to make sure VDSOSupport::Init() is called before // InitGoogle() does any setuid or chroot calls. If VDSOSupport // is used in any global constructor, this will happen, since // VDSOSupport's constructor calls Init. But if not, we need to // ensure it here, with a global constructor of our own. This // is an allowed exception to the normal rule against non-trivial // global constructors. static class VDSOInitHelper { public: VDSOInitHelper() { VDSOSupport::Init(); } } vdso_init_helper; } // namespace debug_internal } // namespace absl #endif // ABSL_HAVE_VDSO_SUPPORT // Copyright 2017 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <string.h> #ifndef __has_feature #define __has_feature(x) 0 #endif /* Compiler-based ThreadSanitizer defines DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL = 1 and provides its own definitions of the functions. */ #ifndef DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL # define DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL 0 #endif /* Each function is empty and called (via a macro) only in debug mode. The arguments are captured by dynamic tools at runtime. */ #if DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL == 0 && !defined(__native_client__) #if __has_feature(memory_sanitizer) #include <sanitizer/msan_interface.h> #endif #ifdef __cplusplus extern "C" { #endif void AnnotateRWLockCreate(const char *, int, const volatile void *){} void AnnotateRWLockDestroy(const char *, int, const volatile void *){} void AnnotateRWLockAcquired(const char *, int, const volatile void *, long){} void AnnotateRWLockReleased(const char *, int, const volatile void *, long){} void AnnotateBenignRace(const char *, int, const volatile void *, const char *){} void AnnotateBenignRaceSized(const char *, int, const volatile void *, size_t, const char *) {} void AnnotateThreadName(const char *, int, const char *){} void AnnotateIgnoreReadsBegin(const char *, int){} void AnnotateIgnoreReadsEnd(const char *, int){} void AnnotateIgnoreWritesBegin(const char *, int){} void AnnotateIgnoreWritesEnd(const char *, int){} void AnnotateEnableRaceDetection(const char *, int, int){} void AnnotateMemoryIsInitialized(const char *, int, const volatile void *mem, size_t size) { #if __has_feature(memory_sanitizer) __msan_unpoison(mem, size); #else (void)mem; (void)size; #endif } void AnnotateMemoryIsUninitialized(const char *, int, const volatile void *mem, size_t size) { #if __has_feature(memory_sanitizer) __msan_allocated_memory(mem, size); #else (void)mem; (void)size; #endif } static int GetRunningOnValgrind(void) { #ifdef RUNNING_ON_VALGRIND if (RUNNING_ON_VALGRIND) return 1; #endif char *running_on_valgrind_str = getenv("RUNNING_ON_VALGRIND"); if (running_on_valgrind_str) { return strcmp(running_on_valgrind_str, "0") != 0; } return 0; } /* See the comments in dynamic_annotations.h */ int RunningOnValgrind(void) { static volatile int running_on_valgrind = -1; int local_running_on_valgrind = running_on_valgrind; /* C doesn't have thread-safe initialization of statics, and we don't want to depend on pthread_once here, so hack it. */ ANNOTATE_BENIGN_RACE(&running_on_valgrind, "safe hack"); if (local_running_on_valgrind == -1) running_on_valgrind = local_running_on_valgrind = GetRunningOnValgrind(); return local_running_on_valgrind; } /* See the comments in dynamic_annotations.h */ double ValgrindSlowdown(void) { /* Same initialization hack as in RunningOnValgrind(). */ static volatile double slowdown = 0.0; double local_slowdown = slowdown; ANNOTATE_BENIGN_RACE(&slowdown, "safe hack"); if (RunningOnValgrind() == 0) { return 1.0; } if (local_slowdown == 0.0) { char *env = getenv("VALGRIND_SLOWDOWN"); slowdown = local_slowdown = env ? atof(env) : 50.0; } return local_slowdown; } #ifdef __cplusplus } // extern "C" #endif #endif /* DYNAMIC_ANNOTATIONS_EXTERNAL_IMPL == 0 */
112,969
39,200
#ifndef STAN_LANG_AST_NODE_ARRAY_EXPR_HPP #define STAN_LANG_AST_NODE_ARRAY_EXPR_HPP #include "expression.hpp" #include "stan/language/ast/scope.hpp" #include "stan/language/ast/type/bare_expr_type.hpp" #include <cstddef> #include <vector> namespace stan { namespace lang { struct expresssion; /** * Structure to hold an array expression. */ struct array_expr { /** * Sequence of expressions for array values. */ std::vector<expression> args_; /** * Type of array. */ bare_expr_type type_; /** * True if there is a variable within any of the expressions * that is a parameter, transformed parameter, or non-integer * local variable. */ bool has_var_; /** * Scope of this array expression. * */ scope array_expr_scope_; /** * Construct a default array expression. */ array_expr(); }; } // namespace lang } // namespace stan #endif
901
310
#include <cassert> #include "HyperionConfig.h" #include "Poco/RegularExpression.h" #include "Poco/StringTokenizer.h" #include "Poco/Timestamp.h" #include "Poco/Delegate.h" #include "Poco/NumberParser.h" #include "hyperion/Hyperion.h" #include "hyperion/ImageProcessorFactory.h" #include "leddevice/LedDevice.h" #include "leddevice/LedDeviceFactory.h" #include "MultiColorTransform.h" #include "LinearColorSmoothing.h" // effect engine includes #ifdef ENABLE_EFFECT_ENGINE #include "effectengine/EffectEngine.h" #endif ColorOrder Hyperion::createColorOrder(const Poco::DynamicStruct &deviceConfig) { std::string order = deviceConfig["colorOrder"]; if (order == "rgb") { return ORDER_RGB; } else if (order == "bgr") { return ORDER_BGR; } else if (order == "rbg") { return ORDER_RBG; } else if (order == "brg") { return ORDER_BRG; } else if (order == "gbr") { return ORDER_GBR; } else if (order == "grb") { return ORDER_GRB; } else { std::cout << "Unknown color order defined (" << order << "). Using RGB." << std::endl; } return ORDER_RGB; } ColorTransform *Hyperion::createColorTransform(const Poco::DynamicStruct &transformConfig) { std::string id = "default"; id = transformConfig["id"].toString(); RgbChannelTransform *redTransform = createRgbChannelTransform(transformConfig["red"].extract<Poco::DynamicStruct>()); RgbChannelTransform *greenTransform = createRgbChannelTransform(transformConfig["green"].extract<Poco::DynamicStruct>()); RgbChannelTransform *blueTransform = createRgbChannelTransform(transformConfig["blue"].extract<Poco::DynamicStruct>()); HsvTransform *hsvTransform = createHsvTransform(transformConfig["hsv"].extract<Poco::DynamicStruct>()); ColorTransform *transform = new ColorTransform(); transform->_id = id; transform->_rgbRedTransform = *redTransform; transform->_rgbGreenTransform = *greenTransform; transform->_rgbBlueTransform = *blueTransform; transform->_hsvTransform = *hsvTransform; // Cleanup the allocated individual transforms delete redTransform; delete greenTransform; delete blueTransform; delete hsvTransform; return transform; } MultiColorTransform *Hyperion::createLedColorsTransform(const unsigned ledCnt, const Poco::DynamicStruct &colorConfig) { // Create the result, the transforms are added to this MultiColorTransform *transform = new MultiColorTransform(ledCnt); Poco::Dynamic::Var transformConfig = colorConfig["transform"]; if (!transformConfig.isArray()) { ColorTransform *colorTransform = createColorTransform(transformConfig.extract<Poco::DynamicStruct>()); transform->addTransform(colorTransform); transform->setTransformForLed(colorTransform->_id, 0, ledCnt - 1); } else { const Poco::RegularExpression overallExp("([0-9]+(\\-[0-9]+)?)(,[ ]*([0-9]+(\\-[0-9]+)?))*"); for (unsigned i = 0; i < transformConfig.size(); i++) { const Poco::DynamicStruct &config = transformConfig[i].extract<Poco::DynamicStruct>(); ColorTransform *colorTransform = createColorTransform(config); transform->addTransform(colorTransform); const std::string ledIndicesStr = config["leds"].toString(); if (ledIndicesStr.compare("*") == 0) { // Special case for indices '*' => all leds transform->setTransformForLed(colorTransform->_id, 0, ledCnt - 1); std::cout << "ColorTransform '" << colorTransform->_id << "' => [0; " << ledCnt - 1 << "]" << std::endl; continue; } if (!overallExp.match(ledIndicesStr)) { std::cerr << "Given led indices " << i << " not correct format: " << ledIndicesStr << std::endl; continue; } std::cout << "ColorTransform '" << colorTransform->_id << "' => ["; Poco::StringTokenizer ledIndexList(ledIndicesStr, ",", Poco::StringTokenizer::TOK_TRIM); for (unsigned j = 0; j < ledIndexList.count(); ++j) { if (j > 0) { std::cout << ", "; } if (ledIndexList[j].find("-") != std::string::npos) { Poco::StringTokenizer ledIndices(ledIndexList[j], "-", Poco::StringTokenizer::TOK_TRIM); const unsigned startInd = Poco::NumberParser::parseUnsigned(ledIndices[0]); const unsigned endInd = Poco::NumberParser::parseUnsigned(ledIndices[1]); transform->setTransformForLed(colorTransform->_id, startInd, endInd); std::cout << startInd << "-" << endInd; } else { const unsigned index = Poco::NumberParser::parseUnsigned(ledIndexList[j]); transform->setTransformForLed(colorTransform->_id, index, index); std::cout << index; } } std::cout << "]" << std::endl; } } return transform; } HsvTransform *Hyperion::createHsvTransform(const Poco::DynamicStruct &hsvConfig) { double saturationGain, valueGain; saturationGain = hsvConfig["saturationGain"].convert<double>(); valueGain = hsvConfig["valueGain"].convert<double>(); return new HsvTransform(saturationGain, valueGain); } RgbChannelTransform *Hyperion::createRgbChannelTransform(const Poco::DynamicStruct &colorConfig) { double threshold, gamma, blacklevel, whitelevel; threshold = colorConfig["threshold"].convert<double>(); gamma = colorConfig["gamma"].convert<double>(); blacklevel = colorConfig["blacklevel"].convert<double>(); whitelevel = colorConfig["whitelevel"].convert<double>(); RgbChannelTransform *transform = new RgbChannelTransform(threshold, gamma, blacklevel, whitelevel); return transform; } LedString Hyperion::createLedString(const Poco::Dynamic::Var &ledsConfig, const ColorOrder deviceOrder) { LedString ledString; if (!ledsConfig.isArray()) { throw std::runtime_error("leds config is not valid"); } const std::string deviceOrderStr = colorOrderToString(deviceOrder); Poco::DynamicStruct ledConfig; for (unsigned i = 0; i < ledsConfig.size(); i++) { ledConfig = ledsConfig[i].extract<Poco::DynamicStruct>(); Led led; led.index = ledConfig["index"]; const Poco::DynamicStruct &hscanConfig = ledConfig["hscan"].extract<Poco::DynamicStruct>(); const Poco::DynamicStruct &vscanConfig = ledConfig["vscan"].extract<Poco::DynamicStruct>(); led.minX_frac = std::max(0.0, std::min(1.0, hscanConfig["minimum"].extract<double>())); led.maxX_frac = std::max(0.0, std::min(1.0, hscanConfig["maximum"].extract<double>())); led.minY_frac = std::max(0.0, std::min(1.0, vscanConfig["minimum"].extract<double>())); led.maxY_frac = std::max(0.0, std::min(1.0, vscanConfig["maximum"].extract<double>())); // Fix if the user swapped min and max if (led.minX_frac > led.maxX_frac) { std::swap(led.minX_frac, led.maxX_frac); } if (led.minY_frac > led.maxY_frac) { std::swap(led.minY_frac, led.maxY_frac); } // Get the order of the rgb channels for this led (default is device order) std::string ledOrderStr = deviceOrderStr; if (ledConfig.contains("colorOrder")) ledOrderStr = ledConfig["colorOrder"].toString(); led.colorOrder = stringToColorOrder(ledOrderStr); ledString.leds().push_back(led); } // Make sure the leds are sorted (on their indices) std::sort(ledString.leds().begin(), ledString.leds().end(), [](const Led &lhs, const Led &rhs) { return lhs.index < rhs.index; }); return ledString; } LedDevice *Hyperion::createColorSmoothing(const Poco::DynamicStruct &smoothingConfig, LedDevice *ledDevice) { std::string type = smoothingConfig["type"].toString(); std::transform(type.begin(), type.end(), type.begin(), ::tolower); if (type == "none") { std::cout << "Not creating any smoothing" << std::endl; return ledDevice; } else if (type == "linear") { if (!smoothingConfig.contains("time_ms")) { std::cout << "Unable to create smoothing of type linear because of missing parameter 'time_ms'" << std::endl; } else if (!smoothingConfig.contains("updateFrequency")) { std::cout << "Unable to create smoothing of type linear because of missing parameter 'updateFrequency'" << std::endl; } else { unsigned updateDelay = 0; updateDelay = smoothingConfig["updateDelay"].extract<int>(); std::cout << "Creating linear smoothing" << std::endl; return new LinearColorSmoothing(ledDevice, smoothingConfig["updateFrequency"].extract<double>(), smoothingConfig["time_ms"].extract<int>(), updateDelay); } } else { std::cout << "Unable to create smoothing of type " << type << std::endl; } return ledDevice; } Hyperion::Hyperion(const Poco::DynamicStruct &config) : _ledString( createLedString(config["leds"], createColorOrder(config["device"].extract<Poco::DynamicStruct>()))), _muxer(_ledString.count()), _raw2ledTransform( createLedColorsTransform(_ledString.count(), config["color"].extract<Poco::DynamicStruct>())), _device(LedDeviceFactory::construct(config["device"].extract<Poco::DynamicStruct>())), _timer(0, 0), _timerRunning() { if (_device == nullptr) { throw std::runtime_error("[ERROR] LED device could not be created"); } if (!_raw2ledTransform->verifyTransforms()) { throw std::runtime_error("Color transformation incorrectly set"); } // initialize the image processor factory ImageProcessorFactory::getInstance().init( _ledString, config["blackborderdetector"]["enable"].extract<bool>(), // TODO default true config["blackborderdetector"]["threshold"].extract<double>()); // TODO default 0.01 // initialize the color smoothing filter _device = createColorSmoothing(config["color"]["smoothing"].extract<Poco::DynamicStruct>(), _device); #ifdef ENABLE_EFFECT_ENGINE // create the effect engine _effectEngine = new EffectEngine(this, config["effects"].extract<Poco::DynamicStruct>()); #endif stopTimerEvent += Poco::delegate(this, &Hyperion::stopTimer); // initialize the leds update(); } Hyperion::~Hyperion() { // switch off all leds clearall(); _device->switchOff(); stopTimerEvent -= Poco::delegate(this, &Hyperion::stopTimer); #ifdef ENABLE_EFFECT_ENGINE // delete the effect engine delete _effectEngine; #endif // Delete the Led-Device object delete _device; // delete the color transform delete _raw2ledTransform; } unsigned Hyperion::getLedCount() const { return _ledString.count(); } void Hyperion::setColor(int priority, const ColorRgb &color, const int timeout_ms, bool clearEffects) { // create led output std::vector<ColorRgb> ledColors(_ledString.count(), color); // set colors setColors(priority, ledColors, timeout_ms, clearEffects); } void Hyperion::setColors(int priority, const std::vector<ColorRgb> &ledColors, const int timeout_ms, bool clearEffects) { #ifdef ENABLE_EFFECT_ENGINE // clear effects if this call does not come from an effect if (clearEffects) { _effectEngine->clearChannel(priority); } #endif if (timeout_ms > 0) { long timeoutTime = (Poco::Timestamp().epochMicroseconds() / 1000) + timeout_ms; _muxer.setInput(priority, ledColors, timeoutTime); } else { _muxer.setInput(priority, ledColors); } if (priority == _muxer.getCurrentPriority()) { update(); } } const std::vector<std::string> &Hyperion::getTransformIds() const { return _raw2ledTransform->getTransformIds(); } ColorTransform *Hyperion::getTransform(const std::string &id) { return _raw2ledTransform->getTransform(id); } void Hyperion::transformsUpdated() { update(); } void Hyperion::clear(int priority) { if (_muxer.hasPriority(priority)) { _muxer.clearInput(priority); // update leds if necessary if (priority < _muxer.getCurrentPriority()) { update(); } } #ifdef ENABLE_EFFECT_ENGINE // send clear signal to the effect engine // (outside the check so the effect gets cleared even when the effect is not sending colors) _effectEngine->clearChannel(priority); #endif } void Hyperion::clearall() { _muxer.clearAll(); // update leds update(); #ifdef ENABLE_EFFECT_ENGINE // send clearall signal to the effect engine _effectEngine->clearAllChannels(); #endif } std::vector<int> Hyperion::getActivePriorities() const { return _muxer.getPriorities(); } const Hyperion::InputInfo &Hyperion::getPriorityInfo(const int priority) const { return _muxer.getInputInfo(priority); } #ifdef ENABLE_EFFECT_ENGINE const std::list<EffectDefinition> &Hyperion::getEffects() const { return _effectEngine->getEffects(); } int Hyperion::setEffect(const std::string &effectName, int priority, int timeout) { return _effectEngine->runEffect(effectName, priority, timeout); } int Hyperion::setEffect(const std::string &effectName, const Poco::DynamicStruct &args, int priority, int timeout) { return _effectEngine->runEffect(effectName, args, priority, timeout); } #endif void Hyperion::startTimer(long timeout) { _timerRunning++; static Poco::TimerCallback<Hyperion> timerCallback(*this, &Hyperion::onTimer); _timer.setStartInterval(timeout); _timer.start(timerCallback); } void Hyperion::stopTimer() { _timerRunning--; _timer.stop(); update(); } void Hyperion::update() { static Poco::FastMutex mutex; if (!mutex.tryLock()) { return; } // Update the muxer, cleaning obsolete priorities int64_t now = Poco::Timestamp().epochMicroseconds() / 1000; _muxer.setCurrentTime(now); // Obtain the current priority channel int priority = _muxer.getCurrentPriority(); PriorityMuxer::InputInfo priorityInfo = _muxer.getInputInfo(priority); long timeout_ms = priorityInfo.timeoutTime_ms > 0 ? (priorityInfo.timeoutTime_ms - now) : 0; //std::cout << "update() current priorityInfo: " << priorityInfo << " - TO: " << timeout_ms << std::endl; // Apply the transform to each led and color-channel std::vector<ColorRgb> ledColors = _raw2ledTransform->applyTransform(priorityInfo.ledColors); const std::vector<Led> &leds = _ledString.leds(); unsigned long i = 0; for (ColorRgb &color : ledColors) { const ColorOrder ledColorOrder = leds.at(i).colorOrder; // correct the color byte order switch (ledColorOrder) { case ORDER_RGB: // leave as it is break; case ORDER_BGR: std::swap(color.red, color.blue); break; case ORDER_RBG: std::swap(color.green, color.blue); break; case ORDER_GRB: std::swap(color.red, color.green); break; case ORDER_GBR: { uint8_t temp = color.red; color.red = color.green; color.green = color.blue; color.blue = temp; break; } case ORDER_BRG: { uint8_t temp = color.red; color.red = color.blue; color.blue = color.green; color.green = temp; break; } } i++; } // Write the data to the device _device->write(ledColors); // Start the timeout-timer if (timeout_ms > 0) { if (_timerRunning == 0) { startTimer(timeout_ms); } } else if (_timerRunning > 0) { stopTimer(); } mutex.unlock(); } void Hyperion::onTimer(Poco::Timer &timer) { stopTimerEvent.notifyAsync(nullptr); }
16,530
4,904
/* * sortProcess.cpp : * Changes all sortindexes in the file to the given index. */ #include <iostream> #include <string> #include <vector> #include "../../CatOfEvilGenius/library/DBPF.h" #include "../../CatOfEvilGenius/library/DBPF_types.h" #include "../../CatOfEvilGenius/library/DBPF_BINX.h" using namespace std; extern "C" // for exporting to shared library for use in Python bool sortProcess(const char* filename, const int index) { // extra crunchy goodness for restoring state after outputting in hex format // ios_base::fmtflags f(cout.flags()); // clog << endl << "Sorting " << filename << " into index " << hex << index << "..." << endl; // cout.flags(f); DBPFtype package; vector<DBPF_resourceType*> resources; // Types that should be decompressed and loaded when opening the file. vector<unsigned int> typesToInit; typesToInit.push_back(DBPF_BINX); // Open package file and read/populate chosen (typesToInit) resources. if(!readPackage(filename, package, typesToInit, resources)) { cerr << "Opening and reading from " << filename << " failed. Sorting aborted." << endl; return false; } // Set all sortindices int item_count = resources.size(); DBPF_resourceType* pResource = NULL; for (int i = 0; i < item_count; i++) { pResource = resources[i]; if (NULL == pResource) { continue; } if (DBPF_BINX == pResource->getType()) { if (((DBPF_BINXtype*)pResource)->setSortIndex(index)) { // clog << "\t" << "Set BINX resource " << i << "." << endl; } } } // clog << "Sorting complete!" << endl; // Write back to file // clog << endl << "Overwriting file " << filename << "..." << endl; bool write_success = writeCompressedPackage(filename, package, resources); if (!write_success) { cerr << "Writing to file " << filename << " failed. File may be corrupted... " << "or you may have the file open somewhere else (SimPE, maybe?). " << "If so, close the file elsewhere and try again." << endl; } // else { // clog << "File written!" << endl; // } // Clean up if (!resources.empty()) { size_t vec_size = resources.size(); for (size_t i = 0; i < vec_size; i++) { if (resources[i] != NULL) { delete resources[i]; resources[i] = NULL; } resources.clear(); } } return write_success; }
2,389
780
#include <iostream> using namespace std; string correct(string s, string t){ int length = s.size(); for(int i = 0; i<length; ++i){ if(s[i] != t[length-1-i]) return "NO"; } return "YES"; } int main() { string s; string t; cin >> s >> t; cout << correct(s, t) << endl; return 0; }
335
130
// Copyright 2020 The XLS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xls/common/logging/log_flags.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "xls/common/logging/capture_stream.h" #include "xls/common/logging/logging_test_base.h" #include "xls/common/status/matchers.h" #include "xls/common/status/status_macros.h" namespace { using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::Not; using ::testing::StartsWith; using xls::status_testing::IsOkAndHolds; template <typename T> class ScopedFlagSetter { public: ScopedFlagSetter(absl::Flag<T>* flag, const T& value) : flag_(flag), original_value_(absl::GetFlag(*flag)) { absl::SetFlag(flag, value); } ~ScopedFlagSetter() { absl::SetFlag(flag_, original_value_); } private: absl::Flag<T>* flag_; T original_value_; }; template <typename T> ScopedFlagSetter(absl::Flag<T>* b, const T& e) -> ScopedFlagSetter<T>; class LogFlagsTest : public ::xls::logging_internal::testing::LoggingTestBase { }; TEST_F(LogFlagsTest, MinloglevelSuppressesLoggingBelowSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_minloglevel, static_cast<int>(absl::LogSeverity::kWarning)); XLS_LOG(INFO) << "test_msg"; EXPECT_THAT(entries_, IsEmpty()); } TEST_F(LogFlagsTest, MinloglevelAllowsLoggingAtSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_minloglevel, static_cast<int>(absl::LogSeverity::kWarning)); XLS_LOG(WARNING) << "test_msg"; auto entry = GetSingleEntry(); EXPECT_THAT(entry.text_message, HasSubstr("test_msg")); } TEST_F(LogFlagsTest, MinloglevelAllowsLoggingAboveSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_minloglevel, static_cast<int>(absl::LogSeverity::kWarning)); XLS_LOG(ERROR) << "test_msg"; auto entry = GetSingleEntry(); EXPECT_THAT(entry.text_message, HasSubstr("test_msg")); } TEST_F(LogFlagsTest, LogToStderrFalseDoesNotCauseInfoLoggingToStderr) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, false); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, false); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(Not(HasSubstr("test_info_log_message")))); } TEST_F(LogFlagsTest, LogToStderrTrueCausesInfoLoggingToStderr) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, true); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, false); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, AlsoLogToStderrTrueCausesInfoLoggingToStderr) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, false); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, true); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, StderrThresholdSuppressesLoggingBelowSpecifiedLevel) { auto set_logtostderr = ScopedFlagSetter(&FLAGS_logtostderr, false); auto set_alsologtostderr = ScopedFlagSetter(&FLAGS_alsologtostderr, false); auto set_stderrthreshold = ScopedFlagSetter( &FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverity::kWarning)); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(INFO) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(Not(HasSubstr("test_info_log_message")))); } TEST_F(LogFlagsTest, StderrThresholdAllowsLoggingAtSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverity::kWarning)); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(WARNING) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, StderrThresholdAllowsLoggingAboveSpecifiedLevel) { auto set_flag = ScopedFlagSetter( &FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverity::kWarning)); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(ERROR) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); } TEST_F(LogFlagsTest, EnabledLogPrefixCausesLoggingToBePrefixed) { auto set_flag = ScopedFlagSetter(&FLAGS_log_prefix, true); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(ERROR) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); EXPECT_THAT(output, IsOkAndHolds(StartsWith("E"))); // For ERROR. } TEST_F(LogFlagsTest, DisabledLogPrefixCausesLoggingToNotBePrefixed) { auto set_flag = ScopedFlagSetter(&FLAGS_log_prefix, false); absl::StatusOr<std::string> output = ::xls::testing::CaptureStream( STDERR_FILENO, [] { XLS_LOG(ERROR) << "test_info_log_message"; }); EXPECT_THAT(output, IsOkAndHolds(HasSubstr("test_info_log_message"))); EXPECT_THAT(output, IsOkAndHolds(Not(StartsWith("E")))); // For ERROR. } } // namespace
6,001
2,191
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "base/bind.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/stl_util.h" #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_dependency_manager.h" #include "chrome/browser/sync_file_system/drive_file_sync_service.h" #include "chrome/browser/sync_file_system/local_file_sync_service.h" #include "chrome/browser/sync_file_system/sync_event_observer.h" #include "content/public/browser/browser_thread.h" #include "googleurl/src/gurl.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/syncable/sync_file_metadata.h" #include "webkit/fileapi/syncable/sync_status_code.h" using content::BrowserThread; using fileapi::ConflictFileInfoCallback; using fileapi::FileSystemURL; using fileapi::SyncFileMetadata; using fileapi::SyncStatusCallback; using fileapi::SyncStatusCode; namespace sync_file_system { namespace { // Run the given join_callback when all the callbacks created by this runner // are run. If any of the callbacks return non-OK state the given join_callback // will be dispatched with the non-OK state that comes first. class SharedCallbackRunner : public base::RefCountedThreadSafe<SharedCallbackRunner> { public: explicit SharedCallbackRunner(const SyncStatusCallback& join_callback) : join_callback_(join_callback), num_shared_callbacks_(0), status_(fileapi::SYNC_STATUS_OK) {} SyncStatusCallback CreateCallback() { ++num_shared_callbacks_; return base::Bind(&SharedCallbackRunner::Done, this); } template <typename R> base::Callback<void(SyncStatusCode, const R& in)> CreateAssignAndRunCallback(R* out) { ++num_shared_callbacks_; return base::Bind(&SharedCallbackRunner::AssignAndRun<R>, this, out); } private: virtual ~SharedCallbackRunner() {} friend class base::RefCountedThreadSafe<SharedCallbackRunner>; template <typename R> void AssignAndRun(R* out, SyncStatusCode status, const R& in) { DCHECK(out); DCHECK_GT(num_shared_callbacks_, 0); if (join_callback_.is_null()) return; *out = in; Done(status); } void Done(SyncStatusCode status) { if (status != fileapi::SYNC_STATUS_OK && status_ == fileapi::SYNC_STATUS_OK) { status_ = status; } if (--num_shared_callbacks_ > 0) return; join_callback_.Run(status_); join_callback_.Reset(); } SyncStatusCallback join_callback_; int num_shared_callbacks_; SyncStatusCode status_; }; void VerifyFileSystemURLSetCallback( base::WeakPtr<SyncFileSystemService> service, const GURL& app_origin, const std::string& service_name, const fileapi::SyncFileSetCallback& callback, fileapi::SyncStatusCode status, const fileapi::FileSystemURLSet& urls) { if (!service.get()) return; #ifndef NDEBUG if (status == fileapi::SYNC_STATUS_OK) { for (fileapi::FileSystemURLSet::const_iterator iter = urls.begin(); iter != urls.end(); ++iter) { DCHECK(iter->origin() == app_origin); DCHECK(iter->filesystem_id() == service_name); } } #endif callback.Run(status, urls); } SyncEventObserver::SyncServiceState RemoteStateToSyncServiceState( RemoteServiceState state) { switch (state) { case REMOTE_SERVICE_OK: return SyncEventObserver::SYNC_SERVICE_RUNNING; case REMOTE_SERVICE_TEMPORARY_UNAVAILABLE: return SyncEventObserver::SYNC_SERVICE_TEMPORARY_UNAVAILABLE; case REMOTE_SERVICE_AUTHENTICATION_REQUIRED: return SyncEventObserver::SYNC_SERVICE_AUTHENTICATION_REQUIRED; case REMOTE_SERVICE_DISABLED: return SyncEventObserver::SYNC_SERVICE_DISABLED; } NOTREACHED(); return SyncEventObserver::SYNC_SERVICE_DISABLED; } } // namespace void SyncFileSystemService::Shutdown() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); local_file_service_->Shutdown(); local_file_service_.reset(); remote_file_service_.reset(); profile_ = NULL; } SyncFileSystemService::~SyncFileSystemService() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!profile_); } void SyncFileSystemService::InitializeForApp( fileapi::FileSystemContext* file_system_context, const std::string& service_name, const GURL& app_origin, const SyncStatusCallback& callback) { DCHECK(local_file_service_); DCHECK(remote_file_service_); DCHECK(app_origin == app_origin.GetOrigin()); DVLOG(1) << "InitializeForApp: " << app_origin.spec(); if (initialized_app_origins_.find(app_origin) != initialized_app_origins_.end()) { DVLOG(1) << "The app is already initialized: " << app_origin.spec(); callback.Run(fileapi::SYNC_STATUS_OK); return; } local_file_service_->MaybeInitializeFileSystemContext( app_origin, service_name, file_system_context, base::Bind(&SyncFileSystemService::DidInitializeFileSystem, AsWeakPtr(), app_origin, callback)); } void SyncFileSystemService::GetConflictFiles( const GURL& app_origin, const std::string& service_name, const fileapi::SyncFileSetCallback& callback) { DCHECK(remote_file_service_); DCHECK(app_origin == app_origin.GetOrigin()); if (!ContainsKey(initialized_app_origins_, app_origin)) { callback.Run(fileapi::SYNC_STATUS_NOT_INITIALIZED, fileapi::FileSystemURLSet()); return; } remote_file_service_->GetConflictFiles( app_origin, base::Bind(&VerifyFileSystemURLSetCallback, AsWeakPtr(), app_origin, service_name, callback)); } void SyncFileSystemService::GetConflictFileInfo( const GURL& app_origin, const std::string& service_name, const FileSystemURL& url, const ConflictFileInfoCallback& callback) { DCHECK(local_file_service_); DCHECK(remote_file_service_); DCHECK(app_origin == app_origin.GetOrigin()); if (!ContainsKey(initialized_app_origins_, app_origin)) { callback.Run(fileapi::SYNC_STATUS_NOT_INITIALIZED, fileapi::ConflictFileInfo()); return; } // Call DidGetConflictFileInfo when both remote and local service's // GetFileMetadata calls are done. SyncFileMetadata* remote_metadata = new SyncFileMetadata; SyncFileMetadata* local_metadata = new SyncFileMetadata; SyncStatusCallback completion_callback = base::Bind(&SyncFileSystemService::DidGetConflictFileInfo, AsWeakPtr(), callback, url, base::Owned(local_metadata), base::Owned(remote_metadata)); scoped_refptr<SharedCallbackRunner> callback_runner( new SharedCallbackRunner(completion_callback)); local_file_service_->GetLocalFileMetadata( url, callback_runner->CreateAssignAndRunCallback(local_metadata)); remote_file_service_->GetRemoteFileMetadata( url, callback_runner->CreateAssignAndRunCallback(remote_metadata)); } void SyncFileSystemService::GetFileSyncStatus( const fileapi::FileSystemURL& url, const fileapi::SyncFileStatusCallback& callback) { DCHECK(local_file_service_); DCHECK(remote_file_service_); if (!ContainsKey(initialized_app_origins_, url.origin())) { base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(callback, fileapi::SYNC_STATUS_NOT_INITIALIZED, fileapi::SYNC_FILE_STATUS_UNKNOWN)); return; } if (remote_file_service_->IsConflicting(url)) { base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(callback, fileapi::SYNC_STATUS_OK, fileapi::SYNC_FILE_STATUS_CONFLICTING)); return; } local_file_service_->HasPendingLocalChanges( url, base::Bind(&SyncFileSystemService::DidGetLocalChangeStatus, AsWeakPtr(), callback)); } void SyncFileSystemService::AddSyncEventObserver(SyncEventObserver* observer) { observers_.AddObserver(observer); } void SyncFileSystemService::RemoveSyncEventObserver( SyncEventObserver* observer) { observers_.RemoveObserver(observer); } SyncFileSystemService::SyncFileSystemService(Profile* profile) : profile_(profile), pending_local_changes_(0), pending_remote_changes_(0), local_sync_running_(false), remote_sync_running_(false), is_waiting_remote_sync_enabled_(false), auto_sync_enabled_(true) { } void SyncFileSystemService::Initialize( scoped_ptr<LocalFileSyncService> local_file_service, scoped_ptr<RemoteFileSyncService> remote_file_service) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(local_file_service); DCHECK(remote_file_service); DCHECK(profile_); local_file_service_ = local_file_service.Pass(); remote_file_service_ = remote_file_service.Pass(); local_file_service_->AddChangeObserver(this); remote_file_service_->AddObserver(this); } void SyncFileSystemService::DidGetConflictFileInfo( const ConflictFileInfoCallback& callback, const FileSystemURL& url, const SyncFileMetadata* local_metadata, const SyncFileMetadata* remote_metadata, SyncStatusCode status) { DCHECK(local_metadata); DCHECK(remote_metadata); fileapi::ConflictFileInfo info; info.url = url; info.local_metadata = *local_metadata; info.remote_metadata = *remote_metadata; callback.Run(status, info); } void SyncFileSystemService::DidInitializeFileSystem( const GURL& app_origin, const fileapi::SyncStatusCallback& callback, fileapi::SyncStatusCode status) { DVLOG(1) << "DidInitializeFileSystem: " << app_origin.spec() << " " << status; if (status != fileapi::SYNC_STATUS_OK) { callback.Run(status); return; } // Local side of initialization for the app is done. // Continue on initializing the remote side. remote_file_service_->RegisterOriginForTrackingChanges( app_origin, base::Bind(&SyncFileSystemService::DidRegisterOrigin, AsWeakPtr(), app_origin, callback)); } void SyncFileSystemService::DidRegisterOrigin( const GURL& app_origin, const fileapi::SyncStatusCallback& callback, fileapi::SyncStatusCode status) { DVLOG(1) << "DidRegisterOrigin: " << app_origin.spec() << " " << status; if (status == fileapi::SYNC_STATUS_OK) initialized_app_origins_.insert(app_origin); callback.Run(status); } void SyncFileSystemService::MaybeStartSync() { if (!profile_ || !auto_sync_enabled_) return; DCHECK(local_file_service_); DCHECK(remote_file_service_); MaybeStartRemoteSync(); MaybeStartLocalSync(); } void SyncFileSystemService::MaybeStartRemoteSync() { if (remote_file_service_->GetCurrentState() == REMOTE_SERVICE_DISABLED) return; // See if we cannot / should not start a new remote sync. if (remote_sync_running_ || pending_remote_changes_ == 0) return; // If we have registered a URL for waiting until sync is enabled on a // file (and the registerred URL seems to be still valid) it won't be // worth trying to start another remote sync. if (is_waiting_remote_sync_enabled_) return; DVLOG(1) << "Calling ProcessRemoteChange"; remote_sync_running_ = true; remote_file_service_->ProcessRemoteChange( local_file_service_.get(), base::Bind(&SyncFileSystemService::DidProcessRemoteChange, AsWeakPtr())); } void SyncFileSystemService::MaybeStartLocalSync() { // If the remote service is not ready probably we should not start a // local sync yet. // (We should be still trying a remote sync so the state should become OK // if the remote-side attempt succeeds.) if (remote_file_service_->GetCurrentState() != REMOTE_SERVICE_OK) return; // See if we cannot / should not start a new local sync. if (local_sync_running_ || pending_local_changes_ == 0) return; DVLOG(1) << "Calling ProcessLocalChange"; local_sync_running_ = true; local_file_service_->ProcessLocalChange( remote_file_service_->GetLocalChangeProcessor(), base::Bind(&SyncFileSystemService::DidProcessLocalChange, AsWeakPtr())); } void SyncFileSystemService::DidProcessRemoteChange( fileapi::SyncStatusCode status, const FileSystemURL& url, fileapi::SyncOperationResult result) { DVLOG(1) << "DidProcessRemoteChange: " << " status=" << status << " (" << SyncStatusCodeToString(status) << ")" << " url=" << url.DebugString() << " operation_result=" << result; DCHECK(remote_sync_running_); remote_sync_running_ = false; if (status != fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC && remote_file_service_->GetCurrentState() != REMOTE_SERVICE_DISABLED) { DCHECK(url.is_valid()); local_file_service_->ClearSyncFlagForURL(url); } if (status == fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC) { // We seem to have no changes to work on for now. // TODO(kinuko): Might be better setting a timer to call MaybeStartSync. return; } if (status == fileapi::SYNC_STATUS_FILE_BUSY) { is_waiting_remote_sync_enabled_ = true; local_file_service_->RegisterURLForWaitingSync( url, base::Bind(&SyncFileSystemService::OnSyncEnabledForRemoteSync, AsWeakPtr())); return; } if ((status == fileapi::SYNC_STATUS_OK || status == fileapi::SYNC_STATUS_HAS_CONFLICT) && result != fileapi::SYNC_OPERATION_NONE) { // Notify observers of the changes made for a remote sync. FOR_EACH_OBSERVER(SyncEventObserver, observers_, OnFileSynced(url, result)); } base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::DidProcessLocalChange( fileapi::SyncStatusCode status, const FileSystemURL& url) { DVLOG(1) << "DidProcessLocalChange:" << " status=" << status << " (" << SyncStatusCodeToString(status) << ")" << " url=" << url.DebugString(); DCHECK(local_sync_running_); local_sync_running_ = false; if (status == fileapi::SYNC_STATUS_NO_CHANGE_TO_SYNC) { // We seem to have no changes to work on for now. return; } DCHECK(url.is_valid()); local_file_service_->ClearSyncFlagForURL(url); if (status == fileapi::SYNC_STATUS_HAS_CONFLICT) { FOR_EACH_OBSERVER(SyncEventObserver, observers_, OnFileSynced(url, fileapi::SYNC_OPERATION_CONFLICTED)); } base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::DidGetLocalChangeStatus( const fileapi::SyncFileStatusCallback& callback, bool has_pending_local_changes) { callback.Run( fileapi::SYNC_STATUS_OK, has_pending_local_changes ? fileapi::SYNC_FILE_STATUS_HAS_PENDING_CHANGES : fileapi::SYNC_FILE_STATUS_SYNCED); } void SyncFileSystemService::OnSyncEnabledForRemoteSync() { is_waiting_remote_sync_enabled_ = false; MaybeStartRemoteSync(); } void SyncFileSystemService::OnLocalChangeAvailable(int64 pending_changes) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(pending_changes, 0); DVLOG(1) << "OnLocalChangeAvailable: " << pending_changes; pending_local_changes_ = pending_changes; base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::OnRemoteChangeQueueUpdated(int64 pending_changes) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK_GE(pending_changes, 0); DVLOG(1) << "OnRemoteChangeQueueUpdated: " << pending_changes; pending_remote_changes_ = pending_changes; if (pending_changes > 0) { // The smallest change available might have changed from the previous one. // Reset the is_waiting_remote_sync_enabled_ flag so that we can retry. is_waiting_remote_sync_enabled_ = false; } base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } void SyncFileSystemService::OnRemoteServiceStateUpdated( RemoteServiceState state, const std::string& description) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DVLOG(1) << "OnRemoteServiceStateUpdated: " << state << " " << description; if (state == REMOTE_SERVICE_OK) { base::MessageLoopProxy::current()->PostTask( FROM_HERE, base::Bind(&SyncFileSystemService::MaybeStartSync, AsWeakPtr())); } FOR_EACH_OBSERVER( SyncEventObserver, observers_, OnSyncStateUpdated(GURL(), RemoteStateToSyncServiceState(state), description)); } // SyncFileSystemServiceFactory ----------------------------------------------- // static SyncFileSystemService* SyncFileSystemServiceFactory::GetForProfile( Profile* profile) { return static_cast<SyncFileSystemService*>( GetInstance()->GetServiceForProfile(profile, true)); } // static SyncFileSystemServiceFactory* SyncFileSystemServiceFactory::GetInstance() { return Singleton<SyncFileSystemServiceFactory>::get(); } void SyncFileSystemServiceFactory::set_mock_remote_file_service( scoped_ptr<RemoteFileSyncService> mock_remote_service) { mock_remote_file_service_ = mock_remote_service.Pass(); } SyncFileSystemServiceFactory::SyncFileSystemServiceFactory() : ProfileKeyedServiceFactory("SyncFileSystemService", ProfileDependencyManager::GetInstance()) { } SyncFileSystemServiceFactory::~SyncFileSystemServiceFactory() {} ProfileKeyedService* SyncFileSystemServiceFactory::BuildServiceInstanceFor( Profile* profile) const { SyncFileSystemService* service = new SyncFileSystemService(profile); scoped_ptr<LocalFileSyncService> local_file_service( new LocalFileSyncService(profile)); scoped_ptr<RemoteFileSyncService> remote_file_service; if (mock_remote_file_service_) remote_file_service = mock_remote_file_service_.Pass(); else remote_file_service.reset(new DriveFileSyncService(profile)); service->Initialize(local_file_service.Pass(), remote_file_service.Pass()); return service; } } // namespace sync_file_system
18,656
5,825
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2017 MaNGOS project <https://getmangos.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "Common.h" #include "Database/DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "World.h" #include "ObjectMgr.h" #include "AccountMgr.h" #include "PlayerDump.h" #include "SpellMgr.h" #include "Player.h" #include "Opcodes.h" #include "GameObject.h" #include "Chat.h" #include "Log.h" #include "Guild.h" #include "GuildMgr.h" #include "ObjectAccessor.h" #include "MapManager.h" #include "MassMailMgr.h" #include "ScriptMgr.h" #include "Language.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" #include "Weather.h" #include "PointMovementGenerator.h" #include "PathFinder.h" #include "TargetedMovementGenerator.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" #include "SystemConfig.h" #include "Config/Config.h" #include "Mail.h" #include "Util.h" #include "ItemEnchantmentMgr.h" #include "BattleGround/BattleGroundMgr.h" #include "MapPersistentStateMgr.h" #include "InstanceData.h" #include "CreatureEventAIMgr.h" #include "DBCEnums.h" #include "AuctionHouseBot/AuctionHouseBot.h" #include "SQLStorages.h" static uint32 ahbotQualityIds[MAX_AUCTION_QUALITY] = { LANG_AHBOT_QUALITY_GREY, LANG_AHBOT_QUALITY_WHITE, LANG_AHBOT_QUALITY_GREEN, LANG_AHBOT_QUALITY_BLUE, LANG_AHBOT_QUALITY_PURPLE, LANG_AHBOT_QUALITY_ORANGE, LANG_AHBOT_QUALITY_YELLOW }; bool ChatHandler::HandleAHBotItemsAmountCommand(char* args) { uint32 qVals[MAX_AUCTION_QUALITY]; for (int i = 0; i < MAX_AUCTION_QUALITY; ++i) if (!ExtractUInt32(&args, qVals[i])) { return false; } sAuctionBot.SetItemsAmount(qVals); for (int i = 0; i < MAX_AUCTION_QUALITY; ++i) { PSendSysMessage(LANG_AHBOT_ITEMS_AMOUNT, GetMangosString(ahbotQualityIds[i]), sAuctionBotConfig.getConfigItemQualityAmount(AuctionQuality(i))); } return true; } template<int Q> bool ChatHandler::HandleAHBotItemsAmountQualityCommand(char* args) { uint32 qVal; if (!ExtractUInt32(&args, qVal)) { return false; } sAuctionBot.SetItemsAmountForQuality(AuctionQuality(Q), qVal); PSendSysMessage(LANG_AHBOT_ITEMS_AMOUNT, GetMangosString(ahbotQualityIds[Q]), sAuctionBotConfig.getConfigItemQualityAmount(AuctionQuality(Q))); return true; } template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_GREY>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_WHITE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_GREEN>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_BLUE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_PURPLE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_ORANGE>(char*); template bool ChatHandler::HandleAHBotItemsAmountQualityCommand<AUCTION_QUALITY_YELLOW>(char*); bool ChatHandler::HandleAHBotItemsRatioCommand(char* args) { uint32 rVal[MAX_AUCTION_HOUSE_TYPE]; for (int i = 0; i < MAX_AUCTION_HOUSE_TYPE; ++i) if (!ExtractUInt32(&args, rVal[i])) { return false; } sAuctionBot.SetItemsRatio(rVal[0], rVal[1], rVal[2]); for (int i = 0; i < MAX_AUCTION_HOUSE_TYPE; ++i) { PSendSysMessage(LANG_AHBOT_ITEMS_RATIO, AuctionBotConfig::GetHouseTypeName(AuctionHouseType(i)), sAuctionBotConfig.getConfigItemAmountRatio(AuctionHouseType(i))); } return true; } template<int H> bool ChatHandler::HandleAHBotItemsRatioHouseCommand(char* args) { uint32 rVal; if (!ExtractUInt32(&args, rVal)) { return false; } sAuctionBot.SetItemsRatioForHouse(AuctionHouseType(H), rVal); PSendSysMessage(LANG_AHBOT_ITEMS_RATIO, AuctionBotConfig::GetHouseTypeName(AuctionHouseType(H)), sAuctionBotConfig.getConfigItemAmountRatio(AuctionHouseType(H))); return true; } template bool ChatHandler::HandleAHBotItemsRatioHouseCommand<AUCTION_HOUSE_ALLIANCE>(char*); template bool ChatHandler::HandleAHBotItemsRatioHouseCommand<AUCTION_HOUSE_HORDE>(char*); template bool ChatHandler::HandleAHBotItemsRatioHouseCommand<AUCTION_HOUSE_NEUTRAL>(char*); bool ChatHandler::HandleAHBotRebuildCommand(char* args) { bool all = false; if (*args) { if (!ExtractLiteralArg(&args, "all")) { return false; } all = true; } sAuctionBot.Rebuild(all); return true; } bool ChatHandler::HandleAHBotReloadCommand(char* /*args*/) { if (sAuctionBot.ReloadAllConfig()) { SendSysMessage(LANG_AHBOT_RELOAD_OK); return true; } else { SendSysMessage(LANG_AHBOT_RELOAD_FAIL); SetSentErrorMessage(true); return false; } } bool ChatHandler::HandleAHBotStatusCommand(char* args) { bool all = false; if (*args) { if (!ExtractLiteralArg(&args, "all")) { return false; } all = true; } AuctionHouseBotStatusInfo statusInfo; sAuctionBot.PrepareStatusInfos(statusInfo); if (!m_session) { SendSysMessage(LANG_AHBOT_STATUS_BAR_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_TITLE1_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_MIDBAR_CONSOLE); } else { SendSysMessage(LANG_AHBOT_STATUS_TITLE1_CHAT); } uint32 fmtId = m_session ? LANG_AHBOT_STATUS_FORMAT_CHAT : LANG_AHBOT_STATUS_FORMAT_CONSOLE; PSendSysMessage(fmtId, GetMangosString(LANG_AHBOT_STATUS_ITEM_COUNT), statusInfo[AUCTION_HOUSE_ALLIANCE].ItemsCount, statusInfo[AUCTION_HOUSE_HORDE].ItemsCount, statusInfo[AUCTION_HOUSE_NEUTRAL].ItemsCount, statusInfo[AUCTION_HOUSE_ALLIANCE].ItemsCount + statusInfo[AUCTION_HOUSE_HORDE].ItemsCount + statusInfo[AUCTION_HOUSE_NEUTRAL].ItemsCount); if (all) { PSendSysMessage(fmtId, GetMangosString(LANG_AHBOT_STATUS_ITEM_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_ALLIANCE_ITEM_AMOUNT_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_HORDE_ITEM_AMOUNT_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_NEUTRAL_ITEM_AMOUNT_RATIO), sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_ALLIANCE_ITEM_AMOUNT_RATIO) + sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_HORDE_ITEM_AMOUNT_RATIO) + sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_NEUTRAL_ITEM_AMOUNT_RATIO)); if (!m_session) { SendSysMessage(LANG_AHBOT_STATUS_BAR_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_TITLE2_CONSOLE); SendSysMessage(LANG_AHBOT_STATUS_MIDBAR_CONSOLE); } else { SendSysMessage(LANG_AHBOT_STATUS_TITLE2_CHAT); } for (int i = 0; i < MAX_AUCTION_QUALITY; ++i) PSendSysMessage(fmtId, GetMangosString(ahbotQualityIds[i]), statusInfo[AUCTION_HOUSE_ALLIANCE].QualityInfo[i], statusInfo[AUCTION_HOUSE_HORDE].QualityInfo[i], statusInfo[AUCTION_HOUSE_NEUTRAL].QualityInfo[i], sAuctionBotConfig.getConfigItemQualityAmount(AuctionQuality(i))); } if (!m_session) { SendSysMessage(LANG_AHBOT_STATUS_BAR_CONSOLE); } return true; } // reload commands bool ChatHandler::HandleReloadAllCommand(char* /*args*/) { HandleReloadSkillFishingBaseLevelCommand((char*)""); HandleReloadAllAchievementCommand((char*)""); HandleReloadAllAreaCommand((char*)""); HandleReloadAutoBroadcastCommand((char*)""); HandleReloadAllEventAICommand((char*)""); HandleReloadAllLootCommand((char*)""); HandleReloadAllNpcCommand((char*)""); HandleReloadAllQuestCommand((char*)""); HandleReloadAllSpellCommand((char*)""); HandleReloadAllItemCommand((char*)""); HandleReloadAllGossipsCommand((char*)""); HandleReloadAllLocalesCommand((char*)""); HandleReloadMailLevelRewardCommand((char*)""); HandleReloadCommandCommand((char*)""); HandleReloadReservedNameCommand((char*)""); HandleReloadMangosStringCommand((char*)""); HandleReloadGameTeleCommand((char*)""); return true; } bool ChatHandler::HandleReloadAllAchievementCommand(char* /*args*/) { HandleReloadAchievementCriteriaRequirementCommand((char*)""); HandleReloadAchievementRewardCommand((char*)""); return true; } bool ChatHandler::HandleReloadAllAreaCommand(char* /*args*/) { // HandleReloadQuestAreaTriggersCommand((char*)""); -- reloaded in HandleReloadAllQuestCommand HandleReloadAreaTriggerTeleportCommand((char*)""); HandleReloadAreaTriggerTavernCommand((char*)""); HandleReloadGameGraveyardZoneCommand((char*)""); return true; } bool ChatHandler::HandleReloadAllLootCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables..."); LoadLootTables(); SendGlobalSysMessage("DB tables `*_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadAllNpcCommand(char* args) { if (*args != 'a') // will be reloaded from all_gossips { HandleReloadNpcGossipCommand((char*)"a"); } HandleReloadNpcTrainerCommand((char*)"a"); HandleReloadNpcVendorCommand((char*)"a"); HandleReloadPointsOfInterestCommand((char*)"a"); HandleReloadSpellClickSpellsCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllQuestCommand(char* /*args*/) { HandleReloadQuestAreaTriggersCommand((char*)"a"); HandleReloadQuestPOICommand((char*)"a"); HandleReloadQuestTemplateCommand((char*)"a"); sLog.outString("Re-Loading Quests Relations..."); sObjectMgr.LoadQuestRelations(); SendGlobalSysMessage("DB tables `*_questrelation` and `*_involvedrelation` reloaded."); return true; } bool ChatHandler::HandleReloadAllScriptsCommand(char* /*args*/) { if (sScriptMgr.IsScriptScheduled()) { PSendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } sLog.outString("Re-Loading Scripts..."); HandleReloadDBScriptsOnCreatureDeathCommand((char*)"a"); HandleReloadDBScriptsOnGoUseCommand((char*)"a"); HandleReloadDBScriptsOnGossipCommand((char*)"a"); HandleReloadDBScriptsOnEventCommand((char*)"a"); HandleReloadDBScriptsOnQuestEndCommand((char*)"a"); HandleReloadDBScriptsOnQuestStartCommand((char*)"a"); HandleReloadDBScriptsOnSpellCommand((char*)"a"); SendGlobalSysMessage("DB tables `*_scripts` reloaded."); HandleReloadDbScriptStringCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllEventAICommand(char* /*args*/) { HandleReloadEventAITextsCommand((char*)"a"); HandleReloadEventAISummonsCommand((char*)"a"); HandleReloadEventAIScriptsCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllSpellCommand(char* /*args*/) { HandleReloadSkillDiscoveryTemplateCommand((char*)"a"); HandleReloadSkillExtraItemTemplateCommand((char*)"a"); HandleReloadSpellAreaCommand((char*)"a"); HandleReloadSpellChainCommand((char*)"a"); HandleReloadSpellElixirCommand((char*)"a"); HandleReloadSpellLearnSpellCommand((char*)"a"); HandleReloadSpellProcEventCommand((char*)"a"); HandleReloadSpellBonusesCommand((char*)"a"); HandleReloadSpellProcItemEnchantCommand((char*)"a"); HandleReloadSpellScriptTargetCommand((char*)"a"); HandleReloadSpellTargetPositionCommand((char*)"a"); HandleReloadSpellThreatsCommand((char*)"a"); HandleReloadSpellPetAurasCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllGossipsCommand(char* args) { if (*args != 'a') // already reload from all_scripts { HandleReloadDBScriptsOnGossipCommand((char*)"a"); } HandleReloadGossipMenuCommand((char*)"a"); HandleReloadNpcGossipCommand((char*)"a"); HandleReloadPointsOfInterestCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllItemCommand(char* /*args*/) { HandleReloadPageTextsCommand((char*)"a"); HandleReloadItemConvertCommand((char*)"a"); HandleReloadItemEnchantementsCommand((char*)"a"); HandleReloadItemRequiredTragetCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadAllLocalesCommand(char* /*args*/) { HandleReloadLocalesAchievementRewardCommand((char*)"a"); HandleReloadLocalesCreatureCommand((char*)"a"); HandleReloadLocalesGameobjectCommand((char*)"a"); HandleReloadLocalesGossipMenuOptionCommand((char*)"a"); HandleReloadLocalesItemCommand((char*)"a"); HandleReloadLocalesNpcTextCommand((char*)"a"); HandleReloadLocalesPageTextCommand((char*)"a"); HandleReloadLocalesPointsOfInterestCommand((char*)"a"); HandleReloadLocalesQuestCommand((char*)"a"); return true; } bool ChatHandler::HandleReloadConfigCommand(char* /*args*/) { sLog.outString("Re-Loading config settings..."); sWorld.LoadConfigSettings(true); sMapMgr.InitializeVisibilityDistanceInfo(); SendGlobalSysMessage("World config settings reloaded."); return true; } bool ChatHandler::HandleReloadAchievementCriteriaRequirementCommand(char* /*args*/) { sLog.outString("Re-Loading Additional Achievement Criteria Requirements Data..."); sAchievementMgr.LoadAchievementCriteriaRequirements(); SendGlobalSysMessage("DB table `achievement_criteria_requirement` reloaded."); return true; } bool ChatHandler::HandleReloadAchievementRewardCommand(char* /*args*/) { sLog.outString("Re-Loading Achievement Reward Data..."); sAchievementMgr.LoadRewards(); SendGlobalSysMessage("DB table `achievement_reward` reloaded."); return true; } bool ChatHandler::HandleReloadAreaTriggerTavernCommand(char* /*args*/) { sLog.outString("Re-Loading Tavern Area Triggers..."); sObjectMgr.LoadTavernAreaTriggers(); SendGlobalSysMessage("DB table `areatrigger_tavern` reloaded."); return true; } bool ChatHandler::HandleReloadAreaTriggerTeleportCommand(char* /*args*/) { sLog.outString("Re-Loading AreaTrigger teleport definitions..."); sObjectMgr.LoadAreaTriggerTeleports(); SendGlobalSysMessage("DB table `areatrigger_teleport` reloaded."); return true; } bool ChatHandler::HandleReloadAutoBroadcastCommand(char* /*args*/) { sLog.outString("Re-Loading broadcast strings..."); sWorld.LoadBroadcastStrings(); SendGlobalSysMessage("Broadcast strings reloaded."); return true; } bool ChatHandler::HandleReloadCommandCommand(char* /*args*/) { load_command_table = true; SendGlobalSysMessage("DB table `command` will be reloaded at next chat command use."); return true; } bool ChatHandler::HandleReloadCreatureQuestRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`creature_questrelation`)"); sObjectMgr.LoadCreatureQuestRelations(); SendGlobalSysMessage("DB table `creature_questrelation` (creature quest givers) reloaded."); return true; } bool ChatHandler::HandleReloadCreatureQuestInvRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`creature_involvedrelation`)"); sObjectMgr.LoadCreatureInvolvedRelations(); SendGlobalSysMessage("DB table `creature_involvedrelation` (creature quest takers) reloaded."); return true; } bool ChatHandler::HandleReloadConditionsCommand(char* /*args*/) { sLog.outString("Re-Loading `conditions`... "); sObjectMgr.LoadConditions(); SendGlobalSysMessage("DB table `conditions` reloaded."); return true; } bool ChatHandler::HandleReloadGossipMenuCommand(char* /*args*/) { sObjectMgr.LoadGossipMenus(); SendGlobalSysMessage("DB tables `gossip_menu` and `gossip_menu_option` reloaded."); return true; } bool ChatHandler::HandleReloadGOQuestRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`gameobject_questrelation`)"); sObjectMgr.LoadGameobjectQuestRelations(); SendGlobalSysMessage("DB table `gameobject_questrelation` (gameobject quest givers) reloaded."); return true; } bool ChatHandler::HandleReloadGOQuestInvRelationsCommand(char* /*args*/) { sLog.outString("Loading Quests Relations... (`gameobject_involvedrelation`)"); sObjectMgr.LoadGameobjectInvolvedRelations(); SendGlobalSysMessage("DB table `gameobject_involvedrelation` (gameobject quest takers) reloaded."); return true; } bool ChatHandler::HandleReloadQuestAreaTriggersCommand(char* /*args*/) { sLog.outString("Re-Loading Quest Area Triggers..."); sObjectMgr.LoadQuestAreaTriggers(); SendGlobalSysMessage("DB table `areatrigger_involvedrelation` (quest area triggers) reloaded."); return true; } bool ChatHandler::HandleReloadQuestTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading Quest Templates..."); sObjectMgr.LoadQuests(); SendGlobalSysMessage("DB table `quest_template` (quest definitions) reloaded."); /// dependent also from `gameobject` but this table not reloaded anyway sLog.outString("Re-Loading GameObjects for quests..."); sObjectMgr.LoadGameObjectForQuests(); SendGlobalSysMessage("Data GameObjects for quests reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesCreatureCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`creature_loot_template`)"); LoadLootTemplates_Creature(); LootTemplates_Creature.CheckLootRefs(); SendGlobalSysMessage("DB table `creature_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesDisenchantCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`disenchant_loot_template`)"); LoadLootTemplates_Disenchant(); LootTemplates_Disenchant.CheckLootRefs(); SendGlobalSysMessage("DB table `disenchant_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesFishingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`fishing_loot_template`)"); LoadLootTemplates_Fishing(); LootTemplates_Fishing.CheckLootRefs(); SendGlobalSysMessage("DB table `fishing_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesGameobjectCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`gameobject_loot_template`)"); LoadLootTemplates_Gameobject(); LootTemplates_Gameobject.CheckLootRefs(); SendGlobalSysMessage("DB table `gameobject_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesItemCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`item_loot_template`)"); LoadLootTemplates_Item(); LootTemplates_Item.CheckLootRefs(); SendGlobalSysMessage("DB table `item_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesMillingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`milling_loot_template`)"); LoadLootTemplates_Milling(); LootTemplates_Milling.CheckLootRefs(); SendGlobalSysMessage("DB table `milling_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesPickpocketingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`pickpocketing_loot_template`)"); LoadLootTemplates_Pickpocketing(); LootTemplates_Pickpocketing.CheckLootRefs(); SendGlobalSysMessage("DB table `pickpocketing_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesProspectingCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`prospecting_loot_template`)"); LoadLootTemplates_Prospecting(); LootTemplates_Prospecting.CheckLootRefs(); SendGlobalSysMessage("DB table `prospecting_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesMailCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`mail_loot_template`)"); LoadLootTemplates_Mail(); LootTemplates_Mail.CheckLootRefs(); SendGlobalSysMessage("DB table `mail_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesReferenceCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`reference_loot_template`)"); LoadLootTemplates_Reference(); SendGlobalSysMessage("DB table `reference_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesSkinningCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`skinning_loot_template`)"); LoadLootTemplates_Skinning(); LootTemplates_Skinning.CheckLootRefs(); SendGlobalSysMessage("DB table `skinning_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadLootTemplatesSpellCommand(char* /*args*/) { sLog.outString("Re-Loading Loot Tables... (`spell_loot_template`)"); LoadLootTemplates_Spell(); LootTemplates_Spell.CheckLootRefs(); SendGlobalSysMessage("DB table `spell_loot_template` reloaded."); return true; } bool ChatHandler::HandleReloadMangosStringCommand(char* /*args*/) { sLog.outString("Re-Loading mangos_string Table!"); sObjectMgr.LoadMangosStrings(); SendGlobalSysMessage("DB table `mangos_string` reloaded."); return true; } bool ChatHandler::HandleReloadNpcGossipCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_gossip` Table!"); sObjectMgr.LoadNpcGossips(); SendGlobalSysMessage("DB table `npc_gossip` reloaded."); return true; } bool ChatHandler::HandleReloadNpcTextCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_text` Table!"); sObjectMgr.LoadGossipText(); SendGlobalSysMessage("DB table `npc_text` reloaded."); return true; } bool ChatHandler::HandleReloadNpcTrainerCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_trainer_template` Table!"); sObjectMgr.LoadTrainerTemplates(); SendGlobalSysMessage("DB table `npc_trainer_template` reloaded."); sLog.outString("Re-Loading `npc_trainer` Table!"); sObjectMgr.LoadTrainers(); SendGlobalSysMessage("DB table `npc_trainer` reloaded."); return true; } bool ChatHandler::HandleReloadNpcVendorCommand(char* /*args*/) { // not safe reload vendor template tables independent... sLog.outString("Re-Loading `npc_vendor_template` Table!"); sObjectMgr.LoadVendorTemplates(); SendGlobalSysMessage("DB table `npc_vendor_template` reloaded."); sLog.outString("Re-Loading `npc_vendor` Table!"); sObjectMgr.LoadVendors(); SendGlobalSysMessage("DB table `npc_vendor` reloaded."); return true; } bool ChatHandler::HandleReloadPointsOfInterestCommand(char* /*args*/) { sLog.outString("Re-Loading `points_of_interest` Table!"); sObjectMgr.LoadPointsOfInterest(); SendGlobalSysMessage("DB table `points_of_interest` reloaded."); return true; } bool ChatHandler::HandleReloadQuestPOICommand(char* /*args*/) { sLog.outString("Re-Loading `quest_poi` and `quest_poi_points` Tables!"); sObjectMgr.LoadQuestPOI(); SendGlobalSysMessage("DB Table `quest_poi` and `quest_poi_points` reloaded."); return true; } bool ChatHandler::HandleReloadSpellClickSpellsCommand(char* /*args*/) { sLog.outString("Re-Loading `npc_spellclick_spells` Table!"); sObjectMgr.LoadNPCSpellClickSpells(); SendGlobalSysMessage("DB table `npc_spellclick_spells` reloaded."); return true; } bool ChatHandler::HandleReloadReservedNameCommand(char* /*args*/) { sLog.outString("Loading ReservedNames... (`reserved_name`)"); sObjectMgr.LoadReservedPlayersNames(); SendGlobalSysMessage("DB table `reserved_name` (player reserved names) reloaded."); return true; } bool ChatHandler::HandleReloadReputationRewardRateCommand(char* /*args*/) { sLog.outString("Re-Loading `reputation_reward_rate` Table!"); sObjectMgr.LoadReputationRewardRate(); SendGlobalSysMessage("DB table `reputation_reward_rate` reloaded."); return true; } bool ChatHandler::HandleReloadReputationSpilloverTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading `reputation_spillover_template` Table!"); sObjectMgr.LoadReputationSpilloverTemplate(); SendGlobalSysMessage("DB table `reputation_spillover_template` reloaded."); return true; } bool ChatHandler::HandleReloadSkillDiscoveryTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading Skill Discovery Table..."); LoadSkillDiscoveryTable(); SendGlobalSysMessage("DB table `skill_discovery_template` (recipes discovered at crafting) reloaded."); return true; } bool ChatHandler::HandleReloadSkillExtraItemTemplateCommand(char* /*args*/) { sLog.outString("Re-Loading Skill Extra Item Table..."); LoadSkillExtraItemTable(); SendGlobalSysMessage("DB table `skill_extra_item_template` (extra item creation when crafting) reloaded."); return true; } bool ChatHandler::HandleReloadScriptBindingCommand(char* /*args*/) { sLog.outString("Trying to re-load `script_binding` Table!"); if (sScriptMgr.ReloadScriptBinding()) SendGlobalSysMessage("DB table `script_binding` reloaded."); else SendSysMessage("DENIED: DB table `script_binding` is reloadable only in Debug build."); return true; } bool ChatHandler::HandleReloadSkillFishingBaseLevelCommand(char* /*args*/) { sLog.outString("Re-Loading Skill Fishing base level requirements..."); sObjectMgr.LoadFishingBaseSkillLevel(); SendGlobalSysMessage("DB table `skill_fishing_base_level` (fishing base level for zone/subzone) reloaded."); return true; } bool ChatHandler::HandleReloadSpellAreaCommand(char* /*args*/) { sLog.outString("Re-Loading SpellArea Data..."); sSpellMgr.LoadSpellAreas(); SendGlobalSysMessage("DB table `spell_area` (spell dependences from area/quest/auras state) reloaded."); return true; } bool ChatHandler::HandleReloadSpellBonusesCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Bonus Data..."); sSpellMgr.LoadSpellBonuses(); SendGlobalSysMessage("DB table `spell_bonus_data` (spell damage/healing coefficients) reloaded."); return true; } bool ChatHandler::HandleReloadSpellChainCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Chain Data... "); sSpellMgr.LoadSpellChains(); SendGlobalSysMessage("DB table `spell_chain` (spell ranks) reloaded."); return true; } bool ChatHandler::HandleReloadSpellElixirCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Elixir types..."); sSpellMgr.LoadSpellElixirs(); SendGlobalSysMessage("DB table `spell_elixir` (spell elixir types) reloaded."); return true; } bool ChatHandler::HandleReloadSpellLearnSpellCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Learn Spells..."); sSpellMgr.LoadSpellLearnSpells(); SendGlobalSysMessage("DB table `spell_learn_spell` reloaded."); return true; } bool ChatHandler::HandleReloadSpellProcEventCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Proc Event conditions..."); sSpellMgr.LoadSpellProcEvents(); SendGlobalSysMessage("DB table `spell_proc_event` (spell proc trigger requirements) reloaded."); return true; } bool ChatHandler::HandleReloadSpellProcItemEnchantCommand(char* /*args*/) { sLog.outString("Re-Loading Spell Proc Item Enchant..."); sSpellMgr.LoadSpellProcItemEnchant(); SendGlobalSysMessage("DB table `spell_proc_item_enchant` (item enchantment ppm) reloaded."); return true; } bool ChatHandler::HandleReloadSpellScriptTargetCommand(char* /*args*/) { sLog.outString("Re-Loading SpellsScriptTarget..."); sSpellMgr.LoadSpellScriptTarget(); SendGlobalSysMessage("DB table `spell_script_target` (spell targets selection in case specific creature/GO requirements) reloaded."); return true; } bool ChatHandler::HandleReloadSpellTargetPositionCommand(char* /*args*/) { sLog.outString("Re-Loading spell target destination coordinates..."); sSpellMgr.LoadSpellTargetPositions(); SendGlobalSysMessage("DB table `spell_target_position` (destination coordinates for spell targets) reloaded."); return true; } bool ChatHandler::HandleReloadSpellThreatsCommand(char* /*args*/) { sLog.outString("Re-Loading Aggro Spells Definitions..."); sSpellMgr.LoadSpellThreats(); SendGlobalSysMessage("DB table `spell_threat` (spell aggro definitions) reloaded."); return true; } bool ChatHandler::HandleReloadSpellPetAurasCommand(char* /*args*/) { sLog.outString("Re-Loading Spell pet auras..."); sSpellMgr.LoadSpellPetAuras(); SendGlobalSysMessage("DB table `spell_pet_auras` reloaded."); return true; } bool ChatHandler::HandleReloadPageTextsCommand(char* /*args*/) { sLog.outString("Re-Loading Page Texts..."); sObjectMgr.LoadPageTexts(); SendGlobalSysMessage("DB table `page_texts` reloaded."); return true; } bool ChatHandler::HandleReloadItemEnchantementsCommand(char* /*args*/) { sLog.outString("Re-Loading Item Random Enchantments Table..."); LoadRandomEnchantmentsTable(); SendGlobalSysMessage("DB table `item_enchantment_template` reloaded."); return true; } bool ChatHandler::HandleReloadItemConvertCommand(char* /*args*/) { sLog.outString("Re-Loading Item Converts Table..."); sObjectMgr.LoadItemConverts(); SendGlobalSysMessage("DB table `item_convert` reloaded."); return true; } bool ChatHandler::HandleReloadItemRequiredTragetCommand(char* /*args*/) { sLog.outString("Re-Loading Item Required Targets Table..."); sObjectMgr.LoadItemRequiredTarget(); SendGlobalSysMessage("DB table `item_required_target` reloaded."); return true; } bool ChatHandler::HandleReloadBattleEventCommand(char* /*args*/) { sLog.outString("Re-Loading BattleGround Eventindexes..."); sBattleGroundMgr.LoadBattleEventIndexes(); SendGlobalSysMessage("DB table `gameobject_battleground` and `creature_battleground` reloaded."); return true; } bool ChatHandler::HandleReloadEventAITextsCommand(char* /*args*/) { sLog.outString("Re-Loading Texts from `creature_ai_texts`..."); sEventAIMgr.LoadCreatureEventAI_Texts(true); SendGlobalSysMessage("DB table `creature_ai_texts` reloaded."); return true; } bool ChatHandler::HandleReloadEventAISummonsCommand(char* /*args*/) { sLog.outString("Re-Loading Summons from `creature_ai_summons`..."); sEventAIMgr.LoadCreatureEventAI_Summons(true); SendGlobalSysMessage("DB table `creature_ai_summons` reloaded."); return true; } bool ChatHandler::HandleReloadEventAIScriptsCommand(char* /*args*/) { sLog.outString("Re-Loading Scripts from `creature_ai_scripts`..."); sEventAIMgr.LoadCreatureEventAI_Scripts(); SendGlobalSysMessage("DB table `creature_ai_scripts` reloaded."); return true; } bool ChatHandler::HandleReloadDbScriptStringCommand(char* /*args*/) { sLog.outString("Re-Loading Script strings from `db_script_string`..."); sScriptMgr.LoadDbScriptStrings(); SendGlobalSysMessage("DB table `db_script_string` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnGossipCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_GOSSIP]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_GOSSIP); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_GOSSIP]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnSpellCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_SPELL]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_SPELL); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_SPELL]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnQuestStartCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_QUEST_START]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_QUEST_START); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_QUEST_START]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnQuestEndCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_QUEST_END]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_QUEST_END); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_QUEST_END]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnEventCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_EVENT]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_EVENT); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_EVENT]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnGoUseCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_GO[_TEMPLATE]_USE]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_GO_USE); sScriptMgr.LoadDbScripts(DBS_ON_GOT_USE); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_GO[_TEMPLATE]_USE]` reloaded."); return true; } bool ChatHandler::HandleReloadDBScriptsOnCreatureDeathCommand(char* args) { if (sScriptMgr.IsScriptScheduled()) { SendSysMessage("DB scripts used currently, please attempt reload later."); SetSentErrorMessage(true); return false; } if (*args != 'a') { sLog.outString("Re-Loading Scripts from `db_scripts [type = DBS_ON_CREATURE_DEATH]`..."); } sScriptMgr.LoadDbScripts(DBS_ON_CREATURE_DEATH); if (*args != 'a') SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_CREATURE_DEATH]` reloaded."); return true; } bool ChatHandler::HandleReloadGameGraveyardZoneCommand(char* /*args*/) { sLog.outString("Re-Loading Graveyard-zone links..."); sObjectMgr.LoadGraveyardZones(); SendGlobalSysMessage("DB table `game_graveyard_zone` reloaded."); return true; } bool ChatHandler::HandleReloadGameTeleCommand(char* /*args*/) { sLog.outString("Re-Loading Game Tele coordinates..."); sObjectMgr.LoadGameTele(); SendGlobalSysMessage("DB table `game_tele` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesAchievementRewardCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Achievement Reward Data..."); sAchievementMgr.LoadRewardLocales(); SendGlobalSysMessage("DB table `locales_achievement_reward` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesCreatureCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Creature ..."); sObjectMgr.LoadCreatureLocales(); SendGlobalSysMessage("DB table `locales_creature` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesGameobjectCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Gameobject ... "); sObjectMgr.LoadGameObjectLocales(); SendGlobalSysMessage("DB table `locales_gameobject` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesGossipMenuOptionCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Gossip Menu Option ... "); sObjectMgr.LoadGossipMenuItemsLocales(); SendGlobalSysMessage("DB table `locales_gossip_menu_option` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesItemCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Item ... "); sObjectMgr.LoadItemLocales(); SendGlobalSysMessage("DB table `locales_item` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesNpcTextCommand(char* /*args*/) { sLog.outString("Re-Loading Locales NPC Text ... "); sObjectMgr.LoadGossipTextLocales(); SendGlobalSysMessage("DB table `locales_npc_text` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesPageTextCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Page Text ... "); sObjectMgr.LoadPageTextLocales(); SendGlobalSysMessage("DB table `locales_page_text` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesPointsOfInterestCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Points Of Interest ... "); sObjectMgr.LoadPointOfInterestLocales(); SendGlobalSysMessage("DB table `locales_points_of_interest` reloaded."); return true; } bool ChatHandler::HandleReloadLocalesQuestCommand(char* /*args*/) { sLog.outString("Re-Loading Locales Quest ... "); sObjectMgr.LoadQuestLocales(); SendGlobalSysMessage("DB table `locales_quest` reloaded."); return true; } bool ChatHandler::HandleReloadMailLevelRewardCommand(char* /*args*/) { sLog.outString("Re-Loading Player level dependent mail rewards..."); sObjectMgr.LoadMailLevelRewards(); SendGlobalSysMessage("DB table `mail_level_reward` reloaded."); return true; } bool ChatHandler::HandleReloadCreaturesStatsCommand(char* /*args*/) { sLog.outString("Re-Loading stats data..."); sObjectMgr.LoadCreatureClassLvlStats(); SendGlobalSysMessage("DB table `creature_template_classlevelstats` reloaded."); return true; } bool ChatHandler::HandleLoadScriptsCommand(char* args) { if (!*args) { return false; } switch (sScriptMgr.LoadScriptLibrary(args)) { case SCRIPT_LOAD_OK: sWorld.SendWorldText(LANG_SCRIPTS_RELOADED_ANNOUNCE); SendSysMessage(LANG_SCRIPTS_RELOADED_OK); break; case SCRIPT_LOAD_ERR_NOT_FOUND: SendSysMessage(LANG_SCRIPTS_NOT_FOUND); break; case SCRIPT_LOAD_ERR_WRONG_API: SendSysMessage(LANG_SCRIPTS_WRONG_API); break; case SCRIPT_LOAD_ERR_OUTDATED: SendSysMessage(LANG_SCRIPTS_OUTDATED); break; } return true; } bool ChatHandler::HandleAccountSetGmLevelCommand(char* args) { char* accountStr = ExtractOptNotLastArg(&args); std::string targetAccountName; Player* targetPlayer = NULL; uint32 targetAccountId = ExtractAccountId(&accountStr, &targetAccountName, &targetPlayer); if (!targetAccountId) { return false; } /// only target player different from self allowed if (GetAccountId() == targetAccountId) { return false; } int32 gm; if (!ExtractInt32(&args, gm)) { return false; } if (gm < SEC_PLAYER || gm > SEC_ADMINISTRATOR) { SendSysMessage(LANG_BAD_VALUE); SetSentErrorMessage(true); return false; } /// can set security level only for target with less security and to less security that we have /// This will reject self apply by specify account name if (HasLowerSecurityAccount(NULL, targetAccountId, true)) { return false; } /// account can't set security to same or grater level, need more power GM or console AccountTypes plSecurity = GetAccessLevel(); if (AccountTypes(gm) >= plSecurity) { SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); SetSentErrorMessage(true); return false; } if (targetPlayer) { ChatHandler(targetPlayer).PSendSysMessage(LANG_YOURS_SECURITY_CHANGED, GetNameLink().c_str(), gm); targetPlayer->GetSession()->SetSecurity(AccountTypes(gm)); } PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm); LoginDatabase.PExecute("UPDATE account SET gmlevel = '%i' WHERE id = '%u'", gm, targetAccountId); return true; } /// Set password for account bool ChatHandler::HandleAccountSetPasswordCommand(char* args) { ///- Get the command line arguments std::string account_name; uint32 targetAccountId = ExtractAccountId(&args, &account_name); if (!targetAccountId) { return false; } // allow or quoted string with possible spaces or literal without spaces char* szPassword1 = ExtractQuotedOrLiteralArg(&args); char* szPassword2 = ExtractQuotedOrLiteralArg(&args); if (!szPassword1 || !szPassword2) { return false; } /// can set password only for target with less security /// This is also reject self apply in fact if (HasLowerSecurityAccount(NULL, targetAccountId, true)) { return false; } if (strcmp(szPassword1, szPassword2)) { SendSysMessage(LANG_NEW_PASSWORDS_NOT_MATCH); SetSentErrorMessage(true); return false; } AccountOpResult result = sAccountMgr.ChangePassword(targetAccountId, szPassword1); switch (result) { case AOR_OK: SendSysMessage(LANG_COMMAND_PASSWORD); break; case AOR_NAME_NOT_EXIST: PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); SetSentErrorMessage(true); return false; case AOR_PASS_TOO_LONG: SendSysMessage(LANG_PASSWORD_TOO_LONG); SetSentErrorMessage(true); return false; default: SendSysMessage(LANG_COMMAND_NOTCHANGEPASSWORD); SetSentErrorMessage(true); return false; } // OK, but avoid normal report for hide passwords, but log use command for anyone char msg[100]; snprintf(msg, 100, ".account set password %s *** ***", account_name.c_str()); LogCommand(msg); SetSentErrorMessage(true); return false; } void ChatHandler::ShowAchievementCriteriaListHelper(AchievementCriteriaEntry const* criEntry, AchievementEntry const* achEntry, LocaleConstant loc, Player* target /*= NULL*/) { std::ostringstream ss; if (m_session) { ss << criEntry->ID << " - |cffffffff|Hachievement_criteria:" << criEntry->ID << "|h[" << criEntry->name[loc] << " " << localeNames[loc] << "]|h|r"; } else ss << criEntry->ID << " - " << criEntry->name[loc] << " " << localeNames[loc]; if (target) ss << " = " << target->GetAchievementMgr().GetCriteriaProgressCounter(criEntry); if (achEntry->flags & ACHIEVEMENT_FLAG_COUNTER) ss << GetMangosString(LANG_COUNTER); else { ss << " [" << AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry) << "]"; if (target && target->GetAchievementMgr().IsCompletedCriteria(criEntry, achEntry)) ss << GetMangosString(LANG_COMPLETE); } SendSysMessage(ss.str().c_str()); } bool ChatHandler::HandleAchievementCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target = NULL; if (nameStr) { if (!ExtractPlayerTarget(&nameStr, &target)) return false; } else target = getSelectedPlayer(); uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) return false; AchievementEntry const* achEntry = sAchievementStore.LookupEntry(achId); if (!achEntry) { PSendSysMessage(LANG_ACHIEVEMENT_NOT_EXIST, achId); SetSentErrorMessage(true); return false; } LocaleConstant loc = GetSessionDbcLocale(); CompletedAchievementData const* completed = target ? target->GetAchievementMgr().GetCompleteData(achId) : NULL; ShowAchievementListHelper(achEntry, loc, completed ? &completed->date : NULL, target); if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) { SendSysMessage(LANG_COMMAND_ACHIEVEMENT_CRITERIA); for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) ShowAchievementCriteriaListHelper(*itr, achEntry, loc, target); } return true; } bool ChatHandler::HandleAchievementAddCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target; if (!ExtractPlayerTarget(&nameStr, &target)) return false; uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) return false; AchievementEntry const* achEntry = sAchievementStore.LookupEntry(achId); if (!achEntry || achEntry->flags & ACHIEVEMENT_FLAG_COUNTER) { PSendSysMessage(LANG_ACHIEVEMENT_NOT_EXIST, achId); SetSentErrorMessage(true); return false; } AchievementMgr& mgr = target->GetAchievementMgr(); if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) { for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) { if (mgr.IsCompletedCriteria(*itr, achEntry)) continue; uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(*itr, achEntry); if (maxValue == std::numeric_limits<uint32>::max()) maxValue = 1; // Exception for counter like achievements, set them only to 1 mgr.SetCriteriaProgress(*itr, achEntry, maxValue, AchievementMgr::PROGRESS_SET); } } LocaleConstant loc = GetSessionDbcLocale(); CompletedAchievementData const* completed = target ? target->GetAchievementMgr().GetCompleteData(achId) : NULL; ShowAchievementListHelper(achEntry, loc, completed ? &completed->date : NULL, target); return true; } bool ChatHandler::HandleAchievementRemoveCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target; if (!ExtractPlayerTarget(&nameStr, &target)) return false; uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) return false; AchievementEntry const* achEntry = sAchievementStore.LookupEntry(achId); if (!achEntry) { PSendSysMessage(LANG_ACHIEVEMENT_NOT_EXIST, achId); SetSentErrorMessage(true); return false; } AchievementMgr& mgr = target->GetAchievementMgr(); if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) mgr.SetCriteriaProgress(*itr, achEntry, 0, AchievementMgr::PROGRESS_SET); LocaleConstant loc = GetSessionDbcLocale(); CompletedAchievementData const* completed = target ? target->GetAchievementMgr().GetCompleteData(achId) : NULL; ShowAchievementListHelper(achEntry, loc, completed ? &completed->date : NULL, target); return true; } bool ChatHandler::HandleAchievementCriteriaAddCommand(char* args) { Player* target; uint32 criId; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) { // maybe player first char* nameStr = ExtractArg(&args); if (!ExtractPlayerTarget(&nameStr, &target)) return false; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) return false; } else target = getSelectedPlayer(); AchievementCriteriaEntry const* criEntry = sAchievementCriteriaStore.LookupEntry(criId); if (!criEntry) { PSendSysMessage(LANG_ACHIEVEMENT_CRITERIA_NOT_EXIST, criId); SetSentErrorMessage(true); return false; } AchievementEntry const* achEntry = sAchievementStore.LookupEntry(criEntry->referredAchievement); if (!achEntry) return false; LocaleConstant loc = GetSessionDbcLocale(); uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry); if (maxValue == std::numeric_limits<uint32>::max()) maxValue = 1; // Exception for counter like achievements, set them only to 1 AchievementMgr& mgr = target->GetAchievementMgr(); // nothing do if completed if (mgr.IsCompletedCriteria(criEntry, achEntry)) { ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } uint32 progress = mgr.GetCriteriaProgressCounter(criEntry); uint32 val; if (!ExtractOptUInt32(&args, val, maxValue ? maxValue : 1)) return false; uint32 new_val; if (maxValue) new_val = progress < maxValue && maxValue - progress > val ? progress + val : maxValue; else { uint32 max_int = std::numeric_limits<uint32>::max(); new_val = progress < max_int && max_int - progress > val ? progress + val : max_int; } mgr.SetCriteriaProgress(criEntry, achEntry, new_val, AchievementMgr::PROGRESS_SET); ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } bool ChatHandler::HandleAchievementCriteriaRemoveCommand(char* args) { Player* target; uint32 criId; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) { // maybe player first char* nameStr = ExtractArg(&args); if (!ExtractPlayerTarget(&nameStr, &target)) return false; if (!ExtractUint32KeyFromLink(&args, "Hachievement_criteria", criId)) return false; } else target = getSelectedPlayer(); AchievementCriteriaEntry const* criEntry = sAchievementCriteriaStore.LookupEntry(criId); if (!criEntry) { PSendSysMessage(LANG_ACHIEVEMENT_CRITERIA_NOT_EXIST, criId); SetSentErrorMessage(true); return false; } AchievementEntry const* achEntry = sAchievementStore.LookupEntry(criEntry->referredAchievement); if (!achEntry) return false; LocaleConstant loc = GetSessionDbcLocale(); uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry); if (maxValue == std::numeric_limits<uint32>::max()) maxValue = 1; // Exception for counter like achievements, set them only to 1 AchievementMgr& mgr = target->GetAchievementMgr(); uint32 progress = mgr.GetCriteriaProgressCounter(criEntry); // nothing do if not started if (progress == 0) { ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } uint32 change; if (!ExtractOptUInt32(&args, change, maxValue ? maxValue : 1)) return false; uint32 newval = change < progress ? progress - change : 0; mgr.SetCriteriaProgress(criEntry, achEntry, newval, AchievementMgr::PROGRESS_SET); ShowAchievementCriteriaListHelper(criEntry, achEntry, loc, target); return true; } bool ChatHandler::HandleMaxSkillCommand(char* /*args*/) { Player* SelectedPlayer = getSelectedPlayer(); if (!SelectedPlayer) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // each skills that have max skill value dependent from level seted to current level max skill value SelectedPlayer->UpdateSkillsToMaxSkillsForLevel(); return true; } bool ChatHandler::HandleSetSkillCommand(char* args) { Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hskill:skill_id|h[name]|h|r char* skill_p = ExtractKeyFromLink(&args, "Hskill"); if (!skill_p) { return false; } int32 skill; if (!ExtractInt32(&skill_p, skill)) { return false; } int32 level; if (!ExtractInt32(&args, level)) { return false; } int32 maxskill; if (!ExtractOptInt32(&args, maxskill, target->GetPureMaxSkillValue(skill))) { return false; } if (skill <= 0) { PSendSysMessage(LANG_INVALID_SKILL_ID, skill); SetSentErrorMessage(true); return false; } SkillLineEntry const* sl = sSkillLineStore.LookupEntry(skill); if (!sl) { PSendSysMessage(LANG_INVALID_SKILL_ID, skill); SetSentErrorMessage(true); return false; } std::string tNameLink = GetNameLink(target); if (!target->GetSkillValue(skill)) { PSendSysMessage(LANG_SET_SKILL_ERROR, tNameLink.c_str(), skill, sl->name[GetSessionDbcLocale()]); SetSentErrorMessage(true); return false; } if (level <= 0 || level > maxskill || maxskill <= 0) { return false; } target->SetSkill(skill, level, maxskill); PSendSysMessage(LANG_SET_SKILL, skill, sl->name[GetSessionDbcLocale()], tNameLink.c_str(), level, maxskill); return true; } bool ChatHandler::HandleUnLearnCommand(char* args) { if (!*args) { return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r uint32 spell_id = ExtractSpellIdFromLink(&args); if (!spell_id) { return false; } bool allRanks = ExtractLiteralArg(&args, "all") != NULL; if (!allRanks && *args) // can be fail also at syntax error { return false; } Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } if (allRanks) { spell_id = sSpellMgr.GetFirstSpellInChain(spell_id); } if (target->HasSpell(spell_id)) { target->removeSpell(spell_id, false, !allRanks); } else { SendSysMessage(LANG_FORGET_SPELL); } if (GetTalentSpellCost(spell_id)) target->SendTalentsInfoData(false); return true; } bool ChatHandler::HandleCooldownCommand(char* args) { Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } std::string tNameLink = GetNameLink(target); if (!*args) { target->RemoveAllSpellCooldown(); PSendSysMessage(LANG_REMOVEALL_COOLDOWN, tNameLink.c_str()); } else { // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell_id = ExtractSpellIdFromLink(&args); if (!spell_id) { return false; } if (!sSpellStore.LookupEntry(spell_id)) { PSendSysMessage(LANG_UNKNOWN_SPELL, target == m_session->GetPlayer() ? GetMangosString(LANG_YOU) : tNameLink.c_str()); SetSentErrorMessage(true); return false; } target->RemoveSpellCooldown(spell_id, true); PSendSysMessage(LANG_REMOVE_COOLDOWN, spell_id, target == m_session->GetPlayer() ? GetMangosString(LANG_YOU) : tNameLink.c_str()); } return true; } bool ChatHandler::HandleLearnAllCommand(char* /*args*/) { static const char* allSpellList[] = { "3365", "6233", "6247", "6246", "6477", "6478", "22810", "8386", "21651", "21652", "522", "7266", "8597", "2479", "22027", "6603", "5019", "133", "168", "227", "5009", "9078", "668", "203", "20599", "20600", "81", "20597", "20598", "20864", "1459", "5504", "587", "5143", "118", "5505", "597", "604", "1449", "1460", "2855", "1008", "475", "5506", "1463", "12824", "8437", "990", "5145", "8450", "1461", "759", "8494", "8455", "8438", "6127", "8416", "6129", "8451", "8495", "8439", "3552", "8417", "10138", "12825", "10169", "10156", "10144", "10191", "10201", "10211", "10053", "10173", "10139", "10145", "10192", "10170", "10202", "10054", "10174", "10193", "12826", "2136", "143", "145", "2137", "2120", "3140", "543", "2138", "2948", "8400", "2121", "8444", "8412", "8457", "8401", "8422", "8445", "8402", "8413", "8458", "8423", "8446", "10148", "10197", "10205", "10149", "10215", "10223", "10206", "10199", "10150", "10216", "10207", "10225", "10151", "116", "205", "7300", "122", "837", "10", "7301", "7322", "6143", "120", "865", "8406", "6141", "7302", "8461", "8407", "8492", "8427", "8408", "6131", "7320", "10159", "8462", "10185", "10179", "10160", "10180", "10219", "10186", "10177", "10230", "10181", "10161", "10187", "10220", "2018", "2663", "12260", "2660", "3115", "3326", "2665", "3116", "2738", "3293", "2661", "3319", "2662", "9983", "8880", "2737", "2739", "7408", "3320", "2666", "3323", "3324", "3294", "22723", "23219", "23220", "23221", "23228", "23338", "10788", "10790", "5611", "5016", "5609", "2060", "10963", "10964", "10965", "22593", "22594", "596", "996", "499", "768", "17002", "1448", "1082", "16979", "1079", "5215", "20484", "5221", "15590", "17007", "6795", "6807", "5487", "1446", "1066", "5421", "3139", "779", "6811", "6808", "1445", "5216", "1737", "5222", "5217", "1432", "6812", "9492", "5210", "3030", "1441", "783", "6801", "20739", "8944", "9491", "22569", "5226", "6786", "1433", "8973", "1828", "9495", "9006", "6794", "8993", "5203", "16914", "6784", "9635", "22830", "20722", "9748", "6790", "9753", "9493", "9752", "9831", "9825", "9822", "5204", "5401", "22831", "6793", "9845", "17401", "9882", "9868", "20749", "9893", "9899", "9895", "9832", "9902", "9909", "22832", "9828", "9851", "9883", "9869", "17406", "17402", "9914", "20750", "9897", "9848", "3127", "107", "204", "9116", "2457", "78", "18848", "331", "403", "2098", "1752", "11278", "11288", "11284", "6461", "2344", "2345", "6463", "2346", "2352", "775", "1434", "1612", "71", "2468", "2458", "2467", "7164", "7178", "7367", "7376", "7381", "21156", "5209", "3029", "5201", "9849", "9850", "20719", "22568", "22827", "22828", "22829", "6809", "8972", "9005", "9823", "9827", "6783", "9913", "6785", "6787", "9866", "9867", "9894", "9896", "6800", "8992", "9829", "9830", "780", "769", "6749", "6750", "9755", "9754", "9908", "20745", "20742", "20747", "20748", "9746", "9745", "9880", "9881", "5391", "842", "3025", "3031", "3287", "3329", "1945", "3559", "4933", "4934", "4935", "4936", "5142", "5390", "5392", "5404", "5420", "6405", "7293", "7965", "8041", "8153", "9033", "9034", //"9036", problems with ghost state "16421", "21653", "22660", "5225", "9846", "2426", "5916", "6634", //"6718", phasing stealth, annoying for learn all case. "6719", "8822", "9591", "9590", "10032", "17746", "17747", "8203", "11392", "12495", "16380", "23452", "4079", "4996", "4997", "4998", "4999", "5000", "6348", "6349", "6481", "6482", "6483", "6484", "11362", "11410", "11409", "12510", "12509", "12885", "13142", "21463", "23460", "11421", "11416", "11418", "1851", "10059", "11423", "11417", "11422", "11419", "11424", "11420", "27", "31", "33", "34", "35", "15125", "21127", "22950", "1180", "201", "12593", "12842", "16770", "6057", "12051", "18468", "12606", "12605", "18466", "12502", "12043", "15060", "12042", "12341", "12848", "12344", "12353", "18460", "11366", "12350", "12352", "13043", "11368", "11113", "12400", "11129", "16766", "12573", "15053", "12580", "12475", "12472", "12953", "12488", "11189", "12985", "12519", "16758", "11958", "12490", "11426", "3565", "3562", "18960", "3567", "3561", "3566", "3563", "1953", "2139", "12505", "13018", "12522", "12523", "5146", "5144", "5148", "8419", "8418", "10213", "10212", "10157", "12524", "13019", "12525", "13020", "12526", "13021", "18809", "13031", "13032", "13033", "4036", "3920", "3919", "3918", "7430", "3922", "3923", "7411", "7418", "7421", "13262", "7412", "7415", "7413", "7416", "13920", "13921", "7745", "7779", "7428", "7457", "7857", "7748", "7426", "13421", "7454", "13378", "7788", "14807", "14293", "7795", "6296", "20608", "755", "444", "427", "428", "442", "447", "3578", "3581", "19027", "3580", "665", "3579", "3577", "6755", "3576", "2575", "2577", "2578", "2579", "2580", "2656", "2657", "2576", "3564", "10248", "8388", "2659", "14891", "3308", "3307", "10097", "2658", "3569", "16153", "3304", "10098", "4037", "3929", "3931", "3926", "3924", "3930", "3977", "3925", "136", "228", "5487", "43", "202", "0" }; int loop = 0; while (strcmp(allSpellList[loop], "0")) { uint32 spell = atol((char*)allSpellList[loop++]); if (m_session->GetPlayer()->HasSpell(spell)) { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); continue; } m_session->GetPlayer()->learnSpell(spell, false); } SendSysMessage(LANG_COMMAND_LEARN_MANY_SPELLS); return true; } bool ChatHandler::HandleLearnAllGMCommand(char* /*args*/) { static const char* gmSpellList[] = { "24347", // Become A Fish, No Breath Bar "35132", // Visual Boom "38488", // Attack 4000-8000 AOE "38795", // Attack 2000 AOE + Slow Down 90% "15712", // Attack 200 "1852", // GM Spell Silence "31899", // Kill "31924", // Kill "29878", // Kill My Self "26644", // More Kill "28550", // Invisible 24 "23452", // Invisible + Target "0" }; uint16 gmSpellIter = 0; while (strcmp(gmSpellList[gmSpellIter], "0")) { uint32 spell = atol((char*)gmSpellList[gmSpellIter++]); SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); continue; } m_session->GetPlayer()->learnSpell(spell, false); } SendSysMessage(LANG_LEARNING_GM_SKILLS); return true; } bool ChatHandler::HandleLearnAllMyClassCommand(char* /*args*/) { HandleLearnAllMySpellsCommand((char*)""); HandleLearnAllMyTalentsCommand((char*)""); return true; } bool ChatHandler::HandleLearnAllMySpellsCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(player->getClass()); if (!clsEntry) { return true; } uint32 family = clsEntry->spellfamily; for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i) { SkillLineAbilityEntry const* entry = sSkillLineAbilityStore.LookupEntry(i); if (!entry) { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(entry->spellId); if (!spellInfo) { continue; } // skip server-side/triggered spells if (spellInfo->spellLevel == 0) { continue; } // skip wrong class/race skills if (!player->IsSpellFitByClassAndRace(spellInfo->Id)) { continue; } // skip other spell families if (spellInfo->SpellFamilyName != family) { continue; } // skip spells with first rank learned as talent (and all talents then also) uint32 first_rank = sSpellMgr.GetFirstSpellInChain(spellInfo->Id); if (GetTalentSpellCost(first_rank) > 0) { continue; } // skip broken spells if (!SpellMgr::IsSpellValid(spellInfo, player, false)) { continue; } player->learnSpell(spellInfo->Id, false); } SendSysMessage(LANG_COMMAND_LEARN_CLASS_SPELLS); return true; } bool ChatHandler::HandleLearnAllMyTalentsCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); uint32 classMask = player->getClassMask(); for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) { continue; } TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) { continue; } if ((classMask & talentTabInfo->ClassMask) == 0) { continue; } // search highest talent rank uint32 spellid = 0; for (int rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] != 0) { spellid = talentInfo->RankID[rank]; break; } } if (!spellid) // ??? none spells in talent { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, player, false)) { continue; } // learn highest rank of talent and learn all non-talent spell ranks (recursive by tree) player->learnSpellHighRank(spellid); } player->SendTalentsInfoData(false); SendSysMessage(LANG_COMMAND_LEARN_CLASS_TALENTS); return true; } bool ChatHandler::HandleLearnAllMyPetTalentsCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); Pet* pet = player->GetPet(); if (!pet) { SendSysMessage(LANG_NO_PET_FOUND); SetSentErrorMessage(true); return false; } CreatureInfo const* ci = pet->GetCreatureInfo(); if (!ci) { SendSysMessage(LANG_WRONG_PET_TYPE); SetSentErrorMessage(true); return false; } CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(ci->Family); if (!pet_family) { SendSysMessage(LANG_WRONG_PET_TYPE); SetSentErrorMessage(true); return false; } if (pet_family->petTalentType < 0) // not hunter pet { SendSysMessage(LANG_WRONG_PET_TYPE); SetSentErrorMessage(true); return false; } for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) continue; TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) continue; // prevent learn talent for different family (cheating) if (((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask) == 0) continue; // search highest talent rank uint32 spellid = 0; for (int rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] != 0) { spellid = talentInfo->RankID[rank]; break; } } if (!spellid) // ??? none spells in talent continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, player, false)) continue; // learn highest rank of talent and learn all non-talent spell ranks (recursive by tree) pet->learnSpellHighRank(spellid); } player->SendTalentsInfoData(true); SendSysMessage(LANG_COMMAND_LEARN_PET_TALENTS); return true; } bool ChatHandler::HandleLearnAllLangCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); // skipping UNIVERSAL language (0) for (int i = 1; i < LANGUAGES_COUNT; ++i) { player->learnSpell(lang_description[i].spell_id, false); } SendSysMessage(LANG_COMMAND_LEARN_ALL_LANG); return true; } bool ChatHandler::HandleLearnAllDefaultCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } target->learnDefaultSpells(); target->learnQuestRewardedSpells(); PSendSysMessage(LANG_COMMAND_LEARN_ALL_DEFAULT_AND_QUEST, GetNameLink(target).c_str()); return true; } bool ChatHandler::HandleLearnCommand(char* args) { Player* player = m_session->GetPlayer(); Player* targetPlayer = getSelectedPlayer(); if (!targetPlayer) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell || !sSpellStore.LookupEntry(spell)) { return false; } bool allRanks = ExtractLiteralArg(&args, "all") != NULL; if (!allRanks && *args) // can be fail also at syntax error { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, player)) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } if (!allRanks && targetPlayer->HasSpell(spell)) { if (targetPlayer == player) { SendSysMessage(LANG_YOU_KNOWN_SPELL); } else PSendSysMessage(LANG_TARGET_KNOWN_SPELL, GetNameLink(targetPlayer).c_str()); SetSentErrorMessage(true); return false; } if (allRanks) { targetPlayer->learnSpellHighRank(spell); } else { targetPlayer->learnSpell(spell, false); } uint32 first_spell = sSpellMgr.GetFirstSpellInChain(spell); if (GetTalentSpellCost(first_spell)) targetPlayer->SendTalentsInfoData(false); return true; } bool ChatHandler::HandleAddItemCommand(char* args) { char* cId = ExtractKeyFromLink(&args, "Hitem"); if (!cId) { return false; } uint32 itemId = 0; if (!ExtractUInt32(&cId, itemId)) // [name] manual form { std::string itemName = cId; WorldDatabase.escape_string(itemName); QueryResult* result = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str()); if (!result) { PSendSysMessage(LANG_COMMAND_COULDNOTFIND, cId); SetSentErrorMessage(true); return false; } itemId = result->Fetch()->GetUInt16(); delete result; } int32 count; if (!ExtractOptInt32(&args, count, 1)) { return false; } Player* pl = m_session->GetPlayer(); Player* plTarget = getSelectedPlayer(); if (!plTarget) { plTarget = pl; } DETAIL_LOG(GetMangosString(LANG_ADDITEM), itemId, count); ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(itemId); if (!pProto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemId); SetSentErrorMessage(true); return false; } // Subtract if (count < 0) { plTarget->DestroyItemCount(itemId, -count, true, false); PSendSysMessage(LANG_REMOVEITEM, itemId, -count, GetNameLink(plTarget).c_str()); return true; } // Adding items uint32 noSpaceForCount = 0; // check space and find places ItemPosCountVec dest; uint8 msg = plTarget->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, count, &noSpaceForCount); if (msg != EQUIP_ERR_OK) // convert to possible store amount { count -= noSpaceForCount; } if (count == 0 || dest.empty()) // can't add any { PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount); SetSentErrorMessage(true); return false; } Item* item = plTarget->StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); // remove binding (let GM give it to another player later) if (pl == plTarget) for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr) if (Item* item1 = pl->GetItemByPos(itr->pos)) { item1->SetBinding(false); } if (count > 0 && item) { pl->SendNewItem(item, count, false, true); if (pl != plTarget) { plTarget->SendNewItem(item, count, true, false); } } if (noSpaceForCount > 0) { PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itemId, noSpaceForCount); } return true; } bool ChatHandler::HandleAddItemSetCommand(char* args) { uint32 itemsetId; if (!ExtractUint32KeyFromLink(&args, "Hitemset", itemsetId)) { return false; } // prevent generation all items with itemset field value '0' if (itemsetId == 0) { PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, itemsetId); SetSentErrorMessage(true); return false; } Player* pl = m_session->GetPlayer(); Player* plTarget = getSelectedPlayer(); if (!plTarget) { plTarget = pl; } DETAIL_LOG(GetMangosString(LANG_ADDITEMSET), itemsetId); bool found = false; for (uint32 id = 0; id < sItemStorage.GetMaxEntry(); ++id) { ItemPrototype const* pProto = sItemStorage.LookupEntry<ItemPrototype>(id); if (!pProto) { continue; } if (pProto->ItemSet == itemsetId) { found = true; ItemPosCountVec dest; InventoryResult msg = plTarget->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, pProto->ItemId, 1); if (msg == EQUIP_ERR_OK) { Item* item = plTarget->StoreNewItem(dest, pProto->ItemId, true); // remove binding (let GM give it to another player later) if (pl == plTarget) { item->SetBinding(false); } pl->SendNewItem(item, 1, false, true); if (pl != plTarget) { plTarget->SendNewItem(item, 1, true, false); } } else { pl->SendEquipError(msg, NULL, NULL, pProto->ItemId); PSendSysMessage(LANG_ITEM_CANNOT_CREATE, pProto->ItemId, 1); } } } if (!found) { PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, itemsetId); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleListItemCommand(char* args) { uint32 item_id; if (!ExtractUint32KeyFromLink(&args, "Hitem", item_id)) { return false; } if (!item_id) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_id); if (!itemProto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } uint32 count; if (!ExtractOptUInt32(&args, count, 10)) { return false; } QueryResult* result; // inventory case uint32 inv_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM character_inventory WHERE item_template='%u'", item_id); if (result) { inv_count = (*result)[0].GetUInt32(); delete result; } result = CharacterDatabase.PQuery( // 0 1 2 3 4 5 "SELECT ci.item, cibag.slot AS bag, ci.slot, ci.guid, characters.account,characters.name " "FROM character_inventory AS ci LEFT JOIN character_inventory AS cibag ON (cibag.item=ci.bag),characters " "WHERE ci.item_template='%u' AND ci.guid = characters.guid LIMIT %u ", item_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 item_bag = fields[1].GetUInt32(); uint32 item_slot = fields[2].GetUInt32(); uint32 owner_guid = fields[3].GetUInt32(); uint32 owner_acc = fields[4].GetUInt32(); std::string owner_name = fields[5].GetCppString(); char const* item_pos = 0; if (Player::IsEquipmentPos(item_bag, item_slot)) { item_pos = "[equipped]"; } else if (Player::IsInventoryPos(item_bag, item_slot)) { item_pos = "[in inventory]"; } else if (Player::IsBankPos(item_bag, item_slot)) { item_pos = "[in bank]"; } else { item_pos = ""; } PSendSysMessage(LANG_ITEMLIST_SLOT, item_guid, owner_name.c_str(), owner_guid, owner_acc, item_pos); } while (result->NextRow()); uint32 res_count = uint32(result->GetRowCount()); delete result; if (count > res_count) { count -= res_count; } else if (count) { count = 0; } } // mail case uint32 mail_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM mail_items WHERE item_template='%u'", item_id); if (result) { mail_count = (*result)[0].GetUInt32(); delete result; } if (count > 0) { result = CharacterDatabase.PQuery( // 0 1 2 3 4 5 6 "SELECT mail_items.item_guid, mail.sender, mail.receiver, char_s.account, char_s.name, char_r.account, char_r.name " "FROM mail,mail_items,characters as char_s,characters as char_r " "WHERE mail_items.item_template='%u' AND char_s.guid = mail.sender AND char_r.guid = mail.receiver AND mail.id=mail_items.mail_id LIMIT %u", item_id, uint32(count)); } else { result = NULL; } if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 item_s = fields[1].GetUInt32(); uint32 item_r = fields[2].GetUInt32(); uint32 item_s_acc = fields[3].GetUInt32(); std::string item_s_name = fields[4].GetCppString(); uint32 item_r_acc = fields[5].GetUInt32(); std::string item_r_name = fields[6].GetCppString(); char const* item_pos = "[in mail]"; PSendSysMessage(LANG_ITEMLIST_MAIL, item_guid, item_s_name.c_str(), item_s, item_s_acc, item_r_name.c_str(), item_r, item_r_acc, item_pos); } while (result->NextRow()); uint32 res_count = uint32(result->GetRowCount()); delete result; if (count > res_count) { count -= res_count; } else if (count) { count = 0; } } // auction case uint32 auc_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM auction WHERE item_template='%u'", item_id); if (result) { auc_count = (*result)[0].GetUInt32(); delete result; } if (count > 0) { result = CharacterDatabase.PQuery( // 0 1 2 3 "SELECT auction.itemguid, auction.itemowner, characters.account, characters.name " "FROM auction,characters WHERE auction.item_template='%u' AND characters.guid = auction.itemowner LIMIT %u", item_id, uint32(count)); } else { result = NULL; } if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 owner = fields[1].GetUInt32(); uint32 owner_acc = fields[2].GetUInt32(); std::string owner_name = fields[3].GetCppString(); char const* item_pos = "[in auction]"; PSendSysMessage(LANG_ITEMLIST_AUCTION, item_guid, owner_name.c_str(), owner, owner_acc, item_pos); } while (result->NextRow()); delete result; } // guild bank case uint32 guild_count = 0; result = CharacterDatabase.PQuery("SELECT COUNT(item_entry) FROM guild_bank_item WHERE item_entry='%u'", item_id); if (result) { guild_count = (*result)[0].GetUInt32(); delete result; } result = CharacterDatabase.PQuery( // 0 1 2 "SELECT gi.item_guid, gi.guildid, guild.name " "FROM guild_bank_item AS gi, guild WHERE gi.item_entry='%u' AND gi.guildid = guild.guildid LIMIT %u ", item_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 guild_guid = fields[1].GetUInt32(); std::string guild_name = fields[2].GetCppString(); char const* item_pos = "[in guild bank]"; PSendSysMessage(LANG_ITEMLIST_GUILD, item_guid, guild_name.c_str(), guild_guid, item_pos); } while (result->NextRow()); uint32 res_count = uint32(result->GetRowCount()); delete result; if (count > res_count) count -= res_count; else if (count) count = 0; } if (inv_count + mail_count + auc_count + guild_count == 0) { SendSysMessage(LANG_COMMAND_NOITEMFOUND); SetSentErrorMessage(true); return false; } PSendSysMessage(LANG_COMMAND_LISTITEMMESSAGE, item_id, inv_count + mail_count + auc_count + guild_count, inv_count, mail_count, auc_count, guild_count); return true; } bool ChatHandler::HandleListObjectCommand(char* args) { // number or [name] Shift-click form |color|Hgameobject_entry:go_id|h[name]|h|r uint32 go_id; if (!ExtractUint32KeyFromLink(&args, "Hgameobject_entry", go_id)) { return false; } if (!go_id) { PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id); SetSentErrorMessage(true); return false; } GameObjectInfo const* gInfo = ObjectMgr::GetGameObjectInfo(go_id); if (!gInfo) { PSendSysMessage(LANG_COMMAND_LISTOBJINVALIDID, go_id); SetSentErrorMessage(true); return false; } uint32 count; if (!ExtractOptUInt32(&args, count, 10)) { return false; } QueryResult* result; uint32 obj_count = 0; result = WorldDatabase.PQuery("SELECT COUNT(guid) FROM gameobject WHERE id='%u'", go_id); if (result) { obj_count = (*result)[0].GetUInt32(); delete result; } if (m_session) { Player* pl = m_session->GetPlayer(); result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM gameobject WHERE id = '%u' ORDER BY order_ ASC LIMIT %u", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), go_id, uint32(count)); } else result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM gameobject WHERE id = '%u' LIMIT %u", go_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); float x = fields[1].GetFloat(); float y = fields[2].GetFloat(); float z = fields[3].GetFloat(); int mapid = fields[4].GetUInt16(); if (m_session) { PSendSysMessage(LANG_GO_LIST_CHAT, guid, PrepareStringNpcOrGoSpawnInformation<GameObject>(guid).c_str(), guid, gInfo->name, x, y, z, mapid); } else { PSendSysMessage(LANG_GO_LIST_CONSOLE, guid, PrepareStringNpcOrGoSpawnInformation<GameObject>(guid).c_str(), gInfo->name, x, y, z, mapid); } } while (result->NextRow()); delete result; } PSendSysMessage(LANG_COMMAND_LISTOBJMESSAGE, go_id, obj_count); return true; } bool ChatHandler::HandleListCreatureCommand(char* args) { // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r uint32 cr_id; if (!ExtractUint32KeyFromLink(&args, "Hcreature_entry", cr_id)) { return false; } if (!cr_id) { PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id); SetSentErrorMessage(true); return false; } CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(cr_id); if (!cInfo) { PSendSysMessage(LANG_COMMAND_INVALIDCREATUREID, cr_id); SetSentErrorMessage(true); return false; } uint32 count; if (!ExtractOptUInt32(&args, count, 10)) { return false; } QueryResult* result; uint32 cr_count = 0; result = WorldDatabase.PQuery("SELECT COUNT(guid) FROM creature WHERE id='%u'", cr_id); if (result) { cr_count = (*result)[0].GetUInt32(); delete result; } if (m_session) { Player* pl = m_session->GetPlayer(); result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM creature WHERE id = '%u' ORDER BY order_ ASC LIMIT %u", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), cr_id, uint32(count)); } else result = WorldDatabase.PQuery("SELECT guid, position_x, position_y, position_z, map FROM creature WHERE id = '%u' LIMIT %u", cr_id, uint32(count)); if (result) { do { Field* fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); float x = fields[1].GetFloat(); float y = fields[2].GetFloat(); float z = fields[3].GetFloat(); int mapid = fields[4].GetUInt16(); if (m_session) { PSendSysMessage(LANG_CREATURE_LIST_CHAT, guid, PrepareStringNpcOrGoSpawnInformation<Creature>(guid).c_str(), guid, cInfo->Name, x, y, z, mapid); } else { PSendSysMessage(LANG_CREATURE_LIST_CONSOLE, guid, PrepareStringNpcOrGoSpawnInformation<Creature>(guid).c_str(), cInfo->Name, x, y, z, mapid); } } while (result->NextRow()); delete result; } PSendSysMessage(LANG_COMMAND_LISTCREATUREMESSAGE, cr_id, cr_count); return true; } void ChatHandler::ShowItemListHelper(uint32 itemId, int loc_idx, Player* target /*=NULL*/) { ItemPrototype const* itemProto = sItemStorage.LookupEntry<ItemPrototype >(itemId); if (!itemProto) { return; } std::string name = itemProto->Name1; sObjectMgr.GetItemLocaleStrings(itemProto->ItemId, loc_idx, &name); char const* usableStr = ""; if (target) { if (target->CanUseItem(itemProto)) { usableStr = GetMangosString(LANG_COMMAND_ITEM_USABLE); } } if (m_session) { PSendSysMessage(LANG_ITEM_LIST_CHAT, itemId, itemId, name.c_str(), usableStr); } else { PSendSysMessage(LANG_ITEM_LIST_CONSOLE, itemId, name.c_str(), usableStr); } } bool ChatHandler::HandleLookupItemCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); Player* pl = m_session ? m_session->GetPlayer() : NULL; uint32 counter = 0; // Search in `item_template` for (uint32 id = 0; id < sItemStorage.GetMaxEntry(); ++id) { ItemPrototype const* pProto = sItemStorage.LookupEntry<ItemPrototype >(id); if (!pProto) { continue; } int loc_idx = GetSessionDbLocaleIndex(); std::string name; // "" for let later only single time check default locale name directly sObjectMgr.GetItemLocaleStrings(id, loc_idx, &name); if ((name.empty() || !Utf8FitTo(name, wnamepart)) && !Utf8FitTo(pProto->Name1, wnamepart)) { continue; } ShowItemListHelper(id, loc_idx, pl); ++counter; } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOITEMFOUND); } return true; } bool ChatHandler::HandleLookupItemSetCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in ItemSet.dbc for (uint32 id = 0; id < sItemSetStore.GetNumRows(); ++id) { ItemSetEntry const* set = sItemSetStore.LookupEntry(id); if (set) { int loc = GetSessionDbcLocale(); std::string name = set->name[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = set->name[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { // send item set in "id - [namedlink locale]" format if (m_session) { PSendSysMessage(LANG_ITEMSET_LIST_CHAT, id, id, name.c_str(), localeNames[loc]); } else { PSendSysMessage(LANG_ITEMSET_LIST_CONSOLE, id, name.c_str(), localeNames[loc]); } ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOITEMSETFOUND); } return true; } bool ChatHandler::HandleLookupSkillCommand(char* args) { if (!*args) { return false; } // can be NULL in console call Player* target = getSelectedPlayer(); std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in SkillLine.dbc for (uint32 id = 0; id < sSkillLineStore.GetNumRows(); ++id) { SkillLineEntry const* skillInfo = sSkillLineStore.LookupEntry(id); if (skillInfo) { int loc = GetSessionDbcLocale(); std::string name = skillInfo->name[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = skillInfo->name[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { char valStr[50] = ""; char const* knownStr = ""; if (target && target->HasSkill(id)) { knownStr = GetMangosString(LANG_KNOWN); uint32 curValue = target->GetPureSkillValue(id); uint32 maxValue = target->GetPureMaxSkillValue(id); uint32 permValue = target->GetSkillPermBonusValue(id); uint32 tempValue = target->GetSkillTempBonusValue(id); char const* valFormat = GetMangosString(LANG_SKILL_VALUES); snprintf(valStr, 50, valFormat, curValue, maxValue, permValue, tempValue); } // send skill in "id - [namedlink locale]" format if (m_session) { PSendSysMessage(LANG_SKILL_LIST_CHAT, id, id, name.c_str(), localeNames[loc], knownStr, valStr); } else { PSendSysMessage(LANG_SKILL_LIST_CONSOLE, id, name.c_str(), localeNames[loc], knownStr, valStr); } ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOSKILLFOUND); } return true; } void ChatHandler::ShowSpellListHelper(Player* target, SpellEntry const* spellInfo, LocaleConstant loc) { uint32 id = spellInfo->Id; bool known = target && target->HasSpell(id); bool learn = (spellInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_LEARN_SPELL); uint32 talentCost = GetTalentSpellCost(id); bool talent = (talentCost > 0); bool passive = IsPassiveSpell(spellInfo); bool active = target && target->HasAura(id); // unit32 used to prevent interpreting uint8 as char at output // find rank of learned spell for learning spell, or talent rank uint32 rank = talentCost ? talentCost : sSpellMgr.GetSpellRank(learn ? spellInfo->EffectTriggerSpell[EFFECT_INDEX_0] : id); // send spell in "id - [name, rank N] [talent] [passive] [learn] [known]" format std::ostringstream ss; if (m_session) { ss << id << " - |cffffffff|Hspell:" << id << "|h[" << spellInfo->SpellName[loc]; } else { ss << id << " - " << spellInfo->SpellName[loc]; } // include rank in link name if (rank) { ss << GetMangosString(LANG_SPELL_RANK) << rank; } if (m_session) { ss << " " << localeNames[loc] << "]|h|r"; } else { ss << " " << localeNames[loc]; } if (talent) { ss << GetMangosString(LANG_TALENT); } if (passive) { ss << GetMangosString(LANG_PASSIVE); } if (learn) { ss << GetMangosString(LANG_LEARN); } if (known) { ss << GetMangosString(LANG_KNOWN); } if (active) { ss << GetMangosString(LANG_ACTIVE); } SendSysMessage(ss.str().c_str()); } bool ChatHandler::HandleLookupSpellCommand(char* args) { if (!*args) { return false; } // can be NULL at console call Player* target = getSelectedPlayer(); std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in Spell.dbc for (uint32 id = 0; id < sSpellStore.GetNumRows(); ++id) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(id); if (spellInfo) { int loc = GetSessionDbcLocale(); std::string name = spellInfo->SpellName[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = spellInfo->SpellName[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { ShowSpellListHelper(target, spellInfo, LocaleConstant(loc)); ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOSPELLFOUND); } return true; } void ChatHandler::ShowQuestListHelper(uint32 questId, int32 loc_idx, Player* target /*= NULL*/) { Quest const* qinfo = sObjectMgr.GetQuestTemplate(questId); if (!qinfo) { return; } std::string title = qinfo->GetTitle(); sObjectMgr.GetQuestLocaleStrings(questId, loc_idx, &title); char const* statusStr = ""; if (target) { QuestStatus status = target->GetQuestStatus(qinfo->GetQuestId()); if (status == QUEST_STATUS_COMPLETE) { if (target->GetQuestRewardStatus(qinfo->GetQuestId())) { statusStr = GetMangosString(LANG_COMMAND_QUEST_REWARDED); } else { statusStr = GetMangosString(LANG_COMMAND_QUEST_COMPLETE); } } else if (status == QUEST_STATUS_INCOMPLETE) { statusStr = GetMangosString(LANG_COMMAND_QUEST_ACTIVE); } } if (m_session) { PSendSysMessage(LANG_QUEST_LIST_CHAT, qinfo->GetQuestId(), qinfo->GetQuestId(), qinfo->GetQuestLevel(), title.c_str(), statusStr); } else { PSendSysMessage(LANG_QUEST_LIST_CONSOLE, qinfo->GetQuestId(), title.c_str(), statusStr); } } bool ChatHandler::HandleLookupQuestCommand(char* args) { if (!*args) { return false; } // can be NULL at console call Player* target = getSelectedPlayer(); std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); uint32 counter = 0 ; int loc_idx = GetSessionDbLocaleIndex(); ObjectMgr::QuestMap const& qTemplates = sObjectMgr.GetQuestTemplates(); for (ObjectMgr::QuestMap::const_iterator iter = qTemplates.begin(); iter != qTemplates.end(); ++iter) { Quest* qinfo = iter->second; std::string title; // "" for avoid repeating check default locale sObjectMgr.GetQuestLocaleStrings(qinfo->GetQuestId(), loc_idx, &title); if ((title.empty() || !Utf8FitTo(title, wnamepart)) && !Utf8FitTo(qinfo->GetTitle(), wnamepart)) { continue; } ShowQuestListHelper(qinfo->GetQuestId(), loc_idx, target); ++counter; } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOQUESTFOUND); } return true; } bool ChatHandler::HandleLookupCreatureCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); uint32 counter = 0; for (uint32 id = 0; id < sCreatureStorage.GetMaxEntry(); ++id) { CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo> (id); if (!cInfo) { continue; } int loc_idx = GetSessionDbLocaleIndex(); char const* name = ""; // "" for avoid repeating check for default locale sObjectMgr.GetCreatureLocaleStrings(id, loc_idx, &name); if (!*name || !Utf8FitTo(name, wnamepart)) { name = cInfo->Name; if (!Utf8FitTo(name, wnamepart)) { continue; } } if (m_session) { PSendSysMessage(LANG_CREATURE_ENTRY_LIST_CHAT, id, id, name); } else { PSendSysMessage(LANG_CREATURE_ENTRY_LIST_CONSOLE, id, name); } ++counter; } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOCREATUREFOUND); } return true; } bool ChatHandler::HandleLookupObjectCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; // converting string that we try to find to lower case if (!Utf8toWStr(namepart, wnamepart)) { return false; } wstrToLower(wnamepart); uint32 counter = 0; for (SQLStorageBase::SQLSIterator<GameObjectInfo> itr = sGOStorage.getDataBegin<GameObjectInfo>(); itr < sGOStorage.getDataEnd<GameObjectInfo>(); ++itr) { int loc_idx = GetSessionDbLocaleIndex(); if (loc_idx >= 0) { GameObjectLocale const* gl = sObjectMgr.GetGameObjectLocale(itr->id); if (gl) { if ((int32)gl->Name.size() > loc_idx && !gl->Name[loc_idx].empty()) { std::string name = gl->Name[loc_idx]; if (Utf8FitTo(name, wnamepart)) { if (m_session) { PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, itr->id, itr->id, name.c_str()); } else { PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, itr->id, name.c_str()); } ++counter; continue; } } } } std::string name = itr->name; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { if (m_session) { PSendSysMessage(LANG_GO_ENTRY_LIST_CHAT, itr->id, itr->id, name.c_str()); } else { PSendSysMessage(LANG_GO_ENTRY_LIST_CONSOLE, itr->id, name.c_str()); } ++counter; } } if (counter == 0) { SendSysMessage(LANG_COMMAND_NOGAMEOBJECTFOUND); } return true; } bool ChatHandler::HandleLookupTaxiNodeCommand(char* args) { if (!*args) { return false; } std::string namepart = args; std::wstring wnamepart; if (!Utf8toWStr(namepart, wnamepart)) { return false; } // converting string that we try to find to lower case wstrToLower(wnamepart); uint32 counter = 0; // Counter for figure out that we found smth. // Search in TaxiNodes.dbc for (uint32 id = 0; id < sTaxiNodesStore.GetNumRows(); ++id) { TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(id); if (nodeEntry) { int loc = GetSessionDbcLocale(); std::string name = nodeEntry->name[loc]; if (name.empty()) { continue; } if (!Utf8FitTo(name, wnamepart)) { loc = 0; for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) { continue; } name = nodeEntry->name[loc]; if (name.empty()) { continue; } if (Utf8FitTo(name, wnamepart)) { break; } } } if (loc < MAX_LOCALE) { // send taxinode in "id - [name] (Map:m X:x Y:y Z:z)" format if (m_session) PSendSysMessage(LANG_TAXINODE_ENTRY_LIST_CHAT, id, id, name.c_str(), localeNames[loc], nodeEntry->map_id, nodeEntry->x, nodeEntry->y, nodeEntry->z); else PSendSysMessage(LANG_TAXINODE_ENTRY_LIST_CONSOLE, id, name.c_str(), localeNames[loc], nodeEntry->map_id, nodeEntry->x, nodeEntry->y, nodeEntry->z); ++counter; } } } if (counter == 0) // if counter == 0 then we found nth { SendSysMessage(LANG_COMMAND_NOTAXINODEFOUND); } return true; } /** \brief GM command level 3 - Create a guild. * * This command allows a GM (level 3) to create a guild. * * The "args" parameter contains the name of the guild leader * and then the name of the guild. * */ bool ChatHandler::HandleGuildCreateCommand(char* args) { // guildmaster name optional char* guildMasterStr = ExtractOptNotLastArg(&args); Player* target; if (!ExtractPlayerTarget(&guildMasterStr, &target)) { return false; } char* guildStr = ExtractQuotedArg(&args); if (!guildStr) { return false; } std::string guildname = guildStr; if (target->GetGuildId()) { SendSysMessage(LANG_PLAYER_IN_GUILD); return true; } Guild* guild = new Guild; if (!guild->Create(target, guildname)) { delete guild; SendSysMessage(LANG_GUILD_NOT_CREATED); SetSentErrorMessage(true); return false; } sGuildMgr.AddGuild(guild); return true; } bool ChatHandler::HandleGuildInviteCommand(char* args) { // player name optional char* nameStr = ExtractOptNotLastArg(&args); // if not guild name only (in "") then player name ObjectGuid target_guid; if (!ExtractPlayerTarget(&nameStr, NULL, &target_guid)) { return false; } char* guildStr = ExtractQuotedArg(&args); if (!guildStr) { return false; } std::string glName = guildStr; Guild* targetGuild = sGuildMgr.GetGuildByName(glName); if (!targetGuild) { return false; } // player's guild membership checked in AddMember before add if (!targetGuild->AddMember(target_guid, targetGuild->GetLowestRank())) { return false; } return true; } bool ChatHandler::HandleGuildUninviteCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) { return false; } uint32 glId = target ? target->GetGuildId() : Player::GetGuildIdFromDB(target_guid); if (!glId) { return false; } Guild* targetGuild = sGuildMgr.GetGuildById(glId); if (!targetGuild) { return false; } if (targetGuild->DelMember(target_guid)) { targetGuild->Disband(); delete targetGuild; } return true; } bool ChatHandler::HandleGuildRankCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } uint32 glId = target ? target->GetGuildId() : Player::GetGuildIdFromDB(target_guid); if (!glId) { return false; } Guild* targetGuild = sGuildMgr.GetGuildById(glId); if (!targetGuild) { return false; } uint32 newrank; if (!ExtractUInt32(&args, newrank)) { return false; } if (newrank > targetGuild->GetLowestRank()) { return false; } MemberSlot* slot = targetGuild->GetMemberSlot(target_guid); if (!slot) { return false; } slot->ChangeRank(newrank); return true; } bool ChatHandler::HandleGuildDeleteCommand(char* args) { if (!*args) { return false; } char* guildStr = ExtractQuotedArg(&args); if (!guildStr) { return false; } std::string gld = guildStr; Guild* targetGuild = sGuildMgr.GetGuildByName(gld); if (!targetGuild) { return false; } targetGuild->Disband(); delete targetGuild; return true; } bool ChatHandler::HandleGetDistanceCommand(char* args) { WorldObject* obj = NULL; if (*args) { if (ObjectGuid guid = ExtractGuidFromLink(&args)) { obj = (WorldObject*)m_session->GetPlayer()->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_OR_GAMEOBJECT); } if (!obj) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } } else { obj = getSelectedUnit(); if (!obj) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } } Player* player = m_session->GetPlayer(); // Calculate point-to-point distance float dx, dy, dz; dx = player->GetPositionX() - obj->GetPositionX(); dy = player->GetPositionY() - obj->GetPositionY(); dz = player->GetPositionZ() - obj->GetPositionZ(); PSendSysMessage(LANG_DISTANCE, player->GetDistance(obj), player->GetDistance2d(obj), sqrt(dx * dx + dy * dy + dz * dz)); return true; } bool ChatHandler::HandleDieCommand(char* /*args*/) { Player* player = m_session->GetPlayer(); Unit* target = getSelectedUnit(); if (!target || !player->GetSelectionGuid()) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } if (target->GetTypeId() == TYPEID_PLAYER) { if (HasLowerSecurity((Player*)target, ObjectGuid(), false)) { return false; } } if (target->IsAlive()) { player->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } return true; } bool ChatHandler::HandleDamageCommand(char* args) { if (!*args) { return false; } Unit* target = getSelectedUnit(); Player* player = m_session->GetPlayer(); if (!target || !player->GetSelectionGuid()) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } if (!target->IsAlive()) { return true; } int32 damage_int; if (!ExtractInt32(&args, damage_int)) { return false; } if (damage_int <= 0) { return true; } uint32 damage = damage_int; // flat melee damage without resistance/etc reduction if (!*args) { player->DealDamage(target, damage, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); if (target != player) { player->SendAttackStateUpdate(HITINFO_NORMALSWING2, target, SPELL_SCHOOL_MASK_NORMAL, damage, 0, 0, VICTIMSTATE_NORMAL, 0); } return true; } uint32 school; if (!ExtractUInt32(&args, school)) { return false; } if (school >= MAX_SPELL_SCHOOL) { return false; } SpellSchoolMask schoolmask = SpellSchoolMask(1 << school); if (schoolmask & SPELL_SCHOOL_MASK_NORMAL) { damage = player->CalcArmorReducedDamage(target, damage); } // melee damage by specific school if (!*args) { uint32 absorb = 0; uint32 resist = 0; target->CalculateDamageAbsorbAndResist(player, schoolmask, SPELL_DIRECT_DAMAGE, damage, &absorb, &resist); if (damage <= absorb + resist) { return true; } damage -= absorb + resist; player->DealDamageMods(target, damage, &absorb); player->DealDamage(target, damage, NULL, DIRECT_DAMAGE, schoolmask, NULL, false); player->SendAttackStateUpdate(HITINFO_NORMALSWING2, target, schoolmask, damage, absorb, resist, VICTIMSTATE_NORMAL, 0); return true; } // non-melee damage // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spellid = ExtractSpellIdFromLink(&args); if (!spellid || !sSpellStore.LookupEntry(spellid)) { return false; } player->SpellNonMeleeDamageLog(target, spellid, damage); return true; } bool ChatHandler::HandleModifyArenaCommand(char* args) { if (!*args) return false; Player* target = getSelectedPlayer(); if (!target) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } int32 amount = (int32)atoi(args); target->ModifyArenaPoints(amount); PSendSysMessage(LANG_COMMAND_MODIFY_ARENA, GetNameLink(target).c_str(), target->GetArenaPoints()); return true; } bool ChatHandler::HandleReviveCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) { return false; } if (target) { target->ResurrectPlayer(0.5f); target->SpawnCorpseBones(); } else // will resurrected at login without corpse { sObjectAccessor.ConvertCorpseForPlayer(target_guid); } return true; } bool ChatHandler::HandleAuraCommand(char* args) { Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spellID = ExtractSpellIdFromLink(&args); SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellID); if (!spellInfo) { return false; } if (!IsSpellAppliesAura(spellInfo) && !IsSpellHaveEffect(spellInfo, SPELL_EFFECT_PERSISTENT_AREA_AURA)) { PSendSysMessage(LANG_SPELL_NO_HAVE_AURAS, spellID); SetSentErrorMessage(true); return false; } SpellAuraHolder* holder = CreateSpellAuraHolder(spellInfo, target, m_session->GetPlayer()); for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) { uint8 eff = spellInfo->Effect[i]; if (eff >= TOTAL_SPELL_EFFECTS) { continue; } if (IsAreaAuraEffect(eff) || eff == SPELL_EFFECT_APPLY_AURA || eff == SPELL_EFFECT_PERSISTENT_AREA_AURA) { Aura* aur = CreateAura(spellInfo, SpellEffectIndex(i), NULL, holder, target); holder->AddAura(aur, SpellEffectIndex(i)); } } target->AddSpellAuraHolder(holder); return true; } bool ChatHandler::HandleUnAuraCommand(char* args) { Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } std::string argstr = args; if (argstr == "all") { target->RemoveAllAuras(); return true; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spellID = ExtractSpellIdFromLink(&args); if (!spellID) { return false; } target->RemoveAurasDueToSpell(spellID); return true; } bool ChatHandler::HandleLinkGraveCommand(char* args) { uint32 g_id; if (!ExtractUInt32(&args, g_id)) { return false; } char* teamStr = ExtractLiteralArg(&args); Team g_team; if (!teamStr) { g_team = TEAM_BOTH_ALLOWED; } else if (strncmp(teamStr, "horde", strlen(teamStr)) == 0) { g_team = HORDE; } else if (strncmp(teamStr, "alliance", strlen(teamStr)) == 0) { g_team = ALLIANCE; } else { return false; } WorldSafeLocsEntry const* graveyard = sWorldSafeLocsStore.LookupEntry(g_id); if (!graveyard) { PSendSysMessage(LANG_COMMAND_GRAVEYARDNOEXIST, g_id); SetSentErrorMessage(true); return false; } Player* player = m_session->GetPlayer(); uint32 zoneId = player->GetZoneId(); AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(zoneId); if (!areaEntry || areaEntry->zone != 0) { PSendSysMessage(LANG_COMMAND_GRAVEYARDWRONGZONE, g_id, zoneId); SetSentErrorMessage(true); return false; } if (sObjectMgr.AddGraveYardLink(g_id, zoneId, g_team)) { PSendSysMessage(LANG_COMMAND_GRAVEYARDLINKED, g_id, zoneId); } else { PSendSysMessage(LANG_COMMAND_GRAVEYARDALRLINKED, g_id, zoneId); } return true; } bool ChatHandler::HandleNearGraveCommand(char* args) { Team g_team; size_t argslen = strlen(args); if (!*args) { g_team = TEAM_BOTH_ALLOWED; } else if (strncmp(args, "horde", argslen) == 0) { g_team = HORDE; } else if (strncmp(args, "alliance", argslen) == 0) { g_team = ALLIANCE; } else { return false; } Player* player = m_session->GetPlayer(); uint32 zone_id = player->GetZoneId(); WorldSafeLocsEntry const* graveyard = sObjectMgr.GetClosestGraveYard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), g_team); if (graveyard) { uint32 g_id = graveyard->ID; GraveYardData const* data = sObjectMgr.FindGraveYardData(g_id, zone_id); if (!data) { PSendSysMessage(LANG_COMMAND_GRAVEYARDERROR, g_id); SetSentErrorMessage(true); return false; } std::string team_name; if (data->team == TEAM_BOTH_ALLOWED) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ANY); } else if (data->team == HORDE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_HORDE); } else if (data->team == ALLIANCE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ALLIANCE); } else // Actually, this case can not happen { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_NOTEAM); } PSendSysMessage(LANG_COMMAND_GRAVEYARDNEAREST, g_id, team_name.c_str(), zone_id); } else { std::string team_name; if (g_team == TEAM_BOTH_ALLOWED) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ANY); } else if (g_team == HORDE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_HORDE); } else if (g_team == ALLIANCE) { team_name = GetMangosString(LANG_COMMAND_GRAVEYARD_ALLIANCE); } if (g_team == TEAM_BOTH_ALLOWED) { PSendSysMessage(LANG_COMMAND_ZONENOGRAVEYARDS, zone_id); } else { PSendSysMessage(LANG_COMMAND_ZONENOGRAFACTION, zone_id, team_name.c_str()); } } return true; } //-----------------------Npc Commands----------------------- bool ChatHandler::HandleNpcAllowMovementCommand(char* /*args*/) { if (sWorld.getAllowMovement()) { sWorld.SetAllowMovement(false); SendSysMessage(LANG_CREATURE_MOVE_DISABLED); } else { sWorld.SetAllowMovement(true); SendSysMessage(LANG_CREATURE_MOVE_ENABLED); } return true; } bool ChatHandler::HandleNpcChangeEntryCommand(char* args) { if (!*args) { return false; } uint32 newEntryNum = atoi(args); if (!newEntryNum) { return false; } Unit* unit = getSelectedUnit(); if (!unit || unit->GetTypeId() != TYPEID_UNIT) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } Creature* creature = (Creature*)unit; if (creature->UpdateEntry(newEntryNum)) { SendSysMessage(LANG_DONE); } else { SendSysMessage(LANG_ERROR); } return true; } bool ChatHandler::HandleNpcInfoCommand(char* /*args*/) { Creature* target = getSelectedCreature(); if (!target) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } uint32 faction = target->getFaction(); uint32 npcflags = target->GetUInt32Value(UNIT_NPC_FLAGS); uint32 displayid = target->GetDisplayId(); uint32 nativeid = target->GetNativeDisplayId(); uint32 Entry = target->GetEntry(); CreatureInfo const* cInfo = target->GetCreatureInfo(); time_t curRespawnDelay = target->GetRespawnTimeEx() - time(NULL); if (curRespawnDelay < 0) { curRespawnDelay = 0; } std::string curRespawnDelayStr = secsToTimeString(curRespawnDelay, true); std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(), true); // Send information dependend on difficulty mode CreatureInfo const* baseInfo = ObjectMgr::GetCreatureTemplate(Entry); uint32 diff = 1; for (; diff < MAX_DIFFICULTY; ++diff) if (baseInfo->DifficultyEntry[diff - 1] == target->GetCreatureInfo()->Entry) break; if (diff < MAX_DIFFICULTY) PSendSysMessage(LANG_NPCINFO_CHAR_DIFFICULTY, target->GetGuidStr().c_str(), faction, npcflags, Entry, target->GetCreatureInfo()->Entry, diff, displayid, nativeid); else PSendSysMessage(LANG_NPCINFO_CHAR, target->GetGuidStr().c_str(), faction, npcflags, Entry, displayid, nativeid); PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel()); PSendSysMessage(LANG_NPCINFO_HEALTH, target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth()); PSendSysMessage(LANG_NPCINFO_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS), target->GetUInt32Value(UNIT_DYNAMIC_FLAGS), target->getFaction()); PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(), curRespawnDelayStr.c_str()); PSendSysMessage(LANG_NPCINFO_LOOT, cInfo->LootId, cInfo->PickpocketLootId, cInfo->SkinningLootId); PSendSysMessage(LANG_NPCINFO_DUNGEON_ID, target->GetInstanceId()); PSendSysMessage(LANG_NPCINFO_POSITION, float(target->GetPositionX()), float(target->GetPositionY()), float(target->GetPositionZ())); if ((npcflags & UNIT_NPC_FLAG_VENDOR)) { SendSysMessage(LANG_NPCINFO_VENDOR); } if ((npcflags & UNIT_NPC_FLAG_TRAINER)) { SendSysMessage(LANG_NPCINFO_TRAINER); } ShowNpcOrGoSpawnInformation<Creature>(target->GetGUIDLow()); return true; } // play npc emote bool ChatHandler::HandleNpcPlayEmoteCommand(char* args) { uint32 emote = atoi(args); Creature* target = getSelectedCreature(); if (!target) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } target->HandleEmote(emote); return true; } // TODO: NpcCommands that needs to be fixed : bool ChatHandler::HandleNpcAddWeaponCommand(char* /*args*/) { /*if (!*args) return false; ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid(); if (guid.IsEmpty()) { SendSysMessage(LANG_NO_SELECTION); return true; } Creature *pCreature = ObjectAccessor::GetCreature(*m_session->GetPlayer(), guid); if(!pCreature) { SendSysMessage(LANG_SELECT_CREATURE); return true; } char* pSlotID = strtok((char*)args, " "); if (!pSlotID) return false; char* pItemID = strtok(NULL, " "); if (!pItemID) return false; uint32 ItemID = atoi(pItemID); uint32 SlotID = atoi(pSlotID); ItemPrototype* tmpItem = ObjectMgr::GetItemPrototype(ItemID); bool added = false; if(tmpItem) { switch(SlotID) { case 1: pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, ItemID); added = true; break; case 2: pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, ItemID); added = true; break; case 3: pCreature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_02, ItemID); added = true; break; default: PSendSysMessage(LANG_ITEM_SLOT_NOT_EXIST,SlotID); added = false; break; } if(added) PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT,ItemID,tmpItem->Name1,SlotID); } else { PSendSysMessage(LANG_ITEM_NOT_FOUND,ItemID); return true; } */ return true; } //---------------------------------------------------------- bool ChatHandler::HandleExploreCheatCommand(char* args) { if (!*args) { return false; } int flag = atoi(args); Player* chr = getSelectedPlayer(); if (chr == NULL) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } if (flag != 0) { PSendSysMessage(LANG_YOU_SET_EXPLORE_ALL, GetNameLink(chr).c_str()); if (needReportToTarget(chr)) { ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_ALL, GetNameLink().c_str()); } } else { PSendSysMessage(LANG_YOU_SET_EXPLORE_NOTHING, GetNameLink(chr).c_str()); if (needReportToTarget(chr)) { ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_NOTHING, GetNameLink().c_str()); } } for (uint8 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i) { if (flag != 0) { m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1 + i, 0xFFFFFFFF); } else { m_session->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1 + i, 0); } } return true; } void ChatHandler::HandleCharacterLevel(Player* player, ObjectGuid player_guid, uint32 oldlevel, uint32 newlevel) { if (player) { player->GiveLevel(newlevel); player->InitTalentForLevel(); player->SetUInt32Value(PLAYER_XP, 0); if (needReportToTarget(player)) { if (oldlevel == newlevel) { ChatHandler(player).PSendSysMessage(LANG_YOURS_LEVEL_PROGRESS_RESET, GetNameLink().c_str()); } else if (oldlevel < newlevel) { ChatHandler(player).PSendSysMessage(LANG_YOURS_LEVEL_UP, GetNameLink().c_str(), newlevel); } else // if(oldlevel > newlevel) { ChatHandler(player).PSendSysMessage(LANG_YOURS_LEVEL_DOWN, GetNameLink().c_str(), newlevel); } } } else { // update level and XP at level, all other will be updated at loading CharacterDatabase.PExecute("UPDATE characters SET level = '%u', xp = 0 WHERE guid = '%u'", newlevel, player_guid.GetCounter()); } } bool ChatHandler::HandleCharacterLevelCommand(char* args) { char* nameStr = ExtractOptNotLastArg(&args); int32 newlevel; bool nolevel = false; // exception opt second arg: .character level $name if (!ExtractInt32(&args, newlevel)) { if (!nameStr) { nameStr = ExtractArg(&args); if (!nameStr) { return false; } nolevel = true; } else { return false; } } Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } int32 oldlevel = target ? target->getLevel() : Player::GetLevelFromDB(target_guid); if (nolevel) { newlevel = oldlevel; } if (newlevel < 1) { return false; } // invalid level if (newlevel > STRONG_MAX_LEVEL) // hardcoded maximum level { newlevel = STRONG_MAX_LEVEL; } HandleCharacterLevel(target, target_guid, oldlevel, newlevel); if (!m_session || m_session->GetPlayer() != target) // including player==NULL { std::string nameLink = playerLink(target_name); PSendSysMessage(LANG_YOU_CHANGE_LVL, nameLink.c_str(), newlevel); } return true; } bool ChatHandler::HandleLevelUpCommand(char* args) { int32 addlevel = 1; char* nameStr = NULL; if (*args) { nameStr = ExtractOptNotLastArg(&args); // exception opt second arg: .levelup $name if (!ExtractInt32(&args, addlevel)) { if (!nameStr) { nameStr = ExtractArg(&args); } else { return false; } } } Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name)) { return false; } int32 oldlevel = target ? target->getLevel() : Player::GetLevelFromDB(target_guid); int32 newlevel = oldlevel + addlevel; if (newlevel < 1) { newlevel = 1; } if (newlevel > STRONG_MAX_LEVEL) // hardcoded maximum level { newlevel = STRONG_MAX_LEVEL; } HandleCharacterLevel(target, target_guid, oldlevel, newlevel); if (!m_session || m_session->GetPlayer() != target) // including chr==NULL { std::string nameLink = playerLink(target_name); PSendSysMessage(LANG_YOU_CHANGE_LVL, nameLink.c_str(), newlevel); } return true; } bool ChatHandler::HandleShowAreaCommand(char* args) { if (!*args) { return false; } Player* chr = getSelectedPlayer(); if (chr == NULL) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } int area = GetAreaFlagByAreaID(atoi(args)); int offset = area / 32; uint32 val = (uint32)(1 << (area % 32)); if (area < 0 || offset >= PLAYER_EXPLORED_ZONES_SIZE) { SendSysMessage(LANG_BAD_VALUE); SetSentErrorMessage(true); return false; } uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset); chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val)); SendSysMessage(LANG_EXPLORE_AREA); return true; } bool ChatHandler::HandleHideAreaCommand(char* args) { if (!*args) { return false; } Player* chr = getSelectedPlayer(); if (chr == NULL) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } int area = GetAreaFlagByAreaID(atoi(args)); int offset = area / 32; uint32 val = (uint32)(1 << (area % 32)); if (area < 0 || offset >= PLAYER_EXPLORED_ZONES_SIZE) { SendSysMessage(LANG_BAD_VALUE); SetSentErrorMessage(true); return false; } uint32 currFields = chr->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset); chr->SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields ^ val)); SendSysMessage(LANG_UNEXPLORE_AREA); return true; } bool ChatHandler::HandleAuctionAllianceCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(m_session->GetPlayer()->GetTeam() != ALLIANCE ? -1 : 0); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionHordeCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(m_session->GetPlayer()->GetTeam() != HORDE ? -1 : 0); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionGoblinCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(1); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionCommand(char* /*args*/) { m_session->GetPlayer()->SetAuctionAccessMode(0); m_session->SendAuctionHello(m_session->GetPlayer()); return true; } bool ChatHandler::HandleAuctionItemCommand(char* args) { // format: (alliance|horde|goblin) item[:count] price [buyout] [short|long|verylong] char* typeStr = ExtractLiteralArg(&args); if (!typeStr) { return false; } uint32 houseid; if (strncmp(typeStr, "alliance", strlen(typeStr)) == 0) { houseid = 1; } else if (strncmp(typeStr, "horde", strlen(typeStr)) == 0) { houseid = 6; } else if (strncmp(typeStr, "goblin", strlen(typeStr)) == 0) { houseid = 7; } else { return false; } // parse item str char* itemStr = ExtractArg(&args); if (!itemStr) { return false; } uint32 item_id = 0; uint32 item_count = 1; if (sscanf(itemStr, "%u:%u", &item_id, &item_count) != 2) if (sscanf(itemStr, "%u", &item_id) != 1) { return false; } uint32 price; if (!ExtractUInt32(&args, price)) { return false; } uint32 buyout; if (!ExtractOptUInt32(&args, buyout, 0)) { return false; } uint32 etime = 4 * MIN_AUCTION_TIME; if (char* timeStr = ExtractLiteralArg(&args)) { if (strncmp(timeStr, "short", strlen(timeStr)) == 0) { etime = 1 * MIN_AUCTION_TIME; } else if (strncmp(timeStr, "long", strlen(timeStr)) == 0) { etime = 2 * MIN_AUCTION_TIME; } else if (strncmp(timeStr, "verylong", strlen(timeStr)) == 0) { etime = 4 * MIN_AUCTION_TIME; } else { return false; } } AuctionHouseEntry const* auctionHouseEntry = sAuctionHouseStore.LookupEntry(houseid); AuctionHouseObject* auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry); if (!item_id) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } ItemPrototype const* item_proto = ObjectMgr::GetItemPrototype(item_id); if (!item_proto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } if (item_count < 1 || (item_proto->MaxCount > 0 && item_count > uint32(item_proto->MaxCount))) { PSendSysMessage(LANG_COMMAND_INVALID_ITEM_COUNT, item_count, item_id); SetSentErrorMessage(true); return false; } do { uint32 item_stack = item_count > item_proto->GetMaxStackSize() ? item_proto->GetMaxStackSize() : item_count; item_count -= item_stack; Item* newItem = Item::CreateItem(item_id, item_stack); MANGOS_ASSERT(newItem); auctionHouse->AddAuction(auctionHouseEntry, newItem, etime, price, buyout); } while (item_count); return true; } bool ChatHandler::HandleBankCommand(char* /*args*/) { m_session->SendShowBank(m_session->GetPlayer()->GetObjectGuid()); return true; } bool ChatHandler::HandleMailBoxCommand(char* /*args*/) { m_session->SendShowMailBox(m_session->GetPlayer()->GetObjectGuid()); return true; } bool ChatHandler::HandleStableCommand(char* /*args*/) { m_session->SendStablePet(m_session->GetPlayer()->GetObjectGuid()); return true; } bool ChatHandler::HandleChangeWeatherCommand(char* args) { // Weather is OFF if (!sWorld.getConfig(CONFIG_BOOL_WEATHER)) { SendSysMessage(LANG_WEATHER_DISABLED); SetSentErrorMessage(true); return false; } uint32 type; if (!ExtractUInt32(&args, type)) { return false; } // see enum WeatherType if (!Weather::IsValidWeatherType(type)) { return false; } float grade; if (!ExtractFloat(&args, grade)) { return false; } // 0 to 1, sending -1 is instant good weather if (grade < 0.0f || grade > 1.0f) { return false; } Player* player = m_session->GetPlayer(); uint32 zoneId = player->GetZoneId(); if (!sWeatherMgr.GetWeatherChances(zoneId)) { SendSysMessage(LANG_NO_WEATHER); SetSentErrorMessage(true); } player->GetMap()->SetWeather(zoneId, (WeatherType)type, grade, false); return true; } bool ChatHandler::HandleTeleAddCommand(char* args) { if (!*args) { return false; } Player* player = m_session->GetPlayer(); if (!player) { return false; } std::string name = args; if (sObjectMgr.GetGameTele(name)) { SendSysMessage(LANG_COMMAND_TP_ALREADYEXIST); SetSentErrorMessage(true); return false; } GameTele tele; tele.position_x = player->GetPositionX(); tele.position_y = player->GetPositionY(); tele.position_z = player->GetPositionZ(); tele.orientation = player->GetOrientation(); tele.mapId = player->GetMapId(); tele.name = name; if (sObjectMgr.AddGameTele(tele)) { SendSysMessage(LANG_COMMAND_TP_ADDED); } else { SendSysMessage(LANG_COMMAND_TP_ADDEDERR); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleTeleDelCommand(char* args) { if (!*args) { return false; } std::string name = args; if (!sObjectMgr.DeleteGameTele(name)) { SendSysMessage(LANG_COMMAND_TELE_NOTFOUND); SetSentErrorMessage(true); return false; } SendSysMessage(LANG_COMMAND_TP_DELETED); return true; } bool ChatHandler::HandleListAurasCommand(char* /*args*/) { Unit* unit = getSelectedUnit(); if (!unit) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } char const* talentStr = GetMangosString(LANG_TALENT); char const* passiveStr = GetMangosString(LANG_PASSIVE); Unit::SpellAuraHolderMap const& uAuras = unit->GetSpellAuraHolderMap(); PSendSysMessage(LANG_COMMAND_TARGET_LISTAURAS, uAuras.size()); for (Unit::SpellAuraHolderMap::const_iterator itr = uAuras.begin(); itr != uAuras.end(); ++itr) { bool talent = GetTalentSpellCost(itr->second->GetId()) > 0; SpellAuraHolder* holder = itr->second; char const* name = holder->GetSpellProto()->SpellName[GetSessionDbcLocale()]; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { Aura* aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); if (!aur) { continue; } if (m_session) { std::ostringstream ss_name; ss_name << "|cffffffff|Hspell:" << itr->second->GetId() << "|h[" << name << "]|h|r"; PSendSysMessage(LANG_COMMAND_TARGET_AURADETAIL, holder->GetId(), aur->GetEffIndex(), aur->GetModifier()->m_auraname, aur->GetAuraDuration(), aur->GetAuraMaxDuration(), ss_name.str().c_str(), (holder->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), holder->GetCasterGuid().GetString().c_str()); } else { PSendSysMessage(LANG_COMMAND_TARGET_AURADETAIL, holder->GetId(), aur->GetEffIndex(), aur->GetModifier()->m_auraname, aur->GetAuraDuration(), aur->GetAuraMaxDuration(), name, (holder->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), holder->GetCasterGuid().GetString().c_str()); } } } for (int i = 0; i < TOTAL_AURAS; ++i) { Unit::AuraList const& uAuraList = unit->GetAurasByType(AuraType(i)); if (uAuraList.empty()) { continue; } PSendSysMessage(LANG_COMMAND_TARGET_LISTAURATYPE, uAuraList.size(), i); for (Unit::AuraList::const_iterator itr = uAuraList.begin(); itr != uAuraList.end(); ++itr) { bool talent = GetTalentSpellCost((*itr)->GetId()) > 0; char const* name = (*itr)->GetSpellProto()->SpellName[GetSessionDbcLocale()]; if (m_session) { std::ostringstream ss_name; ss_name << "|cffffffff|Hspell:" << (*itr)->GetId() << "|h[" << name << "]|h|r"; PSendSysMessage(LANG_COMMAND_TARGET_AURASIMPLE, (*itr)->GetId(), (*itr)->GetEffIndex(), ss_name.str().c_str(), ((*itr)->GetHolder()->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), (*itr)->GetCasterGuid().GetString().c_str()); } else { PSendSysMessage(LANG_COMMAND_TARGET_AURASIMPLE, (*itr)->GetId(), (*itr)->GetEffIndex(), name, ((*itr)->GetHolder()->IsPassive() ? passiveStr : ""), (talent ? talentStr : ""), (*itr)->GetCasterGuid().GetString().c_str()); } } } return true; } bool ChatHandler::HandleListTalentsCommand(char* /*args*/) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } SendSysMessage(LANG_LIST_TALENTS_TITLE); uint32 count = 0; uint32 cost = 0; PlayerSpellMap const& uSpells = player->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = uSpells.begin(); itr != uSpells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.disabled) { continue; } uint32 cost_itr = GetTalentSpellCost(itr->first); if (cost_itr == 0) { continue; } SpellEntry const* spellEntry = sSpellStore.LookupEntry(itr->first); if (!spellEntry) { continue; } ShowSpellListHelper(player, spellEntry, GetSessionDbcLocale()); ++count; cost += cost_itr; } PSendSysMessage(LANG_LIST_TALENTS_COUNT, count, cost); return true; } bool ChatHandler::HandleResetAchievementsCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) return false; if (target) target->GetAchievementMgr().Reset(); else AchievementMgr::DeleteFromDB(target_guid); return true; } bool ChatHandler::HandleResetHonorCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } target->SetHonorPoints(0); target->SetUInt32Value(PLAYER_FIELD_KILLS, 0); target->SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0); target->SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0); target->SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0); target->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL); return true; } static bool HandleResetStatsOrLevelHelper(Player* player) { ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(player->getClass()); if (!cEntry) { sLog.outError("Class %u not found in DBC (Wrong DBC files?)", player->getClass()); return false; } uint8 powertype = cEntry->powerType; // reset m_form if no aura if (!player->HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) { player->SetShapeshiftForm(FORM_NONE); } player->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE); player->SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); player->setFactionForRace(player->getRace()); player->SetByteValue(UNIT_FIELD_BYTES_0, 3, powertype); // reset only if player not in some form; if (player->GetShapeshiftForm() == FORM_NONE) { player->InitDisplayIds(); } player->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); player->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); //-1 is default value player->SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1); // player->SetUInt32Value(PLAYER_FIELD_BYTES, 0xEEE00000 ); return true; } bool ChatHandler::HandleResetLevelCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } if (!HandleResetStatsOrLevelHelper(target)) { return false; } // set starting level uint32 start_level = target->getClass() != CLASS_DEATH_KNIGHT ? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL) : sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL); target->_ApplyAllLevelScaleItemMods(false); target->SetLevel(start_level); target->InitRunes(); target->InitStatsForLevel(true); target->InitTaxiNodesForLevel(); target->InitGlyphsForLevel(); target->InitTalentForLevel(); target->SetUInt32Value(PLAYER_XP, 0); target->_ApplyAllLevelScaleItemMods(true); // reset level for pet if (Pet* pet = target->GetPet()) { pet->SynchronizeLevelWithOwner(); } return true; } bool ChatHandler::HandleResetStatsCommand(char* args) { Player* target; if (!ExtractPlayerTarget(&args, &target)) { return false; } if (!HandleResetStatsOrLevelHelper(target)) { return false; } target->InitRunes(); target->InitStatsForLevel(true); target->InitTaxiNodesForLevel(); target->InitGlyphsForLevel(); target->InitTalentForLevel(); return true; } bool ChatHandler::HandleResetSpellsCommand(char* args) { Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name)) { return false; } if (target) { target->resetSpells(); ChatHandler(target).SendSysMessage(LANG_RESET_SPELLS); if (!m_session || m_session->GetPlayer() != target) { PSendSysMessage(LANG_RESET_SPELLS_ONLINE, GetNameLink(target).c_str()); } } else { CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'", uint32(AT_LOGIN_RESET_SPELLS), target_guid.GetCounter()); PSendSysMessage(LANG_RESET_SPELLS_OFFLINE, target_name.c_str()); } return true; } bool ChatHandler::HandleResetSpecsCommand(char* args) { Player* target; ObjectGuid target_guid; std::string target_name; if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name)) { return false; } if (target) { target->resetTalents(true, true); target->SendTalentsInfoData(false); ChatHandler(target).SendSysMessage(LANG_RESET_TALENTS); if (!m_session || m_session->GetPlayer() != target) { PSendSysMessage(LANG_RESET_TALENTS_ONLINE, GetNameLink(target).c_str()); } Pet* pet = target->GetPet(); Pet::resetTalentsForAllPetsOf(target, pet); if (pet) target->SendTalentsInfoData(true); return true; } else if (target_guid) { uint32 at_flags = AT_LOGIN_RESET_TALENTS | AT_LOGIN_RESET_PET_TALENTS; CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid = '%u'", at_flags, target_guid.GetCounter()); std::string nameLink = playerLink(target_name); PSendSysMessage(LANG_RESET_TALENTS_OFFLINE, nameLink.c_str()); return true; } SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } bool ChatHandler::HandleResetTalentsCommand(char* args) { Player* target; std::string target_name; if (!ExtractPlayerTarget(&args, &target, NULL, &target_name)) { // Try reset talents as Hunter Pet Creature* creature = getSelectedCreature(); if (!*args && creature && creature->IsPet()) { Unit* owner = creature->GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER && ((Pet*)creature)->IsPermanentPetFor((Player*)owner)) { ((Pet*)creature)->resetTalents(true); ((Player*)owner)->SendTalentsInfoData(true); ChatHandler((Player*)owner).SendSysMessage(LANG_RESET_PET_TALENTS); if (!m_session || m_session->GetPlayer() != ((Player*)owner)) PSendSysMessage(LANG_RESET_PET_TALENTS_ONLINE, GetNameLink((Player*)owner).c_str()); } return true; } SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } if (target) { target->resetTalents(true); target->SendTalentsInfoData(false); ChatHandler(target).SendSysMessage(LANG_RESET_TALENTS); if (!m_session || m_session->GetPlayer() != target) PSendSysMessage(LANG_RESET_TALENTS_ONLINE, GetNameLink(target).c_str()); Pet* pet = target->GetPet(); Pet::resetTalentsForAllPetsOf(target, pet); if (pet) target->SendTalentsInfoData(true); return true; } SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } bool ChatHandler::HandleResetAllCommand(char* args) { if (!*args) { return false; } std::string casename = args; AtLoginFlags atLogin; // Command specially created as single command to prevent using short case names if (casename == "spells") { atLogin = AT_LOGIN_RESET_SPELLS; sWorld.SendWorldText(LANG_RESETALL_SPELLS); if (!m_session) { SendSysMessage(LANG_RESETALL_SPELLS); } } else if (casename == "talents") { atLogin = AtLoginFlags(AT_LOGIN_RESET_TALENTS | AT_LOGIN_RESET_PET_TALENTS); sWorld.SendWorldText(LANG_RESETALL_TALENTS); if (!m_session) { SendSysMessage(LANG_RESETALL_TALENTS); } } else { PSendSysMessage(LANG_RESETALL_UNKNOWN_CASE, args); SetSentErrorMessage(true); return false; } CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE (at_login & '%u') = '0'", atLogin, atLogin); HashMapHolder<Player>::MapType const& plist = sObjectAccessor.GetPlayers(); for (HashMapHolder<Player>::MapType::const_iterator itr = plist.begin(); itr != plist.end(); ++itr) { itr->second->SetAtLoginFlag(atLogin); } return true; } bool ChatHandler::HandleServerShutDownCancelCommand(char* /*args*/) { sWorld.ShutdownCancel(); return true; } bool ChatHandler::HandleServerShutDownCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) return false; uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, SHUTDOWN_EXIT_CODE)) return false; // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) return false; sWorld.ShutdownServ(delay, 0, exitcode); return true; } bool ChatHandler::HandleServerRestartCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) { return false; } uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, RESTART_EXIT_CODE)) { return false; } // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) { return false; } sWorld.ShutdownServ(delay, SHUTDOWN_MASK_RESTART, exitcode); return true; } bool ChatHandler::HandleServerIdleRestartCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) return false; uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, RESTART_EXIT_CODE)) return false; // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) return false; sWorld.ShutdownServ(delay, SHUTDOWN_MASK_RESTART | SHUTDOWN_MASK_IDLE, exitcode); return true; } bool ChatHandler::HandleServerIdleShutDownCommand(char* args) { uint32 delay; if (!ExtractUInt32(&args, delay)) return false; uint32 exitcode; if (!ExtractOptUInt32(&args, exitcode, SHUTDOWN_EXIT_CODE)) return false; // Exit code should be in range of 0-125, 126-255 is used // in many shells for their own return codes and code > 255 // is not supported in many others if (exitcode > 125) return false; sWorld.ShutdownServ(delay, SHUTDOWN_MASK_IDLE, exitcode); return true; } bool ChatHandler::HandleQuestAddCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // .addquest #entry' // number or [name] Shift-click form |color|Hquest:quest_id:quest_level|h[name]|h|r uint32 entry; if (!ExtractUint32KeyFromLink(&args, "Hquest", entry)) { return false; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(entry); if (!pQuest) { PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry); SetSentErrorMessage(true); return false; } // check item starting quest (it can work incorrectly if added without item in inventory) for (uint32 id = 0; id < sItemStorage.GetMaxEntry(); ++id) { ItemPrototype const* pProto = sItemStorage.LookupEntry<ItemPrototype>(id); if (!pProto) { continue; } if (pProto->StartQuest == entry) { PSendSysMessage(LANG_COMMAND_QUEST_STARTFROMITEM, entry, pProto->ItemId); SetSentErrorMessage(true); return false; } } // ok, normal (creature/GO starting) quest if (player->CanAddQuest(pQuest, true)) { player->AddQuest(pQuest, NULL); if (player->CanCompleteQuest(entry)) { player->CompleteQuest(entry); } } return true; } bool ChatHandler::HandleQuestRemoveCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // .removequest #entry' // number or [name] Shift-click form |color|Hquest:quest_id:quest_level|h[name]|h|r uint32 entry; if (!ExtractUint32KeyFromLink(&args, "Hquest", entry)) { return false; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(entry); if (!pQuest) { PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry); SetSentErrorMessage(true); return false; } // remove all quest entries for 'entry' from quest log for (uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot) { uint32 quest = player->GetQuestSlotQuestId(slot); if (quest == entry) { player->SetQuestSlot(slot, 0); // we ignore unequippable quest items in this case, its' still be equipped player->TakeQuestSourceItem(quest, false); } } // set quest status to not started (will updated in DB at next save) player->SetQuestStatus(entry, QUEST_STATUS_NONE); // reset rewarded for restart repeatable quest player->getQuestStatusMap()[entry].m_rewarded = false; SendSysMessage(LANG_COMMAND_QUEST_REMOVED); return true; } bool ChatHandler::HandleQuestCompleteCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { SendSysMessage(LANG_NO_CHAR_SELECTED); SetSentErrorMessage(true); return false; } // .quest complete #entry // number or [name] Shift-click form |color|Hquest:quest_id:quest_level|h[name]|h|r uint32 entry; if (!ExtractUint32KeyFromLink(&args, "Hquest", entry)) { return false; } Quest const* pQuest = sObjectMgr.GetQuestTemplate(entry); // If player doesn't have the quest if (!pQuest || player->GetQuestStatus(entry) == QUEST_STATUS_NONE) { PSendSysMessage(LANG_COMMAND_QUEST_NOTFOUND, entry); SetSentErrorMessage(true); return false; } // Add quest items for quests that require items for (uint8 x = 0; x < QUEST_ITEM_OBJECTIVES_COUNT; ++x) { uint32 id = pQuest->ReqItemId[x]; uint32 count = pQuest->ReqItemCount[x]; if (!id || !count) { continue; } uint32 curItemCount = player->GetItemCount(id, true); ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, id, count - curItemCount); if (msg == EQUIP_ERR_OK) { Item* item = player->StoreNewItem(dest, id, true); player->SendNewItem(item, count - curItemCount, true, false); } } // All creature/GO slain/casted (not required, but otherwise it will display "Creature slain 0/10") for (uint8 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) { int32 creature = pQuest->ReqCreatureOrGOId[i]; uint32 creaturecount = pQuest->ReqCreatureOrGOCount[i]; if (uint32 spell_id = pQuest->ReqSpell[i]) { for (uint16 z = 0; z < creaturecount; ++z) { player->CastedCreatureOrGO(creature, ObjectGuid(), spell_id); } } else if (creature > 0) { if (CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(creature)) for (uint16 z = 0; z < creaturecount; ++z) { player->KilledMonster(cInfo, ObjectGuid()); } } else if (creature < 0) { for (uint16 z = 0; z < creaturecount; ++z) { player->CastedCreatureOrGO(-creature, ObjectGuid(), 0); } } } // If the quest requires reputation to complete if (uint32 repFaction = pQuest->GetRepObjectiveFaction()) { uint32 repValue = pQuest->GetRepObjectiveValue(); uint32 curRep = player->GetReputationMgr().GetReputation(repFaction); if (curRep < repValue) if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(repFaction)) { player->GetReputationMgr().SetReputation(factionEntry, repValue); } } // If the quest requires money int32 ReqOrRewMoney = pQuest->GetRewOrReqMoney(); if (ReqOrRewMoney < 0) { player->ModifyMoney(-ReqOrRewMoney); } player->CompleteQuest(entry); return true; } bool ChatHandler::HandleBanAccountCommand(char* args) { return HandleBanHelper(BAN_ACCOUNT, args); } bool ChatHandler::HandleBanCharacterCommand(char* args) { return HandleBanHelper(BAN_CHARACTER, args); } bool ChatHandler::HandleBanIPCommand(char* args) { return HandleBanHelper(BAN_IP, args); } bool ChatHandler::HandleBanHelper(BanMode mode, char* args) { if (!*args) { return false; } char* cnameOrIP = ExtractArg(&args); if (!cnameOrIP) { return false; } std::string nameOrIP = cnameOrIP; char* duration = ExtractArg(&args); // time string if (!duration) { return false; } uint32 duration_secs = TimeStringToSecs(duration); char* reason = ExtractArg(&args); if (!reason) { return false; } switch (mode) { case BAN_ACCOUNT: if (!AccountMgr::normalizeString(nameOrIP)) { PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); SetSentErrorMessage(true); return false; } break; case BAN_CHARACTER: if (!normalizePlayerName(nameOrIP)) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } break; case BAN_IP: if (!IsIPAddress(nameOrIP.c_str())) { return false; } break; } switch (sWorld.BanAccount(mode, nameOrIP, duration_secs, reason, m_session ? m_session->GetPlayerName() : "")) { case BAN_SUCCESS: if (duration_secs > 0) { PSendSysMessage(LANG_BAN_YOUBANNED, nameOrIP.c_str(), secsToTimeString(duration_secs, true).c_str(), reason); } else { PSendSysMessage(LANG_BAN_YOUPERMBANNED, nameOrIP.c_str(), reason); } break; case BAN_SYNTAX_ERROR: return false; case BAN_NOTFOUND: switch (mode) { default: PSendSysMessage(LANG_BAN_NOTFOUND, "account", nameOrIP.c_str()); break; case BAN_CHARACTER: PSendSysMessage(LANG_BAN_NOTFOUND, "character", nameOrIP.c_str()); break; case BAN_IP: PSendSysMessage(LANG_BAN_NOTFOUND, "ip", nameOrIP.c_str()); break; } SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleUnBanAccountCommand(char* args) { return HandleUnBanHelper(BAN_ACCOUNT, args); } bool ChatHandler::HandleUnBanCharacterCommand(char* args) { return HandleUnBanHelper(BAN_CHARACTER, args); } bool ChatHandler::HandleUnBanIPCommand(char* args) { return HandleUnBanHelper(BAN_IP, args); } bool ChatHandler::HandleUnBanHelper(BanMode mode, char* args) { if (!*args) { return false; } char* cnameOrIP = ExtractArg(&args); if (!cnameOrIP) { return false; } std::string nameOrIP = cnameOrIP; switch (mode) { case BAN_ACCOUNT: if (!AccountMgr::normalizeString(nameOrIP)) { PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); SetSentErrorMessage(true); return false; } break; case BAN_CHARACTER: if (!normalizePlayerName(nameOrIP)) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } break; case BAN_IP: if (!IsIPAddress(nameOrIP.c_str())) { return false; } break; } if (sWorld.RemoveBanAccount(mode, nameOrIP)) { PSendSysMessage(LANG_UNBAN_UNBANNED, nameOrIP.c_str()); } else { PSendSysMessage(LANG_UNBAN_ERROR, nameOrIP.c_str()); } return true; } bool ChatHandler::HandleBanInfoAccountCommand(char* args) { if (!*args) { return false; } std::string account_name; uint32 accountid = ExtractAccountId(&args, &account_name); if (!accountid) { return false; } return HandleBanInfoHelper(accountid, account_name.c_str()); } bool ChatHandler::HandleBanInfoCharacterCommand(char* args) { Player* target; ObjectGuid target_guid; if (!ExtractPlayerTarget(&args, &target, &target_guid)) { return false; } uint32 accountid = target ? target->GetSession()->GetAccountId() : sObjectMgr.GetPlayerAccountIdByGUID(target_guid); std::string accountname; if (!sAccountMgr.GetName(accountid, accountname)) { PSendSysMessage(LANG_BANINFO_NOCHARACTER); return true; } return HandleBanInfoHelper(accountid, accountname.c_str()); } bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname) { QueryResult* result = LoginDatabase.PQuery("SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate,banreason,bannedby FROM account_banned WHERE id = '%u' ORDER BY bandate ASC", accountid); if (!result) { PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname); return true; } PSendSysMessage(LANG_BANINFO_BANHISTORY, accountname); do { Field* fields = result->Fetch(); time_t unbandate = time_t(fields[3].GetUInt64()); bool active = false; if (fields[2].GetBool() && (fields[1].GetUInt64() == (uint64)0 || unbandate >= time(NULL))) { active = true; } bool permanent = (fields[1].GetUInt64() == (uint64)0); std::string bantime = permanent ? GetMangosString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); PSendSysMessage(LANG_BANINFO_HISTORYENTRY, fields[0].GetString(), bantime.c_str(), active ? GetMangosString(LANG_BANINFO_YES) : GetMangosString(LANG_BANINFO_NO), fields[4].GetString(), fields[5].GetString()); } while (result->NextRow()); delete result; return true; } bool ChatHandler::HandleBanInfoIPCommand(char* args) { if (!*args) { return false; } char* cIP = ExtractQuotedOrLiteralArg(&args); if (!cIP) { return false; } if (!IsIPAddress(cIP)) { return false; } std::string IP = cIP; LoginDatabase.escape_string(IP); QueryResult* result = LoginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(bandate), FROM_UNIXTIME(unbandate), unbandate-UNIX_TIMESTAMP(), banreason,bannedby,unbandate-bandate FROM ip_banned WHERE ip = '%s'", IP.c_str()); if (!result) { PSendSysMessage(LANG_BANINFO_NOIP); return true; } Field* fields = result->Fetch(); bool permanent = !fields[6].GetUInt64(); PSendSysMessage(LANG_BANINFO_IPENTRY, fields[0].GetString(), fields[1].GetString(), permanent ? GetMangosString(LANG_BANINFO_NEVER) : fields[2].GetString(), permanent ? GetMangosString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[3].GetUInt64(), true).c_str(), fields[4].GetString(), fields[5].GetString()); delete result; return true; } bool ChatHandler::HandleBanListCharacterCommand(char* args) { LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); char* cFilter = ExtractLiteralArg(&args); if (!cFilter) { return false; } std::string filter = cFilter; LoginDatabase.escape_string(filter); QueryResult* result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), filter.c_str()); if (!result) { PSendSysMessage(LANG_BANLIST_NOCHARACTER); return true; } return HandleBanListHelper(result); } bool ChatHandler::HandleBanListAccountCommand(char* args) { LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); char* cFilter = ExtractLiteralArg(&args); std::string filter = cFilter ? cFilter : ""; LoginDatabase.escape_string(filter); QueryResult* result; if (filter.empty()) { result = LoginDatabase.Query("SELECT account.id, username FROM account, account_banned" " WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id"); } else { result = LoginDatabase.PQuery("SELECT account.id, username FROM account, account_banned" " WHERE account.id = account_banned.id AND active = 1 AND username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'")" GROUP BY account.id", filter.c_str()); } if (!result) { PSendSysMessage(LANG_BANLIST_NOACCOUNT); return true; } return HandleBanListHelper(result); } bool ChatHandler::HandleBanListHelper(QueryResult* result) { PSendSysMessage(LANG_BANLIST_MATCHINGACCOUNT); // Chat short output if (m_session) { do { Field* fields = result->Fetch(); uint32 accountid = fields[0].GetUInt32(); QueryResult* banresult = LoginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id", accountid); if (banresult) { Field* fields2 = banresult->Fetch(); PSendSysMessage("%s", fields2[0].GetString()); delete banresult; } } while (result->NextRow()); } // Console wide output else { SendSysMessage(LANG_BANLIST_ACCOUNTS); SendSysMessage("==============================================================================="); SendSysMessage(LANG_BANLIST_ACCOUNTS_HEADER); do { SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); uint32 account_id = fields[0].GetUInt32(); std::string account_name; // "account" case, name can be get in same query if (result->GetFieldCount() > 1) { account_name = fields[1].GetCppString(); } // "character" case, name need extract from another DB else { sAccountMgr.GetName(account_id, account_name); } // No SQL injection. id is uint32. QueryResult* banInfo = LoginDatabase.PQuery("SELECT bandate,unbandate,bannedby,banreason FROM account_banned WHERE id = %u ORDER BY unbandate", account_id); if (banInfo) { Field* fields2 = banInfo->Fetch(); do { time_t t_ban = fields2[0].GetUInt64(); tm* aTm_ban = localtime(&t_ban); if (fields2[0].GetUInt64() == fields2[1].GetUInt64()) { PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", account_name.c_str(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, fields2[2].GetString(), fields2[3].GetString()); } else { time_t t_unban = fields2[1].GetUInt64(); tm* aTm_unban = localtime(&t_unban); PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", account_name.c_str(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, aTm_unban->tm_year % 100, aTm_unban->tm_mon + 1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min, fields2[2].GetString(), fields2[3].GetString()); } } while (banInfo->NextRow()); delete banInfo; } } while (result->NextRow()); SendSysMessage("==============================================================================="); } delete result; return true; } bool ChatHandler::HandleBanListIPCommand(char* args) { LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); char* cFilter = ExtractLiteralArg(&args); std::string filter = cFilter ? cFilter : ""; LoginDatabase.escape_string(filter); QueryResult* result; if (filter.empty()) { result = LoginDatabase.Query("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned" " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP())" " ORDER BY unbandate"); } else { result = LoginDatabase.PQuery("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned" " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP()) AND ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'") " ORDER BY unbandate", filter.c_str()); } if (!result) { PSendSysMessage(LANG_BANLIST_NOIP); return true; } PSendSysMessage(LANG_BANLIST_MATCHINGIP); // Chat short output if (m_session) { do { Field* fields = result->Fetch(); PSendSysMessage("%s", fields[0].GetString()); } while (result->NextRow()); } // Console wide output else { SendSysMessage(LANG_BANLIST_IPS); SendSysMessage("==============================================================================="); SendSysMessage(LANG_BANLIST_IPS_HEADER); do { SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); time_t t_ban = fields[1].GetUInt64(); tm* aTm_ban = localtime(&t_ban); if (fields[1].GetUInt64() == fields[2].GetUInt64()) { PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", fields[0].GetString(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, fields[3].GetString(), fields[4].GetString()); } else { time_t t_unban = fields[2].GetUInt64(); tm* aTm_unban = localtime(&t_unban); PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", fields[0].GetString(), aTm_ban->tm_year % 100, aTm_ban->tm_mon + 1, aTm_ban->tm_mday, aTm_ban->tm_hour, aTm_ban->tm_min, aTm_unban->tm_year % 100, aTm_unban->tm_mon + 1, aTm_unban->tm_mday, aTm_unban->tm_hour, aTm_unban->tm_min, fields[3].GetString(), fields[4].GetString()); } } while (result->NextRow()); SendSysMessage("==============================================================================="); } delete result; return true; } bool ChatHandler::HandleRespawnCommand(char* /*args*/) { Player* pl = m_session->GetPlayer(); // accept only explicitly selected target (not implicitly self targeting case) Unit* target = getSelectedUnit(); if (pl->GetSelectionGuid() && target) { if (target->GetTypeId() != TYPEID_UNIT) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } if (target->IsDead()) { ((Creature*)target)->Respawn(); } return true; } MaNGOS::RespawnDo u_do; MaNGOS::WorldObjectWorker<MaNGOS::RespawnDo> worker(pl, u_do); Cell::VisitGridObjects(pl, worker, pl->GetMap()->GetVisibilityDistance()); return true; } bool ChatHandler::HandleGMFlyCommand(char* args) { bool value; if (!ExtractOnOff(&args, value)) { SendSysMessage(LANG_USE_BOL); SetSentErrorMessage(true); return false; } Player* target = getSelectedPlayer(); if (!target) { target = m_session->GetPlayer(); } target->SetCanFly(value); PSendSysMessage(LANG_COMMAND_FLYMODE_STATUS, GetNameLink(target).c_str(), args); return true; } bool ChatHandler::HandlePDumpLoadCommand(char* args) { char* file = ExtractQuotedOrLiteralArg(&args); if (!file) { return false; } std::string account_name; uint32 account_id = ExtractAccountId(&args, &account_name); if (!account_id) { return false; } char* name_str = ExtractLiteralArg(&args); uint32 lowguid = 0; std::string name; if (name_str) { name = name_str; // normalize the name if specified and check if it exists if (!normalizePlayerName(name)) { PSendSysMessage(LANG_INVALID_CHARACTER_NAME); SetSentErrorMessage(true); return false; } if (ObjectMgr::CheckPlayerName(name, true) != CHAR_NAME_SUCCESS) { PSendSysMessage(LANG_INVALID_CHARACTER_NAME); SetSentErrorMessage(true); return false; } if (*args) { if (!ExtractUInt32(&args, lowguid)) { return false; } if (!lowguid) { PSendSysMessage(LANG_INVALID_CHARACTER_GUID); SetSentErrorMessage(true); return false; } ObjectGuid guid = ObjectGuid(HIGHGUID_PLAYER, lowguid); if (sObjectMgr.GetPlayerAccountIdByGUID(guid)) { PSendSysMessage(LANG_CHARACTER_GUID_IN_USE, lowguid); SetSentErrorMessage(true); return false; } } } switch (PlayerDumpReader().LoadDump(file, account_id, name, lowguid)) { case DUMP_SUCCESS: PSendSysMessage(LANG_COMMAND_IMPORT_SUCCESS); break; case DUMP_FILE_OPEN_ERROR: PSendSysMessage(LANG_FILE_OPEN_FAIL, file); SetSentErrorMessage(true); return false; case DUMP_FILE_BROKEN: PSendSysMessage(LANG_DUMP_BROKEN, file); SetSentErrorMessage(true); return false; case DUMP_TOO_MANY_CHARS: PSendSysMessage(LANG_ACCOUNT_CHARACTER_LIST_FULL, account_name.c_str(), account_id); SetSentErrorMessage(true); return false; default: PSendSysMessage(LANG_COMMAND_IMPORT_FAILED); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandlePDumpWriteCommand(char* args) { if (!*args) { return false; } char* file = ExtractQuotedOrLiteralArg(&args); if (!file) { return false; } char* p2 = ExtractLiteralArg(&args); uint32 lowguid; ObjectGuid guid; // character name can't start from number if (!ExtractUInt32(&p2, lowguid)) { std::string name = ExtractPlayerNameFromLink(&p2); if (name.empty()) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } guid = sObjectMgr.GetPlayerGuidByName(name); if (!guid) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } lowguid = guid.GetCounter(); } else { guid = ObjectGuid(HIGHGUID_PLAYER, lowguid); } if (!sObjectMgr.GetPlayerAccountIdByGUID(guid)) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } switch (PlayerDumpWriter().WriteDump(file, lowguid)) { case DUMP_SUCCESS: PSendSysMessage(LANG_COMMAND_EXPORT_SUCCESS); break; case DUMP_FILE_OPEN_ERROR: PSendSysMessage(LANG_FILE_OPEN_FAIL, file); SetSentErrorMessage(true); return false; default: PSendSysMessage(LANG_COMMAND_EXPORT_FAILED); SetSentErrorMessage(true); return false; } return true; } bool ChatHandler::HandleMovegensCommand(char* /*args*/) { Unit* unit = getSelectedUnit(); if (!unit) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } PSendSysMessage(LANG_MOVEGENS_LIST, (unit->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), unit->GetGUIDLow()); MotionMaster* mm = unit->GetMotionMaster(); float x, y, z; mm->GetDestination(x, y, z); for (MotionMaster::const_iterator itr = mm->begin(); itr != mm->end(); ++itr) { switch ((*itr)->GetMovementGeneratorType()) { case IDLE_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_IDLE); break; case RANDOM_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_RANDOM); break; case WAYPOINT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_WAYPOINT); break; case CONFUSED_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_CONFUSED); break; case CHASE_MOTION_TYPE: { Unit* target = NULL; if (unit->GetTypeId() == TYPEID_PLAYER) { target = static_cast<ChaseMovementGenerator<Player> const*>(*itr)->GetTarget(); } else { target = static_cast<ChaseMovementGenerator<Creature> const*>(*itr)->GetTarget(); } if (!target) { SendSysMessage(LANG_MOVEGENS_CHASE_NULL); } else if (target->GetTypeId() == TYPEID_PLAYER) { PSendSysMessage(LANG_MOVEGENS_CHASE_PLAYER, target->GetName(), target->GetGUIDLow()); } else { PSendSysMessage(LANG_MOVEGENS_CHASE_CREATURE, target->GetName(), target->GetGUIDLow()); } break; } case FOLLOW_MOTION_TYPE: { Unit* target = NULL; if (unit->GetTypeId() == TYPEID_PLAYER) { target = static_cast<FollowMovementGenerator<Player> const*>(*itr)->GetTarget(); } else { target = static_cast<FollowMovementGenerator<Creature> const*>(*itr)->GetTarget(); } if (!target) { SendSysMessage(LANG_MOVEGENS_FOLLOW_NULL); } else if (target->GetTypeId() == TYPEID_PLAYER) { PSendSysMessage(LANG_MOVEGENS_FOLLOW_PLAYER, target->GetName(), target->GetGUIDLow()); } else { PSendSysMessage(LANG_MOVEGENS_FOLLOW_CREATURE, target->GetName(), target->GetGUIDLow()); } break; } case HOME_MOTION_TYPE: if (unit->GetTypeId() == TYPEID_UNIT) { PSendSysMessage(LANG_MOVEGENS_HOME_CREATURE, x, y, z); } else { SendSysMessage(LANG_MOVEGENS_HOME_PLAYER); } break; case FLIGHT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_FLIGHT); break; case POINT_MOTION_TYPE: { PSendSysMessage(LANG_MOVEGENS_POINT, x, y, z); break; } case FLEEING_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_FEAR); break; case DISTRACT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_DISTRACT); break; case EFFECT_MOTION_TYPE: SendSysMessage(LANG_MOVEGENS_EFFECT); break; default: PSendSysMessage(LANG_MOVEGENS_UNKNOWN, (*itr)->GetMovementGeneratorType()); break; } } return true; } bool ChatHandler::HandleServerPLimitCommand(char* args) { if (*args) { char* param = ExtractLiteralArg(&args); if (!param) { return false; } int l = strlen(param); int val; if (strncmp(param, "player", l) == 0) { sWorld.SetPlayerLimit(-SEC_PLAYER); } else if (strncmp(param, "moderator", l) == 0) { sWorld.SetPlayerLimit(-SEC_MODERATOR); } else if (strncmp(param, "gamemaster", l) == 0) { sWorld.SetPlayerLimit(-SEC_GAMEMASTER); } else if (strncmp(param, "administrator", l) == 0) { sWorld.SetPlayerLimit(-SEC_ADMINISTRATOR); } else if (strncmp(param, "reset", l) == 0) { sWorld.SetPlayerLimit(sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT)); } else if (ExtractInt32(&param, val)) { if (val < -SEC_ADMINISTRATOR) { val = -SEC_ADMINISTRATOR; } sWorld.SetPlayerLimit(val); } else { return false; } // kick all low security level players if (sWorld.GetPlayerAmountLimit() > SEC_PLAYER) { sWorld.KickAllLess(sWorld.GetPlayerSecurityLimit()); } } uint32 pLimit = sWorld.GetPlayerAmountLimit(); AccountTypes allowedAccountType = sWorld.GetPlayerSecurityLimit(); char const* secName = ""; switch (allowedAccountType) { case SEC_PLAYER: secName = "Player"; break; case SEC_MODERATOR: secName = "Moderator"; break; case SEC_GAMEMASTER: secName = "Gamemaster"; break; case SEC_ADMINISTRATOR: secName = "Administrator"; break; default: secName = "<unknown>"; break; } PSendSysMessage("Player limits: amount %u, min. security level %s.", pLimit, secName); return true; } bool ChatHandler::HandleCastCommand(char* args) { if (!*args) { return false; } Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell) { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { return false; } if (!SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } m_session->GetPlayer()->CastSpell(target, spell, triggered); return true; } bool ChatHandler::HandleCastBackCommand(char* args) { Creature* caster = getSelectedCreature(); if (!caster) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell || !sSpellStore.LookupEntry(spell)) { return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } caster->SetFacingToObject(m_session->GetPlayer()); caster->CastSpell(m_session->GetPlayer(), spell, triggered); return true; } bool ChatHandler::HandleCastDistCommand(char* args) { if (!*args) { return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell) { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { return false; } if (!SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } float dist; if (!ExtractFloat(&args, dist)) { return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } float x, y, z; m_session->GetPlayer()->GetClosePoint(x, y, z, dist); m_session->GetPlayer()->CastSpell(x, y, z, spell, triggered); return true; } bool ChatHandler::HandleCastTargetCommand(char* args) { Creature* caster = getSelectedCreature(); if (!caster) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } if (!caster->getVictim()) { SendSysMessage(LANG_SELECTED_TARGET_NOT_HAVE_VICTIM); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell || !sSpellStore.LookupEntry(spell)) { return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } caster->SetFacingToObject(m_session->GetPlayer()); caster->CastSpell(caster->getVictim(), spell, triggered); return true; } /* ComeToMe command REQUIRED for 3rd party scripting library to have access to PointMovementGenerator Without this function 3rd party scripting library will get linking errors (unresolved external) when attempting to use the PointMovementGenerator */ bool ChatHandler::HandleComeToMeCommand(char* /*args*/) { Creature* caster = getSelectedCreature(); if (!caster) { SendSysMessage(LANG_SELECT_CREATURE); SetSentErrorMessage(true); return false; } Player* pl = m_session->GetPlayer(); caster->GetMotionMaster()->MovePoint(0, pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ()); return true; } bool ChatHandler::HandleCastSelfCommand(char* args) { if (!*args) { return false; } Unit* target = getSelectedUnit(); if (!target) { SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); SetSentErrorMessage(true); return false; } // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r or Htalent form uint32 spell = ExtractSpellIdFromLink(&args); if (!spell) { return false; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell); if (!spellInfo) { return false; } if (!SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer())) { PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell); SetSentErrorMessage(true); return false; } bool triggered = ExtractLiteralArg(&args, "triggered") != NULL; if (!triggered && *args) // can be fail also at syntax error { return false; } target->CastSpell(target, spell, triggered); return true; } bool ChatHandler::HandleInstanceListBindsCommand(char* /*args*/) { Player* player = getSelectedPlayer(); if (!player) { player = m_session->GetPlayer(); } uint32 counter = 0; for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { Player::BoundInstancesMap& binds = player->GetBoundInstances(Difficulty(i)); for (Player::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { DungeonPersistentState* state = itr->second.state; std::string timeleft = secsToTimeString(state->GetResetTime() - time(NULL), true); if (const MapEntry* entry = sMapStore.LookupEntry(itr->first)) { PSendSysMessage("map: %d (%s) inst: %d perm: %s diff: %d canReset: %s TTR: %s", itr->first, entry->name[GetSessionDbcLocale()], state->GetInstanceId(), itr->second.perm ? "yes" : "no", state->GetDifficulty(), state->CanReset() ? "yes" : "no", timeleft.c_str()); } else PSendSysMessage("bound for a nonexistent map %u", itr->first); ++counter; } } PSendSysMessage("player binds: %d", counter); counter = 0; if (Group* group = player->GetGroup()) { for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { Group::BoundInstancesMap& binds = group->GetBoundInstances(Difficulty(i)); for (Group::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { DungeonPersistentState* state = itr->second.state; std::string timeleft = secsToTimeString(state->GetResetTime() - time(NULL), true); if (const MapEntry* entry = sMapStore.LookupEntry(itr->first)) { PSendSysMessage("map: %d (%s) inst: %d perm: %s diff: %d canReset: %s TTR: %s", itr->first, entry->name[GetSessionDbcLocale()], state->GetInstanceId(), itr->second.perm ? "yes" : "no", state->GetDifficulty(), state->CanReset() ? "yes" : "no", timeleft.c_str()); } else PSendSysMessage("bound for a nonexistent map %u", itr->first); ++counter; } } } PSendSysMessage("group binds: %d", counter); return true; } bool ChatHandler::HandleInstanceUnbindCommand(char* args) { if (!*args) { return false; } Player* player = getSelectedPlayer(); if (!player) { player = m_session->GetPlayer(); } uint32 counter = 0; uint32 mapid = 0; bool got_map = false; if (strncmp(args, "all", strlen(args)) != 0) { if (!isNumeric(args[0])) { return false; } got_map = true; mapid = atoi(args); } for (uint8 i = 0; i < MAX_DIFFICULTY; ++i) { Player::BoundInstancesMap& binds = player->GetBoundInstances(Difficulty(i)); for (Player::BoundInstancesMap::iterator itr = binds.begin(); itr != binds.end();) { if (got_map && mapid != itr->first) { ++itr; continue; } if (itr->first != player->GetMapId()) { DungeonPersistentState* save = itr->second.state; std::string timeleft = secsToTimeString(save->GetResetTime() - time(NULL), true); if (const MapEntry* entry = sMapStore.LookupEntry(itr->first)) { PSendSysMessage("unbinding map: %d (%s) inst: %d perm: %s diff: %d canReset: %s TTR: %s", itr->first, entry->name[GetSessionDbcLocale()], save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); } else PSendSysMessage("bound for a nonexistent map %u", itr->first); player->UnbindInstance(itr, Difficulty(i)); ++counter; } else ++itr; } } PSendSysMessage("instances unbound: %d", counter); return true; } bool ChatHandler::HandleInstanceStatsCommand(char* /*args*/) { PSendSysMessage("instances loaded: %d", sMapMgr.GetNumInstances()); PSendSysMessage("players in instances: %d", sMapMgr.GetNumPlayersInInstances()); uint32 numSaves, numBoundPlayers, numBoundGroups; sMapPersistentStateMgr.GetStatistics(numSaves, numBoundPlayers, numBoundGroups); PSendSysMessage("instance saves: %d", numSaves); PSendSysMessage("players bound: %d", numBoundPlayers); PSendSysMessage("groups bound: %d", numBoundGroups); return true; } bool ChatHandler::HandleInstanceSaveDataCommand(char* /*args*/) { Player* pl = m_session->GetPlayer(); Map* map = pl->GetMap(); InstanceData* iData = map->GetInstanceData(); if (!iData) { PSendSysMessage("Map has no instance data."); SetSentErrorMessage(true); return false; } iData->SaveToDB(); return true; } /// Display the list of GMs bool ChatHandler::HandleGMListFullCommand(char* /*args*/) { ///- Get the accounts with GM Level >0 QueryResult* result = LoginDatabase.Query("SELECT username,gmlevel FROM account WHERE gmlevel > 0"); if (result) { SendSysMessage(LANG_GMLIST); SendSysMessage("========================"); SendSysMessage(LANG_GMLIST_HEADER); SendSysMessage("========================"); ///- Circle through them. Display username and GM level do { Field* fields = result->Fetch(); PSendSysMessage("|%15s|%6s|", fields[0].GetString(), fields[1].GetString()); } while (result->NextRow()); PSendSysMessage("========================"); delete result; } else { PSendSysMessage(LANG_GMLIST_EMPTY); } return true; } /// Define the 'Message of the day' for the realm bool ChatHandler::HandleServerSetMotdCommand(char* args) { sWorld.SetMotd(args); PSendSysMessage(LANG_MOTD_NEW, args); return true; } bool ChatHandler::ShowPlayerListHelper(QueryResult* result, uint32* limit, bool title, bool error) { if (!result) { if (error) { PSendSysMessage(LANG_NO_PLAYERS_FOUND); SetSentErrorMessage(true); } return false; } if (!m_session && title) { SendSysMessage(LANG_CHARACTERS_LIST_BAR); SendSysMessage(LANG_CHARACTERS_LIST_HEADER); SendSysMessage(LANG_CHARACTERS_LIST_BAR); } if (result) { ///- Circle through them. Display username and GM level do { // check limit if (limit) { if (*limit == 0) { break; } --*limit; } Field* fields = result->Fetch(); uint32 guid = fields[0].GetUInt32(); std::string name = fields[1].GetCppString(); uint8 race = fields[2].GetUInt8(); uint8 class_ = fields[3].GetUInt8(); uint32 level = fields[4].GetUInt32(); ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race); ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_); char const* race_name = raceEntry ? raceEntry->name[GetSessionDbcLocale()] : "<?>"; char const* class_name = classEntry ? classEntry->name[GetSessionDbcLocale()] : "<?>"; if (!m_session) { PSendSysMessage(LANG_CHARACTERS_LIST_LINE_CONSOLE, guid, name.c_str(), race_name, class_name, level); } else { PSendSysMessage(LANG_CHARACTERS_LIST_LINE_CHAT, guid, name.c_str(), name.c_str(), race_name, class_name, level); } } while (result->NextRow()); delete result; } if (!m_session) { SendSysMessage(LANG_CHARACTERS_LIST_BAR); } return true; } /// Output list of character for account bool ChatHandler::HandleAccountCharactersCommand(char* args) { ///- Get the command line arguments std::string account_name; Player* target = NULL; // only for triggering use targeted player account uint32 account_id = ExtractAccountId(&args, &account_name, &target); if (!account_id) { return false; } ///- Get the characters for account id QueryResult* result = CharacterDatabase.PQuery("SELECT guid, name, race, class, level FROM characters WHERE account = %u", account_id); return ShowPlayerListHelper(result); } /// Set/Unset the expansion level for an account bool ChatHandler::HandleAccountSetAddonCommand(char* args) { ///- Get the command line arguments char* accountStr = ExtractOptNotLastArg(&args); std::string account_name; uint32 account_id = ExtractAccountId(&accountStr, &account_name); if (!account_id) { return false; } // Let set addon state only for lesser (strong) security level // or to self account if (GetAccountId() && GetAccountId() != account_id && HasLowerSecurityAccount(NULL, account_id, true)) { return false; } uint32 lev; if (!ExtractUInt32(&args, lev)) { return false; } // No SQL injection LoginDatabase.PExecute("UPDATE account SET expansion = '%u' WHERE id = '%u'", lev, account_id); PSendSysMessage(LANG_ACCOUNT_SETADDON, account_name.c_str(), account_id, lev); return true; } bool ChatHandler::HandleSendMailHelper(MailDraft& draft, char* args) { // format: "subject text" "mail text" char* msgSubject = ExtractQuotedArg(&args); if (!msgSubject) { return false; } char* msgText = ExtractQuotedArg(&args); if (!msgText) { return false; } // msgSubject, msgText isn't NUL after prev. check draft.SetSubjectAndBody(msgSubject, msgText); return true; } bool ChatHandler::HandleSendMassMailCommand(char* args) { // format: raceMask "subject text" "mail text" uint32 raceMask = 0; char const* name = NULL; if (!ExtractRaceMask(&args, raceMask, &name)) { return false; } // need dynamic object because it trasfered to mass mailer MailDraft* draft = new MailDraft; // fill mail if (!HandleSendMailHelper(*draft, args)) { delete draft; return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); sMassMailMgr.AddMassMailTask(draft, sender, raceMask); PSendSysMessage(LANG_MAIL_SENT, name); return true; } bool ChatHandler::HandleSendItemsHelper(MailDraft& draft, char* args) { // format: "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] char* msgSubject = ExtractQuotedArg(&args); if (!msgSubject) { return false; } char* msgText = ExtractQuotedArg(&args); if (!msgText) { return false; } // extract items typedef std::pair<uint32, uint32> ItemPair; typedef std::list< ItemPair > ItemPairs; ItemPairs items; // get from tail next item str while (char* itemStr = ExtractArg(&args)) { // parse item str uint32 item_id = 0; uint32 item_count = 1; if (sscanf(itemStr, "%u:%u", &item_id, &item_count) != 2) if (sscanf(itemStr, "%u", &item_id) != 1) { return false; } if (!item_id) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } ItemPrototype const* item_proto = ObjectMgr::GetItemPrototype(item_id); if (!item_proto) { PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, item_id); SetSentErrorMessage(true); return false; } if (item_count < 1 || (item_proto->MaxCount > 0 && item_count > uint32(item_proto->MaxCount))) { PSendSysMessage(LANG_COMMAND_INVALID_ITEM_COUNT, item_count, item_id); SetSentErrorMessage(true); return false; } while (item_count > item_proto->GetMaxStackSize()) { items.push_back(ItemPair(item_id, item_proto->GetMaxStackSize())); item_count -= item_proto->GetMaxStackSize(); } items.push_back(ItemPair(item_id, item_count)); if (items.size() > MAX_MAIL_ITEMS) { PSendSysMessage(LANG_COMMAND_MAIL_ITEMS_LIMIT, MAX_MAIL_ITEMS); SetSentErrorMessage(true); return false; } } // fill mail draft.SetSubjectAndBody(msgSubject, msgText); for (ItemPairs::const_iterator itr = items.begin(); itr != items.end(); ++itr) { if (Item* item = Item::CreateItem(itr->first, itr->second, m_session ? m_session->GetPlayer() : 0)) { item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted draft.AddItem(item); } } return true; } bool ChatHandler::HandleSendItemsCommand(char* args) { // format: name "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] Player* receiver; ObjectGuid receiver_guid; std::string receiver_name; if (!ExtractPlayerTarget(&args, &receiver, &receiver_guid, &receiver_name)) { return false; } MailDraft draft; // fill mail if (!HandleSendItemsHelper(draft, args)) { return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); draft.SendMailTo(MailReceiver(receiver, receiver_guid), sender); std::string nameLink = playerLink(receiver_name); PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } bool ChatHandler::HandleSendMassItemsCommand(char* args) { // format: racemask "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] uint32 raceMask = 0; char const* name = NULL; if (!ExtractRaceMask(&args, raceMask, &name)) { return false; } // need dynamic object because it trasfered to mass mailer MailDraft* draft = new MailDraft; // fill mail if (!HandleSendItemsHelper(*draft, args)) { delete draft; return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); sMassMailMgr.AddMassMailTask(draft, sender, raceMask); PSendSysMessage(LANG_MAIL_SENT, name); return true; } bool ChatHandler::HandleSendMoneyHelper(MailDraft& draft, char* args) { /// format: "subject text" "mail text" money char* msgSubject = ExtractQuotedArg(&args); if (!msgSubject) { return false; } char* msgText = ExtractQuotedArg(&args); if (!msgText) { return false; } uint32 money; if (!ExtractUInt32(&args, money)) { return false; } if (money <= 0) { return false; } // msgSubject, msgText isn't NUL after prev. check draft.SetSubjectAndBody(msgSubject, msgText).SetMoney(money); return true; } bool ChatHandler::HandleSendMoneyCommand(char* args) { /// format: name "subject text" "mail text" money Player* receiver; ObjectGuid receiver_guid; std::string receiver_name; if (!ExtractPlayerTarget(&args, &receiver, &receiver_guid, &receiver_name)) { return false; } MailDraft draft; // fill mail if (!HandleSendMoneyHelper(draft, args)) { return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); draft.SendMailTo(MailReceiver(receiver, receiver_guid), sender); std::string nameLink = playerLink(receiver_name); PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } bool ChatHandler::HandleSendMassMoneyCommand(char* args) { /// format: raceMask "subject text" "mail text" money uint32 raceMask = 0; char const* name = NULL; if (!ExtractRaceMask(&args, raceMask, &name)) { return false; } // need dynamic object because it trasfered to mass mailer MailDraft* draft = new MailDraft; // fill mail if (!HandleSendMoneyHelper(*draft, args)) { delete draft; return false; } // from console show nonexistent sender MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM); sMassMailMgr.AddMassMailTask(draft, sender, raceMask); PSendSysMessage(LANG_MAIL_SENT, name); return true; } /// Send a message to a player in game bool ChatHandler::HandleSendMessageCommand(char* args) { ///- Find the player Player* rPlayer; if (!ExtractPlayerTarget(&args, &rPlayer)) { return false; } ///- message if (!*args) { return false; } WorldSession* rPlayerSession = rPlayer->GetSession(); ///- Check that he is not logging out. if (rPlayerSession->isLogingOut()) { SendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } ///- Send the message // Use SendAreaTriggerMessage for fastest delivery. rPlayerSession->SendAreaTriggerMessage("%s", args); rPlayerSession->SendAreaTriggerMessage("|cffff0000[Message from administrator]:|r"); // Confirmation message std::string nameLink = GetNameLink(rPlayer); PSendSysMessage(LANG_SENDMESSAGE, nameLink.c_str(), args); return true; } bool ChatHandler::HandleFlushArenaPointsCommand(char* /*args*/) { sBattleGroundMgr.DistributeArenaPoints(); return true; } bool ChatHandler::HandleModifyGenderCommand(char* args) { if (!*args) { return false; } Player* player = getSelectedPlayer(); if (!player) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } PlayerInfo const* info = sObjectMgr.GetPlayerInfo(player->getRace(), player->getClass()); if (!info) { return false; } char* gender_str = args; int gender_len = strlen(gender_str); Gender gender; if (!strncmp(gender_str, "male", gender_len)) // MALE { if (player->getGender() == GENDER_MALE) { return true; } gender = GENDER_MALE; } else if (!strncmp(gender_str, "female", gender_len)) // FEMALE { if (player->getGender() == GENDER_FEMALE) { return true; } gender = GENDER_FEMALE; } else { SendSysMessage(LANG_MUST_MALE_OR_FEMALE); SetSentErrorMessage(true); return false; } // Set gender player->SetByteValue(UNIT_FIELD_BYTES_0, 2, gender); player->SetUInt16Value(PLAYER_BYTES_3, 0, uint16(gender) | (player->GetDrunkValue() & 0xFFFE)); // Change display ID player->InitDisplayIds(); char const* gender_full = gender ? "female" : "male"; PSendSysMessage(LANG_YOU_CHANGE_GENDER, player->GetName(), gender_full); if (needReportToTarget(player)) { ChatHandler(player).PSendSysMessage(LANG_YOUR_GENDER_CHANGED, gender_full, GetNameLink().c_str()); } return true; } bool ChatHandler::HandleShowGearScoreCommand(char* args) { Player* player = getSelectedPlayer(); if (!player) { PSendSysMessage(LANG_PLAYER_NOT_FOUND); SetSentErrorMessage(true); return false; } uint32 withBags, withBank; if (!ExtractOptUInt32(&args, withBags, 1)) return false; if (!ExtractOptUInt32(&args, withBank, 0)) return false; // always recalculate gear score for display player->ResetCachedGearScore(); uint32 gearScore = player->GetEquipGearScore(withBags != 0, withBank != 0); PSendSysMessage(LANG_GEARSCORE, GetNameLink(player).c_str(), gearScore); return true; } bool ChatHandler::HandleMmap(char* args) { bool on; if (ExtractOnOff(&args, on)) { if (on) { sWorld.setConfig(CONFIG_BOOL_MMAP_ENABLED, true); SendSysMessage("WORLD: mmaps are now ENABLED (individual map settings still in effect)"); } else { sWorld.setConfig(CONFIG_BOOL_MMAP_ENABLED, false); SendSysMessage("WORLD: mmaps are now DISABLED"); } return true; } on = sWorld.getConfig(CONFIG_BOOL_MMAP_ENABLED); PSendSysMessage("mmaps are %sabled", on ? "en" : "dis"); return true; } bool ChatHandler::HandleMmapTestArea(char* args) { float radius = 40.0f; ExtractFloat(&args, radius); std::list<Creature*> creatureList; MaNGOS::AnyUnitInObjectRangeCheck go_check(m_session->GetPlayer(), radius); MaNGOS::CreatureListSearcher<MaNGOS::AnyUnitInObjectRangeCheck> go_search(creatureList, go_check); // Get Creatures Cell::VisitGridObjects(m_session->GetPlayer(), go_search, radius); if (!creatureList.empty()) { PSendSysMessage("Found " SIZEFMTD " Creatures.", creatureList.size()); uint32 paths = 0; uint32 uStartTime = WorldTimer::getMSTime(); float gx, gy, gz; m_session->GetPlayer()->GetPosition(gx, gy, gz); for (std::list<Creature*>::iterator itr = creatureList.begin(); itr != creatureList.end(); ++itr) { PathFinder path(*itr); path.calculate(gx, gy, gz); ++paths; } uint32 uPathLoadTime = WorldTimer::getMSTimeDiff(uStartTime, WorldTimer::getMSTime()); PSendSysMessage("Generated %i paths in %i ms", paths, uPathLoadTime); } else { PSendSysMessage("No creatures in %f yard range.", radius); } return true; } // use ".mmap testheight 10" selecting any creature/player bool ChatHandler::HandleMmapTestHeight(char* args) { float radius = 0.0f; ExtractFloat(&args, radius); if (radius > 40.0f) radius = 40.0f; Unit* unit = getSelectedUnit(); Player* player = m_session->GetPlayer(); if (!unit) unit = player; if (unit->GetTypeId() == TYPEID_UNIT) { if (radius < 0.1f) radius = static_cast<Creature*>(unit)->GetRespawnRadius(); } else { if (unit->GetTypeId() != TYPEID_PLAYER) { PSendSysMessage(LANG_SELECT_CHAR_OR_CREATURE); return false; } } if (radius < 0.1f) { PSendSysMessage("Provided spawn radius for %s is too small. Using 5.0f instead.", unit->GetGuidStr().c_str()); radius = 5.0f; } float gx, gy, gz; unit->GetPosition(gx, gy, gz); Creature* summoned = unit->SummonCreature(VISUAL_WAYPOINT, gx, gy, gz + 0.5f, 0, TEMPSUMMON_TIMED_DESPAWN, 20000); summoned->CastSpell(summoned, 8599, false); uint32 tries = 1; uint32 successes = 0; uint32 startTime = WorldTimer::getMSTime(); for (; tries < 500; ++tries) { unit->GetPosition(gx, gy, gz); if (unit->GetMap()->GetReachableRandomPosition(unit, gx, gy, gz, radius)) { unit->SummonCreature(VISUAL_WAYPOINT, gx, gy, gz, 0, TEMPSUMMON_TIMED_DESPAWN, 15000); ++successes; if (successes >= 100) break; } } uint32 genTime = WorldTimer::getMSTimeDiff(startTime, WorldTimer::getMSTime()); PSendSysMessage("Generated %u valid points for %u try in %ums.", successes, tries, genTime); return true; } bool ChatHandler::HandleServerResetAllRaidCommand(char* args) { PSendSysMessage("Global raid instances reset, all players in raid instances will be teleported to homebind!"); sMapPersistentStateMgr.GetScheduler().ResetAllRaid(); return true; }
220,487
75,625
#include <oni-core/graphic/oni-graphic-renderer-ogl-quad.h> #include <cassert> #include <GL/glew.h> #include <oni-core/graphic/buffer/oni-graphic-buffer-data.h> #include <oni-core/graphic/buffer/oni-graphic-index-buffer.h> #include <oni-core/graphic/buffer/oni-graphic-frame-buffer.h> #include <oni-core/graphic/buffer/oni-graphic-vertex-array.h> #include <oni-core/graphic/oni-graphic-shader.h> #include <oni-core/component/oni-component-geometry.h> #include <oni-core/component/oni-component-visual.h> #include <oni-core/math/oni-math-function.h> namespace oni { Renderer_OpenGL_Quad::Renderer_OpenGL_Quad(oniGLsizei maxPrimitiveCount, TextureManager &tm) : Renderer_OpenGL(PrimitiveType::TRIANGLES, tm), mMaxPrimitiveCount(maxPrimitiveCount) { mMaxIndicesCount = mMaxPrimitiveCount * 6; oniGLsizei vertexSize = sizeof(QuadVertex); oniGLsizei primitiveSize = vertexSize * 4; assert(mMaxIndicesCount < std::numeric_limits<i32>::max()); oniGLsizei maxBufferSize{primitiveSize * mMaxPrimitiveCount}; auto vertShader = std::string_view("oni-resources/shaders/quad.vert"); auto geomShader = std::string_view(""); auto fragShader = std::string_view("oni-resources/shaders/quad.frag"); mShader = std::make_unique<Shader>(vertShader, geomShader, fragShader); auto program = mShader->getProgram(); auto positionIndex = glGetAttribLocation(program, "position"); auto colorIndex = glGetAttribLocation(program, "color"); auto uvIndex = glGetAttribLocation(program, "uv"); auto samplerFrontIndex = glGetAttribLocation(program, "samplerFront"); auto samplerBackIndex = glGetAttribLocation(program, "samplerBack"); if (positionIndex == -1 || uvIndex == -1 || colorIndex == -1 || samplerFrontIndex == -1 || samplerBackIndex == -1) { assert(false); } BufferStructure samplerFront; samplerFront.index = static_cast<oniGLuint>(samplerFrontIndex); samplerFront.componentCount = 1; samplerFront.componentType = GL_FLOAT; samplerFront.normalized = GL_FALSE; samplerFront.stride = vertexSize; samplerFront.offset = static_cast<const oniGLvoid *>(nullptr); BufferStructure samplerBack; samplerBack.index = static_cast<oniGLuint>(samplerBackIndex); samplerBack.componentCount = 1; samplerBack.componentType = GL_FLOAT; samplerBack.normalized = GL_FALSE; samplerBack.stride = vertexSize; samplerBack.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, samplerBack)); BufferStructure color; color.index = static_cast<oniGLuint>(colorIndex); color.componentCount = 4; color.componentType = GL_FLOAT; color.normalized = GL_TRUE; color.stride = vertexSize; color.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, color)); BufferStructure uv; uv.index = static_cast<oniGLuint>(uvIndex); uv.componentCount = 2; uv.componentType = GL_FLOAT; uv.normalized = GL_TRUE; uv.stride = vertexSize; uv.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, uv)); BufferStructure position; position.index = static_cast<oniGLuint>(positionIndex); position.componentCount = 3; position.componentType = GL_FLOAT; position.normalized = GL_FALSE; position.stride = vertexSize; position.offset = reinterpret_cast<const oniGLvoid *>(offsetof(QuadVertex, pos)); std::vector<BufferStructure> bufferStructures; bufferStructures.push_back(samplerFront); bufferStructures.push_back(samplerBack); bufferStructures.push_back(color); bufferStructures.push_back(uv); bufferStructures.push_back(position); mVertexArray = std::make_unique<VertexArray>(bufferStructures, maxBufferSize); if (mMaxIndicesCount > mMaxPrimitiveCount) { mIndexBuffer = std::make_unique<IndexBuffer>(mMaxIndicesCount); } std::vector<GLint> samplers; for (i8 i = 0; i < mMaxNumTextureSamplers; ++i) { samplers.push_back(i); } mShader->enable(); mShader->setUniformiv("samplers", samplers); mShader->disable(); } Renderer_OpenGL_Quad::~Renderer_OpenGL_Quad() = default; void Renderer_OpenGL_Quad::submit(const Quad &quad, const Color &color, const Texture *texture) { assert(mIndexCount + 6 < mMaxIndicesCount); auto buffer = static_cast<QuadVertex *>(mBuffer); auto samplerFront = -1.f; auto samplerBack = -1.f; auto uv0 = vec2{}; auto uv1 = vec2{}; auto uv2 = vec2{}; auto uv3 = vec2{}; if (texture) { samplerFront = getSamplerID(texture->id); uv0 = texture->uv.values[0]; uv1 = texture->uv.values[1]; uv2 = texture->uv.values[2]; uv3 = texture->uv.values[3]; } auto c = color.rgba(); // a. buffer->pos = quad.a.value; buffer->color = c; buffer->uv = uv0; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // b. buffer->pos = quad.b.value; buffer->color = c; buffer->uv = uv1; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // c. buffer->pos = quad.c.value; buffer->color = c; buffer->uv = uv2; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // d. buffer->pos = quad.d.value; buffer->color = c; buffer->uv = uv3; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; // Update the mBuffer to point to the head. mBuffer = static_cast<void *>(buffer); // +6 as there are 6 vertices that makes up two adjacent triangles but those triangles are // defined by 4 vertices only. /** * 1 +---+ 2 * | /| * |/ | * 0 +---+ 3 **/ mIndexCount += 6; } void Renderer_OpenGL_Quad::submit(const Quad &quad, const Color &color, const Texture &front, const Texture &back) { assert(mIndexCount + 6 < mMaxIndicesCount); assert(front.id); assert(back.id); assert(almost_Equal(front.uv.values[0].x, back.uv.values[0].x)); assert(almost_Equal(front.uv.values[1].x, back.uv.values[1].x)); assert(almost_Equal(front.uv.values[2].x, back.uv.values[2].x)); assert(almost_Equal(front.uv.values[3].x, back.uv.values[3].x)); assert(almost_Equal(front.uv.values[0].y, back.uv.values[0].y)); assert(almost_Equal(front.uv.values[1].y, back.uv.values[1].y)); assert(almost_Equal(front.uv.values[2].y, back.uv.values[2].y)); assert(almost_Equal(front.uv.values[3].y, back.uv.values[3].y)); auto buffer = static_cast<QuadVertex *>(mBuffer); auto samplerFront = getSamplerID(front.id); auto samplerBack = getSamplerID(back.id); auto c = color.rgba(); buffer->pos = quad.a.value; buffer->color = c; buffer->uv = front.uv.values[0]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; buffer->pos = quad.b.value; buffer->color = c; buffer->uv = front.uv.values[1]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; buffer->pos = quad.c.value; buffer->color = c; buffer->uv = front.uv.values[2]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; buffer->pos = quad.d.value; buffer->color = c; buffer->uv = front.uv.values[3]; buffer->samplerFront = samplerFront; buffer->samplerBack = samplerBack; ++buffer; mBuffer = static_cast<void *>(buffer); mIndexCount += 6; } void Renderer_OpenGL_Quad::submit(const Renderable &renderable) { // TODO: Implement assert(false); } void Renderer_OpenGL_Quad::enableShader(const RenderSpec &spec) { mShader->enable(); mShader->setUniformMat4("model", spec.model); mShader->setUniformMat4("view", spec.view); mShader->setUniformMat4("proj", spec.proj); } oniGLsizei Renderer_OpenGL_Quad::getIndexCount() { return mIndexCount; } void Renderer_OpenGL_Quad::resetIndexCount() { mIndexCount = 0; } }
9,255
2,923
#include <cstdlib> #include <cstdint> #include <string> #include <vector> #include <chrono> #include <ctime> #include <fstream> #include <unistd.h> #include <sys/reboot.h> #include "powercycle.hpp" Powercycle::Powercycle(const uint32_t& wakeupTime) : wakeupTime_(wakeupTime) { execute(); } void Powercycle::execute() { invokeRTC(); shutdown(); } void Powercycle::invokeRTC() { time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::ofstream rtcStream; rtcStream.open(RTC_WAKEALARM); rtcStream << time(&currentTime) + (wakeupTime_ * SECONDS); rtcStream.close(); } /* using reboot(2) to shutdown immediately, see man reboot(2) */ void Powercycle::shutdown() { reboot(RB_POWER_OFF); }
760
302
/**************************************************************************** ** $Id$ ** ** Copyright (C) 2001-2006 Trolltech AS. All rights reserved. ** ** This file is part of the Qt Script for Applications framework (QSA). ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding a valid Qt Script for Applications license may use ** this file in accordance with the Qt Script for Applications License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for ** information about QSA Commercial License Agreements. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** *****************************************************************************/ #include "qsclass.h" #include "qsenv.h" #include "qsoperations.h" #include "qstypes.h" #include "qsnodes.h" #include "qsfuncref.h" #include <stdlib.h> #if defined(Q_OS_WIN32) #include <qt_windows.h> #endif using namespace QS; QSClass::QSClass( QSEnv *e, int a ) : en( e ), bclass( 0 ), encClass( 0 ), attrs( a ) { Q_ASSERT( e ); init(); } QSClass::QSClass( QSClass *b, int a ) : bclass( b ), encClass( 0 ), attrs( a ) { Q_ASSERT( b && b->env() ); en = b->env(); init(); } QSClass::~QSClass() { } void QSClass::clear() { for (QSMemberMap::ConstIterator it = mmap->begin(); it!=mmap->end(); ++it) { if ((*it).type() == QSMember::ScriptFunction) { if ((*it).scriptFunction->deref()) { delete (*it).scriptFunction; } } } delete mmap; mmap = 0; staticMembers.clear(); } void QSClass::init() { mmap = new QSMemberMap(); numVars = base() ? base()->numVariables() : 0; numStaticVars = 0; en->registerClass( this ); } /*! Checks if the two objects are equal. Returns positive if equal, 0 if not equal and negative if the class is unable to determine. */ QSEqualsResult QSClass::isEqual( const QSObject &a, const QSObject &/*b*/ ) const { Q_ASSERT( a.isA( this ) ); // qDebug( "QSClass::isEqual( %s, %s )", // a.typeName().ascii(), b.typeName().ascii() ); return EqualsUndefined; } /*! Checks if two objects are strictly equal, meaning that they are exactly the same object. */ QSEqualsResult QSClass::isStrictEqual( const QSObject &a, const QSObject &b ) const { Q_ASSERT( a.isA( this ) ); if ( a.objectType() != b.objectType() ) return EqualsNotEqual; if ( a.isUndefined() || a.isNull() ) return EqualsIsEqual; if ( a.isNumber() ) { double doubA = a.toNumber(); if ( isNaN( doubA ) ) return EqualsNotEqual; double doubB = b.toNumber(); if ( isNaN( doubB ) ) return EqualsNotEqual; if ( doubA == doubB || ( doubA==0 && doubB==-0 ) || ( doubA==-0 && doubB==0 ) ) return EqualsIsEqual; return EqualsNotEqual; } else if ( a.isString() ) { return (QSEqualsResult) (a.toString() == b.toString() || (a.sVal().isEmpty() && b.sVal().isEmpty())); } else if ( a.isBoolean() ) { return ( QSEqualsResult ) ( a.toBoolean() == b.toBoolean() ); } return ( QSEqualsResult ) ( a.shVal() == b.shVal() ); } QSCompareResult QSClass::compare( const QSObject &a, const QSObject &b ) const { // qDebug( "\nQSClass::compare" ); // qDebug( "a: %s\nb: %s", a.toString().latin1(), b.toString().latin1() ); QSObject primA = a.toPrimitive( env()->numberClass() ); QSObject primB = b.toPrimitive( env()->numberClass() ); if( primA.isString() && primB.isString() ) { QString strA = primA.toString(); QString strB = primB.toString(); if (strA.isEmpty() && strB.isEmpty()) return CompareEqual; int ret = QString::compare(strA, strB); if( ret==0 ) return CompareEqual; else if( ret<0 ) return CompareLess; else return CompareGreater; } double doubA = primA.toNumber(); double doubB = primB.toNumber(); // qDebug( "a=%f, b=%f", doubA, doubB ); if( isNaN( doubA ) || isNaN( doubB ) ) { return CompareUndefined; } // ### +0 vs -0 cases... if( doubA==doubB ) { return CompareEqual; } else if( doubA < doubB ) { return CompareLess; } else { return CompareGreater; } return CompareUndefined; } void QSClass::finalize() { #if 0 // ### required to avoid double deletions QSObjectList::iterator it = staticMembers.begin(); QSObjectList::iterator end = staticMembers.end(); while ( it != end ) { (*it).invalidate(); ++it; } #else staticMembers.clear(); #endif for (QSMemberMap::ConstIterator it = mmap->begin(); it!=mmap->end(); ++it) if ((*it).type() == QSMember::ScriptFunction) { if ((*it).scriptFunction->scopeDefinition()) (*it).scriptFunction->scopeDefinition()->setFunctionBodyNode(0); (*it).scriptFunction->setScopeDefinition(0); } } QSClassClass* QSClass::asClass() const { return name() == QString::fromLatin1("Class") ? (QSClassClass*)this : 0; } QSObject QSClass::execute( const QSObject *, QSObject *, const QSList & ) const { throwError( TypeError, QString::fromLatin1("Cannot invoke objects of type %1 as function").arg(name()) ); return createUndefined(); } /*! Returns TRUE if this class is a subclass of \c; FALSE otherwise. A class is defined to be a subclass of itself. */ bool QSClass::inherits( const QSClass *c ) const { const QSClass *b = this; while ( b && b != c ) b = b->base(); return b == c; } /*! * Mark \a o and its sub-properties as referenced. This is used * for the mark & sweep garbage collection. * * The default implementation does nothing but you should reimplement * this function if objects of this class contain other objects * or references to them. */ void QSClass::mark( QSObject * /*o*/ ) const { // do nothing } void QSClass::ref( QSObject * /*o*/ ) const { } void QSClass::deref( QSObject * /*o*/ ) const { } /*! * Returns \a obj converted to a boolean value. * * The default implementation returns TRUE. */ bool QSClass::toBoolean( const QSObject * /*obj*/ ) const { return TRUE; } /*! * Return \a obj converted to a floating point number; NaN if * the conversion failed. * * The default implementation returns NaN. */ double QSClass::toNumber( const QSObject * ) const { return NaN; } /*! * Return \a obj converted to a string. * * The default implementation returns "[object N]" where N is * the name of this class as retrieved by name(). */ QString QSClass::toString( const QSObject * ) const { return QString::fromLatin1("[object ") + name() + QString::fromLatin1("]"); } QSObject QSClass::toPrimitive( const QSObject *obj, const QSClass *preferred ) const { if( preferred != env()->numberClass() ) return createString( toString( obj ) ); else return createNumber( toNumber( obj ) ); } /*! Convert \a obj to an equivalent QVariant. The default implementation returns in invalid QVariant which may also be the case where no mapping for an equivalent type exists. */ QVariant QSClass::toVariant( const QSObject * /*obj*/, QVariant::Type ) const { // ### how about respecting the prefered type ? return QVariant(); } #if QS_MAX_STACK>0 static int debugStringRecursionDepth = 0; #endif QString QSClass::debugString( const QSObject *obj ) const { #if QS_MAX_STACK>0 if( ++debugStringRecursionDepth==QS_MAX_STACK ) { Q_ASSERT( obj->isValid() ); obj->env()->throwError( RangeError, QString::fromLatin1("Internal recursion level maxed out in: " "QSArrayClass::joinInternal"), -1 ); --debugStringRecursionDepth; return QString::null; } #endif QString retVal = QString::null; if ( obj->isPrimitive() ) { retVal = toString( obj ) + QString::fromLatin1(":") + name(); } else { QSMemberMap m = members( obj ); if ( m.isEmpty() ) { retVal = toString( obj ) + QString::fromLatin1(":") + name(); } else { QSMemberMap::ConstIterator it = m.begin(); retVal = "{"; for ( ;; ) { QSObject p = env()->resolveValue( it.key() ); if ( !p.isValid() ) { // ### should never happen (but sometimes does) ++it; if ( it == m.end() ) break; else continue; } retVal += it.key() + QString::fromLatin1("=") + p.debugString(); ++it; if ( it == m.end() ) break; else retVal += QString::fromLatin1(","); } retVal += QString::fromLatin1("}:") + identifier(); } } #if QS_MAX_STACK>0 --debugStringRecursionDepth; #endif return retVal; } bool QSClass::deleteProperty( QSObject *, const QSMember & ) const { return FALSE; } /*! Retrieves a pointer to the class member \a n; 0 if no such member exists. */ bool QSClass::member( const QSObject *, const QString &n, QSMember *m ) const { // qDebug( "QSClass::member() class = %s, name = %s", name().latin1(), n.latin1() ); Q_ASSERT( !n.isEmpty() ); Q_ASSERT( m ); Q_ASSERT( mmap ); QSMemberMap::Iterator it = mmap->find( n ); if( it == mmap->end() ) { return FALSE; } else { *m = it.data(); return TRUE; } } QSObject QSClass::fetchValue( const QSObject *objPtr, const QSMember &mem ) const { // qDebug( "fetching from: " + identifier() + ", " + mem ); if( !mem.isReadable() ) { qDebug( "QSClass:fetchValue() - not readable: %s", mem.name().latin1() ); return createUndefined(); } if( mem.type()==QSMember::Variable ) { if ( !mem.isStatic() ) { QSInstanceData *data = (QSInstanceData*)objPtr->shVal(); if ( mem.idx >= data->size() ) { // ### could throw error in member() // qWarning( "QSClass::fetchValue: non-resized array access" ); return createUndefined(); } QSObject * ptr = data->value( mem.idx ); if ( !ptr->isValid() ) { // qWarning( "QSMember::fetch: Accessed uninitialized variable" ); return createUndefined(); } return *ptr; } else { return staticMember( mem.idx ); } } else if ( mem.isExecutable() ) { return env()->funcRefClass()->createReference( *objPtr, mem ); } return createUndefined(); } void QSClass::write( QSObject *objPtr, const QSMember &mem, const QSObject &val ) const { Q_ASSERT( mem.isWritable() ); if (mem.type() != QSMember::Variable) { env()->throwError(ReferenceError, QString::fromLatin1("Member '%1' cannot be overwritten in '%2'") .arg(mem.name()).arg(name())); return; } if ( mem.isWritable() && mem.type()==QSMember::Variable ) { if ( !mem.isStatic() ) { QSInstanceData *data = (QSInstanceData*)objPtr->shVal(); if ( mem.idx >= data->size() ) { qWarning( "QSClass::write(), index=%d greater than array size=%d", mem.idx, data->size() ); // ### could throw error in member() return; } data->setValue( mem.idx, val ); } else { QSClass * cl = (QSClass*) this; cl->setStaticMember( mem.idx, val ); } } } /*! Only use for objPtr's that absolutly have QSInstanceData */ void QSClass::write( QSObject * objPtr, int index, const QSObject &val ) const { QSInstanceData *idata = (QSInstanceData*)objPtr->shVal(); idata->setValue( index, val ); } void QSClass::setStaticMember( int idx, const QSObject &val ) { Q_ASSERT( idx>=0 && idx<numStaticVars ); staticMembers[idx] = val; } QSObject QSClass::staticMember( int idx ) const { Q_ASSERT( idx>=0 && idx<numStaticVars ); return staticMembers[idx]; } static bool compareScopes( const QSObject &a, const QSObject &b ) { return a.objectType()==b.objectType() && a.shVal()==b.shVal(); } QSObject QSClass::invoke( QSObject * objPtr, const QSMember &mem ) const { Q_ASSERT( mem.isExecutable() ); Q_ASSERT( objPtr->objectType() == this ); switch( mem.type() ) { case QSMember::NativeFunction: return (*mem.nativeFunction)( env() ); case QSMember::NativeVoidFunction: (*mem.nativeVoidFunction)( env() ); return createUndefined(); case QSMember::NativeMemberFunction: Q_ASSERT( !mem.isStatic() ); qWarning( "This should never be called!!" ); return createUndefined(); case QSMember::ScriptFunction: { Q_ASSERT( mem.scriptFunction ); const QSList *args = env()->arguments(); #ifdef QSDEBUGGER Debugger *dbg = env()->engine()->debugger(); // arguments as string for call stack info QString argStr = QString::fromLatin1(""); for ( int j = 0; j < args->size(); j++ ) { if ( j > 0 ) argStr += QString::fromLatin1(", "); QSObject a = args->at( j ); argStr += a.toString() + QString::fromLatin1(" : ") + a.typeName(); } QString n = mem.scriptFunction->scopeDefinition()->identifier(); if( dbg ) dbg->callEvent( n, argStr ); // debugger has to be told that we are potentially // jumping to script code in a different source unit int oldSourceId = -1; if ( dbg ) { oldSourceId = dbg->sourceId(); dbg->setSourceId( mem.scriptFunction->sourceId() ); } #endif QSFunctionScopeClass *scopeDef = mem.scriptFunction->scopeDefinition(); // qDebug( "Calling function: " + scopeDef->identifier() ); // qDebug( "objPtr is: " + objPtr->objectType()->identifier() ); // qDebug( "currentScope is: " + env()->currentScope().objectType()->identifier() ); // env()->printScopeChain(); // Use invalid object for scopes that don't have variables.. QSObject scope = scopeDef->construct( *args ); QSObject returnValue; if ( compareScopes( *objPtr, env()->currentScope() ) ) { // qDebug( "Push scope type 1" ); env()->pushScope( scope ); returnValue = mem.scriptFunction->execute( env() ); env()->popScope(); } else if( objPtr->objectType()->enclosingClass()==env()->currentScope().objectType() ) { // qDebug( "Push scope type 1b" ); env()->pushScope( *objPtr ); env()->pushScope( scope ); returnValue = mem.scriptFunction->execute( env() ); env()->popScope(); env()->popScope(); } else if ( objPtr->objectType()->enclosingClass() == 0 ) { // qDebug( "Push scope type 1c" ); env()->pushScopeBlock(); env()->pushScope( env()->globalObject() ); env()->pushScope( *objPtr ); env()->pushScope( scope ); // env()->printScopeChain(); returnValue = mem.scriptFunction->execute( env() ); env()->popScopeBlock(); } else if ( env()->currentScope().objectType() == env()->globalObject().objectType() ) { // object has an enclosing class, but current scope is only global // qDebug( "Push scope type 1d" ); env()->pushScopeBlock(); env()->pushScope( env()->globalObject() ); env()->pushScope( *objPtr ); env()->pushScope( scope ); returnValue = mem.scriptFunction->execute( env() ); env()->popScopeBlock(); } else { // qDebug( "Push scope type 2" ); // ### This loop is a duplicate of the one already done in resolvenode ScopeChain chain = env()->scope(); ScopeChain::Iterator it = chain.begin(); bool pushObj = FALSE; while( it!=chain.end() ) { if( compareScopes( *it, *objPtr ) ) { break; } else if ( (*it).objectType() == objPtr->objectType()->enclosingClass() ) { pushObj = TRUE; break; } else { it = chain.remove( it ); } } env()->pushScopeBlock(); while( chain.size()>0 ) { env()->pushScope( chain.back() ); chain.pop_back(); } if( pushObj ) env()->pushScope( *objPtr ); env()->pushScope( scope ); // env()->printScopeChain(); returnValue = mem.scriptFunction->execute( env() ); env()->popScopeBlock(); } #ifdef QSDEBUGGER if ( dbg ) dbg->returnEvent(); // restore previous source id if (dbg) dbg->setSourceId(oldSourceId); #endif return env()->isReturnValueMode() ? returnValue : createUndefined(); } case QSMember::Variable: { QSObject o = fetchValue( objPtr, mem ); if ( o.objectType()->valueType() == TypeClass ) return QSTypeClass::classValue(&o)->cast( *env()->arguments() ); qFatal( "QSClass::invoke: Unhandled variable type" ); break; } default: qFatal( "QSClass::invoke: Unhandled switch case %d", mem.type() ); } return createUndefined(); } void QSClass::addFunctionMember( const QString &n, QSFunctionBodyNode * f, int attributes ) { addMember( n, QSMember( f, attributes ), createUndefined() ); } int QSClass::addVariableMember( const QString &n, int attributes ) { addMember( n, QSMember( QSMember::Variable, attributes ), createUndefined() ); return attributes & AttributeStatic ? numStaticVars - 1 : numVars-1; } void QSClass::addStaticVariableMember( const QString &name, const QSObject &value, int attr ) { addMember( name, QSMember( QSMember::Variable, attr | AttributeStatic ), value ); } /*! Add member \a member with name \a n to this class. \stVal contains the value if the member is a static variable. */ void QSClass::addMember( const QString &n, const QSMember &member, const QSObject &stVal ) { Q_ASSERT( !mmap->contains( n ) ); QSMember m = member; m.setName( n ); m.setOwner( this ); switch (m.type()) { case QSMember::Variable: if( m.isStatic() ) { m.setIndex( numStaticVars++ ); staticMembers.append( stVal ); } else { m.setIndex( numVars++ ); } break; case QSMember::ScriptFunction: m.scriptFunction->ref(); // Since it is stored by member. break; default: break; } mmap->insert( n, m ); } /* Factored out from replace member */ void QSClass::removeStaticVar( const QSMember &old ) { staticMembers.remove( staticMembers.at(old.idx) ); QSMemberMap::iterator it = mmap->begin(); while( it!=mmap->end() ) { QSMember &cur = *it; if( cur.type()==QSMember::Variable && cur.isStatic() && cur.idx>old.idx ) cur.idx--; it++; } numStaticVars--; } /* Factored out from replaceMember */ void QSClass::fillMemberVarIndex( QSMember *member ) { if( !replacedVars.isEmpty() ) { // Reuse old varspace if possible. member->idx = replacedVars[0]; replacedVars.pop_front(); } else { member->idx = numVars++; } } /*! Replaces the member \name with \member. \stVal can contain the value if the member is a static variable. */ void QSClass::replaceMember( const QString &name, QSMember *member, const QSObject &stVal ) { // qDebug( "QSClass::replaceMember(%s)", name.latin1() ); Q_ASSERT( mmap->contains( name ) ); QSMember old = *(mmap->find( name )); QSMember &m = *member; m.setName( name ); m.setOwner( this ); // Delete old function implementation. if (old.type() == QSMember::ScriptFunction) { if (old.scriptFunction->deref()) { // will delete delete old.scriptFunction; old.scriptFunction = 0; } else { if (old.scriptFunction->scopeDefinition()) old.scriptFunction->setScopeDefinition(0); old.scriptFunction->setScopeDefinition(0); } } // Ref new one... if (m.type() == QSMember::ScriptFunction) m.scriptFunction->ref(); if( old.type()==QSMember::Variable && m.type()==QSMember::Variable ) { if( old.isStatic() == m.isStatic() ) { // both static or both nonstatic m.idx = old.idx; if( old.isStatic() ) // replace value if static staticMembers[m.idx] = stVal; } else if( old.isStatic() ) { removeStaticVar( old ); fillMemberVarIndex( &m ); } else if( m.isStatic() ) { m.idx = numStaticVars++; staticMembers.append( stVal ); replacedVars.append( old.idx ); } } else if( (old.type()==QSMember::ScriptFunction || old.type()==QSMember::NativeFunction || old.type()==QSMember::NativeMemberFunction) && (m.type()==QSMember::ScriptFunction || m.type()==QSMember::NativeFunction || m.type()==QSMember::NativeMemberFunction) ) { // Replace only... } else if ( old.type()==QSMember::Variable ) { // Variable -> function if( old.isStatic() ) { // Delete and update member indexes removeStaticVar( old ); } else { // Store index for reuse later. replacedVars.append( old.idx ); } } else if ( m.type()==QSMember::Variable ) { if( m.isStatic() ) { m.idx = numStaticVars++; staticMembers.append( stVal ); } else { fillMemberVarIndex( &m ); } } else { qFatal( "QSClass::replaceMember() -- Unhandled case" ); } mmap->replace( name, m ); } /*! Deletes the member under name \name. If deletion was not possible, FALSE is returned */ bool QSClass::deleteMember( const QString &name ) { if( !mmap->contains( name ) ) { return FALSE; } // ### What do we do about variable indexes?? mmap->remove( name ); return TRUE; } bool QSClass::hasProperty( const QSObject *obj, const QString &p ) const { // standard class property ? QSMember m; if ( member( obj, p, &m ) && m.type() != QSMember::Identifier ) return TRUE; // // dynamic property // return data( obj )->hasProperty( p ); return FALSE; } QSObject QSClass::get( const QSObject *objPtr, const QString &p ) const { QSMember mem; if ( !member( objPtr, p, &mem ) || mem.type() == QSMember::Identifier ) return createUndefined(); return fetchValue( objPtr, mem ); } void QSClass::put( QSObject *objPtr, const QString &p, const QSObject &v ) const { QSMember mem; if ( !member( objPtr, p, &mem ) && mem.type() != QSMember::Identifier ) { qWarning( "QSClass::put: refused write of %s", p.ascii() ); return; } mem.setName( p ); write( objPtr, mem, v ); } QSObject QSClass::construct( const QSList & /* args */ ) const { return createUndefined(); } QSObject QSClass::cast( const QSList &args ) const { return args.size() > 0 ? args[0] : createUndefined() ; } /*! Returns the map of members of \a obj or class members if \a obj is 0. The default implementation will list all members pre-defined via the addMember() function or one of its specializations. Class inherting from QSClass can reimplement this function to also give information about custom properties. */ QSMemberMap QSClass::members( const QSObject *obj ) const { Q_ASSERT( mmap ); if ( obj ) return *mmap; QSMemberMap m; QSMemberMap::const_iterator it = mmap->begin(); for ( ; it != mmap->end(); ++it ) if ( (*it).isStatic() ) m.insert( it.key(), it.data() ); return m; } /*! Convenience function to throw an error of type \a a with the user visible message \a msg. */ void QSClass::throwError( ErrorType e, const QString &msg ) const { (void)env()->throwError( e, msg, -1 ); } QSObject QSClass::createString( const QString &s ) const { return en->createString( s ); } QSObject QSClass::createNumber( double d ) const { return en->createNumber( d ); } QSObject QSClass::createBoolean( bool b ) const { return en->createBoolean( b ); } QSObject QSClass::createUndefined() const { return en->createUndefined(); } QSObject QSClass::createNull() const { return en->createNull(); } bool QSUndefinedClass::toBoolean( const QSObject * ) const { return FALSE; } double QSUndefinedClass::toNumber( const QSObject * ) const { return NaN; } QString QSUndefinedClass::toString( const QSObject * ) const { return QString::fromLatin1("undefined"); } QSObject QSUndefinedClass::toPrimitive( const QSObject *obj, const QSClass * ) const { return *obj; } QSEqualsResult QSUndefinedClass::isEqual( const QSObject &a, const QSObject &b ) const { Q_ASSERT( a.isA( this ) ); if ( b.isUndefined() || b.isNull() ) return EqualsIsEqual; else return EqualsUndefined; } bool QSNullClass::toBoolean( const QSObject * ) const { return FALSE; } double QSNullClass::toNumber( const QSObject * ) const { return 0.0; } QString QSNullClass::toString( const QSObject * ) const { return QString::fromLatin1("null"); } QSObject QSNullClass::toPrimitive( const QSObject *obj, const QSClass * ) const { return *obj; } QSEqualsResult QSNullClass::isEqual( const QSObject &a, const QSObject &b ) const { Q_ASSERT( a.isA( this ) ); if( b.isNull() || b.isUndefined() ) return EqualsIsEqual; return EqualsUndefined; } bool QSCharacterClass::toBoolean( const QSObject *obj ) const { return !obj->sVal()[0].isNull(); } double QSCharacterClass::toNumber( const QSObject *obj ) const { return QSString::toDouble( obj->sVal() ); } QString QSCharacterClass::toString( const QSObject *obj ) const { return obj->sVal(); } void QSSharedClass::ref( QSObject * o ) const { #ifndef QS_LEAK o->shVal()->ref(); #endif } void QSSharedClass::deref( QSObject * o ) const { #ifndef QS_LEAK o->shVal()->deref(); if( o->shVal()->count==0 ) { env()->removeShared( o->shVal() ); delete o->shVal(); o->setVal( (QSShared*)0 ); // for debugging purposes only } #endif } QSClassClass::QSClassClass( QSClass *b, int a, const QString &n ) : QSSharedClass( b, a ), cname( n ), defaultCtor( FALSE ), bodyNode( 0 ), clDefNode(0) { memberInit = new QSNodeList(); staticInit = new QSNodeList(); } QSClassClass::~QSClassClass() { // If shut down, we cannot allow other classes to be deleted as this will // mess up the iterators calling finalize, clear and delete in QSEnv::clear(). if (env()->isShuttingDown()) { if (bodyNode->scopeDefinition()) bodyNode->scopeDefinition()->setFunctionBodyNode(0); bodyNode->setScopeDefinition(0); } clDefNode->setClassDefinition(0); if (clDefNode->deref()) { delete clDefNode; bodyNode = 0; clDefNode = 0; } delete memberInit; delete staticInit; } bool QSClassClass::toBoolean( const QSObject * ) const { return TRUE; } double QSClassClass::toNumber( const QSObject * ) const { return NaN; } QString QSClassClass::toString( const QSObject * ) const { return QString::fromLatin1("[class ") + cname + QString::fromLatin1("]"); } QSInstanceData* QSClassClass::data( QSObject *obj ) { return (QSInstanceData*)obj->shVal(); } const QSInstanceData* QSClassClass::data( const QSObject *obj ) { return (const QSInstanceData*)obj->shVal(); } /*! \reimp Construct an instance of the class described by this object. */ QSObject QSClassClass::construct( const QSList &args ) const { /* Look for non QSClassClass in parent chain. Can only be object class. If anything else, it must be a QSAbstractBaseClass, which is an error at this point. */ QSClass *baseChain = base(); while (baseChain && baseChain->asClass()) baseChain = baseChain->base(); if (baseChain && baseChain->name() == QString::fromLatin1("AbstractBase")) { return env()->throwError(QString(QString::fromLatin1("class '%1' is %2derived from undefined class '%3'")) .arg(cname) .arg(baseChain == base() ? QString::fromLatin1("") : QString::fromLatin1("indirectly ")) .arg(baseChain->identifier())); } // Initialize all entries to undefined QSInstanceData *data = new QSInstanceData( numVariables(), createUndefined() ); for( int i=0; i < numVariables(); i++ ) data->setValue( i, createUndefined() ); QSObject inst = env()->createShared( this, data ); // Set up scope ScopeChain chain = env()->scope(); ScopeChain::Iterator sit = chain.begin(); while( sit!=chain.end() ) { if( (*sit).objectType()==enclosingClass() ) { break; } sit = chain.remove( sit ); } // Fill up scope chain. env()->pushScopeBlock(); while( chain.size()>0 ) { env()->pushScope( chain.back() ); chain.pop_back(); } env()->pushScope( inst ); initVariables( data ); // Clean up scope env()->popScopeBlock(); if ( hasDefaultConstructor() && !env()->isExceptionMode() ) { QSObject ctor = get( &inst, cname ); Q_ASSERT( ctor.isExecutable() ); ctor.invoke( QSMember(), args ); // ### do something with the return value/type ? } return inst; } QSEqualsResult QSClassClass::isEqual( const QSObject &a, const QSObject &b ) const { if( b.objectType() == this ) { return ( QSEqualsResult ) ( b.shVal() == a.shVal() ); } return EqualsNotEqual; } void QSClassClass::addMemberInitializer( QSNode * node ) { memberInit->append( node ); } void QSClassClass::addStaticInitializer( QSNode * node ) { staticInit->append( node ); } void QSClassClass::setClassBodyNode( QSFunctionBodyNode * node ) { bodyNode = node; } /*! Execute statements contained in this class' block. */ void QSClassClass::executeBlock( QSEnv *env ) { // Set up scope ScopeChain chain = env->scope(); ScopeChain::Iterator sit = chain.begin(); while( sit!=chain.end() ) { if( (*sit).objectType()==enclosingClass() ) { break; } sit = chain.remove( sit ); } // Fill up scope chain. env->pushScopeBlock(); while( chain.size()>0 ) { env->pushScope( chain.back() ); chain.pop_back(); } // Push the type object... env->pushScope( env->globalObject().get(cname) ); // Call initializers QPtrListIterator<QSNode> it( *staticInit ); for ( uint j = 0; j<staticInit->count(); j++ ) { QSNode *init = it(); if ( init ) { setStaticMember( j, init->rhs( env ) ); // abort if init code caused an error if ( env->isExceptionMode() ) break; } } if( bodyNode ) bodyNode->execute( env ); // Clean up scope env->popScopeBlock(); } /*! \internal Runs the initializers on the variables declared in this class. This function assumes that scopes are set up correctly and can only be called from within the QSClassClass::construct function. */ int QSClassClass::initVariables( QSInstanceData * data ) const { int offset = 0; QSClassClass *cl = base() ? base()->asClass() : 0; if( cl ) offset = cl->initVariables( data ); // Call initializers QPtrListIterator<QSNode> it( *memberInit ); for ( uint j = 0; j<memberInit->count(); j++ ) { QSNode *init = it(); if ( init ) { data->setValue( offset + j, init->rhs( env() ) ); // abort if init code caused an error if ( env()->isExceptionMode() ) break; } } return offset + memberInit->count(); } /*! \reimp */ void QSWritableClass::mark( QSObject * /*o*/ ) const { } bool QSWritableClass::member( const QSObject *o, const QString &n, QSMember *m ) const { // qDebug( "QSWritableClass::member() class = %s, name = %s", name().latin1(), n.latin1() ); Q_ASSERT( /* o &&*/ !n.isEmpty() ); Q_ASSERT( m ); if( !o || !o->isDefined() ) { return QSClass::member( o, n, m ); } if( !o->shVal() ) { return QSClass::member( 0, n, m ); } // The error here is that the object is a dummy!!! const QSWritable *w = (QSWritable*) o->shVal(); //data( o ); if ( !w->hasProperty( n ) ) { if ( QSClass::member( o, n, m ) ) return TRUE; // property doesn't exit, yet. We'll offer to create a new one m->setType( QSMember::Identifier ); m->setName( n ); m->setOwner( this ); return FALSE; } m->setType( QSMember::Object ); m->obj = &w->reference( n )->object; m->setName( n ); m->setOwner( this ); return TRUE; } QSObject QSWritableClass::fetchValue( const QSObject *objPtr, const QSMember &mem ) const { // qDebug( "QSWritableClass::fetchValue() -> mem.type = %s", mem.typeName().latin1() ); if( mem.type()==QSMember::Object ) { return *mem.obj; } return QSClass::fetchValue( objPtr, mem ); } void QSWritableClass::write( QSObject *objPtr, const QSMember &mem, const QSObject &val ) const { // qDebug( "QSWritableClass::write() -> mem.type = %s", mem.typeName().latin1() ); if( mem.type()==QSMember::Object ) { *mem.obj = val; } else if( mem.type()==QSMember::Identifier ) { // qDebug( "Writing to QSMember::Identifier: name = %s", mem.str.latin1() ); data( objPtr )->setProperty( mem.name(), QSProperty( val ) ); } else { QSClass::write( objPtr, mem, val ); } } bool QSWritableClass::deleteProperty( QSObject *obj, const QSMember &mem ) const { if ( mem.type()==QSMember::Object ) { properties( obj )->remove( mem.name() ); return TRUE; } return FALSE; } QSObject QSWritableClass::invoke( QSObject * objPtr, const QSMember &mem ) const { if( mem.type()==QSMember::Object ) { Q_ASSERT( mem.obj->isValid() ); return objPtr->invoke( mem, *env()->arguments() ); } return QSClass::invoke( objPtr, mem ); } QSWritable *QSWritableClass::data( QSObject *obj ) { return (QSWritable*)obj->shVal(); } const QSWritable *QSWritableClass::data( const QSObject *obj ) { return (const QSWritable*)obj->shVal(); } /*! Create an empty, writable object of this class. */ QSObject QSWritableClass::createWritable() const { return QSObject( this, new QSWritable() ); } QSPropertyMap *QSWritableClass::properties( const QSObject *obj ) const { return data( obj )->properties(); } /*! \reimp Returns the pre-defined members plus dynamic properties of \a obj. */ QSMemberMap QSWritableClass::members( const QSObject *obj ) const { QSMemberMap map = QSClass::members( obj ); if ( obj ) { QSPropertyMap *pmap = properties( obj ); if ( pmap ) { QSPropertyMap::ConstIterator it = pmap->begin(); while ( it != pmap->end() ) { QSMember mem( QSMember::Object, AttributeEnumerable ); mem.setName( it.key() ); mem.setExecutable( it.data().object.isExecutable() ); map.insert( it.key(), mem ); ++it; } } } return map; } QSEqualsResult QSWritableClass::isEqual( const QSObject &a, const QSObject &b ) const { if( b.objectType() == this ) { return ( QSEqualsResult ) ( b.shVal() == a.shVal() ); } return EqualsNotEqual; } QSFunctionScopeClass::QSFunctionScopeClass( QSClass *b, QSFuncDeclNode * func ) : QSWritableClass( b ), ident(func->identifier()), numArgs( 0 ), body_node(0) { } QString QSFunctionScopeClass::identifier() const { return ident.isNull() ? QString(QString::fromLatin1("[anonymous]")) : ident; } void QSFunctionScopeClass::clear() { if (body_node) body_node->setScopeDefinition(0); body_node = 0; QSWritableClass::clear(); } QSObject QSFunctionScopeClass::construct( const QSList &args ) const { // qDebug( "Creating functions scope for: " + identifier() + ", %d", numVariables() ); QSInstanceData *dat = new QSInstanceData( numVariables(), createUndefined() ); QSObject scope = env()->createShared( this, dat ); // fill slots for passed arguments QSListIterator it = args.begin(); int i = 0; while ( it != args.end() && i < numArguments() ) { dat->setValue( i, *it ); it++; i++; } // intialize remaining ones with "undefined" while ( i < numArguments() ) dat->setValue( i++, createUndefined() ); QSArray argObj( env() ); it = args.begin(); for ( i = 0; it != args.end(); ++i, ++it ) argObj.put( QString::number( i ), *it ); scope.put( QString::fromLatin1("arguments"), argObj ); return scope; } QSObject QSEvalScopeClass::construct( const QSList & ) const { return env()->createShared( this, new QSInstanceData( numVariables(), createUndefined() ) ); } void QSBlockScopeClass::activateScope() const { QSObject scope( this ); scope.setVal( env()->currentScope().shVal() ); ref( &scope ); env()->pushScope( scope ); } void QSBlockScopeClass::deactivateScope() const { env()->popScope(); } QSMemberMap QSBlockScopeClass::members( const QSObject *obj ) const { QSMemberMap newMap( *definedMembers() ); QSMemberMap encMap = enclosingClass()->members( obj ); QSMemberMap::ConstIterator it = encMap.begin(); while( it!=encMap.end() ) { newMap[ it.key() ] = it.data(); it++; } return newMap; } class QSTypeClassShared : public QSShared { public: QSTypeClassShared(QSClass *cl) : classValue(cl) { } ~QSTypeClassShared() { // Delete the class when it is cleared. if (!classValue->env()->isShuttingDown()) { classValue->env()->unregisterClass(classValue); classValue->clear(); delete classValue; } } QSClass *classValue; }; QSShared *QSTypeClass::createTypeShared(QSClass *cl) const { return new QSTypeClassShared(cl); } QSObject QSTypeClass::createType(QSClass *cl) const { return QSObject(this, new QSTypeClassShared(cl)); } QSClass *QSTypeClass::classValue(const QSObject *obj) { Q_ASSERT(obj->objectType()->inherits(obj->objectType()->env()->typeClass())); return ((QSTypeClassShared *)obj->shVal())->classValue; } bool QSTypeClass::member( const QSObject *o, const QString &n, QSMember *m ) const { if( !o ) return FALSE; Q_ASSERT( o->isA( this ) ); QSClass *tcl = classValue(o); return tcl->member( 0, n, m ); } QSMemberMap QSTypeClass::members( const QSObject *obj ) const { Q_ASSERT( obj->isA( this ) ); if ( ( ( const QSClass * ) classValue(obj) ) == this ) return QSClass::members( obj ); else return classValue(obj)->members( 0 ); } QSMemberMap QSTypeClass::allMembers( const QSObject *obj ) const { Q_ASSERT( obj->isA( this ) ); if ( ( ( const QSClass * ) classValue(obj) ) == this ) return QSClass::members( obj ); else return *( classValue(obj)->definedMembers() ); } QSObject QSTypeClass::fetchValue( const QSObject *o, const QSMember &mem ) const { Q_ASSERT( o->isA( this ) ); if ( !mem.hasAttribute( AttributeStatic ) ) { throwError( ReferenceError, QString::fromLatin1("Cannot access a non-static member " "without an object reference") ); return createUndefined(); } QSClass *tcl = classValue(o); return tcl->fetchValue( o, mem ); } QSObject QSTypeClass::invoke( QSObject *o, const QSMember &mem ) const { Q_ASSERT( o->objectType()==this ); // we are not interested in static functions if ( mem.isStatic() ) return QSClass::invoke( o, mem ); else if( mem.type()==QSMember::Variable ) // Indirect casting. return classValue(o)->cast( *env()->arguments() ); throwError( ReferenceError, QString::fromLatin1("Cannot invoke a non-static function " "without an object reference") ); return createUndefined(); } void QSTypeClass::write( QSObject *objPtr, const QSMember &mem, const QSObject &val ) const { Q_ASSERT( mem.isWritable() ); // Q_ASSERT( mem.type()==QSMember::Variable ); if ( !mem.hasAttribute( AttributeStatic ) ) { throwError( ReferenceError, QString::fromLatin1("Cannot access a non-static member " "without an object reference") ); return; } QSClass * cl = classValue(objPtr); if( mem.type()==QSMember::Variable ) { cl->setStaticMember( mem.idx, val ); } else { throwError( ReferenceError, QString::fromLatin1("Trying to write to a nonvariable") ); return; } } QSEqualsResult QSTypeClass::isEqual( const QSObject &a, const QSObject &b ) const { if( b.objectType()==this ) { return ( QSEqualsResult ) ( classValue(&a) == classValue(&b) ); } return EqualsUndefined; } static void qs_dumpclass( const QSClass *cl ) { printf( "class %s", cl->identifier().latin1() ); printf( " - %s\n", cl->isExecutable() ? "executable" : "not executable" ); printf( " - %s\n", cl->isFinal() ? "final" : "not final" ); QSMemberMap::Iterator it = cl->definedMembers()->begin(); for( ; it!=cl->definedMembers()->end(); it++ ) { QSMember mem = *it; QString line = QString(QString::fromLatin1(" ")) + mem; printf( "%s\n", line.latin1() ); } if( cl->enclosingClass() ) qs_dumpclass( cl->enclosingClass() ); if( cl->base() ) qs_dumpclass( cl->base() ); } static void qs_dumptype( const QSList &args ) { if ( args.size()>=1 && args[0].objectType()==args[0].objectType()->env()->typeClass() ) { printf( "DUMP TYPE::\n" ); QSObject arg0 = args[0]; QSClass *cl = QSTypeClass::classValue(&arg0); qs_dumpclass( cl ); } printf( "\n" ); } static void qs_dumpobject( const QSObject &obj ) { const QSClass * cl = obj.objectType(); printf( "DUMP OBJECT:: %p\n", obj.shVal() ); printf( "class %s :: %s\n", cl->name().latin1(), cl->identifier().latin1() ); QSMemberMap::Iterator it = cl->definedMembers()->begin(); for( ; it!=cl->definedMembers()->end(); it++ ) { QSMember mem = *it; if( mem.isReadable() ) { QSObject value = cl->fetchValue( &obj, mem ); if( mem.type()==QSMember::Variable ) printf( " %2d: %s = %s\n", mem.index(), mem.name().latin1(), value.toString().latin1() ); else printf( " %s = %s\n", mem.name().latin1(), value.toString().latin1() ); } } } QSDebugClass::QSDebugClass( QSClass *base ) : QSClass( base, AttributeAbstract ) { addMember( QString::fromLatin1("dumpObject"), QSMember( &dumpObject, AttributeNonWritable|AttributeStatic ) ); addMember( QString::fromLatin1("dumpScope"), QSMember( &dumpScope, AttributeNonWritable|AttributeStatic ) ); addMember( QString::fromLatin1("dumpType"), QSMember( &dumpType, AttributeNonWritable|AttributeStatic ) ); } void QSDebugClass::dumpObject( QSEnv * env ) { qs_dumpobject( ( env->numArgs() > 0 ? env->arg( 0 ) : env->createUndefined() ) ); } void QSDebugClass::dumpScope( QSEnv * env ) { ScopeChain chain = env->scope(); ScopeChain::ConstIterator it = chain.begin(); qDebug( "\n---------- DUMP SCOPE ----------" ); while( it!=chain.end() ) { qs_dumpobject( *it ); if( (*it).objectType() == env->typeClass() ) { QSList itList( *it ); qs_dumptype( itList ); } it++; } qDebug( "---------- DUMP COMPLETE ----------" ); } void QSDebugClass::dumpType( QSEnv * env ) { qs_dumptype( *env->arguments() ); } QSSystemClass::QSSystemClass( QSClass *base ) : QSClass( base, AttributeAbstract ) { addMember( QString::fromLatin1("print"), QSMember( &print, AttributeNonWritable | AttributeStatic ) ); addMember( QString::fromLatin1("println"), QSMember( &println, AttributeNonWritable | AttributeStatic ) ); addMember( QString::fromLatin1("getenv"), QSMember( &getenv, AttributeNonWritable | AttributeStatic ) ); addMember( QString::fromLatin1("setenv"), QSMember( &setenv, AttributeNonWritable | AttributeStatic ) ); } void QSSystemClass::println( QSEnv *env ) { printf( "%s\n", env->arg( 0 ).toString().latin1() ); } void QSSystemClass::print( QSEnv *env ) { printf( "%s", env->arg( 0 ).toString().latin1() ); } QSObject QSSystemClass::getenv( QSEnv *env ) { return env->createString( QString::fromLatin1(::getenv( env->arg( 0 ).toString().latin1() )) ); } void QSSystemClass::setenv( QSEnv *env ) { #if defined(Q_OS_HPUX) || defined(Q_OS_IRIX) || defined(Q_OS_SOLARIS) || defined( Q_CC_BOR ) putenv( (char*)( env->arg( 0 ).toString() + "=" + env->arg( 1 ).toString() ).latin1() ); // char* on Solaris #elif defined(Q_OS_WIN32) _putenv( QString::fromLatin1("%1=%2") .arg(env->arg( 0 ).toString()) .arg(env->arg( 1 ).toString() ).latin1() ); #else ::setenv( (char *)env->arg( 0 ).toString().latin1(), (char *)env->arg( 1 ).toString().latin1(), 1 ); #endif } /* Implementation of the QSAbstractBaseClass. * Used primarly to support cross referencing of class between files, e.g. * declaring a class in one file and deriving from it in another. */ void QSAbstractBaseClass::replace(QSClassClass *newBase) { QPtrList<QSClassClass> userClasses; QPtrList<QSClass> allClasses = env()->classes(); // Build a list of the user classes, excluding this one. QPtrListIterator<QSClass> it(allClasses); QSClass *tmp; while ((tmp = it())) if (tmp->asClass() && tmp != newBase) userClasses.append((QSClassClass*)tmp); // Check if userclasses have this abstract class definition as parent and update // member table if so. QPtrListIterator<QSClassClass> userIt(userClasses); QPtrList<QSClassClass> directChildren; QSClassClass *userClass; while ((userClass = userIt())) { QSClass *baseClass = userClass->base(); // Directly derived, base pointer must be updated later if (userClass->base() == this) directChildren.append(userClass); while (baseClass && baseClass != this) baseClass = baseClass->base(); // update offsets in member table... if (baseClass == this) { userClass->setNumVariables(newBase->numVariables() + userClass->numVariables()); QSMemberMap *mems = userClass->definedMembers(); for (QSMemberMap::Iterator it = mems->begin(); it != mems->end(); ++it) { QSMember &m = (*it); if (m.type() == QSMember::Variable && !m.isStatic()) m.setIndex(m.index()+newBase->numVariables()); } } } userIt = QPtrListIterator<QSClassClass>(directChildren); while ((userClass = userIt())) userClass->setBase(newBase); // We no longer serve any purpose, so we disappear... env()->unregisterClass(this); clear(); delete this; }; QSInstanceData::QSInstanceData( int count, const QSObject &def ) { vals = new QSObject[count]; sz = count; for( int i=0; i<count; i++ ) vals[i] = def; } void QSInstanceData::resize( int count, const QSObject &def ) { QSObject *tmp = vals; vals = new QSObject[count]; for( int i=0; i<sz; i++ ) { vals[i] = tmp[i]; } for( int j=sz; j<count; j++ ) vals[j] = def; delete [] tmp; sz = count; } /*! Insure that this object has enough space for \a count objects. If that is already the case the array won't be resized. */ void QSInstanceData::ensureSize( int count, const QSObject &def ) { if ( count > sz ) resize( count, def ); } /*! Invalidates all the objects in this instance data so that it can be destroyed at a later time without any problems without further reference counting. */ void QSInstanceData::invalidate() { for( int i=0; i<sz; i++ ) { vals[i].invalidate(); } QSWritable::invalidate(); } QString operator+( const QString &a, const QSMember &b ) { QString s; s.sprintf( "QSMember(%s.%s, %s, %x)", b.owner() ? b.owner()->identifier().latin1() : "(no owner)", b.name().latin1(), b.typeName().latin1(), b.attributes() ); return a + s; } bool operator==( const QSMember &a, const QSMember &b ) { return a.type() == b.type() && a.owner() == b.owner() && !a.name().isEmpty() && a.name() == b.name(); }
47,347
16,673
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetCircleResolution(120); red = 233; blue = 233; green = 233; hideGUI = false; bdrawGrid = false; bdrawPadding = false; ddl = NULL; textInput = NULL; img = new ofImage(); img->loadImage("nerd_me.png"); buffer = new float[256]; for(int i = 0; i < 256; i++) { buffer[i] = ofNoise(i/100.0); } setGUI1(); setGUI2(); setGUI3(); setGUI4(); setGUI5(); gui1->loadSettings("gui1Settings.xml"); gui2->loadSettings("gui2Settings.xml"); gui3->loadSettings("gui3Settings.xml"); gui4->loadSettings("gui4Settings.xml"); gui5->loadSettings("gui5Settings.xml"); } //-------------------------------------------------------------- void ofApp::update(){ mg->addPoint(buffer[0]); for(int i = 0; i < 256; i++) { buffer[i] = ofNoise(i/100.0, ofGetElapsedTimef()); } } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(red, green, blue, 255); ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_ALPHA); if(bdrawGrid) { ofSetColor(255, 255, 255, 25); drawGrid(8,8); } ofPopStyle(); ofSetRectMode(OF_RECTMODE_CENTER); } void ofApp::guiEvent(ofxUIEventArgs &e) { string name = e.getName(); int kind = e.getKind(); cout << "got event from: " << name << endl; if(kind == OFX_UI_WIDGET_NUMBERDIALER) { ofxUINumberDialer *n = (ofxUINumberDialer *) e.widget; cout << n->getValue() << endl; } if(name == "SAMPLER") { ofxUIImageSampler *is = (ofxUIImageSampler *) e.widget; ofColor clr = is->getColor(); red = clr.r; blue = clr.b; green = clr.g; } else if(name == "BUTTON") { ofxUIButton *button = (ofxUIButton *) e.getButton(); bdrawGrid = button->getValue(); } else if(name == "TOGGLE") { ofxUIToggle *toggle = (ofxUIToggle *) e.getToggle(); bdrawGrid = toggle->getValue(); if(textInput != NULL) { textInput->setFocus(bdrawGrid); } } else if(name == "RADIO VERTICAL") { ofxUIRadio *radio = (ofxUIRadio *) e.widget; cout << radio->getName() << " value: " << radio->getValue() << " active name: " << radio->getActiveName() << endl; } else if(name == "TEXT INPUT") { ofxUITextInput *ti = (ofxUITextInput *) e.widget; if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_ENTER) { cout << "ON ENTER: "; } else if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_FOCUS) { cout << "ON FOCUS: "; } else if(ti->getInputTriggerType() == OFX_UI_TEXTINPUT_ON_UNFOCUS) { cout << "ON BLUR: "; } string output = ti->getTextString(); cout << output << endl; } } //-------------------------------------------------------------- void ofApp::exit() { gui1->saveSettings("gui1Settings.xml"); gui2->saveSettings("gui2Settings.xml"); gui3->saveSettings("gui3Settings.xml"); gui4->saveSettings("gui4Settings.xml"); gui5->saveSettings("gui5Settings.xml"); delete gui1; delete gui2; delete gui3; delete gui4; delete gui5; delete[] buffer; delete img; delete env; } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(gui2->hasKeyboardFocus()) { return; } switch (key) { case 't': { if(textInput != NULL) { textInput->setTextString(ofGetTimestampString()); } } break; case 'T': { if(tm != NULL) { int cols = tm->getColumnCount(); int rows = tm->getRowCount(); for(int row = 0; row < rows; row++) { for(int col = 0; col < cols; col++) { cout << tm->getState(row, col) << "\t"; } cout << endl; } } } break; case 'd': { if(ddl != NULL) { vector<ofxUIWidget *> selected = ddl->getSelected(); for(vector<ofxUIWidget *>::iterator it = selected.begin(); it != selected.end(); ++it) { ofxUILabelToggle *lt = (ofxUILabelToggle *) (*it); cout << lt->getName() << endl; } } } break; case 'D': { if(ddl != NULL) { vector<string> names = ddl->getSelectedNames(); for(vector<string>::iterator it = names.begin(); it != names.end(); ++it) { cout << (*it) << endl; } } } break; case 'r': { if(textInput != NULL) { textInput->setFocus(!textInput->isFocused()); } } break; case 'f': ofToggleFullscreen(); break; case 'F': { if(tm != NULL) { tm->setDrawOutlineHighLight(!tm->getDrawOutlineHighLight()); // tm->setDrawPaddingOutline(!tm->getDrawPaddingOutline()); } } break; case 'h': gui1->toggleVisible(); gui2->toggleVisible(); gui3->toggleVisible(); gui4->toggleVisible(); gui5->toggleVisible(); break; case 'p': bdrawPadding = !bdrawPadding; gui1->setDrawWidgetPaddingOutline(bdrawPadding); gui2->setDrawWidgetPaddingOutline(bdrawPadding); gui3->setDrawWidgetPaddingOutline(bdrawPadding); gui4->setDrawWidgetPaddingOutline(bdrawPadding); gui5->setDrawWidgetPaddingOutline(bdrawPadding); break; case '[': gui1->setDrawWidgetPadding(false); gui2->setDrawWidgetPadding(false); gui3->setDrawWidgetPadding(false); gui4->setDrawWidgetPadding(false); gui5->setDrawWidgetPadding(false); break; case ']': gui1->setDrawWidgetPadding(true); gui2->setDrawWidgetPadding(true); gui3->setDrawWidgetPadding(true); gui4->setDrawWidgetPadding(true); gui5->setDrawWidgetPadding(true); break; case '1': gui1->toggleVisible(); break; case '2': gui2->toggleVisible(); break; case '3': gui3->toggleVisible(); break; case '4': gui4->toggleVisible(); break; case '5': gui5->toggleVisible(); break; default: break; } } void ofApp::drawGrid(float x, float y) { float w = ofGetWidth(); float h = ofGetHeight(); for(int i = 0; i < h; i+=y) { ofLine(0,i,w,i); } for(int j = 0; j < w; j+=x) { ofLine(j,0,j,h); } } void ofApp::setGUI1() { vector<string> names; names.push_back("RAD1"); names.push_back("RAD2"); names.push_back("RAD3"); gui1 = new ofxUISuperCanvas("PANEL 1: BASICS"); gui1->addSpacer(); gui1->addLabel("Press 'h' to Hide GUIs", OFX_UI_FONT_SMALL); gui1->addSpacer(); gui1->addLabel("H SLIDERS"); gui1->addSlider("RED", 0.0, 255.0, &red)->setTriggerType(OFX_UI_TRIGGER_ALL); gui1->addSlider("GREEN", 0.0, 255.0, &green)->setTriggerType(OFX_UI_TRIGGER_BEGIN|OFX_UI_TRIGGER_CHANGE|OFX_UI_TRIGGER_END); gui1->addSlider("BLUE", 0.0, 255.0, &blue)->setTriggerType(OFX_UI_TRIGGER_BEGIN|OFX_UI_TRIGGER_CHANGE); gui1->addSpacer(); gui1->addLabel("V SLIDERS"); gui1->addSlider("0", 0.0, 255.0, 150, 17, 160); gui1->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui1->addSlider("1", 0.0, 255.0, 150, 17, 160); gui1->addSlider("2", 0.0, 255.0, 150, 17, 160); gui1->addSlider("3", 0.0, 255.0, 150, 17, 160); gui1->addSlider("4", 0.0, 255.0, 150, 17, 160); gui1->addSlider("5", 0.0, 255.0, 150, 17, 160); gui1->addSlider("6", 0.0, 255.0, 150, 17, 160); gui1->addSlider("7", 0.0, 255.0, 150, 17, 160); gui1->addSlider("8", 0.0, 255.0, 150, 17, 160); gui1->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui1->addSpacer(); gui1->addRadio("RADIO HORIZONTAL", names, OFX_UI_ORIENTATION_HORIZONTAL); gui1->addRadio("RADIO VERTICAL", names, OFX_UI_ORIENTATION_VERTICAL); gui1->addSpacer(); gui1->setWidgetFontSize(OFX_UI_FONT_SMALL); gui1->addButton("BUTTON", false); gui1->addToggle( "TOGGLE", false); gui1->addSpacer(); gui1->addLabel("RANGE SLIDER"); gui1->addRangeSlider("RSLIDER", 0.0, 255.0, 50.0, 100.0); string textString = "This widget is a text area widget. Use this when you need to display a paragraph of text. It takes care of formatting the text to fit the block."; gui1->addSpacer(); gui1->addTextArea("textarea", textString, OFX_UI_FONT_SMALL); gui1->autoSizeToFitWidgets(); ofAddListener(gui1->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI2() { gui2 = new ofxUISuperCanvas("PANEL 2: ADVANCED"); gui2->addSpacer(); gui2->setWidgetFontSize(OFX_UI_FONT_MEDIUM); textInput = gui2->addTextInput("TEXT INPUT", "Input Text"); textInput->setAutoUnfocus(false); gui2->addLabel("AUTO CLEAR DISABLED", OFX_UI_FONT_SMALL); gui2->addTextInput("TEXT INPUT2", "Input Text")->setAutoClear(false); gui2->setWidgetFontSize(OFX_UI_FONT_MEDIUM); gui2->addSpacer(); gui2->addLabel("WAVEFORM DISPLAY"); gui2->addWaveform("WAVEFORM", buffer, 256, 0.0, 1.0); gui2->addLabel("SPECTRUM DISPLAY"); gui2->addSpectrum("SPECTRUM", buffer, 256, 0.0, 1.0); vector<float> buffer; for(int i = 0; i < 256; i++) { buffer.push_back(0.0); } gui2->addLabel("MOVING GRAPH", OFX_UI_FONT_MEDIUM); mg = gui2->addMovingGraph("MOVING", buffer, 256, 0.0, 1.0); gui2->addSpacer(); gui2->addLabel("IMAGE DISPLAY"); gui2->addImage("IMAGE CAPTION", img); gui2->addSpacer(); gui2->addLabel("FPS LABEL"); gui2->addFPS(); gui2->setWidgetFontSize(OFX_UI_FONT_SMALL); gui2->addSpacer(); gui2->addLabel("NUMBER DIALER"); gui2->addNumberDialer("DIALER", -10000, 10000, 5000, 3); gui2->addSpacer(); gui2->addLabel("LABEL BUTTON", OFX_UI_FONT_MEDIUM); gui2->addLabelButton("LABEL BTN", false); gui2->addSpacer(); gui2->addLabel("LABEL TOGGLES", OFX_UI_FONT_MEDIUM); gui2->addLabelToggle("LABEL TGL", false)->getLabelWidget()->setColorFill(ofColor(255, 0, 0)); gui2->setPosition(212, 0); gui2->autoSizeToFitWidgets(); ofAddListener(gui2->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI3() { gui3 = new ofxUISuperCanvas("PANEL 3: ADVANCED"); gui3->addSpacer(); gui3->setGlobalButtonDimension(24); gui3->addLabel("MATRIX", OFX_UI_FONT_MEDIUM); gui3->addToggleMatrix("MATRIX1", 3, 3); tm = gui3->addToggleMatrix("MATRIX2", 3, 6); gui3->addToggleMatrix("MATRIX3", 1, 4); gui3->addSpacer(); gui3->setGlobalButtonDimension(64); gui3->addImageButton("IMAGEBTN", "GUI/images/App.png", false); gui3->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui3->addImageToggle("IMAGETGL", "GUI/images/Preview.png", false); gui3->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui3->addSpacer(); env = new ofxUIEnvelope(); for(float i = 0; i <= 5; i++) { env->addPoint(i/5.0, i/5.0); } gui3->addWidgetDown(new ofxUIEnvelopeEditor("ENV", env, 200, 128)); vector<string> items; items.push_back("FIRST ITEM"); items.push_back("SECOND ITEM"); items.push_back("THIRD ITEM"); items.push_back("FOURTH ITEM"); items.push_back("FIFTH ITEM"); items.push_back("SIXTH ITEM"); gui3->addSpacer(); gui3->setWidgetFontSize(OFX_UI_FONT_SMALL); gui3->addSortableList("SORTABLE LIST", items); gui3->addSpacer(); gui3->setWidgetFontSize(OFX_UI_FONT_MEDIUM); ddl = gui3->addDropDownList("DROP DOWN LIST", items); ddl->setAllowMultiple(true); gui3->setGlobalButtonDimension(OFX_UI_GLOBAL_BUTTON_DIMENSION); gui3->setPosition(212*2, 0); gui3->autoSizeToFitWidgets(); ofAddListener(gui3->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI4() { gui4 = new ofxUISuperCanvas("PANEL 4: ADVANCED"); gui4->addSpacer(); gui4->addLabel("BILABEL SLIDER"); gui4->addBiLabelSlider("BILABEL", "HOT", "COLD", 0, 100, 50); gui4->addLabel("MINIMAL SLIDER"); gui4->addMinimalSlider("MINIMAL", 0, 100, 50.0)->getLabelWidget()->setColorFill(ofColor(255, 255, 0)); gui4->addSpacer(); gui4->addLabel("FPS SLIDER", OFX_UI_FONT_MEDIUM); gui4->addFPSSlider("FPS SLIDER"); gui4->addSpacer(); gui4->addLabel("IMAGE SAMPLER", OFX_UI_FONT_MEDIUM); gui4->addImageSampler("SAMPLER", img); gui4->setGlobalButtonDimension(64); gui4->addMultiImageButton("IMAGE BUTTON", "GUI/toggle.png", false); gui4->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui4->addMultiImageToggle("IMAGE TOGGLE", "GUI/toggle.png", false); gui4->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui4->addBaseDraws("BASE DRAW", img, true); gui4->addSpacer(); gui4->setGlobalButtonDimension(32); gui4->addButton("BTN", false)->setLabelVisible(false); gui4->addToggle("TGL", false)->setLabelVisible(false); gui4->setPosition(212*3,0); gui4->autoSizeToFitWidgets(); ofAddListener(gui4->newGUIEvent,this,&ofApp::guiEvent); } void ofApp::setGUI5() { gui5 = new ofxUISuperCanvas("PANEL 5: ADVANCED"); gui5->addSpacer(); gui5->addLabel("2D PAD"); gui5->add2DPad("PAD", ofPoint(-100, 100), ofPoint(-100,100), ofPoint(0,0)); gui5->addSpacer(); gui5->addLabel("ROTARY SLIDER", OFX_UI_FONT_MEDIUM); gui5->addRotarySlider("R2SLIDER", 0, 100, 50); gui5->addSpacer(); gui5->addLabel("CIRCLE SLIDER", OFX_UI_FONT_MEDIUM); gui5->addCircleSlider("NORTH SOUTH", 0, 100, 50.0); gui5->setPosition(212*4,0); gui5->autoSizeToFitWidgets(); ofAddListener(gui5->newGUIEvent,this,&ofApp::guiEvent); } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
15,264
6,066
#include "ModeSetState.h" #include <common/net/message/nodes/SetTargetConsistencyStatesMsg.h> #include <common/net/message/nodes/SetTargetConsistencyStatesRespMsg.h> #include <common/toolkit/MessagingTk.h> #include <common/toolkit/UiTk.h> #include <program/Program.h> #define MODESETSTATE_ARG_TARGETID "--targetid" #define MODESETSTATE_ARG_NODEID "--nodeid" #define MODESETSTATE_ARG_STATE "--state" #define MODESETSTATE_ARG_STATE_GOOD "good" #define MODESETSTATE_ARG_STATE_BAD "bad" #define MODESETSTATE_ARG_FORCE "--force" int ModeSetState::execute() { App* app = Program::getApp(); StringMap* cfg = app->getConfig()->getUnknownConfigArgs(); uint16_t cfgTargetID = 0; TargetConsistencyState cfgState; if (!ModeHelper::checkRootPrivileges()) return APPCODE_RUNTIME_ERROR; nodeType = ModeHelper::nodeTypeFromCfg(cfg); if (this->nodeType != NODETYPE_Meta && this->nodeType != NODETYPE_Storage) { std::cerr << "Invalid or missing node type." << std::endl; return APPCODE_INVALID_CONFIG; } StringMapIter iter = cfg->find(MODESETSTATE_ARG_TARGETID); if(iter != cfg->end() ) { if (nodeType == NODETYPE_Meta) { std::cerr << "TargetIDs are only supported when setting state of storage targets. " "For metadata servers, plase use the --nodeID parameter." << std::endl; return APPCODE_INVALID_CONFIG; } bool isNumericRes = StringTk::isNumeric(iter->second); if(!isNumericRes) { std::cerr << "Invalid targetID given (must be numeric): " << iter->second << std::endl; return APPCODE_INVALID_CONFIG; } cfgTargetID = StringTk::strToUInt(iter->second); cfg->erase(iter); } iter = cfg->find(MODESETSTATE_ARG_NODEID); if (iter != cfg->end()) { if (nodeType == NODETYPE_Storage) { std::cerr << "NodeIDs are only supported when setting state of metadata nodes. " "For storage targets, please use the --targetID parameter." << std::endl; return APPCODE_INVALID_CONFIG; } bool isNumericRes = StringTk::isNumeric(iter->second); if (!isNumericRes) { std::cerr << "Invalid nodeID given (must be numeric): " << iter->second << std::endl; return APPCODE_INVALID_CONFIG; } cfgTargetID = StringTk::strToUInt(iter->second); cfg->erase(iter); } iter = cfg->find(MODESETSTATE_ARG_STATE); if (iter != cfg->end()) { if (iter->second == MODESETSTATE_ARG_STATE_GOOD) { cfg->erase(iter); // erase the "--state" iter = cfg->find(MODESETSTATE_ARG_FORCE); if (iter == cfg->end()) { std::cerr << "If state should be set to \"good\", --force must be given." << std::endl; return APPCODE_INVALID_CONFIG; } cfg->erase(iter); // erase the "--force" cfgState = TargetConsistencyState_GOOD; } else if (iter->second == MODESETSTATE_ARG_STATE_BAD) { cfgState = TargetConsistencyState_BAD; cfg->erase(iter); // erase the "--state" } else { std::cerr << "Invalid state given (must be \"good\" or \"bad\"): " << iter->second << std::endl; return APPCODE_INVALID_CONFIG; } } else { std::cerr << "State must be specified." << std::endl; return APPCODE_INVALID_CONFIG; } if (ModeHelper::checkInvalidArgs(cfg)) return APPCODE_INVALID_CONFIG; if (!uitk::userYNQuestion("WARNING!\n\nThis command is very dangerous and can cause serious data " "loss.\n" "It should not be used under normal circumstances. It is absolutely recommended to contact " "support before proceeding.")) return APPCODE_INVALID_CONFIG; return doSet(cfgTargetID, cfgState); } void ModeSetState::printHelp() { std::cout << "MODE ARGUMENTS:" << std::endl; std::cout << " Mandatory:" << std::endl; std::cout << " --nodetype=<nodetype> The node type (metadata, storage)." << std::endl; std::cout << " --targetid=<targetID> The ID of the target whose state should be" << std::endl; std::cout << " set." << std::endl; std::cout << " (only for nodetype=storage)" << std::endl; std::cout << " --nodeid=<nodeID> The ID of the node whose state should be set." << std::endl; std::cout << " (only for nodetype=metadata)" << std::endl; std::cout << " --state=<state> The state to be set (\"good\" or \"bad\")." << std::endl; std::cout << std::endl; std::cout << "USAGE:" << std::endl; std::cout << " This mode can be used to forcefully set the state of a target or node. This is" << std::endl; std::cout << " useful to manually set a target or node to the state \"bad\", or to resolve a" << std::endl; std::cout << " situation in which both buddies in a buddy mirror group are in the state" << std::endl; std::cout << " \"needs-resync\"." << std::endl; std::cout << std::endl; std::cout << " Example: Set a metadata node to \"bad\"" << std::endl; std::cout << " $ beegfs-ctl --setstate --nodetype=metadata --nodeid=10 --state=bad" << std::endl; } int ModeSetState::doSet(uint16_t targetID, TargetConsistencyState state) { App* app = Program::getApp(); // Send message to mgmtd auto nodes = app->getMgmtNodes(); NodeHandle node = nodes->referenceFirstNode(); UInt16List targetIDs(1, targetID); UInt8List states(1, (uint8_t)state); SetTargetConsistencyStatesMsg msg(nodeType, &targetIDs, &states, false); { const auto respMsgRaw = MessagingTk::requestResponse(*node, msg, NETMSGTYPE_SetTargetConsistencyStatesResp); if (!respMsgRaw) { std::cerr << "Communication with node not successful." << std::endl; return APPCODE_RUNTIME_ERROR; } SetTargetConsistencyStatesRespMsg* respMsgCast = reinterpret_cast<SetTargetConsistencyStatesRespMsg*>(respMsgRaw.get()); if (respMsgCast->getResult() != FhgfsOpsErr_SUCCESS) { std::cerr << "Management host did not accept state change. Error: " << respMsgCast->getResult() << std::endl; return APPCODE_RUNTIME_ERROR; } } // Send message to node if (nodeType == NODETYPE_Storage) { TargetMapper* targetMapper = app->getTargetMapper(); FhgfsOpsErr err; nodes = app->getStorageNodes(); node = nodes->referenceNodeByTargetID(targetID, targetMapper, &err); if (!node) { std::cerr << "Unable to resolve node for target ID " << targetID << ". Error: " << err << std::endl; return APPCODE_RUNTIME_ERROR; } } else { nodes = app->getMetaNodes(); node = nodes->referenceNode(NumNodeID(targetID)); if (!node) { std::cerr << "Unable to resolve node for node ID " << targetID << std::endl; return APPCODE_RUNTIME_ERROR; } } { const auto respMsgRaw = MessagingTk::requestResponse(*node, msg, NETMSGTYPE_SetTargetConsistencyStatesResp); if (!respMsgRaw) { std::cerr << "Communication with node not successful." << std::endl; return APPCODE_RUNTIME_ERROR; } auto respMsgCast = reinterpret_cast<SetTargetConsistencyStatesRespMsg*>(respMsgRaw.get()); if (respMsgCast->getResult() != FhgfsOpsErr_SUCCESS) { std::cerr << "Node did not accept state change. Error: " << respMsgCast->getResult() << std::endl; return APPCODE_RUNTIME_ERROR; } } std::cout << "Successfully set state." << std::endl; return APPCODE_NO_ERROR; }
7,845
2,572
// 2303. 숫자 게임 // 2019.10.27 // 구현 #include<iostream> #include<vector> using namespace std; int maxVal; int idx; int check(vector<int>& v) { int val = 0; for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 4; j++) { for (int k = j + 1; k < 5; k++) { int sum = (v[i] + v[j] + v[k]) % 10; val = val > sum ? val : sum; } } } return val; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { vector<int> v(5); for (int i = 0; i < 5; i++) { cin >> v[i]; } int val = check(v); if (maxVal <= val) { maxVal = val; idx = i + 1; } } cout << idx << endl; return 0; }
629
370
#include "task_base_pro/task_group.hpp"
39
16
#include <escher/stack_view.h> #include <escher/metric.h> extern "C" { #include <assert.h> } namespace Escher { StackView::StackView() : View(), m_controller(nullptr) { } void StackView::setTextColor(KDColor textColor) { m_textColor = textColor; markRectAsDirty(bounds()); } void StackView::setBackgroundColor(KDColor backgroundColor) { m_backgroundColor = backgroundColor; markRectAsDirty(bounds()); } void StackView::setSeparatorColor(KDColor separatorColor) { m_separatorColor = separatorColor; markRectAsDirty(bounds()); } void StackView::setNamedController(ViewController * controller) { m_controller = controller; markRectAsDirty(bounds()); } void StackView::drawRect(KDContext * ctx, KDRect rect) const { KDRect b = bounds(); drawBorderOfRect(ctx, b, m_separatorColor); drawInnerRect(ctx, b, m_backgroundColor); // Write title const KDFont * font = KDFont::SmallFont; // Add horizontal margins KDPoint point = KDPoint(Metric::CellLeftMargin, 0); KDSize size = KDSize(m_frame.width() - Metric::CellLeftMargin - Metric::CellRightMargin, m_frame.height()); ctx->alignAndDrawString(m_controller->title(), point, size, 0.5f, 0.5f, font, m_textColor, m_backgroundColor); } #if ESCHER_VIEW_LOGGING const char * StackView::className() const { return "StackView"; } void StackView::logAttributes(std::ostream &os) const { View::logAttributes(os); os << " name=\"" << m_name << "\""; } #endif }
1,446
508
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "Metric.h" using namespace std; using namespace Common; using namespace Reliability::LoadBalancingComponent; Metric::Metric( wstring && name, double weight, double balancingThreshold, DynamicBitSet && blockList, uint activityThreshold, int64 clusterTotalCapacity, int64 clusterBufferedCapacity, int64 clusterLoad, bool isDefrag, int32 defragEmptyNodeCount, size_t defragEmptyNodeLoadThreshold, int64 reservationLoad, DefragDistributionType defragEmptyNodesDistribution, double placementHeuristicIncomingLoadFactor, double placementHeuristicEmptySpacePercent, bool defragmentationScopedAlgorithmEnabled, PlacementStrategy placementStrategy, double defragmentationEmptyNodeWeight, double defragmentationNonEmptyNodeWeight, bool balancingByPercentage) : name_(move(name)), weight_(weight), balancingThreshold_(balancingThreshold), blockList_(move(blockList)), isBalanced_(false), activityThreshold_(activityThreshold), clusterTotalCapacity_(clusterTotalCapacity), clusterBufferedCapacity_(clusterBufferedCapacity), clusterLoad_(clusterLoad), isDefrag_(isDefrag), defragEmptyNodeCount_(defragEmptyNodeCount), defragEmptyNodeLoadThreshold_(defragEmptyNodeLoadThreshold), reservationLoad_(reservationLoad), defragEmptyNodesDistribution_(defragEmptyNodesDistribution), placementHeuristicIncomingLoadFactor_(placementHeuristicIncomingLoadFactor), placementHeuristicEmptySpacePercent_(placementHeuristicEmptySpacePercent), defragmentationScopedAlgorithmEnabled_(defragmentationScopedAlgorithmEnabled), placementStrategy_(placementStrategy), defragmentationEmptyNodeWeight_(defragmentationEmptyNodeWeight), defragmentationNonEmptyNodeWeight_(defragmentationNonEmptyNodeWeight), balancingByPercentage_(balancingByPercentage) { // 1.0 means do balancing for any diff, 0.0 means infinity, e.g. never trigger balancing ASSERT_IFNOT(balancingThreshold >= 1.0 || balancingThreshold == 0.0, "balancingThreshold should >= 1 or == 0, current value is {0}", balancingThreshold); } Metric::Metric(Metric const & other) : name_(other.name_), weight_(other.weight_), balancingThreshold_(other.balancingThreshold_), blockList_(other.blockList_), isBalanced_(other.isBalanced_), activityThreshold_(other.activityThreshold_), clusterTotalCapacity_(other.clusterTotalCapacity_), clusterBufferedCapacity_(other.clusterBufferedCapacity_), clusterLoad_(other.clusterLoad_), isDefrag_(other.isDefrag_), defragEmptyNodeCount_(other.defragEmptyNodeCount_), defragEmptyNodeLoadThreshold_(other.defragEmptyNodeLoadThreshold_), reservationLoad_(other.reservationLoad_), defragEmptyNodesDistribution_(other.defragEmptyNodesDistribution_), placementHeuristicIncomingLoadFactor_(other.placementHeuristicIncomingLoadFactor_), placementHeuristicEmptySpacePercent_(other.placementHeuristicEmptySpacePercent_), defragmentationScopedAlgorithmEnabled_(other.defragmentationScopedAlgorithmEnabled_), placementStrategy_(other.placementStrategy_), defragmentationEmptyNodeWeight_(other.defragmentationEmptyNodeWeight_), defragmentationNonEmptyNodeWeight_(other.defragmentationNonEmptyNodeWeight_), balancingByPercentage_(other.balancingByPercentage_), indexInGlobalDomain_(other.indexInGlobalDomain_), indexInLocalDomain_(other.indexInLocalDomain_), indexInTotalDomain_(other.indexInTotalDomain_) { } Metric::Metric(Metric && other) : name_(move(other.name_)), weight_(other.weight_), balancingThreshold_(other.balancingThreshold_), blockList_(move(other.blockList_)), isBalanced_(other.isBalanced_), activityThreshold_(other.activityThreshold_), clusterTotalCapacity_(other.clusterTotalCapacity_), clusterBufferedCapacity_(other.clusterBufferedCapacity_), clusterLoad_(other.clusterLoad_), isDefrag_(other.isDefrag_), defragEmptyNodeCount_(other.defragEmptyNodeCount_), defragEmptyNodeLoadThreshold_(other.defragEmptyNodeLoadThreshold_), reservationLoad_(other.reservationLoad_), defragEmptyNodesDistribution_(other.defragEmptyNodesDistribution_), placementHeuristicIncomingLoadFactor_(other.placementHeuristicIncomingLoadFactor_), placementHeuristicEmptySpacePercent_(other.placementHeuristicEmptySpacePercent_), defragmentationScopedAlgorithmEnabled_(other.defragmentationScopedAlgorithmEnabled_), placementStrategy_(other.placementStrategy_), defragmentationEmptyNodeWeight_(other.defragmentationEmptyNodeWeight_), defragmentationNonEmptyNodeWeight_(other.defragmentationNonEmptyNodeWeight_), balancingByPercentage_(other.balancingByPercentage_), indexInGlobalDomain_(other.indexInGlobalDomain_), indexInLocalDomain_(other.indexInLocalDomain_), indexInTotalDomain_(other.indexInTotalDomain_) { } Metric & Metric::operator = (Metric && other) { if (this != &other) { name_ = move(other.name_); weight_ = other.weight_; balancingThreshold_ = other.balancingThreshold_; blockList_ = move(other.blockList_); isBalanced_ = other.isBalanced_; activityThreshold_ = other.activityThreshold_; clusterTotalCapacity_ = other.clusterTotalCapacity_; clusterBufferedCapacity_ = other.clusterBufferedCapacity_; clusterLoad_ = other.clusterLoad_; isDefrag_ = other.isDefrag_; defragEmptyNodeCount_ = other.defragEmptyNodeCount_; defragEmptyNodeLoadThreshold_ = other.defragEmptyNodeLoadThreshold_; reservationLoad_ = other.reservationLoad_; defragEmptyNodesDistribution_ = other.defragEmptyNodesDistribution_; placementHeuristicIncomingLoadFactor_ = other.placementHeuristicIncomingLoadFactor_; placementHeuristicEmptySpacePercent_ = other.placementHeuristicEmptySpacePercent_; defragmentationScopedAlgorithmEnabled_ = other.defragmentationScopedAlgorithmEnabled_; placementStrategy_ = other.placementStrategy_; defragmentationEmptyNodeWeight_ = other.defragmentationEmptyNodeWeight_; defragmentationNonEmptyNodeWeight_ = other.defragmentationNonEmptyNodeWeight_; balancingByPercentage_ = other.balancingByPercentage_; indexInGlobalDomain_ = other.indexInGlobalDomain_; indexInLocalDomain_ = other.indexInLocalDomain_; indexInTotalDomain_ = other.indexInTotalDomain_; } return *this; } bool Metric::get_ShouldCalculateBeneficialNodesForPlacement() const { return isDefrag_ && ( placementHeuristicIncomingLoadFactor_ != 0 || placementHeuristicEmptySpacePercent_ != 0 || defragmentationScopedAlgorithmEnabled_ ); } void Metric::WriteTo(TextWriter& writer, FormatOptions const&) const { writer.Write("{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}/{9}", name_, weight_, balancingThreshold_, isBalanced_, blockList_, activityThreshold_, clusterTotalCapacity_, clusterBufferedCapacity_, clusterLoad_, balancingByPercentage_); if (isDefrag_) { writer.Write("/{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}/{9}/{10}", isDefrag_, defragEmptyNodeLoadThreshold_, reservationLoad_, defragEmptyNodeCount_, defragEmptyNodesDistribution_, placementHeuristicIncomingLoadFactor_, placementHeuristicEmptySpacePercent_, defragmentationScopedAlgorithmEnabled_, defragmentationEmptyNodeWeight_, placementStrategy_, defragmentationNonEmptyNodeWeight_); } } void Reliability::LoadBalancingComponent::WriteToTextWriter(Common::TextWriter & writer, Metric::DefragDistributionType const & val) { switch (val) { case Metric::DefragDistributionType::SpreadAcrossFDs_UDs: writer.Write("SpreadAcrossFDsAndUDs"); break; case Metric::DefragDistributionType::NumberOfEmptyNodes: writer.Write("NoDistribution"); break; } } void Reliability::LoadBalancingComponent::WriteToTextWriter(Common::TextWriter & writer, Metric::PlacementStrategy const & val) { switch (val) { case Metric::PlacementStrategy::Balancing: writer.Write("Balancing"); break; case Metric::PlacementStrategy::ReservationAndBalance: writer.Write("ReservationAndBalance"); break; case Metric::PlacementStrategy::Reservation: writer.Write("Reservation"); break; case Metric::PlacementStrategy::ReservationAndPack: writer.Write("ReservationAndPack"); break; case Metric::PlacementStrategy::Defragmentation: writer.Write("Defragmentation"); break; } }
9,030
2,557
//: C12:ByteTest.cpp // From Thinking in C++, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 2000 // Copyright notice in Copyright.txt #include "Byte.h" #include <fstream> using namespace std; ofstream out("ByteTest.out"); void k(Byte& b1, Byte& b2) { b1 = b1 * b2 + b2 % b1; #define TRY2(OP) \ out << "b1 = "; b1.print(out); \ out << ", b2 = "; b2.print(out); \ out << "; b1 " #OP " b2 produces "; \ (b1 OP b2).print(out); \ out << endl; b1 = 9; b2 = 47; TRY2(+) TRY2(-) TRY2(*) TRY2(/) TRY2(%) TRY2(^) TRY2(&) TRY2(|) TRY2(<<) TRY2(>>) TRY2(+=) TRY2(-=) TRY2(*=) TRY2(/=) TRY2(%=) TRY2(^=) TRY2(&=) TRY2(|=) TRY2(>>=) TRY2(<<=) TRY2(=) // Assignment operator // Conditionals: #define TRYC2(OP) \ out << "b1 = "; b1.print(out); \ out << ", b2 = "; b2.print(out); \ out << "; b1 " #OP " b2 produces "; \ out << (b1 OP b2); \ out << endl; b1 = 9; b2 = 47; TRYC2(<) TRYC2(>) TRYC2(==) TRYC2(!=) TRYC2(<=) TRYC2(>=) TRYC2(&&) TRYC2(||) // Chained assignment: Byte b3 = 92; b1 = b2 = b3; } int main() { out << "member functions:" << endl; Byte b1(47), b2(9); k(b1, b2); } ///:~
1,239
632
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_MODELEDITOR_SCENE_VIEW_3D_HPP_INCLUDED #define CAFU_MODELEDITOR_SCENE_VIEW_3D_HPP_INCLUDED #include "../Generic3DWindow.hpp" #include "Models/Model_cmdl.hpp" #include "Renderer3D.hpp" namespace MatSys { class RenderMaterialT; } namespace ModelEditor { class ChildFrameT; class SceneView3DT : public Generic3DWindowT { public: SceneView3DT(ChildFrameT* Parent); Vector3fT TraceCameraRay(const wxPoint& RefPtWin, AnimPoseT::TraceResultT& ModelTR) const; private: // Implement virtual methods of Generic3DViewT base class. virtual Vector3fT GetRefPtWorld(const wxPoint& RefPtWin) const; virtual void InfoCameraChanged(); virtual void InfoRightMouseClick(wxMouseEvent& ME); /// Renders the skeleton of the model with the given joints and matrices. void RenderSkeleton(const ArrayT<CafuModelT::JointT>& Joints, const ArrayT<MatrixT>& Matrices, bool IsSubModel) const; /// Renders a single pass of the scene. void RenderPass() const; ChildFrameT* m_Parent; Renderer3DT m_Renderer; ///< Performs the 3D rendering in our window. unsigned long m_TimeOfLastPaint; ///< The time at which the OnPaint() event handler was last called. ArrayT<bool> m_JointSelCache; ///< Stores for each joint whether it is currently selected, updated every frame. // Event handlers. void OnKeyDown (wxKeyEvent& KE); void OnMouseLeftDown(wxMouseEvent& ME); ///< We also handle "double-click" events in this method (use ME.ButtonDClick() for distinction). void OnMouseLeftUp (wxMouseEvent& ME); void OnMouseMove (wxMouseEvent& ME); void OnContextMenu (wxContextMenuEvent& CE); void OnPaint (wxPaintEvent& PE); void OnIdle (wxIdleEvent& IE); DECLARE_EVENT_TABLE() }; } #endif
2,141
671
//===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Hacks and fun related to the code rewriter. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Frontend/ASTConsumers.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/Attr.h" #include "clang/AST/ParentMap.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Config/config.h" #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Core/Rewriter.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include <memory> #if CLANG_ENABLE_OBJC_REWRITER using namespace clang; using llvm::utostr; namespace { class RewriteModernObjC : public ASTConsumer { protected: enum { BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)), block, ... */ BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */ BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the __block variable */ BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy helpers */ BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose support routines */ BLOCK_BYREF_CURRENT_MAX = 256 }; enum { BLOCK_NEEDS_FREE = (1 << 24), BLOCK_HAS_COPY_DISPOSE = (1 << 25), BLOCK_HAS_CXX_OBJ = (1 << 26), BLOCK_IS_GC = (1 << 27), BLOCK_IS_GLOBAL = (1 << 28), BLOCK_HAS_DESCRIPTOR = (1 << 29) }; Rewriter Rewrite; DiagnosticsEngine &Diags; const LangOptions &LangOpts; ASTContext *Context; SourceManager *SM; TranslationUnitDecl *TUDecl; FileID MainFileID; const char *MainFileStart, *MainFileEnd; Stmt *CurrentBody; ParentMap *PropParentMap; // created lazily. std::string InFileName; std::unique_ptr<raw_ostream> OutFile; std::string Preamble; TypeDecl *ProtocolTypeDecl; VarDecl *GlobalVarDecl; Expr *GlobalConstructionExp; unsigned RewriteFailedDiag; unsigned GlobalBlockRewriteFailedDiag; // ObjC string constant support. unsigned NumObjCStringLiterals; VarDecl *ConstantStringClassReference; RecordDecl *NSStringRecord; // ObjC foreach break/continue generation support. int BcLabelCount; unsigned TryFinallyContainsReturnDiag; // Needed for super. ObjCMethodDecl *CurMethodDef; RecordDecl *SuperStructDecl; RecordDecl *ConstantStringDecl; FunctionDecl *MsgSendFunctionDecl; FunctionDecl *MsgSendSuperFunctionDecl; FunctionDecl *MsgSendStretFunctionDecl; FunctionDecl *MsgSendSuperStretFunctionDecl; FunctionDecl *MsgSendFpretFunctionDecl; FunctionDecl *GetClassFunctionDecl; FunctionDecl *GetMetaClassFunctionDecl; FunctionDecl *GetSuperClassFunctionDecl; FunctionDecl *SelGetUidFunctionDecl; FunctionDecl *CFStringFunctionDecl; FunctionDecl *SuperConstructorFunctionDecl; FunctionDecl *CurFunctionDef; /* Misc. containers needed for meta-data rewrite. */ SmallVector<ObjCImplementationDecl *, 8> ClassImplementation; SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation; llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs; llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols; llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces; llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags; SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen; /// DefinedNonLazyClasses - List of defined "non-lazy" classes. SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses; /// DefinedNonLazyCategories - List of defined "non-lazy" categories. SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories; SmallVector<Stmt *, 32> Stmts; SmallVector<int, 8> ObjCBcLabelNo; // Remember all the @protocol(<expr>) expressions. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls; llvm::DenseSet<uint64_t> CopyDestroyCache; // Block expressions. SmallVector<BlockExpr *, 32> Blocks; SmallVector<int, 32> InnerDeclRefsCount; SmallVector<DeclRefExpr *, 32> InnerDeclRefs; SmallVector<DeclRefExpr *, 32> BlockDeclRefs; // Block related declarations. SmallVector<ValueDecl *, 8> BlockByCopyDecls; llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet; SmallVector<ValueDecl *, 8> BlockByRefDecls; llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet; llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo; llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls; llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; llvm::DenseMap<ObjCInterfaceDecl *, llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars; // ivar bitfield grouping containers llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups; llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber; // This container maps an <class, group number for ivar> tuple to the type // of the struct where the bitfield belongs. llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType; SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen; // This maps an original source AST to it's rewritten form. This allows // us to avoid rewriting the same node twice (which is very uncommon). // This is needed to support some of the exotic property rewriting. llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes; // Needed for header files being rewritten bool IsHeader; bool SilenceRewriteMacroWarning; bool GenerateLineInfo; bool objc_impl_method; bool DisableReplaceStmt; class DisableReplaceStmtScope { RewriteModernObjC &R; bool SavedValue; public: DisableReplaceStmtScope(RewriteModernObjC &R) : R(R), SavedValue(R.DisableReplaceStmt) { R.DisableReplaceStmt = true; } ~DisableReplaceStmtScope() { R.DisableReplaceStmt = SavedValue; } }; void InitializeCommon(ASTContext &context); public: llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames; // Top Level Driver code. bool HandleTopLevelDecl(DeclGroupRef D) override { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) { if (!Class->isThisDeclarationADefinition()) { RewriteForwardClassDecl(D); break; } else { // Keep track of all interface declarations seen. ObjCInterfacesSeen.push_back(Class); break; } } if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) { if (!Proto->isThisDeclarationADefinition()) { RewriteForwardProtocolDecl(D); break; } } if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) { // Under modern abi, we cannot translate body of the function // yet until all class extensions and its implementation is seen. // This is because they may introduce new bitfields which must go // into their grouping struct. if (FDecl->isThisDeclarationADefinition() && // Not c functions defined inside an objc container. !FDecl->isTopLevelDeclInObjCContainer()) { FunctionDefinitionsSeen.push_back(FDecl); break; } } HandleTopLevelSingleDecl(*I); } return true; } void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); else RewriteObjCQualifiedInterfaceTypes(TD); } } } void HandleTopLevelSingleDecl(Decl *D); void HandleDeclInMainFile(Decl *D); RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, DiagnosticsEngine &D, const LangOptions &LOpts, bool silenceMacroWarn, bool LineInfo); ~RewriteModernObjC() override {} void HandleTranslationUnit(ASTContext &C) override; void ReplaceStmt(Stmt *Old, Stmt *New) { ReplaceStmtWithRange(Old, New, Old->getSourceRange()); } void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) { assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's"); Stmt *ReplacingStmt = ReplacedNodes[Old]; if (ReplacingStmt) return; // We can't rewrite the same node twice. if (DisableReplaceStmt) return; // Measure the old text. int Size = Rewrite.getRangeSize(SrcRange); if (Size == -1) { Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) << Old->getSourceRange(); return; } // Get the new text. std::string SStr; llvm::raw_string_ostream S(SStr); New->printPretty(S, nullptr, PrintingPolicy(LangOpts)); const std::string &Str = S.str(); // If replacement succeeded or warning disabled return with no warning. if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) { ReplacedNodes[Old] = New; return; } if (SilenceRewriteMacroWarning) return; Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag) << Old->getSourceRange(); } void InsertText(SourceLocation Loc, StringRef Str, bool InsertAfter = true) { // If insertion succeeded or warning disabled return with no warning. if (!Rewrite.InsertText(Loc, Str, InsertAfter) || SilenceRewriteMacroWarning) return; Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); } void ReplaceText(SourceLocation Start, unsigned OrigLength, StringRef Str) { // If removal succeeded or warning disabled return with no warning. if (!Rewrite.ReplaceText(Start, OrigLength, Str) || SilenceRewriteMacroWarning) return; Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); } // Syntactic Rewriting. void RewriteRecordBody(RecordDecl *RD); void RewriteInclude(); void RewriteLineDirective(const Decl *D); void ConvertSourceLocationToLineDirective(SourceLocation Loc, std::string &LineString); void RewriteForwardClassDecl(DeclGroupRef D); void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG); void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString); void RewriteImplementations(); void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, ObjCImplementationDecl *IMD, ObjCCategoryImplDecl *CID); void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl); void RewriteImplementationDecl(Decl *Dcl); void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, ObjCMethodDecl *MDecl, std::string &ResultStr); void RewriteTypeIntoString(QualType T, std::string &ResultStr, const FunctionType *&FPRetType); void RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def=false); void RewriteCategoryDecl(ObjCCategoryDecl *Dcl); void RewriteProtocolDecl(ObjCProtocolDecl *Dcl); void RewriteForwardProtocolDecl(DeclGroupRef D); void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG); void RewriteMethodDeclaration(ObjCMethodDecl *Method); void RewriteProperty(ObjCPropertyDecl *prop); void RewriteFunctionDecl(FunctionDecl *FD); void RewriteBlockPointerType(std::string& Str, QualType Type); void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD); void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD); void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl); void RewriteTypeOfDecl(VarDecl *VD); void RewriteObjCQualifiedInterfaceTypes(Expr *E); std::string getIvarAccessString(ObjCIvarDecl *D); // Expression Rewriting. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S); Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp); Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo); Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo); Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp); Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp); Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp); Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp); Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp); Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp); Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp); Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp); Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S); Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S); Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S); Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, SourceLocation OrigEnd); Stmt *RewriteBreakStmt(BreakStmt *S); Stmt *RewriteContinueStmt(ContinueStmt *S); void RewriteCastExpr(CStyleCastExpr *CE); void RewriteImplicitCastObjCExpr(CastExpr *IE); // Computes ivar bitfield group no. unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV); // Names field decl. for ivar bitfield group. void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result); // Names struct type for ivar bitfield group. void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result); // Names symbol for ivar bitfield group field offset. void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result); // Given an ivar bitfield, it builds (or finds) its group record type. QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV); QualType SynthesizeBitfieldGroupStructType( ObjCIvarDecl *IV, SmallVectorImpl<ObjCIvarDecl *> &IVars); // Block rewriting. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D); // Block specific rewrite rules. void RewriteBlockPointerDecl(NamedDecl *VD); void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl); Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD); Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE); void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result); void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result); bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition); void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result); bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result); void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, std::string &Result); void Initialize(ASTContext &context) override; // Misc. AST transformation routines. Sometimes they end up calling // rewriting routines on the new ASTs. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD, ArrayRef<Expr *> Args, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method); Stmt *SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc=SourceLocation(), SourceLocation EndLoc=SourceLocation()); void SynthCountByEnumWithState(std::string &buf); void SynthMsgSendFunctionDecl(); void SynthMsgSendSuperFunctionDecl(); void SynthMsgSendStretFunctionDecl(); void SynthMsgSendFpretFunctionDecl(); void SynthMsgSendSuperStretFunctionDecl(); void SynthGetClassFunctionDecl(); void SynthGetMetaClassFunctionDecl(); void SynthGetSuperClassFunctionDecl(); void SynthSelGetUidFunctionDecl(); void SynthSuperConstructorFunctionDecl(); // Rewriting metadata template<typename MethodIterator> void RewriteObjCMethodsMetaData(MethodIterator MethodBegin, MethodIterator MethodEnd, bool IsInstanceMethod, StringRef prefix, StringRef ClassName, std::string &Result); void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol, std::string &Result); void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result); void RewriteClassSetupInitHook(std::string &Result); void RewriteMetaDataIntoBuffer(std::string &Result); void WriteImageInfo(std::string &Result); void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl, std::string &Result); void RewriteCategorySetupInitHook(std::string &Result); // Rewriting ivar void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result); Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV); std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag); std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag); std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc); std::string SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef funcName, unsigned hasCopy); Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp); void SynthesizeBlockLiterals(SourceLocation FunLocStart, StringRef FunName); FunctionDecl *SynthBlockInitFunctionDecl(StringRef name); Stmt *SynthBlockInitExpr(BlockExpr *Exp, const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs); // Misc. helper routines. QualType getProtocolType(); void WarnAboutReturnGotoStmts(Stmt *S); void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND); void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); bool IsDeclStmtInForeachHeader(DeclStmt *DS); void CollectBlockDeclRefInfo(BlockExpr *Exp); void GetBlockDeclRefExprs(Stmt *S); void GetInnerBlockDeclRefExprs(Stmt *S, SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts); // We avoid calling Type::isBlockPointerType(), since it operates on the // canonical type. We only care if the top-level type is a closure pointer. bool isTopLevelBlockPointerType(QualType T) { return isa<BlockPointerType>(T); } /// convertBlockPointerToFunctionPointer - Converts a block-pointer type /// to a function pointer type and upon success, returns true; false /// otherwise. bool convertBlockPointerToFunctionPointer(QualType &T) { if (isTopLevelBlockPointerType(T)) { const auto *BPT = T->castAs<BlockPointerType>(); T = Context->getPointerType(BPT->getPointeeType()); return true; } return false; } bool convertObjCTypeToCStyleType(QualType &T); bool needToScanForQualifiers(QualType T); QualType getSuperStructType(); QualType getConstantStringStructType(); QualType convertFunctionTypeOfBlocks(const FunctionType *FT); void convertToUnqualifiedObjCType(QualType &T) { if (T->isObjCQualifiedIdType()) { bool isConst = T.isConstQualified(); T = isConst ? Context->getObjCIdType().withConst() : Context->getObjCIdType(); } else if (T->isObjCQualifiedClassType()) T = Context->getObjCClassType(); else if (T->isObjCObjectPointerType() && T->getPointeeType()->isObjCQualifiedInterfaceType()) { if (const ObjCObjectPointerType * OBJPT = T->getAsObjCInterfacePointerType()) { const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType(); T = QualType(IFaceT, 0); T = Context->getPointerType(T); } } } // FIXME: This predicate seems like it would be useful to add to ASTContext. bool isObjCType(QualType T) { if (!LangOpts.ObjC) return false; QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || OCT == Context->getCanonicalType(Context->getObjCClassType())) return true; if (const PointerType *PT = OCT->getAs<PointerType>()) { if (isa<ObjCInterfaceType>(PT->getPointeeType()) || PT->getPointeeType()->isObjCQualifiedIdType()) return true; } return false; } bool PointerTypeTakesAnyBlockArguments(QualType QT); bool PointerTypeTakesAnyObjCQualifiedType(QualType QT); void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); void QuoteDoublequotes(std::string &From, std::string &To) { for (unsigned i = 0; i < From.length(); i++) { if (From[i] == '"') To += "\\\""; else To += From[i]; } } QualType getSimpleFunctionType(QualType result, ArrayRef<QualType> args, bool variadic = false) { if (result == Context->getObjCInstanceType()) result = Context->getObjCIdType(); FunctionProtoType::ExtProtoInfo fpi; fpi.Variadic = variadic; return Context->getFunctionType(result, args, fpi); } // Helper function: create a CStyleCastExpr with trivial type source info. CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty, CastKind Kind, Expr *E) { TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation()); return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr, FPOptionsOverride(), TInfo, SourceLocation(), SourceLocation()); } bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const { IdentifierInfo* II = &Context->Idents.get("load"); Selector LoadSel = Context->Selectors.getSelector(0, &II); return OD->getClassMethod(LoadSel) != nullptr; } StringLiteral *getStringLiteral(StringRef Str) { QualType StrType = Context->getConstantArrayType( Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr, ArrayType::Normal, 0); return StringLiteral::Create(*Context, Str, StringLiteral::Ascii, /*Pascal=*/false, StrType, SourceLocation()); } }; } // end anonymous namespace void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D) { if (const FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) { for (const auto &I : fproto->param_types()) if (isTopLevelBlockPointerType(I)) { // All the args are checked/rewritten. Don't call twice! RewriteBlockPointerDecl(D); break; } } } void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) { const PointerType *PT = funcType->getAs<PointerType>(); if (PT && PointerTypeTakesAnyBlockArguments(funcType)) RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND); } static bool IsHeaderFile(const std::string &Filename) { std::string::size_type DotPos = Filename.rfind('.'); if (DotPos == std::string::npos) { // no file extension return false; } std::string Ext = Filename.substr(DotPos + 1); // C header: .h // C++ header: .hh or .H; return Ext == "h" || Ext == "hh" || Ext == "H"; } RewriteModernObjC::RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS, DiagnosticsEngine &D, const LangOptions &LOpts, bool silenceMacroWarn, bool LineInfo) : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)), SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) { IsHeader = IsHeaderFile(inFile); RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "rewriting sub-expression within a macro (may not be correct)"); // FIXME. This should be an error. But if block is not called, it is OK. And it // may break including some headers. GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning, "rewriting block literal declared in global scope is not implemented"); TryFinallyContainsReturnDiag = Diags.getCustomDiagID( DiagnosticsEngine::Warning, "rewriter doesn't support user-specified control flow semantics " "for @try/@finally (code may not execute properly)"); } std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter( const std::string &InFile, std::unique_ptr<raw_ostream> OS, DiagnosticsEngine &Diags, const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) { return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning, LineInfo); } void RewriteModernObjC::InitializeCommon(ASTContext &context) { Context = &context; SM = &Context->getSourceManager(); TUDecl = Context->getTranslationUnitDecl(); MsgSendFunctionDecl = nullptr; MsgSendSuperFunctionDecl = nullptr; MsgSendStretFunctionDecl = nullptr; MsgSendSuperStretFunctionDecl = nullptr; MsgSendFpretFunctionDecl = nullptr; GetClassFunctionDecl = nullptr; GetMetaClassFunctionDecl = nullptr; GetSuperClassFunctionDecl = nullptr; SelGetUidFunctionDecl = nullptr; CFStringFunctionDecl = nullptr; ConstantStringClassReference = nullptr; NSStringRecord = nullptr; CurMethodDef = nullptr; CurFunctionDef = nullptr; GlobalVarDecl = nullptr; GlobalConstructionExp = nullptr; SuperStructDecl = nullptr; ProtocolTypeDecl = nullptr; ConstantStringDecl = nullptr; BcLabelCount = 0; SuperConstructorFunctionDecl = nullptr; NumObjCStringLiterals = 0; PropParentMap = nullptr; CurrentBody = nullptr; DisableReplaceStmt = false; objc_impl_method = false; // Get the ID and start/end of the main file. MainFileID = SM->getMainFileID(); llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID); MainFileStart = MainBuf.getBufferStart(); MainFileEnd = MainBuf.getBufferEnd(); Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts()); } //===----------------------------------------------------------------------===// // Top Level Driver Code //===----------------------------------------------------------------------===// void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) { if (Diags.hasErrorOccurred()) return; // Two cases: either the decl could be in the main file, or it could be in a // #included file. If the former, rewrite it now. If the later, check to see // if we rewrote the #include/#import. SourceLocation Loc = D->getLocation(); Loc = SM->getExpansionLoc(Loc); // If this is for a builtin, ignore it. if (Loc.isInvalid()) return; // Look for built-in declarations that we need to refer during the rewrite. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { RewriteFunctionDecl(FD); } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) { // declared in <Foundation/NSString.h> if (FVD->getName() == "_NSConstantStringClassReference") { ConstantStringClassReference = FVD; return; } } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) { RewriteCategoryDecl(CD); } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) { if (PD->isThisDeclarationADefinition()) RewriteProtocolDecl(PD); } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) { // Recurse into linkage specifications for (DeclContext::decl_iterator DI = LSD->decls_begin(), DIEnd = LSD->decls_end(); DI != DIEnd; ) { if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) { if (!IFace->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; SourceLocation StartLoc = IFace->getBeginLoc(); do { if (isa<ObjCInterfaceDecl>(*DI) && !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() && StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; ++DI; } while (DI != DIEnd); RewriteForwardClassDecl(DG); continue; } else { // Keep track of all interface declarations seen. ObjCInterfacesSeen.push_back(IFace); ++DI; continue; } } if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) { if (!Proto->isThisDeclarationADefinition()) { SmallVector<Decl *, 8> DG; SourceLocation StartLoc = Proto->getBeginLoc(); do { if (isa<ObjCProtocolDecl>(*DI) && !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() && StartLoc == (*DI)->getBeginLoc()) DG.push_back(*DI); else break; ++DI; } while (DI != DIEnd); RewriteForwardProtocolDecl(DG); continue; } } HandleTopLevelSingleDecl(*DI); ++DI; } } // If we have a decl in the main file, see if we should rewrite it. if (SM->isWrittenInMainFile(Loc)) return HandleDeclInMainFile(D); } //===----------------------------------------------------------------------===// // Syntactic (non-AST) Rewriting Code //===----------------------------------------------------------------------===// void RewriteModernObjC::RewriteInclude() { SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID); StringRef MainBuf = SM->getBufferData(MainFileID); const char *MainBufStart = MainBuf.begin(); const char *MainBufEnd = MainBuf.end(); size_t ImportLen = strlen("import"); // Loop over the whole file, looking for includes. for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) { if (*BufPtr == '#') { if (++BufPtr == MainBufEnd) return; while (*BufPtr == ' ' || *BufPtr == '\t') if (++BufPtr == MainBufEnd) return; if (!strncmp(BufPtr, "import", ImportLen)) { // replace import with include SourceLocation ImportLoc = LocStart.getLocWithOffset(BufPtr-MainBufStart); ReplaceText(ImportLoc, ImportLen, "include"); BufPtr += ImportLen; } } } } static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl, ObjCIvarDecl *IvarDecl, std::string &Result) { Result += "OBJC_IVAR_$_"; Result += IDecl->getName(); Result += "$"; Result += IvarDecl->getName(); } std::string RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface(); // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(ClassDecl, D, IvarOffsetName); std::string S = "(*("; QualType IvarT = D->getType(); if (D->isBitField()) IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl(); RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) CDecl = CatDecl->getClassInterface(); std::string RecName = std::string(CDecl->getName()); RecName += "_IMPL"; RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), Context->UnsignedIntTy, SourceLocation()); Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero); ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Zero); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(D->getNameAsString()), IvarT, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary); IvarT = Context->getDecltypeType(ME, ME->getType()); } } convertObjCTypeToCStyleType(IvarT); QualType castT = Context->getPointerType(IvarT); std::string TypeString(castT.getAsString(Context->getPrintingPolicy())); S += TypeString; S += ")"; // ((char *)self + IVAR_OFFSET_SYMBOL_NAME) S += "((char *)self + "; S += IvarOffsetName; S += "))"; if (D->isBitField()) { S += "."; S += D->getNameAsString(); } ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D); return S; } /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not /// been found in the class implementation. In this case, it must be synthesized. static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, ObjCPropertyDecl *PD, bool getter) { auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName() : PD->getSetterName()); return !OMD || OMD->isSynthesizedAccessorStub(); } void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, ObjCImplementationDecl *IMD, ObjCCategoryImplDecl *CID) { static bool objcGetPropertyDefined = false; static bool objcSetPropertyDefined = false; SourceLocation startGetterSetterLoc; if (PID->getBeginLoc().isValid()) { SourceLocation startLoc = PID->getBeginLoc(); InsertText(startLoc, "// "); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synthesize location"); const char *semiBuf = strchr(startBuf, ';'); assert((*semiBuf == ';') && "@synthesize: can't find ';'"); startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1); } else startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc(); if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) return; // FIXME: is this correct? // Generate the 'getter' function. ObjCPropertyDecl *PD = PID->getPropertyDecl(); ObjCIvarDecl *OID = PID->getPropertyIvarDecl(); assert(IMD && OID && "Synthesized ivars must be attached to @implementation"); unsigned Attributes = PD->getPropertyAttributes(); if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) { bool GenGetProperty = !(Attributes & ObjCPropertyAttribute::kind_nonatomic) && (Attributes & (ObjCPropertyAttribute::kind_retain | ObjCPropertyAttribute::kind_copy)); std::string Getr; if (GenGetProperty && !objcGetPropertyDefined) { objcGetPropertyDefined = true; // FIXME. Is this attribute correct in all cases? Getr = "\nextern \"C\" __declspec(dllimport) " "id objc_getProperty(id, SEL, long, bool);\n"; } RewriteObjCMethodDecl(OID->getContainingInterface(), PID->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. // See objc-act.c:objc_synthesize_new_getter() for details. if (GenGetProperty) { // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) Getr += "typedef "; const FunctionType *FPRetType = nullptr; RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr, FPRetType); Getr += " _TYPE"; if (FPRetType) { Getr += ")"; // close the precedence "scope" for "*". // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){ Getr += "("; for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { if (i) Getr += ", "; std::string ParamStr = FT->getParamType(i).getAsString(Context->getPrintingPolicy()); Getr += ParamStr; } if (FT->isVariadic()) { if (FT->getNumParams()) Getr += ", "; Getr += "..."; } Getr += ")"; } else Getr += "()"; } Getr += ";\n"; Getr += "return (_TYPE)"; Getr += "objc_getProperty(self, _cmd, "; RewriteIvarOffsetComputation(OID, Getr); Getr += ", 1)"; } else Getr += "return " + getIvarAccessString(OID); Getr += "; }"; InsertText(startGetterSetterLoc, Getr); } if (PD->isReadOnly() || !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/)) return; // Generate the 'setter' function. std::string Setr; bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain | ObjCPropertyAttribute::kind_copy); if (GenSetProperty && !objcSetPropertyDefined) { objcSetPropertyDefined = true; // FIXME. Is this attribute correct in all cases? Setr = "\nextern \"C\" __declspec(dllimport) " "void objc_setProperty (id, SEL, long, id, bool, bool);\n"; } RewriteObjCMethodDecl(OID->getContainingInterface(), PID->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. // See objc-act.c:objc_synthesize_new_setter() for details. if (GenSetProperty) { Setr += "objc_setProperty (self, _cmd, "; RewriteIvarOffsetComputation(OID, Setr); Setr += ", (id)"; Setr += PD->getName(); Setr += ", "; if (Attributes & ObjCPropertyAttribute::kind_nonatomic) Setr += "0, "; else Setr += "1, "; if (Attributes & ObjCPropertyAttribute::kind_copy) Setr += "1)"; else Setr += "0)"; } else { Setr += getIvarAccessString(OID) + " = "; Setr += PD->getName(); } Setr += "; }\n"; InsertText(startGetterSetterLoc, Setr); } static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl, std::string &typedefString) { typedefString += "\n#ifndef _REWRITER_typedef_"; typedefString += ForwardDecl->getNameAsString(); typedefString += "\n"; typedefString += "#define _REWRITER_typedef_"; typedefString += ForwardDecl->getNameAsString(); typedefString += "\n"; typedefString += "typedef struct objc_object "; typedefString += ForwardDecl->getNameAsString(); // typedef struct { } _objc_exc_Classname; typedefString += ";\ntypedef struct {} _objc_exc_"; typedefString += ForwardDecl->getNameAsString(); typedefString += ";\n#endif\n"; } void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl, const std::string &typedefString) { SourceLocation startLoc = ClassDecl->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *semiPtr = strchr(startBuf, ';'); // Replace the @class with typedefs corresponding to the classes. ReplaceText(startLoc, semiPtr-startBuf+1, typedefString); } void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) { std::string typedefString; for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) { if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) { if (I == D.begin()) { // Translate to typedef's that forward reference structs with the same name // as the class. As a convenience, we include the original declaration // as a comment. typedefString += "// @class "; typedefString += ForwardDecl->getNameAsString(); typedefString += ";"; } RewriteOneForwardClassDecl(ForwardDecl, typedefString); } else HandleTopLevelSingleDecl(*I); } DeclGroupRef::iterator I = D.begin(); RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString); } void RewriteModernObjC::RewriteForwardClassDecl( const SmallVectorImpl<Decl *> &D) { std::string typedefString; for (unsigned i = 0; i < D.size(); i++) { ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]); if (i == 0) { typedefString += "// @class "; typedefString += ForwardDecl->getNameAsString(); typedefString += ";"; } RewriteOneForwardClassDecl(ForwardDecl, typedefString); } RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString); } void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) { // When method is a synthesized one, such as a getter/setter there is // nothing to rewrite. if (Method->isImplicit()) return; SourceLocation LocStart = Method->getBeginLoc(); SourceLocation LocEnd = Method->getEndLoc(); if (SM->getExpansionLineNumber(LocEnd) > SM->getExpansionLineNumber(LocStart)) { InsertText(LocStart, "#if 0\n"); ReplaceText(LocEnd, 1, ";\n#endif\n"); } else { InsertText(LocStart, "// "); } } void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) { SourceLocation Loc = prop->getAtLoc(); ReplaceText(Loc, 0, "// "); // FIXME: handle properties that are declared across multiple lines. } void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { SourceLocation LocStart = CatDecl->getBeginLoc(); // FIXME: handle category headers that are declared across multiple lines. if (CatDecl->getIvarRBraceLoc().isValid()) { ReplaceText(LocStart, 1, "/** "); ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ "); } else { ReplaceText(LocStart, 0, "// "); } for (auto *I : CatDecl->instance_properties()) RewriteProperty(I); for (auto *I : CatDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : CatDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. ReplaceText(CatDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { SourceLocation LocStart = PDecl->getBeginLoc(); assert(PDecl->isThisDeclarationADefinition()); // FIXME: handle protocol headers that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); for (auto *I : PDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : PDecl->class_methods()) RewriteMethodDeclaration(I); for (auto *I : PDecl->instance_properties()) RewriteProperty(I); // Lastly, comment out the @end. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin(); ReplaceText(LocEnd, strlen("@end"), "/* @end */\n"); // Must comment out @optional/@required const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); for (const char *p = startBuf; p < endBuf; p++) { if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) { SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */"); } else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) { SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf); ReplaceText(OptionalLoc, strlen("@required"), "/* @required */"); } } } void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) { SourceLocation LocStart = (*D.begin())->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); } void RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) { SourceLocation LocStart = DG[0]->getBeginLoc(); if (LocStart.isInvalid()) llvm_unreachable("Invalid SourceLocation"); // FIXME: handle forward protocol that are declared across multiple lines. ReplaceText(LocStart, 0, "// "); } void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr, const FunctionType *&FPRetType) { if (T->isObjCQualifiedIdType()) ResultStr += "id"; else if (T->isFunctionPointerType() || T->isBlockPointerType()) { // needs special handling, since pointer-to-functions have special // syntax (where a decaration models use). QualType retType = T; QualType PointeeTy; if (const PointerType* PT = retType->getAs<PointerType>()) PointeeTy = PT->getPointeeType(); else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>()) PointeeTy = BPT->getPointeeType(); if ((FPRetType = PointeeTy->getAs<FunctionType>())) { ResultStr += FPRetType->getReturnType().getAsString(Context->getPrintingPolicy()); ResultStr += "(*"; } } else ResultStr += T.getAsString(Context->getPrintingPolicy()); } void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl, ObjCMethodDecl *OMD, std::string &ResultStr) { //fprintf(stderr,"In RewriteObjCMethodDecl\n"); const FunctionType *FPRetType = nullptr; ResultStr += "\nstatic "; RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType); ResultStr += " "; // Unique method name std::string NameStr; if (OMD->isInstanceMethod()) NameStr += "_I_"; else NameStr += "_C_"; NameStr += IDecl->getNameAsString(); NameStr += "_"; if (ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) { NameStr += CID->getNameAsString(); NameStr += "_"; } // Append selector names, replacing ':' with '_' { std::string selString = OMD->getSelector().getAsString(); int len = selString.size(); for (int i = 0; i < len; i++) if (selString[i] == ':') selString[i] = '_'; NameStr += selString; } // Remember this name for metadata emission MethodInternalNames[OMD] = NameStr; ResultStr += NameStr; // Rewrite arguments ResultStr += "("; // invisible arguments if (OMD->isInstanceMethod()) { QualType selfTy = Context->getObjCInterfaceType(IDecl); selfTy = Context->getPointerType(selfTy); if (!LangOpts.MicrosoftExt) { if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl))) ResultStr += "struct "; } // When rewriting for Microsoft, explicitly omit the structure name. ResultStr += IDecl->getNameAsString(); ResultStr += " *"; } else ResultStr += Context->getObjCClassType().getAsString( Context->getPrintingPolicy()); ResultStr += " self, "; ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy()); ResultStr += " _cmd"; // Method arguments. for (const auto *PDecl : OMD->parameters()) { ResultStr += ", "; if (PDecl->getType()->isObjCQualifiedIdType()) { ResultStr += "id "; ResultStr += PDecl->getNameAsString(); } else { std::string Name = PDecl->getNameAsString(); QualType QT = PDecl->getType(); // Make sure we convert "t (^)(...)" to "t (*)(...)". (void)convertBlockPointerToFunctionPointer(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); ResultStr += Name; } } if (OMD->isVariadic()) ResultStr += ", ..."; ResultStr += ") "; if (FPRetType) { ResultStr += ")"; // close the precedence "scope" for "*". // Now, emit the argument types (if any). if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) { ResultStr += "("; for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { if (i) ResultStr += ", "; std::string ParamStr = FT->getParamType(i).getAsString(Context->getPrintingPolicy()); ResultStr += ParamStr; } if (FT->isVariadic()) { if (FT->getNumParams()) ResultStr += ", "; ResultStr += "..."; } ResultStr += ")"; } else { ResultStr += "()"; } } } void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID); ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID); assert((IMD || CID) && "Unknown implementation type"); if (IMD) { if (IMD->getIvarRBraceLoc().isValid()) { ReplaceText(IMD->getBeginLoc(), 1, "/** "); ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ "); } else { InsertText(IMD->getBeginLoc(), "// "); } } else InsertText(CID->getBeginLoc(), "// "); for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { if (!OMD->getBody()) continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); ReplaceText(LocStart, endBuf-startBuf, ResultStr); } for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { if (!OMD->getBody()) continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); ReplaceText(LocStart, endBuf-startBuf, ResultStr); } for (auto *I : IMD ? IMD->property_impls() : CID->property_impls()) RewritePropertyImplDecl(I, IMD, CID); InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// "); } void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { // Do not synthesize more than once. if (ObjCSynthesizedStructs.count(ClassDecl)) return; // Make sure super class's are written before current class is written. ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass(); while (SuperClass) { RewriteInterfaceDecl(SuperClass); SuperClass = SuperClass->getSuperClass(); } std::string ResultStr; if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) { // we haven't seen a forward decl - generate a typedef. RewriteOneForwardClassDecl(ClassDecl, ResultStr); RewriteIvarOffsetSymbols(ClassDecl, ResultStr); RewriteObjCInternalStruct(ClassDecl, ResultStr); // Mark this typedef as having been written into its c++ equivalent. ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl()); for (auto *I : ClassDecl->instance_properties()) RewriteProperty(I); for (auto *I : ClassDecl->instance_methods()) RewriteMethodDeclaration(I); for (auto *I : ClassDecl->class_methods()) RewriteMethodDeclaration(I); // Lastly, comment out the @end. ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"), "/* @end */\n"); } } Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) { SourceRange OldRange = PseudoOp->getSourceRange(); // We just magically know some things about the structure of this // expression. ObjCMessageExpr *OldMsg = cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr( PseudoOp->getNumSemanticExprs() - 1)); // Because the rewriter doesn't allow us to rewrite rewritten code, // we need to suppress rewriting the sub-statements. Expr *Base; SmallVector<Expr*, 2> Args; { DisableReplaceStmtScope S(*this); // Rebuild the base expression if we have one. Base = nullptr; if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { Base = OldMsg->getInstanceReceiver(); Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); } unsigned numArgs = OldMsg->getNumArgs(); for (unsigned i = 0; i < numArgs; i++) { Expr *Arg = OldMsg->getArg(i); if (isa<OpaqueValueExpr>(Arg)) Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr(); Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg)); Args.push_back(Arg); } } // TODO: avoid this copy. SmallVector<SourceLocation, 1> SelLocs; OldMsg->getSelectorLocs(SelLocs); ObjCMessageExpr *NewMsg = nullptr; switch (OldMsg->getReceiverKind()) { case ObjCMessageExpr::Class: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getClassReceiverTypeInfo(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::Instance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), Base, OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::SuperClass: case ObjCMessageExpr::SuperInstance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getSuperLoc(), OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, OldMsg->getSuperType(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; } Stmt *Replacement = SynthMessageExpr(NewMsg); ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); return Replacement; } Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) { SourceRange OldRange = PseudoOp->getSourceRange(); // We just magically know some things about the structure of this // expression. ObjCMessageExpr *OldMsg = cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit()); // Because the rewriter doesn't allow us to rewrite rewritten code, // we need to suppress rewriting the sub-statements. Expr *Base = nullptr; SmallVector<Expr*, 1> Args; { DisableReplaceStmtScope S(*this); // Rebuild the base expression if we have one. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) { Base = OldMsg->getInstanceReceiver(); Base = cast<OpaqueValueExpr>(Base)->getSourceExpr(); Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base)); } unsigned numArgs = OldMsg->getNumArgs(); for (unsigned i = 0; i < numArgs; i++) { Expr *Arg = OldMsg->getArg(i); if (isa<OpaqueValueExpr>(Arg)) Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr(); Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg)); Args.push_back(Arg); } } // Intentionally empty. SmallVector<SourceLocation, 1> SelLocs; ObjCMessageExpr *NewMsg = nullptr; switch (OldMsg->getReceiverKind()) { case ObjCMessageExpr::Class: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getClassReceiverTypeInfo(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::Instance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), Base, OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; case ObjCMessageExpr::SuperClass: case ObjCMessageExpr::SuperInstance: NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(), OldMsg->getValueKind(), OldMsg->getLeftLoc(), OldMsg->getSuperLoc(), OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance, OldMsg->getSuperType(), OldMsg->getSelector(), SelLocs, OldMsg->getMethodDecl(), Args, OldMsg->getRightLoc(), OldMsg->isImplicit()); break; } Stmt *Replacement = SynthMessageExpr(NewMsg); ReplaceStmtWithRange(PseudoOp, Replacement, OldRange); return Replacement; } /// SynthCountByEnumWithState - To print: /// ((NSUInteger (*) /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger)) /// (void *)objc_msgSend)((id)l_collection, /// sel_registerName( /// "countByEnumeratingWithState:objects:count:"), /// &enumState, /// (id *)__rw_items, (NSUInteger)16) /// void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) { buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, " "id *, _WIN_NSUInteger))(void *)objc_msgSend)"; buf += "\n\t\t"; buf += "((id)l_collection,\n\t\t"; buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),"; buf += "\n\t\t"; buf += "&enumState, " "(id *)__rw_items, (_WIN_NSUInteger)16)"; } /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach /// statement to exit to its outer synthesized loop. /// Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) { if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) return S; // replace break with goto __break_label std::string buf; SourceLocation startLoc = S->getBeginLoc(); buf = "goto __break_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("break"), buf); return nullptr; } void RewriteModernObjC::ConvertSourceLocationToLineDirective( SourceLocation Loc, std::string &LineString) { if (Loc.isFileID() && GenerateLineInfo) { LineString += "\n#line "; PresumedLoc PLoc = SM->getPresumedLoc(Loc); LineString += utostr(PLoc.getLine()); LineString += " \""; LineString += Lexer::Stringify(PLoc.getFilename()); LineString += "\"\n"; } } /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach /// statement to continue with its inner synthesized loop. /// Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) { if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back())) return S; // replace continue with goto __continue_label std::string buf; SourceLocation startLoc = S->getBeginLoc(); buf = "goto __continue_label_"; buf += utostr(ObjCBcLabelNo.back()); ReplaceText(startLoc, strlen("continue"), buf); return nullptr; } /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement. /// It rewrites: /// for ( type elem in collection) { stmts; } /// Into: /// { /// type elem; /// struct __objcFastEnumerationState enumState = { 0 }; /// id __rw_items[16]; /// id l_collection = (id)collection; /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState /// objects:__rw_items count:16]; /// if (limit) { /// unsigned long startMutations = *enumState.mutationsPtr; /// do { /// unsigned long counter = 0; /// do { /// if (startMutations != *enumState.mutationsPtr) /// objc_enumerationMutation(l_collection); /// elem = (type)enumState.itemsPtr[counter++]; /// stmts; /// __continue_label: ; /// } while (counter < limit); /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState /// objects:__rw_items count:16])); /// elem = nil; /// __break_label: ; /// } /// else /// elem = nil; /// } /// Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S, SourceLocation OrigEnd) { assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty"); assert(isa<ObjCForCollectionStmt>(Stmts.back()) && "ObjCForCollectionStmt Statement stack mismatch"); assert(!ObjCBcLabelNo.empty() && "ObjCForCollectionStmt - Label No stack empty"); SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); StringRef elementName; std::string elementTypeAsString; std::string buf; // line directive first. SourceLocation ForEachLoc = S->getForLoc(); ConvertSourceLocationToLineDirective(ForEachLoc, buf); buf += "{\n\t"; if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) { // type elem; NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl()); QualType ElementType = cast<ValueDecl>(D)->getType(); if (ElementType->isObjCQualifiedIdType() || ElementType->isObjCQualifiedInterfaceType()) // Simply use 'id' for all qualified types. elementTypeAsString = "id"; else elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy()); buf += elementTypeAsString; buf += " "; elementName = D->getName(); buf += elementName; buf += ";\n\t"; } else { DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement()); elementName = DR->getDecl()->getName(); ValueDecl *VD = DR->getDecl(); if (VD->getType()->isObjCQualifiedIdType() || VD->getType()->isObjCQualifiedInterfaceType()) // Simply use 'id' for all qualified types. elementTypeAsString = "id"; else elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy()); } // struct __objcFastEnumerationState enumState = { 0 }; buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t"; // id __rw_items[16]; buf += "id __rw_items[16];\n\t"; // id l_collection = (id) buf += "id l_collection = (id)"; // Find start location of 'collection' the hard way! const char *startCollectionBuf = startBuf; startCollectionBuf += 3; // skip 'for' startCollectionBuf = strchr(startCollectionBuf, '('); startCollectionBuf++; // skip '(' // find 'in' and skip it. while (*startCollectionBuf != ' ' || *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' || (*(startCollectionBuf+3) != ' ' && *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '(')) startCollectionBuf++; startCollectionBuf += 3; // Replace: "for (type element in" with string constructed thus far. ReplaceText(startLoc, startCollectionBuf - startBuf, buf); // Replace ')' in for '(' type elem in collection ')' with ';' SourceLocation rightParenLoc = S->getRParenLoc(); const char *rparenBuf = SM->getCharacterData(rightParenLoc); SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf); buf = ";\n\t"; // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState // objects:__rw_items count:16]; // which is synthesized into: // NSUInteger limit = // ((NSUInteger (*) // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger)) // (void *)objc_msgSend)((id)l_collection, // sel_registerName( // "countByEnumeratingWithState:objects:count:"), // (struct __objcFastEnumerationState *)&state, // (id *)__rw_items, (NSUInteger)16); buf += "_WIN_NSUInteger limit =\n\t\t"; SynthCountByEnumWithState(buf); buf += ";\n\t"; /// if (limit) { /// unsigned long startMutations = *enumState.mutationsPtr; /// do { /// unsigned long counter = 0; /// do { /// if (startMutations != *enumState.mutationsPtr) /// objc_enumerationMutation(l_collection); /// elem = (type)enumState.itemsPtr[counter++]; buf += "if (limit) {\n\t"; buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t"; buf += "do {\n\t\t"; buf += "unsigned long counter = 0;\n\t\t"; buf += "do {\n\t\t\t"; buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t"; buf += "objc_enumerationMutation(l_collection);\n\t\t\t"; buf += elementName; buf += " = ("; buf += elementTypeAsString; buf += ")enumState.itemsPtr[counter++];"; // Replace ')' in for '(' type elem in collection ')' with all of these. ReplaceText(lparenLoc, 1, buf); /// __continue_label: ; /// } while (counter < limit); /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState /// objects:__rw_items count:16])); /// elem = nil; /// __break_label: ; /// } /// else /// elem = nil; /// } /// buf = ";\n\t"; buf += "__continue_label_"; buf += utostr(ObjCBcLabelNo.back()); buf += ": ;"; buf += "\n\t\t"; buf += "} while (counter < limit);\n\t"; buf += "} while ((limit = "; SynthCountByEnumWithState(buf); buf += "));\n\t"; buf += elementName; buf += " = (("; buf += elementTypeAsString; buf += ")0);\n\t"; buf += "__break_label_"; buf += utostr(ObjCBcLabelNo.back()); buf += ": ;\n\t"; buf += "}\n\t"; buf += "else\n\t\t"; buf += elementName; buf += " = (("; buf += elementTypeAsString; buf += ")0);\n\t"; buf += "}\n"; // Insert all these *after* the statement body. // FIXME: If this should support Obj-C++, support CXXTryStmt if (isa<CompoundStmt>(S->getBody())) { SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1); InsertText(endBodyLoc, buf); } else { /* Need to treat single statements specially. For example: * * for (A *a in b) if (stuff()) break; * for (A *a in b) xxxyy; * * The following code simply scans ahead to the semi to find the actual end. */ const char *stmtBuf = SM->getCharacterData(OrigEnd); const char *semiBuf = strchr(stmtBuf, ';'); assert(semiBuf && "Can't find ';'"); SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1); InsertText(endBodyLoc, buf); } Stmts.pop_back(); ObjCBcLabelNo.pop_back(); return nullptr; } static void Write_RethrowObject(std::string &buf) { buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n"; buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n"; buf += "\tid rethrow;\n"; buf += "\t} _fin_force_rethow(_rethrow);"; } /// RewriteObjCSynchronizedStmt - /// This routine rewrites @synchronized(expr) stmt; /// into: /// objc_sync_enter(expr); /// @try stmt @finally { objc_sync_exit(expr); } /// Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @synchronized location"); std::string buf; SourceLocation SynchLoc = S->getAtSynchronizedLoc(); ConvertSourceLocationToLineDirective(SynchLoc, buf); buf += "{ id _rethrow = 0; id _sync_obj = (id)"; const char *lparenBuf = startBuf; while (*lparenBuf != '(') lparenBuf++; ReplaceText(startLoc, lparenBuf-startBuf+1, buf); buf = "; objc_sync_enter(_sync_obj);\n"; buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}"; buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}"; buf += "\n\tid sync_exit;"; buf += "\n\t} _sync_exit(_sync_obj);\n"; // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since // the sync expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc(); const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc); while (*RParenExprLocBuf != ')') RParenExprLocBuf--; RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf); SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc(); const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc); assert (*LBraceLocBuf == '{'); ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf); SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc(); assert((*SM->getCharacterData(startRBraceLoc) == '}') && "bogus @synchronized block"); buf = "} catch (id e) {_rethrow = e;}\n"; Write_RethrowObject(buf); buf += "}\n"; buf += "}\n"; ReplaceText(startRBraceLoc, 1, buf); return nullptr; } void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S) { // Perform a bottom up traversal of all children. for (Stmt *SubStmt : S->children()) if (SubStmt) WarnAboutReturnGotoStmts(SubStmt); if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) { Diags.Report(Context->getFullLoc(S->getBeginLoc()), TryFinallyContainsReturnDiag); } } Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { SourceLocation startLoc = S->getAtLoc(); ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */"); ReplaceText(S->getSubStmt()->getBeginLoc(), 1, "{ __AtAutoreleasePool __autoreleasepool; "); return nullptr; } Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) { ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt(); bool noCatch = S->getNumCatchStmts() == 0; std::string buf; SourceLocation TryLocation = S->getAtTryLoc(); ConvertSourceLocationToLineDirective(TryLocation, buf); if (finalStmt) { if (noCatch) buf += "{ id volatile _rethrow = 0;\n"; else { buf += "{ id volatile _rethrow = 0;\ntry {\n"; } } // Get the start location and compute the semi location. SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @try location"); if (finalStmt) ReplaceText(startLoc, 1, buf); else // @try -> try ReplaceText(startLoc, 1, ""); for (ObjCAtCatchStmt *Catch : S->catch_stmts()) { VarDecl *catchDecl = Catch->getCatchParamDecl(); startLoc = Catch->getBeginLoc(); bool AtRemoved = false; if (catchDecl) { QualType t = catchDecl->getType(); if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) { // Should be a pointer to a class. ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface(); if (IDecl) { std::string Result; ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result); startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @catch location"); SourceLocation rParenLoc = Catch->getRParenLoc(); const char *rParenBuf = SM->getCharacterData(rParenLoc); // _objc_exc_Foo *_e as argument to catch. Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString(); Result += " *_"; Result += catchDecl->getNameAsString(); Result += ")"; ReplaceText(startLoc, rParenBuf-startBuf+1, Result); // Foo *e = (Foo *)_e; Result.clear(); Result = "{ "; Result += IDecl->getNameAsString(); Result += " *"; Result += catchDecl->getNameAsString(); Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)"; Result += "_"; Result += catchDecl->getNameAsString(); Result += "; "; SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc(); ReplaceText(lBraceLoc, 1, Result); AtRemoved = true; } } } if (!AtRemoved) // @catch -> catch ReplaceText(startLoc, 1, ""); } if (finalStmt) { buf.clear(); SourceLocation FinallyLoc = finalStmt->getBeginLoc(); if (noCatch) { ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; } else { buf += "}\n"; ConvertSourceLocationToLineDirective(FinallyLoc, buf); buf += "catch (id e) {_rethrow = e;}\n"; } SourceLocation startFinalLoc = finalStmt->getBeginLoc(); ReplaceText(startFinalLoc, 8, buf); Stmt *body = finalStmt->getFinallyBody(); SourceLocation startFinalBodyLoc = body->getBeginLoc(); buf.clear(); Write_RethrowObject(buf); ReplaceText(startFinalBodyLoc, 1, buf); SourceLocation endFinalBodyLoc = body->getEndLoc(); ReplaceText(endFinalBodyLoc, 1, "}\n}"); // Now check for any return/continue/go statements within the @try. WarnAboutReturnGotoStmts(S->getTryBody()); } return nullptr; } // This can't be done with ReplaceStmt(S, ThrowExpr), since // the throw expression is typically a message expression that's already // been rewritten! (which implies the SourceLocation's are invalid). Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) { // Get the start location and compute the semi location. SourceLocation startLoc = S->getBeginLoc(); const char *startBuf = SM->getCharacterData(startLoc); assert((*startBuf == '@') && "bogus @throw location"); std::string buf; /* void objc_exception_throw(id) __attribute__((noreturn)); */ if (S->getThrowExpr()) buf = "objc_exception_throw("; else buf = "throw"; // handle "@ throw" correctly. const char *wBuf = strchr(startBuf, 'w'); assert((*wBuf == 'w') && "@throw: can't find 'w'"); ReplaceText(startLoc, wBuf-startBuf+1, buf); SourceLocation endLoc = S->getEndLoc(); const char *endBuf = SM->getCharacterData(endLoc); const char *semiBuf = strchr(endBuf, ';'); assert((*semiBuf == ';') && "@throw: can't find ';'"); SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf); if (S->getThrowExpr()) ReplaceText(semiLoc, 1, ");"); return nullptr; } Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) { // Create a new string expression. std::string StrEncoding; Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding); Expr *Replacement = getStringLiteral(StrEncoding); ReplaceStmt(Exp, Replacement); // Replace this subexpr in the parent. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return Replacement; } Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) { if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl"); // Create a call to sel_registerName("selName"). SmallVector<Expr*, 8> SelExprs; SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs); ReplaceStmt(Exp, SelExp); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return SelExp; } CallExpr * RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD, ArrayRef<Expr *> Args, SourceLocation StartLoc, SourceLocation EndLoc) { // Get the type, we will need to reference it in a couple spots. QualType msgSendType = FD->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType, VK_LValue, SourceLocation()); // Now, we cast the reference to a pointer to the objc_msgSend type. QualType pToFunc = Context->getPointerType(msgSendType); ImplicitCastExpr *ICE = ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay, DRE, nullptr, VK_PRValue, FPOptionsOverride()); const auto *FT = msgSendType->castAs<FunctionType>(); CallExpr *Exp = CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context), VK_PRValue, EndLoc, FPOptionsOverride()); return Exp; } static bool scanForProtocolRefs(const char *startBuf, const char *endBuf, const char *&startRef, const char *&endRef) { while (startBuf < endBuf) { if (*startBuf == '<') startRef = startBuf; // mark the start. if (*startBuf == '>') { if (startRef && *startRef == '<') { endRef = startBuf; // mark the end. return true; } return false; } startBuf++; } return false; } static void scanToNextArgument(const char *&argRef) { int angle = 0; while (*argRef != ')' && (*argRef != ',' || angle > 0)) { if (*argRef == '<') angle++; else if (*argRef == '>') angle--; argRef++; } assert(angle == 0 && "scanToNextArgument - bad protocol type syntax"); } bool RewriteModernObjC::needToScanForQualifiers(QualType T) { if (T->isObjCQualifiedIdType()) return true; if (const PointerType *PT = T->getAs<PointerType>()) { if (PT->getPointeeType()->isObjCQualifiedIdType()) return true; } if (T->isObjCObjectPointerType()) { T = T->getPointeeType(); return T->isObjCQualifiedInterfaceType(); } if (T->isArrayType()) { QualType ElemTy = Context->getBaseElementType(T); return needToScanForQualifiers(ElemTy); } return false; } void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) { QualType Type = E->getType(); if (needToScanForQualifiers(Type)) { SourceLocation Loc, EndLoc; if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) { Loc = ECE->getLParenLoc(); EndLoc = ECE->getRParenLoc(); } else { Loc = E->getBeginLoc(); EndLoc = E->getEndLoc(); } // This will defend against trying to rewrite synthesized expressions. if (Loc.isInvalid() || EndLoc.isInvalid()) return; const char *startBuf = SM->getCharacterData(Loc); const char *endBuf = SM->getCharacterData(EndLoc); const char *startRef = nullptr, *endRef = nullptr; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf); SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*"); InsertText(GreaterLoc, "*/"); } } } void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) { SourceLocation Loc; QualType Type; const FunctionProtoType *proto = nullptr; if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) { Loc = VD->getLocation(); Type = VD->getType(); } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) { Loc = FD->getLocation(); // Check for ObjC 'id' and class types that have been adorned with protocol // information (id<p>, C<p>*). The protocol references need to be rewritten! const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); assert(funcType && "missing function type"); proto = dyn_cast<FunctionProtoType>(funcType); if (!proto) return; Type = proto->getReturnType(); } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) { Loc = FD->getLocation(); Type = FD->getType(); } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) { Loc = TD->getLocation(); Type = TD->getUnderlyingType(); } else return; if (needToScanForQualifiers(Type)) { // Since types are unique, we need to scan the buffer. const char *endBuf = SM->getCharacterData(Loc); const char *startBuf = endBuf; while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart) startBuf--; // scan backward (from the decl location) for return type. const char *startRef = nullptr, *endRef = nullptr; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf); SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*"); InsertText(GreaterLoc, "*/"); } } if (!proto) return; // most likely, was a variable // Now check arguments. const char *startBuf = SM->getCharacterData(Loc); const char *startFuncBuf = startBuf; for (unsigned i = 0; i < proto->getNumParams(); i++) { if (needToScanForQualifiers(proto->getParamType(i))) { // Since types are unique, we need to scan the buffer. const char *endBuf = startBuf; // scan forward (from the decl location) for argument types. scanToNextArgument(endBuf); const char *startRef = nullptr, *endRef = nullptr; if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) { // Get the locations of the startRef, endRef. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startFuncBuf); SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startFuncBuf+1); // Comment out the protocol references. InsertText(LessLoc, "/*"); InsertText(GreaterLoc, "*/"); } startBuf = ++endBuf; } else { // If the function name is derived from a macro expansion, then the // argument buffer will not follow the name. Need to speak with Chris. while (*startBuf && *startBuf != ')' && *startBuf != ',') startBuf++; // scan forward (from the decl location) for argument types. startBuf++; } } } void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) { QualType QT = ND->getType(); const Type* TypePtr = QT->getAs<Type>(); if (!isa<TypeOfExprType>(TypePtr)) return; while (isa<TypeOfExprType>(TypePtr)) { const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); TypePtr = QT->getAs<Type>(); } // FIXME. This will not work for multiple declarators; as in: // __typeof__(a) b,c,d; std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy())); SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); const char *startBuf = SM->getCharacterData(DeclLoc); if (ND->getInit()) { std::string Name(ND->getNameAsString()); TypeAsString += " " + Name + " = "; Expr *E = ND->getInit(); SourceLocation startLoc; if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); const char *endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); } else { SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString); } } // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str); void RewriteModernObjC::SynthSelGetUidFunctionDecl() { IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); QualType getFuncType = getSimpleFunctionType(Context->getObjCSelType(), ArgTys); SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), SelGetUidIdent, getFuncType, nullptr, SC_Extern); } void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) { // declared in <objc/objc.h> if (FD->getIdentifier() && FD->getName() == "sel_registerName") { SelGetUidFunctionDecl = FD; return; } RewriteObjCQualifiedInterfaceTypes(FD); } void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) { std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); const char *argPtr = TypeString.c_str(); if (!strchr(argPtr, '^')) { Str += TypeString; return; } while (*argPtr) { Str += (*argPtr == '^' ? '*' : *argPtr); argPtr++; } } // FIXME. Consolidate this routine with RewriteBlockPointerType. void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) { QualType Type = VD->getType(); std::string TypeString(Type.getAsString(Context->getPrintingPolicy())); const char *argPtr = TypeString.c_str(); int paren = 0; while (*argPtr) { switch (*argPtr) { case '(': Str += *argPtr; paren++; break; case ')': Str += *argPtr; paren--; break; case '^': Str += '*'; if (paren == 1) Str += VD->getNameAsString(); break; default: Str += *argPtr; break; } argPtr++; } } void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) { SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); const FunctionType *funcType = FD->getType()->getAs<FunctionType>(); const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType); if (!proto) return; QualType Type = proto->getReturnType(); std::string FdStr = Type.getAsString(Context->getPrintingPolicy()); FdStr += " "; FdStr += FD->getName(); FdStr += "("; unsigned numArgs = proto->getNumParams(); for (unsigned i = 0; i < numArgs; i++) { QualType ArgType = proto->getParamType(i); RewriteBlockPointerType(FdStr, ArgType); if (i+1 < numArgs) FdStr += ", "; } if (FD->isVariadic()) { FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n"; } else FdStr += ");\n"; InsertText(FunLocStart, FdStr); } // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super); void RewriteModernObjC::SynthSuperConstructorFunctionDecl() { if (SuperConstructorFunctionDecl) return; IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys); SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...); void RewriteModernObjC::SynthMsgSendFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); argT = Context->getObjCSelType(); assert(!argT.isNull() && "Can't find 'SEL' type"); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void); void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper"); SmallVector<QualType, 2> ArgTys; ArgTys.push_back(Context->VoidTy); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...); void RewriteModernObjC::SynthMsgSendStretFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); argT = Context->getObjCSelType(); assert(!argT.isNull() && "Can't find 'SEL' type"); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendSuperStretFunctionDecl - // id objc_msgSendSuper_stret(void); void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper_stret"); SmallVector<QualType, 2> ArgTys; ArgTys.push_back(Context->VoidTy); QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(), ArgTys, /*variadic=*/true); MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...); void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() { IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret"); SmallVector<QualType, 16> ArgTys; QualType argT = Context->getObjCIdType(); assert(!argT.isNull() && "Can't find 'id' type"); ArgTys.push_back(argT); argT = Context->getObjCSelType(); assert(!argT.isNull() && "Can't find 'SEL' type"); ArgTys.push_back(argT); QualType msgSendType = getSimpleFunctionType(Context->DoubleTy, ArgTys, /*variadic=*/true); MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), msgSendIdent, msgSendType, nullptr, SC_Extern); } // SynthGetClassFunctionDecl - Class objc_getClass(const char *name); void RewriteModernObjC::SynthGetClassFunctionDecl() { IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), ArgTys); GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), getClassIdent, getClassType, nullptr, SC_Extern); } // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls); void RewriteModernObjC::SynthGetSuperClassFunctionDecl() { IdentifierInfo *getSuperClassIdent = &Context->Idents.get("class_getSuperclass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getObjCClassType()); QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), ArgTys); GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), getSuperClassIdent, getClassType, nullptr, SC_Extern); } // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name); void RewriteModernObjC::SynthGetMetaClassFunctionDecl() { IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass"); SmallVector<QualType, 16> ArgTys; ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst())); QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(), ArgTys); GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), getClassIdent, getClassType, nullptr, SC_Extern); } Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) { assert (Exp != nullptr && "Expected non-null ObjCStringLiteral"); QualType strType = getConstantStringStructType(); std::string S = "__NSConstantStringImpl_"; std::string tmpName = InFileName; unsigned i; for (i=0; i < tmpName.length(); i++) { char c = tmpName.at(i); // replace any non-alphanumeric characters with '_'. if (!isAlphanumeric(c)) tmpName[i] = '_'; } S += tmpName; S += "_"; S += utostr(NumObjCStringLiterals++); Preamble += "static __NSConstantStringImpl " + S; Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,"; Preamble += "0x000007c8,"; // utf8_str // The pretty printer for StringLiteral handles escape characters properly. std::string prettyBufS; llvm::raw_string_ostream prettyBuf(prettyBufS); Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts)); Preamble += prettyBuf.str(); Preamble += ","; Preamble += utostr(Exp->getString()->getByteLength()) + "};\n"; VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(S), strType, nullptr, SC_Static); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation()); Expr *Unop = UnaryOperator::Create( const_cast<ASTContext &>(*Context), DRE, UO_AddrOf, Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); // cast to NSConstantString * CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(), CK_CPointerToObjCPointerCast, Unop); ReplaceStmt(Exp, cast); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return cast; } Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) { unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, Exp->getValue()), Context->IntTy, Exp->getLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy, CK_BitCast, FlagExp); ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(), cast); ReplaceStmt(Exp, PE); return PE; } Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) { // synthesize declaration of helper functions needed in this routine. if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); // use objc_msgSend() for all. if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getBeginLoc(); SourceLocation EndLoc = Exp->getEndLoc(); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 4> MsgExprs; SmallVector<Expr*, 4> ClsExprs; // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument. ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod(); ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface(); IdentifierInfo *clsName = BoxingClass->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); // Create a call to sel_registerName("<BoxingMethod>:"), etc. // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; SelExprs.push_back( getStringLiteral(BoxingMethod->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // User provided sub-expression is the 3rd, and last, argument. Expr *subExpr = Exp->getSubExpr(); if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) { QualType type = ICE->getType(); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK = CK_BitCast; if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) CK = CK_IntegralToBoolean; subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr); } MsgExprs.push_back(subExpr); SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto PI : BoxingMethod->parameters()) ArgTypes.push_back(PI->getType()); QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); auto *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); ReplaceStmt(Exp, CE); return CE; } Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) { // synthesize declaration of helper functions needed in this routine. if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); // use objc_msgSend() for all. if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getBeginLoc(); SourceLocation EndLoc = Exp->getEndLoc(); // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSArrayFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSArrayFName("__NSContainer_literal"); FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName); DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr( *Context, NSArrayFD, false, NSArrayFType, VK_PRValue, SourceLocation()); SmallVector<Expr*, 16> InitExprs; unsigned NumElements = Exp->getNumElements(); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); InitExprs.push_back(count); for (unsigned i = 0; i < NumElements; i++) InitExprs.push_back(Exp->getElement(i)); Expr *NSArrayCallExpr = CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue, SourceLocation(), FPOptionsOverride()); FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("arr"), Context->getPointerType(Context->VoidPtrTy), nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ArrayLiteralME = MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD, ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); CStyleCastExpr * ArrayLiteralObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, ArrayLiteralME); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); // Create a call to objc_getClass("NSArray"). It will be th 1st argument. ObjCInterfaceDecl *Class = expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface(); IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod(); SelExprs.push_back( getStringLiteral(ArrayMethod->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // (const id [])objects MsgExprs.push_back(ArrayLiteralObjects); // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : ArrayMethod->parameters()) ArgTypes.push_back(PI->getType()); QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); ReplaceStmt(Exp, CE); return CE; } Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) { // synthesize declaration of helper functions needed in this routine. if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); // use objc_msgSend() for all. if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; SourceLocation StartLoc = Exp->getBeginLoc(); SourceLocation EndLoc = Exp->getEndLoc(); // Build the expression: __NSContainer_literal(int, ...).arr QualType IntQT = Context->IntTy; QualType NSDictFType = getSimpleFunctionType(Context->VoidTy, IntQT, true); std::string NSDictFName("__NSContainer_literal"); FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName); DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr( *Context, NSDictFD, false, NSDictFType, VK_PRValue, SourceLocation()); SmallVector<Expr*, 16> KeyExprs; SmallVector<Expr*, 16> ValueExprs; unsigned NumElements = Exp->getNumElements(); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *count = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); KeyExprs.push_back(count); ValueExprs.push_back(count); for (unsigned i = 0; i < NumElements; i++) { ObjCDictionaryElement Element = Exp->getKeyValueElement(i); KeyExprs.push_back(Element.Key); ValueExprs.push_back(Element.Value); } // (const id [])objects Expr *NSValueCallExpr = CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue, SourceLocation(), FPOptionsOverride()); FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("arr"), Context->getPointerType(Context->VoidPtrTy), nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *DictLiteralValueME = MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD, ARRFD->getType(), VK_LValue, OK_Ordinary); QualType ConstIdT = Context->getObjCIdType().withConst(); CStyleCastExpr * DictValueObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralValueME); // (const id <NSCopying> [])keys Expr *NSKeyCallExpr = CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue, SourceLocation(), FPOptionsOverride()); MemberExpr *DictLiteralKeyME = MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD, ARRFD->getType(), VK_LValue, OK_Ordinary); CStyleCastExpr * DictKeyObjects = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(ConstIdT), CK_BitCast, DictLiteralKeyME); // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 32> MsgExprs; SmallVector<Expr*, 4> ClsExprs; QualType expType = Exp->getType(); // Create a call to objc_getClass("NSArray"). It will be th 1st argument. ObjCInterfaceDecl *Class = expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface(); IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); MsgExprs.push_back(Cls); // Create a call to sel_registerName("arrayWithObjects:count:"). // it will be the 2nd argument. SmallVector<Expr*, 4> SelExprs; ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod(); SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // (const id [])objects MsgExprs.push_back(DictValueObjects); // (const id <NSCopying> [])keys MsgExprs.push_back(DictKeyObjects); // (NSUInteger)cnt Expr *cnt = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, NumElements), Context->UnsignedIntTy, SourceLocation()); MsgExprs.push_back(cnt); SmallVector<QualType, 8> ArgTypes; ArgTypes.push_back(Context->getObjCClassType()); ArgTypes.push_back(Context->getObjCSelType()); for (const auto *PI : DictMethod->parameters()) { QualType T = PI->getType(); if (const PointerType* PT = T->getAs<PointerType>()) { QualType PointeeTy = PT->getPointeeType(); convertToUnqualifiedObjCType(PointeeTy); T = Context->getPointerType(PointeeTy); } ArgTypes.push_back(T); } QualType returnType = Exp->getType(); // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); CastExpr *cast = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. QualType castType = getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic()); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); ReplaceStmt(Exp, CE); return CE; } // struct __rw_objc_super { // struct objc_object *object; struct objc_object *superClass; // }; QualType RewriteModernObjC::getSuperStructType() { if (!SuperStructDecl) { SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__rw_objc_super")); QualType FieldTypes[2]; // struct objc_object *object; FieldTypes[0] = Context->getObjCIdType(); // struct objc_object *superClass; FieldTypes[1] = Context->getObjCIdType(); // Create fields for (unsigned i = 0; i < 2; ++i) { SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl, SourceLocation(), SourceLocation(), nullptr, FieldTypes[i], nullptr, /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit)); } SuperStructDecl->completeDefinition(); } return Context->getTagDeclType(SuperStructDecl); } QualType RewriteModernObjC::getConstantStringStructType() { if (!ConstantStringDecl) { ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__NSConstantStringImpl")); QualType FieldTypes[4]; // struct objc_object *receiver; FieldTypes[0] = Context->getObjCIdType(); // int flags; FieldTypes[1] = Context->IntTy; // char *str; FieldTypes[2] = Context->getPointerType(Context->CharTy); // long length; FieldTypes[3] = Context->LongTy; // Create fields for (unsigned i = 0; i < 4; ++i) { ConstantStringDecl->addDecl(FieldDecl::Create(*Context, ConstantStringDecl, SourceLocation(), SourceLocation(), nullptr, FieldTypes[i], nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit)); } ConstantStringDecl->completeDefinition(); } return Context->getTagDeclType(ConstantStringDecl); } /// getFunctionSourceLocation - returns start location of a function /// definition. Complication arises when function has declared as /// extern "C" or extern "C" {...} static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R, FunctionDecl *FD) { if (FD->isExternC() && !FD->isMain()) { const DeclContext *DC = FD->getDeclContext(); if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) // if it is extern "C" {...}, return function decl's own location. if (!LSD->getRBraceLoc().isValid()) return LSD->getExternLoc(); } if (FD->getStorageClass() != SC_None) R.RewriteBlockLiteralFunctionDecl(FD); return FD->getTypeSpecStartLoc(); } void RewriteModernObjC::RewriteLineDirective(const Decl *D) { SourceLocation Location = D->getLocation(); if (Location.isFileID() && GenerateLineInfo) { std::string LineString("\n#line "); PresumedLoc PLoc = SM->getPresumedLoc(Location); LineString += utostr(PLoc.getLine()); LineString += " \""; LineString += Lexer::Stringify(PLoc.getFilename()); if (isa<ObjCMethodDecl>(D)) LineString += "\""; else LineString += "\"\n"; Location = D->getBeginLoc(); if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->isExternC() && !FD->isMain()) { const DeclContext *DC = FD->getDeclContext(); if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC)) // if it is extern "C" {...}, return function decl's own location. if (!LSD->getRBraceLoc().isValid()) Location = LSD->getExternLoc(); } } InsertText(Location, LineString); } } /// SynthMsgSendStretCallExpr - This routine translates message expression /// into a call to objc_msgSend_stret() entry point. Tricky part is that /// nil check on receiver must be performed before calling objc_msgSend_stret. /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...) /// msgSendType - function type of objc_msgSend_stret(...) /// returnType - Result type of the method being synthesized. /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type. /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret, /// starting with receiver. /// Method - Method being rewritten. Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor, QualType returnType, SmallVectorImpl<QualType> &ArgTypes, SmallVectorImpl<Expr*> &MsgExprs, ObjCMethodDecl *Method) { // Now do the "normal" pointer to function cast. QualType FuncType = getSimpleFunctionType( returnType, ArgTypes, Method ? Method->isVariadic() : false); QualType castType = Context->getPointerType(FuncType); // build type for containing the objc_msgSend_stret object. static unsigned stretCount=0; std::string name = "__Stret"; name += utostr(stretCount); std::string str = "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n"; str += "namespace {\n"; str += "struct "; str += name; str += " {\n\t"; str += name; str += "(id receiver, SEL sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { std::string ArgName = "arg"; ArgName += utostr(i); ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy()); str += ", "; str += ArgName; } // could be vararg. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { std::string ArgName = "arg"; ArgName += utostr(i); MsgExprs[i]->getType().getAsStringInternal(ArgName, Context->getPrintingPolicy()); str += ", "; str += ArgName; } str += ") {\n"; str += "\t unsigned size = sizeof("; str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n"; str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n"; str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { str += ", arg"; str += utostr(i); } // could be vararg. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { str += ", arg"; str += utostr(i); } str+= ");\n"; str += "\t else if (receiver == 0)\n"; str += "\t memset((void*)&s, 0, sizeof(s));\n"; str += "\t else\n"; str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy()); str += ")(void *)objc_msgSend_stret)(receiver, sel"; for (unsigned i = 2; i < ArgTypes.size(); i++) { str += ", arg"; str += utostr(i); } // could be vararg. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) { str += ", arg"; str += utostr(i); } str += ");\n"; str += "\t}\n"; str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy()); str += " s;\n"; str += "};\n};\n\n"; SourceLocation FunLocStart; if (CurFunctionDef) FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); else { assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null"); FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, str); ++stretCount; // AST for __Stretn(receiver, args).s; IdentifierInfo *ID = &Context->Idents.get(name); FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, FuncType, nullptr, SC_Extern, false, false); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, castType, VK_PRValue, SourceLocation()); CallExpr *STCE = CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue, SourceLocation(), FPOptionsOverride()); FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("s"), returnType, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary); return ME; } Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp, SourceLocation StartLoc, SourceLocation EndLoc) { if (!SelGetUidFunctionDecl) SynthSelGetUidFunctionDecl(); if (!MsgSendFunctionDecl) SynthMsgSendFunctionDecl(); if (!MsgSendSuperFunctionDecl) SynthMsgSendSuperFunctionDecl(); if (!MsgSendStretFunctionDecl) SynthMsgSendStretFunctionDecl(); if (!MsgSendSuperStretFunctionDecl) SynthMsgSendSuperStretFunctionDecl(); if (!MsgSendFpretFunctionDecl) SynthMsgSendFpretFunctionDecl(); if (!GetClassFunctionDecl) SynthGetClassFunctionDecl(); if (!GetSuperClassFunctionDecl) SynthGetSuperClassFunctionDecl(); if (!GetMetaClassFunctionDecl) SynthGetMetaClassFunctionDecl(); // default to objc_msgSend(). FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl; // May need to use objc_msgSend_stret() as well. FunctionDecl *MsgSendStretFlavor = nullptr; if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) { QualType resultType = mDecl->getReturnType(); if (resultType->isRecordType()) MsgSendStretFlavor = MsgSendStretFunctionDecl; else if (resultType->isRealFloatingType()) MsgSendFlavor = MsgSendFpretFunctionDecl; } // Synthesize a call to objc_msgSend(). SmallVector<Expr*, 8> MsgExprs; switch (Exp->getReceiverKind()) { case ObjCMessageExpr::SuperClass: { MsgSendFlavor = MsgSendSuperFunctionDecl; if (MsgSendStretFlavor) MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); SmallVector<Expr*, 4> InitExprs; // set the receiver to self, the first argument to all methods. InitExprs.push_back(NoTypeInfoCStyleCastExpr( Context, Context->getObjCIdType(), CK_BitCast, new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_PRValue, SourceLocation()))); // set the 'receiver'. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); // (Class)objc_getClass("CurrentClass") CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl, ClsExprs, StartLoc, EndLoc); ClsExprs.clear(); ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using class_getSuperclass(). NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, Cls)); // struct __rw_objc_super QualType superType = getSuperStructType(); Expr *SuperRep; if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, VK_LValue, SourceLocation()); SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue, SourceLocation(), FPOptionsOverride()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why // we need the cast below. For example: // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) // SuperRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf, Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); SuperRep = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(superType), CK_BitCast, SuperRep); } else { // (struct __rw_objc_super) { <exprs from above> } InitListExpr *ILE = new (Context) InitListExpr(*Context, SourceLocation(), InitExprs, SourceLocation()); TypeSourceInfo *superTInfo = Context->getTrivialTypeSourceInfo(superType); SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo, superType, VK_LValue, ILE, false); // struct __rw_objc_super * SuperRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf, Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); } MsgExprs.push_back(SuperRep); break; } case ObjCMessageExpr::Class: { SmallVector<Expr*, 8> ClsExprs; ObjCInterfaceDecl *Class = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface(); IdentifierInfo *clsName = Class->getIdentifier(); ClsExprs.push_back(getStringLiteral(clsName->getName())); CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, Cls); MsgExprs.push_back(ArgExpr); break; } case ObjCMessageExpr::SuperInstance:{ MsgSendFlavor = MsgSendSuperFunctionDecl; if (MsgSendStretFlavor) MsgSendStretFlavor = MsgSendSuperStretFunctionDecl; assert(MsgSendFlavor && "MsgSendFlavor is NULL!"); ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface(); SmallVector<Expr*, 4> InitExprs; InitExprs.push_back(NoTypeInfoCStyleCastExpr( Context, Context->getObjCIdType(), CK_BitCast, new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false, Context->getObjCIdType(), VK_PRValue, SourceLocation()))); // set the 'receiver'. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) SmallVector<Expr*, 8> ClsExprs; ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName())); // (Class)objc_getClass("CurrentClass") CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs, StartLoc, EndLoc); ClsExprs.clear(); ClsExprs.push_back(Cls); Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs, StartLoc, EndLoc); // (id)class_getSuperclass((Class)objc_getClass("CurrentClass")) // To turn off a warning, type-cast to 'id' InitExprs.push_back( // set 'super class', using class_getSuperclass(). NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK_BitCast, Cls)); // struct __rw_objc_super QualType superType = getSuperStructType(); Expr *SuperRep; if (LangOpts.MicrosoftExt) { SynthSuperConstructorFunctionDecl(); // Simulate a constructor call... DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType, VK_LValue, SourceLocation()); SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue, SourceLocation(), FPOptionsOverride()); // The code for super is a little tricky to prevent collision with // the structure definition in the header. The rewriter has it's own // internal definition (__rw_objc_super) that is uses. This is why // we need the cast below. For example: // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER")) // SuperRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf, Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); SuperRep = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(superType), CK_BitCast, SuperRep); } else { // (struct __rw_objc_super) { <exprs from above> } InitListExpr *ILE = new (Context) InitListExpr(*Context, SourceLocation(), InitExprs, SourceLocation()); TypeSourceInfo *superTInfo = Context->getTrivialTypeSourceInfo(superType); SuperRep = new (Context) CompoundLiteralExpr( SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false); } MsgExprs.push_back(SuperRep); break; } case ObjCMessageExpr::Instance: { // Remove all type-casts because it may contain objc-style types; e.g. // Foo<Proto> *. Expr *recExpr = Exp->getInstanceReceiver(); while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr)) recExpr = CE->getSubExpr(); CastKind CK = recExpr->getType()->isObjCObjectPointerType() ? CK_BitCast : recExpr->getType()->isBlockPointerType() ? CK_BlockPointerToObjCPointerCast : CK_CPointerToObjCPointerCast; recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK, recExpr); MsgExprs.push_back(recExpr); break; } } // Create a call to sel_registerName("selName"), it will be the 2nd argument. SmallVector<Expr*, 8> SelExprs; SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString())); CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl, SelExprs, StartLoc, EndLoc); MsgExprs.push_back(SelExp); // Now push any user supplied arguments. for (unsigned i = 0; i < Exp->getNumArgs(); i++) { Expr *userExpr = Exp->getArg(i); // Make all implicit casts explicit...ICE comes in handy:-) if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) { // Reuse the ICE type, it is exactly what the doctor ordered. QualType type = ICE->getType(); if (needToScanForQualifiers(type)) type = Context->getObjCIdType(); // Make sure we convert "type (^)(...)" to "type (*)(...)". (void)convertBlockPointerToFunctionPointer(type); const Expr *SubExpr = ICE->IgnoreParenImpCasts(); CastKind CK; if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType()) { CK = CK_IntegralToBoolean; } else if (type->isObjCObjectPointerType()) { if (SubExpr->getType()->isBlockPointerType()) { CK = CK_BlockPointerToObjCPointerCast; } else if (SubExpr->getType()->isPointerType()) { CK = CK_CPointerToObjCPointerCast; } else { CK = CK_BitCast; } } else { CK = CK_BitCast; } userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr); } // Make id<P...> cast into an 'id' cast. else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) { if (CE->getType()->isObjCQualifiedIdType()) { while ((CE = dyn_cast<CStyleCastExpr>(userExpr))) userExpr = CE->getSubExpr(); CastKind CK; if (userExpr->getType()->isIntegralType(*Context)) { CK = CK_IntegralToPointer; } else if (userExpr->getType()->isBlockPointerType()) { CK = CK_BlockPointerToObjCPointerCast; } else if (userExpr->getType()->isPointerType()) { CK = CK_CPointerToObjCPointerCast; } else { CK = CK_BitCast; } userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(), CK, userExpr); } } MsgExprs.push_back(userExpr); // We've transferred the ownership to MsgExprs. For now, we *don't* null // out the argument in the original expression (since we aren't deleting // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info. //Exp->setArg(i, 0); } // Generate the funky cast. CastExpr *cast; SmallVector<QualType, 8> ArgTypes; QualType returnType; // Push 'id' and 'SEL', the 2 implicit arguments. if (MsgSendFlavor == MsgSendSuperFunctionDecl) ArgTypes.push_back(Context->getPointerType(getSuperStructType())); else ArgTypes.push_back(Context->getObjCIdType()); ArgTypes.push_back(Context->getObjCSelType()); if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) { // Push any user argument types. for (const auto *PI : OMD->parameters()) { QualType t = PI->getType()->isObjCQualifiedIdType() ? Context->getObjCIdType() : PI->getType(); // Make sure we convert "t (^)(...)" to "t (*)(...)". (void)convertBlockPointerToFunctionPointer(t); ArgTypes.push_back(t); } returnType = Exp->getType(); convertToUnqualifiedObjCType(returnType); (void)convertBlockPointerToFunctionPointer(returnType); } else { returnType = Context->getObjCIdType(); } // Get the type, we will need to reference it in a couple spots. QualType msgSendType = MsgSendFlavor->getType(); // Create a reference to the objc_msgSend() declaration. DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation()); // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid). // If we don't do this cast, we get the following bizarre warning/note: // xx.m:13: warning: function called through a non-compatible type // xx.m:13: note: if this code is reached, the program will abort cast = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE); // Now do the "normal" pointer to function cast. // If we don't have a method decl, force a variadic cast. const ObjCMethodDecl *MD = Exp->getMethodDecl(); QualType castType = getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true); castType = Context->getPointerType(castType); cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast, cast); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast); const FunctionType *FT = msgSendType->castAs<FunctionType>(); CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(), VK_PRValue, EndLoc, FPOptionsOverride()); Stmt *ReplacingStmt = CE; if (MsgSendStretFlavor) { // We have the method which returns a struct/union. Must also generate // call to objc_msgSend_stret and hang both varieties on a conditional // expression which dictate which one to envoke depending on size of // method's return type. Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor, returnType, ArgTypes, MsgExprs, Exp->getMethodDecl()); ReplacingStmt = STCE; } // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return ReplacingStmt; } Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) { Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc()); // Now do the actual rewrite. ReplaceStmt(Exp, ReplacingStmt); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return ReplacingStmt; } // typedef struct objc_object Protocol; QualType RewriteModernObjC::getProtocolType() { if (!ProtocolTypeDecl) { TypeSourceInfo *TInfo = Context->getTrivialTypeSourceInfo(Context->getObjCIdType()); ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("Protocol"), TInfo); } return Context->getTypeDeclType(ProtocolTypeDecl); } /// RewriteObjCProtocolExpr - Rewrite a protocol expression into /// a synthesized/forward data reference (to the protocol's metadata). /// The forward references (and metadata) are generated in /// RewriteModernObjC::HandleTranslationUnit(). Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) { std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" + Exp->getProtocol()->getNameAsString(); IdentifierInfo *ID = &Context->Idents.get(Name); VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, getProtocolType(), nullptr, SC_Extern); DeclRefExpr *DRE = new (Context) DeclRefExpr( *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation()); CastExpr *castExpr = NoTypeInfoCStyleCastExpr( Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE); ReplaceStmt(Exp, castExpr); ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl()); // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info. return castExpr; } /// IsTagDefinedInsideClass - This routine checks that a named tagged type /// is defined inside an objective-c class. If so, it returns true. bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag, bool &IsNamedDefinition) { if (!IDecl) return false; SourceLocation TagLocation; if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) { RD = RD->getDefinition(); if (!RD || !RD->getDeclName().getAsIdentifierInfo()) return false; IsNamedDefinition = true; TagLocation = RD->getLocation(); return Context->getSourceManager().isBeforeInTranslationUnit( IDecl->getLocation(), TagLocation); } if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) { if (!ED || !ED->getDeclName().getAsIdentifierInfo()) return false; IsNamedDefinition = true; TagLocation = ED->getLocation(); return Context->getSourceManager().isBeforeInTranslationUnit( IDecl->getLocation(), TagLocation); } return false; } /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer. /// It handles elaborated types, as well as enum types in the process. bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type, std::string &Result) { if (isa<TypedefType>(Type)) { Result += "\t"; return false; } if (Type->isArrayType()) { QualType ElemTy = Context->getBaseElementType(Type); return RewriteObjCFieldDeclType(ElemTy, Result); } else if (Type->isRecordType()) { RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); if (RD->isCompleteDefinition()) { if (RD->isStruct()) Result += "\n\tstruct "; else if (RD->isUnion()) Result += "\n\tunion "; else assert(false && "class not allowed as an ivar type"); Result += RD->getName(); if (GlobalDefinedTags.count(RD)) { // struct/union is defined globally, use it. Result += " "; return true; } Result += " {\n"; for (auto *FD : RD->fields()) RewriteObjCFieldDecl(FD, Result); Result += "\t} "; return true; } } else if (Type->isEnumeralType()) { EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); if (ED->isCompleteDefinition()) { Result += "\n\tenum "; Result += ED->getName(); if (GlobalDefinedTags.count(ED)) { // Enum is globall defined, use it. Result += " "; return true; } Result += " {\n"; for (const auto *EC : ED->enumerators()) { Result += "\t"; Result += EC->getName(); Result += " = "; Result += toString(EC->getInitVal(), 10); Result += ",\n"; } Result += "\t} "; return true; } } Result += "\t"; convertObjCTypeToCStyleType(Type); return false; } /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer. /// It handles elaborated types, as well as enum types in the process. void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); std::string Name = fieldDecl->getNameAsString(); bool EleboratedType = RewriteObjCFieldDeclType(Type, Result); if (!EleboratedType) Type.getAsStringInternal(Name, Context->getPrintingPolicy()); Result += Name; if (fieldDecl->isBitField()) { Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context)); } else if (EleboratedType && Type->isArrayType()) { const ArrayType *AT = Context->getAsArrayType(Type); do { if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { Result += "["; llvm::APInt Dim = CAT->getSize(); Result += utostr(Dim.getZExtValue()); Result += "]"; } AT = Context->getAsArrayType(AT->getElementType()); } while (AT); } Result += ";\n"; } /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined /// named aggregate types into the input buffer. void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl, std::string &Result) { QualType Type = fieldDecl->getType(); if (isa<TypedefType>(Type)) return; if (Type->isArrayType()) Type = Context->getBaseElementType(Type); auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext()); TagDecl *TD = nullptr; if (Type->isRecordType()) { TD = Type->castAs<RecordType>()->getDecl(); } else if (Type->isEnumeralType()) { TD = Type->castAs<EnumType>()->getDecl(); } if (TD) { if (GlobalDefinedTags.count(TD)) return; bool IsNamedDefinition = false; if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) { RewriteObjCFieldDeclType(Type, Result); Result += ";"; } if (IsNamedDefinition) GlobalDefinedTags.insert(TD); } } unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) { return IvarGroupNumber[IV]; } unsigned GroupNo = 0; SmallVector<const ObjCIvarDecl *, 8> IVars; for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); for (unsigned i = 0, e = IVars.size(); i < e; i++) if (IVars[i]->isBitField()) { IvarGroupNumber[IVars[i++]] = ++GroupNo; while (i < e && IVars[i]->isBitField()) IvarGroupNumber[IVars[i++]] = GroupNo; if (i < e) --i; } ObjCInterefaceHasBitfieldGroups.insert(CDecl); return IvarGroupNumber[IV]; } QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType( ObjCIvarDecl *IV, SmallVectorImpl<ObjCIvarDecl *> &IVars) { std::string StructTagName; ObjCIvarBitfieldGroupType(IV, StructTagName); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, Context->getTranslationUnitDecl(), SourceLocation(), SourceLocation(), &Context->Idents.get(StructTagName)); for (unsigned i=0, e = IVars.size(); i < e; i++) { ObjCIvarDecl *Ivar = IVars[i]; RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(), &Context->Idents.get(Ivar->getName()), Ivar->getType(), nullptr, /*Expr *BW */Ivar->getBitWidth(), false, ICIS_NoInit)); } RD->completeDefinition(); return Context->getTagDeclType(RD); } QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo); if (GroupRecordType.count(tuple)) return GroupRecordType[tuple]; SmallVector<ObjCIvarDecl *, 8> IVars; for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { if (IVD->isBitField()) IVars.push_back(const_cast<ObjCIvarDecl *>(IVD)); else { if (!IVars.empty()) { unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]); // Generate the struct type for this group of bitfield ivars. GroupRecordType[std::make_pair(CDecl, GroupNo)] = SynthesizeBitfieldGroupStructType(IVars[0], IVars); IVars.clear(); } } } if (!IVars.empty()) { // Do the last one. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]); GroupRecordType[std::make_pair(CDecl, GroupNo)] = SynthesizeBitfieldGroupStructType(IVars[0], IVars); } QualType RetQT = GroupRecordType[tuple]; assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL"); return RetQT; } /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group. /// Name would be: classname__GRBF_n where n is the group number for this ivar. void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); Result += CDecl->getName(); Result += "__GRBF_"; unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); Result += utostr(GroupNo); } /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group. /// Name of the struct would be: classname__T_n where n is the group number for /// this ivar. void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result) { const ObjCInterfaceDecl *CDecl = IV->getContainingInterface(); Result += CDecl->getName(); Result += "__T_"; unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV); Result += utostr(GroupNo); } /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset. /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for /// this ivar. void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result) { Result += "OBJC_IVAR_$_"; ObjCIvarBitfieldGroupDecl(IV, Result); } #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \ while ((IX < ENDIX) && VEC[IX]->isBitField()) \ ++IX; \ if (IX < ENDIX) \ --IX; \ } /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to /// an objective-c class with ivars. void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl, std::string &Result) { assert(CDecl && "Class missing in SynthesizeObjCInternalStruct"); assert(CDecl->getName() != "" && "Name missing in SynthesizeObjCInternalStruct"); ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass(); SmallVector<ObjCIvarDecl *, 8> IVars; for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) IVars.push_back(IVD); SourceLocation LocStart = CDecl->getBeginLoc(); SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc(); const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); // If no ivars and no root or if its root, directly or indirectly, // have no ivars (thus not synthesized) then no need to synthesize this class. if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) { endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); ReplaceText(LocStart, endBuf-startBuf, Result); return; } // Insert named struct/union definitions inside class to // outer scope. This follows semantics of locally defined // struct/unions in objective-c classes. for (unsigned i = 0, e = IVars.size(); i < e; i++) RewriteLocallyDefinedNamedAggregates(IVars[i], Result); // Insert named structs which are syntheized to group ivar bitfields // to outer scope as well. for (unsigned i = 0, e = IVars.size(); i < e; i++) if (IVars[i]->isBitField()) { ObjCIvarDecl *IV = IVars[i]; QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV); RewriteObjCFieldDeclType(QT, Result); Result += ";"; // skip over ivar bitfields in this group. SKIP_BITFIELDS(i , e, IVars); } Result += "\nstruct "; Result += CDecl->getNameAsString(); Result += "_IMPL {\n"; if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) { Result += "\tstruct "; Result += RCDecl->getNameAsString(); Result += "_IMPL "; Result += RCDecl->getNameAsString(); Result += "_IVARS;\n"; } for (unsigned i = 0, e = IVars.size(); i < e; i++) { if (IVars[i]->isBitField()) { ObjCIvarDecl *IV = IVars[i]; Result += "\tstruct "; ObjCIvarBitfieldGroupType(IV, Result); Result += " "; ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n"; // skip over ivar bitfields in this group. SKIP_BITFIELDS(i , e, IVars); } else RewriteObjCFieldDecl(IVars[i], Result); } Result += "};\n"; endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts); ReplaceText(LocStart, endBuf-startBuf, Result); // Mark this struct as having been generated. if (!ObjCSynthesizedStructs.insert(CDecl).second) llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct"); } /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which /// have been referenced in an ivar access expression. void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl, std::string &Result) { // write out ivar offset symbols which have been referenced in an ivar // access expression. llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl]; if (Ivars.empty()) return; llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput; for (ObjCIvarDecl *IvarDecl : Ivars) { const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface(); unsigned GroupNo = 0; if (IvarDecl->isBitField()) { GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl); if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo))) continue; } Result += "\n"; if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; Result += "extern \"C\" "; if (LangOpts.MicrosoftExt && IvarDecl->getAccessControl() != ObjCIvarDecl::Private && IvarDecl->getAccessControl() != ObjCIvarDecl::Package) Result += "__declspec(dllimport) "; Result += "unsigned long "; if (IvarDecl->isBitField()) { ObjCIvarBitfieldGroupOffset(IvarDecl, Result); GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo)); } else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += ";"; } } //===----------------------------------------------------------------------===// // Meta Data Emission //===----------------------------------------------------------------------===// /// RewriteImplementations - This routine rewrites all method implementations /// and emits meta-data. void RewriteModernObjC::RewriteImplementations() { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); // Rewrite implemented methods for (int i = 0; i < ClsDefCount; i++) { ObjCImplementationDecl *OIMP = ClassImplementation[i]; ObjCInterfaceDecl *CDecl = OIMP->getClassInterface(); if (CDecl->isImplicitInterfaceDecl()) assert(false && "Legacy implicit interface rewriting not supported in moder abi"); RewriteImplementationDecl(OIMP); } for (int i = 0; i < CatDefCount; i++) { ObjCCategoryImplDecl *CIMP = CategoryImplementation[i]; ObjCInterfaceDecl *CDecl = CIMP->getClassInterface(); if (CDecl->isImplicitInterfaceDecl()) assert(false && "Legacy implicit interface rewriting not supported in moder abi"); RewriteImplementationDecl(CIMP); } } void RewriteModernObjC::RewriteByRefString(std::string &ResultStr, const std::string &Name, ValueDecl *VD, bool def) { assert(BlockByRefDeclNo.count(VD) && "RewriteByRefString: ByRef decl missing"); if (def) ResultStr += "struct "; ResultStr += "__Block_byref_" + Name + "_" + utostr(BlockByRefDeclNo[VD]) ; } static bool HasLocalVariableExternalStorage(ValueDecl *VD) { if (VarDecl *Var = dyn_cast<VarDecl>(VD)) return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage()); return false; } std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i, StringRef funcName, std::string Tag) { const FunctionType *AFT = CE->getFunctionType(); QualType RT = AFT->getReturnType(); std::string StructRef = "struct " + Tag; SourceLocation BlockLoc = CE->getExprLoc(); std::string S; ConvertSourceLocationToLineDirective(BlockLoc, S); S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" + funcName.str() + "_block_func_" + utostr(i); BlockDecl *BD = CE->getBlockDecl(); if (isa<FunctionNoProtoType>(AFT)) { // No user-supplied arguments. Still need to pass in a pointer to the // block (to reference imported block decl refs). S += "(" + StructRef + " *__cself)"; } else if (BD->param_empty()) { S += "(" + StructRef + " *__cself)"; } else { const FunctionProtoType *FT = cast<FunctionProtoType>(AFT); assert(FT && "SynthesizeBlockFunc: No function proto"); S += '('; // first add the implicit argument. S += StructRef + " *__cself, "; std::string ParamStr; for (BlockDecl::param_iterator AI = BD->param_begin(), E = BD->param_end(); AI != E; ++AI) { if (AI != BD->param_begin()) S += ", "; ParamStr = (*AI)->getNameAsString(); QualType QT = (*AI)->getType(); (void)convertBlockPointerToFunctionPointer(QT); QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy()); S += ParamStr; } if (FT->isVariadic()) { if (!BD->param_empty()) S += ", "; S += "..."; } S += ')'; } S += " {\n"; // Create local declarations to avoid rewriting all closure decl ref exprs. // First, emit a declaration for all "by ref" decls. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string Name = (*I)->getNameAsString(); std::string TypeString; RewriteByRefString(TypeString, Name, (*I)); TypeString += " *"; Name = TypeString + Name; S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n"; } // Next, emit a declaration for all "by copy" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; // Handle nested closure invocation. For example: // // void (^myImportedClosure)(void); // myImportedClosure = ^(void) { setGlobalInt(x + y); }; // // void (^anotherClosure)(void); // anotherClosure = ^(void) { // myImportedClosure(); // import and invoke the closure // }; // if (isTopLevelBlockPointerType((*I)->getType())) { RewriteBlockPointerTypeVariable(S, (*I)); S += " = ("; RewriteBlockPointerType(S, (*I)->getType()); S += ")"; S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } else { std::string Name = (*I)->getNameAsString(); QualType QT = (*I)->getType(); if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(Name, Context->getPrintingPolicy()); S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n"; } } std::string RewrittenStr = RewrittenBlockExprs[CE]; const char *cstr = RewrittenStr.c_str(); while (*cstr++ != '{') ; S += cstr; S += "\n"; return S; } std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, StringRef funcName, std::string Tag) { std::string StructRef = "struct " + Tag; std::string S = "static void __"; S += funcName; S += "_block_copy_" + utostr(i); S += "(" + StructRef; S += "*dst, " + StructRef; S += "*src) {"; for (ValueDecl *VD : ImportedBlockDecls) { S += "_Block_object_assign((void*)&dst->"; S += VD->getNameAsString(); S += ", (void*)src->"; S += VD->getNameAsString(); if (BlockByRefDeclsPtrSet.count(VD)) S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; else if (VD->getType()->isBlockPointerType()) S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; else S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; S += "\nstatic void __"; S += funcName; S += "_block_dispose_" + utostr(i); S += "(" + StructRef; S += "*src) {"; for (ValueDecl *VD : ImportedBlockDecls) { S += "_Block_object_dispose((void*)src->"; S += VD->getNameAsString(); if (BlockByRefDeclsPtrSet.count(VD)) S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);"; else if (VD->getType()->isBlockPointerType()) S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);"; else S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);"; } S += "}\n"; return S; } std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag, std::string Desc) { std::string S = "\nstruct " + Tag; std::string Constructor = " " + Tag; S += " {\n struct __block_impl impl;\n"; S += " struct " + Desc; S += "* Desc;\n"; Constructor += "(void *fp, "; // Invoke function pointer. Constructor += "struct " + Desc; // Descriptor pointer. Constructor += " *desc"; if (BlockDeclRefs.size()) { // Output all "by copy" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); std::string ArgName = "_" + FieldName; // Handle nested closure invocation. For example: // // void (^myImportedBlock)(void); // myImportedBlock = ^(void) { setGlobalInt(x + y); }; // // void (^anotherBlock)(void); // anotherBlock = ^(void) { // myImportedBlock(); // import and invoke the closure // }; // if (isTopLevelBlockPointerType((*I)->getType())) { S += "struct __block_impl *"; Constructor += ", void *" + ArgName; } else { QualType QT = (*I)->getType(); if (HasLocalVariableExternalStorage(*I)) QT = Context->getPointerType(QT); QT.getAsStringInternal(FieldName, Context->getPrintingPolicy()); QT.getAsStringInternal(ArgName, Context->getPrintingPolicy()); Constructor += ", " + ArgName; } S += FieldName + ";\n"; } // Output all "by ref" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { S += " "; std::string FieldName = (*I)->getNameAsString(); std::string ArgName = "_" + FieldName; { std::string TypeString; RewriteByRefString(TypeString, FieldName, (*I)); TypeString += " *"; FieldName = TypeString + FieldName; ArgName = TypeString + ArgName; Constructor += ", " + ArgName; } S += FieldName + "; // by ref\n"; } // Finish writing the constructor. Constructor += ", int flags=0)"; // Initialize all "by copy" arguments. bool firsTime = true; for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); if (firsTime) { Constructor += " : "; firsTime = false; } else Constructor += ", "; if (isTopLevelBlockPointerType((*I)->getType())) Constructor += Name + "((struct __block_impl *)_" + Name + ")"; else Constructor += Name + "(_" + Name + ")"; } // Initialize all "by ref" arguments. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { std::string Name = (*I)->getNameAsString(); if (firsTime) { Constructor += " : "; firsTime = false; } else Constructor += ", "; Constructor += Name + "(_" + Name + "->__forwarding)"; } Constructor += " {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; else Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; Constructor += " Desc = desc;\n"; } else { // Finish writing the constructor. Constructor += ", int flags=0) {\n"; if (GlobalVarDecl) Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n"; else Constructor += " impl.isa = &_NSConcreteStackBlock;\n"; Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n"; Constructor += " Desc = desc;\n"; } Constructor += " "; Constructor += "}\n"; S += Constructor; S += "};\n"; return S; } std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag, std::string ImplTag, int i, StringRef FunName, unsigned hasCopy) { std::string S = "\nstatic struct " + DescTag; S += " {\n size_t reserved;\n"; S += " size_t Block_size;\n"; if (hasCopy) { S += " void (*copy)(struct "; S += ImplTag; S += "*, struct "; S += ImplTag; S += "*);\n"; S += " void (*dispose)(struct "; S += ImplTag; S += "*);\n"; } S += "} "; S += DescTag + "_DATA = { 0, sizeof(struct "; S += ImplTag + ")"; if (hasCopy) { S += ", __" + FunName.str() + "_block_copy_" + utostr(i); S += ", __" + FunName.str() + "_block_dispose_" + utostr(i); } S += "};\n"; return S; } void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart, StringRef FunName) { bool RewriteSC = (GlobalVarDecl && !Blocks.empty() && GlobalVarDecl->getStorageClass() == SC_Static && GlobalVarDecl->getType().getCVRQualifiers()); if (RewriteSC) { std::string SC(" void __"); SC += GlobalVarDecl->getNameAsString(); SC += "() {}"; InsertText(FunLocStart, SC); } // Insert closures that were part of the function. for (unsigned i = 0, count=0; i < Blocks.size(); i++) { CollectBlockDeclRefInfo(Blocks[i]); // Need to copy-in the inner copied-in variables not actually used in this // block. for (int j = 0; j < InnerDeclRefsCount[i]; j++) { DeclRefExpr *Exp = InnerDeclRefs[count++]; ValueDecl *VD = Exp->getDecl(); BlockDeclRefs.push_back(Exp); if (!VD->hasAttr<BlocksAttr>()) { if (!BlockByCopyDeclsPtrSet.count(VD)) { BlockByCopyDeclsPtrSet.insert(VD); BlockByCopyDecls.push_back(VD); } continue; } if (!BlockByRefDeclsPtrSet.count(VD)) { BlockByRefDeclsPtrSet.insert(VD); BlockByRefDecls.push_back(VD); } // imported objects in the inner blocks not used in the outer // blocks must be copied/disposed in the outer block as well. if (VD->getType()->isObjCObjectPointerType() || VD->getType()->isBlockPointerType()) ImportedBlockDecls.insert(VD); } std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i); std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i); std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag); InsertText(FunLocStart, CI); std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag); InsertText(FunLocStart, CF); if (ImportedBlockDecls.size()) { std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag); InsertText(FunLocStart, HF); } std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName, ImportedBlockDecls.size() > 0); InsertText(FunLocStart, BD); BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByRefDeclsPtrSet.clear(); BlockByCopyDecls.clear(); BlockByCopyDeclsPtrSet.clear(); ImportedBlockDecls.clear(); } if (RewriteSC) { // Must insert any 'const/volatile/static here. Since it has been // removed as result of rewriting of block literals. std::string SC; if (GlobalVarDecl->getStorageClass() == SC_Static) SC = "static "; if (GlobalVarDecl->getType().isConstQualified()) SC += "const "; if (GlobalVarDecl->getType().isVolatileQualified()) SC += "volatile "; if (GlobalVarDecl->getType().isRestrictQualified()) SC += "restrict "; InsertText(FunLocStart, SC); } if (GlobalConstructionExp) { // extra fancy dance for global literal expression. // Always the latest block expression on the block stack. std::string Tag = "__"; Tag += FunName; Tag += "_block_impl_"; Tag += utostr(Blocks.size()-1); std::string globalBuf = "static "; globalBuf += Tag; globalBuf += " "; std::string SStr; llvm::raw_string_ostream constructorExprBuf(SStr); GlobalConstructionExp->printPretty(constructorExprBuf, nullptr, PrintingPolicy(LangOpts)); globalBuf += constructorExprBuf.str(); globalBuf += ";\n"; InsertText(FunLocStart, globalBuf); GlobalConstructionExp = nullptr; } Blocks.clear(); InnerDeclRefsCount.clear(); InnerDeclRefs.clear(); RewrittenBlockExprs.clear(); } void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { SourceLocation FunLocStart = (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD) : FD->getTypeSpecStartLoc(); StringRef FuncName = FD->getName(); SynthesizeBlockLiterals(FunLocStart, FuncName); } static void BuildUniqueMethodName(std::string &Name, ObjCMethodDecl *MD) { ObjCInterfaceDecl *IFace = MD->getClassInterface(); Name = std::string(IFace->getName()); Name += "__" + MD->getSelector().getAsString(); // Convert colons to underscores. std::string::size_type loc = 0; while ((loc = Name.find(':', loc)) != std::string::npos) Name.replace(loc, 1, "_"); } void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n"); // SourceLocation FunLocStart = MD->getBeginLoc(); SourceLocation FunLocStart = MD->getBeginLoc(); std::string FuncName; BuildUniqueMethodName(FuncName, MD); SynthesizeBlockLiterals(FunLocStart, FuncName); } void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) { for (Stmt *SubStmt : S->children()) if (SubStmt) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) GetBlockDeclRefExprs(CBE->getBody()); else GetBlockDeclRefExprs(SubStmt); } // Handle specific things. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) if (DRE->refersToEnclosingVariableOrCapture() || HasLocalVariableExternalStorage(DRE->getDecl())) // FIXME: Handle enums. BlockDeclRefs.push_back(DRE); } void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S, SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs, llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) { for (Stmt *SubStmt : S->children()) if (SubStmt) { if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) { InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl())); GetInnerBlockDeclRefExprs(CBE->getBody(), InnerBlockDeclRefs, InnerContexts); } else GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts); } // Handle specific things. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { if (DRE->refersToEnclosingVariableOrCapture() || HasLocalVariableExternalStorage(DRE->getDecl())) { if (!InnerContexts.count(DRE->getDecl()->getDeclContext())) InnerBlockDeclRefs.push_back(DRE); if (VarDecl *Var = cast<VarDecl>(DRE->getDecl())) if (Var->isFunctionOrMethodVarDecl()) ImportedLocalExternalDecls.insert(Var); } } } /// convertObjCTypeToCStyleType - This routine converts such objc types /// as qualified objects, and blocks to their closest c/c++ types that /// it can. It returns true if input type was modified. bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) { QualType oldT = T; convertBlockPointerToFunctionPointer(T); if (T->isFunctionPointerType()) { QualType PointeeTy; if (const PointerType* PT = T->getAs<PointerType>()) { PointeeTy = PT->getPointeeType(); if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) { T = convertFunctionTypeOfBlocks(FT); T = Context->getPointerType(T); } } } convertToUnqualifiedObjCType(T); return T != oldT; } /// convertFunctionTypeOfBlocks - This routine converts a function type /// whose result type may be a block pointer or whose argument type(s) /// might be block pointers to an equivalent function type replacing /// all block pointers to function pointers. QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) { const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); // FTP will be null for closures that don't take arguments. // Generate a funky cast. SmallVector<QualType, 8> ArgTypes; QualType Res = FT->getReturnType(); bool modified = convertObjCTypeToCStyleType(Res); if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; // Make sure we convert "t (^)(...)" to "t (*)(...)". if (convertObjCTypeToCStyleType(t)) modified = true; ArgTypes.push_back(t); } } QualType FuncType; if (modified) FuncType = getSimpleFunctionType(Res, ArgTypes); else FuncType = QualType(FT, 0); return FuncType; } Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) { // Navigate to relevant type information. const BlockPointerType *CPT = nullptr; if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) { CPT = DRE->getType()->getAs<BlockPointerType>(); } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) { CPT = MExpr->getType()->getAs<BlockPointerType>(); } else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) { return SynthesizeBlockCall(Exp, PRE->getSubExpr()); } else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp)) CPT = IEXPR->getType()->getAs<BlockPointerType>(); else if (const ConditionalOperator *CEXPR = dyn_cast<ConditionalOperator>(BlockExp)) { Expr *LHSExp = CEXPR->getLHS(); Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp); Expr *RHSExp = CEXPR->getRHS(); Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp); Expr *CONDExp = CEXPR->getCond(); ConditionalOperator *CondExpr = new (Context) ConditionalOperator( CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(), cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary); return CondExpr; } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) { CPT = IRE->getType()->getAs<BlockPointerType>(); } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BlockExp)) { CPT = POE->getType()->castAs<BlockPointerType>(); } else { assert(false && "RewriteBlockClass: Bad type"); } assert(CPT && "RewriteBlockClass: Bad type"); const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>(); assert(FT && "RewriteBlockClass: Bad type"); const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT); // FTP will be null for closures that don't take arguments. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get("__block_impl")); QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD)); // Generate a funky cast. SmallVector<QualType, 8> ArgTypes; // Push the block argument type. ArgTypes.push_back(PtrBlock); if (FTP) { for (auto &I : FTP->param_types()) { QualType t = I; // Make sure we convert "t (^)(...)" to "t (*)(...)". if (!convertBlockPointerToFunctionPointer(t)) convertToUnqualifiedObjCType(t); ArgTypes.push_back(t); } } // Now do the pointer to function cast. QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes); PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType); CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock, CK_BitCast, const_cast<Expr*>(BlockExp)); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), BlkCast); //PE->dump(); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary); CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType, CK_BitCast, ME); PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast); SmallVector<Expr*, 8> BlkExprs; // Add the implicit argument. BlkExprs.push_back(BlkCast); // Add the user arguments. for (CallExpr::arg_iterator I = Exp->arg_begin(), E = Exp->arg_end(); I != E; ++I) { BlkExprs.push_back(*I); } CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue, SourceLocation(), FPOptionsOverride()); return CE; } // We need to return the rewritten expression to handle cases where the // DeclRefExpr is embedded in another expression being rewritten. // For example: // // int main() { // __block Foo *f; // __block int i; // // void (^myblock)() = ^() { // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten). // i = 77; // }; //} Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) { // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR // for each DeclRefExp where BYREFVAR is name of the variable. ValueDecl *VD = DeclRefExp->getDecl(); bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() || HasLocalVariableExternalStorage(DeclRefExp->getDecl()); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get("__forwarding"), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary); StringRef Name = VD->getName(); FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(Name), Context->VoidPtrTy, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(), VK_LValue, OK_Ordinary); // Need parens to enforce precedence. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(), DeclRefExp->getExprLoc(), ME); ReplaceStmt(DeclRefExp, PE); return PE; } // Rewrites the imported local variable V with external storage // (static, extern, etc.) as *V // Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) { ValueDecl *VD = DRE->getDecl(); if (VarDecl *Var = dyn_cast<VarDecl>(VD)) if (!ImportedLocalExternalDecls.count(Var)) return DRE; Expr *Exp = UnaryOperator::Create( const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(), VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride()); // Need parens to enforce precedence. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Exp); ReplaceStmt(DRE, PE); return PE; } void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) { SourceLocation LocStart = CE->getLParenLoc(); SourceLocation LocEnd = CE->getRParenLoc(); // Need to avoid trying to rewrite synthesized casts. if (LocStart.isInvalid()) return; // Need to avoid trying to rewrite casts contained in macros. if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd)) return; const char *startBuf = SM->getCharacterData(LocStart); const char *endBuf = SM->getCharacterData(LocEnd); QualType QT = CE->getType(); const Type* TypePtr = QT->getAs<Type>(); if (isa<TypeOfExprType>(TypePtr)) { const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr); QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType(); std::string TypeAsString = "("; RewriteBlockPointerType(TypeAsString, QT); TypeAsString += ")"; ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString); return; } // advance the location to startArgList. const char *argPtr = startBuf; while (*argPtr++ && (argPtr < endBuf)) { switch (*argPtr) { case '^': // Replace the '^' with '*'. LocStart = LocStart.getLocWithOffset(argPtr-startBuf); ReplaceText(LocStart, 1, "*"); break; } } } void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) { CastKind CastKind = IC->getCastKind(); if (CastKind != CK_BlockPointerToObjCPointerCast && CastKind != CK_AnyPointerToBlockPointerCast) return; QualType QT = IC->getType(); (void)convertBlockPointerToFunctionPointer(QT); std::string TypeString(QT.getAsString(Context->getPrintingPolicy())); std::string Str = "("; Str += TypeString; Str += ")"; InsertText(IC->getSubExpr()->getBeginLoc(), Str); } void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { SourceLocation DeclLoc = FD->getLocation(); unsigned parenCount = 0; // We have 1 or more arguments that have closure pointers. const char *startBuf = SM->getCharacterData(DeclLoc); const char *startArgList = strchr(startBuf, '('); assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); parenCount++; // advance the location to startArgList. DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf); assert((DeclLoc.isValid()) && "Invalid DeclLoc"); const char *argPtr = startArgList; while (*argPtr++ && parenCount) { switch (*argPtr) { case '^': // Replace the '^' with '*'. DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList); ReplaceText(DeclLoc, 1, "*"); break; case '(': parenCount++; break; case ')': parenCount--; break; } } } bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) { const FunctionProtoType *FTP; const PointerType *PT = QT->getAs<PointerType>(); if (PT) { FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); } else { const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); } if (FTP) { for (const auto &I : FTP->param_types()) if (isTopLevelBlockPointerType(I)) return true; } return false; } bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) { const FunctionProtoType *FTP; const PointerType *PT = QT->getAs<PointerType>(); if (PT) { FTP = PT->getPointeeType()->getAs<FunctionProtoType>(); } else { const BlockPointerType *BPT = QT->getAs<BlockPointerType>(); assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); FTP = BPT->getPointeeType()->getAs<FunctionProtoType>(); } if (FTP) { for (const auto &I : FTP->param_types()) { if (I->isObjCQualifiedIdType()) return true; if (I->isObjCObjectPointerType() && I->getPointeeType()->isObjCQualifiedInterfaceType()) return true; } } return false; } void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen) { const char *argPtr = strchr(Name, '('); assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); LParen = argPtr; // output the start. argPtr++; // skip past the left paren. unsigned parenCount = 1; while (*argPtr && parenCount) { switch (*argPtr) { case '(': parenCount++; break; case ')': parenCount--; break; default: break; } if (parenCount) argPtr++; } assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); RParen = argPtr; // output the end } void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { RewriteBlockPointerFunctionArgs(FD); return; } // Handle Variables and Typedefs. SourceLocation DeclLoc = ND->getLocation(); QualType DeclT; if (VarDecl *VD = dyn_cast<VarDecl>(ND)) DeclT = VD->getType(); else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND)) DeclT = TDD->getUnderlyingType(); else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) DeclT = FD->getType(); else llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled"); const char *startBuf = SM->getCharacterData(DeclLoc); const char *endBuf = startBuf; // scan backward (from the decl location) for the end of the previous decl. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) startBuf--; SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf); std::string buf; unsigned OrigLength=0; // *startBuf != '^' if we are dealing with a pointer to function that // may take block argument types (which will be handled below). if (*startBuf == '^') { // Replace the '^' with '*', computing a negative offset. buf = '*'; startBuf++; OrigLength++; } while (*startBuf != ')') { buf += *startBuf; startBuf++; OrigLength++; } buf += ')'; OrigLength++; if (PointerTypeTakesAnyBlockArguments(DeclT) || PointerTypeTakesAnyObjCQualifiedType(DeclT)) { // Replace the '^' with '*' for arguments. // Replace id<P> with id/*<>*/ DeclLoc = ND->getLocation(); startBuf = SM->getCharacterData(DeclLoc); const char *argListBegin, *argListEnd; GetExtentOfArgList(startBuf, argListBegin, argListEnd); while (argListBegin < argListEnd) { if (*argListBegin == '^') buf += '*'; else if (*argListBegin == '<') { buf += "/*"; buf += *argListBegin++; OrigLength++; while (*argListBegin != '>') { buf += *argListBegin++; OrigLength++; } buf += *argListBegin; buf += "*/"; } else buf += *argListBegin; argListBegin++; OrigLength++; } buf += ')'; OrigLength++; } ReplaceText(Start, OrigLength, buf); } /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes: /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst, /// struct Block_byref_id_object *src) { /// _Block_object_assign (&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object /// _Block_object_assign(&_dest->object, _src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } /// And: /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) { /// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT /// [|BLOCK_FIELD_IS_WEAK]) // object /// _Block_object_dispose(_src->object, /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK /// [|BLOCK_FIELD_IS_WEAK]) // block /// } std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag) { std::string S; if (CopyDestroyCache.count(flag)) return S; CopyDestroyCache.insert(flag); S = "static void __Block_byref_id_object_copy_"; S += utostr(flag); S += "(void *dst, void *src) {\n"; // offset into the object pointer is computed as: // void * + void* + int + int + void* + void * unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); unsigned VoidPtrSize = static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy)); unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth(); S += " _Block_object_assign((char*)dst + "; S += utostr(offset); S += ", *(void * *) ((char*)src + "; S += utostr(offset); S += "), "; S += utostr(flag); S += ");\n}\n"; S += "static void __Block_byref_id_object_dispose_"; S += utostr(flag); S += "(void *src) {\n"; S += " _Block_object_dispose(*(void * *) ((char*)src + "; S += utostr(offset); S += "), "; S += utostr(flag); S += ");\n}\n"; return S; } /// RewriteByRefVar - For each __block typex ND variable this routine transforms /// the declaration into: /// struct __Block_byref_ND { /// void *__isa; // NULL for everything except __weak pointers /// struct __Block_byref_ND *__forwarding; /// int32_t __flags; /// int32_t __size; /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object /// typex ND; /// }; /// /// It then replaces declaration of ND variable with: /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag, /// __size=sizeof(struct __Block_byref_ND), /// ND=initializer-if-any}; /// /// void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl, bool lastDecl) { int flag = 0; int isa = 0; SourceLocation DeclLoc = ND->getTypeSpecStartLoc(); if (DeclLoc.isInvalid()) // If type location is missing, it is because of missing type (a warning). // Use variable's location which is good for this case. DeclLoc = ND->getLocation(); const char *startBuf = SM->getCharacterData(DeclLoc); SourceLocation X = ND->getEndLoc(); X = SM->getExpansionLoc(X); const char *endBuf = SM->getCharacterData(X); std::string Name(ND->getNameAsString()); std::string ByrefType; RewriteByRefString(ByrefType, Name, ND, true); ByrefType += " {\n"; ByrefType += " void *__isa;\n"; RewriteByRefString(ByrefType, Name, ND); ByrefType += " *__forwarding;\n"; ByrefType += " int __flags;\n"; ByrefType += " int __size;\n"; // Add void *__Block_byref_id_object_copy; // void *__Block_byref_id_object_dispose; if needed. QualType Ty = ND->getType(); bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND); if (HasCopyAndDispose) { ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n"; ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n"; } QualType T = Ty; (void)convertBlockPointerToFunctionPointer(T); T.getAsStringInternal(Name, Context->getPrintingPolicy()); ByrefType += " " + Name + ";\n"; ByrefType += "};\n"; // Insert this type in global scope. It is needed by helper function. SourceLocation FunLocStart; if (CurFunctionDef) FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef); else { assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null"); FunLocStart = CurMethodDef->getBeginLoc(); } InsertText(FunLocStart, ByrefType); if (Ty.isObjCGCWeak()) { flag |= BLOCK_FIELD_IS_WEAK; isa = 1; } if (HasCopyAndDispose) { flag = BLOCK_BYREF_CALLER; QualType Ty = ND->getType(); // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well. if (Ty->isBlockPointerType()) flag |= BLOCK_FIELD_IS_BLOCK; else flag |= BLOCK_FIELD_IS_OBJECT; std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag); if (!HF.empty()) Preamble += HF; } // struct __Block_byref_ND ND = // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND), // initializer-if-any}; bool hasInit = (ND->getInit() != nullptr); // FIXME. rewriter does not support __block c++ objects which // require construction. if (hasInit) if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) { CXXConstructorDecl *CXXDecl = CExp->getConstructor(); if (CXXDecl && CXXDecl->isDefaultConstructor()) hasInit = false; } unsigned flags = 0; if (HasCopyAndDispose) flags |= BLOCK_HAS_COPY_DISPOSE; Name = ND->getNameAsString(); ByrefType.clear(); RewriteByRefString(ByrefType, Name, ND); std::string ForwardingCastType("("); ForwardingCastType += ByrefType + " *)"; ByrefType += " " + Name + " = {(void*)"; ByrefType += utostr(isa); ByrefType += "," + ForwardingCastType + "&" + Name + ", "; ByrefType += utostr(flags); ByrefType += ", "; ByrefType += "sizeof("; RewriteByRefString(ByrefType, Name, ND); ByrefType += ")"; if (HasCopyAndDispose) { ByrefType += ", __Block_byref_id_object_copy_"; ByrefType += utostr(flag); ByrefType += ", __Block_byref_id_object_dispose_"; ByrefType += utostr(flag); } if (!firstDecl) { // In multiple __block declarations, and for all but 1st declaration, // find location of the separating comma. This would be start location // where new text is to be inserted. DeclLoc = ND->getLocation(); const char *startDeclBuf = SM->getCharacterData(DeclLoc); const char *commaBuf = startDeclBuf; while (*commaBuf != ',') commaBuf--; assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','"); DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf); startBuf = commaBuf; } if (!hasInit) { ByrefType += "};\n"; unsigned nameSize = Name.size(); // for block or function pointer declaration. Name is already // part of the declaration. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) nameSize = 1; ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType); } else { ByrefType += ", "; SourceLocation startLoc; Expr *E = ND->getInit(); if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) startLoc = ECE->getLParenLoc(); else startLoc = E->getBeginLoc(); startLoc = SM->getExpansionLoc(startLoc); endBuf = SM->getCharacterData(startLoc); ReplaceText(DeclLoc, endBuf-startBuf, ByrefType); const char separator = lastDecl ? ';' : ','; const char *startInitializerBuf = SM->getCharacterData(startLoc); const char *separatorBuf = strchr(startInitializerBuf, separator); assert((*separatorBuf == separator) && "RewriteByRefVar: can't find ';' or ','"); SourceLocation separatorLoc = startLoc.getLocWithOffset(separatorBuf-startInitializerBuf); InsertText(separatorLoc, lastDecl ? "}" : "};\n"); } } void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) { // Add initializers for any closure decl refs. GetBlockDeclRefExprs(Exp->getBody()); if (BlockDeclRefs.size()) { // Unique all "by copy" declarations. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl()); } } // Unique all "by ref" declarations. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) { if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) { BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl()); BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl()); } } // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < BlockDeclRefs.size(); i++) if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || BlockDeclRefs[i]->getType()->isObjCObjectPointerType() || BlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl()); } } FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) { IdentifierInfo *ID = &Context->Idents.get(name); QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy); return FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), ID, FType, nullptr, SC_Extern, false, false); } Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp, const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) { const BlockDecl *block = Exp->getBlockDecl(); Blocks.push_back(Exp); CollectBlockDeclRefInfo(Exp); // Add inner imported variables now used in current block. int countOfInnerDecls = 0; if (!InnerBlockDeclRefs.empty()) { for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) { DeclRefExpr *Exp = InnerBlockDeclRefs[i]; ValueDecl *VD = Exp->getDecl(); if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) { // We need to save the copied-in variables in nested // blocks because it is needed at the end for some of the API generations. // See SynthesizeBlockLiterals routine. InnerDeclRefs.push_back(Exp); countOfInnerDecls++; BlockDeclRefs.push_back(Exp); BlockByCopyDeclsPtrSet.insert(VD); BlockByCopyDecls.push_back(VD); } if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) { InnerDeclRefs.push_back(Exp); countOfInnerDecls++; BlockDeclRefs.push_back(Exp); BlockByRefDeclsPtrSet.insert(VD); BlockByRefDecls.push_back(VD); } } // Find any imported blocks...they will need special attention. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() || InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() || InnerBlockDeclRefs[i]->getType()->isBlockPointerType()) ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl()); } InnerDeclRefsCount.push_back(countOfInnerDecls); std::string FuncName; if (CurFunctionDef) FuncName = CurFunctionDef->getNameAsString(); else if (CurMethodDef) BuildUniqueMethodName(FuncName, CurMethodDef); else if (GlobalVarDecl) FuncName = std::string(GlobalVarDecl->getNameAsString()); bool GlobalBlockExpr = block->getDeclContext()->getRedeclContext()->isFileContext(); if (GlobalBlockExpr && !GlobalVarDecl) { Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag); GlobalBlockExpr = false; } std::string BlockNumber = utostr(Blocks.size()-1); std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; // Get a pointer to the function type so we can cast appropriately. QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType()); QualType FType = Context->getPointerType(BFT); FunctionDecl *FD; Expr *NewRep; // Simulate a constructor call... std::string Tag; if (GlobalBlockExpr) Tag = "__global_"; else Tag = "__"; Tag += FuncName + "_block_impl_" + BlockNumber; FD = SynthBlockInitFunctionDecl(Tag); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation()); SmallVector<Expr*, 4> InitExprs; // Initialize the block function. FD = SynthBlockInitFunctionDecl(Func); DeclRefExpr *Arg = new (Context) DeclRefExpr( *Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); InitExprs.push_back(castExpr); // Initialize the block descriptor. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA"; VarDecl *NewVD = VarDecl::Create( *Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static); UnaryOperator *DescRefExpr = UnaryOperator::Create( const_cast<ASTContext &>(*Context), new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy, VK_LValue, SourceLocation()), UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); InitExprs.push_back(DescRefExpr); // Add initializers for any closure decl refs. if (BlockDeclRefs.size()) { Expr *Exp; // Output all "by copy" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(), E = BlockByCopyDecls.end(); I != E; ++I) { if (isObjCType((*I)->getType())) { // FIXME: Conform to ABI ([[obj retain] autorelease]). FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); QT = Context->getPointerType(QT); Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); } } else if (isTopLevelBlockPointerType((*I)->getType())) { FD = SynthBlockInitFunctionDecl((*I)->getName()); Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg); } else { FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); if (HasLocalVariableExternalStorage(*I)) { QualType QT = (*I)->getType(); QT = Context->getPointerType(QT); Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, QT, VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); } } InitExprs.push_back(Exp); } // Output all "by ref" declarations. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(), E = BlockByRefDecls.end(); I != E; ++I) { ValueDecl *ND = (*I); std::string Name(ND->getNameAsString()); std::string RecName; RewriteByRefString(RecName, Name, ND, true); IdentifierInfo *II = &Context->Idents.get(RecName.c_str() + sizeof("struct")); RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), II); assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl"); QualType castT = Context->getPointerType(Context->getTagDeclType(RD)); FD = SynthBlockInitFunctionDecl((*I)->getName()); Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(), VK_LValue, SourceLocation()); bool isNestedCapturedVar = false; if (block) for (const auto &CI : block->captures()) { const VarDecl *variable = CI.getVariable(); if (variable == ND && CI.isNested()) { assert (CI.isByRef() && "SynthBlockInitExpr - captured block variable is not byref"); isNestedCapturedVar = true; break; } } // captured nested byref variable has its address passed. Do not take // its address again. if (!isNestedCapturedVar) Exp = UnaryOperator::Create( const_cast<ASTContext &>(*Context), Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp); InitExprs.push_back(Exp); } } if (ImportedBlockDecls.size()) { // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR); unsigned IntSize = static_cast<unsigned>(Context->getTypeSize(Context->IntTy)); Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag), Context->IntTy, SourceLocation()); InitExprs.push_back(FlagExp); } NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue, SourceLocation(), FPOptionsOverride()); if (GlobalBlockExpr) { assert (!GlobalConstructionExp && "SynthBlockInitExpr - GlobalConstructionExp must be null"); GlobalConstructionExp = NewRep; NewRep = DRE; } NewRep = UnaryOperator::Create( const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast, NewRep); // Put Paren around the call. NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(), NewRep); BlockDeclRefs.clear(); BlockByRefDecls.clear(); BlockByRefDeclsPtrSet.clear(); BlockByCopyDecls.clear(); BlockByCopyDeclsPtrSet.clear(); ImportedBlockDecls.clear(); return NewRep; } bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) { if (const ObjCForCollectionStmt * CS = dyn_cast<ObjCForCollectionStmt>(Stmts.back())) return CS->getElement() == DS; return false; } //===----------------------------------------------------------------------===// // Function Body / Expression rewriting //===----------------------------------------------------------------------===// Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) { if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || isa<ForStmt>(S)) Stmts.push_back(S); else if (isa<ObjCForCollectionStmt>(S)) { Stmts.push_back(S); ObjCBcLabelNo.push_back(++BcLabelCount); } // Pseudo-object operations and ivar references need special // treatment because we're going to recursively rewrite them. if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) { if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) { return RewritePropertyOrImplicitSetter(PseudoOp); } else { return RewritePropertyOrImplicitGetter(PseudoOp); } } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) { return RewriteObjCIvarRefExpr(IvarRefExpr); } else if (isa<OpaqueValueExpr>(S)) S = cast<OpaqueValueExpr>(S)->getSourceExpr(); SourceRange OrigStmtRange = S->getSourceRange(); // Perform a bottom up rewrite of all children. for (Stmt *&childStmt : S->children()) if (childStmt) { Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt); if (newStmt) { childStmt = newStmt; } } if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) { SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs; llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts; InnerContexts.insert(BE->getBlockDecl()); ImportedLocalExternalDecls.clear(); GetInnerBlockDeclRefExprs(BE->getBody(), InnerBlockDeclRefs, InnerContexts); // Rewrite the block body in place. Stmt *SaveCurrentBody = CurrentBody; CurrentBody = BE->getBody(); PropParentMap = nullptr; // block literal on rhs of a property-dot-sytax assignment // must be replaced by its synthesize ast so getRewrittenText // works as expected. In this case, what actually ends up on RHS // is the blockTranscribed which is the helper function for the // block literal; as in: self.c = ^() {[ace ARR];}; bool saveDisableReplaceStmt = DisableReplaceStmt; DisableReplaceStmt = false; RewriteFunctionBodyOrGlobalInitializer(BE->getBody()); DisableReplaceStmt = saveDisableReplaceStmt; CurrentBody = SaveCurrentBody; PropParentMap = nullptr; ImportedLocalExternalDecls.clear(); // Now we snarf the rewritten text and stash it away for later use. std::string Str = Rewrite.getRewrittenText(BE->getSourceRange()); RewrittenBlockExprs[BE] = Str; Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs); //blockTranscribed->dump(); ReplaceStmt(S, blockTranscribed); return blockTranscribed; } // Handle specific things. if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S)) return RewriteAtEncode(AtEncode); if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S)) return RewriteAtSelector(AtSelector); if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S)) return RewriteObjCStringLiteral(AtString); if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S)) return RewriteObjCBoolLiteralExpr(BoolLitExpr); if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S)) return RewriteObjCBoxedExpr(BoxedExpr); if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S)) return RewriteObjCArrayLiteralExpr(ArrayLitExpr); if (ObjCDictionaryLiteral *DictionaryLitExpr = dyn_cast<ObjCDictionaryLiteral>(S)) return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr); if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) { #if 0 // Before we rewrite it, put the original message expression in a comment. SourceLocation startLoc = MessExpr->getBeginLoc(); SourceLocation endLoc = MessExpr->getEndLoc(); const char *startBuf = SM->getCharacterData(startLoc); const char *endBuf = SM->getCharacterData(endLoc); std::string messString; messString += "// "; messString.append(startBuf, endBuf-startBuf+1); messString += "\n"; // FIXME: Missing definition of // InsertText(clang::SourceLocation, char const*, unsigned int). // InsertText(startLoc, messString); // Tried this, but it didn't work either... // ReplaceText(startLoc, 0, messString.c_str(), messString.size()); #endif return RewriteMessageExpr(MessExpr); } if (ObjCAutoreleasePoolStmt *StmtAutoRelease = dyn_cast<ObjCAutoreleasePoolStmt>(S)) { return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease); } if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S)) return RewriteObjCTryStmt(StmtTry); if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S)) return RewriteObjCSynchronizedStmt(StmtTry); if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S)) return RewriteObjCThrowStmt(StmtThrow); if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S)) return RewriteObjCProtocolExpr(ProtocolExp); if (ObjCForCollectionStmt *StmtForCollection = dyn_cast<ObjCForCollectionStmt>(S)) return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtRange.getEnd()); if (BreakStmt *StmtBreakStmt = dyn_cast<BreakStmt>(S)) return RewriteBreakStmt(StmtBreakStmt); if (ContinueStmt *StmtContinueStmt = dyn_cast<ContinueStmt>(S)) return RewriteContinueStmt(StmtContinueStmt); // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls // and cast exprs. if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { // FIXME: What we're doing here is modifying the type-specifier that // precedes the first Decl. In the future the DeclGroup should have // a separate type-specifier that we can rewrite. // NOTE: We need to avoid rewriting the DeclStmt if it is within // the context of an ObjCForCollectionStmt. For example: // NSArray *someArray; // for (id <FooProtocol> index in someArray) ; // This is because RewriteObjCForCollectionStmt() does textual rewriting // and it depends on the original text locations/positions. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS)) RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin()); // Blocks rewrite rules. for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { Decl *SD = *DI; if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { if (isTopLevelBlockPointerType(ND->getType())) RewriteBlockPointerDecl(ND); else if (ND->getType()->isFunctionPointerType()) CheckFunctionPointerDecl(ND->getType(), ND); if (VarDecl *VD = dyn_cast<VarDecl>(SD)) { if (VD->hasAttr<BlocksAttr>()) { static unsigned uniqueByrefDeclCount = 0; assert(!BlockByRefDeclNo.count(ND) && "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl"); BlockByRefDeclNo[ND] = uniqueByrefDeclCount++; RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE)); } else RewriteTypeOfDecl(VD); } } if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); } } } if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) RewriteObjCQualifiedInterfaceTypes(CE); if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || isa<ForStmt>(S)) { assert(!Stmts.empty() && "Statement stack is empty"); assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) || isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back())) && "Statement stack mismatch"); Stmts.pop_back(); } // Handle blocks rewriting. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) { ValueDecl *VD = DRE->getDecl(); if (VD->hasAttr<BlocksAttr>()) return RewriteBlockDeclRefExpr(DRE); if (HasLocalVariableExternalStorage(VD)) return RewriteLocalVariableExternalStorage(DRE); } if (CallExpr *CE = dyn_cast<CallExpr>(S)) { if (CE->getCallee()->getType()->isBlockPointerType()) { Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee()); ReplaceStmt(S, BlockCall); return BlockCall; } } if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) { RewriteCastExpr(CE); } if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { RewriteImplicitCastObjCExpr(ICE); } #if 0 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) { CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation()); // Get the new text. std::string SStr; llvm::raw_string_ostream Buf(SStr); Replacement->printPretty(Buf); const std::string &Str = Buf.str(); printf("CAST = %s\n", &Str[0]); InsertText(ICE->getSubExpr()->getBeginLoc(), Str); delete S; return Replacement; } #endif // Return this stmt unmodified. return S; } void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) { for (auto *FD : RD->fields()) { if (isTopLevelBlockPointerType(FD->getType())) RewriteBlockPointerDecl(FD); if (FD->getType()->isObjCQualifiedIdType() || FD->getType()->isObjCQualifiedInterfaceType()) RewriteObjCQualifiedInterfaceTypes(FD); } } /// HandleDeclInMainFile - This is called for each top-level decl defined in the /// main file of the input. void RewriteModernObjC::HandleDeclInMainFile(Decl *D) { switch (D->getKind()) { case Decl::Function: { FunctionDecl *FD = cast<FunctionDecl>(D); if (FD->isOverloadedOperator()) return; // Since function prototypes don't have ParmDecl's, we check the function // prototype. This enables us to rewrite function declarations and // definitions using the same code. RewriteBlocksInFunctionProtoType(FD->getType(), FD); if (!FD->isThisDeclarationADefinition()) break; // FIXME: If this should support Obj-C++, support CXXTryStmt if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) { CurFunctionDef = FD; CurrentBody = Body; Body = cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); FD->setBody(Body); CurrentBody = nullptr; if (PropParentMap) { delete PropParentMap; PropParentMap = nullptr; } // This synthesizes and inserts the block "impl" struct, invoke function, // and any copy/dispose helper functions. InsertBlockLiteralsWithinFunction(FD); RewriteLineDirective(D); CurFunctionDef = nullptr; } break; } case Decl::ObjCMethod: { ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D); if (CompoundStmt *Body = MD->getCompoundBody()) { CurMethodDef = MD; CurrentBody = Body; Body = cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body)); MD->setBody(Body); CurrentBody = nullptr; if (PropParentMap) { delete PropParentMap; PropParentMap = nullptr; } InsertBlockLiteralsWithinMethod(MD); RewriteLineDirective(D); CurMethodDef = nullptr; } break; } case Decl::ObjCImplementation: { ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D); ClassImplementation.push_back(CI); break; } case Decl::ObjCCategoryImpl: { ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D); CategoryImplementation.push_back(CI); break; } case Decl::Var: { VarDecl *VD = cast<VarDecl>(D); RewriteObjCQualifiedInterfaceTypes(VD); if (isTopLevelBlockPointerType(VD->getType())) RewriteBlockPointerDecl(VD); else if (VD->getType()->isFunctionPointerType()) { CheckFunctionPointerDecl(VD->getType(), VD); if (VD->getInit()) { if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { RewriteCastExpr(CE); } } } else if (VD->getType()->isRecordType()) { RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl(); if (RD->isCompleteDefinition()) RewriteRecordBody(RD); } if (VD->getInit()) { GlobalVarDecl = VD; CurrentBody = VD->getInit(); RewriteFunctionBodyOrGlobalInitializer(VD->getInit()); CurrentBody = nullptr; if (PropParentMap) { delete PropParentMap; PropParentMap = nullptr; } SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName()); GlobalVarDecl = nullptr; // This is needed for blocks. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) { RewriteCastExpr(CE); } } break; } case Decl::TypeAlias: case Decl::Typedef: { if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { if (isTopLevelBlockPointerType(TD->getUnderlyingType())) RewriteBlockPointerDecl(TD); else if (TD->getUnderlyingType()->isFunctionPointerType()) CheckFunctionPointerDecl(TD->getUnderlyingType(), TD); else RewriteObjCQualifiedInterfaceTypes(TD); } break; } case Decl::CXXRecord: case Decl::Record: { RecordDecl *RD = cast<RecordDecl>(D); if (RD->isCompleteDefinition()) RewriteRecordBody(RD); break; } default: break; } // Nothing yet. } /// Write_ProtocolExprReferencedMetadata - This routine writer out the /// protocol reference symbols in the for of: /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA. static void Write_ProtocolExprReferencedMetadata(ASTContext *Context, ObjCProtocolDecl *PDecl, std::string &Result) { // Also output .objc_protorefs$B section and its meta-data. if (Context->getLangOpts().MicrosoftExt) Result += "static "; Result += "struct _protocol_t *"; Result += "_OBJC_PROTOCOL_REFERENCE_$_"; Result += PDecl->getNameAsString(); Result += " = &"; Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += ";\n"; } void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) { if (Diags.hasErrorOccurred()) return; RewriteInclude(); for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) { // translation of function bodies were postponed until all class and // their extensions and implementations are seen. This is because, we // cannot build grouping structs for bitfields until they are all seen. FunctionDecl *FDecl = FunctionDefinitionsSeen[i]; HandleTopLevelSingleDecl(FDecl); } // Here's a great place to add any extra declarations that may be needed. // Write out meta data for each @protocol(<expr>). for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) { RewriteObjCProtocolMetaData(ProtDecl, Preamble); Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble); } InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false); if (ClassImplementation.size() || CategoryImplementation.size()) RewriteImplementations(); for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) { ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i]; // Write struct declaration for the class matching its ivar declarations. // Note that for modern abi, this is postponed until the end of TU // because class extensions and the implementation might declare their own // private ivars. RewriteInterfaceDecl(CDecl); } // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(MainFileID)) { //printf("Changed:\n"); *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end()); } else { llvm::errs() << "No changes\n"; } if (ClassImplementation.size() || CategoryImplementation.size() || ProtocolExprDecls.size()) { // Rewrite Objective-c meta data* std::string ResultStr; RewriteMetaDataIntoBuffer(ResultStr); // Emit metadata. *OutFile << ResultStr; } // Emit ImageInfo; { std::string ResultStr; WriteImageInfo(ResultStr); *OutFile << ResultStr; } OutFile->flush(); } void RewriteModernObjC::Initialize(ASTContext &context) { InitializeCommon(context); Preamble += "#ifndef __OBJC2__\n"; Preamble += "#define __OBJC2__\n"; Preamble += "#endif\n"; // declaring objc_selector outside the parameter list removes a silly // scope related warning... if (IsHeader) Preamble = "#pragma once\n"; Preamble += "struct objc_selector; struct objc_class;\n"; Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; "; Preamble += "\n\tstruct objc_object *superClass; "; // Add a constructor for creating temporary objects. Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) "; Preamble += ": object(o), superClass(s) {} "; Preamble += "\n};\n"; if (LangOpts.MicrosoftExt) { // Define all sections using syntax that makes sense. // These are currently generated. Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n"; // These are generated but not necessary for functionality. Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n"; // These need be generated for performance. Currently they are not, // using API calls instead. Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n"; Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n"; } Preamble += "#ifndef _REWRITER_typedef_Protocol\n"; Preamble += "typedef struct objc_object Protocol;\n"; Preamble += "#define _REWRITER_typedef_Protocol\n"; Preamble += "#endif\n"; if (LangOpts.MicrosoftExt) { Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n"; Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n"; } else Preamble += "#define __OBJC_RW_DLLIMPORT extern\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n"; Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass"; Preamble += "(const char *);\n"; Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass"; Preamble += "(struct objc_class *);\n"; Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass"; Preamble += "(const char *);\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n"; // @synchronized hooks. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n"; Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n"; Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n"; Preamble += "#ifdef _WIN64\n"; Preamble += "typedef unsigned long long _WIN_NSUInteger;\n"; Preamble += "#else\n"; Preamble += "typedef unsigned int _WIN_NSUInteger;\n"; Preamble += "#endif\n"; Preamble += "#ifndef __FASTENUMERATIONSTATE\n"; Preamble += "struct __objcFastEnumerationState {\n\t"; Preamble += "unsigned long state;\n\t"; Preamble += "void **itemsPtr;\n\t"; Preamble += "unsigned long *mutationsPtr;\n\t"; Preamble += "unsigned long extra[5];\n};\n"; Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n"; Preamble += "#define __FASTENUMERATIONSTATE\n"; Preamble += "#endif\n"; Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n"; Preamble += "struct __NSConstantStringImpl {\n"; Preamble += " int *isa;\n"; Preamble += " int flags;\n"; Preamble += " char *str;\n"; Preamble += "#if _WIN64\n"; Preamble += " long long length;\n"; Preamble += "#else\n"; Preamble += " long length;\n"; Preamble += "#endif\n"; Preamble += "};\n"; Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n"; Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n"; Preamble += "#else\n"; Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n"; Preamble += "#endif\n"; Preamble += "#define __NSCONSTANTSTRINGIMPL\n"; Preamble += "#endif\n"; // Blocks preamble. Preamble += "#ifndef BLOCK_IMPL\n"; Preamble += "#define BLOCK_IMPL\n"; Preamble += "struct __block_impl {\n"; Preamble += " void *isa;\n"; Preamble += " int Flags;\n"; Preamble += " int Reserved;\n"; Preamble += " void *FuncPtr;\n"; Preamble += "};\n"; Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n"; Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n"; Preamble += "extern \"C\" __declspec(dllexport) " "void _Block_object_assign(void *, const void *, const int);\n"; Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n"; Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n"; Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n"; Preamble += "#else\n"; Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n"; Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n"; Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n"; Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n"; Preamble += "#endif\n"; Preamble += "#endif\n"; if (LangOpts.MicrosoftExt) { Preamble += "#undef __OBJC_RW_DLLIMPORT\n"; Preamble += "#undef __OBJC_RW_STATICIMPORT\n"; Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests. Preamble += "#define __attribute__(X)\n"; Preamble += "#endif\n"; Preamble += "#ifndef __weak\n"; Preamble += "#define __weak\n"; Preamble += "#endif\n"; Preamble += "#ifndef __block\n"; Preamble += "#define __block\n"; Preamble += "#endif\n"; } else { Preamble += "#define __block\n"; Preamble += "#define __weak\n"; } // Declarations required for modern objective-c array and dictionary literals. Preamble += "\n#include <stdarg.h>\n"; Preamble += "struct __NSContainer_literal {\n"; Preamble += " void * *arr;\n"; Preamble += " __NSContainer_literal (unsigned int count, ...) {\n"; Preamble += "\tva_list marker;\n"; Preamble += "\tva_start(marker, count);\n"; Preamble += "\tarr = new void *[count];\n"; Preamble += "\tfor (unsigned i = 0; i < count; i++)\n"; Preamble += "\t arr[i] = va_arg(marker, void *);\n"; Preamble += "\tva_end( marker );\n"; Preamble += " };\n"; Preamble += " ~__NSContainer_literal() {\n"; Preamble += "\tdelete[] arr;\n"; Preamble += " }\n"; Preamble += "};\n"; // Declaration required for implementation of @autoreleasepool statement. Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n"; Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n"; Preamble += "struct __AtAutoreleasePool {\n"; Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n"; Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n"; Preamble += " void * atautoreleasepoolobj;\n"; Preamble += "};\n"; // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long // as this avoids warning in any 64bit/32bit compilation model. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n"; } /// RewriteIvarOffsetComputation - This routine synthesizes computation of /// ivar offset. void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar, std::string &Result) { Result += "__OFFSETOFIVAR__(struct "; Result += ivar->getContainingInterface()->getNameAsString(); if (LangOpts.MicrosoftExt) Result += "_IMPL"; Result += ", "; if (ivar->isBitField()) ObjCIvarBitfieldGroupDecl(ivar, Result); else Result += ivar->getNameAsString(); Result += ")"; } /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI. /// struct _prop_t { /// const char *name; /// char *attributes; /// } /// struct _prop_list_t { /// uint32_t entsize; // sizeof(struct _prop_t) /// uint32_t count_of_properties; /// struct _prop_t prop_list[count_of_properties]; /// } /// struct _protocol_t; /// struct _protocol_list_t { /// long protocol_count; // Note, this is 32/64 bit /// struct _protocol_t * protocol_list[protocol_count]; /// } /// struct _objc_method { /// SEL _cmd; /// const char *method_type; /// char *_imp; /// } /// struct _method_list_t { /// uint32_t entsize; // sizeof(struct _objc_method) /// uint32_t method_count; /// struct _objc_method method_list[method_count]; /// } /// struct _protocol_t { /// id isa; // NULL /// const char *protocol_name; /// const struct _protocol_list_t * protocol_list; // super protocols /// const struct method_list_t *instance_methods; /// const struct method_list_t *class_methods; /// const struct method_list_t *optionalInstanceMethods; /// const struct method_list_t *optionalClassMethods; /// const struct _prop_list_t * properties; /// const uint32_t size; // sizeof(struct _protocol_t) /// const uint32_t flags; // = 0 /// const char ** extendedMethodTypes; /// } /// struct _ivar_t { /// unsigned long int *offset; // pointer to ivar offset location /// const char *name; /// const char *type; /// uint32_t alignment; /// uint32_t size; /// } /// struct _ivar_list_t { /// uint32 entsize; // sizeof(struct _ivar_t) /// uint32 count; /// struct _ivar_t list[count]; /// } /// struct _class_ro_t { /// uint32_t flags; /// uint32_t instanceStart; /// uint32_t instanceSize; /// uint32_t reserved; // only when building for 64bit targets /// const uint8_t *ivarLayout; /// const char *name; /// const struct _method_list_t *baseMethods; /// const struct _protocol_list_t *baseProtocols; /// const struct _ivar_list_t *ivars; /// const uint8_t *weakIvarLayout; /// const struct _prop_list_t *properties; /// } /// struct _class_t { /// struct _class_t *isa; /// struct _class_t *superclass; /// void *cache; /// IMP *vtable; /// struct _class_ro_t *ro; /// } /// struct _category_t { /// const char *name; /// struct _class_t *cls; /// const struct _method_list_t *instance_methods; /// const struct _method_list_t *class_methods; /// const struct _protocol_list_t *protocols; /// const struct _prop_list_t *properties; /// } /// MessageRefTy - LLVM for: /// struct _message_ref_t { /// IMP messenger; /// SEL name; /// }; /// SuperMessageRefTy - LLVM for: /// struct _super_message_ref_t { /// SUPER_IMP messenger; /// SEL name; /// }; static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) { static bool meta_data_declared = false; if (meta_data_declared) return; Result += "\nstruct _prop_t {\n"; Result += "\tconst char *name;\n"; Result += "\tconst char *attributes;\n"; Result += "};\n"; Result += "\nstruct _protocol_t;\n"; Result += "\nstruct _objc_method {\n"; Result += "\tstruct objc_selector * _cmd;\n"; Result += "\tconst char *method_type;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; Result += "\nstruct _protocol_t {\n"; Result += "\tvoid * isa; // NULL\n"; Result += "\tconst char *protocol_name;\n"; Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n"; Result += "\tconst struct method_list_t *instance_methods;\n"; Result += "\tconst struct method_list_t *class_methods;\n"; Result += "\tconst struct method_list_t *optionalInstanceMethods;\n"; Result += "\tconst struct method_list_t *optionalClassMethods;\n"; Result += "\tconst struct _prop_list_t * properties;\n"; Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n"; Result += "\tconst unsigned int flags; // = 0\n"; Result += "\tconst char ** extendedMethodTypes;\n"; Result += "};\n"; Result += "\nstruct _ivar_t {\n"; Result += "\tunsigned long int *offset; // pointer to ivar offset location\n"; Result += "\tconst char *name;\n"; Result += "\tconst char *type;\n"; Result += "\tunsigned int alignment;\n"; Result += "\tunsigned int size;\n"; Result += "};\n"; Result += "\nstruct _class_ro_t {\n"; Result += "\tunsigned int flags;\n"; Result += "\tunsigned int instanceStart;\n"; Result += "\tunsigned int instanceSize;\n"; const llvm::Triple &Triple(Context->getTargetInfo().getTriple()); if (Triple.getArch() == llvm::Triple::x86_64) Result += "\tunsigned int reserved;\n"; Result += "\tconst unsigned char *ivarLayout;\n"; Result += "\tconst char *name;\n"; Result += "\tconst struct _method_list_t *baseMethods;\n"; Result += "\tconst struct _objc_protocol_list *baseProtocols;\n"; Result += "\tconst struct _ivar_list_t *ivars;\n"; Result += "\tconst unsigned char *weakIvarLayout;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; Result += "\nstruct _class_t {\n"; Result += "\tstruct _class_t *isa;\n"; Result += "\tstruct _class_t *superclass;\n"; Result += "\tvoid *cache;\n"; Result += "\tvoid *vtable;\n"; Result += "\tstruct _class_ro_t *ro;\n"; Result += "};\n"; Result += "\nstruct _category_t {\n"; Result += "\tconst char *name;\n"; Result += "\tstruct _class_t *cls;\n"; Result += "\tconst struct _method_list_t *instance_methods;\n"; Result += "\tconst struct _method_list_t *class_methods;\n"; Result += "\tconst struct _protocol_list_t *protocols;\n"; Result += "\tconst struct _prop_list_t *properties;\n"; Result += "};\n"; Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n"; Result += "#pragma warning(disable:4273)\n"; meta_data_declared = true; } static void Write_protocol_list_t_TypeDecl(std::string &Result, long super_protocol_count) { Result += "struct /*_protocol_list_t*/"; Result += " {\n"; Result += "\tlong protocol_count; // Note, this is 32/64 bit\n"; Result += "\tstruct _protocol_t *super_protocols["; Result += utostr(super_protocol_count); Result += "];\n"; Result += "}"; } static void Write_method_list_t_TypeDecl(std::string &Result, unsigned int method_count) { Result += "struct /*_method_list_t*/"; Result += " {\n"; Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n"; Result += "\tunsigned int method_count;\n"; Result += "\tstruct _objc_method method_list["; Result += utostr(method_count); Result += "];\n"; Result += "}"; } static void Write__prop_list_t_TypeDecl(std::string &Result, unsigned int property_count) { Result += "struct /*_prop_list_t*/"; Result += " {\n"; Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; Result += "\tunsigned int count_of_properties;\n"; Result += "\tstruct _prop_t prop_list["; Result += utostr(property_count); Result += "];\n"; Result += "}"; } static void Write__ivar_list_t_TypeDecl(std::string &Result, unsigned int ivar_count) { Result += "struct /*_ivar_list_t*/"; Result += " {\n"; Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n"; Result += "\tunsigned int count;\n"; Result += "\tstruct _ivar_t ivar_list["; Result += utostr(ivar_count); Result += "];\n"; Result += "}"; } static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result, ArrayRef<ObjCProtocolDecl *> SuperProtocols, StringRef VarName, StringRef ProtocolName) { if (SuperProtocols.size() > 0) { Result += "\nstatic "; Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size()); Result += " "; Result += VarName; Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n"; for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) { ObjCProtocolDecl *SuperPD = SuperProtocols[i]; Result += "\t&"; Result += "_OBJC_PROTOCOL_"; Result += SuperPD->getNameAsString(); if (i == e-1) Result += "\n};\n"; else Result += ",\n"; } } } static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCMethodDecl *> Methods, StringRef VarName, StringRef TopLevelDeclName, bool MethodImpl) { if (Methods.size() > 0) { Result += "\nstatic "; Write_method_list_t_TypeDecl(Result, Methods.size()); Result += " "; Result += VarName; Result += TopLevelDeclName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n"; Result += "\t"; Result += utostr(Methods.size()); Result += ",\n"; for (unsigned i = 0, e = Methods.size(); i < e; i++) { ObjCMethodDecl *MD = Methods[i]; if (i == 0) Result += "\t{{(struct objc_selector *)\""; else Result += "\t{(struct objc_selector *)\""; Result += (MD)->getSelector().getAsString(); Result += "\""; Result += ", "; std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD); Result += "\""; Result += MethodTypeString; Result += "\""; Result += ", "; if (!MethodImpl) Result += "0"; else { Result += "(void *)"; Result += RewriteObj.MethodInternalNames[MD]; } if (i == e-1) Result += "}}\n"; else Result += "},\n"; } Result += "};\n"; } } static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCPropertyDecl *> Properties, const Decl *Container, StringRef VarName, StringRef ProtocolName) { if (Properties.size() > 0) { Result += "\nstatic "; Write__prop_list_t_TypeDecl(Result, Properties.size()); Result += " "; Result += VarName; Result += ProtocolName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n"; Result += "\t"; Result += utostr(Properties.size()); Result += ",\n"; for (unsigned i = 0, e = Properties.size(); i < e; i++) { ObjCPropertyDecl *PropDecl = Properties[i]; if (i == 0) Result += "\t{{\""; else Result += "\t{\""; Result += PropDecl->getName(); Result += "\","; std::string PropertyTypeString = Context->getObjCEncodingForPropertyDecl(PropDecl, Container); std::string QuotePropertyTypeString; RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString); Result += "\""; Result += QuotePropertyTypeString; Result += "\""; if (i == e-1) Result += "}}\n"; else Result += "},\n"; } Result += "};\n"; } } // Metadata flags enum MetaDataDlags { CLS = 0x0, CLS_META = 0x1, CLS_ROOT = 0x2, OBJC2_CLS_HIDDEN = 0x10, CLS_EXCEPTION = 0x20, /// (Obsolete) ARC-specific: this class has a .release_ivars method CLS_HAS_IVAR_RELEASER = 0x40, /// class was compiled with -fobjc-arr CLS_COMPILED_BY_ARC = 0x80 // (1<<7) }; static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result, unsigned int flags, const std::string &InstanceStart, const std::string &InstanceSize, ArrayRef<ObjCMethodDecl *>baseMethods, ArrayRef<ObjCProtocolDecl *>baseProtocols, ArrayRef<ObjCIvarDecl *>ivars, ArrayRef<ObjCPropertyDecl *>Properties, StringRef VarName, StringRef ClassName) { Result += "\nstatic struct _class_ro_t "; Result += VarName; Result += ClassName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += llvm::utostr(flags); Result += ", "; Result += InstanceStart; Result += ", "; Result += InstanceSize; Result += ", \n"; Result += "\t"; const llvm::Triple &Triple(Context->getTargetInfo().getTriple()); if (Triple.getArch() == llvm::Triple::x86_64) // uint32_t const reserved; // only when building for 64bit targets Result += "(unsigned int)0, \n\t"; // const uint8_t * const ivarLayout; Result += "0, \n\t"; Result += "\""; Result += ClassName; Result += "\",\n\t"; bool metaclass = ((flags & CLS_META) != 0); if (baseMethods.size() > 0) { Result += "(const struct _method_list_t *)&"; if (metaclass) Result += "_OBJC_$_CLASS_METHODS_"; else Result += "_OBJC_$_INSTANCE_METHODS_"; Result += ClassName; Result += ",\n\t"; } else Result += "0, \n\t"; if (!metaclass && baseProtocols.size() > 0) { Result += "(const struct _objc_protocol_list *)&"; Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName; Result += ",\n\t"; } else Result += "0, \n\t"; if (!metaclass && ivars.size() > 0) { Result += "(const struct _ivar_list_t *)&"; Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName; Result += ",\n\t"; } else Result += "0, \n\t"; // weakIvarLayout Result += "0, \n\t"; if (!metaclass && Properties.size() > 0) { Result += "(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; Result += ",\n"; } else Result += "0, \n"; Result += "};\n"; } static void Write_class_t(ASTContext *Context, std::string &Result, StringRef VarName, const ObjCInterfaceDecl *CDecl, bool metaclass) { bool rootClass = (!CDecl->getSuperClass()); const ObjCInterfaceDecl *RootClass = CDecl; if (!rootClass) { // Find the Root class RootClass = CDecl->getSuperClass(); while (RootClass->getSuperClass()) { RootClass = RootClass->getSuperClass(); } } if (metaclass && rootClass) { // Need to handle a case of use of forward declaration. Result += "\n"; Result += "extern \"C\" "; if (CDecl->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; } // Also, for possibility of 'super' metadata class not having been defined yet. if (!rootClass) { ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass(); Result += "\n"; Result += "extern \"C\" "; if (SuperClass->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t "; Result += VarName; Result += SuperClass->getNameAsString(); Result += ";\n"; if (metaclass && RootClass != SuperClass) { Result += "extern \"C\" "; if (RootClass->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t "; Result += VarName; Result += RootClass->getNameAsString(); Result += ";\n"; } } Result += "\nextern \"C\" __declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n"; Result += "\t"; if (metaclass) { if (!rootClass) { Result += "0, // &"; Result += VarName; Result += RootClass->getNameAsString(); Result += ",\n\t"; Result += "0, // &"; Result += VarName; Result += CDecl->getSuperClass()->getNameAsString(); Result += ",\n\t"; } else { Result += "0, // &"; Result += VarName; Result += CDecl->getNameAsString(); Result += ",\n\t"; Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ",\n\t"; } } else { Result += "0, // &OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ",\n\t"; if (!rootClass) { Result += "0, // &"; Result += VarName; Result += CDecl->getSuperClass()->getNameAsString(); Result += ",\n\t"; } else Result += "0,\n\t"; } Result += "0, // (void *)&_objc_empty_cache,\n\t"; Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t"; if (metaclass) Result += "&_OBJC_METACLASS_RO_$_"; else Result += "&_OBJC_CLASS_RO_$_"; Result += CDecl->getNameAsString(); Result += ",\n};\n"; // Add static function to initialize some of the meta-data fields. // avoid doing it twice. if (metaclass) return; const ObjCInterfaceDecl *SuperClass = rootClass ? CDecl : CDecl->getSuperClass(); Result += "static void OBJC_CLASS_SETUP_$_"; Result += CDecl->getNameAsString(); Result += "(void ) {\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += RootClass->getNameAsString(); Result += ";\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; if (rootClass) Result += "&OBJC_CLASS_$_"; else Result += "&OBJC_METACLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".isa = "; Result += "&OBJC_METACLASS_$_"; Result += CDecl->getNameAsString(); Result += ";\n"; if (!rootClass) { Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".superclass = "; Result += "&OBJC_CLASS_$_"; Result += SuperClass->getNameAsString(); Result += ";\n"; } Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString(); Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n"; Result += "}\n"; } static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ObjCCategoryDecl *CatDecl, ObjCInterfaceDecl *ClassDecl, ArrayRef<ObjCMethodDecl *> InstanceMethods, ArrayRef<ObjCMethodDecl *> ClassMethods, ArrayRef<ObjCProtocolDecl *> RefedProtocols, ArrayRef<ObjCPropertyDecl *> ClassProperties) { StringRef CatName = CatDecl->getName(); StringRef ClassName = ClassDecl->getName(); // must declare an extern class object in case this class is not implemented // in this TU. Result += "\n"; Result += "extern \"C\" "; if (ClassDecl->getImplementation()) Result += "__declspec(dllexport) "; else Result += "__declspec(dllimport) "; Result += "struct _class_t "; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ";\n"; Result += "\nstatic struct _category_t "; Result += "_OBJC_$_CATEGORY_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; Result += "{\n"; Result += "\t\""; Result += ClassName; Result += "\",\n"; Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName; Result += ",\n"; if (InstanceMethods.size() > 0) { Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; if (ClassMethods.size() > 0) { Result += "\t(const struct _method_list_t *)&"; Result += "_OBJC_$_CATEGORY_CLASS_METHODS_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; if (RefedProtocols.size() > 0) { Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_CATEGORY_PROTOCOLS_$_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; if (ClassProperties.size() > 0) { Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_"; Result += ClassName; Result += "_$_"; Result += CatName; Result += ",\n"; } else Result += "\t0,\n"; Result += "};\n"; // Add static function to initialize the class pointer in the category structure. Result += "static void OBJC_CATEGORY_SETUP_$_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; Result += "(void ) {\n"; Result += "\t_OBJC_$_CATEGORY_"; Result += ClassDecl->getNameAsString(); Result += "_$_"; Result += CatName; Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName; Result += ";\n}\n"; } static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCMethodDecl *> Methods, StringRef VarName, StringRef ProtocolName) { if (Methods.size() == 0) return; Result += "\nstatic const char *"; Result += VarName; Result += ProtocolName; Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n"; Result += "{\n"; for (unsigned i = 0, e = Methods.size(); i < e; i++) { ObjCMethodDecl *MD = Methods[i]; std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD, true); std::string QuoteMethodTypeString; RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString); Result += "\t\""; Result += QuoteMethodTypeString; Result += "\""; if (i == e-1) Result += "\n};\n"; else { Result += ",\n"; } } } static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCIvarDecl *> Ivars, ObjCInterfaceDecl *CDecl) { // FIXME. visibilty of offset symbols may have to be set; for Darwin // this is what happens: /** if (Ivar->getAccessControl() == ObjCIvarDecl::Private || Ivar->getAccessControl() == ObjCIvarDecl::Package || Class->getVisibility() == HiddenVisibility) Visibility should be: HiddenVisibility; else Visibility should be: DefaultVisibility; */ Result += "\n"; for (unsigned i =0, e = Ivars.size(); i < e; i++) { ObjCIvarDecl *IvarDecl = Ivars[i]; if (Context->getLangOpts().MicrosoftExt) Result += "__declspec(allocate(\".objc_ivar$B\")) "; if (!Context->getLangOpts().MicrosoftExt || IvarDecl->getAccessControl() == ObjCIvarDecl::Private || IvarDecl->getAccessControl() == ObjCIvarDecl::Package) Result += "extern \"C\" unsigned long int "; else Result += "extern \"C\" __declspec(dllexport) unsigned long int "; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result); else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))"; Result += " = "; RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result); Result += ";\n"; if (Ivars[i]->isBitField()) { // skip over rest of the ivar bitfields. SKIP_BITFIELDS(i , e, Ivars); } } } static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj, ASTContext *Context, std::string &Result, ArrayRef<ObjCIvarDecl *> OriginalIvars, StringRef VarName, ObjCInterfaceDecl *CDecl) { if (OriginalIvars.size() > 0) { Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl); SmallVector<ObjCIvarDecl *, 8> Ivars; // strip off all but the first ivar bitfield from each group of ivars. // Such ivars in the ivar list table will be replaced by their grouping struct // 'ivar'. for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) { if (OriginalIvars[i]->isBitField()) { Ivars.push_back(OriginalIvars[i]); // skip over rest of the ivar bitfields. SKIP_BITFIELDS(i , e, OriginalIvars); } else Ivars.push_back(OriginalIvars[i]); } Result += "\nstatic "; Write__ivar_list_t_TypeDecl(Result, Ivars.size()); Result += " "; Result += VarName; Result += CDecl->getNameAsString(); Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n"; Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n"; Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n"; for (unsigned i =0, e = Ivars.size(); i < e; i++) { ObjCIvarDecl *IvarDecl = Ivars[i]; if (i == 0) Result += "\t{{"; else Result += "\t {"; Result += "(unsigned long int *)&"; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result); else WriteInternalIvarName(CDecl, IvarDecl, Result); Result += ", "; Result += "\""; if (Ivars[i]->isBitField()) RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result); else Result += IvarDecl->getName(); Result += "\", "; QualType IVQT = IvarDecl->getType(); if (IvarDecl->isBitField()) IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl); std::string IvarTypeString, QuoteIvarTypeString; Context->getObjCEncodingForType(IVQT, IvarTypeString, IvarDecl); RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString); Result += "\""; Result += QuoteIvarTypeString; Result += "\", "; // FIXME. this alignment represents the host alignment and need be changed to // represent the target alignment. unsigned Align = Context->getTypeAlign(IVQT)/8; Align = llvm::Log2_32(Align); Result += llvm::utostr(Align); Result += ", "; CharUnits Size = Context->getTypeSizeInChars(IVQT); Result += llvm::utostr(Size.getQuantity()); if (i == e-1) Result += "}}\n"; else Result += "},\n"; } Result += "};\n"; } } /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data. void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, std::string &Result) { // Do not synthesize the protocol more than once. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl())) return; WriteModernMetadataDeclarations(Context, Result); if (ObjCProtocolDecl *Def = PDecl->getDefinition()) PDecl = Def; // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. for (auto *I : PDecl->protocols()) RewriteObjCProtocolMetaData(I, Result); // Construct method lists. std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods; std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods; for (auto *MD : PDecl->instance_methods()) { if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptInstanceMethods.push_back(MD); } else { InstanceMethods.push_back(MD); } } for (auto *MD : PDecl->class_methods()) { if (MD->getImplementationControl() == ObjCMethodDecl::Optional) { OptClassMethods.push_back(MD); } else { ClassMethods.push_back(MD); } } std::vector<ObjCMethodDecl *> AllMethods; for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++) AllMethods.push_back(InstanceMethods[i]); for (unsigned i = 0, e = ClassMethods.size(); i < e; i++) AllMethods.push_back(ClassMethods[i]); for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++) AllMethods.push_back(OptInstanceMethods[i]); for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++) AllMethods.push_back(OptClassMethods[i]); Write__extendedMethodTypes_initializer(*this, Context, Result, AllMethods, "_OBJC_PROTOCOL_METHOD_TYPES_", PDecl->getNameAsString()); // Protocol's super protocol list SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols()); Write_protocol_list_initializer(Context, Result, SuperProtocols, "_OBJC_PROTOCOL_REFS_", PDecl->getNameAsString()); Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_PROTOCOL_INSTANCE_METHODS_", PDecl->getNameAsString(), false); Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_PROTOCOL_CLASS_METHODS_", PDecl->getNameAsString(), false); Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods, "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_", PDecl->getNameAsString(), false); Write_method_list_t_initializer(*this, Context, Result, OptClassMethods, "_OBJC_PROTOCOL_OPT_CLASS_METHODS_", PDecl->getNameAsString(), false); // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties( PDecl->instance_properties()); Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties, /* Container */nullptr, "_OBJC_PROTOCOL_PROPERTIES_", PDecl->getNameAsString()); // Writer out root metadata for current protocol: struct _protocol_t Result += "\n"; if (LangOpts.MicrosoftExt) Result += "static "; Result += "struct _protocol_t _OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += " __attribute__ ((used)) = {\n"; Result += "\t0,\n"; // id is; is null Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n"; if (SuperProtocols.size() > 0) { Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (InstanceMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (ClassMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (OptInstanceMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (OptClassMethods.size() > 0) { Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; if (ProtocolProperties.size() > 0) { Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_"; Result += PDecl->getNameAsString(); Result += ",\n"; } else Result += "\t0,\n"; Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n"; Result += "\t0,\n"; if (AllMethods.size() > 0) { Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_"; Result += PDecl->getNameAsString(); Result += "\n};\n"; } else Result += "\t0\n};\n"; if (LangOpts.MicrosoftExt) Result += "static "; Result += "struct _protocol_t *"; Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString(); Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString(); Result += ";\n"; // Mark this protocol as having been generated. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second) llvm_unreachable("protocol already synthesized"); } /// hasObjCExceptionAttribute - Return true if this class or any super /// class has the __objc_exception__ attribute. /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen. static bool hasObjCExceptionAttribute(ASTContext &Context, const ObjCInterfaceDecl *OID) { if (OID->hasAttr<ObjCExceptionAttr>()) return true; if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) return hasObjCExceptionAttribute(Context, Super); return false; } void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, std::string &Result) { ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); // Explicitly declared @interface's are already synthesized. if (CDecl->isImplicitInterfaceDecl()) assert(false && "Legacy implicit interface rewriting not supported in moder abi"); WriteModernMetadataDeclarations(Context, Result); SmallVector<ObjCIvarDecl *, 8> IVars; for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) continue; IVars.push_back(IVD); } Write__ivar_list_t_initializer(*this, Context, Result, IVars, "_OBJC_$_INSTANCE_VARIABLES_", CDecl); // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) continue; if (!Prop->getPropertyIvarDecl()) continue; ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/)) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/)) InstanceMethods.push_back(Setter); } Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_INSTANCE_METHODS_", IDecl->getNameAsString(), true); SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CLASS_METHODS_", IDecl->getNameAsString(), true); // Protocols referenced in class declaration? // Protocol's super protocol list std::vector<ObjCProtocolDecl *> RefedProtocols; const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); I != E; ++I) { RefedProtocols.push_back(*I); // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(*I, Result); } Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CLASS_PROTOCOLS_$_", IDecl->getNameAsString()); // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, /* Container */IDecl, "_OBJC_$_PROP_LIST_", CDecl->getNameAsString()); // Data for initializing _class_ro_t metaclass meta-data uint32_t flags = CLS_META; std::string InstanceSize; std::string InstanceStart; bool classIsHidden = CDecl->getVisibility() == HiddenVisibility; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; InstanceSize = "sizeof(struct _class_t)"; InstanceStart = InstanceSize; Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, ClassMethods, nullptr, nullptr, nullptr, "_OBJC_METACLASS_RO_$_", CDecl->getNameAsString()); // Data for initializing _class_ro_t meta-data flags = CLS; if (classIsHidden) flags |= OBJC2_CLS_HIDDEN; if (hasObjCExceptionAttribute(*Context, CDecl)) flags |= CLS_EXCEPTION; if (!CDecl->getSuperClass()) // class is root flags |= CLS_ROOT; InstanceSize.clear(); InstanceStart.clear(); if (!ObjCSynthesizedStructs.count(CDecl)) { InstanceSize = "0"; InstanceStart = "0"; } else { InstanceSize = "sizeof(struct "; InstanceSize += CDecl->getNameAsString(); InstanceSize += "_IMPL)"; ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin(); if (IVD) { RewriteIvarOffsetComputation(IVD, InstanceStart); } else InstanceStart = InstanceSize; } Write__class_ro_t_initializer(Context, Result, flags, InstanceStart, InstanceSize, InstanceMethods, RefedProtocols, IVars, ClassProperties, "_OBJC_CLASS_RO_$_", CDecl->getNameAsString()); Write_class_t(Context, Result, "OBJC_METACLASS_$_", CDecl, /*metaclass*/true); Write_class_t(Context, Result, "OBJC_CLASS_$_", CDecl, /*metaclass*/false); if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyClasses.push_back(CDecl); } void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) { int ClsDefCount = ClassImplementation.size(); if (!ClsDefCount) return; Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n"; Result += "__declspec(allocate(\".objc_inithooks$B\")) "; Result += "static void *OBJC_CLASS_SETUP[] = {\n"; for (int i = 0; i < ClsDefCount; i++) { ObjCImplementationDecl *IDecl = ClassImplementation[i]; ObjCInterfaceDecl *CDecl = IDecl->getClassInterface(); Result += "\t(void *)&OBJC_CLASS_SETUP_$_"; Result += CDecl->getName(); Result += ",\n"; } Result += "};\n"; } void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) { int ClsDefCount = ClassImplementation.size(); int CatDefCount = CategoryImplementation.size(); // For each implemented class, write out all its meta data. for (int i = 0; i < ClsDefCount; i++) RewriteObjCClassMetaData(ClassImplementation[i], Result); RewriteClassSetupInitHook(Result); // For each implemented category, write out all its meta data. for (int i = 0; i < CatDefCount; i++) RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result); RewriteCategorySetupInitHook(Result); if (ClsDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_classlist$B\")) "; Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ ["; Result += llvm::utostr(ClsDefCount); Result += "]"; Result += " __attribute__((used, section (\"__DATA, __objc_classlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < ClsDefCount; i++) { Result += "\t&OBJC_CLASS_$_"; Result += ClassImplementation[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; if (!DefinedNonLazyClasses.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n"; Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t"; for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) { Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } } if (CatDefCount > 0) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_catlist$B\")) "; Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ ["; Result += llvm::utostr(CatDefCount); Result += "]"; Result += " __attribute__((used, section (\"__DATA, __objc_catlist," "regular,no_dead_strip\")))= {\n"; for (int i = 0; i < CatDefCount; i++) { Result += "\t&_OBJC_$_CATEGORY_"; Result += CategoryImplementation[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += CategoryImplementation[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } if (!DefinedNonLazyCategories.empty()) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n"; Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t"; for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) { Result += "\t&_OBJC_$_CATEGORY_"; Result += DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString(); Result += "_$_"; Result += DefinedNonLazyCategories[i]->getNameAsString(); Result += ",\n"; } Result += "};\n"; } } void RewriteModernObjC::WriteImageInfo(std::string &Result) { if (LangOpts.MicrosoftExt) Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n"; Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } "; // version 0, ObjCABI is 2 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n"; } /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category /// implementation. void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, std::string &Result) { WriteModernMetadataDeclarations(Context, Result); ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); // Find category declaration for this implementation. ObjCCategoryDecl *CDecl = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier()); std::string FullCategoryName = ClassDecl->getNameAsString(); FullCategoryName += "_$_"; FullCategoryName += CDecl->getNameAsString(); // Build _objc_method_list for class's instance methods if needed SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods()); // If any of our property implementations have associated getters or // setters, produce metadata for them as well. for (const auto *Prop : IDecl->property_impls()) { if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) continue; if (!Prop->getPropertyIvarDecl()) continue; ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) InstanceMethods.push_back(Setter); } Write_method_list_t_initializer(*this, Context, Result, InstanceMethods, "_OBJC_$_CATEGORY_INSTANCE_METHODS_", FullCategoryName, true); SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods()); Write_method_list_t_initializer(*this, Context, Result, ClassMethods, "_OBJC_$_CATEGORY_CLASS_METHODS_", FullCategoryName, true); // Protocols referenced in class declaration? // Protocol's super protocol list SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols()); for (auto *I : CDecl->protocols()) // Must write out all protocol definitions in current qualifier list, // and in their nested qualifiers before writing out current definition. RewriteObjCProtocolMetaData(I, Result); Write_protocol_list_initializer(Context, Result, RefedProtocols, "_OBJC_CATEGORY_PROTOCOLS_$_", FullCategoryName); // Protocol's property metadata. SmallVector<ObjCPropertyDecl *, 8> ClassProperties( CDecl->instance_properties()); Write_prop_list_t_initializer(*this, Context, Result, ClassProperties, /* Container */IDecl, "_OBJC_$_PROP_LIST_", FullCategoryName); Write_category_t(*this, Context, Result, CDecl, ClassDecl, InstanceMethods, ClassMethods, RefedProtocols, ClassProperties); // Determine if this category is also "non-lazy". if (ImplementationIsNonLazy(IDecl)) DefinedNonLazyCategories.push_back(CDecl); } void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) { int CatDefCount = CategoryImplementation.size(); if (!CatDefCount) return; Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n"; Result += "__declspec(allocate(\".objc_inithooks$B\")) "; Result += "static void *OBJC_CATEGORY_SETUP[] = {\n"; for (int i = 0; i < CatDefCount; i++) { ObjCCategoryImplDecl *IDecl = CategoryImplementation[i]; ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl(); ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface(); Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_"; Result += ClassDecl->getName(); Result += "_$_"; Result += CatDecl->getName(); Result += ",\n"; } Result += "};\n"; } // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or /// class methods. template<typename MethodIterator> void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin, MethodIterator MethodEnd, bool IsInstanceMethod, StringRef prefix, StringRef ClassName, std::string &Result) { if (MethodBegin == MethodEnd) return; if (!objc_impl_method) { /* struct _objc_method { SEL _cmd; char *method_types; void *_imp; } */ Result += "\nstruct _objc_method {\n"; Result += "\tSEL _cmd;\n"; Result += "\tchar *method_types;\n"; Result += "\tvoid *_imp;\n"; Result += "};\n"; objc_impl_method = true; } // Build _objc_method_list for class's methods if needed /* struct { struct _objc_method_list *next_method; int method_count; struct _objc_method method_list[]; } */ unsigned NumMethods = std::distance(MethodBegin, MethodEnd); Result += "\n"; if (LangOpts.MicrosoftExt) { if (IsInstanceMethod) Result += "__declspec(allocate(\".inst_meth$B\")) "; else Result += "__declspec(allocate(\".cls_meth$B\")) "; } Result += "static struct {\n"; Result += "\tstruct _objc_method_list *next_method;\n"; Result += "\tint method_count;\n"; Result += "\tstruct _objc_method method_list["; Result += utostr(NumMethods); Result += "];\n} _OBJC_"; Result += prefix; Result += IsInstanceMethod ? "INSTANCE" : "CLASS"; Result += "_METHODS_"; Result += ClassName; Result += " __attribute__ ((used, section (\"__OBJC, __"; Result += IsInstanceMethod ? "inst" : "cls"; Result += "_meth\")))= "; Result += "{\n\t0, " + utostr(NumMethods) + "\n"; Result += "\t,{{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString().c_str(); std::string MethodTypeString; Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); Result += "\", \""; Result += MethodTypeString; Result += "\", (void *)"; Result += MethodInternalNames[*MethodBegin]; Result += "}\n"; for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) { Result += "\t ,{(SEL)\""; Result += (*MethodBegin)->getSelector().getAsString().c_str(); std::string MethodTypeString; Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString); Result += "\", \""; Result += MethodTypeString; Result += "\", (void *)"; Result += MethodInternalNames[*MethodBegin]; Result += "}\n"; } Result += "\t }\n};\n"; } Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) { SourceRange OldRange = IV->getSourceRange(); Expr *BaseExpr = IV->getBase(); // Rewrite the base, but without actually doing replaces. { DisableReplaceStmtScope S(*this); BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr)); IV->setBase(BaseExpr); } ObjCIvarDecl *D = IV->getDecl(); Expr *Replacement = IV; if (BaseExpr->getType()->isObjCObjectPointerType()) { const ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType()); assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null"); // lookup which class implements the instance variable. ObjCInterfaceDecl *clsDeclared = nullptr; iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared); assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class"); // Build name of symbol holding ivar offset. std::string IvarOffsetName; if (D->isBitField()) ObjCIvarBitfieldGroupOffset(D, IvarOffsetName); else WriteInternalIvarName(clsDeclared, D, IvarOffsetName); ReferencedIvars[clsDeclared].insert(D); // cast offset to "char *". CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->getPointerType(Context->CharTy), CK_BitCast, BaseExpr); VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(IvarOffsetName), Context->UnsignedLongTy, nullptr, SC_Extern); DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy, VK_LValue, SourceLocation()); BinaryOperator *addExpr = BinaryOperator::Create( *Context, castExpr, DRE, BO_Add, Context->getPointerType(Context->CharTy), VK_PRValue, OK_Ordinary, SourceLocation(), FPOptionsOverride()); // Don't forget the parens to enforce the proper binding. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), addExpr); QualType IvarT = D->getType(); if (D->isBitField()) IvarT = GetGroupRecordTypeForObjCIvarBitfield(D); if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) { RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl(); RD = RD->getDefinition(); if (RD && !RD->getDeclName().getAsIdentifierInfo()) { // decltype(((Foo_IMPL*)0)->bar) * auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext()); // ivar in class extensions requires special treatment. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) CDecl = CatDecl->getClassInterface(); std::string RecName = std::string(CDecl->getName()); RecName += "_IMPL"; RecordDecl *RD = RecordDecl::Create( *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(), &Context->Idents.get(RecName)); QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD)); unsigned UnsignedIntSize = static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy)); Expr *Zero = IntegerLiteral::Create(*Context, llvm::APInt(UnsignedIntSize, 0), Context->UnsignedIntTy, SourceLocation()); Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero); ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), Zero); FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(D->getNameAsString()), IvarT, nullptr, /*BitWidth=*/nullptr, /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit( *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary); IvarT = Context->getDecltypeType(ME, ME->getType()); } } convertObjCTypeToCStyleType(IvarT); QualType castT = Context->getPointerType(IvarT); castExpr = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, PE); Expr *Exp = UnaryOperator::Create( const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT, VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride()); PE = new (Context) ParenExpr(OldRange.getBegin(), OldRange.getEnd(), Exp); if (D->isBitField()) { FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(), &Context->Idents.get(D->getNameAsString()), D->getType(), nullptr, /*BitWidth=*/D->getBitWidth(), /*Mutable=*/true, ICIS_NoInit); MemberExpr *ME = MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD, FD->getType(), VK_LValue, OK_Ordinary); Replacement = ME; } else Replacement = PE; } ReplaceStmtWithRange(IV, Replacement, OldRange); return Replacement; } #endif // CLANG_ENABLE_OBJC_REWRITER
295,372
94,020
/*-------------------------------------------------------------------- # required.h - R2TAO CORBA basic support # # Author: Martin Corino # # This program is free software; you can redistribute it and/or # modify it under the terms of the R2CORBA LICENSE which is # included with this program. # # Copyright (c) Remedy IT Expertise BV #------------------------------------------------------------------*/ #include "required.h" #include "exception.h" #include "typecode.h" #include "ace/Env_Value_T.h" #include "ace/Null_Mutex.h" #include "ace/Singleton.h" #include "ace/TSS_T.h" #include "tao/AnyTypeCode/Any.h" #include "tao/DynamicInterface/Unknown_User_Exception.h" #include "tao/debug.h" #include <memory> #define RUBY_INVOKE_FUNC RUBY_ALLOC_FUNC R2TAO_EXPORT VALUE r2tao_nsCORBA = 0; R2TAO_EXPORT VALUE r2tao_nsCORBA_Native = 0; extern void r2tao_Init_Exception(); extern void r2tao_Init_Object(); extern void r2tao_Init_ORB(); extern void r2tao_Init_Typecode(); extern void r2tao_init_Values(); class R2TAO_ObjectRegistry { friend class ACE_Singleton<R2TAO_ObjectRegistry, ACE_Null_Mutex>; private: R2TAO_ObjectRegistry() : registry_ (Qnil) { // create an anchoring object R2TAO_ObjectRegistry::registry_anchor_ = Data_Wrap_Struct (rb_cObject, 0, R2TAO_ObjectRegistry::registry_free, this); // prevent GC while Ruby lives rb_gc_register_address (&R2TAO_ObjectRegistry::registry_anchor_); // create registry Hash this->registry_ = rb_hash_new (); // create an instance variable to hold registry (prevents GC since anchor is registered) rb_ivar_set (R2TAO_ObjectRegistry::registry_anchor_, rb_intern ("@registry_"), this->registry_); R2TAO_ObjectRegistry::has_singleton_ = true; } static VALUE registry_anchor_; static bool has_singleton_; public: ~R2TAO_ObjectRegistry() { // no need to unregister; as we live as long as Ruby does // we had better let Ruby take care of cleaning up otherwise // we may end up in a race condition // Just mark the registry as destroyed R2TAO_ObjectRegistry::has_singleton_ = false; this->registry_ = Qnil; } void register_object (VALUE rbobj) { if (TAO_debug_level > 9) ACE_DEBUG ((LM_INFO, "R2TAO (%P|%t) - R2TAO_ObjectRegistry::register_object(%@) - reg=%@\n", rbobj, this->registry_)); if (!NIL_P(this->registry_)) { rb_hash_aset (this->registry_, rbobj, rbobj); } else { if (TAO_debug_level > 1) ACE_DEBUG ((LM_INFO, "R2TAO (%P|%t) - R2TAO_ObjectRegistry::register_object(%@) - " "not registring since registry is nil\n", rbobj)); } } void unregister_object (VALUE rbobj) { if (TAO_debug_level > 9) ACE_DEBUG ((LM_INFO, "R2TAO (%P|%t) - R2TAO_ObjectRegistry::unregister_object(%@) - reg=%@\n", rbobj, this->registry_)); if (!NIL_P(this->registry_)) { rb_hash_delete (this->registry_, rbobj); } } static bool has_singleton (); private: VALUE registry_; void clear_registry () { this->registry_ = Qnil; } static void registry_free(void *ptr) { // what came first? is registry singleton still there? if (R2TAO_ObjectRegistry::has_singleton ()) { // registry anchor is being GC-ed so clean up to prevent illegal access R2TAO_ObjectRegistry* objreg = reinterpret_cast<R2TAO_ObjectRegistry*> (ptr); objreg->clear_registry (); } } }; VALUE R2TAO_ObjectRegistry::registry_anchor_ = Qnil; bool R2TAO_ObjectRegistry::has_singleton_ = false; bool R2TAO_ObjectRegistry::has_singleton () { return R2TAO_ObjectRegistry::has_singleton_; } typedef ACE_Singleton<R2TAO_ObjectRegistry, ACE_Null_Mutex> R2TAO_OBJECTREGISTRY; #if defined(WIN32) && defined(_DEBUG) extern "C" R2TAO_EXPORT void Init_libr2taod() #else extern "C" R2TAO_EXPORT void Init_libr2tao() #endif { rb_eval_string("puts 'Init_libr2tao start' if $VERBOSE"); if (r2tao_nsCORBA) return; // TAO itself only does this when an ORB is initialized; we want it sooner if (TAO_debug_level <= 0) TAO_debug_level = ACE_Env_Value<u_int> ("TAO_ORB_DEBUG", 0); rb_eval_string("puts 'Init_libr2tao 2' if $VERBOSE"); VALUE klass = rb_define_module_under (rb_eval_string ("::R2CORBA"), "TAO"); rb_define_const (klass, "MAJOR_VERSION", INT2NUM (TAO_MAJOR_VERSION)); rb_define_const (klass, "MINOR_VERSION", INT2NUM (TAO_MINOR_VERSION)); rb_define_const (klass, "MICRO_VERSION", INT2NUM (TAO_MICRO_VERSION)); rb_define_const (klass, "VERSION", rb_str_new2 (TAO_VERSION)); rb_define_const (klass, "RUBY_THREAD_SUPPORT", #ifdef R2TAO_THREAD_SAFE Qtrue #else Qfalse #endif ); r2tao_nsCORBA = rb_eval_string("::R2CORBA::CORBA"); r2tao_nsCORBA_Native = rb_define_module_under (r2tao_nsCORBA, "Native"); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Exception' if $VERBOSE"); r2tao_Init_Exception(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Object' if $VERBOSE"); r2tao_Init_Object(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_ORB' if $VERBOSE"); r2tao_Init_ORB(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Typecode' if $VERBOSE"); r2tao_Init_Typecode(); rb_eval_string("puts 'Init_libr2tao r2tao_Init_Values' if $VERBOSE"); r2tao_init_Values(); } R2TAO_EXPORT void r2tao_check_type(VALUE x, VALUE t) { if (rb_obj_is_kind_of(x, t) != Qtrue) { VALUE rb_dump = rb_funcall (x, rb_intern ("inspect"), 0); rb_raise(r2tao_cBAD_PARAM, "wrong argument type %s (expected %s)\n", RSTRING_PTR(rb_dump), rb_class2name(t)); } } R2TAO_EXPORT void r2tao_register_object(VALUE rbobj) { R2TAO_OBJECTREGISTRY::instance ()->register_object (rbobj); } R2TAO_EXPORT void r2tao_unregister_object(VALUE rbobj) { if (R2TAO_ObjectRegistry::has_singleton ()) { R2TAO_OBJECTREGISTRY::instance ()->unregister_object (rbobj); } } #if defined (R2TAO_THREAD_SAFE) class R2TAO_GVLGuard { public: R2TAO_GVLGuard (bool lock=true) : lock_(lock) { TSSManager::set_indicator (this->lock_); } ~R2TAO_GVLGuard () { TSSManager::set_indicator (!this->lock_); } static bool gvl_locked (bool start_locked=false) { if (start_locked && !TSSManager::has_indicator ()) { TSSManager::set_indicator (start_locked); } return TSSManager::indicator (); } private: bool lock_; class TSSManager { public: TSSManager () { gvl_indicator_ = new ACE_TSS< ACE_TSS_Type_Adapter<u_int> > (); } ~TSSManager () { delete gvl_indicator_; gvl_indicator_ = nullptr; } static void set_indicator (bool val) { if (gvl_indicator_) (*gvl_indicator_)->operator u_int & () = (val ? 1 : 0); } static bool has_indicator () { return (gvl_indicator_ && (*gvl_indicator_).ts_object ()); } static bool indicator () { // if the TSS storage has alredy been destroyed we're in the exit procedure and the // GVL is always locked return (gvl_indicator_ == 0 || (*gvl_indicator_)->operator u_int () == 1); } private: static ACE_TSS< ACE_TSS_Type_Adapter<u_int> >* gvl_indicator_; }; static TSSManager tss_gvl_flag_; }; ACE_TSS< ACE_TSS_Type_Adapter<u_int> >* R2TAO_GVLGuard::TSSManager::gvl_indicator_; R2TAO_GVLGuard::TSSManager R2TAO_GVLGuard::tss_gvl_flag_; template <typename FTYPE> struct r2tao_gvl_call_arg { r2tao_gvl_call_arg (FTYPE func, void* data) : func_ (func), data_ (data) {} FTYPE func_; void* data_; }; void* r2tao_call_with_gvl (void *data) { R2TAO_GVLGuard gvl_guard_; r2tao_gvl_call_arg<void*(*)(void*)>& arg = *reinterpret_cast<r2tao_gvl_call_arg<void*(*)(void*)>*> (data); return (*arg.func_) (arg.data_); } void* r2tao_call_without_gvl (void *data) { R2TAO_GVLGuard gvl_guard_ (false); r2tao_gvl_call_arg<void*(*)(void*)>& arg = *reinterpret_cast<r2tao_gvl_call_arg<void*(*)(void*)>*> (data); return (*arg.func_) (arg.data_); } #endif R2TAO_EXPORT void* r2tao_call_thread_safe (void *(*func)(void *), void *data) { #if defined (R2TAO_THREAD_SAFE) if (!R2TAO_GVLGuard::gvl_locked ()) { r2tao_gvl_call_arg<void*(*)(void*)> arg(func, data); return rb_thread_call_with_gvl(r2tao_call_with_gvl, &arg); } #endif return (*func) (data); } R2TAO_EXPORT VALUE r2tao_blocking_call (VALUE (*func)(void*), void*data) { #if defined (R2TAO_THREAD_SAFE) if (R2TAO_GVLGuard::gvl_locked (true)) { r2tao_gvl_call_arg<VALUE(*)(void*)> arg(func, data); void *rc = rb_thread_call_without_gvl(r2tao_call_without_gvl, &arg, RUBY_UBF_IO, 0); return reinterpret_cast<VALUE> (rc); } #endif return (*func) (data); } R2TAO_EXPORT VALUE r2tao_blocking_call_ex (VALUE (*func)(void*), void*data, void (*unblock_func)(void*), void*unblock_data) { #if defined (R2TAO_THREAD_SAFE) if (R2TAO_GVLGuard::gvl_locked (true)) { r2tao_gvl_call_arg<VALUE(*)(void*)> arg(func, data); void *rc = rb_thread_call_without_gvl(r2tao_call_without_gvl, &arg, unblock_func, unblock_data); return reinterpret_cast<VALUE> (rc); } #else ACE_UNUSED_ARG(unblock_func); ACE_UNUSED_ARG(unblock_data); #endif return (*func) (data); } R2TAO_RBFuncall::R2TAO_RBFuncall (ID fnid, bool throw_on_ex) : fn_id_ (fnid), throw_on_ex_ (throw_on_ex), ex_caught_ (false) { } R2TAO_RBFuncall::R2TAO_RBFuncall (const char* fn, bool throw_on_ex) : fn_id_ (rb_intern (fn)), throw_on_ex_ (throw_on_ex), ex_caught_ (false) { } VALUE R2TAO_RBFuncall::invoke (VALUE rcvr, VALUE args) { return this->_invoke (FuncArgArray (rcvr, args)); } VALUE R2TAO_RBFuncall::invoke (VALUE rcvr, int argc, VALUE *args) { return this->_invoke (FuncArgList (rcvr, argc, args)); } VALUE R2TAO_RBFuncall::invoke (VALUE rcvr) { return this->_invoke (FuncArgList (rcvr, 0, 0)); } VALUE R2TAO_RBFuncall::_invoke (const FuncArgs& fa) { static ID interface_repository_id_ID = rb_intern ("_interface_repository_id");; this->ex_caught_ = false; // reset int invoke_state = 0; HelperArgs ha (*this, fa); VALUE result = rb_protect (RUBY_INVOKE_FUNC (R2TAO_RBFuncall::invoke_helper), (VALUE)&ha, &invoke_state); if (invoke_state) { if (this->throw_on_ex_) { // handle exception VALUE rexc = rb_gv_get ("$!"); if (rb_obj_is_kind_of(rexc, r2tao_cUserException) == Qtrue) { VALUE rextc = rb_eval_string ("R2CORBA::CORBA::Any.typecode_for_any ($!)"); if (rextc != Qnil) { CORBA::Any _xval; CORBA::TypeCode_ptr _xtc = r2corba_TypeCode_r2t (rextc); r2tao_Ruby2Any(_xval, _xtc, rexc); throw ::CORBA::UnknownUserException (_xval); } } if (rb_obj_is_kind_of(rexc, r2tao_cSystemException) == Qtrue) { VALUE rid = rb_funcall (rexc, interface_repository_id_ID, 0); CORBA::SystemException* _exc = TAO::create_system_exception (RSTRING_PTR (rid)); _exc->minor ( static_cast<CORBA::ULong> (NUM2ULONG (rb_iv_get (rexc, "@minor")))); _exc->completed ( static_cast<CORBA::CompletionStatus> (NUM2ULONG (rb_iv_get (rexc, "@completed")))); std::unique_ptr<CORBA::SystemException> e_ptr(_exc); _exc->_raise (); } else { rb_eval_string ("STDERR.puts $!.to_s+\"\\n\"+$!.backtrace.join(\"\\n\")"); throw ::CORBA::UNKNOWN (0, CORBA::COMPLETED_MAYBE); } } else { this->ex_caught_ = true; } } else { return result; } return Qnil; } VALUE R2TAO_RBFuncall::FuncArgArray::rb_invoke (ID fnid) const { return rb_apply (this->receiver_, fnid, this->args_); } VALUE R2TAO_RBFuncall::FuncArgList::rb_invoke (ID fnid) const { return rb_funcall2 (this->receiver_, fnid, this->argc_, this->args_); } VALUE R2TAO_RBFuncall::invoke_inner (const FuncArgs& fnargs) { return fnargs.rb_invoke (this->fn_id_); } VALUE R2TAO_RBFuncall::invoke_helper (VALUE arg) { HelperArgs* ha = reinterpret_cast<HelperArgs*> (arg); return ha->caller_.invoke_inner (ha->fnargs_); }
12,199
4,994
class ref_count_intf { unsigned d_count; public: ref_count_intf() : d_count(0) {} virtual ~ref_count_intf() = default; ref_count_intf(const ref_count_intf&) = default; ref_count_intf& operator=(const ref_count_intf&) = default; virtual void destroy()=0; void inc() { ++d_count; } bool dec() { if (--d_count == 0) { destroy(); } return d_count == 0; } }; template<typename T> class shared_ptr { template<typename U> class ref_count_impl: public ref_count_intf { U *pu; public: ref_count_impl(U *_pu) : pu(_pu) {} virtual void destroy() { delete pu; } }; ref_count_intf *d_rc_p; T *d_t_p; public: shared_ptr() : d_rc_p(nullptr), d_t_p(nullptr) {} /* shared_ptr(T *t) : d_rc_p(new ref_count_impl<T>(t)), d_t_p(t) { d_rc_p->inc(); } */ shared_ptr(const shared_ptr& s) : d_rc_p(s.d_rc_p), d_t_p(s.d_t_p) { d_rc_p->inc(); } /* shared_ptr& operator=(const shared_ptr& s) { if (this != &s) { if (d_rc_p && d_rc_p->dec()) { delete d_rc_p; } d_t_p = s.get(); d_rc_p = s.d_rc_p; d_rc_p->inc(); } return *this; } */ ~shared_ptr() { if(d_rc_p && d_rc_p->dec()) { delete d_rc_p; } } template<typename U> explicit shared_ptr(U *pu) : d_rc_p(new ref_count_impl<U>(pu)), d_t_p(pu) { d_rc_p->inc(); } template<typename U> friend class shared_ptr; template<typename U> shared_ptr(const shared_ptr<U>& s) : d_rc_p(s.d_rc_p), d_t_p(s.get()) { d_rc_p->inc(); } template<typename U> shared_ptr& operator=(const shared_ptr<U>& s) { if (!d_t_p || d_t_p != s.get()) { if (d_rc_p && d_rc_p->dec()) { delete d_rc_p; } d_t_p = s.get(); d_rc_p = s.d_rc_p; d_rc_p->inc(); } return *this; } T& operator*() const { return *d_t_p; } T * operator->() const { return d_t_p; } T * get() const { return d_t_p; } }; class Foo { public: Foo() = default; virtual ~Foo() = default; }; class Bar : public Foo {}; int main() { shared_ptr<Foo> foo; { shared_ptr<Bar> bar(new Bar); foo = bar; } return 0; }
2,361
970
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "SemanticScene.h" #include "GibsonSemanticScene.h" #include "Mp3dSemanticScene.h" #include "ReplicaSemanticScene.h" #include <algorithm> #include <fstream> #include <map> #include <sophus/se3.hpp> #include <sstream> #include <string> #include "esp/io/Io.h" #include "esp/io/Json.h" namespace esp { namespace scene { bool SemanticScene:: loadSemanticSceneDescriptor(const std::string& ssdFileName, SemanticScene& scene, const quatf& rotation /* = quatf::FromTwoVectors(-vec3f::UnitZ(), geo::ESP_GRAVITY) */) { bool success = false; bool exists = checkFileExists(ssdFileName, "loadSemanticSceneDescriptor"); if (exists) { // TODO: we need to investigate the possibility of adding an identifying tag // to the SSD config files. // Try file load mechanisms for various types // first try Mp3d try { // only returns false if file does not exist, or attempting to open it // fails // open stream and determine house format version try { std::ifstream ifs = std::ifstream(ssdFileName); std::string header; std::getline(ifs, header); if (header.find("ASCII 1.1") != std::string::npos) { success = buildMp3dHouse(ifs, scene, rotation); } else if (header.find("HM3D Semantic Annotations") != std::string::npos) { success = buildHM3DHouse(ifs, scene, rotation); } } catch (...) { success = false; } if (!success) { // if not successful then attempt to load known json files const io::JsonDocument& jsonDoc = io::parseJsonFile(ssdFileName); // if no error thrown, then we have loaded a json file of given name bool hasCorrectObjects = (jsonDoc.HasMember("objects") && jsonDoc["objects"].IsArray()); // check if also has "classes" tag, otherwise will assume it is a // gibson file if (jsonDoc.HasMember("classes") && jsonDoc["classes"].IsArray()) { // attempt to load replica or replicaCAD if has classes (replicaCAD // does not have objects in SSDescriptor) success = buildReplicaHouse(jsonDoc, scene, hasCorrectObjects, rotation); } else if (hasCorrectObjects) { // attempt to load gibson if has objects but not classes success = buildGibsonHouse(jsonDoc, scene, rotation); } } if (success) { // if successfully loaded, return true; return true; } } catch (...) { // if error thrown, assume it is because file load attempt fails success = false; } } // should only reach here if not successfully loaded namespace FileUtil = Cr::Utility::Directory; // check if constructed replica file exists in directory of passed // ssdFileName const std::string tmpFName = FileUtil::join(FileUtil::path(ssdFileName), "info_semantic.json"); if (FileUtil::exists(tmpFName)) { success = scene::SemanticScene::loadReplicaHouse(tmpFName, scene); } return success; } // SemanticScene::loadSemanticSceneDescriptor } // namespace scene } // namespace esp
3,316
964
/* drdec3.f -- translated by f2c (version 19990311). */ #include <ivp_physics.hxx> #if !( (defined(__MWERKS__) && defined(__POWERPC__)) || defined(GEKKO) ) #include <malloc.h> #endif #include <ivp_betterdebugmanager.hxx> #include <geompack.hxx> int IVP_Geompack::i_sign(int a, int b) { int x; x = (a >= 0 ? a : - a); return( b >= 0 ? x : -x); } double IVP_Geompack::d_sign(double a, double b) { double x; x = (a >= 0 ? a : - a); return( b >= 0 ? x : -x); } int IVP_Geompack::increase_memory(void **mem_block, int *mem_size, int size_of_element) { //// void *new_mem = p_realloc(*mem_block, (*mem_size) * 2 * size_of_element); #ifndef GEKKO void *new_mem = p_realloc(*mem_block, (*mem_size + 1024) * size_of_element); #else void *new_mem = p_malloc( (*mem_size + 1024) * size_of_element ); #endif if ( !new_mem ) { return(0); } #ifdef GEKKO memcpy(new_mem, mem_block, *mem_size); #endif *mem_block = new_mem; return(1); } void IVP_Geompack::decompose(struct geompack_parameters *params) { // Local variables int i; int retry_counter; // Initializing variables this->size_intworkarray = 12; // orig: maxiw [5000]. Should be divisible by 3 & 4!; this->size_doubleworkarray = 12; // orig: maxwk [5000]. Should be divisible by 3 & 4!; this->size_vcl = params->nvc + 2; // number of vertices (NOT bytesize of array!) this->size_polyhedronfirstfaceoffset = 2; // Leave this to "2" if there will never be more than one polyhedron to decompose. <orig. maxhf [200]> this->size_polyhedronfaceindices = 1; // number of entries (NOT bytesize of array!) <orig: maxpf [2000]> this->size_facearrays = params->nface + 2; // <orig. maxfp [800]> this->size_facevertexarrays = params->facep[params->nface*3]+2; // <orig. maxfv> this->size_ev = 200; this->hashtable_maxsize = 307; int * n_original_vertices_out = params->nvc_out; int * nface_out = params->nface_out; int * n_work_vertices_out = params->nvert_out; int * npolh_out = params->npolh_out; double ** vcl_out = params->vcl_out; int ** facep_out = params->facep_out; int ** fvl_out = params->fvl_out; *n_original_vertices_out = 0; *nface_out = 0; *n_work_vertices_out = 0; *npolh_out = 0; // TOLIN - relative tolerance used to determine TOL // TOL - relative tolerance MAX(TOLIN,100.0D0*EPS) where // EPS is approximation to machine epsilon // ANGACC - min acceptable dihedral angle in degrees produced by // a cut face // RDACC - minimum acceptable relative distance between a cut // plane and vertices not on plane this->angacc = params->angacc * IVP_PI / 180.0; this->rdacc = params->rdacc; // Initialize some basic values this->initcb_(params->tolin); // allocate necessary dynamic memory this->g_hashtable = (int *) p_calloc(this->hashtable_maxsize , sizeof(int)); this->g_intworkarray = (int *) p_calloc(this->size_intworkarray , sizeof(int)); // [5000] this->g_doubleworkarray = (double *)p_calloc(this->size_doubleworkarray , sizeof(double)); // [5000] this->g_polyhedronfirstfaceoffset = (int *) p_calloc(this->size_polyhedronfirstfaceoffset, sizeof(int)); // [200] this->g_polyhedronfaceindices = (int *) p_calloc(this->size_polyhedronfaceindices , 2*sizeof(int)); // [4000] this->g_normals = (double *)p_calloc(this->size_facearrays , 3*sizeof(double)); // [2400] this->g_facesdata = (int *) p_calloc(this->size_facearrays , 3*sizeof(int)); // [2400] this->g_facestype = (int *) p_calloc(this->size_facearrays , sizeof(int)); this->g_faceverticeslist = (int *) p_calloc(this->size_facevertexarrays , 6*sizeof(int)); // [21000] this->g_edge_angles = (double *)p_calloc(this->size_facevertexarrays , sizeof(double)); // [3500] this->g_ev = (int *) p_calloc(this->size_ev , sizeof(int)); if ( !this->g_facesdata || !this->g_facestype || !this->g_hashtable || !this->g_polyhedronfirstfaceoffset || !this->g_polyhedronfaceindices || !this->g_faceverticeslist || !this->g_intworkarray || !this->g_doubleworkarray || !this->g_edge_angles || !this->g_normals || !this->g_ev ) { IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "*** GEOMPACK: Out of memory!\n\n"); } } goto out_of_memory; } // N_ORIGINAL_VERTICES - number of original vertex coordinates (i.e. total number of polyhedron points without any duplicated points for different polygons!) // NFACE - number of faces in decomposition // NPOLH - number of polyhedra in decomposition this->n_original_vertices = params->nvc; this->nface = params->nface; this->npolh = 1; // if changed to anything higher than 1 you will have to adjust the variable 'this->size_polyhedronfirstfaceoffset' accordingly! // ----------------------------------------------------------------------- // Initializing polyhedral decomposition data structure. // ----------------------------------------------------------------------- // init 'vertex coordinate list' this->g_vcl = params->vcl; // init 'face pointer' list (offsets for each face into faceverticeslist) this->g_facesdata = params->facep; // set face type for each face to ZERO for (i=0; i<this->nface; i++) { this->g_facestype[i] = 0; } this->n_work_vertices = this->g_facesdata[this->nface*3] - 1; // face list: offsets of (face defining) points in VCL for (i=0; i<this->n_work_vertices; i++) { this->g_faceverticeslist[i*6] = params->fvl[i]; } // offsets into face list for each polyhedron (we will only process ONE polyhedron!) this->g_polyhedronfirstfaceoffset[0] = 1; this->g_polyhedronfirstfaceoffset[1] = this->nface+1; this->n_polyhedronfaces = this->g_polyhedronfirstfaceoffset[this->npolh] - 1; while ( ((2+this->n_polyhedronfaces)*1) > this->size_polyhedronfaceindices ) { // 2000 int res = increase_memory((void **)&this->g_polyhedronfaceindices, &this->size_polyhedronfaceindices, 2*sizeof(int)); if ( res == 0 ) { this->ierr = 500; goto GEOMPACK_abort; } // size_polyhedronfaceindices *= 2; this->size_polyhedronfaceindices += 1024; } // init 'this->g_polyhedronfaceindices' (?)... we will simply set these values to the number of the // corresponding face. for (i=1; i<=this->n_polyhedronfaces; i++) { this->g_polyhedronfaceindices[(i<<1)-2] = i; } this->hashtable_size = min(prime_(this->n_original_vertices + 2), this->hashtable_maxsize); // *********************************************************************** // ----------------------------------------------------------------------- // Init data structure // ----------------------------------------------------------------------- dsphdc_(); if (this->ierr != 0) { IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { if ( this->ierr == 500 ) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "*** GEOMPACK: Out of memory!\n\n"); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Premature abort due to above error.\n\n"); } } goto GEOMPACK_abort; } IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { int n_reflex_edges; double minimum_angle; int mem_iwa; int mem_dwa; int mem_vcl; int mem_pffl; int mem_pfil; int mem_fl; int mem_fvl; int mem_total; // calculate some statistical values n_reflex_edges = 0; minimum_angle = IVP_PI * 2.0f; // set minimum angle to 2*pi for (i=0; i<this->n_work_vertices; i++) { if (this->g_edge_angles[i] > IVP_PI + this->tolerance) { n_reflex_edges++; } if (this->g_edge_angles[i] > -1.0) { // Computing minimum angle in convex decomposition minimum_angle = min(minimum_angle, this->g_edge_angles[i]); } } minimum_angle = minimum_angle * 180.0f / IVP_PI; ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Statistics after initializing polyhedral decomposition data structure:\n"); mem_iwa = this->size_intworkarray*sizeof(int); mem_dwa = this->size_doubleworkarray*sizeof(double); mem_vcl = this->size_vcl*3*sizeof(double); mem_pffl = this->size_polyhedronfirstfaceoffset*sizeof(int); mem_pfil = this->size_polyhedronfaceindices*2*sizeof(int); mem_fl = this->size_facearrays*sizeof(int)+this->size_facearrays*3*sizeof(int)+this->size_facearrays*3*sizeof(double); mem_fvl = this->size_facevertexarrays*6*sizeof(int)+this->size_facevertexarrays*sizeof(double); mem_total = mem_iwa+ mem_dwa + mem_vcl + mem_pffl + mem_pfil + mem_fl + mem_fvl; IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL2) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for int WORK ARRAY: %d bytes\n" , mem_iwa); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for DOUBLE WORK ARRAY: %d bytes\n" , mem_dwa); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for VERTEX COORDINATE LIST: %d bytes\n" , mem_vcl); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for POLYHEDRON FIRST FACE LIST: %d bytes\n", mem_pffl); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for POLYHEDRON FACE INDEX LIST: %d bytes\n", mem_pfil); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for FACE LISTS: %d bytes\n" , mem_fl); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for FACE VERTICES LISTS: %d bytes\n" , mem_fvl); } else { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Total memory allocated: %d bytes\n", mem_total); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_ORIGINAL_VERTICES = %d\n", this->n_original_vertices); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "NFACE = %d\n", this->nface); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_WORK_VERTICES = %d\n", this->n_work_vertices); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "NPOLH = %d\n", this->npolh); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_POLYHEDRONFACES = %d\n", this->n_polyhedronfaces); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_REFLEX_EDGES = %d\n", n_reflex_edges); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "MINIMUM_ANGLE = %f\n", minimum_angle); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "\n"); } } // ----------------------------------------------------------------------- // Decompose polyhedral region into convex parts. // ----------------------------------------------------------------------- retry_counter = 1; Retry_convex_decomposition: // *********************************************************************** this->cvdec3_(); if ( (this->ierr != 0) && (this->ierr != 327) ) { // abort on error but skip "reflex edge" resolving problems IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { if ( this->ierr == 500 ) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "*** GEOMPACK: Out of memory!\n\n"); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Premature abort due to above error.\n\n"); } } goto GEOMPACK_abort; } IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { int n_reflex_edges; double minimum_angle; int mem_iwa; int mem_dwa; int mem_vcl; int mem_pffl; int mem_pfil; int mem_fl; int mem_fvl; int mem_total; // calculate some statistical values n_reflex_edges = 0; minimum_angle = IVP_PI * 2.0f; // set minimum angle to 2*pi for (i=0; i<this->n_work_vertices; i++) { if (this->g_edge_angles[i] > IVP_PI + this->tolerance) { n_reflex_edges++; } if (this->g_edge_angles[i] > -1.0) { // Computing minimum angle in convex decomposition minimum_angle = min(minimum_angle, this->g_edge_angles[i]); } } minimum_angle = minimum_angle * 180.0f / IVP_PI; ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Intermediate decomposition statistics:\n"); mem_iwa = this->size_intworkarray*sizeof(int); mem_dwa = this->size_doubleworkarray*sizeof(double); mem_vcl = this->size_vcl*3*sizeof(double); mem_pffl = this->size_polyhedronfirstfaceoffset*sizeof(int); mem_pfil = this->size_polyhedronfaceindices*2*sizeof(int); mem_fl = this->size_facearrays*sizeof(int)+this->size_facearrays*3*sizeof(int)+this->size_facearrays*3*sizeof(double); mem_fvl = this->size_facevertexarrays*6*sizeof(int)+this->size_facevertexarrays*sizeof(double); mem_total = mem_iwa+ mem_dwa + mem_vcl + mem_pffl + mem_pfil + mem_fl + mem_fvl; IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL2) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for int WORK ARRAY: %d bytes\n" , mem_iwa); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for DOUBLE WORK ARRAY: %d bytes\n" , mem_dwa); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for VERTEX COORDINATE LIST: %d bytes\n" , mem_vcl); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for POLYHEDRON FIRST FACE LIST: %d bytes\n", mem_pffl); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for POLYHEDRON FACE INDEX LIST: %d bytes\n", mem_pfil); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for FACE LISTS: %d bytes\n" , mem_fl); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "Memory allocated for FACE VERTICES LISTS: %d bytes\n" , mem_fvl); } else { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Total memory allocated: %d bytes\n", mem_total); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_ORIGINAL_VERTICES = %d\n", this->n_original_vertices); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "NFACE = %d\n", this->nface); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_WORK_VERTICES = %d\n", this->n_work_vertices); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "NPOLH = %d\n", this->npolh); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_POLYHEDRONFACES = %d\n", this->n_polyhedronfaces); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_REFLEX_EDGES = %d\n", n_reflex_edges); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "MINIMUM_ANGLE = %f\n", minimum_angle); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "\n"); } } if (this->ierr == 327) { // unresolved reflex edge if (retry_counter < 36) { // orig. 3 this->angacc -= IVP_PI / 36.0; // orig. 36.0 if (this->angacc > 0.0) { this->rdacc *= 0.95; this->ierr = 0; retry_counter++; IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Retrying with <angacc=%f> and <rdacc=%f>\n\n", this->angacc, this->rdacc); } } goto Retry_convex_decomposition; } } IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Premature abort due to difficulties in resolving some reflex edge(s).\n\n"); } } goto GEOMPACK_abort; } // ----------------------------------------------------------------------- // Final output. // ----------------------------------------------------------------------- IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "+++ Convex decomposition successful!\n\n"); } IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL2) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "VCL (vertex coordinate list)\n"); for (i=1; i<=this->n_original_vertices; i++) { int j; printf("#%d : \t", i); for (j=1; j<=3; j++) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "%f ", this->g_vcl[j+(i*3)-4]); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "\n"); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "\n"); for (i=1; i<=this->nface; i++) { int j; ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "i=%d\tfacesdata={", i); for (j=1; j<=3; j++) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "%d ", this->g_facesdata[j+(i*3)-4]); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "} facestype[%d]=%d\tnormals={", i-1, this->g_facestype[i-1]); for (j=1; j<=3; j++) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "%f ", this->g_normals[j+(i*3)-4]); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "\n"); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "\n\n"); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "FaceVertexList >>FVL<<\n"); for (i=1; i<=this->n_work_vertices; i++) { int j; ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "#%d\t", i); for (j=1; j<=6; j++) { switch (j) { case 1: ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "LOC = "); break; case 2: ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "FACN = "); break; case 3: ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "SUCC = "); break; case 4: ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "PRED = "); break; case 5: ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "EDGA = "); break; case 6: ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "EDGC = "); break; } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "%d\t", this->g_faceverticeslist[j+(i*6)-7]); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "\t(%f Grad)\n", this->g_edge_angles[i-1]/IVP_PI*180.0); } ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL2, "\n\n"); } #if 0 s_wsfe(&io___90); for (i=0; i<this->npolh; i++) { do_fio(1, (char *)&this->g_polyhedronfirstfaceoffset[i], (ftnlen)sizeof(int)); } e_wsfe(); s_wsfe(&io___91); for (i__ = 1; i__ <= this->n_polyhedronfaces; i__++) { int j; do_fio(1, (char *)&i__, (ftnlen)sizeof(int)); for (j=1; j<=2; j++) { do_fio(1, (char *)&this->g_polyhedronfaceindices[j + (i__ << 1) - 3], (ftnlen) sizeof(int)); } } e_wsfe(); #endif } GEOMPACK_abort: IVP_IF(1) { IVP_IFDEBUG(IVP_DM_GEOMPACK_LEVEL1) { ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "Final GEOMPACK statistics:\n"); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_ORIGINAL_VERTICES \t= %d (number of vertex coordinates)\n", this->n_original_vertices); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "NFACE \t= %d (number of faces in polyhedral decomposition)\n", this->nface); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "N_WORK_VERTICES \t= %d (number of positions used in FVL array)\n", this->n_work_vertices); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "NPOLH \t= %d (number of polyhedra in decomposition)\n", this->npolh); ivp_debugmanager.dprint(IVP_DM_GEOMPACK_LEVEL1, "\n\n"); } } *n_original_vertices_out = this->n_original_vertices; *nface_out = this->nface; *n_work_vertices_out = this->n_work_vertices; *npolh_out = this->npolh; *facep_out = &this->g_facesdata[0]; *fvl_out = &this->g_faceverticeslist[0]; *vcl_out = &this->g_vcl[0]; out_of_memory: P_FREE(this->g_facestype); P_FREE(this->g_hashtable); P_FREE(this->g_polyhedronfirstfaceoffset); P_FREE(this->g_polyhedronfaceindices); P_FREE(this->g_intworkarray); P_FREE(this->g_doubleworkarray); P_FREE(this->g_edge_angles); P_FREE(this->g_normals); P_FREE(this->g_ev); return; }
20,604
8,681
/* * Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient> * * 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 "particle.h" #include "particleaffector.h" #include <framework/core/clock.h> ParticleAffector::ParticleAffector() { m_active = false; m_finished = false; m_delay = 0; m_duration = 0; m_elapsedTime = 0; } void ParticleAffector::update(float elapsedTime) { if(m_duration >= 0 && m_elapsedTime >= m_duration + m_delay) { m_finished = true; return; } if(!m_active && m_elapsedTime > m_delay) m_active = true; m_elapsedTime += elapsedTime; } bool ParticleAffector::load(const OTMLNodePtr& node) { float minDelay = 0, maxDelay = 0; float minDuration = -1, maxDuration = -1; for(const OTMLNodePtr& childNode : node->children()) { if(childNode->tag() == "delay") { minDelay = childNode->value<float>(); maxDelay = childNode->value<float>(); } else if(childNode->tag() == "min-delay") minDelay = childNode->value<float>(); else if(childNode->tag() == "max-delay") maxDelay = childNode->value<float>(); if(childNode->tag() == "duration") { minDuration = childNode->value<float>(); maxDuration = childNode->value<float>(); } else if(childNode->tag() == "min-duration") minDuration = childNode->value<float>(); else if(childNode->tag() == "max-duration") maxDuration = childNode->value<float>(); } m_delay = Fw::randomRange(minDelay, maxDelay); m_duration = Fw::randomRange(minDuration, maxDuration); return true; } bool GravityAffector::load(const OTMLNodePtr& node) { if(!ParticleAffector::load(node)) return false; m_angle = 270 * DEG_TO_RAD; m_gravity = 9.8; for(const OTMLNodePtr& childNode : node->children()) { if(childNode->tag() == "angle") m_angle = childNode->value<float>() * DEG_TO_RAD; else if(childNode->tag() == "gravity") m_gravity = childNode->value<float>(); } return true; } void GravityAffector::updateParticle(const ParticlePtr& particle, float elapsedTime) { if(!m_active) return; PointF velocity = particle->getVelocity(); velocity += PointF(m_gravity * elapsedTime * cos(m_angle), m_gravity * elapsedTime * sin(m_angle)); particle->setVelocity(velocity); } bool AttractionAffector::load(const OTMLNodePtr& node) { if(!ParticleAffector::load(node)) return false; m_acceleration = 32; m_reduction = 0; m_repelish = false; for(const OTMLNodePtr& childNode : node->children()) { if(childNode->tag() == "position") m_position = childNode->value<Point>(); else if(childNode->tag() == "acceleration") m_acceleration = childNode->value<float>(); else if(childNode->tag() == "velocity-reduction-percent") m_reduction = childNode->value<float>(); else if(childNode->tag() == "repelish") m_repelish = childNode->value<bool>(); } return true; } void AttractionAffector::updateParticle(const ParticlePtr& particle, float elapsedTime) { if(!m_active) return; PointF pPosition = particle->getPosition(); PointF d = PointF(m_position.x - pPosition.x, pPosition.y - m_position.y); if(d.length() == 0) return; PointF direction = PointF(1, 1); if(m_repelish) direction = PointF(-1, -1); PointF pVelocity = particle->getVelocity() + (d / d.length() * m_acceleration * elapsedTime) * direction; particle->setVelocity(pVelocity - pVelocity * m_reduction/100.0 * elapsedTime); }
4,772
1,590
#include <iostream> #include <fstream> #include <cstring> #include <glad/glad.h> #include "debug.h" #include "model.h" Model::Model(const char *vertexShaderSourcePath, const char *fragmentShaderSourcePath) { char vPath[128] = "\0", fPath[128] = "\0"; fullPath(vertexShaderSourcePath, vPath); fullPath(fragmentShaderSourcePath, fPath); char vSource[10240] = "\0", fSource[10240] = "\0"; loadSource(vPath, vSource); loadSource(fPath, fSource); compileVertexShader(vSource); compileFragmentShader(fSource); compileLinkProgram(); } Model::~Model() { // delete all? glDeleteShader(vertexShader); glDeleteShader(fragmentShader); glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteProgram(program); } void Model::render() { glUseProgram(program); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); } void Model::toX(float *vertices, unsigned int size) { createVBO(vertices, size); } void Model::fullPath(const char *path, char *full) { strcat(full, __DIR__); //@TODO strcat(full, path); strcat(full, ".txt"); DEBUG("MODEL::FULLPATH", full, DEBUG_L::INFO); } void Model::loadSource(const char *path, char *source) { std::ifstream file(path); if (!file) { DEBUG("MODEL::LOADSOURCE", "failed open file", DEBUG_L::ERROR); return; } // get length of file file.seekg(0, file.end); int length = file.tellg(); file.seekg(0, file.beg); // if length > 10k, throw ERROR if (length > 10240) { DEBUG("MODEL::LOADSOURCE ", "length must < 1KB", DEBUG_L::ERROR); return; } // @TODO file.read(source, length); DEBUG("MODEL::LOADSOURCE", source, DEBUG_L::INFO); file.close(); } unsigned int Model::getShaderWithSource(const char *source, unsigned int type) { if (!source) return -1; //@TODO type check int result = 0; char message[512]; unsigned int shader; shader = glCreateShader(type); glShaderSource(shader, 1, &source, NULL); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if (!result) { glGetShaderInfoLog(shader, 512, NULL, message); // @TODO DEBUG("MODEL::COMPILE", message, DEBUG_L::ERROR); } return shader; } void Model::compileVertexShader(const char *source) { vertexShader = getShaderWithSource(source, GL_VERTEX_SHADER); } void Model::compileFragmentShader(const char *source) { fragmentShader = getShaderWithSource(source, GL_FRAGMENT_SHADER); } void Model::compileLinkProgram() { int result = 0; char message[512]; program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &result); if (!result) { glGetProgramInfoLog(program, 512, NULL, message); DEBUG("MODEL::COMPILELINKPROGRAM", message, DEBUG_L::ERROR); } //@TODO link error } void Model::createVBO(float *vertices, unsigned int size) { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *) 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); }
3,532
1,286
#if !defined(BOOST_PP_IS_ITERATING) ///// header body // NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION! // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include "Utilogeny/lib/boost/mpl/numeric_cast.hpp" # include "Utilogeny/lib/boost/mpl/apply_wrap.hpp" # include "Utilogeny/lib/boost/mpl/if.hpp" # include "Utilogeny/lib/boost/mpl/tag.hpp" # include "Utilogeny/lib/boost/mpl/aux_/numeric_cast_utils.hpp" # include "Utilogeny/lib/boost/mpl/aux_/na.hpp" # include "Utilogeny/lib/boost/mpl/aux_/na_spec.hpp" # include "Utilogeny/lib/boost/mpl/aux_/lambda_support.hpp" # include "Utilogeny/lib/boost/mpl/aux_/msvc_eti_base.hpp" # include "Utilogeny/lib/boost/mpl/aux_/value_wknd.hpp" # include "Utilogeny/lib/boost/mpl/aux_/config/eti.hpp" # include "Utilogeny/lib/boost/mpl/aux_/nttp_decl.hpp" #endif #include "Utilogeny/lib/boost/mpl/aux_/config/static_constant.hpp" #if defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ || defined(BOOST_MPL_PREPROCESSING_MODE) # include "Utilogeny/lib/boost/mpl/limits/arity.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/partial_spec_params.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/def_params_tail.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/repeat.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/ext_params.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/params.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/enum.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/add.hpp" # include "Utilogeny/lib/boost/mpl/aux_/preprocessor/sub.hpp" # include "Utilogeny/lib/boost/mpl/aux_/config/ctps.hpp" # include "Utilogeny/lib/boost/mpl/aux_/config/eti.hpp" # include "Utilogeny/lib/boost/mpl/aux_/config/msvc.hpp" # include "Utilogeny/lib/boost/mpl/aux_/config/workaround.hpp" # include "Utilogeny/lib/boost/preprocessor/dec.hpp" # include "Utilogeny/lib/boost/preprocessor/inc.hpp" # include "Utilogeny/lib/boost/preprocessor/iterate.hpp" # include "Utilogeny/lib/boost/preprocessor/cat.hpp" #if !defined(AUX778076_OP_ARITY) # define AUX778076_OP_ARITY BOOST_MPL_LIMIT_METAFUNCTION_ARITY #endif #if !defined(AUX778076_OP_IMPL_NAME) # define AUX778076_OP_IMPL_NAME BOOST_PP_CAT(AUX778076_OP_PREFIX,_impl) #endif #if !defined(AUX778076_OP_TAG_NAME) # define AUX778076_OP_TAG_NAME BOOST_PP_CAT(AUX778076_OP_PREFIX,_tag) #endif namespace boost { namespace mpl { template< typename Tag1 , typename Tag2 #if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) , BOOST_MPL_AUX_NTTP_DECL(int, tag1_) = BOOST_MPL_AUX_MSVC_VALUE_WKND(Tag1)::value , BOOST_MPL_AUX_NTTP_DECL(int, tag2_) = BOOST_MPL_AUX_MSVC_VALUE_WKND(Tag2)::value > struct AUX778076_OP_IMPL_NAME : if_c< ( tag1_ > tag2_ ) #else > struct AUX778076_OP_IMPL_NAME : if_c< ( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1) > BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2) ) #endif , aux::cast2nd_impl< AUX778076_OP_IMPL_NAME<Tag1,Tag1>,Tag1,Tag2 > , aux::cast1st_impl< AUX778076_OP_IMPL_NAME<Tag2,Tag2>,Tag1,Tag2 > >::type { }; /// for Digital Mars C++/compilers with no CTPS/TTP support template<> struct AUX778076_OP_IMPL_NAME<na,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template< typename Tag > struct AUX778076_OP_IMPL_NAME<na,Tag> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template< typename Tag > struct AUX778076_OP_IMPL_NAME<Tag,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; #else template<> struct AUX778076_OP_IMPL_NAME<na,integral_c_tag> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; template<> struct AUX778076_OP_IMPL_NAME<integral_c_tag,na> { template< typename U1, typename U2 > struct apply { typedef apply type; BOOST_STATIC_CONSTANT(int, value = 0); }; }; #endif #if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ && BOOST_WORKAROUND(BOOST_MSVC, >= 1300) template< typename T > struct AUX778076_OP_TAG_NAME : tag<T,na> { }; #else template< typename T > struct AUX778076_OP_TAG_NAME { typedef typename T::tag type; }; #endif #if AUX778076_OP_ARITY != 2 # if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) # define AUX778076_OP_RIGHT_OPERAND(unused, i, N) , BOOST_PP_CAT(N, BOOST_MPL_PP_ADD(i, 2))> # define AUX778076_OP_N_CALLS(i, N) \ BOOST_MPL_PP_REPEAT( BOOST_PP_DEC(i), BOOST_MPL_PP_REPEAT_IDENTITY_FUNC, AUX778076_OP_NAME< ) \ N1 BOOST_MPL_PP_REPEAT( BOOST_MPL_PP_SUB(i, 1), AUX778076_OP_RIGHT_OPERAND, N ) \ /**/ template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) BOOST_MPL_PP_DEF_PARAMS_TAIL(2, typename N, na) > struct AUX778076_OP_NAME : AUX778076_OP_N_CALLS(AUX778076_OP_ARITY, N) { BOOST_MPL_AUX_LAMBDA_SUPPORT( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARAMS(AUX778076_OP_ARITY, N) ) ) }; #define BOOST_PP_ITERATION_PARAMS_1 \ (3,( BOOST_PP_DEC(AUX778076_OP_ARITY), 2, "Utilogeny/lib/boost/mpl/aux_/numeric_op.hpp" )) #include BOOST_PP_ITERATE() # undef AUX778076_OP_N_CALLS # undef AUX778076_OP_RIGHT_OPERAND # else // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION /// forward declaration template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct BOOST_PP_CAT(AUX778076_OP_NAME,2); template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) BOOST_MPL_PP_DEF_PARAMS_TAIL(2, typename N, na) > struct AUX778076_OP_NAME #if BOOST_WORKAROUND(BOOST_MSVC, == 1300) : aux::msvc_eti_base< typename if_< #else : if_< #endif is_na<N3> , BOOST_PP_CAT(AUX778076_OP_NAME,2)<N1,N2> , AUX778076_OP_NAME< BOOST_PP_CAT(AUX778076_OP_NAME,2)<N1,N2> , BOOST_MPL_PP_EXT_PARAMS(3, BOOST_PP_INC(AUX778076_OP_ARITY), N) > >::type #if BOOST_WORKAROUND(BOOST_MSVC, == 1300) > #endif { BOOST_MPL_AUX_LAMBDA_SUPPORT( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARAMS(AUX778076_OP_ARITY, N) ) ) }; template< typename N1 , typename N2 > struct BOOST_PP_CAT(AUX778076_OP_NAME,2) #endif #else // AUX778076_OP_ARITY == 2 template< typename BOOST_MPL_AUX_NA_PARAM(N1) , typename BOOST_MPL_AUX_NA_PARAM(N2) > struct AUX778076_OP_NAME #endif #if !defined(BOOST_MPL_CFG_MSVC_ETI_BUG) : AUX778076_OP_IMPL_NAME< typename AUX778076_OP_TAG_NAME<N1>::type , typename AUX778076_OP_TAG_NAME<N2>::type >::template apply<N1,N2>::type #else : aux::msvc_eti_base< typename apply_wrap2< AUX778076_OP_IMPL_NAME< typename AUX778076_OP_TAG_NAME<N1>::type , typename AUX778076_OP_TAG_NAME<N2>::type > , N1 , N2 >::type >::type #endif { #if AUX778076_OP_ARITY != 2 # if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(2, N, na) ) ) # else BOOST_MPL_AUX_LAMBDA_SUPPORT(2, BOOST_PP_CAT(AUX778076_OP_NAME,2), (N1, N2)) # endif #else BOOST_MPL_AUX_LAMBDA_SUPPORT(2, AUX778076_OP_NAME, (N1, N2)) #endif }; BOOST_MPL_AUX_NA_SPEC2(2, AUX778076_OP_ARITY, AUX778076_OP_NAME) }} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS ///// iteration, depth == 1 // For gcc 4.4 compatability, we must include the // BOOST_PP_ITERATION_DEPTH test inside an #else clause. #else // BOOST_PP_IS_ITERATING #if BOOST_PP_ITERATION_DEPTH() == 1 # define i_ BOOST_PP_FRAME_ITERATION(1) template< BOOST_MPL_PP_PARAMS(i_, typename N) > struct AUX778076_OP_NAME<BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(i_, N, na)> #if i_ != 2 : AUX778076_OP_N_CALLS(i_, N) { BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC( AUX778076_OP_ARITY , AUX778076_OP_NAME , ( BOOST_MPL_PP_PARTIAL_SPEC_PARAMS(i_, N, na) ) ) }; #endif # undef i_ #endif // BOOST_PP_ITERATION_DEPTH() #endif // BOOST_PP_IS_ITERATING
8,923
4,297
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2020 Intel Corporation. All Rights Reserved. //#cmake:add-file ../../../../common/utilities/number/stabilized-value.h #include "../../../test.h" #include <../common/utilities/number/stabilized-value.h> using namespace utilities::number; // Test group description: // * This tests group verifies stabilized_value class. // // Current test description: // * Verify if history is filled with a stable value at the required percentage , the user // will get it when asked for even if other inputs exist in history TEST_CASE( "get 60% stability", "[stabilized value]" ) { stabilized_value< float > stab_value( 10 ); CHECK_NOTHROW( stab_value.add( 55.0f ) ); CHECK_NOTHROW( stab_value.add( 55.0f ) ); CHECK_NOTHROW( stab_value.add( 55.0f ) ); CHECK_NOTHROW( stab_value.add( 55.0f ) ); CHECK_NOTHROW( stab_value.add( 55.0f ) ); CHECK_NOTHROW( stab_value.add( 55.0f ) ); CHECK_NOTHROW( stab_value.add( 60.0f ) ); CHECK_NOTHROW( stab_value.add( 60.0f ) ); CHECK_NOTHROW( stab_value.add( 60.0f ) ); CHECK_NOTHROW( stab_value.add( 60.0f ) ); CHECK( 55.0f == stab_value.get( 0.6f ) ); }
1,225
474
#include "source_wrap.h" #include <napi.h> #include <uv.h> #include "log_message.h" Napi::FunctionReference Source::constructor; Napi::Object Source::Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); constexpr auto name = "_Source"; Napi::Function func = DefineClass(env, name, { InstanceMethod("prepare", &Source::Prepare), InstanceMethod("start", &Source::Start), InstanceMethod("stop", &Source::Stop), InstanceMethod("pause", &Source::Pause), InstanceMethod("seek", &Source::Seek), InstanceMethod("requestPidChannel", &Source::RequestPidChannel), InstanceMethod("findStream", &Source::FindStream), InstanceAccessor("datasource", &Source::dataSource, &Source::SetDataSource), InstanceAccessor("audioPid", &Source::audioPid, nullptr), InstanceAccessor("hasAudio", &Source::hasAudio, nullptr), InstanceAccessor("videoPid", &Source::videoPid, nullptr), InstanceAccessor("hasVideo", &Source::hasVideo, nullptr), InstanceAccessor("trace", &Source::log_enabled, &Source::EnableLog), InstanceAccessor("duration", &Source::duration, nullptr), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); exports.Set(name, func); return exports; } Source::Source(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Source>(info) { if(log_enabled_) LOG(INFO) << __func__; Napi::Env env = info.Env(); Napi::HandleScope scope(env); source_.reset(new gurum::Source); } void Source::SetDataSource(const Napi::CallbackInfo& info, const Napi::Value &value) { Napi::Env env = info.Env(); if (info.Length() <= 0 || !value.IsString()) { Napi::TypeError::New(env, "String expected").ThrowAsJavaScriptException(); return; } source_->SetDataSource(value.ToString().Utf8Value()); } Napi::Value Source::dataSource(const Napi::CallbackInfo& info) { return Napi::String::New(info.Env(), source_->dataSource()); } Napi::Value Source::audioPid(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), source_->audioPid()); } Napi::Value Source::hasAudio(const Napi::CallbackInfo& info) { return Napi::Boolean::New(info.Env(), source_->HasAudio()); } Napi::Value Source::videoPid(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), source_->videoPid()); } Napi::Value Source::hasVideo(const Napi::CallbackInfo& info) { return Napi::Boolean::New(info.Env(), source_->HasVideo()); } Napi::Value Source::Prepare(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); auto root = Napi::Object::New(env); auto format = Napi::Object::New(env); const AVFormatContext *fmt = source_->Prepare(); format["native"] = Napi::External<AVFormatContext>::New(env, (AVFormatContext *)fmt); format["duration"] = fmt->duration; AVDictionary* meta_data = fmt->metadata; AVDictionaryEntry* entry = NULL; while ((entry = av_dict_get((const AVDictionary*)meta_data, "", entry, AV_DICT_IGNORE_SUFFIX))) { format[entry->key] = entry->value; } root["format"] = format; auto streams = Napi::Array::New(env, fmt->nb_streams); for (int i = 0; i < (int)fmt->nb_streams; i++) { auto stream = Napi::Object::New(env); AVStream *strm = fmt->streams[i]; stream["native"] = Napi::External<AVStream>::New(env, strm); AVCodecParameters *codec_param = strm->codecpar; stream["duration"] = Napi::Number::New(env, strm->duration); AVCodecID codec_id = codec_param->codec_id; stream["codec"] = Napi::String::New(env, avcodec_get_name(codec_id)); stream["bitrate"] = Napi::Number::New(env, codec_param->bit_rate); stream["channels"] = Napi::Number::New(env, codec_param->channels); stream["samplerate"] = Napi::Number::New(env, codec_param->sample_rate); AVDictionary* meta_data = strm->metadata; while ((entry = av_dict_get((const AVDictionary*)meta_data, "", entry, AV_DICT_IGNORE_SUFFIX))) { stream[entry->key] = Napi::String::New(env, entry->value); } streams[i] = stream; } root["streams"] = streams; return root; } void Source::Start(const Napi::CallbackInfo& info) { assert(source_); source_->Start(); } void Source::Stop(const Napi::CallbackInfo& info) { assert(source_); source_->Stop(); } void Source::Pause(const Napi::CallbackInfo& info) { assert(source_); source_->Pause(); } void Source::Seek(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() <= 0 || !info[0].IsObject()) { Napi::TypeError::New(env, "Object expected").ThrowAsJavaScriptException(); return; } Napi::Object obj = info[0].ToObject(); do { if(!obj.HasOwnProperty("pos")) { Napi::TypeError::New(env, "no pos").ThrowAsJavaScriptException(); return; } if(!static_cast<Napi::Value>(obj["pos"]).IsNumber()) { Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException(); return; } } while(0); int64_t pos = (int64_t) static_cast<Napi::Value>(obj["pos"]).ToNumber(); do { if(!obj.HasOwnProperty("backward")) { Napi::TypeError::New(env, "no backward").ThrowAsJavaScriptException(); return; } if(!static_cast<Napi::Value>(obj["backward"]).IsBoolean()) { Napi::TypeError::New(env, "Boolean expected").ThrowAsJavaScriptException(); return; } } while(0); bool backward = static_cast<Napi::Value>(obj["backward"]).ToBoolean(); do { if(!obj.HasOwnProperty("callback")) { Napi::TypeError::New(env, "no callback").ThrowAsJavaScriptException(); return; } if(!static_cast<Napi::Value>(obj["callback"]).IsFunction()) { Napi::TypeError::New(env, "Function expected").ThrowAsJavaScriptException(); return; } } while(0); int flag = backward ? AVSEEK_FLAG_BACKWARD : 0; assert(source_); source_->Seek(pos, flag, [&]{ auto callback = static_cast<Napi::Value>(obj["callback"]).As<Napi::Function>(); callback.Call(env.Global(), {}); }); } Napi::Value Source::RequestPidChannel(const Napi::CallbackInfo& info){ Napi::Env env = info.Env(); if (info.Length() <= 0) { Napi::TypeError::New(env, "Object expected").ThrowAsJavaScriptException(); return env.Undefined(); } Napi::Value value; if (info[0].IsObject()) { Napi::Object obj = info[0].ToObject(); if(!obj.HasOwnProperty("pid")) { Napi::TypeError::New(env, "no pid").ThrowAsJavaScriptException(); return env.Undefined(); } value = obj["pid"]; if(! value.IsNumber()) { Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException(); return env.Undefined(); } } else if(info[0].IsNumber()) { value = info[0].ToNumber(); } else { Napi::TypeError::New(env, "Object | Number expected").ThrowAsJavaScriptException(); return env.Undefined(); } Napi::Number number = value.As<Napi::Number>(); int pid = (int) number; auto pidchannel = source_->RequestPidChannel(pid); assert(pidchannel); return Napi::External<gurum::PidChannel>::New(env, pidchannel); } Napi::Value Source::FindStream(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); if (info.Length() <= 0 || !info[0].IsNumber()) { Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException(); return env.Undefined(); } int pid = (int) info[0].ToNumber(); auto stream = source_->FindStream(pid); assert(stream); return Napi::External<AVStream>::New(env, stream); } void Source::EnableLog(const Napi::CallbackInfo& info, const Napi::Value &value) { Napi::Env env = info.Env(); if (info.Length() <= 0 || !value.IsBoolean()) { Napi::TypeError::New(env, "Boolean expected").ThrowAsJavaScriptException(); return; } log_enabled_ = value.ToBoolean(); if(source_) source_->EnableLog(log_enabled_); } Napi::Value Source::log_enabled(const Napi::CallbackInfo& info) { return Napi::Boolean::New(info.Env(), log_enabled_); } Napi::Value Source::duration(const Napi::CallbackInfo& info) { return Napi::Number::New(info.Env(), source_->GetDuration()); }
8,327
2,765
// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s struct Agg { const char * x; const char * y; constexpr Agg() : x(0), y(0) {} }; struct Struct { constexpr static const char *name = "foo"; constexpr static __complex float complexValue = 42.0; static constexpr const Agg &agg = Agg(); Struct(); Struct(int x); }; void use(int n, const char *c); Struct *getPtr(); // CHECK: @[[STR:.*]] = private unnamed_addr constant [4 x i8] c"foo\00", align 1 void scalarStaticVariableInMemberExpr(Struct *ptr, Struct &ref) { use(1, Struct::name); // CHECK: call void @_Z3useiPKc(i32 noundef 1, i8* noundef getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0)) Struct s; use(2, s.name); // CHECK: call void @_Z3useiPKc(i32 noundef 2, i8* noundef getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0)) use(3, ptr->name); // CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8 // CHECK: call void @_Z3useiPKc(i32 noundef 3, i8* noundef getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0)) use(4, ref.name); // CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8 // CHECK: call void @_Z3useiPKc(i32 noundef 4, i8* noundef getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0)) use(5, Struct(2).name); // CHECK: call void @_ZN6StructC1Ei(%struct.Struct* {{[^,]*}} %{{.*}}, i32 noundef 2) // CHECK: call void @_Z3useiPKc(i32 noundef 5, i8* noundef getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0)) use(6, getPtr()->name); // CHECK: call noundef %struct.Struct* @_Z6getPtrv() // CHECK: call void @_Z3useiPKc(i32 noundef 6, i8* noundef getelementptr inbounds ([4 x i8], [4 x i8]* @[[STR]], i32 0, i32 0)) } void use(int n, __complex float v); void complexStaticVariableInMemberExpr(Struct *ptr, Struct &ref) { use(1, Struct::complexValue); // CHECK: store float 4.200000e+01, float* %[[coerce0:.*]].{{.*}}, align 4 // CHECK: store float 0.000000e+00, float* %[[coerce0]].{{.*}}, align 4 // CHECK: %[[cast0:.*]] = bitcast { float, float }* %[[coerce0]] to <2 x float>* // CHECK: %[[vector0:.*]] = load <2 x float>, <2 x float>* %[[cast0]], align 4 // CHECK: call void @_Z3useiCf(i32 noundef 1, <2 x float> noundef %[[vector0]]) Struct s; use(2, s.complexValue); // CHECK: store float 4.200000e+01, float* %[[coerce1:.*]].{{.*}}, align 4 // CHECK: store float 0.000000e+00, float* %[[coerce1]].{{.*}}, align 4 // CHECK: %[[cast1:.*]] = bitcast { float, float }* %[[coerce1]] to <2 x float>* // CHECK: %[[vector1:.*]] = load <2 x float>, <2 x float>* %[[cast1]], align 4 // CHECK: call void @_Z3useiCf(i32 noundef 2, <2 x float> noundef %[[vector1]]) use(3, ptr->complexValue); // CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8 // CHECK: store float 4.200000e+01, float* %[[coerce2:.*]].{{.*}}, align 4 // CHECK: store float 0.000000e+00, float* %[[coerce2]].{{.*}}, align 4 // CHECK: %[[cast2:.*]] = bitcast { float, float }* %[[coerce2]] to <2 x float>* // CHECK: %[[vector2:.*]] = load <2 x float>, <2 x float>* %[[cast2]], align 4 // CHECK: call void @_Z3useiCf(i32 noundef 3, <2 x float> noundef %[[vector2]]) use(4, ref.complexValue); // CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8 // CHECK: store float 4.200000e+01, float* %[[coerce3:.*]].{{.*}}, align 4 // CHECK: store float 0.000000e+00, float* %[[coerce3]].{{.*}}, align 4 // CHECK: %[[cast3:.*]] = bitcast { float, float }* %[[coerce3]] to <2 x float>* // CHECK: %[[vector3:.*]] = load <2 x float>, <2 x float>* %[[cast3]], align 4 // CHECK: call void @_Z3useiCf(i32 noundef 4, <2 x float> noundef %[[vector3]]) use(5, Struct(2).complexValue); // CHECK: call void @_ZN6StructC1Ei(%struct.Struct* {{[^,]*}} %{{.*}}, i32 noundef 2) // CHECK: store float 4.200000e+01, float* %[[coerce4:.*]].{{.*}}, align 4 // CHECK: store float 0.000000e+00, float* %[[coerce4]].{{.*}}, align 4 // CHECK: %[[cast4:.*]] = bitcast { float, float }* %[[coerce4]] to <2 x float>* // CHECK: %[[vector4:.*]] = load <2 x float>, <2 x float>* %[[cast4]], align 4 // CHECK: call void @_Z3useiCf(i32 noundef 5, <2 x float> noundef %[[vector4]]) use(6, getPtr()->complexValue); // CHECK: call noundef %struct.Struct* @_Z6getPtrv() // CHECK: store float 4.200000e+01, float* %[[coerce5:.*]].{{.*}}, align 4 // CHECK: store float 0.000000e+00, float* %[[coerce5]].{{.*}}, align 4 // CHECK: %[[cast5:.*]] = bitcast { float, float }* %[[coerce5]] to <2 x float>* // CHECK: %[[vector5:.*]] = load <2 x float>, <2 x float>* %[[cast5]], align 4 // CHECK: call void @_Z3useiCf(i32 noundef 6, <2 x float> noundef %[[vector5]]) } void aggregateRefInMemberExpr(Struct *ptr, Struct &ref) { use(1, Struct::agg.x); // CHECK: %[[value0:.*]] = load i8*, i8** getelementptr inbounds (%struct.Agg, %struct.Agg* @_ZGRN6Struct3aggE_, i32 0, i32 0), align 8 // CHECK: call void @_Z3useiPKc(i32 noundef 1, i8* noundef %[[value0]]) Struct s; use(2, s.agg.x); // CHECK: %[[value1:.*]] = load i8*, i8** getelementptr inbounds (%struct.Agg, %struct.Agg* @_ZGRN6Struct3aggE_, i32 0, i32 0), align 8 // CHECK: call void @_Z3useiPKc(i32 noundef 2, i8* noundef %[[value1]]) use(3, ptr->agg.x); // CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8 // CHECK: %[[value2:.*]] = load i8*, i8** getelementptr inbounds (%struct.Agg, %struct.Agg* @_ZGRN6Struct3aggE_, i32 0, i32 0), align 8 // CHECK: call void @_Z3useiPKc(i32 noundef 3, i8* noundef %[[value2]]) use(4, ref.agg.x); // CHECK: load %struct.Struct*, %struct.Struct** %{{.*}}, align 8 // CHECK: %[[value3:.*]] = load i8*, i8** getelementptr inbounds (%struct.Agg, %struct.Agg* @_ZGRN6Struct3aggE_, i32 0, i32 0), align 8 // CHECK: call void @_Z3useiPKc(i32 noundef 4, i8* noundef %[[value3]]) }
5,805
2,562
#include "pch.h" #include <string.h> #include "nacl_includes\crypto_sign.h" #include "additions\crypto_hash_sha512.h" #include "ge.h" #include "sc.h" int crypto_sign( unsigned char *sm, unsigned long long *smlen, const unsigned char *m, unsigned long long mlen, const unsigned char *sk ) { unsigned char pk[32]; unsigned char az[64]; unsigned char nonce[64]; unsigned char hram[64]; ge_p3 R; memmove(pk, sk + 32, 32); crypto_hash_sha512(az, sk, 32); az[0] &= 248; az[31] &= 63; az[31] |= 64; *smlen = mlen + 64; memmove(sm + 64, m, mlen); memmove(sm + 32, az + 32, 32); crypto_hash_sha512(nonce, sm + 32, mlen + 32); memmove(sm + 32, pk, 32); sc_reduce(nonce); ge_scalarmult_base(&R, nonce); ge_p3_tobytes(sm, &R); crypto_hash_sha512(hram, sm, mlen + 64); sc_reduce(hram); sc_muladd(sm + 32, hram, az, nonce); return 0; }
854
443
// Preprocessor Directives #ifndef GLITTER #define GLITTER #pragma once // System Headers #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <btBulletDynamicsCommon.h> #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // Reference: https://github.com/nothings/stb/blob/master/stb_image.h#L4 // To use stb_image, add this in *one* C++ source file. // #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> // Define Some Constants const int mWidth = 1280; const int mHeight = 800; #endif //~ Glitter Header
630
253
#include <algorithm> #include <regex> #include "AutoSchedule.h" #include "AutoScheduleUtils.h" #include "ExprUsesVar.h" #include "FindCalls.h" #include "Func.h" #include "IREquality.h" #include "Inline.h" #include "ParallelRVar.h" #include "RealizationOrder.h" #include "RegionCosts.h" #include "Scope.h" #include "Simplify.h" #include "Util.h" namespace Halide { namespace Internal { using std::deque; using std::make_pair; using std::map; using std::pair; using std::set; using std::string; using std::vector; namespace { // Substitute parameter estimates into the exprs describing the box bounds. void substitute_estimates_box(Box &box) { box.used = subsitute_var_estimates(box.used); for (auto &b : box.bounds) { b.min = subsitute_var_estimates(b.min); b.max = subsitute_var_estimates(b.max); } } // Substitute parameter estimates into the boxes in 'region'. void substitute_estimates_region(map<string, Box> &region) { for (auto &iter : region) { substitute_estimates_box(iter.second); } } // Return true if any of the box dimension is unbounded. bool is_box_unbounded(const Box &b) { for (size_t i = 0; i < b.size(); i++) { if (!b[i].is_bounded()) { return true; } } return false; } // Helper function to simplify the upper and lower bounds of each dimension of a box. void simplify_box(Box &b) { for (size_t i = 0; i < b.size(); i++) { b[i].min = simplify(b[i].min); b[i].max = simplify(b[i].max); } } // Helper function to merge the partial region map into the result region map. void merge_regions(map<string, Box> &result, const map<string, Box> &partial) { // Merge regions from 'partial' with an existing region in 'result'. for (const auto &reg : partial) { auto iter = result.find(reg.first); if (iter == result.end()) { result.emplace(reg.first, reg.second); } else { merge_boxes(iter->second, reg.second); } } } // Replace all occurrences of non-alphanumeric chars in 'name' with '_'. string get_sanitized_name(string name) { if (isdigit(name[0])) { name = "_" + name; } for (size_t i = 0; i < name.size(); ++i) { if (!isalnum(name[i])) { name[i] = '_'; } } return name; } // Representation of a function stage in the pipeline. struct FStage { Function func; uint32_t stage_num; FStage(Function func, uint32_t stage_num) : func(func), stage_num(stage_num) {} bool operator==(const FStage &other_stage) const { return (func.name() == other_stage.func.name()) && (stage_num == other_stage.stage_num); } bool operator<(const FStage &other_stage) const { return func.name() < other_stage.func.name() || ((func.name() == other_stage.func.name()) && (stage_num < other_stage.stage_num)); } friend std::ostream& operator<<(std::ostream &stream, const FStage &s) { if (s.stage_num == 0) { stream << s.func.name(); } else { stream << s.func.name() << ".update(" << (s.stage_num - 1) << ")"; } return stream; } }; struct DependenceAnalysis { // Map containing all the functions in the pipeline. map<string, Function> env; vector<string> order; FuncValueBounds func_val_bounds; struct RegionsRequiredQuery { string f; int stage; set<string> prods; bool only_regions_computed; RegionsRequiredQuery(const string &f, int stage, const set<string> &prods, bool only_regions_computed) : f(f), stage(stage), prods(prods), only_regions_computed(only_regions_computed) {} bool operator==(const RegionsRequiredQuery &other) const { return (f == other.f) && (stage == other.stage) && (prods == other.prods) && (only_regions_computed == other.only_regions_computed); } bool operator<(const RegionsRequiredQuery &other) const { if (f < other.f) { return true; } else if (f > other.f) { return false; } if (stage < other.stage) { return true; } else if (stage > other.stage) { return false; } if (only_regions_computed < other.only_regions_computed) { return true; } else if (only_regions_computed > other.only_regions_computed) { return false; } return prods < other.prods; } }; struct RegionsRequired { DimBounds bounds; // Regions required to compute 'bounds' given a particular // RegionsRequiredQuery. map<string, Box> regions; RegionsRequired(const DimBounds &b, const map<string, Box> &r) : bounds(b), regions(r) {} }; // Cache for bounds queries (bound queries with the same parameters are // common during the grouping process). map<RegionsRequiredQuery, vector<RegionsRequired>> regions_required_cache; DependenceAnalysis(const map<string, Function> &env, const vector<string> &order, const FuncValueBounds &func_val_bounds) : env(env), order(order), func_val_bounds(func_val_bounds) {} // Return the regions of the producers ('prods') required to compute the region // of the function stage ('f', 'stage_num') specified by 'bounds'. When // 'only_regions_computed' is set to true, this only returns the computed // regions and not the total allocated regions. map<string, Box> regions_required(Function f, int stage_num, const DimBounds &bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates); // Return the regions of the producers ('prods') required to compute the region // of the function specified by 'pure_bounds'. When 'only_regions_computed' // is set to true, this only returns the computed regions and not the total // allocated regions. map<string, Box> regions_required(Function f, const DimBounds &pure_bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates); // Return redundantly computed regions of producers ('prods') while computing // a region of the function stage ('f', 'stage_num') specified by 'bounds'. // 'var' is the dimension along which redundant computation is accounted for. // When 'only_regions_computed' is set to true, this only returns the computed // regions and not the total allocated regions. When 'only_regions_computed' // is set to true, this only returns the computed regions and not the total // allocated regions. map<string, Box> redundant_regions(Function f, int stage_num, string var, const DimBounds &bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates); // Return overlapping regions of producers ('prods') while computing a function // stage along each of the dimensions. vector<map<string, Box>> overlap_regions(Function f, int stage_num, const DimBounds &bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates); }; // Return the regions of the producers ('prods') required to compute the region // of the function specified by 'pure_bounds'. map<string, Box> DependenceAnalysis::regions_required(Function f, const DimBounds &pure_bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates) { // Find the regions required for each stage and merge them. map<string, Box> regions; int num_stages = f.updates().size() + 1; for (int s = 0; s < num_stages; s++) { DimBounds bounds = get_stage_bounds(f, s, pure_bounds); map<string, Box> stage_regions = regions_required(f, s, bounds, prods, only_regions_computed, input_estimates); merge_regions(regions, stage_regions); } return regions; } struct StageBounds { FStage f_stage; DimBounds bounds; StageBounds(const FStage &fs, const DimBounds &b) : f_stage(fs), bounds(b) {} StageBounds(Function func, uint32_t stage_num, const DimBounds &b) : f_stage(FStage(func, stage_num)), bounds(b) {} bool operator==(const StageBounds &other) const { return (f_stage == other.f_stage) && (bounds == other.bounds); } bool operator<(const StageBounds &other) const { return (f_stage < other.f_stage) || ((f_stage == other.f_stage) && (bounds.size() < other.bounds.size())); } friend std::ostream& operator<<(std::ostream &stream, const StageBounds &s) { stream << "Stage: " << s.f_stage << "\n"; stream << "Bounds:\n"; for (const auto &iter : s.bounds) { stream << "\t" << iter.first << " -> [" << iter.second.min << ", " << iter.second.max << "]\n"; } stream << "\n"; return stream; } }; // Helper function to queue regions that need to be traversed. 'fs_bounds' is // the queue into which the regions specified by 'prod_func' and 'region' // will be added. void queue_func_regions(map<FStage, DimBounds> &fs_bounds, const Function &prod_func, const Box &region, const set<StageBounds>& visited) { DimBounds prod_pure_bounds; const vector<string> &args = prod_func.args(); internal_assert(region.size() == args.size()); // The region only specifies the extent of each dimension // by position. Populating a map which is keyed by name. for (size_t v = 0; v < args.size(); v++) { prod_pure_bounds[args[v]] = region[v]; } // Get the bounds of all stages in a function from the // bounds on the pure dimensions. vector<DimBounds> prod_bounds = get_stage_bounds(prod_func, prod_pure_bounds); size_t num_stages = prod_func.updates().size() + 1; internal_assert(prod_bounds.size() == num_stages); // Add all stages of a function into the queue. for (size_t prod_s = 0; prod_s < num_stages; prod_s++) { StageBounds sb(prod_func, prod_s, prod_bounds[prod_s]); if (visited.find(sb) == visited.end()) { auto iter = fs_bounds.find(sb.f_stage); if (iter == fs_bounds.end()) { fs_bounds.emplace(sb.f_stage, sb.bounds); } else { for (const auto &b : sb.bounds) { DimBounds &curr_bounds = iter->second; auto b_iter = curr_bounds.find(b.first); if (b_iter == curr_bounds.end()) { curr_bounds.emplace(b.first, b.second); } else { if (b_iter->second.has_lower_bound() && b.second.has_lower_bound()) { b_iter->second.min = simplify(Interval::make_min(b_iter->second.min, b.second.min)); } else { b_iter->second.min = Interval::neg_inf; } if (b_iter->second.has_upper_bound() && b.second.has_upper_bound()) { b_iter->second.max = simplify(Interval::make_max(b_iter->second.max, b.second.max)); } else { b_iter->second.max = Interval::pos_inf; } } } } } } } // Helper function for merging 'curr_regions' to the global map of regions // and adding them to the queue of regions that need to be traversed. // 'prods' is the set of producer functions that are under consideration. void merge_and_queue_regions(map<FStage, DimBounds> &fs_bounds, map<string, Box> &regions, map<string, Box> &curr_regions, const set<string> &prods, const map<string, Function> &env, bool only_regions_computed, string curr_func_name, const set<StageBounds>& visited) { for (const auto &reg : curr_regions) { // Merge region with an existing region of a function in the // global map. Do not merge the parent function itself to the region // when querying only for the values computed. if (!only_regions_computed || (only_regions_computed && (reg.first != curr_func_name))) { auto iter = regions.find(reg.first); if (iter == regions.end()) { regions.emplace(reg.first, reg.second); } else { merge_boxes(iter->second, reg.second); } } // Skip adding the current region into to the queue if the function // is not in 'prods'. if (prods.find(reg.first) == prods.end()) { continue; } const auto &it = env.find(reg.first); if ((it != env.end()) && (reg.first != curr_func_name)) { // Add all stages of the function representing the // region into the queue. queue_func_regions(fs_bounds, it->second, reg.second, visited); } } } // Return the regions of the producers ('prods') required to compute the region // of the function stage ('f', 'stage_num') specified by 'bounds'. map<string, Box> DependenceAnalysis::regions_required(Function f, int stage_num, const DimBounds &bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates) { // Iteratively compute the required regions by traversing the chain // of dependencies. // Check the cache if we've already computed this previously. RegionsRequiredQuery query(f.name(), stage_num, prods, only_regions_computed); const auto &iter = regions_required_cache.find(query); if (iter != regions_required_cache.end()) { const auto &it = std::find_if(iter->second.begin(), iter->second.end(), [&bounds](const RegionsRequired &r) { return (r.bounds == bounds); }); if (it != iter->second.end()) { internal_assert((iter->first == query) && (it->bounds == bounds)); return it->regions; } } // Map of all the required regions. map<string, Box> regions; map<FStage, DimBounds> fs_bounds; set<StageBounds> visited; // Add the query function and its region to the queue. fs_bounds.emplace(FStage(f, stage_num), bounds); while (!fs_bounds.empty()) { for (int i = order.size() - 1; i >= 0; --i) { const Function &f = env.find(order[i])->second; int num_stages = f.updates().size() + 1; for (int stage_num = 0; stage_num < num_stages; ++stage_num) { FStage s(f, stage_num); const auto &iter = fs_bounds.find(s); if (iter == fs_bounds.end()) { continue; } DimBounds curr_bounds = iter->second; visited.insert(StageBounds(s, curr_bounds)); // Scope for containing all the estimates on parameters and intervals. Scope<Interval> curr_scope; curr_scope.set_containing_scope(input_estimates); // If the function has an extern definition, there is no visibility into // the expression defining the function. So the regions required will be // the entire domain of the inputs to the extern func. Use the estimates // on the inputs to the extern function if available. // // TODO: Query the extern function for bounds of the functions which it // it depends on. This can be done by calling the extern func in the // bounds query mode. if (s.func.has_extern_definition()) { for (const ExternFuncArgument &arg : s.func.extern_arguments()) { if (arg.is_func()) { // If the argument is an entire function, the bounds of the // function required are unknown. Create an infinite region // of the correct dimension, update the region map, and // add it to the queue. string prod_name = Function(arg.func).name(); const Function &prod_func = get_element(env, prod_name); map<string, Box> prod_reg; const vector<string> &args = prod_func.args(); for (size_t v = 0; v < args.size(); v++) { prod_reg[prod_name].push_back(Interval()); } merge_and_queue_regions(fs_bounds, regions, prod_reg, prods, env, only_regions_computed, s.func.name(), visited); } else if (arg.is_expr()) { // Find the boxes required for the expression and add the regions // to the queue. Expr subs_arg = subsitute_var_estimates(arg.expr); map<string, Box> arg_regions = boxes_required(subs_arg, curr_scope, func_val_bounds); substitute_estimates_region(arg_regions); merge_and_queue_regions(fs_bounds, regions, arg_regions, prods, env, only_regions_computed, s.func.name(), visited); } else if (arg.is_image_param() || arg.is_buffer()) { // If the argument is an image or a buffer, the required // bounds are unknown. Create an infinite region of the // correct dimension and update the region map. Buffer<> buf; if (arg.is_image_param()) { buf = arg.image_param.buffer(); } else { buf = arg.buffer; } map<string, Box> buf_reg; for (int v = 0; v < buf.dimensions(); v++) { buf_reg[buf.name()].push_back(Interval()); } merge_regions(regions, buf_reg); } } } else { Definition def = get_stage_definition(s.func, s.stage_num); const vector<Dim> &dims = def.schedule().dims(); // Substitute parameter estimates into the bounds and add them to the // current scope. for (int d = 0; d < (int)dims.size() - 1; d++) { Interval simple_bounds = get_element(curr_bounds, dims[d].var); simple_bounds.min = subsitute_var_estimates(simple_bounds.min); simple_bounds.max = subsitute_var_estimates(simple_bounds.max); curr_scope.push(dims[d].var, simple_bounds); } // Find the regions required for each value of the current function stage, // update the region map, and add them to the queue. for (const auto &val : def.values()) { // Substitute the parameter estimates into the expression and get // the regions required for the expression. Expr subs_val = subsitute_var_estimates(val); map<string, Box> curr_regions = boxes_required(subs_val, curr_scope, func_val_bounds); substitute_estimates_region(curr_regions); // Arguments to the definition may require regions of functions. // For example, update definitions in histograms where the bin is // based on the value of a function. Box left_reg; for (const Expr &arg : def.args()) { Expr subs_arg = subsitute_var_estimates(arg); map<string, Box> arg_regions = boxes_required(subs_arg, curr_scope, func_val_bounds); substitute_estimates_region(arg_regions); // Merge the regions with the regions found while looking at // the values. merge_regions(curr_regions, arg_regions); Interval arg_bounds = bounds_of_expr_in_scope(arg, curr_scope, func_val_bounds); left_reg.push_back(arg_bounds); } auto iter_curr = curr_regions.find(s.func.name()); if (iter_curr == curr_regions.end()) { curr_regions.emplace(s.func.name(), left_reg); } else { merge_boxes(iter_curr->second, left_reg); } // Update the region map, and add 'curr_regions' to the queue. merge_and_queue_regions(fs_bounds, regions, curr_regions, prods, env, only_regions_computed, s.func.name(), visited); } } // Remove processed region from the queue. fs_bounds.erase(iter); } } } // Simplify the bounds on each region and substitute global pipeline // bounds for function regions which lower and upper bounds could not be // determined. map<string, Box> concrete_regions; for (auto &f_reg : regions) { simplify_box(f_reg.second); Box concrete_box; for (size_t i = 0; i < f_reg.second.size(); i++) { Expr lower = f_reg.second[i].min; Expr upper = f_reg.second[i].max; auto iter = env.find(f_reg.first); bool in_env = (iter != env.end()); if (!lower.as<IntImm>() && in_env) { const Function &curr_f = iter->second; for (const auto &b : curr_f.schedule().estimates()) { size_t num_pure_args = curr_f.args().size(); if ((i < num_pure_args) && (b.var == curr_f.args()[i])) { lower = b.min; } } } if (!upper.as<IntImm>() && in_env) { const Function &curr_f = iter->second; for (const auto &b : curr_f.schedule().estimates()) { size_t num_pure_args = curr_f.args().size(); if ((i < num_pure_args) && (b.var == curr_f.args()[i])) { const IntImm *bmin = b.min.as<IntImm>(); const IntImm *bextent = b.extent.as<IntImm>(); upper = IntImm::make(Int(32), bmin->value + bextent->value - 1); } } } Interval concrete_bounds = Interval(lower, upper); concrete_box.push_back(concrete_bounds); } concrete_regions[f_reg.first] = concrete_box; } regions_required_cache[query].push_back(RegionsRequired(bounds, concrete_regions)); return concrete_regions; } // Return redundantly computed regions of producers ('prods') while computing a // region of the function stage ('f', 'stage_num') specified by 'bounds'. 'var' // is the dimension along which redundant computation is accounted for. map<string, Box> DependenceAnalysis::redundant_regions(Function f, int stage_num, string var, const DimBounds &bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates) { // Find the regions required to compute the region of 'f' specified // by 'bounds'. map<string, Box> regions = regions_required( f, stage_num, bounds, prods, only_regions_computed, input_estimates); // Shift the bounds by the size of the interval along the direction // of var. DimBounds shifted_bounds; for (const auto &b : bounds) { if (b.first == var) { Expr len = b.second.max - b.second.min + 1; Interval bound = Interval(b.second.min + len, b.second.max + len); shifted_bounds[b.first] = bound; } else { shifted_bounds[b.first] = b.second; } } // Find the regions required to compute the region of f specified // by shifted_bounds. map<string, Box> regions_shifted = regions_required( f, stage_num, shifted_bounds, prods, only_regions_computed, input_estimates); // Compute the overlaps between 'regions_shifted' and the original // regions required. map<string, Box> overlaps; for (const auto &reg : regions) { auto iter = regions_shifted.find(reg.first); if (iter == regions.end()) { // It will be interesting to log cases where this actually happens // i.e., the shifted regions do not contain a function that was // there in the original regions. continue; } const Box &b = reg.second; const Box &b_shifted = iter->second; // The boxes should be of the same size. internal_assert(b.size() == b_shifted.size()); Box b_intersect; for (uint32_t i = 0 ; i < b.size(); i++) { b_intersect.push_back(Interval::make_intersection(b[i], b_shifted[i])); } // A function should appear once in the regions and therefore cannot // already be present in the overlaps map. internal_assert(overlaps.find(reg.first) == overlaps.end()); overlaps.emplace(reg.first, b_intersect); } // Simplify the bounds of each of the overlap regions. for (auto &f : overlaps) { simplify_box(f.second); } return overlaps; } // Return overlapping regions of producers ('prods') while computing a function // stage along each of the dimensions. vector<map<string, Box>> DependenceAnalysis::overlap_regions(Function f, int stage_num, const DimBounds &bounds, const set<string> &prods, bool only_regions_computed, const Scope<Interval> *input_estimates) { vector<map<string, Box>> conc_overlaps; const vector<Dim> &dims = get_stage_dims(f, stage_num); // Get the redundant regions along each dimension of f. for (int d = 0; d < (int)dims.size() - 1; d++) { map<string, Box> conc_reg = redundant_regions(f, stage_num, dims[d].var, bounds, prods, only_regions_computed, input_estimates); conc_overlaps.push_back(conc_reg); } return conc_overlaps; } // Return the regions of each function required for computing the // outputs of the pipeline. map<string, Box> get_pipeline_bounds(DependenceAnalysis &analysis, const vector<Function> &outputs, const Scope<Interval> *input_estimates) { map<string, Box> pipeline_bounds; // Find the regions required for each of the outputs and merge them // to compute the full pipeline_bounds. for (const auto &out : outputs) { DimBounds pure_bounds; Box out_box; // Use the estimates on the output for determining the output bounds. // If there are duplicates, use the most recent estimate. const auto &estimates = out.schedule().estimates(); for (const auto &arg : out.args()) { int i; for (i = estimates.size() - 1; i >= 0; --i) { const auto &est = estimates[i]; if ((est.var == arg) && est.min.defined() && est.extent.defined()) { Interval in = Interval(est.min, simplify(est.min + est.extent - 1)); pure_bounds.emplace(arg, in); out_box.push_back(in); break; } } internal_assert(i >= 0) << "Could not find estimate for " << arg << "\n"; } set<string> prods; for (const pair<string, Function> &fpair : analysis.env) { prods.insert(fpair.first); } map<string, Box> regions = analysis.regions_required(out, pure_bounds, prods, false, input_estimates); // Add the output region to the pipeline bounds as well. regions.emplace(out.name(), out_box); merge_regions(pipeline_bounds, regions); } return pipeline_bounds; } struct AutoSchedule { struct Stage { string function; size_t stage; Stage(const string &f, size_t s) : function(f), stage(s) {} bool operator==(const Stage &other) const { return (function == other.function) && (stage == other.stage); } bool operator<(const Stage &other) const { return (function < other.function) || ((function == other.function) && (stage < other.stage)); } }; const map<string, Function> &env; // Contain maps from function name to the topological order of the pipeline. map<string, size_t> topological_order; // Cache for storing all internal vars/rvars that have been declared during // the course of schedule generation, to ensure that we don't introduce any // duplicates in the string representation of the schedules. map<string, VarOrRVar> internal_vars; // Store the list of schedules applied to some function stages (most recent // schedule is placed last in the list). map<string, map<int, vector<string>>> func_schedules; // Store the list of vars/rvars used in the schedule applied to some // function stages. map<string, map<int, set<string>>> used_vars; AutoSchedule(const map<string, Function> &env, const vector<string> &order) : env(env) { for (size_t i = 0; i < order.size(); ++i) { topological_order.emplace(order[i], i); } // Allocate a slot in 'used_vars' for each function stages in the pipeline for (const auto &iter : env) { for (size_t i = 0; i < iter.second.updates().size() + 1; ++i) { used_vars[iter.first][i]; } } } // Given a function name, return a string representation of getting the // function handle string get_func_handle(const string &name) const { size_t index = get_element(topological_order, name); return "pipeline.get_func(" + std::to_string(index) + ")"; } friend std::ostream& operator<<(std::ostream &stream, const AutoSchedule &sched) { stream << "// Delete this line if not using Generator\n"; stream << "Pipeline pipeline = get_pipeline();\n\n"; for (const auto &iter : sched.internal_vars) { if (iter.second.is_rvar) { stream << "RVar "; } else { stream << "Var "; } stream << iter.first << "(\"" << iter.first << "\");\n"; } stream << "\n"; // Declare all the functions + schedules std::ostringstream func_ss; std::ostringstream schedule_ss; for (const auto &f : sched.func_schedules) { const string &fname = get_sanitized_name(f.first); func_ss << "Func " << fname << " = " << sched.get_func_handle(f.first) << ";\n"; schedule_ss << "{\n"; // Declare all the Vars and RVars that are actually used in the schedule const Function &func = get_element(sched.env, f.first); for (size_t i = 0; i < func.args().size(); ++i) { if (sched.used_vars.at(func.name()).at(0).find(func.args()[i]) != sched.used_vars.at(func.name()).at(0).end()) { schedule_ss << " Var " << func.args()[i] << " = " << fname << ".args()[" << i << "];\n"; } } set<string> declared_rvars; for (size_t i = 0; i < func.updates().size(); ++i) { const vector<ReductionVariable> &rvars = func.updates()[i].schedule().rvars(); const set<string> &var_list = sched.used_vars.at(func.name()).at(i+1); for (size_t j = 0; j < rvars.size(); ++j) { if ((var_list.find(rvars[j].var) == var_list.end()) || (declared_rvars.find(rvars[j].var) != declared_rvars.end())) { continue; } declared_rvars.insert(rvars[j].var); schedule_ss << " RVar " << rvars[j].var << "(" << fname << ".update(" << i << ").get_schedule().rvars()[" << j << "].var);\n"; } } for (const auto &s : f.second) { internal_assert(!s.second.empty()); schedule_ss << " " << fname; if (s.first > 0) { schedule_ss << ".update(" << std::to_string(s.first - 1) << ")"; } for (size_t i = 0; i < s.second.size(); ++i) { schedule_ss << "\n ." << s.second[i]; } schedule_ss << ";\n"; } schedule_ss << "}\n"; } stream << func_ss.str() << "\n"; stream << schedule_ss.str() << "\n"; return stream; } void push_schedule(const string &stage_name, size_t stage_num, const string &sched, const set<string> &vars) { vector<string> v = split_string(stage_name, "."); internal_assert(!v.empty()); used_vars[v[0]][stage_num].insert(vars.begin(), vars.end()); // If the previous schedule applied is the same as this one, // there is no need to re-apply the schedule auto &schedules = func_schedules[v[0]][stage_num]; if (schedules.empty()) { schedules.push_back(sched); } else { if (schedules[schedules.size()-1] != sched) { schedules.push_back(sched); } } } }; // Implement the grouping algorithm and the cost model for making the grouping // choices. struct Partitioner { // GroupingChoice encodes the grouping of the 'prod' function into the 'cons' stage. struct GroupingChoice { string prod; FStage cons; GroupingChoice(const string &prod, const FStage &cons) : prod(prod), cons(cons) {} bool operator==(const GroupingChoice &other) const { return (prod == other.prod) && (cons == other.cons); } bool operator<(const GroupingChoice &other) const { return (prod < other.prod) || ((prod == other.prod) && (cons < other.cons)); } friend std::ostream& operator<<(std::ostream &stream, const GroupingChoice &choice) { stream << "Choice: " << choice.prod << " -> " << choice.cons << '\n'; return stream; } }; // A group is a sub-pipeline with a single output. Members of a group are // either inlined into the consumer functions within the group or computed // at tiles of the output, specified by 'tile_sizes'. // // TODO: The restriction of computing either at the inline or tile level // makes the space of scheduling choices for a group very tractable. // However, the restriction might miss good schedules which can only be // realized by computing the members of the group at different levels of // the group. // // There are two approaches to extend the space of schedules considered: // 1) Recursive grouping: Treat the problem of determining the compute levels // within a group as a smaller instance of the grouping problem with // different parameters for the input, output sizes, and cache model. // // 2) Tightening: Always compute a function at the lowest level possible // without introducing redundant work. This is a restricted form of recursive // grouping which does not explore the trade-off between redundant work and // locality. // // Either approach can be implemented as a post process for each group // after the initial grouping process finishes. The cost model may // already make sub-optimal higher level partitioning when it is not aware // of the benefits of the post processing. However, it should strictly be // an improvement over the initial grouping. As a first step, it is good // to make it a post process. // // Incorporating the recursive grouping process into the cost model can be // tricky and can potentially make the cost of analyzing a group // prohibitive, as it requires solving smaller instances of the grouping // problem for analyzing each configuration. On the other hand, tightening // can be integrated into the cost model with out significantly increasing // the time to analyze a grouping configuration. // // TODO: Add sliding window optimizations. For start, it may be enough to // implement sliding window as a post-pass by moving the store level of all // the members of the group to the outermost serial loop. This could possibly // be incorporated in the cost model with some effort. Line-buffering // presents additional challenges for this post-processing strategy though. // A typical line-buffer would use terrible tile size for tiling, but its // performance will improve significantly once sliding window is turned on. // // TODO: Register tiling is an important transformation especially for // benchmarks with significant reuse of the data (like matrix multiply and // convolutional layers). The mechanism for realizing register tiling is to // completely unroll small tiles of the innermost kernels. Unrolling // interacts with vectorization, storage layout, and depends on the outer // level tiling. struct Group { // The output stage representing the group. FStage output; // Functions that belong to the group. vector<FStage> members; // Members of the group which are inlined. set<string> inlined; // Tile sizes along dimensions of the output function of the group. map<string, Expr> tile_sizes; Group(const FStage &output, const vector<FStage> &members) : output(output), members(members) {} friend std::ostream& operator<<(std::ostream &stream, const Group &g) { stream << "Output FStage: " << g.output << '\n'; stream << "Members: " << '{'; for (size_t i = 0; i < g.members.size(); ++i) { if (i > 0) { stream << ", "; } stream << g.members[i]; } stream << "}" << '\n'; stream << "Inlined: " << '{'; for (auto iter = g.inlined.begin(); iter != g.inlined.end(); ++iter) { if (std::distance(g.inlined.begin(), iter) > 0) { stream << ", "; } stream << *iter; } stream << "}" << '\n'; stream << "Tile sizes: " << "{"; for (auto iter = g.tile_sizes.begin(); iter != g.tile_sizes.end(); ++iter) { if (std::distance(g.tile_sizes.begin(), iter) > 0) { stream << ", "; } stream << "(" << iter->first << ", " << iter->second << ")"; } stream << "}" << '\n'; return stream; } }; // Result of the analysis of a group. struct GroupAnalysis { // Estimate of the arithmetic and memory cost for computing the group. Cost cost; // Estimate of the parallelism that can be exploited while computing // the group. Expr parallelism; GroupAnalysis() : cost(Cost()) , parallelism(Expr()) {} GroupAnalysis(const Cost &c, Expr p) : cost(c), parallelism(std::move(p)) {} inline bool defined() const { return cost.defined() && parallelism.defined(); } void simplify() { cost.simplify(); if (parallelism.defined()) { parallelism = Internal::simplify(parallelism); } } friend std::ostream& operator<<(std::ostream &stream, const GroupAnalysis &analysis) { stream << "[arith cost:" << analysis.cost.arith << ", "; stream << "memory cost:" << analysis.cost.memory << ", "; stream << "parallelism:" << analysis.parallelism << "]\n"; return stream; } }; // Configuration of a group and the corresponding analysis. A group is the // set of functions that are computed together in tiles and the group config // specifies at what granularity they are computed together ('tile_sizes'). struct GroupConfig { map<string, Expr> tile_sizes; GroupAnalysis analysis; GroupConfig(const map<string, Expr> &tile_sizes, const GroupAnalysis &analysis) : tile_sizes(tile_sizes), analysis(analysis) {} GroupConfig() : tile_sizes(map<string, Expr>()), analysis(GroupAnalysis()) {} }; // Cache for storing the best configuration for the grouping choice. During // the grouping process, the impact of grouping two groups together is only // limited to the producers and consumers of the groups that are being grouped // together. The best grouping choices for the rest of the pipeline need not be // re-evaluated and caching them improves performance significantly. map<GroupingChoice, GroupConfig> grouping_cache; // Each group in the pipeline has a single output stage. A group is comprised // of function stages that are computed together in tiles (stages of a function // are always grouped together). 'groups' is the mapping from the output stage // of the group to the group. map<FStage, Group> groups; // The child stages of each stage (i.e. stages that depend on or use the values // computed by a particular stage) in the pipeline. map<FStage, set<FStage>> children; // Map from the output stage of the group to the analysis of the group. The mapping // needs to be updated whenever the grouping changes. map<FStage, GroupAnalysis> group_costs; // Levels that are targeted by the grouping algorithm. In the 'Inline' mode, the grouping // algorithm groups the functions by inlining the expression for the producer function // into the consumer stage. In the 'FastMem' mode, the grouping is done at the level of // tiles of the group output stage. enum class Level {Inline, FastMem}; // Bounds of each function stage in the pipeline. These bounds are inferred from the // estimates of the outputs and other functions in the pipeline. const map<string, Box> &pipeline_bounds; // Parameters of the machine model that is used for estimating the cost of each // group in the pipeline. const MachineParams &arch_params; // Dependency analysis of the pipeline. This support queries on regions // accessed and computed for producing some regions of some functions. DependenceAnalysis &dep_analysis; // The arithmetic and memory costs of evaluating the expressions which define // each function in the pipeline. RegionCosts &costs; // Output functions of the pipeline. const vector<Function> &outputs; Partitioner(const map<string, Box> &_pipeline_bounds, const MachineParams &_arch_params, const vector<Function> &_outputs, DependenceAnalysis &_dep_analysis, RegionCosts &_costs); void initialize_groups(); // Merge 'prod_group' into 'cons_group'. The output stage of 'cons_group' // will be the output stage of the merged group. Group merge_groups(const Group &prod_group, const Group &cons_group); // Merge 'prods' in 'choice' into 'cons'. Set the tile size of the new group // to the one specified by 'eval'. If 'level' is set to Inline, all members // of 'prods' will be inlined in the new group. void merge_groups(const GroupingChoice &choice, const GroupConfig &eval, Partitioner::Level level); // Given a grouping 'g', compute the estimated cost (arithmetic + memory) and // parallelism that can be potentially exploited when computing that group. GroupAnalysis analyze_group(const Group &g, bool show_analysis); // For each group in the partition, return the regions of the producers // need to be allocated to compute a tile of the group's output. map<FStage, map<string, Box>> group_storage_bounds(); // For each group in the partition, return the regions of the producers // required to compute a tile of the group's output. map<FStage, map<FStage, DimBounds>> group_loop_bounds(); // Partition the pipeline by iteratively merging groups until a fixpoint is // reached. void group(Partitioner::Level level); // Given a grouping choice, return a configuration for the group that gives // the highest estimated benefits. GroupConfig evaluate_choice(const GroupingChoice &group, Partitioner::Level level); // Pick the best choice among all the grouping options currently available. Uses // the cost model to estimate the benefit of each choice. This returns a vector of // choice and configuration pairs which describe the best grouping choice. vector<pair<GroupingChoice, GroupConfig>> choose_candidate_grouping(const vector<pair<string, string>> &cands, Partitioner::Level level); // Return the bounds required to produce a function stage. DimBounds get_bounds(const FStage &stg); // Return the bounds required to produce a tile of a function stage. DimBounds get_bounds_from_tile_sizes(const FStage &stg, const map<string, Expr> &tile_sizes); // Return the estimated size of the bounds. map<string, Expr> bounds_to_estimates(const DimBounds &bounds); // Given a function stage, return a vector of possible tile configurations for // that function stage. vector<map<string, Expr>> generate_tile_configs(const FStage &stg); // Find the best tiling configuration for a group 'g' among a set of tile // configurations. This returns a pair of configuration with the highest // estimated benefit and the estimated benefit. pair<map<string, Expr>, GroupAnalysis> find_best_tile_config(const Group &g); // Estimate the benefit (arithmetic + memory) of 'new_grouping' over 'old_grouping'. // Positive values indicates that 'new_grouping' may be preferrable over 'old_grouping'. // When 'ensure_parallelism' is set to true, this will return an undefined cost // if the estimated parallelism is smaller than the machine parameters. // If 'no_redundant_work' is set, we only consider the arithmetic cost, i.e. if // the arithmetic benefit is negative, we will treat it as no benefits and we // should not perform the new grouping. Expr estimate_benefit(const GroupAnalysis &old_grouping, const GroupAnalysis &new_grouping, bool no_redundant_work, bool ensure_parallelism); // Same as above; however, 'new_grouping' is a vector of function pairs that // are to be grouped together. Expr estimate_benefit(const vector<pair<GroupingChoice, GroupConfig>> &new_grouping, bool no_redundant_work, bool ensure_parallelism); // Return the total estimate on arithmetic and memory costs of computing all // groups within the pipeline. Cost get_pipeline_cost(); // Return the maximum access stride to allocation of 'func_acc' along any // loop variable specified in 'vars'. Access expressions along each dimension // of the allocation are specified by 'acc_exprs'. The dimension bounds of the // allocation are specified by 'buffer_bounds'. Expr find_max_access_stride(const Scope<> &vars, const string &func_acc, const vector<Expr> &acc_exprs, const Box &buffer_bounds); // Return the sum of access strides along each of the loop variables in // a function stage. The bounds of all the allocations accessed are specified // in 'allocation_bounds'. Return an empty map if it can't figure out any of // the stride dimension. map<string, Expr> analyze_spatial_locality( const FStage &stg, const map<string, Box> &parent_bounds, const set<string> &inlines = set<string>()); map<string, Expr> evaluate_reuse(const FStage &stg, const set<string> &prods); // Generate and apply schedules for all functions within a pipeline by // following their grouping structure. // // TODO: A mode where schedules are not applied to the functions might be // interesting. // // TODO: The current form of the schedule returned is not very useful since it // cannot be manipulated and introspected very easily. The problem is that all // of the scheduling uses internal function and variable names which are not // visible to the user. Additionally, functions like sum and maximum are not // user visible. More thought needs to go into interaction between the user and // auto scheduling. void generate_cpu_schedule(const Target &t, AutoSchedule &sched); // Same as \ref Partitioner::generate_cpu_schedule, but this generates and // applies schedules for a group of function stages. void generate_group_cpu_schedule(const Group &g, const Target &t, const map<FStage, DimBounds> &group_loop_bounds, const map<string, Box> &group_storage_bounds, const set<string> &inlines, AutoSchedule &sched); // Split the dimension of stage 'f_handle' along 'v' into inner and outer // dimensions. Modify 'estimates' according to the split and append the split // schedule to 'sched'. pair<VarOrRVar, VarOrRVar> split_dim( const Group &g, Stage f_handle, int stage_num, Definition def, bool is_group_output, VarOrRVar v, const Expr &factor, string in_suffix, string out_suffix, map<string, Expr> &estimates, AutoSchedule &sched); // Loop over the dimensions of function stage 'f_handle' starting from innermost // and vectorize the first pure dimension encountered. void vectorize_stage( const Group &g, Stage f_handle, int stage_num, Definition def, Function func, bool is_group_output, const Target &t, set<string> &rvars, map<string, Expr> &estimates, AutoSchedule &sched); // Reorder the dimensions to preserve spatial locality. This function // checks the stride of each access. The dimensions of the loop are reordered // such that the dimension with the smallest access stride is innermost. // This takes the strides along each dimension as input. void reorder_dims(Stage f_handle, int stage_num, Definition def, map<string, Expr> strides, AutoSchedule &sched); // Helper functions to display partition information of the pipeline. void disp_pipeline_costs(); void disp_pipeline_bounds(); void disp_pipeline_graph(); void disp_grouping(); }; void Partitioner::disp_grouping() { debug(0) << "\n=========" << '\n'; debug(0) << "Grouping:" << '\n'; debug(0) << "=========" << '\n'; for (const auto &g : groups) { debug(0) << g.second << '\n'; } debug(0) << "=========" << '\n'; } void Partitioner::disp_pipeline_graph() { debug(0) << "\n================" << '\n'; debug(0) << "Pipeline graph:" << '\n'; debug(0) << "================" << '\n'; for (const auto &f : children) { debug(0) << f.first << ": {"; for (auto iter = f.second.begin(); iter != f.second.end(); ++iter) { if (std::distance(f.second.begin(), iter) > 0) { debug(0) << ", "; } debug(0) << *iter; } debug(0) << "}" << '\n'; } debug(0) << "================" << '\n'; } void Partitioner::disp_pipeline_bounds() { debug(0) << "\n================" << '\n'; debug(0) << "Pipeline bounds:" << '\n'; debug(0) << "================" << '\n'; disp_regions(pipeline_bounds); debug(0) << "===============" << '\n'; } Cost Partitioner::get_pipeline_cost() { internal_assert(!group_costs.empty()); Cost total_cost(0, 0); for (const pair<FStage, Group> &g : groups) { const GroupAnalysis &analysis = get_element(group_costs, g.first); if (!analysis.cost.defined()) { return Cost(); } total_cost.arith += analysis.cost.arith; total_cost.memory += analysis.cost.memory; } total_cost.simplify(); return total_cost; } void Partitioner::disp_pipeline_costs() { internal_assert(!group_costs.empty()); Cost total_cost(0, 0); debug(0) << "\n===============" << '\n'; debug(0) << "Pipeline costs:" << '\n'; debug(0) << "===============" << '\n'; debug(0) << "Group: (name) [arith cost, mem cost, parallelism]" << '\n'; for (const pair<FStage, Group> &g : groups) { const GroupAnalysis &analysis = get_element(group_costs, g.first); if (!total_cost.arith.defined()) { continue; } else if (!analysis.cost.arith.defined()) { total_cost.arith = Expr(); } else { total_cost.arith += analysis.cost.arith; } if (!total_cost.memory.defined()) { continue; } else if (!analysis.cost.memory.defined()) { total_cost.memory = Expr(); } else { total_cost.memory += analysis.cost.memory; } debug(0) << "Group: " << g.first << " ["; debug(0) << analysis.cost.arith << ", " << analysis.cost.memory << ", " << analysis.parallelism << "]\n"; } total_cost.simplify(); debug(0) << "Total arithmetic cost: " << total_cost.arith << '\n'; debug(0) << "Total memory cost: " << total_cost.memory << '\n'; debug(0) << "===============" << '\n'; } // Construct a partitioner and build the pipeline graph on which the grouping // algorithm operates. Partitioner::Partitioner(const map<string, Box> &_pipeline_bounds, const MachineParams &_arch_params, const vector<Function> &_outputs, DependenceAnalysis &_dep_analysis, RegionCosts &_costs) : pipeline_bounds(_pipeline_bounds), arch_params(_arch_params), dep_analysis(_dep_analysis), costs(_costs), outputs(_outputs) { // Place each stage of a function in its own group. Each stage is // a node in the pipeline graph. for (const auto &f : dep_analysis.env) { if (!pipeline_bounds.count(f.first)) { // If a function does not have a pipeline bound (i.e. it can be // statically proven that no one ever uses it), we should not // consider it during the grouping. debug(5) << "Creating partitioner: ignore function \"" << f.first << "\" since it has empty pipeline bounds\n"; continue; } int num_stages = f.second.updates().size() + 1; for (int s = 0; s < num_stages; s++) { FStage stg(f.second, s); Group g(stg, {stg}); groups.insert(make_pair(stg, g)); } } // Find the consumers of each function and use it to populate the children map. for (const auto &f : dep_analysis.env) { int num_stages = f.second.updates().size() + 1; for (int s = 0; s < num_stages; s++) { set<string> parents = get_parents(f.second, s); for (const string &c : parents) { // Filter out the calls to pipeline inputs. 'env' only contains // the functions computed and not the inputs. auto iter = dep_analysis.env.find(c); if ((c != f.first) && (iter != dep_analysis.env.end())) { // Consumer depends only on the last stage of a producer // with multiple stages. const Function &prod_func = iter->second; int final_stage = prod_func.updates().size(); FStage prod_stage(prod_func, final_stage); FStage cons_stage(f.second, s); children[prod_stage].insert(cons_stage); } } if (s > 0) { // Update the children map to reflect the dependencies between // different stages of the same function. FStage prod_stage(f.second, s - 1); FStage cons_stage(f.second, s); children[prod_stage].insert(cons_stage); } } } } void Partitioner::initialize_groups() { for (pair<const FStage, Group> &g : groups) { pair<map<string, Expr>, GroupAnalysis> best = find_best_tile_config(g.second); g.second.tile_sizes = best.first; group_costs.emplace(g.second.output, best.second); } grouping_cache.clear(); } map<string, Expr> Partitioner::evaluate_reuse(const FStage &stg, const set<string> &prods) { map<string, Expr> reuse; Function f = stg.func; // TODO: Check if tile size of 1 in each dimension gives a reasonable // answer or reuse should be evaluated at a much larger granularity or // symbolically. Using a symbolic version might be better if the objective // is to prove the dimension has no reuse. The only downside with the // symbolic method is that it is totally at the mercy of the simplifier. // Another option is sampling or using a larger granularity. map<string, Expr> tile_sizes; const vector<Dim> &dims = get_stage_dims(stg.func, stg.stage_num); for (int d = 0; d < (int)dims.size() - 1; d++) { tile_sizes[dims[d].var] = 1; } DimBounds bounds = get_bounds_from_tile_sizes(stg, tile_sizes); vector<map<string, Box>> reuse_regions = dep_analysis.overlap_regions(stg.func, stg.stage_num, bounds, prods, false, &costs.input_estimates); for (int d = 0; d < (int)dims.size() - 1; d++) { Expr total_reuse = make_zero(Int(64)); if (debug::debug_level() >= 3) { disp_regions(reuse_regions[d]); } for (const auto &reg : reuse_regions[d]) { Expr size = box_size(reg.second); if (!size.defined()) { total_reuse = Expr(); break; } else { total_reuse += size; } } reuse.emplace(dims[d].var, simplify(total_reuse)); } return reuse; } vector<pair<Partitioner::GroupingChoice, Partitioner::GroupConfig>> Partitioner::choose_candidate_grouping(const vector<pair<string, string>> &cands, Partitioner::Level level) { vector<pair<GroupingChoice, GroupConfig>> best_grouping; Expr best_benefit = make_zero(Int(64)); for (const auto &p : cands) { // Compute the aggregate benefit of inlining into all the children. vector<pair<GroupingChoice, GroupConfig>> grouping; const Function &prod_f = get_element(dep_analysis.env, p.first); int final_stage = prod_f.updates().size(); FStage prod(prod_f, final_stage); for (const FStage &c : get_element(children, prod)) { GroupConfig best_config; GroupingChoice cand_choice(prod_f.name(), c); // Check if the candidate has been evaluated for grouping before const auto &iter = grouping_cache.find(cand_choice); if (iter != grouping_cache.end()) { best_config = iter->second; } else { best_config = evaluate_choice(cand_choice, level); // Cache the result of the evaluation for the pair grouping_cache.emplace(cand_choice, best_config); } grouping.push_back(make_pair(cand_choice, best_config)); } bool no_redundant_work = false; Expr overall_benefit = estimate_benefit(grouping, no_redundant_work, true); debug(3) << "Candidate grouping:\n"; for (const auto &g : grouping) { debug(3) << " " << g.first; } debug(3) << "Candidate benefit: " << overall_benefit << '\n'; // TODO: The grouping process can be non-deterministic when the costs // of two choices are equal if (overall_benefit.defined() && can_prove(best_benefit < overall_benefit)) { best_grouping = grouping; best_benefit = overall_benefit; } } debug(3) << "\nBest grouping:\n"; for (const auto &g : best_grouping) { debug(3) << " " << g.first; } if (best_grouping.size() > 0) { debug(3) << "Best benefit: " << best_benefit << '\n'; } return best_grouping; } inline bool operator==(const map<string, Expr> &m1, const map<string, Expr> &m2) { if (m1.size() != m2.size()) { return false; } for (const auto &it1 : m1) { const auto &it2 = m2.find(it1.first); if (it2 == m2.end()) { return false; } else if (!equal(it1.second, it2->second)) { return false; } } return true; } vector<map<string, Expr>> Partitioner::generate_tile_configs(const FStage &stg) { // TODO: This is a wart due to the cost model not taking vectorization // and pre-fetching into account. Ensuring the innermost dimension has // at least size of 64 gives enough values for vectorization and can help // with prefetching. This also interacts with the number of parallel tasks // that are generated. int min_inner_dim_size = 64; const vector<Dim> &dims = get_stage_dims(stg.func, stg.stage_num); // Get the dimensions that are going to be tiled in this stage. // Skipping rvars for now. vector<string> tile_vars; for (int d = 0; d < (int)dims.size() - 1; d++) { if (!dims[d].is_rvar()) { tile_vars.push_back(dims[d].var); } } vector<int> size_variants = {1, 4, 8, 16, 32, 64, 128, 256}; vector<map<string, Expr>> tile_configs; // For all the tile configurations generated, we force the innermost dimension // to be at least of size 64 to ensure enough values for vectorization. // Skewed tile configurations for (size_t i = 0; i < tile_vars.size(); i++) { for (const auto &dim_size : size_variants) { map<string, Expr> tiling; tiling.emplace(tile_vars[i], (i == 0) ? std::max(dim_size, min_inner_dim_size): dim_size); for (size_t j = 0; j < tile_vars.size(); j++) { if (j < i) { tiling.emplace(tile_vars[j], size_variants[size_variants.size() - 1]); } else if (j > i) { tiling.emplace(tile_vars[j], size_variants[0]); } } if (!tiling.empty()) { bool is_duplicate = std::find_if(tile_configs.begin(), tile_configs.end(), [&tiling](const map<string, Expr> &m) { return (tiling == m);}) != tile_configs.end(); if (!is_duplicate) { tile_configs.push_back(tiling); } } } } // Almost square tile configurations for (const auto &dim_size : size_variants) { map<string, Expr> tiling; for (size_t j = 0; j < tile_vars.size(); j++) { tiling.emplace(tile_vars[j], (j == 0) ? std::max(dim_size, min_inner_dim_size): dim_size); } if (!tiling.empty()) { bool is_duplicate = std::find_if(tile_configs.begin(), tile_configs.end(), [&tiling](const map<string, Expr> &m) { return (tiling == m);}) != tile_configs.end(); if (!is_duplicate) { tile_configs.push_back(tiling); } } } // Reorder tile configurations for (int i = 0; i < (1 << (tile_vars.size())); i++) { map<string, Expr> tiling; for (size_t j = 0; j < tile_vars.size(); j++) { if (((i >> (j)) & 1) == 1) { if (j == 0) { tiling.emplace(tile_vars[j], min_inner_dim_size); } else { tiling.emplace(tile_vars[j], 1); } } } if (!tiling.empty()) { bool is_duplicate = std::find_if(tile_configs.begin(), tile_configs.end(), [&tiling](const map<string, Expr> &m) { return (tiling == m);}) != tile_configs.end(); if (!is_duplicate) { tile_configs.push_back(tiling); } } } return tile_configs; } pair<map<string, Expr>, Partitioner::GroupAnalysis> Partitioner::find_best_tile_config(const Group &g) { // Initialize to no tiling map<string, Expr> no_tile_config; Group no_tile = g; no_tile.tile_sizes = no_tile_config; bool show_analysis = false; GroupAnalysis no_tile_analysis = analyze_group(no_tile, show_analysis); GroupAnalysis best_analysis = no_tile_analysis; map<string, Expr> best_config = no_tile_config; if (!best_analysis.cost.defined()) { return make_pair(best_config, best_analysis); } // Generate tiling configurations vector<map<string, Expr>> configs = generate_tile_configs(g.output); Group best_group = g; for (const auto &config : configs) { Group new_group = g; new_group.tile_sizes = config; GroupAnalysis new_analysis = analyze_group(new_group, show_analysis); bool no_redundant_work = false; Expr benefit = estimate_benefit(best_analysis, new_analysis, no_redundant_work, true); if (show_analysis) { debug(0) << "Benefit relative to not tiling:" << benefit << '\n'; debug(0) << "Best analysis:" << new_analysis; debug(0) << "No tile analysis:" << no_tile_analysis; debug(0) << "arith cost:" << cast<float>(new_analysis.cost.arith / no_tile_analysis.cost.arith) << ", mem cost:" << cast<float>(new_analysis.cost.memory / no_tile_analysis.cost.memory) << '\n'; } if (benefit.defined() && can_prove(benefit > 0)) { best_config = config; best_analysis = new_analysis; best_group = new_group; } } return make_pair(best_config, best_analysis); } void Partitioner::group(Partitioner::Level level) { bool fixpoint = false; while (!fixpoint) { Cost pre_merge = get_pipeline_cost(); fixpoint = true; vector<pair<string, string>> cand; for (const pair<FStage, Group> &g : groups) { bool is_output = false; for (const Function &f : outputs) { if (g.first.func.name() == f.name()) { is_output = true; break; } } // All stages of a function are computed at a single location. // The last stage of the function represents the candidate choice // of grouping the function into a consumer. const Function &prod_f = get_element(dep_analysis.env, g.first.func.name()); bool is_final_stage = (g.first.stage_num == prod_f.updates().size()); if (is_output || !is_final_stage) { continue; } const auto &iter = children.find(g.first); if (iter != children.end()) { // All the stages belonging to a function are considered to be a // single child. set<string> child_groups; for (const FStage &s : iter->second) { child_groups.insert(s.func.name()); } int num_children = child_groups.size(); // Only groups with a single child are considered for grouping // when grouping for computing in tiles. // TODO: The current scheduling model does not allow functions // to be computed at different points. if ((num_children == 1) && (level == Partitioner::Level::FastMem)) { const string &prod_name = prod_f.name(); const string &cons_name = (*child_groups.begin()); cand.push_back(make_pair(prod_name, cons_name)); } else if((level == Partitioner::Level::Inline) && prod_f.is_pure()) { const string &prod_name = prod_f.name(); cand.push_back(make_pair(prod_name, "")); } } } debug(3) << "\n============================" << '\n'; debug(3) << "Current grouping candidates:" << '\n'; debug(3) << "============================" << '\n'; for (size_t i = 0; i < cand.size(); ++i) { debug(3) << "{" << cand[i].first << ", " << cand[i].second << "}" << '\n'; } vector<pair<GroupingChoice, GroupConfig>> best = choose_candidate_grouping(cand, level); if (best.empty()) { continue; } else { fixpoint = false; } // The following code makes the assumption that all the stages of a function // will be in the same group. 'choose_candidate_grouping' ensures that the // grouping choice being returned adheres to this constraint. const string &prod = best[0].first.prod; const Function &prod_f = get_element(dep_analysis.env, prod); size_t num_stages = prod_f.updates().size() + 1; FStage final_stage(prod_f, num_stages - 1); set<FStage> prod_group_children = get_element(children, final_stage); // Invalidate entries of the grouping cache set<GroupingChoice> invalid_keys; for (const auto &c : prod_group_children) { for (const auto &entry : grouping_cache) { if ((entry.first.prod == c.func.name()) || (entry.first.cons == c)) { invalid_keys.insert(entry.first); } } } for (const auto &key : invalid_keys) { grouping_cache.erase(key); } for (const auto &group : best) { internal_assert(group.first.prod == prod); merge_groups(group.first, group.second, level); } for (size_t s = 0; s < num_stages; s++) { FStage prod_group(prod_f, s); groups.erase(prod_group); group_costs.erase(prod_group); // Update the children mapping children.erase(prod_group); for (auto &f : children) { set<FStage> &cons = f.second; auto iter = cons.find(prod_group); if (iter != cons.end()) { cons.erase(iter); // For a function with multiple stages, all the stages will // be in the same group and the consumers of the function // only depend on the last stage. Therefore, when the // producer group has multiple stages, parents of the // producers should point to the consumers of the last // stage of the producer. cons.insert(prod_group_children.begin(), prod_group_children.end()); } } } Cost post_merge = get_pipeline_cost(); if (debug::debug_level() >= 3) { disp_pipeline_costs(); } } } DimBounds Partitioner::get_bounds(const FStage &s) { DimBounds bounds; const vector<string> &args = s.func.args(); for (size_t d = 0; d < args.size(); d++) { bounds[args[d]] = get_element(pipeline_bounds, s.func.name())[d]; } return get_stage_bounds(s.func, s.stage_num, bounds); } DimBounds Partitioner::get_bounds_from_tile_sizes(const FStage &s, const map<string, Expr> &tile_sizes) { map<string, Interval> bounds; const map<string, Interval> &def_bounds = get_bounds(s); const vector<Dim> &dims = get_stage_dims(s.func, s.stage_num); for (int d = 0; d < (int)dims.size() - 1; d++) { string var = dims[d].var; const Interval &bound = get_element(def_bounds, var); const auto &iter = tile_sizes.find(var); if (iter != tile_sizes.end()) { const Expr &size = iter->second; // Check if the bounds allow for tiling with the given tile size, // i.e. ensure at least 2 tiles Expr extent = get_extent(bound); internal_assert(extent.defined()); if (can_prove(extent >= 2 * size)) { // TODO: Maybe shift this to the center of the pipeline bound bounds[var] = Interval(0, simplify(size - 1)); } else { // If the dimension is too small, do not tile it and set the // extent of the bounds to that of the dimension estimate bounds[var] = bound; } } else { bounds[var] = bound; } } return bounds; } Partitioner::GroupAnalysis Partitioner::analyze_group(const Group &g, bool show_analysis) { set<string> group_inputs; set<string> group_members; for (const auto &stg : g.members) { group_members.insert(stg.func.name()); set<string> parents = get_parents(stg.func, stg.stage_num); for (const auto &c : parents) { bool is_member = false; for (const auto &m : g.members) { if (m.func.name() == c) { is_member = true; break; } } if (!is_member) { group_inputs.insert(c); } } } // Count the number of tiles Expr estimate_tiles = make_one(Int(64)); Expr parallelism = make_one(Int(64)); if (!g.output.func.has_extern_definition()) { // Get the definition corresponding to the group output Definition def = get_stage_definition(g.output.func, g.output.stage_num); const vector<Dim> &dims = def.schedule().dims(); DimBounds stg_bounds = get_bounds(g.output); for (int d = 0; d < (int)dims.size() - 1; d++) { const string &var = dims[d].var; const auto &iter = g.tile_sizes.find(var); if (iter != g.tile_sizes.end()) { const Expr &size = iter->second; Expr extent = get_extent(get_element(stg_bounds, var)); if (!extent.defined()) { return GroupAnalysis(); } Expr dim_tiles = simplify((extent + size - 1) / size); estimate_tiles *= dim_tiles; // Since all Vars are inherently parallelizable by construct, we // only need to take RVars into account for the analysis. if (can_parallelize_rvar(var, g.output.func.name(), def)) { parallelism *= dim_tiles; } } } } // Get the regions of the pipeline required to compute a tile of the group DimBounds tile_bounds = get_bounds_from_tile_sizes(g.output, g.tile_sizes); map<string, Box> alloc_regions = dep_analysis.regions_required( g.output.func, g.output.stage_num, tile_bounds, group_members, false, &costs.input_estimates); map<string, Box> compute_regions = dep_analysis.regions_required( g.output.func, g.output.stage_num, tile_bounds, group_members, true, &costs.input_estimates); map<string, Box> group_reg, prod_reg, input_reg; // Separating into regions that computed within the group and regions that // are input to the group for (const auto &reg : compute_regions) { if ((group_members.find(reg.first) != group_members.end()) && (reg.first != g.output.func.name())) { group_reg.emplace(reg.first, reg.second); } else if (group_inputs.find(reg.first) != group_inputs.end()) { if (dep_analysis.env.find(reg.first) != dep_analysis.env.end()) { prod_reg.emplace(reg.first, reg.second); } else { input_reg.emplace(reg.first, reg.second); } } } // Aggregate costs for intermediate functions in a tile and the // tile output Cost tile_cost = costs.region_cost(group_reg, g.inlined); if (!tile_cost.defined()) { return GroupAnalysis(); } Cost out_cost = costs.stage_region_cost(g.output.func.name(), g.output.stage_num, tile_bounds, g.inlined); if (!out_cost.defined()) { return GroupAnalysis(); } for (const auto &reg : alloc_regions) { if (!box_size(reg.second).defined()) { return GroupAnalysis(); } } Cost group_cost(simplify(tile_cost.arith + out_cost.arith), simplify(tile_cost.memory + out_cost.memory)); // Detailed load costs for all the group intermediates map<string, Expr> group_load_costs = costs.detailed_load_costs(group_reg, g.inlined); map<string, Expr> out_load_costs = costs.stage_detailed_load_costs(g.output.func.name(), g.output.stage_num, tile_bounds, g.inlined); combine_load_costs(group_load_costs, out_load_costs); Box out_tile_extent; if (g.output.stage_num == 0) { const vector<string> &args = g.output.func.args(); for (size_t d = 0; d < args.size(); d++) { const auto &iter = tile_bounds.find(args[d]); if (iter != tile_bounds.end()) { out_tile_extent.push_back(iter->second); } else { out_tile_extent.push_back(Interval()); } } } Cost per_tile_cost(group_cost.arith, make_zero(Int(64))); // This is the old cost model; keeping it here for reference, for now. /* if (tile_inter_size > arch_params.l1_size) { // Conservative estimate of accesses to memory //per_tile_mem_cost = tile_inter_size; // Aggressive estimate of accesses to memory per_tile_mem_cost = tile_cost.second; } else { // The tile_input_size captures the region of the input // required to compute the tile. However, all of it many not be // accessed during the computation of the tile when the access // is sparse. A better estimate is given by the smaller of // the number of memory accesses and the region size per_tile_mem_cost = std::min(tile_input_size + tile_output_size, tile_cost.second); }*/ // TODO: Use smooth step curve from Jon to better model cache behavior, // where each step corresponds to different cache level. // // The current cost model drops off linearly. Larger memory footprint is // penalized more than smaller memory footprint (since smaller one can fit // more in the cache). The cost is clamped at 'balance', which is roughly at // memory footprint equal to or larger than the last level cache size. // If 'model_reuse' is set, the cost model should take into account memory // reuse within the tile, e.g. matrix multiply reuses inputs multiple times. // TODO: Implement a better reuse model. bool model_reuse = false; // Linear dropoff Expr load_slope = cast<float>(arch_params.balance) / arch_params.last_level_cache_size; for (const auto &f_load : group_load_costs) { internal_assert(g.inlined.find(f_load.first) == g.inlined.end()) << "Intermediates of inlined pure fuction \"" << f_load.first << "\" should not have been in the group_load_costs\n"; const auto &alloc_reg = get_element(alloc_regions, f_load.first); Expr footprint; bool is_group_member = (group_members.find(f_load.first) != group_members.end()); bool is_output = (f_load.first == g.output.func.name()); // We use allocated region as conservative estimate of the footprint since // the loads could be from any random locations of the allocated regions. if (!is_output && is_group_member) { footprint = costs.region_size(f_load.first, alloc_reg); } else { Expr initial_footprint; const auto &f_load_pipeline_bounds = get_element(pipeline_bounds, f_load.first); bool is_function = (dep_analysis.env.find(f_load.first) != dep_analysis.env.end()); if (!is_function) { // It is a load to some input buffer // Initial loads initial_footprint = costs.input_region_size(f_load.first, f_load_pipeline_bounds); // Subsequent loads footprint = costs.input_region_size(f_load.first, alloc_reg); } else if (is_output) { // Load to the output function of the group internal_assert(is_group_member) << "Output " << f_load.first << " should have been a group member\n"; // Initial loads initial_footprint = costs.region_size(f_load.first, f_load_pipeline_bounds); // Subsequent loads footprint = costs.region_size(f_load.first, out_tile_extent); } else { // Load to some non-member function (i.e. function from other groups) // Initial loads initial_footprint = costs.region_size(f_load.first, f_load_pipeline_bounds); // Subsequent loads footprint = costs.region_size(f_load.first, alloc_reg); } if (model_reuse) { Expr initial_factor = cast<int64_t>(min(1 + initial_footprint * load_slope, arch_params.balance)); per_tile_cost.memory += initial_factor * footprint; } else { footprint = initial_footprint; } if (!footprint.defined()) { return GroupAnalysis(); } } Expr cost_factor = cast<int64_t>(min(1 + footprint * load_slope, arch_params.balance)); per_tile_cost.memory += cost_factor * f_load.second; } if (show_analysis) { debug(0) << "\nDetailed loads:\n"; for (const auto &f_load : group_load_costs) { debug(0) << "(" << f_load.first << "," << f_load.second << ")"; } debug(0) << '\n'; debug(0) << "\nPer tile memory cost:" << per_tile_cost.memory << '\n'; debug(0) << "Per tile arith cost:" << per_tile_cost.arith << '\n'; } GroupAnalysis g_analysis( Cost(per_tile_cost.arith * estimate_tiles, per_tile_cost.memory * estimate_tiles), parallelism); g_analysis.simplify(); return g_analysis; } Partitioner::Group Partitioner::merge_groups(const Group &prod_group, const Group &cons_group) { vector<FStage> group_members; for (const auto &s : prod_group.members) { group_members.push_back(s); } for (const auto &s : cons_group.members) { group_members.push_back(s); } Group group(cons_group.output, group_members); for (const auto &f : prod_group.inlined) { group.inlined.insert(f); } for (const auto &f : cons_group.inlined) { group.inlined.insert(f); } return group; } void Partitioner::merge_groups(const GroupingChoice &choice, const GroupConfig &eval, Partitioner::Level level) { const Function &prod_f = get_element(dep_analysis.env, choice.prod); size_t num_stages = prod_f.updates().size() + 1; const FStage &child = choice.cons; Group &child_group = get_element(groups, child); for (size_t s = 0; s < num_stages; s++) { FStage cand(prod_f, s); Group &cand_group = get_element(groups, cand); child_group.members.insert(child_group.members.end(), cand_group.members.begin(), cand_group.members.end()); if (level == Partitioner::Level::Inline) { for (const auto &stg : cand_group.members) { child_group.inlined.insert(stg.func.name()); } } else { for (const auto &in : cand_group.inlined) { child_group.inlined.insert(in); } } } child_group.tile_sizes = eval.tile_sizes; // Update group costs. // We could just reuse the analysis from 'eval' since it was computed // by assuming the merge had happened. group_costs[child] = eval.analysis; } Partitioner::GroupConfig Partitioner::evaluate_choice(const GroupingChoice &choice, Partitioner::Level level) { // Create a group that reflects the grouping choice and evaluate the cost // of the group. const Function &prod_f = get_element(dep_analysis.env, choice.prod); int num_prod_stages = prod_f.updates().size() + 1; vector<Group> prod_groups; for (int s = 0; s < num_prod_stages; s++) { FStage prod_s(prod_f, s); prod_groups.push_back(get_element(groups, prod_s)); } Group cons = get_element(groups, choice.cons); Group group = cons; for (const auto &prod_g : prod_groups) { group = merge_groups(prod_g, group); } GroupAnalysis group_analysis; map<string, Expr> best_tile_config; if (level == Partitioner::Level::Inline) { // Set the tile sizes to one along all dimensions of the consumer group map<string, Expr> tile_sizes; const Function &cons_f = cons.output.func; const vector<Dim> &dims = get_stage_dims(cons_f, cons.output.stage_num); for (int d = 0; d < (int)dims.size() - 1; d++) { tile_sizes[dims[d].var] = 1; } group.tile_sizes = tile_sizes; for (const auto &prod_g : prod_groups) { for (const FStage &s : prod_g.members) { group.inlined.insert(s.func.name()); } } for (const string &f : cons.inlined) { group.inlined.insert(f); } group_analysis = analyze_group(group, false); best_tile_config = tile_sizes; } else { pair<map<string, Expr>, GroupAnalysis> config = find_best_tile_config(group); best_tile_config = config.first; group_analysis = config.second; } return GroupConfig(best_tile_config, group_analysis); } Expr Partitioner::estimate_benefit(const GroupAnalysis &old_grouping, const GroupAnalysis &new_grouping, bool no_redundant_work, bool ensure_parallelism) { // TODO: Instead of having a hard parallelism constraint, it may be better // to consider other metric, such as arith_cost/parallelism if (ensure_parallelism && (!new_grouping.parallelism.defined() || !can_prove(new_grouping.parallelism >= arch_params.parallelism))) { return Expr(); } if (!old_grouping.cost.defined() || !new_grouping.cost.defined()) { return Expr(); } Expr arith_benefit = old_grouping.cost.arith - new_grouping.cost.arith; if (no_redundant_work && !can_prove(arith_benefit >= 0)) { return Expr(); } Expr mem_benefit = old_grouping.cost.memory - new_grouping.cost.memory; return simplify(mem_benefit + arith_benefit); } Expr Partitioner::estimate_benefit( const vector<pair<GroupingChoice, GroupConfig>> &new_grouping, bool no_redundant_work, bool ensure_parallelism) { set<FStage> old_groups; GroupAnalysis new_group_analysis(Cost(0, 0), Int(64).max()); for (const auto &g : new_grouping) { const Function &prod_f = get_element(dep_analysis.env, g.first.prod); int num_prod_stages = prod_f.updates().size() + 1; for (int s = 0; s < num_prod_stages; s++) { FStage prod_s(prod_f, s); old_groups.insert(prod_s); } old_groups.insert(g.first.cons); GroupAnalysis analysisg = g.second.analysis; if (analysisg.defined()) { new_group_analysis.cost.arith += analysisg.cost.arith; new_group_analysis.cost.memory += analysisg.cost.memory; new_group_analysis.parallelism = min(new_group_analysis.parallelism, analysisg.parallelism); } else { new_group_analysis.cost = Cost(); new_group_analysis.parallelism = Expr(); break; } } new_group_analysis.simplify(); GroupAnalysis old_group_analysis(Cost(0, 0), Int(64).max()); for (const auto &g : old_groups) { const auto &iter = group_costs.find(g); internal_assert(iter != group_costs.end()); GroupAnalysis analysisg = iter->second; if (analysisg.defined()) { old_group_analysis.cost.arith += analysisg.cost.arith; old_group_analysis.cost.memory += analysisg.cost.memory; old_group_analysis.parallelism = min(old_group_analysis.parallelism, analysisg.parallelism); } else { old_group_analysis.cost = Cost(); old_group_analysis.parallelism = Expr(); break; } } old_group_analysis.simplify(); return estimate_benefit(old_group_analysis, new_group_analysis, no_redundant_work, ensure_parallelism); } map<string, Expr> Partitioner::bounds_to_estimates(const DimBounds &bounds) { map<string, Expr> estimates; for (const auto &bound : bounds) { estimates.emplace(bound.first, get_extent(bound.second)); } return estimates; } map<FStage, map<string, Box>> Partitioner::group_storage_bounds() { map<FStage, map<string, Box>> group_storage_bounds; for (const pair<const FStage, Group> &gpair : groups) { const Group &g = gpair.second; DimBounds bounds = get_bounds_from_tile_sizes(g.output, g.tile_sizes); set<string> prods; for (const FStage &s : g.members) { prods.insert(s.func.name()); } map<string, Box> reg_alloc = dep_analysis.regions_required(g.output.func, g.output.stage_num, bounds, prods, false, &costs.input_estimates); map<string, Box> group_alloc; for (const FStage &s : g.members) { const auto &iter = reg_alloc.find(s.func.name()); if ((iter != reg_alloc.end()) && (s.func.name() != g.output.func.name())) { group_alloc[s.func.name()] = iter->second; } } group_storage_bounds[gpair.first] = group_alloc; } return group_storage_bounds; } map<FStage, map<FStage, DimBounds>> Partitioner::group_loop_bounds() { map<FStage, map<FStage, DimBounds>> group_bounds; for (const pair<const FStage, Group> &gpair : groups) { Group g = gpair.second; map<FStage, DimBounds> mem_bounds; DimBounds bounds = get_bounds_from_tile_sizes(g.output, g.tile_sizes); set<string> prods; for (const FStage &s : g.members) { prods.insert(s.func.name()); } map<string, Box> reg_computed = dep_analysis.regions_required(g.output.func, g.output.stage_num, bounds, prods, true, &costs.input_estimates); for (const FStage &s : g.members) { const auto &iter = reg_computed.find(s.func.name()); if (iter != reg_computed.end()) { map<string, Expr> tile_sizes; const vector<string> &args = s.func.args(); for (size_t arg = 0; arg < args.size(); arg++) { tile_sizes[args[arg]] = get_extent(iter->second[arg]); } mem_bounds[s] = get_bounds_from_tile_sizes(s, tile_sizes); } } group_bounds[gpair.first] = mem_bounds; } return group_bounds; } // We need to get the base name of the dimension for scheduling (i.e. it // can't have any dots). For example, in split case, if "x" is the starting // dimension name, after split(x, x0, xi, ...), we will end up with something // like "x.x0" and "x.xi". If we want to later schedule "x.x0", we need to // pass "x0" instead of "x.x0". string get_base_name(string name) { size_t dot_pos = name.rfind('.'); if (dot_pos != string::npos) { return name.substr(dot_pos + 1); } return name; } // Return true if any of the values or args in 'def' refers to any of // the inputs or outputs, with access function which depends on 'var'. bool access_inputs_or_outputs(Definition def, VarOrRVar var, const map<string, Type> &inputs, const vector<Function> &outputs) { FindAllCalls find; def.accept(&find); for (size_t i = 0; i < find.call_args.size(); ++i) { const string &func = find.call_args[i].first; const vector<Expr> &args = find.call_args[i].second; if (inputs.find(func) == inputs.end()) { // Check if 'func' is an output bool is_output = std::find_if(outputs.begin(), outputs.end(), [&func](const Function &f) { return (f.name() == func);}) != outputs.end(); if (!is_output) { // 'func' is neither an input or an output continue; } } // Check if any of the accesses to 'func' depends on 'var' for (const auto &arg : args) { if (expr_uses_var(arg, var.name())) { return true; } } } return false; } pair<VarOrRVar, VarOrRVar> Partitioner::split_dim( const Group &g, Stage f_handle, int stage_num, Definition def, bool is_group_output, VarOrRVar v, const Expr &factor, string in_suffix, string out_suffix, map<string, Expr> &estimates, AutoSchedule &sched) { // Create new variables for the split dimensions string arg_name = v.name(); string inner_name = arg_name + in_suffix; string outer_name = arg_name + out_suffix; VarOrRVar inner(inner_name, v.is_rvar), outer(outer_name, v.is_rvar); { const auto &iter = sched.internal_vars.find(inner.name()); if (iter == sched.internal_vars.end()) { sched.internal_vars.emplace(inner.name(), inner); } else { internal_assert(iter->second.is_rvar == inner.is_rvar); } } { const auto &iter = sched.internal_vars.find(outer.name()); if (iter == sched.internal_vars.end()) { sched.internal_vars.emplace(outer.name(), outer); } else { internal_assert(iter->second.is_rvar == outer.is_rvar); } } // The default tail strategy is good enough for most use cases (see docs on // TailStrategy::Auto). However, the default of pure vars in update definitions // is RoundUp, which may introduces an out-of-bound error if it is an access // to inputs or outputs. // // We could have just used GuardWithIf when splitting pure vars in update // definition to ensure no out-of-bounds error. However, this is only // necessary, if the update definition involves accesses to inputs or outputs. // For other accesses, we could potentially use a more aggressive tail strategy // such as RoundUp or ShiftInwards. Note that if we use RoundUp or ShiftInwards, // any nested loops (generated by compute_at) will be affected as well. However, // since in the current auto-scheduler model, we always compute_at at the group // output, if the update definition is not the group output, we do not need to // care for the nested loops. If it is the update definition of the group output // however, we'd better make sure that no other member of the groups accesses // the inputs or outputs. TailStrategy strategy = TailStrategy::Auto; if ((stage_num > 0) && !v.is_rvar) { if (!is_group_output) { if (access_inputs_or_outputs(def, v, costs.inputs, outputs)) { strategy = TailStrategy::GuardWithIf; } } else { bool any_access_inputs_outputs = false; for (const FStage &mem : g.members) { if (mem.func.name() == f_handle.name()) { continue; } Definition mem_def = get_stage_definition(mem.func, mem.stage_num); if (access_inputs_or_outputs(mem_def, v, costs.inputs, outputs)) { any_access_inputs_outputs = true; break; } } if (any_access_inputs_outputs) { strategy = TailStrategy::GuardWithIf; } } } f_handle.split(v, outer, inner, factor, strategy); std::ostringstream oss; oss << "split(" << arg_name << ", " << outer_name << ", " << inner_name << ", " << factor; switch (strategy) { case TailStrategy::RoundUp: oss << ", TailStrategy::RoundUp)"; break; case TailStrategy::GuardWithIf: oss << ", TailStrategy::GuardWithIf)"; break; case TailStrategy::ShiftInwards: oss << ", TailStrategy::ShiftInwards)"; break; case TailStrategy::Auto: oss << ")"; break; default: internal_assert(false); } sched.push_schedule(f_handle.name(), stage_num, oss.str(), {arg_name, outer_name, inner_name}); const Expr &est = get_element(estimates, arg_name); internal_assert(est.defined()); estimates[inner_name] = factor; estimates[outer_name] = simplify((est + factor - 1) / factor); estimates.erase(arg_name); return make_pair(inner, outer); } void Partitioner::vectorize_stage(const Group &g, Stage f_handle, int stage_num, Definition def, Function func, bool is_group_output, const Target &t, set<string> &rvars, map<string, Expr> &estimates, AutoSchedule &sched) { vector<Dim> &dims = def.schedule().dims(); int vec_dim_index = -1; // Set the vector length as the maximum of the natural vector size of all // values produced by the function. int vec_len = 0; for (const auto &type : func.output_types()) { vec_len = std::max(vec_len, t.natural_vector_size(type)); } for (int d = 0; d < (int) dims.size() - 1; d++) { string dim_name = get_base_name(dims[d].var); bool can_vectorize = true; if (rvars.find(dim_name) != rvars.end()) { can_vectorize = can_parallelize_rvar(dim_name, func.name(), def); } const auto &iter = estimates.find(dim_name); if ((iter != estimates.end()) && iter->second.defined()) { if (can_vectorize && can_prove(iter->second >= vec_len)) { vec_dim_index = d; break; } } } if (vec_dim_index >= 0) { string vec_dim_name = get_base_name(dims[vec_dim_index].var); bool is_rvar = (rvars.find(vec_dim_name) != rvars.end()); internal_assert(is_rvar == dims[vec_dim_index].is_rvar()); VarOrRVar vec_var(vec_dim_name, is_rvar); pair<VarOrRVar, VarOrRVar> split_vars = split_dim(g, f_handle, stage_num, def, is_group_output, vec_var, vec_len, "_vi", "_vo", estimates, sched); f_handle.vectorize(split_vars.first); sched.push_schedule(f_handle.name(), stage_num, "vectorize(" + split_vars.first.name() + ")", {split_vars.first.name()}); if (is_rvar) { rvars.erase(vec_dim_name); rvars.insert(split_vars.first.name()); rvars.insert(split_vars.second.name()); } // TODO: Reorder vector dim to innermost if it is the innermost // storage dimension of the func. // // TODO: Check if the warning is necessary. if (vec_dim_index > 0) { user_warning << "Outer dim vectorization of var \"" << vec_dim_name << "\" in function \"" << f_handle.name() << "\"\n"; } } } // Return true if the vars/rvars in 'ordering' are in the same order as the // dim list. inline bool operator==(const vector<Dim> &dims, const vector<VarOrRVar> &ordering) { if (dims.size() != ordering.size() + 1) { // The dim list also contains '__outermost' return false; } for (size_t i = 0; i < ordering.size(); ++i) { if (dims[i].var != ordering[i].name()) { return false; } } return true; } // Return true if the vars/rvars in 'ordering' are not in the same order as the // dim list. inline bool operator!=(const vector<Dim> &dims, const vector<VarOrRVar> &ordering) { return !(dims == ordering); } void Partitioner::reorder_dims(Stage f_handle, int stage_num, Definition def, map<string, Expr> strides, AutoSchedule &sched) { vector<Dim> &dims = def.schedule().dims(); internal_assert(dims.size() > 1); vector<pair<string, int>> order; for (int d = 0; d < (int)dims.size() - 1; d++) { internal_assert(strides.find(dims[d].var) != strides.end()); } // Iterate until all the dimensions have been assigned an order while (strides.size() > 0) { // Find the pure dimension (can be vars or rvars) with the smallest stride bool found_pure_dim = false; Expr min_pure_stride = Int(64).max(); string min_pure_var; int min_pure_index = -1; for (int d = 0; d < (int)dims.size() - 1; d++) { string var_name = get_base_name(dims[d].var); const auto &iter = strides.find(var_name); if ((iter != strides.end()) && dims[d].is_pure()) { const Expr &dim_stride = iter->second; internal_assert(dim_stride.defined()); if (can_prove(dim_stride < min_pure_stride)) { min_pure_stride = dim_stride; min_pure_var = var_name; min_pure_index = d; } found_pure_dim = true; } } if (found_pure_dim && min_pure_var.empty()) { // Since none of the pure strides can be proven as the minimum, we // should break here otherwise it may cause infinite loop. return; } // Check if the stride of the pure dimension is smaller than // the first impure dimension that has not yet been assigned // an order Expr min_impure_stride = Int(64).max(); string min_impure_var; int min_impure_index = -1; for (int d = 0; d < (int)dims.size() - 1; d++) { string var_name = get_base_name(dims[d].var); const auto &iter = strides.find(var_name); if ((iter != strides.end()) && !dims[d].is_pure()) { const Expr &dim_stride = iter->second; internal_assert(dim_stride.defined()); if (can_prove(dim_stride < min_impure_stride)) { min_impure_stride = dim_stride; min_impure_var = var_name; min_impure_index = d; // Impure dimensions cannot be reordered relative to // each other. Stop after encountering the first impure // dimension. break; } } } if (min_pure_var.empty() && min_impure_var.empty()) { // Since none of the pure and impure strides can be proven as the // minimum, we should break here otherwise it may cause infinite loop. return; } pair<string, int> curr_min_var; if (!min_impure_var.empty() && can_prove(min_impure_stride < min_pure_stride)) { curr_min_var.first = min_impure_var; curr_min_var.second = min_impure_index; internal_assert(dims[min_impure_index].is_rvar()); } else { curr_min_var.first = min_pure_var; curr_min_var.second = min_pure_index; } order.push_back(curr_min_var); strides.erase(curr_min_var.first); } vector<VarOrRVar> ordering; for (const auto &o : order) { VarOrRVar o_var(o.first, dims[o.second].is_rvar()); ordering.push_back(o_var); } internal_assert(!ordering.empty()); set<string> var_list = {ordering[0].name()}; string var_order = ordering[0].name(); for (size_t o = 1; o < ordering.size(); o++) { var_order += ", " + ordering[o].name(); var_list.insert(ordering[o].name()); } if (dims != ordering) { f_handle.reorder(ordering); sched.push_schedule(f_handle.name(), stage_num, "reorder(" + var_order + ")", var_list); } } // Visitor to find all the variables the depend on a variable. class FindVarsUsingVar : public IRVisitor { using IRVisitor::visit; void visit(const Let *let) { if (expr_uses_vars(let->value, vars)) { vars.push(let->name); } let->value.accept(this); let->body.accept(this); } public : Scope<> vars; FindVarsUsingVar(string var) { vars.push(var); } }; void Partitioner::generate_group_cpu_schedule( const Group &g, const Target &t, const map<FStage, DimBounds> &group_loop_bounds, const map<string, Box> &group_storage_bounds, const set<string> &inlines, AutoSchedule &sched) { string out_f_name = g.output.func.name(); Function g_out = g.output.func; debug(3) << "\n================\n"; debug(3) << "Scheduling group:\n"; debug(3) << "================\n"; debug(3) << g; if (g.output.func.has_extern_definition()) { internal_assert(g.members.size() == 1); Func(g_out).compute_root(); sched.push_schedule(g_out.name(), g.output.stage_num, "compute_root()", {}); return; } // Get the estimates for stage bounds DimBounds stg_bounds = get_bounds(g.output); map<string, Expr> stg_estimates = bounds_to_estimates(stg_bounds); Stage f_handle = Stage(Func(g_out)); // Get a function handle for scheduling the stage if (g.output.stage_num > 0) { int stage_num = g.output.stage_num; f_handle = Func(g_out).update(stage_num - 1); } else { Func(g_out).compute_root(); sched.push_schedule(f_handle.name(), g.output.stage_num, "compute_root()", {}); } // Realize tiling and update the dimension estimates vector<VarOrRVar> outer_dims; vector<VarOrRVar> inner_dims; // Get the definition corresponding to the stage Definition def = get_stage_definition(g_out, g.output.stage_num); // 'dims' will get modified since we are going to apply the schedules // (e.g. tiling, reordering, etc.) vector<Dim> &dims = def.schedule().dims(); // Keep track of the rvars set<string> rvars; for (int d = 0; d < (int)dims.size() - 1; d++) { if (dims[d].is_rvar()) { rvars.insert(get_base_name(dims[d].var)); } } // Reorder the dimensions for better spatial locality (i.e. smallest stride // is innermost). If we only have one dimension (excluding __outermost), // there is nothing to reorder. if (dims.size() > 2) { map<string, Expr> strides = analyze_spatial_locality(g.output, group_storage_bounds, inlines); if (!strides.empty()) { reorder_dims(f_handle, g.output.stage_num, def, strides, sched); } } vector<string> dim_vars(dims.size() - 1); for (int d = 0; d < (int)dims.size() - 1; d++) { dim_vars[d] = get_base_name(dims[d].var); } // Apply tiling to output of the group for (const auto &var : dim_vars) { bool is_rvar = (rvars.find(var) != rvars.end()); VarOrRVar v(var, is_rvar); const auto &iter = g.tile_sizes.find(var); if ((iter != g.tile_sizes.end()) && get_element(stg_estimates, var).defined() && can_prove(get_element(stg_estimates, var) > iter->second)) { const Expr &tile_size = iter->second; if (can_prove(tile_size == 1)) { outer_dims.push_back(v); } else { pair<VarOrRVar, VarOrRVar> tile_vars = split_dim(g, f_handle, g.output.stage_num, def, true, v, tile_size, "_i", "_o", stg_estimates, sched); inner_dims.push_back(tile_vars.first); outer_dims.push_back(tile_vars.second); if (is_rvar) { rvars.erase(var); rvars.insert(tile_vars.first.name()); rvars.insert(tile_vars.second.name()); } } } else { inner_dims.push_back(v); } } // Reorder the tile dimensions if (!outer_dims.empty()) { vector<VarOrRVar> ordering; for (const auto &v : inner_dims) { ordering.push_back(v); } for (const auto &v : outer_dims) { ordering.push_back(v); } set<string> var_list; string var_order = ordering[0].name(); for (size_t o = 1; o < ordering.size(); o++) { var_order += ", " + ordering[o].name(); var_list.insert(ordering[o].name()); } if (dims != ordering) { f_handle.reorder(ordering); sched.push_schedule(f_handle.name(), g.output.stage_num, "reorder(" + var_order + ")", var_list); } } vectorize_stage(g, f_handle, g.output.stage_num, def, g_out, true, t, rvars, stg_estimates, sched); // Parallelize definition Expr def_par = 1; // TODO: Investigate if it is better to pull one large dimension and // parallelize over it or to generate nested parallelism. // // Go from the outer to the innermost loop until sufficient parallelism // is achieved. Stop the search once we find a vectorized dimension since // it doesn't make any sense to have a parallelized inner loop within a // vectorized outer loop. bool nested_parallelism = true; if (nested_parallelism) { int dim_start = dims.size() - 2; string seq_var = ""; for (int d = dim_start; d >= 0; d--) { if (dims[d].for_type == ForType::Vectorized) { break; } string var = get_base_name(dims[d].var); bool is_rvar = (rvars.find(var) != rvars.end()); internal_assert(is_rvar == dims[d].is_rvar()); VarOrRVar v(var, is_rvar); if (is_rvar && !can_parallelize_rvar(var, g_out.name(), def)) { if (seq_var == "") { seq_var = var; } continue; } if (can_prove(def_par >= arch_params.parallelism)) { // Enough parallelism to saturate target machine break; } const auto &iter = stg_estimates.find(var); if ((iter != stg_estimates.end()) && iter->second.defined()) { if (seq_var != "") { VarOrRVar seq(seq_var, (rvars.find(seq_var) != rvars.end())); f_handle.reorder(seq, v); sched.push_schedule(f_handle.name(), g.output.stage_num, "reorder(" + seq_var + ", " + var + ")", {seq_var, var}); } f_handle.parallel(v); sched.push_schedule(f_handle.name(), g.output.stage_num, "parallel(" + var + ")", {var}); def_par = simplify(def_par * iter->second); } else { break; } } } if (can_prove(def_par < arch_params.parallelism)) { user_warning << "Insufficient parallelism for " << f_handle.name() << '\n'; } // Find the level at which group members will be computed. int tile_inner_index = dims.size() - outer_dims.size() - 1; VarOrRVar tile_inner_var("", false); if (!outer_dims.empty()) { string var_name = get_base_name(dims[tile_inner_index].var); bool is_rvar = (rvars.find(var_name) != rvars.end()); tile_inner_var = VarOrRVar(var_name, is_rvar); } for (const FStage &mem : g.members) { // Skip member stages that have been inlined or stage that is the // output stage of the group if ((g.inlined.find(mem.func.name()) != g.inlined.end()) || (mem.func.name() == g_out.name())) { continue; } // Get the definition corresponding to the stage Definition mem_def = get_stage_definition(mem.func, mem.stage_num); // Get the estimates for the dimensions of the member stage map<string, Expr> mem_estimates = bounds_to_estimates(get_element(group_loop_bounds, mem)); set<string> mem_rvars; vector<Dim> &mem_dims = mem_def.schedule().dims(); for (int d = 0; d < (int)mem_dims.size() - 1; d++) { if (mem_dims[d].is_rvar()) { mem_rvars.insert(get_base_name(mem_dims[d].var)); } } // Get a function handle for scheduling the stage Stage mem_handle = Stage(Func(mem.func)); if (mem.stage_num > 0) { mem_handle = Func(mem.func).update(mem.stage_num - 1); } else { if (!outer_dims.empty()) { if (tile_inner_var.is_rvar) { Func(mem.func).compute_at(Func(g_out), tile_inner_var.rvar); } else { Func(mem.func).compute_at(Func(g_out), tile_inner_var.var); } string sanitized_g_out = get_sanitized_name(g_out.name()); sched.push_schedule(mem_handle.name(), mem.stage_num, "compute_at(" + sanitized_g_out + ", " + tile_inner_var.name() + ")", {sanitized_g_out, tile_inner_var.name()}); } else { user_warning << "Degenerate tiling. No dimensions are tiled" << '\n'; user_warning << "Computing \"" << mem.func.name() << "\" at root" << '\n'; Func(mem.func).compute_root(); sched.push_schedule(mem_handle.name(), mem.stage_num, "compute_root()", {}); } } // Reorder the dimensions for better spatial locality. If we only have // one dimension (excluding __outermost), there is nothing to reorder. if (dims.size() > 2) { map<string, Expr> mem_strides = analyze_spatial_locality(mem, group_storage_bounds, inlines); if (!mem_strides.empty()) { reorder_dims(mem_handle, mem.stage_num, mem_def, mem_strides, sched); } } vectorize_stage(g, mem_handle, mem.stage_num, mem_def, mem.func, false, t, mem_rvars, mem_estimates, sched); } } void Partitioner::generate_cpu_schedule(const Target &t, AutoSchedule &sched) { // Grab the group bounds early as they rely on the dimensions of the group // outputs which will be altered by modifying schedules. map<FStage, map<FStage, DimBounds>> loop_bounds = group_loop_bounds(); map<FStage, map<string, Box>> storage_bounds = group_storage_bounds(); set<string> inlines; // Mark all functions that are inlined. for (const pair<FStage, Group> &g : groups) { for (const string &inline_func : g.second.inlined) { inlines.insert(inline_func); } } // TODO: Inlining functions with update definitions has different // behavior than pure functions. They may need to be computed above // the innermost vector loop to avoid complications with varying // extents across different vector lanes. // // Since the default schedule is compute inline, we don't need to // explicitly call compute_inline() on the function. // Realize schedule for each group in the pipeline. for (const auto &g : groups) { generate_group_cpu_schedule(g.second, t, get_element(loop_bounds, g.first), get_element(storage_bounds, g.first), inlines, sched); } } Expr Partitioner::find_max_access_stride(const Scope<> &vars, const string &func_acc, const vector<Expr> &acc_exprs, const Box &buffer_bounds) { size_t num_storage_dims = 0; Expr bytes_per_ele = make_zero(Int(64)); // Get the number of dimensions of the allocated storage and the // number of bytes required to store a single value of func_acc. const auto &iter = dep_analysis.env.find(func_acc); if (iter != dep_analysis.env.end()) { const Function &f = iter->second; for (const auto &e : f.values()) { bytes_per_ele += e.type().bytes(); } num_storage_dims = f.schedule().storage_dims().size(); } else { bytes_per_ele = get_element(costs.inputs, func_acc).bytes(); num_storage_dims = buffer_bounds.size(); } Expr curr_stride = bytes_per_ele; Expr stride = make_zero(Int(64)); internal_assert(num_storage_dims <= acc_exprs.size()); for (size_t sdim = 0; sdim < num_storage_dims; sdim++) { // Check if the access expression depends on any of the loop variables // in 'vars'. Expressions that do not involve the variable have stride 0. if (expr_uses_vars(acc_exprs[sdim], vars)) { stride = max(stride, curr_stride); } const Interval &dim_range = buffer_bounds[sdim]; Expr dim_extent = get_extent(dim_range); if (!dim_extent.defined()) { return Expr(); } curr_stride *= dim_extent; } return simplify(stride); } map<string, Expr> Partitioner::analyze_spatial_locality(const FStage &stg, const map<string, Box> &allocation_bounds, const set<string> &inlines) { internal_assert(!stg.func.has_extern_definition()); // Handle inlining. When a function is inlined into another, the stride of // the accesses should be computed on the expression post inlining. // For example: // f(x, y) = ...; // g(x, y) = f(y, x); // transpose // h(x, y) = g(y, x); // transpose // // If both g and f are inlined into h, then the resulting expression for h // will look like: // h(x, y) = f(x, y); // // Computing the stride of a loop over x in the function h will be incorrect // if inlining is not taken into account. // Get all the allocations accessed in the definition corresponding to 'stg'. FindAllCalls find; Definition def = get_stage_definition(stg.func, stg.stage_num); // Perform inlining on the all the values and the args in the stage. for (auto &val : def.values()) { val = perform_inline(val, dep_analysis.env, inlines); } for (auto &arg : def.args()) { arg = perform_inline(arg, dep_analysis.env, inlines); } def.accept(&find); // Arguments on the left hand side might themselves involve accesses // to allocations and thus need to be accounted for when computing the // strides along each dimension. vector<pair<string, vector<Expr>>> &call_args = find.call_args; // Account for the spatial locality of the store. Add the access on the // left hand side to call_args. call_args.push_back(make_pair(stg.func.name(), def.args())); // Map for holding the strides across each dimension map<string, Expr> var_strides; const vector<Dim> &dims = def.schedule().dims(); for (int d = 0; d < (int)dims.size() - 1; d++) { // Get all the variables involving the dimension in the definition. FindVarsUsingVar dep_vars(dims[d].var); def.accept(&dep_vars); // Accumulate the stride of each access to a loop dimension. Expr total_stride = 0; for (const pair<string, vector<Expr>> &call : call_args) { Box call_alloc_reg; const auto &iter = allocation_bounds.find(call.first); if (iter != allocation_bounds.end()) { call_alloc_reg = iter->second; } else { call_alloc_reg = get_element(pipeline_bounds, call.first); } Expr current_stride = find_max_access_stride(dep_vars.vars, call.first, call.second, call_alloc_reg); if (!current_stride.defined()) { return map<string, Expr>(); } total_stride += current_stride; } var_strides.emplace(dims[d].var, simplify(total_stride)); } return var_strides; } // Verify that function 'f' does not have partially specified schedules/bounds. // The current auto scheduler cannots handle such cases. void validate_no_partial_schedules(const Function &f) { if (f.has_extern_definition()) { return; } // Verify no compute_root or bounds are specified user_assert(f.schedule().compute_level().is_inlined()) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since it is scheduled to be computed at root\n"; user_assert(f.schedule().bounds().empty()) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since it has partially specified bounds\n"; int num_stages = f.updates().size() + 1; for (int stage = 0; stage < num_stages; ++stage) { const Definition &def = get_stage_definition(f, stage); const StageSchedule &schedule = def.schedule(); // Verify no splits are specified user_assert(schedule.splits().empty()) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since it has partially specified schedules at stage " << stage << "\n"; // Verify that none of the dimensions are scheduled to be parallelized or // vectorized, or unrolled. for (const auto &d : schedule.dims()) { user_assert(d.for_type == ForType::Serial) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since stage " << stage << " is not serial at dim " << d.var << "\n"; } if (stage == 0) { // Since we can only specialize on a Func, we only need to check for no // specializations for the initial stage. user_assert(def.specializations().empty()) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since it has specializations\n"; // Verify that there is no loop reordering on the initial definition // (i.e. the Vars in the dim list should be in the same order as // the args in the LHS of the definition). internal_assert(schedule.dims().size() - 1 == def.args().size()); for (size_t i = 0; i < def.args().size(); ++i) { const Variable *arg = def.args()[i].as<Variable>(); internal_assert(arg); user_assert(arg->name == schedule.dims()[i].var) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since dim \"" << arg->name << "\" at stage " << stage << " has been reordered\n"; } } else { // Verify that there is no loop reordering on the update definition // (i.e. the Vars in the dim list should be in the same order as // the args in the LHS of the definition, the RVars in the dim list // should be in the same order as the RVars in the rvar list, and // all RVars should come before all Vars). const vector<Dim> &dims = schedule.dims(); const vector<ReductionVariable> &rvars = schedule.rvars(); const vector<Expr> &args = f.definition().args(); internal_assert(dims.size() - 1 >= rvars.size()); for (size_t i = 0; i < rvars.size(); ++i) { const Dim &d = dims[i]; user_assert(d.is_rvar() && (d.var == rvars[i].var)) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since dim \"" << i << "\" at stage " << stage << " has been reordered\n"; } internal_assert(dims.size() - rvars.size() - 1 <= args.size()); int last_index = -1; for (int i = rvars.size(); i < (int)dims.size() - 1; ++i) { const Dim &d = dims[i]; user_assert(!d.is_rvar()) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since dim \"" << i << "\" at stage " << stage << " has been reordered\n"; const auto &iter = std::find_if(args.begin(), args.end(), [&d](const Expr &arg) { const Variable *v = arg.as<Variable>(); return (d.var == v->name); }); internal_assert(iter != args.end()); int current_index = iter - args.begin(); user_assert(current_index > last_index) << "AutoSchedule: cannot auto-schedule function \"" << f.name() << "\" since dim \"" << i << "\" at stage " << stage << " has been reordered\n"; last_index = current_index; } } } } // Determine if a Func (order[index]) is only consumed by another single Func // in element-wise manner. If it is, return the name of the consumer Func; // otherwise, return an empty string. string is_func_called_element_wise(const vector<string> &order, size_t index, const map<string, Function> &env) { Function f1 = env.at(order[index]); if (f1.has_extern_definition() || !f1.can_be_inlined()) { return ""; } internal_assert(index < order.size()); string caller = ""; for (size_t i = index + 1; i < order.size(); ++i) { Function f2 = env.at(order[i]); if (f2.has_extern_definition()) { continue; } int num_stages = f2.updates().size() + 1; for (int s = 0; s < num_stages; ++s) { Definition def = get_stage_definition(f2, s); FindAllCalls find; def.accept(&find); if (find.funcs_called.count(f1.name())) { if (caller.empty()) { caller = f2.name(); } else { // Found another caller of 'f1' return ""; } } for (const auto &iter : find.call_args) { if (iter.first != f1.name()) { continue; } if (def.args().size() != iter.second.size()) { // It's not an element-wise access return ""; } for (size_t j = 0; j < iter.second.size(); ++j) { if (!equal(def.args()[j], iter.second[j])) { // It's not an element-wise access return ""; } } } } } return caller; } // Return true if 'f' is used by some extern Func. bool used_by_extern_func(const map<string, Function> &env, const Function &f) { for (const auto &iter : env) { for (const ExternFuncArgument &arg : iter.second.extern_arguments()) { if (arg.is_func()) { if (Function(arg.func).name() == f.name()) { return true; } } } } return false; } // If the bounds of a Func are undefined, then we should just inline the Func // as long as it is legal to inline or used by some extern Func. set<string> get_unbounded_functions(const map<string, Box> &pipeline_bounds, const map<string, Function> &env) { set<string> unbounded; for (const auto &iter : env) { if (!pipeline_bounds.count(iter.first)) { debug(5) << "...Skip checking function \"" << iter.first << "\" since it does not have pipeline bounds\n"; continue; } const Function &f = iter.second; if (!f.can_be_inlined() || used_by_extern_func(env, f)) { continue; } const Box &bound = get_element(pipeline_bounds, iter.first); if (is_box_unbounded(bound)) { unbounded.insert(iter.first); } } return unbounded; } bool inline_unbounded(const vector<Function> &outputs, const vector<string> &order, const map<string, Function> &env, const set<string> &unbounded) { bool inlined = false; // The very last few functions in 'order' are the last to be realized in the // pipeline (the final producers) so there is no point in checking it. for (int i = 0; i < (int)order.size() - (int)outputs.size(); ++i) { Function f1 = env.at(order[i]); if (!unbounded.count(f1.name())) { continue; } inlined = true; debug(4) << "Function \"" << order[i] << "\" is unbounded\n"; for (int j = i + 1; j < (int)order.size(); ++j) { internal_assert(order[i] != order[j]); Function f2 = env.at(order[j]); debug(5) << "Inline unbounded function \"" << f1.name() << "\" inside \"" << f2.name() << "\"\n"; inline_function(f2, f1); } } return inlined; } } // anonymous namespace // Check if all the pipeline outputs have estimates specified // on each of their dimensions; otherwise, throw an assertion. void check_estimates_on_outputs(const vector<Function> &outputs) { for (const auto &out : outputs) { const vector<Bound> &estimates = out.schedule().estimates(); // Check if the estimate for each dimension of the output is available // and is an integer. If there are duplicates for the estimate of a // dimension, we only check the last defined estimate (which min and // extent values are defined) since it is the one that would be // eventually used. Bound est; for (const auto &arg : out.args()) { bool found = false; for (int i = (int)estimates.size() - 1; i >= 0; --i) { if ((estimates[i].var == arg) && estimates[i].min.defined() && estimates[i].extent.defined()) { found = true; est = estimates[i]; break; } } user_assert(found && est.min.type().is_int() && est.extent.type().is_int()) << "Please provide a valid estimate for dimension " << est.var << " of output \"" << out.name() << "\"\n"; } } } // If the cost of computing a Func is about the same as calling the Func, // inline the Func. Return true of any of the Funcs is inlined. bool inline_all_trivial_functions(const vector<Function> &outputs, const vector<string> &order, const map<string, Function> &env) { bool inlined = false; // The very last few functions in 'order' are the last to be realized in the // pipeline (the final producers) so there is no point in checking it. for (int i = 0; i < (int)order.size() - (int)outputs.size(); ++i) { bool is_output = false; for (const Function &f : outputs) { if (order[i] == f.name()) { is_output = true; break; } } if (is_output) { // Should not inline output Func debug(5) << "Skip inlining " << order[i] << " since it is an output\n"; continue; } Function f1 = env.at(order[i]); if (is_func_trivial_to_inline(f1)) { inlined = true; debug(4) << "Function \"" << order[i] << "\" is trivial to inline\n"; for (int j = i + 1; j < (int)order.size() - (int)outputs.size(); ++j) { internal_assert(order[i] != order[j]); Function f2 = env.at(order[j]); if (f2.has_extern_definition() && !f1.is_wrapper()) { debug(5) << "Skip inlining of function \"" << f1.name() << "\" inside \"" << f2.name() << "\", because " << "non-wrapper functions cannot be inlined inside " << "extern functions.\n"; } else { debug(5) << "Inline trivial function \"" << f1.name() << "\" inside \"" << f2.name() << "\"\n"; inline_function(f2, f1); } } } } return inlined; } // Inline a Func if its values are only consumed by another single Func in // element-wise manner. bool inline_all_element_wise_functions(const vector<Function> &outputs, const vector<string> &order, const map<string, Function> &env) { bool inlined = false; // The very last few functions in 'order' are the last to be realized in the // pipeline (the final producers) so there is no point in checking it. for (int i = 0; i < (int)order.size() - (int)outputs.size(); ++i) { bool is_output = false; for (const Function &f : outputs) { if (order[i] == f.name()) { is_output = true; break; } } if (is_output) { // Should not inline output Func debug(5) << "Skip inlining " << order[i] << " since it is an output\n"; continue; } string caller = is_func_called_element_wise(order, i, env); if (!caller.empty()) { inlined = true; debug(4) << "Inline function \"" << order[i] << "\" since it is called only by " << caller << " in element-wise manner\n"; internal_assert(order[i] != caller); inline_function(env.at(caller), get_element(env, order[i])); } } return inlined; } // Generate schedules for all functions in the pipeline required to compute the // outputs. This applies the schedules and returns a string representation of // the schedules. The target architecture is specified by 'target'. string generate_schedules(const vector<Function> &outputs, const Target &target, const MachineParams &arch_params) { // Make an environment map which is used throughout the auto scheduling process. map<string, Function> env; for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } // Finalize all the LoopLevels for (auto &iter : env) { iter.second.lock_loop_levels(); } // Compute the topological order, before any trivial inlining (i.e. before // we remove any functions from 'env'). We need the full topological // order to pass to get_func() when generating the string representation // of the schedule. debug(2) << "Computing topological order...\n"; vector<string> top_order = topological_order(outputs, env); // Validate that none of the functions in the pipeline have partial schedules. debug(2) << "Validating no partial schedules...\n"; for (const auto &iter : env) { validate_no_partial_schedules(iter.second); } // The auto scheduling algorithm requires estimates on the outputs of the // pipeline to get quantitative estimates of costs for computing functions // in the pipeline. debug(2) << "Checking estimates on outputs...\n"; check_estimates_on_outputs(outputs); // Run a pre-pass that inline all trivial Funcs (i.e. if the cost of // computing a Func is about the same as calling that Func, we should // just inline it). debug(2) << "Inlining all trivial functions...\n"; if (inline_all_trivial_functions(outputs, top_order, env)) { // If any of the Funcs is inlined, we need to recompute 'env', since some // of the Funcs are no longer used and need to be removed from 'env'. // // Instead of recomputing 'env', we could also remove the inlined Func // within inline_all_trivial_functions(); however, it is a bit tricky // to do when dealing with inlined tuple. Consider the following case: // f(x, y) = x + y; // g(x, y) = {x, f(x, y)}; // h(x, y) = g(x, y)[0]; // When 'g' is inlined in 'h', no one uses 'f' anymore and it can // be removed from 'env'. However, to know this, we need to trace // all the function calls within the pipeline. Thus, we might as well // recompute the 'env' from scratch. env.clear(); for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } } // Compute the realization order of the functions within the pipeline. vector<string> order = realization_order(outputs, env).first; // Run a pre-pass that inline all Funcs which values are accessed by // another single Func in element-wise manner. We need to do this // repeatedly since some inlining decisions may enable further inlining // that previously not possible. Consider the following case: // f1(x) = x; // f2(x) = f1(x) + 2; // f3(x) = f1(x) * 2; // f4(x) = f2(x) + f3(x); // f5(x) = f4(x) + 3; // In the first iteration, we cannot inline 'f1' since it is used by two // functions: 'f2' and 'f3'. If 'f2' and 'f4' get inlined and 'f3' is only // used by 'f4', then 'f1' can now also be inlined. debug(2) << "Inlining all element-wise functions...\n"; while (inline_all_element_wise_functions(outputs, order, env)) { // We need to recompute 'env' for the same reason as with // inline_all_trivial_functions env.clear(); for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } order = realization_order(outputs, env).first; } // Compute the bounds of function values which are used for dependence analysis. debug(2) << "Computing function value bounds...\n"; FuncValueBounds func_val_bounds = compute_function_value_bounds(order, env); // Initialize the cost model. // Compute the expression costs for each function in the pipeline. debug(2) << "Initializing region costs...\n"; RegionCosts costs(env); if (debug::debug_level() >= 3) { costs.disp_func_costs(); } debug(2) << "Initializing dependence analysis...\n"; DependenceAnalysis dep_analysis(env, order, func_val_bounds); // Compute bounds of all functions in the pipeline given estimates on // outputs. Also report functions which bounds could not be inferred. debug(2) << "Computing pipeline bounds...\n"; map<string, Box> pipeline_bounds = get_pipeline_bounds(dep_analysis, outputs, &costs.input_estimates); // Determine all unbounded functions that are not extern Func or // used by some extern Funcs. debug(2) << "Determining all unbounded functions...\n"; set<string> unbounded = get_unbounded_functions(pipeline_bounds, env); if (!unbounded.empty()) { // If some functions are unbounded, we should inline those directly. // Also, we need to recompute 'env' and re-initialize 'costs' and // 'dep_analysis' debug(2) << "Inlining all unbounded functions...\n"; internal_assert(inline_unbounded(outputs, order, env, unbounded)); env.clear(); for (Function f : outputs) { map<string, Function> more_funcs = find_transitive_calls(f); env.insert(more_funcs.begin(), more_funcs.end()); } order = realization_order(outputs, env).first; debug(2) << "Re-computing function value bounds...\n"; func_val_bounds = compute_function_value_bounds(order, env); debug(2) << "Re-initializing region costs...\n"; RegionCosts costs(env); debug(2) << "Re-initializing dependence analysis...\n"; dep_analysis = DependenceAnalysis(env, order, func_val_bounds); debug(2) << "Re-computing pipeline bounds...\n"; pipeline_bounds = get_pipeline_bounds(dep_analysis, outputs, &costs.input_estimates); } debug(2) << "Initializing partitioner...\n"; Partitioner part(pipeline_bounds, arch_params, outputs, dep_analysis, costs); // Compute and display reuse /* TODO: Use the reuse estimates to reorder loops for (const auto &f : env) { FindAllCalls find; f.second.accept(&find); int num_stages = f.second.updates().size() + 1; for (int s = 0; s < num_stages; s++) { FStage curr_s(f.second, s); map<string, Expr> reuse = part.evaluate_reuse(curr_s, find.funcs_called); debug(0) << curr_s << '\n'; for (const auto &dir : reuse) { debug(0) << dir.first << " " << dir.second << ','; } debug(0) << '\n'; } }*/ // Display the current pipeline graph. // TODO: Output the graph in dot format. if (debug::debug_level() >= 3) { part.disp_pipeline_graph(); part.disp_pipeline_bounds(); } debug(2) << "Partitioner initializing groups...\n"; part.initialize_groups(); if (debug::debug_level() >= 3) { part.disp_pipeline_costs(); } // ///////////// // Remove the following two stages? debug(2) << "Partitioner computing inline group...\n"; part.group(Partitioner::Level::Inline); if (debug::debug_level() >= 3) { part.disp_grouping(); } debug(2) << "Partitioner computing fast-mem group...\n"; part.grouping_cache.clear(); part.group(Partitioner::Level::FastMem); if (debug::debug_level() >= 3) { part.disp_pipeline_costs(); part.disp_grouping(); part.disp_pipeline_graph(); } debug(2) << "Initializing AutoSchedule...\n"; AutoSchedule sched(env, top_order); debug(2) << "Generating CPU schedule...\n"; part.generate_cpu_schedule(target, sched); std::ostringstream oss; oss << "// Target: " << target.to_string() << "\n"; oss << "// MachineParams: " << arch_params.to_string() << "\n"; oss << "\n"; oss << sched; string sched_string = oss.str(); debug(3) << "\n\n*******************************\nSchedule:\n" << "*******************************\n" << sched_string << "\n\n"; // TODO: Unify both inlining and grouping for fast mem // TODO: GPU scheduling // TODO: Hierarchical tiling return sched_string; } } // namespace Internal MachineParams MachineParams::generic() { return MachineParams(16, 16 * 1024 * 1024, 40); } std::string MachineParams::to_string() const { internal_assert(parallelism.type().is_int() && last_level_cache_size.type().is_int() && balance.type().is_int()); std::ostringstream o; o << parallelism << "," << last_level_cache_size << "," << balance; return o.str(); } MachineParams::MachineParams(const std::string &s) { std::vector<std::string> v = Internal::split_string(s, ","); user_assert(v.size() == 3) << "Unable to parse MachineParams: " << s; parallelism = Internal::string_to_int(v[0]); last_level_cache_size = Internal::string_to_int(v[1]); balance = Internal::string_to_int(v[2]); } } // namespace Halide
147,876
43,093
// Copyright 2018 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 "chrome/chrome_cleaner/zip_archiver/target/sandbox_setup.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_executor.h" #include "chrome/chrome_cleaner/constants/chrome_cleaner_switches.h" #include "chrome/chrome_cleaner/ipc/mojo_sandbox_hooks.h" #include "chrome/chrome_cleaner/ipc/mojo_task_runner.h" #include "chrome/chrome_cleaner/os/early_exit.h" #include "chrome/chrome_cleaner/zip_archiver/target/zip_archiver_impl.h" namespace chrome_cleaner { namespace { class ZipArchiverSandboxTargetHooks : public MojoSandboxTargetHooks { public: explicit ZipArchiverSandboxTargetHooks(MojoTaskRunner* mojo_task_runner); ~ZipArchiverSandboxTargetHooks() override; // Sandbox hooks ResultCode TargetDroppedPrivileges( const base::CommandLine& command_line) override; private: void CreateZipArchiverImpl( mojo::PendingReceiver<mojom::ZipArchiver> receiver); MojoTaskRunner* mojo_task_runner_; base::SingleThreadTaskExecutor main_thread_task_executor_; std::unique_ptr<ZipArchiverImpl, base::OnTaskRunnerDeleter> zip_archiver_impl_; }; ZipArchiverSandboxTargetHooks::ZipArchiverSandboxTargetHooks( MojoTaskRunner* mojo_task_runner) : mojo_task_runner_(mojo_task_runner), zip_archiver_impl_(nullptr, base::OnTaskRunnerDeleter(mojo_task_runner_)) {} ZipArchiverSandboxTargetHooks::~ZipArchiverSandboxTargetHooks() = default; ResultCode ZipArchiverSandboxTargetHooks::TargetDroppedPrivileges( const base::CommandLine& command_line) { mojo::PendingReceiver<mojom::ZipArchiver> receiver( ExtractSandboxMessagePipe(command_line)); // This loop will run forever. Once the communication channel with the broker // process is broken, mojo error handler will abort this process. base::RunLoop run_loop; mojo_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ZipArchiverSandboxTargetHooks::CreateZipArchiverImpl, base::Unretained(this), std::move(receiver))); run_loop.Run(); return RESULT_CODE_SUCCESS; } void ZipArchiverSandboxTargetHooks::CreateZipArchiverImpl( mojo::PendingReceiver<mojom::ZipArchiver> receiver) { // Replace the null pointer by the actual |ZipArchiverImpl|. // Manually use |new| here because |make_unique| doesn't work with // custom deleter. zip_archiver_impl_.reset( new ZipArchiverImpl(std::move(receiver), base::BindOnce(&EarlyExit, 1))); } } // namespace ResultCode RunZipArchiverSandboxTarget( const base::CommandLine& command_line, sandbox::TargetServices* target_services) { DCHECK(target_services); scoped_refptr<MojoTaskRunner> mojo_task_runner = MojoTaskRunner::Create(); ZipArchiverSandboxTargetHooks target_hooks(mojo_task_runner.get()); return RunSandboxTarget(command_line, target_services, &target_hooks); } } // namespace chrome_cleaner
3,184
1,078
/** * Copyright 2018 - 2019 HITSIC * 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. */ /** * @brief 陀螺仪驱动,适用于mpu6050,mpu9250,icm20602 * @author xiao qq1761690868 * @doc drv_imu_invensense.md * @version v1.0 * @date 2020-10-16 */ #ifndef UTILITIES_DRV_IMU_INVENSENSE_DEF_HPP #define UTILITIES_DRV_IMU_INVENSENSE_DEF_HPP #include "hitsic_common.h" #if (defined(HITSIC_USE_DRV_IMU_INV) && (HITSIC_USE_DRV_IMU_INV > 0U)) namespace inv { enum class icm20602_RegMap :uint8_t { XG_OFFS_TC_H = 0x4, // READ/ WRITE XG_OFFS_TC_L = 0x5, // READ/ WRITE YG_OFFS_TC_H = 0x7, // READ/ WRITE YG_OFFS_TC_L = 0x8, // READ/ WRITE ZG_OFFS_TC_H = 0x0A, // READ/ WRITE ZG_OFFS_TC_L = 0x0B, // READ/ WRITE SELF_TEST_X_ACCEL = 0x0D, // READ/ WRITE SELF_TEST_Y_ACCEL = 0x0E, // READ/ WRITE SELF_TEST_Z_ACCEL = 0x0F, // READ/ WRITE XG_OFFS_USRH = 0x13, // READ/ WRITE XG_OFFS_USRL = 0x14, // READ/ WRITE YG_OFFS_USRH = 0x15, // READ/ WRITE YG_OFFS_USRL = 0x16, // READ/ WRITE ZG_OFFS_USRH = 0x17, // READ/ WRITE ZG_OFFS_USRL = 0x18, // READ/ WRITE SMPLRT_DIV = 0x19, // READ/ WRITE CONFIG = 0x1A, // READ/ WRITE default value:0x80 GYRO_CONFIG = 0x1B, // READ/ WRITE ACCEL_CONFIG = 0x1C, // READ/ WRITE ACCEL_CONFIG2 = 0x1D, // READ/ WRITE LP_MODE_CFG = 0x1E, // READ/ WRITE ACCEL_WOM_X_THR = 0x20, // READ/ WRITE ACCEL_WOM_Y_THR = 0x21, // READ/ WRITE ACCEL_WOM_Z_THR = 0x22, // READ/ WRITE FIFO_EN = 0x23, // READ/ WRITE FSYNC_INT = 0x36, // READ to CLEAR INT_PIN_CFG = 0x37, // READ/ WRITE INT_ENABLE = 0x38, // READ/ WRITE FIFO_WM_INT_STATUS = 0x39, // READ to CLEAR INT_STATUS = 0x3A, // READ to CLEAR ACCEL_XOUT_H = 0x3B, // READ ACCEL_XOUT_L = 0x3C, // READ ACCEL_YOUT_H = 0x3D, // READ ACCEL_YOUT_L = 0x3E, // READ ACCEL_ZOUT_H = 0x3F, // READ ACCEL_ZOUT_L = 0x40, // READ TEMP_OUT_H = 0x41, // READ TEMP_OUT_L = 0x42, // READ GYRO_XOUT_H = 0x43, // READ GYRO_XOUT_L = 0x44, // READ GYRO_YOUT_H = 0x45, // READ GYRO_YOUT_L = 0x46, // READ GYRO_ZOUT_H = 0x47, // READ GYRO_ZOUT_L = 0x48, // READ SELF_TEST_X_GYRO = 0x50, // READ/ WRITE SELF_TEST_Y_GYRO = 0x51, // READ/ WRITE SELF_TEST_Z_GYRO = 0x52, // READ/ WRITE FIFO_WM_TH1 = 0x60, // READ/ WRITE FIFO_WM_TH2 = 0x61, // READ/ WRITE SIGNAL_PATH_RESET = 0x68, // READ/ WRITE ACCEL_INTEL_CTRL = 0x69, // READ/ WRITE USER_CTRL = 0x6A, // READ/ WRITE PWR_MGMT_1 = 0x6B, // READ/ WRITE default value:0x41 PWR_MGMT_2 = 0x6C, // READ/ WRITE I2C_IF = 0x70, // READ/ WRITE FIFO_COUNTH = 0x72, // READ FIFO_COUNTL = 0x73, // READ FIFO_R_W = 0x74, // READ/ WRITE WHO_AM_I = 0x75, // READ default value:0x12 XA_OFFSET_H = 0x77, // READ/ WRITE XA_OFFSET_L = 0x78, // READ/ WRITE YA_OFFSET_H = 0x7A, // READ/ WRITE YA_OFFSET_L = 0x7B, // READ/ WRITE ZA_OFFSET_H = 0x7D, // READ/ WRITE ZA_OFFSET_L = 0x7E, // READ/ WRITE }; enum class mpu6050_RegMap :uint8_t { SELF_TEST_X = 0x0D, //R/W SELF_TEST_Y = 0x0E, //R/W SELF_TEST_Z = 0x0F, //R/W SELF_TEST_A = 0x10, //R/W SMPLRT_DIV = 0x19, //R/W CONFIG = 0x1A, //R/W GYRO_CONFIG = 0x1B, //R/W ACCEL_CONFIG = 0x1C, //R/W FIFO_EN = 0x23, //R/W I2C_MST_CTRL = 0x24, //R/W I2C_SLV0_ADDR = 0x25, //R/W I2C_SLV0_REG = 0x26, //R/W I2C_SLV0_CTRL = 0x27, //R/W I2C_SLV1_ADDR = 0x28, //R/W I2C_SLV1_REG = 0x29, //R/W I2C_SLV1_CTRL = 0x2A, //R/W I2C_SLV2_ADDR = 0x2B, //R/W I2C_SLV2_REG = 0x2C, //R/W I2C_SLV2_CTRL = 0x2D, //R/W I2C_SLV3_ADDR = 0x2E, //R/W I2C_SLV3_REG = 0x2F, //R/W I2C_SLV3_CTRL = 0x30, //R/W I2C_SLV4_ADDR = 0x31, //R/W I2C_SLV4_REG = 0x32, //R/W I2C_SLV4_DO = 0x33, //R/W I2C_SLV4_CTRL = 0x34, //R/W I2C_SLV4_DI = 0x35, //R I2C_MST_STATUS = 0x36, //R INT_PIN_CFG = 0x37, //R/W INT_ENABLE = 0x38, //R/W INT_STATUS = 0x3A, //R ACCEL_XOUT_H = 0x3B, //R ACCEL_XOUT_L = 0x3C, //R ACCEL_YOUT_H = 0x3D, //R ACCEL_YOUT_L = 0x3E, //R ACCEL_ZOUT_H = 0x3F, //R ACCEL_ZOUT_L = 0x40, //R TEMP_OUT_H = 0x41, //R TEMP_OUT_L = 0x42, //R GYRO_XOUT_H = 0x43, //R GYRO_XOUT_L = 0x44, //R GYRO_YOUT_H = 0x45, //R GYRO_YOUT_L = 0x46, //R GYRO_ZOUT_H = 0x47, //R GYRO_ZOUT_L = 0x48, //R EXT_SENS_DATA_00 = 0x49, //R EXT_SENS_DATA_01 = 0x4A, //R EXT_SENS_DATA_02 = 0x4B, //R EXT_SENS_DATA_03 = 0x4C, //R EXT_SENS_DATA_04 = 0x4D, //R EXT_SENS_DATA_05 = 0x4E, //R EXT_SENS_DATA_06 = 0x4F, //R EXT_SENS_DATA_07 = 0x50, //R EXT_SENS_DATA_08 = 0x51, //R EXT_SENS_DATA_09 = 0x52, //R EXT_SENS_DATA_10 = 0x53, //R EXT_SENS_DATA_11 = 0x54, //R EXT_SENS_DATA_12 = 0x55, //R EXT_SENS_DATA_13 = 0x56, //R EXT_SENS_DATA_14 = 0x57, //R EXT_SENS_DATA_15 = 0x58, //R EXT_SENS_DATA_16 = 0x59, //R EXT_SENS_DATA_17 = 0x5A, //R EXT_SENS_DATA_18 = 0x5B, //R EXT_SENS_DATA_19 = 0x5C, //R EXT_SENS_DATA_20 = 0x5D, //R EXT_SENS_DATA_21 = 0x5E, //R EXT_SENS_DATA_22 = 0x5F, //R EXT_SENS_DATA_23 = 0x60, //R I2C_SLV0_DO = 0x63, //R/W I2C_SLV1_DO = 0x64, //R/W I2C_SLV2_DO = 0x65, //R/W I2C_SLV3_DO = 0x66, //R/W I2C_MST_DELAY_CTRL = 0x67, //R/W SIGNAL_PATH_RESET = 0x68, //R/W USER_CTRL = 0x6A, //R/W PWR_MGMT_1 = 0x6B, //R/W PWR_MGMT_2 = 0x6C, //R/W FIFO_COUNTH = 0x72, //R/W FIFO_COUNTL = 0x73, //R/W FIFO_R_W = 0x74, //R/W WHO_AM_I = 0x75, //R }; enum class mpu9250_RegMap :uint8_t { SELF_TEST_X_GYRO = 0x0,//R/W SELF_TEST_Y_GYRO = 0x1,//R/W SELF_TEST_Z_GYRO = 0x2,//R/W SELF_TEST_X_ACCEL = 0x0D,//R/W SELF_TEST_Y_ACCEL = 0x0E,//R/W SELF_TEST_Z_ACCEL = 0x0F,//R/W XG_OFFSET_H = 0x13,//R/W XG_OFFSET_L = 0x14,//R/W YG_OFFSET_H = 0x15,//R/W YG_OFFSET_L = 0x16,//R/W ZG_OFFSET_H = 0x17,//R/W ZG_OFFSET_L = 0x18,//R/W SMPLRT_DIV = 0x19,//R/W CONFIG = 0x1A,//R/W GYRO_CONFIG = 0x1B,//R/W ACCEL_CONFIG = 0x1C,//R/W ACCEL_CONFIG2 = 0x1D,//R/W LP_ACCEL_ODR = 0x1E,//R/W WOM_THR = 0x1F,//R/W FIFO_EN = 0x23,//R/W I2C_MST_CTRL = 0x24,//R/W I2C_SLV0_ADDR = 0x25,//R/W I2C_SLV0_REG = 0x26,//R/W I2C_SLV0_CTRL = 0x27,//R/W I2C_SLV1_ADDR = 0x28,//R/W I2C_SLV1_REG = 0x29,//R/W I2C_SLV1_CTRL = 0x2A,//R/W I2C_SLV2_ADDR = 0x2B,//R/W I2C_SLV2_REG = 0x2C,//R/W I2C_SLV2_CTRL = 0x2D,//R/W I2C_SLV3_ADDR = 0x2E,//R/W I2C_SLV3_REG = 0x2F,//R/W I2C_SLV3_CTRL = 0x30,//R/W I2C_SLV4_ADDR = 0x31,//R/W I2C_SLV4_REG = 0x32,//R/W I2C_SLV4_DO = 0x33,//R/W I2C_SLV4_CTRL = 0x34,//R/W I2C_SLV4_DI = 0x35,//R I2C_MST_STATUS = 0x36,//R INT_PIN_CFG = 0x37,//R/W INT_ENABLE = 0x38,//R/W INT_STATUS = 0x3A,//R ACCEL_XOUT_H = 0x3B,//R ACCEL_XOUT_L = 0x3C,//R ACCEL_YOUT_H = 0x3D,//R ACCEL_YOUT_L = 0x3E,//R ACCEL_ZOUT_H = 0x3F,//R ACCEL_ZOUT_L = 0x40,//R TEMP_OUT_H = 0x41,//R TEMP_OUT_L = 0x42,//R GYRO_XOUT_H = 0x43,//R GYRO_XOUT_L = 0x44,//R GYRO_YOUT_H = 0x45,//R GYRO_YOUT_L = 0x46,//R GYRO_ZOUT_H = 0x47,//R GYRO_ZOUT_L = 0x48,//R EXT_SENS_DATA_00 = 0x49,//R EXT_SENS_DATA_01 = 0x4A,//R EXT_SENS_DATA_02 = 0x4B,//R EXT_SENS_DATA_03 = 0x4C,//R EXT_SENS_DATA_04 = 0x4D,//R EXT_SENS_DATA_05 = 0x4E,//R EXT_SENS_DATA_06 = 0x4F,//R EXT_SENS_DATA_07 = 0x50,//R EXT_SENS_DATA_08 = 0x51,//R EXT_SENS_DATA_09 = 0x52,//R EXT_SENS_DATA_10 = 0x53,//R EXT_SENS_DATA_11 = 0x54,//R EXT_SENS_DATA_12 = 0x55,//R EXT_SENS_DATA_13 = 0x56,//R EXT_SENS_DATA_14 = 0x57,//R EXT_SENS_DATA_15 = 0x58,//R EXT_SENS_DATA_16 = 0x59,//R EXT_SENS_DATA_17 = 0x5A,//R EXT_SENS_DATA_18 = 0x5B,//R EXT_SENS_DATA_19 = 0x5C,//R EXT_SENS_DATA_20 = 0x5D,//R EXT_SENS_DATA_21 = 0x5E,//R EXT_SENS_DATA_22 = 0x5F,//R EXT_SENS_DATA_23 = 0x60,//R I2C_SLV0_DO = 0x63,//R/W I2C_SLV1_DO = 0x64,//R/W I2C_SLV2_DO = 0x65,//R/W I2C_SLV3_DO = 0x66,//R/W I2C_MST_DELAY_CTRL = 0x67,//R/W SIGNAL_PATH_RESET = 0x68,//R/W MOT_DETECT_CTRL = 0x69,//R/W USER_CTRL = 0x6A,//R/W PWR_MGMT_1 = 0x6B,//R/W PWR_MGMT_2 = 0x6C,//R/W FIFO_COUNTH = 0x72,//R/W FIFO_COUNTL = 0x73,//R/W FIFO_R_W = 0x74,//R/W WHO_AM_I = 0x75,//R XA_OFFSET_H = 0x77,//R/W XA_OFFSET_L = 0x78,//R/W YA_OFFSET_H = 0x7A,//R/W YA_OFFSET_L = 0x7B,//R/W ZA_OFFSET_H = 0x7D,//R/W ZA_OFFSET_L = 0x7E,//R/W }; enum class ak8963_RegMap : uint8_t { //Magnetometer register maps WIA = 0x00, INFO = 0x01, ST1 = 0x02, XOUT_L = 0x03, XOUT_H = 0x04, YOUT_L = 0x05, YOUT_H = 0x06, ZOUT_L = 0x07, ZOUT_H = 0x08, ST2 = 0x09, CNTL = 0x0A, CNTL2 = 0x0B, RSV = 0x0B, //DO NOT ACCESS <MPU9250_AK8963_CNTL2> ASTC = 0x0C, TS1 = 0x0D, //DO NOT ACCESS TS2 = 0x0E, //DO NOT ACCESS I2CDIS = 0x0F, ASAX = 0x10, ASAY = 0x11, ASAZ = 0x12, }; } #endif // ! HITSIC_USE_DRV_IMU_INV #endif //UTILITIES_DRV_IMU_INVENSENSE_DEF_HPP
9,840
6,870
/** Copyright (c) 2014-2015, Sandia Corporation All rights reserved. This file is part of fast-matmul and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause. */ #ifndef _COMMON_HPP_ #define _COMMON_HPP_ #define _DFS_PAR_ 1 #define _BFS_PAR_ 2 #define _HYBRID_PAR_ 3 #include "MemoryManager.hpp" #include "linalg.hpp" #ifdef _PARALLEL_ # include "omp.h" #endif #include "par_util.hpp" #include "options.hpp" #include "timing.hpp" template <typename T> std::ostream& operator<<(std::ostream& os, std::vector<T>& vec) { for (int i = 0; i < vec.size(); ++i) { os << vec[i] << " "; } os << std::endl; } #endif // _COMMON_HPP_
751
319
#include <ThirdParty/imgui/imgui.h> #include "Gui/BibleBookWindow.h" namespace GUI { /// Updates and renders a single frame of the window, if it's open. /// @return The verse range for any selected chapter; null if no chapter was selected. std::optional<BIBLE_DATA::BibleVerseRange> BibleBookWindow::UpdateAndRender() { // DON'T RENDER ANYTHING IF THE WINDOW ISN'T OPEN. if (!Open) { return std::nullopt; } // RENDER THE WINDOW AND GET ANY SELECTED CHAPTER. std::optional<BIBLE_DATA::BibleVerseRange> selected_verse_range; // Window positioning/sizing is only done upon the first use to allow preserving a user's manual changes. // The window is positioned to basically be in the top-left corner of the window after the main menu bar. ImVec2 current_drawing_cursor_position = ImGui::GetCursorPos(); ImGui::SetNextWindowPos(current_drawing_cursor_position, ImGuiCond_FirstUseEver); // The width is set to be wide enough for all book titles to be displayed. constexpr float MAX_BOOK_TITLE_WIDTH_IN_PIXELS = 200.0f; ImGuiIO& io = ImGui::GetIO(); float available_vertical_screen_space_in_pixels = io.DisplaySize.y - current_drawing_cursor_position.y; ImVec2 window_size_in_pixels(MAX_BOOK_TITLE_WIDTH_IN_PIXELS, available_vertical_screen_space_in_pixels); ImGui::SetNextWindowSize(window_size_in_pixels, ImGuiCond_FirstUseEver); if (ImGui::Begin("Books & Chapters", &Open)) { // RENDER EACH BOOK. for (const auto& id_and_book : BIBLE_DATA::Bible::BOOKS_BY_ID) { // RENDER THE CURRENT BOOK WITH A COLLAPSING TREE NODE. std::string book_name = BIBLE_DATA::BibleBook::FullName(id_and_book.first); if (ImGui::TreeNodeEx(book_name.c_str(), ImGuiTreeNodeFlags_CollapsingHeader)) { // RENDER A SELECTABLE ITEM FOR EACH CHAPTER. const BIBLE_DATA::BibleBook& book = id_and_book.second; std::size_t chapter_count = book.VerseCountsByChapter.size(); for (std::size_t chapter_index = 0; chapter_index < chapter_count; ++chapter_index) { // RENDER A SELECTABLE FOR THE CHAPTER. unsigned int chapter_number = static_cast<unsigned int>(chapter_index + 1); std::string chapter_text = "Chapter " + std::to_string(chapter_number); std::string chapter_id = "##" + book_name + chapter_text; std::string chapter_text_and_id = chapter_text + chapter_id; if (ImGui::Selectable(chapter_text_and_id.c_str())) { // TRACK THE SELECTED CHAPTER. unsigned int chapter_verse_count = book.VerseCountsByChapter[chapter_index]; selected_verse_range = BIBLE_DATA::BibleVerseRange { .StartingVerse = BIBLE_DATA::BibleVerseId { .Book = id_and_book.first, .ChapterNumber = chapter_number, // All chapters begin at verse 1. .VerseNumber = 1 }, .EndingVerse = BIBLE_DATA::BibleVerseId { .Book = id_and_book.first, .ChapterNumber = chapter_number, .VerseNumber = chapter_verse_count }, }; } } } } } ImGui::End(); // RETURN ANY SELECTED CHAPTER. return selected_verse_range; } }
4,068
1,127
/* * Essex Engine * * Copyright (C) 2018 Nathan Mentley - All Rights Reserved * You may use, distribute and modify this code under the * terms of the BSD license. * * You should have received a copy of the BSD license with * this file. If not, please visit: https://github.com/nathanmentley/EssexEngine */ #include <EssexEngineConfigDaemon/ConfigDaemon.h> using EssexEngine::Context; using EssexEngine::WeakPointer; using EssexEngine::Daemons::Config::ConfigDaemon; extern "C" { void* daemon_init(WeakPointer<Context> context) { ConfigDaemon* daemon = new ConfigDaemon(context); context->RegisterDaemon<ConfigDaemon>( daemon ); return daemon; } }
716
227
/// @file lahqr_schur22.hpp /// @author Thijs Steel, KU Leuven, Belgium /// Adapted from @see https://github.com/Reference-LAPACK/lapack/tree/master/SRC/dlanv2.f // // Copyright (c) 2013-2022, University of Colorado Denver. All rights reserved. // // This file is part of <T>LAPACK. // <T>LAPACK is free software: you can redistribute it and/or modify it under // the terms of the BSD 3-Clause license. See the accompanying LICENSE file. #ifndef __LAHQR_SCHUR22_HH__ #define __LAHQR_SCHUR22_HH__ #include <complex> #include <cmath> #include "lapack/utils.hpp" #include "lapack/types.hpp" namespace lapack { /** Computes the Schur factorization of a 2x2 matrix A * * A = [a b] = [cs -sn] [aa bb] [ cs sn] * [c d] [sn cs] [cc dd] [-sn cs] * * This routine is designed for real matrices. * If the template T is complex, it returns with error * and does nothing. (This is so we don't need c++17's static if * but still keep the code somewhat clean). * * @return 0 if the template T is real * @return -1 if the template T is complex * * @param[in,out] a scalar, A(0,0). * @param[in,out] b scalar, A(0,1). * @param[in,out] c scalar, A(1,0). * @param[in,out] d scalar, A(1,1). * On entry, the elements of the matrix A. * On exit, the elements of the Schur factor (aa, bb, cc and dd). * @param[out] s1 complex scalar. * First eigenvalue of the matrix. * @param[out] s2 complex scalar. * Second eigenvalue of the matrix. * @param[out] cs scalar. * Cosine factor of the rotation * @param[out] sn scalar. * Sine factor of the rotation * * @ingroup geev */ template < typename T, enable_if_t<!is_complex<T>::value, bool> = true> int lahqr_schur22(T &a, T &b, T &c, T &d, std::complex<T> &s1, std::complex<T> &s2, T &cs, T &sn) { using blas::abs; using std::log; using std::max; using std::min; using std::pow; using std::copysign; const T zero(0); const T half(0.5); const T one(1); const T two(2); const T multpl(4); const T eps = blas::uroundoff<T>(); const T safmin = blas::safe_min<T>(); const T safmn2 = pow(two, (int)(log(safmin / eps) / log(two)) / two); const T safmx2 = one / safmn2; if (c == zero) { // c is zero, the matrix is already in Schur form. cs = one; sn = zero; } else if (b == zero) { // b is zero, swapping rows and columns results in Schur form. cs = zero; sn = one; auto temp = d; d = a; a = temp; b = -c; c = zero; } else if ((a - d) == zero and copysign(one,b) != copysign(one,c)) { cs = one; sn = zero; } else { auto temp = a - d; auto p = half * temp; auto bcmax = max(abs(b), abs(c)); auto bcmin = min(abs(b), abs(c)) * copysign(one,b) * copysign(one,c); auto scale = max(abs(p), bcmax); auto z = (p / scale) * p + (bcmax / scale) * bcmin; // if z is positive, we should have real eigenvalues // however, is z is very small, but positive, we postpone the decision if (z >= multpl * eps) { // Real eigenvalues. // Compute a and d. z = p + copysign(one,p) * sqrt(scale) * sqrt(z); a = d + z; d = d - (bcmax / z) * bcmin; // Compute b and the rotation matrix auto tau = lapy2(c, z); cs = z / tau; sn = c / tau; b = b - c; c = zero; } else { // Complex eigenvalues, or real (almost) equal eigenvalues. // Make diagonal elements equal. auto sigma = b + c; for (int count = 0; count < 20; ++count) { scale = max(abs(temp), abs(sigma)); if (scale >= safmx2) { sigma = sigma * safmn2; temp = temp * safmn2; continue; } if (scale <= safmn2) { sigma = sigma * safmx2; temp = temp * safmx2; continue; } break; } p = half * temp; auto tau = lapy2(sigma, temp); cs = sqrt(half * (one + abs(sigma) / tau)); sn = -(p / (tau * cs)) * copysign(one,sigma); // // Compute [aa bb] = [a b][cs -sn] // [cc dd] = [c d][sn cs] // auto aa = a * cs + b * sn; auto bb = -a * sn + b * cs; auto cc = c * cs + d * sn; auto dd = -c * sn + d * cs; // // Compute [a b] = [ cs sn][aa bb] // [c d] = [-sn cs][cc dd] // a = aa * cs + cc * sn; b = bb * cs + dd * sn; c = -aa * sn + cc * cs; d = -bb * sn + dd * cs; temp = half * (a + d); a = temp; d = temp; if (c != zero) { if (b != zero) { if (copysign(one,b) == copysign(one,c)) { // Real eigenvalues: reduce to upper triangular form auto sab = sqrt(abs(b)); auto sac = sqrt(abs(c)); p = abs(c) * copysign(one,sab * sac); tau = one / sqrt(abs(b + c)); a = temp + p; d = temp - p; b = b - c; c = zero; auto cs1 = sab * tau; auto sn1 = sac * tau; temp = cs * cs1 - sn * sn1; sn = cs * sn1 + sn * cs1; cs = temp; } } } } } // Store eigenvalues in s1 and s2 if (c != zero) { auto temp = sqrt(abs(b)) * sqrt(abs(c)); s1 = std::complex<T>(a, temp); s2 = std::complex<T>(d, -temp); } else { s1 = a; s2 = d; } return 0; } template < typename T, enable_if_t<is_complex<T>::value, bool> = true> int lahqr_schur22(T &a, T &b, T &c, T &d, T &s1, T &s2, real_type<T> &cs, T &sn) { return -1; } } // lapack #endif // __LAHQR_SCHUR22_HH__
7,239
2,275
/** For conditions of distribution and use, see copyright notice in LICENSE @file AssetsWindow.cpp @brief The main UI for managing asset storages and assets. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "AssetsWindow.h" #include "AssetTreeWidget.h" #include "TreeWidgetUtils.h" #include "SceneTreeWidgetItems.h" #include "Framework.h" #include "AssetAPI.h" #include "IAsset.h" #include "IAssetBundle.h" #include "IAssetStorage.h" #include "UiAPI.h" #include "Profiler.h" #include "MemoryLeakCheck.h" namespace { bool HasSameRefAsPredecessors(QTreeWidgetItem *item) { QTreeWidgetItem *parent = 0, *child = item; while((parent = child->parent()) != 0) { if (parent->text(0).compare(child->text(0), Qt::CaseInsensitive) == 0) return true; child = parent; } return false; } } AssetsWindow::AssetsWindow(Framework *fw, QWidget *parent) : QWidget(parent), framework(fw), noStorageItem(0) { Initialize(); PopulateTreeWidget(); } AssetsWindow::AssetsWindow(const QString &assetType_, Framework *fw, QWidget *parent) : QWidget(parent), framework(fw), noStorageItem(0), assetType(assetType_) { Initialize(); PopulateTreeWidget(); // Asset picking layout QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Fixed); QPushButton *cancelButton = new QPushButton(tr("Cancel"), this); QPushButton *pickButton = new QPushButton(tr("Pick"), this); QHBoxLayout *hlayout2= new QHBoxLayout; hlayout2->insertSpacerItem(-1, spacer); hlayout2->addWidget(pickButton); hlayout2->addWidget(cancelButton); static_cast<QVBoxLayout *>(layout())->addLayout(hlayout2); connect(treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), SLOT(ChangeSelectedAsset(QTreeWidgetItem *))); connect(pickButton, SIGNAL(clicked()), SLOT(PickAssetAndClose())); connect(cancelButton, SIGNAL(clicked()), SLOT(Cancel())); } AssetsWindow::~AssetsWindow() { // Disable ResizeToContents, Qt goes sometimes into eternal loop after // ~AssetsWindow() if we have lots (hundreds or thousands) of items. treeWidget->blockSignals(true); treeWidget->header()->setResizeMode(QHeaderView::Interactive); QTreeWidgetItemIterator it(treeWidget); while(*it) { QTreeWidgetItem *item = *it; SAFE_DELETE(item); ++it; } } void AssetsWindow::PopulateTreeWidget() { PROFILE(AssetsWindow_PopulateTreeWidget) treeWidget->clear(); alreadyAdded.clear(); // Create "No provider" for assets without storage. SAFE_DELETE(noStorageItem); noStorageItem = new QTreeWidgetItem(); noStorageItem->setText(0, tr("No Storage")); // Iterate storages CreateStorageItem(framework->Asset()->DefaultAssetStorage()); foreach(const AssetStoragePtr &storage, framework->Asset()->AssetStorages()) CreateStorageItem(storage); // Iterate asset bundles std::pair<QString, AssetBundlePtr> bundlePair; foreach(bundlePair, framework->Asset()->AssetBundles()) AddBundle(bundlePair.second); // Iterate assets std::pair<QString, AssetPtr> pair; foreach(pair, framework->Asset()->Assets()) AddAsset(pair.second); // Add the no provider last and hide if no children. treeWidget->addTopLevelItem(noStorageItem); noStorageItem->setHidden(noStorageItem->childCount() == 0); } void AssetsWindow::AddAsset(const AssetPtr &asset) { PROFILE(AssetsWindow_AddAsset) if (alreadyAdded.find(asset) != alreadyAdded.end()) return; if (!assetType.isEmpty() && assetType != asset->Type()) return; AssetItem *item = CreateAssetItem(asset); if (!item) return; AddChildren(asset, item); connect(asset.get(), SIGNAL(Loaded(AssetPtr)), SLOT(UpdateAssetItem(AssetPtr)), Qt::UniqueConnection); connect(asset.get(), SIGNAL(Unloaded(IAsset *)), SLOT(UpdateAssetItem(IAsset *)), Qt::UniqueConnection); connect(asset.get(), SIGNAL(PropertyStatusChanged(IAsset *)), SLOT(UpdateAssetItem(IAsset *)), Qt::UniqueConnection); noStorageItem->setHidden(noStorageItem->childCount() == 0); // If we have an ongoing search, make sure that the new item is compared too. QString searchFilter = searchField->text().trimmed(); if (!searchFilter.isEmpty()) TreeWidgetSearch(treeWidget, 0, searchFilter); } void AssetsWindow::AddBundle(const AssetBundlePtr &bundle) { CreateBundleItem(bundle); } void AssetsWindow::RemoveAsset(AssetPtr asset) { QTreeWidgetItemIterator it(treeWidget); while(*it) { AssetItem *item = dynamic_cast<AssetItem *>(*it); if (item && item->Asset() && item->Asset() == asset) { QTreeWidgetItem *parent = item->parent(); parent->removeChild(item); SAFE_DELETE(item); alreadyAdded.erase(asset); addedItemNames.erase(asset->Name()); } ++it; } } void AssetsWindow::Search(const QString &filter) { TreeWidgetSearch(treeWidget, 0, filter); } void AssetsWindow::UpdateAssetItem(IAsset *asset) { QTreeWidgetItemIterator it(treeWidget); while(*it) { AssetItem *item = dynamic_cast<AssetItem *>(*it); if (item && item->Asset().get() == asset) { item->SetText(asset); break; } ++it; } } void AssetsWindow::Initialize() { setWindowTitle(tr("Assets")); // Append asset type if we're viewing only assets of specific type. if (!assetType.isEmpty()) setWindowTitle(windowTitle() + ": " + assetType); resize(450, 450); QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(5, 5, 5, 5); setLayout(layout); // Create child widgets treeWidget = new AssetTreeWidget(framework, this); treeWidget->setHeaderHidden(true); searchField = new QLineEdit(this); searchField->setPlaceholderText(tr("Search...")); expandAndCollapseButton = new QPushButton(tr("Expand All"), this); QHBoxLayout *hlayout= new QHBoxLayout; hlayout->addWidget(searchField); hlayout->addWidget(expandAndCollapseButton); layout->addLayout(hlayout); layout->addWidget(treeWidget); connect(searchField, SIGNAL(textEdited(const QString &)), SLOT(Search(const QString &))); connect(expandAndCollapseButton, SIGNAL(clicked()), SLOT(ExpandOrCollapseAll())); connect(framework->Asset(), SIGNAL(AssetCreated(AssetPtr)), SLOT(AddAsset(AssetPtr))); connect(framework->Asset(), SIGNAL(AssetAboutToBeRemoved(AssetPtr)), SLOT(RemoveAsset(AssetPtr))); connect(treeWidget, SIGNAL(itemCollapsed(QTreeWidgetItem*)), SLOT(CheckTreeExpandStatus(QTreeWidgetItem*))); connect(treeWidget, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(CheckTreeExpandStatus(QTreeWidgetItem*))); connect(treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), SLOT(OnItemDoubleClicked(QTreeWidgetItem*, int))); } void AssetsWindow::closeEvent(QCloseEvent *e) { emit AboutToClose(this); QWidget::closeEvent(e); } void AssetsWindow::AddChildren(const AssetPtr &asset, QTreeWidgetItem *parent) { PROFILE(AssetsWindow_AddChildren) foreach(const AssetReference &ref, asset->FindReferences()) { AssetPtr asset = framework->Asset()->GetAsset(ref.ref); if (asset && alreadyAdded.find(asset) == alreadyAdded.end()) { AssetItem *item = new AssetItem(asset, parent); parent->addChild(item); alreadyAdded.insert(asset); // Check for recursive dependencies. if (HasSameRefAsPredecessors(item)) item->setText(0, tr("Recursive dependency to ") + asset->Name()); else AddChildren(asset, item); } } } void AssetsWindow::ExpandOrCollapseAll() { treeWidget->blockSignals(true); bool treeExpanded = TreeWidgetExpandOrCollapseAll(treeWidget); treeWidget->blockSignals(false); expandAndCollapseButton->setText(treeExpanded ? tr("Collapse All") : tr("Expand All")); } void AssetsWindow::CheckTreeExpandStatus(QTreeWidgetItem * /*item*/) { expandAndCollapseButton->setText(TreeWidgetIsAnyExpanded(treeWidget) ? tr("Collapse All") : tr("Expand All")); } void AssetsWindow::OnItemDoubleClicked(QTreeWidgetItem *item, int /*column*/) { AssetItem* assItem = dynamic_cast<AssetItem*>(item); if (!assItem || !assItem->Asset()) return; QMenu dummyMenu; QList<QObject*> targets; targets.push_back(assItem->Asset().get()); framework->Ui()->EmitContextMenuAboutToOpen(&dummyMenu, targets); foreach(QAction *action, dummyMenu.actions()) if (action->text() == "Open") { action->activate(QAction::ActionEvent()); break; } } void AssetsWindow::ChangeSelectedAsset(QTreeWidgetItem *current) { // Note: clause if <=1 cause for some reason when activating item for the first time // treeWidget->selectedItems().size() returns 0, even though we should have 1. if (treeWidget->selectedItems().size() <= 1 && current) { AssetItem *item = dynamic_cast<AssetItem *>(current); if (item && item->Asset()) emit SelectedAssetChanged(item->Asset()); } } void AssetsWindow::PickAssetAndClose() { if (treeWidget->selectedItems().size() == 1) { AssetItem *item = dynamic_cast<AssetItem *>(treeWidget->currentItem()); if (item && item->Asset()) emit AssetPicked(item->Asset()); } close(); } void AssetsWindow::Cancel() { emit PickCanceled(); close(); } AssetStorageItem *AssetsWindow::CreateStorageItem(const AssetStoragePtr &storage) { for (int i=0; i<treeWidget->topLevelItemCount(); ++i) { AssetStorageItem *existing = dynamic_cast<AssetStorageItem*>(treeWidget->topLevelItem(i)); if (existing && storage == existing->Storage()) return 0; } AssetStorageItem *item = new AssetStorageItem(storage); treeWidget->addTopLevelItem(item); if (storage == framework->Asset()->DefaultAssetStorage()) { QFont font = item->font(0); font.setBold(true); item->setFont(0, font); } return item; } AssetBundleItem *AssetsWindow::CreateBundleItem(const AssetBundlePtr &bundle) { if (addedItemNames.find(bundle->Name()) != addedItemNames.end()) return 0; // for (int i=0; i<treeWidget->topLevelItemCount(); ++i) // if (FindBundleItemRecursive(treeWidget->topLevelItem(i), bundle)) // return 0; addedItemNames.insert(bundle->Name()); QTreeWidgetItem *p = FindParentItem(bundle); AssetBundleItem *item = new AssetBundleItem(bundle, p); p->addChild(item); return item; } AssetItem *AssetsWindow::CreateAssetItem(const AssetPtr &asset) { if (addedItemNames.find(asset->Name()) != addedItemNames.end()) return 0; // for (int i=0; i<treeWidget->topLevelItemCount(); ++i) // if (FindAssetItemRecursive(treeWidget->topLevelItem(i), asset)) // return 0; addedItemNames.insert(asset->Name()); QTreeWidgetItem *p = FindParentItem(asset); AssetItem *item = new AssetItem(asset, p); p->addChild(item); return item; } AssetBundleItem *AssetsWindow::FindBundleItemRecursive(QTreeWidgetItem *parent, const AssetBundlePtr &bundle) { PROFILE(AssetsWindow_FindBundleItemRecursive_bundle) if (!parent || parent->childCount() == 0) return 0; AssetBundleItem *result = 0; for (int i=0; i<parent->childCount(); ++i) { AssetBundleItem *existing = dynamic_cast<AssetBundleItem*>(parent->child(i)); if (existing && existing->AssetBundle() == bundle) result = existing; else result = FindBundleItemRecursive(parent->child(i), bundle); if (result) break; } return result; } AssetBundleItem *AssetsWindow::FindBundleItemRecursive(QTreeWidgetItem *parent, const QString &subAssetRef) { PROFILE(AssetsWindow_FindBundleItemRecursive_subAssetRef) if (!parent || parent->childCount() == 0) return 0; AssetBundleItem *result = 0; for (int i=0; i<parent->childCount(); ++i) { AssetBundleItem *existing = dynamic_cast<AssetBundleItem*>(parent->child(i)); if (existing && existing->Contains(subAssetRef)) result = existing; else result = FindBundleItemRecursive(parent->child(i), subAssetRef); if (result) break; } return result; } AssetItem *AssetsWindow::FindAssetItemRecursive(QTreeWidgetItem *parent, const AssetPtr &asset) { PROFILE(AssetsWindow_FindAssetItemRecursive) if (!parent || parent->childCount() == 0) return 0; AssetItem *result = 0; for (int i=0; i<parent->childCount(); ++i) { AssetItem *existing = dynamic_cast<AssetItem*>(parent->child(i)); if (existing && existing->Asset() == asset) result = existing; else result = FindAssetItemRecursive(parent->child(i), asset); if (result) break; } return result; } template <typename T> QTreeWidgetItem *AssetsWindow::FindParentItem(const T &item) { PROFILE(AssetsWindow_FindParentItem) QString subAssetPart; AssetAPI::ParseAssetRef(item->Name(), 0, 0, 0, 0, 0, 0, 0, &subAssetPart); for (int i=0; i<treeWidget->topLevelItemCount(); ++i) { AssetStorageItem *existingStorage = dynamic_cast<AssetStorageItem*>(treeWidget->topLevelItem(i)); if (existingStorage && existingStorage->Storage() == item->AssetStorage()) { // If this is a sub asset to a bundle, find the bundle item from this storage. if (!subAssetPart.isEmpty()) { AssetBundleItem *existingBundle = FindBundleItemRecursive(existingStorage, item->Name()); if (existingBundle) return existingBundle; } return existingStorage; } } // If this is a sub asset to a bundle, try to find the bundle also from no storage item. if (!subAssetPart.isEmpty()) { AssetBundleItem *existingBundle = FindBundleItemRecursive(noStorageItem, item->Name()); if (existingBundle) return existingBundle; } return noStorageItem; }
14,504
4,465
int global; int main() { int i, j, k, l, m, n; }
53
27
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Heiko Strathmann, Soeren Sonnenburg, Sergey Lisitsyn, Viktor Gal */ #include <shogun/features/streaming/StreamingFeatures.h> #include <shogun/features/streaming/StreamingDenseFeatures.h> #include <shogun/features/DenseFeatures.h> using namespace shogun; CStreamingFeatures::CStreamingFeatures() : CFeatures() { working_file=NULL; } CStreamingFeatures::~CStreamingFeatures() { SG_DEBUG("entering CStreamingFeatures::~CStreamingFeatures()\n") SG_UNREF(working_file); SG_DEBUG("leaving CStreamingFeatures::~CStreamingFeatures()\n") } void CStreamingFeatures::set_read_functions() { set_vector_reader(); set_vector_and_label_reader(); } bool CStreamingFeatures::get_has_labels() { return has_labels; } bool CStreamingFeatures::is_seekable() { return seekable; } void CStreamingFeatures::reset_stream() { SG_NOTIMPLEMENTED return; }
943
353
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/formats/format_transfers/format_transfer_nhwc_nc1hwc0.h" #include <securec.h> #include <memory> #include "common/formats/utils/formats_definitions.h" #include "common/formats/utils/formats_trans_utils.h" #include "framework/common/debug/ge_log.h" #include "graph/utils/type_utils.h" namespace ge { namespace formats { namespace { bool CheckDataTypeSupported(const DataType &data_type) { return GetSizeByDataType(data_type) > 0; } Status TransShapeNhwcToNc1hwc0(const std::vector<int64_t> &src_shape, DataType data_type, std::vector<int64_t> &dst_shape) { int64_t c0 = GetCubeSizeByDataType(data_type); if (c0 <= 0) { GELOGE(PARAM_INVALID, "Failed to get cube size, the data type is invalid"); return PARAM_INVALID; } dst_shape.clear(); dst_shape.push_back(src_shape.at(kNhwcN)); dst_shape.push_back((src_shape.at(kNhwcC) - 1) / c0 + 1); dst_shape.push_back(src_shape.at(kNhwcH)); dst_shape.push_back(src_shape.at(kNhwcW)); dst_shape.push_back(c0); if (!CheckShapeValid(dst_shape, kNc1hwc0DimsNum)) { GELOGE(PARAM_INVALID, "Failed to check dst shape %s", ShapeToString(dst_shape).c_str()); return PARAM_INVALID; } return SUCCESS; } Status CheckArgsForNhwcToNc1hwc0(const TransArgs &args) { if (args.src_format != FORMAT_NHWC || args.dst_format != FORMAT_NC1HWC0) { GELOGE(UNSUPPORTED, "Does not support trans format from %s to %s", TypeUtils::FormatToSerialString(args.src_format).c_str(), TypeUtils::FormatToSerialString(args.dst_format).c_str()); return UNSUPPORTED; } if (!CheckDataTypeSupported(args.src_data_type)) { GELOGE(UNSUPPORTED, "Failed to trans shape from NHWC to NC1HWC0, invalid data type %s", TypeUtils::DataTypeToSerialString(args.src_data_type).c_str()); return UNSUPPORTED; } if (!CheckShapeValid(args.src_shape, kNhwcDimsNum)) { GELOGE(PARAM_INVALID, "Failed to check src shape %s", ShapeToString(args.src_shape).c_str()); return PARAM_INVALID; } if (!CheckShapeValid(args.dst_shape, kNc1hwc0DimsNum)) { GELOGE(PARAM_INVALID, "Failed to check dst shape %s", ShapeToString(args.dst_shape).c_str()); return PARAM_INVALID; } std::vector<int64_t> expect_dst_shape; auto ret = TransShapeNhwcToNc1hwc0(args.src_shape, args.src_data_type, expect_dst_shape); if (ret != SUCCESS) { return ret; } if (args.dst_shape != expect_dst_shape) { GELOGE(PARAM_INVALID, "Failed to trans format, the src and dst shape are not compatible. src shape %s, dst shape %s, " "expect dst shape %s", ShapeToString(args.src_shape).c_str(), ShapeToString(args.dst_shape).c_str(), ShapeToString(expect_dst_shape).c_str()); return PARAM_INVALID; } return SUCCESS; } Status GetDstDataAfterTrans(const TransArgs &args, TransResult &result, const int size, const int64_t total_size) { std::shared_ptr<uint8_t> dst(new (std::nothrow) uint8_t[total_size], std::default_delete<uint8_t[]>()); if (dst == nullptr) { GELOGE(OUT_OF_MEMORY, "Failed to trans format from %s to %s, can not alloc the memory for dst buf %ld, shape %s", TypeUtils::FormatToSerialString(args.src_format).c_str(), TypeUtils::FormatToSerialString(args.dst_format).c_str(), total_size, ShapeToString(args.dst_shape).c_str()); return OUT_OF_MEMORY; } auto n = args.src_shape.at(kNhwcN); auto h = args.src_shape.at(kNhwcH); auto w = args.src_shape.at(kNhwcW); auto c = args.src_shape.at(kNhwcC); auto c1 = args.dst_shape.at(kNc1hwc0C1); auto c0 = args.dst_shape.at(kNc1hwc0C0); int64_t wc = w * c; int64_t hwc = h * wc; int64_t wc0 = w * c0; int64_t hwc0 = h * wc0; int64_t c1hwc0 = c1 * hwc0; for (int64_t n_idx = 0; n_idx < n; n_idx++) { int64_t n_head_addr = n_idx * c1hwc0; for (int64_t c1_idx = 0; c1_idx < c1; c1_idx++) { int64_t c1_head_addr = n_head_addr + c1_idx * hwc0; for (int64_t h_idx = 0; h_idx < h; h_idx++) { int64_t h_head_addr = c1_head_addr + h_idx * wc0; for (int64_t w_idx = 0; w_idx < w; w_idx++) { int64_t w_head_addr = h_head_addr + w_idx * c0; for (int64_t c0_idx = 0; c0_idx < c0; c0_idx++) { int64_t dst_idx = c0_idx + w_head_addr; int64_t dst_offset = dst_idx * size; auto protected_size = total_size - dst_offset < static_cast<int64_t>(SECUREC_MEM_MAX_LEN) ? total_size - dst_offset : static_cast<int64_t>(SECUREC_MEM_MAX_LEN); int64_t c_idx = c0_idx + c1_idx * c0; int64_t src_idx = n_idx * hwc + h_idx * wc + w_idx * c + c_idx; auto src_offset = src_idx * size; if (c_idx < c) { auto ret = memcpy_s(dst.get() + dst_offset, protected_size, args.data + src_offset, size); if (ret != EOK) { GELOGE(INTERNAL_ERROR, "Failed to copy data from NHWC[%ld, %ld, %ld, %ld] offset %ld to " "NC1HWC0[%ld, %ld, %ld, %ld, %ld] offset %ld err-code %d", n_idx, h_idx, w_idx, c_idx, src_offset, n_idx, c1_idx, h_idx, w_idx, c0_idx, dst_offset, ret); return INTERNAL_ERROR; } } else { auto ret = memset_s(dst.get() + dst_offset, protected_size, 0, size); if (ret != EOK) { GELOGE(INTERNAL_ERROR, "Failed to set 0 to NC1HWC0[%ld, %ld, %ld, %ld, %ld] offset %ld base err-code %d", n_idx, c1_idx, h_idx, w_idx, c0_idx, dst_offset, ret); return INTERNAL_ERROR; } } } } } } } result.data = dst; result.length = static_cast<size_t>(total_size); return SUCCESS; } } // namespace Status FormatTransferNhwcNc1hwc0::TransFormat(const TransArgs &args, TransResult &result) { if (CheckArgsForNhwcToNc1hwc0(args) != SUCCESS) { return PARAM_INVALID; } int size = GetSizeByDataType(args.src_data_type); auto total_size = GetItemNumByShape(args.dst_shape) * size; if (total_size <= 0) { GELOGE(INTERNAL_ERROR, "Get %ld total size from dst shape %s, src shape %s", total_size, ShapeToString(args.dst_shape).c_str(), ShapeToString(args.src_shape).c_str()); return PARAM_INVALID; } GELOGD("Begin to trans format from NHWC to NC1HWC0, src shape %s, data type %s, dst shape %s, memory size %ld", ShapeToString(args.src_shape).c_str(), TypeUtils::DataTypeToSerialString(args.src_data_type).c_str(), ShapeToString(args.dst_shape).c_str(), total_size); if (GetDstDataAfterTrans(args, result, size, total_size) != SUCCESS) { GELOGE(INTERNAL_ERROR, "Failed to get data after trans, src shape %s, data type %s, dst shape %s, memory size %ld", ShapeToString(args.src_shape).c_str(), TypeUtils::DataTypeToSerialString(args.src_data_type).c_str(), ShapeToString(args.dst_shape).c_str(), total_size); return INTERNAL_ERROR; } return SUCCESS; } Status FormatTransferNhwcNc1hwc0::TransShape(Format src_format, const std::vector<int64_t> &src_shape, DataType data_type, Format dst_format, std::vector<int64_t> &dst_shape) { if (src_format == FORMAT_NHWC && CheckDataTypeSupported(data_type)) { if (!CheckShapeValid(src_shape, kNhwcDimsNum)) { GELOGE(PARAM_INVALID, "Failed to check src shape %s", ShapeToString(src_shape).c_str()); return PARAM_INVALID; } return TransShapeNhwcToNc1hwc0(src_shape, data_type, dst_shape); } else { return UNSUPPORTED; } } REGISTER_FORMAT_TRANSFER(FormatTransferNhwcNc1hwc0, FORMAT_NHWC, FORMAT_NC1HWC0) } // namespace formats } // namespace ge
8,443
3,222
/* * This file is part of the Micro Python project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2015 Damien P. George * * 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 "MicroBit.h" #include "microbitobj.h" extern "C" { #include "py/runtime.h" #include "modmicrobit.h" #include "lib/pwm.h" #include "microbit/microbitpin.h" #include "nrf_gpio.h" #include "py/mphal.h" #define SINOBIT const microbit_pin_obj_t microbit_p0_obj = {{&microbit_touch_pin_type}, 0, MICROBIT_PIN_P0, MODE_UNUSED}; const microbit_pin_obj_t microbit_p1_obj = {{&microbit_touch_pin_type}, 1, MICROBIT_PIN_P1, MODE_UNUSED}; const microbit_pin_obj_t microbit_p2_obj = {{&microbit_touch_pin_type}, 2, MICROBIT_PIN_P2, MODE_UNUSED}; #ifdef SINOBIT const microbit_pin_obj_t microbit_p3_obj = {{&microbit_touch_pin_type}, 3, MICROBIT_PIN_P3, MODE_UNUSED}; const microbit_pin_obj_t microbit_p4_obj = {{&microbit_touch_pin_type}, 4, MICROBIT_PIN_P4, MODE_UNUSED}; #else const microbit_pin_obj_t microbit_p3_obj = {{&microbit_ad_pin_type}, 3, MICROBIT_PIN_P3, MODE_DISPLAY}; const microbit_pin_obj_t microbit_p4_obj = {{&microbit_ad_pin_type}, 4, MICROBIT_PIN_P4, MODE_DISPLAY}; #endif const microbit_pin_obj_t microbit_p5_obj = {{&microbit_dig_pin_type}, 5, MICROBIT_PIN_P5, MODE_BUTTON}; #ifdef SINOBIT const microbit_pin_obj_t microbit_p6_obj = {{&microbit_dig_pin_type}, 6, MICROBIT_PIN_P6, MODE_UNUSED}; const microbit_pin_obj_t microbit_p7_obj = {{&microbit_dig_pin_type}, 7, MICROBIT_PIN_P7, MODE_UNUSED}; const microbit_pin_obj_t microbit_p8_obj = {{&microbit_dig_pin_type}, 8, MICROBIT_PIN_P8, MODE_UNUSED}; const microbit_pin_obj_t microbit_p9_obj = {{&microbit_dig_pin_type}, 9, MICROBIT_PIN_P9, MODE_UNUSED}; const microbit_pin_obj_t microbit_p10_obj = {{&microbit_touch_pin_type}, 10, MICROBIT_PIN_P10, MODE_UNUSED}; #else const microbit_pin_obj_t microbit_p6_obj = {{&microbit_dig_pin_type}, 6, MICROBIT_PIN_P6, MODE_DISPLAY}; const microbit_pin_obj_t microbit_p7_obj = {{&microbit_dig_pin_type}, 7, MICROBIT_PIN_P7, MODE_DISPLAY}; const microbit_pin_obj_t microbit_p8_obj = {{&microbit_dig_pin_type}, 8, MICROBIT_PIN_P8, MODE_UNUSED}; const microbit_pin_obj_t microbit_p9_obj = {{&microbit_dig_pin_type}, 9, MICROBIT_PIN_P9, MODE_DISPLAY}; const microbit_pin_obj_t microbit_p10_obj = {{&microbit_ad_pin_type}, 10, MICROBIT_PIN_P10, MODE_DISPLAY}; #endif const microbit_pin_obj_t microbit_p11_obj = {{&microbit_dig_pin_type}, 11, MICROBIT_PIN_P11, MODE_BUTTON}; const microbit_pin_obj_t microbit_p12_obj = {{&microbit_dig_pin_type}, 12, MICROBIT_PIN_P12, MODE_UNUSED}; const microbit_pin_obj_t microbit_p13_obj = {{&microbit_dig_pin_type}, 13, MICROBIT_PIN_P13, MODE_SPI}; const microbit_pin_obj_t microbit_p14_obj = {{&microbit_dig_pin_type}, 14, MICROBIT_PIN_P14, MODE_SPI}; const microbit_pin_obj_t microbit_p15_obj = {{&microbit_dig_pin_type}, 15, MICROBIT_PIN_P15, MODE_SPI}; const microbit_pin_obj_t microbit_p16_obj = {{&microbit_dig_pin_type}, 16, MICROBIT_PIN_P16, MODE_UNUSED}; const microbit_pin_obj_t microbit_p19_obj = {{&microbit_dig_pin_type}, 19, MICROBIT_PIN_P19, MODE_I2C}; const microbit_pin_obj_t microbit_p20_obj = {{&microbit_dig_pin_type}, 20, MICROBIT_PIN_P20, MODE_I2C}; static mp_obj_t microbit_pin_get_mode_func(mp_obj_t self_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; return MP_OBJ_NEW_QSTR(microbit_pin_get_mode(self)->name); } MP_DEFINE_CONST_FUN_OBJ_1(microbit_pin_get_mode_obj, microbit_pin_get_mode_func); mp_obj_t microbit_pin_write_digital(mp_obj_t self_in, mp_obj_t value_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; int val = mp_obj_get_int(value_in); if (val >> 1) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "value must be 0 or 1")); } if (microbit_pin_get_mode(self) != microbit_pin_mode_write_digital) { microbit_obj_pin_acquire(self, microbit_pin_mode_write_digital); nrf_gpio_cfg_output(self->name); } if (val) nrf_gpio_pin_set(self->name); else nrf_gpio_pin_clear(self->name); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(microbit_pin_write_digital_obj, microbit_pin_write_digital); mp_obj_t microbit_pin_read_digital(mp_obj_t self_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; if (microbit_pin_get_mode(self) != microbit_pin_mode_read_digital) { microbit_obj_pin_acquire(self, microbit_pin_mode_read_digital); nrf_gpio_cfg_input(self->name, NRF_GPIO_PIN_PULLDOWN); } return mp_obj_new_int(nrf_gpio_pin_read(self->name)); } MP_DEFINE_CONST_FUN_OBJ_1(microbit_pin_read_digital_obj, microbit_pin_read_digital); #define SHIFT_PULL_MASK ((1<<NRF_GPIO_PIN_PULLDOWN) | (1<<NRF_GPIO_PIN_PULLUP) | (1<<NRF_GPIO_PIN_NOPULL)) mp_obj_t microbit_pin_set_pull(mp_obj_t self_in, mp_obj_t pull_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; int pull = mp_obj_get_int(pull_in); if (((1 << pull) & SHIFT_PULL_MASK) == 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid pull")); } const microbit_pinmode_t *mode = microbit_pin_get_mode(self); /* Pull only applies in an read digital mode */ if (mode != microbit_pin_mode_read_digital) { pinmode_error(self); } nrf_gpio_cfg_input(self->name, (nrf_gpio_pin_pull_t)pull); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(microbit_pin_set_pull_obj, microbit_pin_set_pull); #define PULL_MASK (NRF_GPIO_PIN_PULLDOWN | NRF_GPIO_PIN_NOPULL | NRF_GPIO_PIN_PULLUP) mp_obj_t microbit_pin_get_pull(mp_obj_t self_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; const microbit_pinmode_t *mode = microbit_pin_get_mode(self); /* Pull only applies in an read digital mode */ if (mode != microbit_pin_mode_read_digital) { pinmode_error(self); } uint32_t pull = (NRF_GPIO->PIN_CNF[self->name] >> GPIO_PIN_CNF_PULL_Pos) & PULL_MASK; return mp_obj_new_int(pull); } MP_DEFINE_CONST_FUN_OBJ_1(microbit_pin_get_pull_obj, microbit_pin_get_pull); mp_obj_t microbit_pin_write_analog(mp_obj_t self_in, mp_obj_t value_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; int set_value; if (mp_obj_is_float(value_in)) { mp_float_t val = mp_obj_get_float(value_in); set_value = val+0.5; } else { set_value = mp_obj_get_int(value_in); } if (set_value < 0 || set_value > MICROBIT_PIN_MAX_OUTPUT) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "value must be between 0 and 1023")); } if (microbit_pin_get_mode(self) != microbit_pin_mode_write_analog) { microbit_obj_pin_acquire(self, microbit_pin_mode_write_analog); nrf_gpio_cfg_output(self->name); } pwm_set_duty_cycle(self->name, set_value); if (set_value == 0) microbit_obj_pin_acquire(self, microbit_pin_mode_unused); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(microbit_pin_write_analog_obj, microbit_pin_write_analog); mp_obj_t microbit_pin_read_analog(mp_obj_t self_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; microbit_obj_pin_acquire(self, microbit_pin_mode_unused); analogin_t obj; analogin_init(&obj, (PinName)self->name); int val = analogin_read_u16(&obj); NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Disabled; return mp_obj_new_int(val); } MP_DEFINE_CONST_FUN_OBJ_1(microbit_pin_read_analog_obj, microbit_pin_read_analog); mp_obj_t microbit_pin_set_analog_period(mp_obj_t self_in, mp_obj_t period_in) { (void)self_in; int err = pwm_set_period_us(mp_obj_get_int(period_in)*1000); if (err) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid period")); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(microbit_pin_set_analog_period_obj, microbit_pin_set_analog_period); mp_obj_t microbit_pin_set_analog_period_microseconds(mp_obj_t self_in, mp_obj_t period_in) { (void)self_in; int err = pwm_set_period_us(mp_obj_get_int(period_in)); if (err) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid period")); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(microbit_pin_set_analog_period_microseconds_obj, microbit_pin_set_analog_period_microseconds); mp_obj_t microbit_pin_get_analog_period_microseconds(mp_obj_t self_in) { (void)self_in; int32_t period = pwm_get_period_us(); return mp_obj_new_int(period); } MP_DEFINE_CONST_FUN_OBJ_1(microbit_pin_get_analog_period_microseconds_obj, microbit_pin_get_analog_period_microseconds); mp_obj_t microbit_pin_is_touched(mp_obj_t self_in) { microbit_pin_obj_t *self = (microbit_pin_obj_t*)self_in; const microbit_pinmode_t *mode = microbit_pin_get_mode(self); if (mode != microbit_pin_mode_touch && mode != microbit_pin_mode_button) { microbit_obj_pin_acquire(self, microbit_pin_mode_touch); nrf_gpio_cfg_input(self->name, NRF_GPIO_PIN_PULLUP); } /* Pin is touched if it is low after debouncing */ return mp_obj_new_bool(!microbit_pin_high_debounced(self)); } MP_DEFINE_CONST_FUN_OBJ_1(microbit_pin_is_touched_obj, microbit_pin_is_touched); #define PULL_CONSTANTS \ { MP_OBJ_NEW_QSTR(MP_QSTR_PULL_UP), MP_OBJ_NEW_SMALL_INT(NRF_GPIO_PIN_PULLUP) }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_PULL_DOWN), MP_OBJ_NEW_SMALL_INT(NRF_GPIO_PIN_PULLDOWN) }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_NO_PULL), MP_OBJ_NEW_SMALL_INT(NRF_GPIO_PIN_NOPULL) } STATIC const mp_map_elem_t microbit_dig_pin_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_write_digital), (mp_obj_t)&microbit_pin_write_digital_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read_digital), (mp_obj_t)&microbit_pin_read_digital_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_write_analog), (mp_obj_t)&microbit_pin_write_analog_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_analog_period), (mp_obj_t)&microbit_pin_set_analog_period_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_analog_period_microseconds), (mp_obj_t)&microbit_pin_set_analog_period_microseconds_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_get_analog_period_microseconds), (mp_obj_t)&microbit_pin_get_analog_period_microseconds_obj }, PULL_CONSTANTS, { MP_OBJ_NEW_QSTR(MP_QSTR_get_pull),(mp_obj_t)&microbit_pin_get_pull_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_pull),(mp_obj_t)&microbit_pin_set_pull_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_get_mode), (mp_obj_t)&microbit_pin_get_mode_obj }, }; STATIC const mp_map_elem_t microbit_ann_pin_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_write_digital), (mp_obj_t)&microbit_pin_write_digital_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read_digital), (mp_obj_t)&microbit_pin_read_digital_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_write_analog), (mp_obj_t)&microbit_pin_write_analog_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read_analog), (mp_obj_t)&microbit_pin_read_analog_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_analog_period), (mp_obj_t)&microbit_pin_set_analog_period_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_analog_period_microseconds), (mp_obj_t)&microbit_pin_set_analog_period_microseconds_obj }, PULL_CONSTANTS, { MP_OBJ_NEW_QSTR(MP_QSTR_get_pull),(mp_obj_t)&microbit_pin_get_pull_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_pull),(mp_obj_t)&microbit_pin_set_pull_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_get_mode), (mp_obj_t)&microbit_pin_get_mode_obj }, }; STATIC const mp_map_elem_t microbit_touch_pin_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_write_digital), (mp_obj_t)&microbit_pin_write_digital_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read_digital), (mp_obj_t)&microbit_pin_read_digital_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_write_analog), (mp_obj_t)&microbit_pin_write_analog_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_read_analog), (mp_obj_t)&microbit_pin_read_analog_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_analog_period), (mp_obj_t)&microbit_pin_set_analog_period_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_analog_period_microseconds), (mp_obj_t)&microbit_pin_set_analog_period_microseconds_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_is_touched), (mp_obj_t)&microbit_pin_is_touched_obj }, PULL_CONSTANTS, { MP_OBJ_NEW_QSTR(MP_QSTR_get_pull),(mp_obj_t)&microbit_pin_get_pull_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_pull),(mp_obj_t)&microbit_pin_set_pull_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_get_mode), (mp_obj_t)&microbit_pin_get_mode_obj }, }; STATIC MP_DEFINE_CONST_DICT(microbit_dig_pin_locals_dict, microbit_dig_pin_locals_dict_table); STATIC MP_DEFINE_CONST_DICT(microbit_ann_pin_locals_dict, microbit_ann_pin_locals_dict_table); STATIC MP_DEFINE_CONST_DICT(microbit_touch_pin_locals_dict, microbit_touch_pin_locals_dict_table); const mp_obj_type_t microbit_dig_pin_type = { { &mp_type_type }, .name = MP_QSTR_MicroBitDigitalPin, .print = NULL, .make_new = NULL, .call = NULL, .unary_op = NULL, .binary_op = NULL, .attr = NULL, .subscr = NULL, .getiter = NULL, .iternext = NULL, .buffer_p = {NULL}, .stream_p = NULL, .bases_tuple = NULL, .locals_dict = (mp_obj_dict_t*)&microbit_dig_pin_locals_dict, }; const mp_obj_type_t microbit_ad_pin_type = { { &mp_type_type }, .name = MP_QSTR_MicroBitAnalogDigitalPin, .print = NULL, .make_new = NULL, .call = NULL, .unary_op = NULL, .binary_op = NULL, .attr = NULL, .subscr = NULL, .getiter = NULL, .iternext = NULL, .buffer_p = {NULL}, .stream_p = NULL, .bases_tuple = NULL, .locals_dict = (mp_obj_dict_t*)&microbit_ann_pin_locals_dict, }; const mp_obj_type_t microbit_touch_pin_type = { { &mp_type_type }, .name = MP_QSTR_MicroBitTouchPin, .print = NULL, .make_new = NULL, .call = NULL, .unary_op = NULL, .binary_op = NULL, .attr = NULL, .subscr = NULL, .getiter = NULL, .iternext = NULL, .buffer_p = {NULL}, .stream_p = NULL, .bases_tuple = NULL, .locals_dict = (mp_obj_dict_t*)&microbit_touch_pin_locals_dict, }; void microbit_pin_init(void) { nrf_gpio_cfg_input(microbit_p5_obj.name, NRF_GPIO_PIN_PULLUP); nrf_gpio_cfg_input(microbit_p11_obj.name, NRF_GPIO_PIN_PULLUP); } const microbit_pin_obj_t *microbit_obj_get_pin(mp_obj_t o) { mp_obj_type_t *type = mp_obj_get_type(o); if (type == &microbit_touch_pin_type || type == &microbit_ad_pin_type || type == &microbit_dig_pin_type) { return (microbit_pin_obj_t*)o; } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "expecting a pin")); } } PinName microbit_obj_get_pin_name(mp_obj_t o) { return (PinName)microbit_obj_get_pin(o)->name; } }
15,617
6,982
#include "GameApp.h" #include "d3dUtil.h" #include "DXTrace.h" using namespace DirectX; GameApp::GameApp(HINSTANCE hInstance) : D3DApp(hInstance), m_IndexCount(), m_CurrFrame(), m_CurrMode(ShowMode::WoodCrate), m_VSConstantBuffer(), m_PSConstantBuffer() { } GameApp::~GameApp() { } bool GameApp::Init() { if (!D3DApp::Init()) return false; if (!InitEffect()) return false; if (!InitResource()) return false; // 初始化鼠标,键盘不需要 m_pMouse->SetWindow(m_hMainWnd); m_pMouse->SetMode(DirectX::Mouse::MODE_ABSOLUTE); return true; } void GameApp::OnResize() { assert(m_pd2dFactory); assert(m_pdwriteFactory); // 释放D2D的相关资源 m_pColorBrush.Reset(); m_pd2dRenderTarget.Reset(); D3DApp::OnResize(); // 为D2D创建DXGI表面渲染目标 ComPtr<IDXGISurface> surface; HR(m_pSwapChain->GetBuffer(0, __uuidof(IDXGISurface), reinterpret_cast<void**>(surface.GetAddressOf()))); D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED)); HRESULT hr = m_pd2dFactory->CreateDxgiSurfaceRenderTarget(surface.Get(), &props, m_pd2dRenderTarget.GetAddressOf()); surface.Reset(); if (hr == E_NOINTERFACE) { OutputDebugStringW(L"\n警告:Direct2D与Direct3D互操作性功能受限,你将无法看到文本信息。现提供下述可选方法:\n" L"1. 对于Win7系统,需要更新至Win7 SP1,并安装KB2670838补丁以支持Direct2D显示。\n" L"2. 自行完成Direct3D 10.1与Direct2D的交互。详情参阅:" L"https://docs.microsoft.com/zh-cn/windows/desktop/Direct2D/direct2d-and-direct3d-interoperation-overview""\n" L"3. 使用别的字体库,比如FreeType。\n\n"); } else if (hr == S_OK) { // 创建固定颜色刷和文本格式 HR(m_pd2dRenderTarget->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::White), m_pColorBrush.GetAddressOf())); HR(m_pdwriteFactory->CreateTextFormat(L"宋体", nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 20, L"zh-cn", m_pTextFormat.GetAddressOf())); } else { // 报告异常问题 assert(m_pd2dRenderTarget); } } void GameApp::UpdateScene(float dt) { Keyboard::State state = m_pKeyboard->GetState(); m_KeyboardTracker.Update(state); // 键盘切换模式 if (m_KeyboardTracker.IsKeyPressed(Keyboard::D1) && m_CurrMode != ShowMode::WoodCrate) { // 播放木箱动画 m_CurrMode = ShowMode::WoodCrate; m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout3D.Get()); auto meshData = Geometry::CreateBox(); ResetMesh(meshData); m_pd3dImmediateContext->VSSetShader(m_pVertexShader3D.Get(), nullptr, 0); m_pd3dImmediateContext->PSSetShader(m_pPixelShader3D.Get(), nullptr, 0); m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pWoodCrate.GetAddressOf()); } else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D2) && m_CurrMode != ShowMode::FireAnim) { m_CurrMode = ShowMode::FireAnim; m_CurrFrame = 0; m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout2D.Get()); auto meshData = Geometry::Create2DShow(); ResetMesh(meshData); m_pd3dImmediateContext->VSSetShader(m_pVertexShader2D.Get(), nullptr, 0); m_pd3dImmediateContext->PSSetShader(m_pPixelShader2D.Get(), nullptr, 0); m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pFireAnims[0].GetAddressOf()); } if (m_CurrMode == ShowMode::WoodCrate) { static float phi = 0.0f, theta = 0.0f; phi += 0.0001f, theta += 0.00015f; XMMATRIX W = XMMatrixRotationX(phi) * XMMatrixRotationY(theta); m_VSConstantBuffer.world = XMMatrixTranspose(W); m_VSConstantBuffer.worldInvTranspose = XMMatrixInverse(nullptr, W); // 两次转置抵消 // 更新常量缓冲区,让立方体转起来 D3D11_MAPPED_SUBRESOURCE mappedData; HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[0].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedData)); memcpy_s(mappedData.pData, sizeof(VSConstantBuffer), &m_VSConstantBuffer, sizeof(VSConstantBuffer)); m_pd3dImmediateContext->Unmap(m_pConstantBuffers[0].Get(), 0); } else if (m_CurrMode == ShowMode::FireAnim) { // 用于限制在1秒60帧 static float totDeltaTime = 0; totDeltaTime += dt; if (totDeltaTime > 1.0f / 60) { totDeltaTime -= 1.0f / 60; m_CurrFrame = (m_CurrFrame + 1) % 120; m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pFireAnims[m_CurrFrame].GetAddressOf()); } } } void GameApp::DrawScene() { assert(m_pd3dImmediateContext); assert(m_pSwapChain); m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&Colors::Black)); m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); // 绘制几何模型 m_pd3dImmediateContext->DrawIndexed(m_IndexCount, 0, 0); // // 绘制Direct2D部分 // if (m_pd2dRenderTarget != nullptr) { m_pd2dRenderTarget->BeginDraw(); static const WCHAR* textStr = L"切换显示: 1-木箱(3D) 2-火焰(2D)\n"; m_pd2dRenderTarget->DrawTextW(textStr, (UINT)wcslen(textStr), m_pTextFormat.Get(), D2D1_RECT_F{ 0.0f, 0.0f, 600.0f, 200.0f }, m_pColorBrush.Get()); HR(m_pd2dRenderTarget->EndDraw()); } HR(m_pSwapChain->Present(0, 0)); } bool GameApp::InitEffect() { ComPtr<ID3DBlob> blob; // 创建顶点着色器(2D) HR(CreateShaderFromFile(L"HLSL\\Basic_VS_2D.cso", L"HLSL\\Basic_VS_2D.hlsl", "VS_2D", "vs_5_0", blob.ReleaseAndGetAddressOf())); HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader2D.GetAddressOf())); // 创建顶点布局(2D) HR(m_pd3dDevice->CreateInputLayout(VertexPosTex::inputLayout, ARRAYSIZE(VertexPosTex::inputLayout), blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout2D.GetAddressOf())); // 创建像素着色器(2D) HR(CreateShaderFromFile(L"HLSL\\Basic_PS_2D.cso", L"HLSL\\Basic_PS_2D.hlsl", "PS_2D", "ps_5_0", blob.ReleaseAndGetAddressOf())); HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader2D.GetAddressOf())); // 创建顶点着色器(3D) HR(CreateShaderFromFile(L"HLSL\\Basic_VS_3D.cso", L"HLSL\\Basic_VS_3D.hlsl", "VS_3D", "vs_5_0", blob.ReleaseAndGetAddressOf())); HR(m_pd3dDevice->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pVertexShader3D.GetAddressOf())); // 创建顶点布局(3D) HR(m_pd3dDevice->CreateInputLayout(VertexPosNormalTex::inputLayout, ARRAYSIZE(VertexPosNormalTex::inputLayout), blob->GetBufferPointer(), blob->GetBufferSize(), m_pVertexLayout3D.GetAddressOf())); // 创建像素着色器(3D) HR(CreateShaderFromFile(L"HLSL\\Basic_PS_3D.cso", L"HLSL\\Basic_PS_3D.hlsl", "PS_3D", "ps_5_0", blob.ReleaseAndGetAddressOf())); HR(m_pd3dDevice->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, m_pPixelShader3D.GetAddressOf())); return true; } bool GameApp::InitResource() { // 初始化网格模型并设置到输入装配阶段 auto meshData = Geometry::CreateBox(); ResetMesh(meshData); // ****************** // 设置常量缓冲区描述 // D3D11_BUFFER_DESC cbd; ZeroMemory(&cbd, sizeof(cbd)); cbd.Usage = D3D11_USAGE_DYNAMIC; cbd.ByteWidth = sizeof(VSConstantBuffer); cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // 新建用于VS和PS的常量缓冲区 HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[0].GetAddressOf())); cbd.ByteWidth = sizeof(PSConstantBuffer); HR(m_pd3dDevice->CreateBuffer(&cbd, nullptr, m_pConstantBuffers[1].GetAddressOf())); // ****************** // 初始化纹理和采样器状态 // // 初始化木箱纹理 HR(CreateDDSTextureFromFile(m_pd3dDevice.Get(), L"Texture\\WoodCrate.dds", nullptr, m_pWoodCrate.GetAddressOf())); // 初始化火焰纹理 WCHAR strFile[40]; m_pFireAnims.resize(120); for (int i = 1; i <= 120; ++i) { wsprintf(strFile, L"Texture\\FireAnim\\Fire%03d.bmp", i); HR(CreateWICTextureFromFile(m_pd3dDevice.Get(), strFile, nullptr, m_pFireAnims[static_cast<size_t>(i) - 1].GetAddressOf())); } // 初始化采样器状态 D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; HR(m_pd3dDevice->CreateSamplerState(&sampDesc, m_pSamplerState.GetAddressOf())); // ****************** // 初始化常量缓冲区的值 // // 初始化用于VS的常量缓冲区的值 m_VSConstantBuffer.world = XMMatrixIdentity(); m_VSConstantBuffer.view = XMMatrixTranspose(XMMatrixLookAtLH( XMVectorSet(0.0f, 0.0f, -5.0f, 0.0f), XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f) )); m_VSConstantBuffer.proj = XMMatrixTranspose(XMMatrixPerspectiveFovLH(XM_PIDIV2, AspectRatio(), 1.0f, 1000.0f)); m_VSConstantBuffer.worldInvTranspose = XMMatrixIdentity(); // 初始化用于PS的常量缓冲区的值 // 这里只使用一盏点光来演示 m_PSConstantBuffer.pointLight[0].position = XMFLOAT3(0.0f, 0.0f, -10.0f); m_PSConstantBuffer.pointLight[0].ambient = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); m_PSConstantBuffer.pointLight[0].diffuse = XMFLOAT4(0.7f, 0.7f, 0.7f, 1.0f); m_PSConstantBuffer.pointLight[0].specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_PSConstantBuffer.pointLight[0].att = XMFLOAT3(0.0f, 0.1f, 0.0f); m_PSConstantBuffer.pointLight[0].range = 25.0f; m_PSConstantBuffer.numDirLight = 0; m_PSConstantBuffer.numPointLight = 1; m_PSConstantBuffer.numSpotLight = 0; // 初始化材质 m_PSConstantBuffer.material.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); m_PSConstantBuffer.material.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); m_PSConstantBuffer.material.specular = XMFLOAT4(0.1f, 0.1f, 0.1f, 5.0f); // 注意不要忘记设置此处的观察位置,否则高亮部分会有问题 m_PSConstantBuffer.eyePos = XMFLOAT4(0.0f, 0.0f, -5.0f, 0.0f); // 更新PS常量缓冲区资源 D3D11_MAPPED_SUBRESOURCE mappedData; HR(m_pd3dImmediateContext->Map(m_pConstantBuffers[1].Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedData)); memcpy_s(mappedData.pData, sizeof(PSConstantBuffer), &m_PSConstantBuffer, sizeof(PSConstantBuffer)); m_pd3dImmediateContext->Unmap(m_pConstantBuffers[1].Get(), 0); // ****************** // 给渲染管线各个阶段绑定好所需资源 // 设置图元类型,设定输入布局 m_pd3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_pd3dImmediateContext->IASetInputLayout(m_pVertexLayout3D.Get()); // 默认绑定3D着色器 m_pd3dImmediateContext->VSSetShader(m_pVertexShader3D.Get(), nullptr, 0); // VS常量缓冲区对应HLSL寄存于b0的常量缓冲区 m_pd3dImmediateContext->VSSetConstantBuffers(0, 1, m_pConstantBuffers[0].GetAddressOf()); // PS常量缓冲区对应HLSL寄存于b1的常量缓冲区 m_pd3dImmediateContext->PSSetConstantBuffers(1, 1, m_pConstantBuffers[1].GetAddressOf()); // 像素着色阶段设置好采样器 m_pd3dImmediateContext->PSSetSamplers(0, 1, m_pSamplerState.GetAddressOf()); m_pd3dImmediateContext->PSSetShaderResources(0, 1, m_pWoodCrate.GetAddressOf()); m_pd3dImmediateContext->PSSetShader(m_pPixelShader3D.Get(), nullptr, 0); // ****************** // 设置调试对象名 // D3D11SetDebugObjectName(m_pVertexLayout2D.Get(), "VertexPosTexLayout"); D3D11SetDebugObjectName(m_pVertexLayout3D.Get(), "VertexPosNormalTexLayout"); D3D11SetDebugObjectName(m_pConstantBuffers[0].Get(), "VSConstantBuffer"); D3D11SetDebugObjectName(m_pConstantBuffers[1].Get(), "PSConstantBuffer"); D3D11SetDebugObjectName(m_pVertexShader2D.Get(), "Basic_VS_2D"); D3D11SetDebugObjectName(m_pVertexShader3D.Get(), "Basic_VS_3D"); D3D11SetDebugObjectName(m_pPixelShader2D.Get(), "Basic_PS_2D"); D3D11SetDebugObjectName(m_pPixelShader3D.Get(), "Basic_PS_3D"); D3D11SetDebugObjectName(m_pSamplerState.Get(), "SSLinearWrap"); return true; } template<class VertexType> bool GameApp::ResetMesh(const Geometry::MeshData<VertexType>& meshData) { // 释放旧资源 m_pVertexBuffer.Reset(); m_pIndexBuffer.Reset(); // 设置顶点缓冲区描述 D3D11_BUFFER_DESC vbd; ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = (UINT)meshData.vertexVec.size() * sizeof(VertexType); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; // 新建顶点缓冲区 D3D11_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = meshData.vertexVec.data(); HR(m_pd3dDevice->CreateBuffer(&vbd, &InitData, m_pVertexBuffer.GetAddressOf())); // 输入装配阶段的顶点缓冲区设置 UINT stride = sizeof(VertexType); // 跨越字节数 UINT offset = 0; // 起始偏移量 m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset); // 设置索引缓冲区描述 m_IndexCount = (UINT)meshData.indexVec.size(); D3D11_BUFFER_DESC ibd; ZeroMemory(&ibd, sizeof(ibd)); ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(DWORD) * m_IndexCount; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; // 新建索引缓冲区 InitData.pSysMem = meshData.indexVec.data(); HR(m_pd3dDevice->CreateBuffer(&ibd, &InitData, m_pIndexBuffer.GetAddressOf())); // 输入装配阶段的索引缓冲区设置 m_pd3dImmediateContext->IASetIndexBuffer(m_pIndexBuffer.Get(), DXGI_FORMAT_R32_UINT, 0); // 设置调试对象名 D3D11SetDebugObjectName(m_pVertexBuffer.Get(), "VertexBuffer"); D3D11SetDebugObjectName(m_pIndexBuffer.Get(), "IndexBuffer"); return true; }
12,791
6,494
// Copyright 2022 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 "src/ui/scenic/lib/display/display_power_manager.h" #include <fuchsia/ui/display/internal/cpp/fidl.h> #include <lib/async/default.h> #include <lib/async/time.h> #include <thread> #include <unordered_set> #include <gtest/gtest.h> #include "src/lib/testing/loop_fixture/real_loop_fixture.h" #include "src/ui/scenic/lib/display/display_manager.h" #include "src/ui/scenic/lib/display/tests/mock_display_controller.h" namespace scenic_impl { namespace gfx { namespace test { namespace { struct ChannelPair { zx::channel server; zx::channel client; }; ChannelPair CreateChannelPair() { ChannelPair c; FX_CHECK(ZX_OK == zx::channel::create(0, &c.server, &c.client)); return c; } } // namespace class DisplayPowerManagerMockTest : public gtest::RealLoopFixture { public: DisplayPowerManagerMockTest() { display_manager_ = std::make_unique<display::DisplayManager>([] {}); display_power_manager_ = std::make_unique<display::DisplayPowerManager>(display_manager_.get()); } display::DisplayManager* display_manager() { return display_manager_.get(); } display::DisplayPowerManager* display_power_manager() { return display_power_manager_.get(); } display::Display* display() { return display_manager()->default_display(); } private: std::unique_ptr<display::DisplayManager> display_manager_; std::unique_ptr<display::DisplayPowerManager> display_power_manager_; }; TEST_F(DisplayPowerManagerMockTest, Ok) { const uint64_t kDisplayId = 0; const uint32_t kDisplayWidth = 1024; const uint32_t kDisplayHeight = 768; auto controller_channel = CreateChannelPair(); auto device_channel = CreateChannelPair(); display_manager()->BindDefaultDisplayController( fidl::InterfaceHandle<fuchsia::hardware::display::Controller>( std::move(controller_channel.client)), std::move(device_channel.client)); display_manager()->SetDefaultDisplayForTests( std::make_shared<display::Display>(kDisplayId, kDisplayWidth, kDisplayHeight)); display::test::MockDisplayController mock_display_controller; mock_display_controller.Bind(std::move(device_channel.server), std::move(controller_channel.server), dispatcher()); mock_display_controller.set_set_display_power_result(ZX_OK); RunLoopUntilIdle(); { bool callback_executed = false; std::thread set_display_power_thread([&callback_executed, this] { display_power_manager()->SetDisplayPower( /* power_on */ false, [&callback_executed]( fuchsia::ui::display::internal::DisplayPower_SetDisplayPower_Result result) { callback_executed = true; EXPECT_TRUE(result.is_response()); }); }); RunLoopUntil([&callback_executed] { return callback_executed; }); set_display_power_thread.join(); EXPECT_FALSE(mock_display_controller.display_power_on()); } { bool callback_executed = false; std::thread set_display_power_thread([&callback_executed, this] { display_power_manager()->SetDisplayPower( /* power_on */ true, [&callback_executed]( fuchsia::ui::display::internal::DisplayPower_SetDisplayPower_Result result) { callback_executed = true; EXPECT_TRUE(result.is_response()); }); }); RunLoopUntil([&callback_executed] { return callback_executed; }); set_display_power_thread.join(); EXPECT_TRUE(mock_display_controller.display_power_on()); } } TEST_F(DisplayPowerManagerMockTest, NoDisplay) { auto controller_channel = CreateChannelPair(); auto device_channel = CreateChannelPair(); display_manager()->BindDefaultDisplayController( fidl::InterfaceHandle<fuchsia::hardware::display::Controller>( std::move(controller_channel.client)), std::move(device_channel.client)); display_manager()->SetDefaultDisplayForTests(nullptr); display::test::MockDisplayController mock_display_controller; mock_display_controller.Bind(std::move(device_channel.server), std::move(controller_channel.server), dispatcher()); RunLoopUntilIdle(); { bool callback_executed = false; std::thread set_display_power_thread([&callback_executed, this] { display_power_manager()->SetDisplayPower( /* power_on */ false, [&callback_executed]( fuchsia::ui::display::internal::DisplayPower_SetDisplayPower_Result result) { callback_executed = true; ASSERT_TRUE(result.is_err()); EXPECT_EQ(result.err(), ZX_ERR_NOT_FOUND); }); }); RunLoopUntil([&callback_executed] { return callback_executed; }); set_display_power_thread.join(); } } TEST_F(DisplayPowerManagerMockTest, NotSupported) { const uint64_t kDisplayId = 0; const uint32_t kDisplayWidth = 1024; const uint32_t kDisplayHeight = 768; auto controller_channel = CreateChannelPair(); auto device_channel = CreateChannelPair(); display_manager()->BindDefaultDisplayController( fidl::InterfaceHandle<fuchsia::hardware::display::Controller>( std::move(controller_channel.client)), std::move(device_channel.client)); display_manager()->SetDefaultDisplayForTests( std::make_shared<display::Display>(kDisplayId, kDisplayWidth, kDisplayHeight)); display::test::MockDisplayController mock_display_controller; mock_display_controller.Bind(std::move(device_channel.server), std::move(controller_channel.server), dispatcher()); mock_display_controller.set_set_display_power_result(ZX_ERR_NOT_SUPPORTED); RunLoopUntilIdle(); { bool callback_executed = false; std::thread set_display_power_thread([&callback_executed, this] { display_power_manager()->SetDisplayPower( /* power_on */ false, [&callback_executed]( fuchsia::ui::display::internal::DisplayPower_SetDisplayPower_Result result) { callback_executed = true; EXPECT_TRUE(result.is_err()); EXPECT_EQ(result.err(), ZX_ERR_NOT_SUPPORTED); }); }); RunLoopUntil([&callback_executed] { return callback_executed; }); set_display_power_thread.join(); } } } // namespace test } // namespace gfx } // namespace scenic_impl
6,478
1,965
/* * Copyright 2018 by Marco Martin <mart@kde.org> * * 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 "abstractdelegate.h" #include "mycroftcontroller.h" #include <QQmlEngine> #include <QQmlContext> DelegateLoader::DelegateLoader(AbstractSkillView *parent) : QObject(parent), m_view(parent) {} DelegateLoader::~DelegateLoader() { if (m_delegate) { m_delegate->deleteLater(); } } void DelegateLoader::init(const QString skillId, const QUrl &delegateUrl) { if (!m_skillId.isEmpty()) { qWarning() << "Init already called"; } m_skillId = skillId; m_delegateUrl = delegateUrl; QQmlEngine *engine = qmlEngine(m_view); //This class should be *ALWAYS* created from QML Q_ASSERT(engine); m_component = new QQmlComponent(engine, delegateUrl, m_view); switch(m_component->status()) { case QQmlComponent::Error: qWarning() << "ERROR Loading QML file" << delegateUrl; for (auto err : m_component->errors()) { qWarning() << err.toString(); } break; case QQmlComponent::Ready: createObject(); break; case QQmlComponent::Loading: connect(m_component, &QQmlComponent::statusChanged, this, &DelegateLoader::createObject); break; default: break; } } void DelegateLoader::createObject() { QQmlContext *context = QQmlEngine::contextForObject(m_view); //This class should be *ALWAYS* created from QML Q_ASSERT(context); QObject *guiObject = m_component->beginCreate(context); m_delegate = qobject_cast<AbstractDelegate *>(guiObject); if (m_component->isError()) { qWarning() << "ERROR Loading QML file" << m_delegateUrl; for (auto err : m_component->errors()) { qWarning() << err.toString(); } return; } if (!m_delegate) { qWarning()<<"ERROR: QML gui" << guiObject << "not a Mycroft.AbstractDelegate instance"; guiObject->deleteLater(); return; } connect(m_delegate, &QObject::destroyed, this, &QObject::deleteLater); m_delegate->setSkillId(m_skillId); m_delegate->setQmlUrl(m_delegateUrl); m_delegate->setSkillView(m_view); m_delegate->setSessionData(m_view->sessionDataForSkill(m_skillId)); m_component->completeCreate(); emit delegateCreated(); if (m_focus) { m_delegate->forceActiveFocus((Qt::FocusReason)AbstractSkillView::ServerEventFocusReason); } }; AbstractDelegate *DelegateLoader::delegate() { return m_delegate; } void DelegateLoader::setFocus(bool focus) { m_focus = focus; if (m_delegate && focus) { m_delegate->forceActiveFocus((Qt::FocusReason)AbstractSkillView::ServerEventFocusReason); } else if (m_delegate) { m_delegate->setFocus(false); } } ////////////////////////////////////////// AbstractDelegate::AbstractDelegate(QQuickItem *parent) : QQuickItem(parent) { setFiltersChildMouseEvents(true); setFlags(QQuickItem::ItemIsFocusScope); setAcceptedMouseButtons(Qt::LeftButton); } AbstractDelegate::~AbstractDelegate() { } void AbstractDelegate::triggerGuiEvent(const QString &eventName, const QVariantMap &parameters) { if (!m_skillView) { qWarning() << "No SkillView, this should never happen: orphan delegate?"; return; } if (eventName.startsWith(QStringLiteral("system."))) { m_skillView->triggerEvent(QStringLiteral("system"), eventName, parameters); } else { m_skillView->triggerEvent(m_skillId, eventName, parameters); } } void AbstractDelegate::syncChildItemsGeometry(const QSizeF &size) { if (m_contentItem) { m_contentItem->setX(m_leftPadding); m_contentItem->setY(m_topPadding); if (m_contentItemAutoWidth && m_contentItemAutoHeight) { m_contentItem->setSize(QSizeF(size.width() - m_leftPadding - m_rightPadding, size.height() - m_topPadding - m_bottomPadding)); } else if (m_contentItemAutoWidth) { m_contentItem->setWidth(size.width() - m_leftPadding - m_rightPadding); } else if (m_contentItemAutoHeight) { m_contentItem->setHeight(size.height() - m_topPadding - m_bottomPadding); } } if (m_backgroundItem) { m_backgroundItem->setX(0); m_backgroundItem->setY(0); m_backgroundItem->setSize(size); } } void AbstractDelegate::contentData_append(QQmlListProperty<QObject> *prop, QObject *object) { AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object); if (!delegate) { return; } // QQuickItem *item = qobject_cast<QQuickItem *>(object); delegate->m_contentData.append(object); } int AbstractDelegate::contentData_count(QQmlListProperty<QObject> *prop) { AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object); if (!delegate) { return 0; } return delegate->m_contentData.count(); } QObject *AbstractDelegate::contentData_at(QQmlListProperty<QObject> *prop, int index) { AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object); if (!delegate) { return nullptr; } if (index < 0 || index >= delegate->m_contentData.count()) { return nullptr; } return delegate->m_contentData.value(index); } void AbstractDelegate::contentData_clear(QQmlListProperty<QObject> *prop) { AbstractDelegate *delegate = static_cast<AbstractDelegate *>(prop->object); if (!delegate) { return; } return delegate->m_contentData.clear(); } QQmlListProperty<QObject> AbstractDelegate::contentData() { return QQmlListProperty<QObject>(this, nullptr, contentData_append, contentData_count, contentData_at, contentData_clear); } void AbstractDelegate::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { syncChildItemsGeometry(newGeometry.size()); QQuickItem::geometryChanged(newGeometry, oldGeometry); emit contentWidthChanged(); emit contentHeightChanged(); } void AbstractDelegate::componentComplete() { if (!m_contentItem) { //qWarning()<<"Creting default contentItem"; m_contentItem = new QQuickItem(this); } QQuickItem *item; for (auto *o : m_contentData) { item = qobject_cast<QQuickItem *>(o); if (item) { item->setParentItem(m_contentItem); } else { o->setParent(this); } } QQuickItem::componentComplete(); } bool AbstractDelegate::childMouseEventFilter(QQuickItem *item, QEvent *event) { if (event->type() == QEvent::MouseButtonPress) { forceActiveFocus(Qt::MouseFocusReason); triggerGuiEvent(QStringLiteral("system.gui.user.interaction"), QVariantMap()); } return QQuickItem::childMouseEventFilter(item, event); } void AbstractDelegate::mousePressEvent(QMouseEvent *event) { forceActiveFocus(Qt::MouseFocusReason); triggerGuiEvent(QStringLiteral("system.gui.user.interaction"), QVariantMap()); } void AbstractDelegate::focusInEvent(QFocusEvent *event) { //if the focus came from the server, don't ask the server again if (event->reason() == (Qt::FocusReason)AbstractSkillView::ServerEventFocusReason) { return; } if (!parentItem()) { return; } QQmlContext *context = QQmlEngine::contextForObject(parentItem()); if (!context) { return; } int index = context->contextProperty(QStringLiteral("index")).toInt(); if (index >= 0) { triggerGuiEvent(QStringLiteral("page_gained_focus"), QVariantMap({{QStringLiteral("number"), index}})); } } QQuickItem *AbstractDelegate::contentItem() const { return m_contentItem; } void AbstractDelegate::setContentItem(QQuickItem *item) { if (m_contentItem == item) { return; } m_contentItem = item; item->setParentItem(this); m_contentItem->setX(m_leftPadding); m_contentItem->setY(m_topPadding); if (m_contentItemAutoWidth && m_contentItemAutoHeight) { m_contentItem->setSize(QSizeF(width() - m_leftPadding - m_rightPadding, height() - m_topPadding - m_bottomPadding)); } else if (m_contentItemAutoWidth) { m_contentItem->setWidth(width() - m_leftPadding - m_rightPadding); } else if (m_contentItemAutoHeight) { m_contentItem->setHeight(height() - m_topPadding - m_bottomPadding); } emit contentItemChanged(); } QQuickItem *AbstractDelegate::background() const { return m_backgroundItem; } void AbstractDelegate::setBackground(QQuickItem *item) { if (m_backgroundItem == item) { return; } m_backgroundItem = item; m_backgroundItem->setParentItem(this); m_backgroundItem->setX(0); m_backgroundItem->setY(0); m_backgroundItem->setSize(size()); emit backgroundChanged(); } int AbstractDelegate::leftPadding() const { return m_leftPadding; } void AbstractDelegate::setLeftPadding(int padding) { if (m_leftPadding == padding) { return; } m_leftPadding = padding; syncChildItemsGeometry(size()); emit leftPaddingChanged(); emit contentWidthChanged(); } int AbstractDelegate::topPadding() const { return m_topPadding; } void AbstractDelegate::setTopPadding(int padding) { if (m_topPadding == padding) { return; } m_topPadding = padding; syncChildItemsGeometry(size()); emit topPaddingChanged(); emit contentHeightChanged(); } int AbstractDelegate::rightPadding() const { return m_rightPadding; } void AbstractDelegate::setRightPadding(int padding) { if (m_rightPadding == padding) { return; } m_rightPadding = padding; syncChildItemsGeometry(size()); emit rightPaddingChanged(); emit contentWidthChanged(); } int AbstractDelegate::bottomPadding() const { return m_bottomPadding; } void AbstractDelegate::setBottomPadding(int padding) { if (m_bottomPadding == padding) { return; } m_bottomPadding = padding; syncChildItemsGeometry(size()); emit bottomPaddingChanged(); emit contentHeightChanged(); } int AbstractDelegate::contentWidth() const { return width() - m_leftPadding - m_rightPadding; } int AbstractDelegate::contentHeight() const { return height() - m_topPadding - m_bottomPadding; } void AbstractDelegate::setSkillView(AbstractSkillView *view) { //possible to call only once, by the skillview, setting itself upon instantiation Q_ASSERT(!m_skillView); m_skillView = view; } AbstractSkillView *AbstractDelegate::skillView() const { return m_skillView; } void AbstractDelegate::setSessionData(SessionDataMap *data) { //possible to call only once, by the skillview upon instantiation Q_ASSERT(!m_data); m_data = data; } SessionDataMap *AbstractDelegate::sessionData() const { return m_data; } void AbstractDelegate::setQmlUrl(const QUrl &url) { //possible to call only once, by the skillview upon instantiation Q_ASSERT(m_qmlUrl.isEmpty()); m_qmlUrl = url; } QUrl AbstractDelegate::qmlUrl() const { return m_qmlUrl; } void AbstractDelegate::setSkillId(const QString &skillId) { //possible to call only once, by the skillview upon instantiation Q_ASSERT(m_skillId.isEmpty()); m_skillId = skillId; } QString AbstractDelegate::skillId() const { return m_skillId; } #include "moc_abstractdelegate.cpp"
12,109
3,801
#include <algorithm> #include <iostream> #include <queue> #include <set> #include <stdio.h> #include <string.h> #include <string> #include <vector> #define MAX_L 1005 #define INF 0xffffff #define LL long long using namespace std; int G[MAX_L][MAX_L]; int dis[MAX_L][MAX_L]; LL t, s, d, n = 0; int start[MAX_L]; int dest[MAX_L]; void init() { // 未清 0 // start.clear(); // dest.clear(); fill(G[0], G[0] + MAX_L * MAX_L, INF); fill(dis[0], dis[0] + MAX_L * MAX_L, INF); for (int i = 0; i < MAX_L; i++) { G[i][i] = 0; dis[i][i] = 0; } } void floyd() { for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { if (G[k][i] == INF) { continue; } for (int j = 0; j < n; j++) { dis[i][j] = min(dis[i][k] + dis[k][j], dis[i][j]); } } } } int main() { while (~scanf("%lld %lld %lld", &t, &s, &d)) { init(); for (int i = 0; i < t; i++) { LL a, b, c; cin >> a >> b >> c; a--; b--; if (c < G[a][b]) { G[a][b] = G[b][a] = dis[a][b] = dis[b][a] = c; } n = max(n, max(a, b)); } LL temp; for (int i = 0; i < s;i++){ cin >> temp; start[i] = temp - 1; } for (int i = 0; i < d; i++) { cin >> temp; dest[i] = temp - 1; } // while (s--) { // cin >> temp; // start.push_back(temp - 1); // } // while (d--) { // cin >> temp; // dest.push_back(temp - 1); // } floyd(); int mint = INF; for (int i = 0; i < s;i++){ for (int j = 0; j < d;j++){ mint = min(mint, dis[start[i]][dest[j]]); } } // for (auto i : start) { // for (auto j : dest) { // mint = min(mint, dis[i][j]); // } // } cout << mint << endl; } return 0; }
1,652
920
#include <bits/stdc++.h> using namespace std; int main() { int testCases; cin >> testCases; while (testCases--) { long long int A,Y,X; cin>>A>>Y>>X; if( Y>A ) { cout<<X*A +1<<endl; } else if(Y<=A) { cout<<X*Y <<endl; } } return 0; }
363
142
// // Copyright (c) 2020 Erwin Rol <erwin@erwinrol.com> // // SPDX-License-Identifier: MIT // #ifndef NEDERROCK_SRC_AND_PARSER_NODE_HPP #define NEDERROCK_SRC_AND_PARSER_NODE_HPP #include "and_parser_node_pre.hpp" #include "separator_parser_node_pre.hpp" #include "equality_check_parser_node_pre.hpp" #include "token_stream.hpp" #include "scope_state.hpp" #include <memory> #include <istream> #include <string> #include <variant> class And_Parser_Node { public: struct Choice_1 { void dump(std::wostream& output) const; void generate_cpp(Scope_State_Ptr state) const; void collect_variables(Scope_State_Ptr state) const; Equality_Check_Parser_Node_Ptr m_equality; Separator_Parser_Node_Ptr m_separator_1; std::wstring m_keyword; Separator_Parser_Node_Ptr m_separator_2; And_Parser_Node_Ptr m_and; }; struct Choice_2 { void dump(std::wostream& output) const; void generate_cpp(Scope_State_Ptr state) const; void collect_variables(Scope_State_Ptr state) const; Equality_Check_Parser_Node_Ptr m_equality; }; public: And_Parser_Node(Choice_1&& choice); And_Parser_Node(Choice_2&& choice); static And_Parser_Node_Ptr parse_choice_1(Token_Stream& input); static And_Parser_Node_Ptr parse_choice_2(Token_Stream& input); static And_Parser_Node_Ptr parse(Token_Stream& input); void dump(std::wostream& output) const; void generate_cpp(Scope_State_Ptr state) const; void collect_variables(Scope_State_Ptr state) const; private: std::variant<Choice_1, Choice_2> m_choice; }; #endif // NEDERROCK_SRC_AND_PARSER_NODE_HPP
1,636
599
// NewEditBox.cpp : implementation file // #include "stdafx.h" #include "Magenta.h" #include "Constants.h" #include "Person.h" #include "NewEditBox.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CNewEditBox CNewEditBox::CNewEditBox() { // Basic initialization... m_iSelStart = 0; m_iSelLength = 0; } CNewEditBox::~CNewEditBox() { } BEGIN_MESSAGE_MAP(CNewEditBox, CEdit) //{{AFX_MSG_MAP(CNewEditBox) ON_WM_KEYUP() ON_WM_KEYDOWN() ON_WM_CHAR() ON_MESSAGE(WM_UNINITMENUPOPUP, OnUninitPopup) //}}AFX_MSG_MAP END_MESSAGE_MAP() // Processes an autocomplete request. void CNewEditBox::ProcessAutoComplete() { int i; INT_PTR iCount = 0; int iMatches = 0; int iStart, iEnd, iMiddle; CString szText; CString szName, szItem, szTemp; CPoint ptCursor; GetSel(iStart, iMiddle); // Get the position of the cursor (considered to be iMiddle) GetWindowText(szText); // Also grab ahold of the text in the window. // Prepare the menu if(m_mnuAuto.GetSafeHmenu() != NULL) m_mnuAuto.DestroyMenu(); if(!m_mnuAuto.CreatePopupMenu()) { AfxMessageBox(_T("Unable to generate menu for Tab Complete!"), MB_ICONSTOP | MB_OK); return; } // Look for the start of the string. if(iMiddle > 0) iStart = FindRev(szText, " ", iMiddle - 1); else iStart = FindRev(szText, " ", 0); if(iStart == -1) iStart = 0; iEnd = szText.Find(_T(" "), iMiddle + 1); if(iEnd == -1) iEnd = szText.GetLength(); SetSel(iStart, iEnd); // Cosmetic reasons. szName = szText.Mid(iStart, iEnd - iStart); // Because MFC won't give us the selected text..>< if(szName.GetLength() > 0) { //iCount = m_plstRegulars->GetCount(); iCount = m_pcolUsers->GetSize(); iMatches = 0; m_pcsUsers->Lock(); //szName.MakeUpper(); for(i = 0; i < iCount; i++) { szItem = ((CPerson*)m_pcolUsers->GetAt(i))->szName; //m_plstRegulars->GetText(i, szItem); szTemp = szItem; //szTemp.MakeUpper(); if(szTemp.Left(szName.GetLength()).CompareNoCase(szName) == 0) { // We matched. Add one, and add it to the list. iMatches++; if(iMatches <= MATCH_LIMIT) { //m_plstOutput->AddString(szItem); m_mnuAuto.AppendMenu(MF_STRING, ID_AUTO_BASE + iMatches, szItem); } } } m_pcsUsers->Unlock(); if(iMatches > 1) { // Lock the text in the message textbox and let them choose a completion. SetReadOnly(TRUE); // Cache selection info m_iSelStart = iStart; m_iSelLength = iEnd - iStart; // Get the insertion point position and popup the menu right where it is. ptCursor = GetCaretPos(); ClientToScreen(&ptCursor); m_mnuAuto.TrackPopupMenu(TPM_CENTERALIGN | TPM_LEFTBUTTON, ptCursor.x, ptCursor.y, this); } else if(iMatches == 1) { // Merely paste in the last item. m_mnuAuto.GetMenuString(0, szItem, MF_BYPOSITION); m_mnuAuto.DestroyMenu(); ReplaceSel(szItem); } // Fix the selection start. GetWindowText(szText); SetSel(szText.GetLength(), szText.GetLength()); } } // Searches for a substring starting at the end of a string. int CNewEditBox::FindRev(CString szString, CString szFind, int iStart) { int iRet = -1; int iPos, iLen; // Reverse the strings... szString.MakeReverse(); szFind.MakeReverse(); iLen = szString.GetLength(); iPos = szString.Find(szFind, iLen - iStart - 1); if(iPos != -1) iRet = szString.GetLength() - iPos - szFind.GetLength() + 1; return iRet; } ///////////////////////////////////////////////////////////////////////////// // CNewEditBox message handlers void CNewEditBox::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { switch(nChar) { case VK_ESCAPE: if(!m_bHadMenu) { // We want to clear it. SetWindowText(_T("")); } else { m_bHadMenu = FALSE; // This flag only makes sense for this case, so far. } break; case VK_TAB: ProcessAutoComplete(); break; default: // Nothing to do... break; } // Call default CEdit::OnKeyUp(nChar, nRepCnt, nFlags); } void CNewEditBox::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // Doggone tabs! Don't process unless I say so! if(nChar != VK_TAB) CEdit::OnKeyDown(nChar, nRepCnt, nFlags); } void CNewEditBox::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // Another attempt to keep tabs from processing... if(nChar != VK_TAB) CEdit::OnChar(nChar, nRepCnt, nFlags); } BOOL CNewEditBox::OnCommand(WPARAM wParam, LPARAM lParam) { int iID; CString szItem; CString szMessage; iID = LOWORD(wParam); // Get the command ID. (which should be from the menu) if(iID & ID_AUTO_BASE) { // It's one of our popups, all right... m_mnuAuto.GetMenuString(iID, szItem, MF_BYCOMMAND); ASSERT(szItem.GetLength() > 0); SetSel(m_iSelStart, m_iSelLength + m_iSelStart); ReplaceSel(szItem); SetReadOnly(FALSE); m_mnuAuto.DestroyMenu(); } return CEdit::OnCommand(wParam, lParam); } LRESULT CNewEditBox::OnUninitPopup(WPARAM wParam, LPARAM lParam) { // Hm, let's see....we can try to do this this way. o.o // Unfortunately, now my program doesn't work on Win95, but // who uses Win95 anymore, anyway? if((HMENU)wParam == m_mnuAuto.GetSafeHmenu()) { SetReadOnly(FALSE); m_bHadMenu = TRUE; } return 0; }
5,496
2,312
#pragma once #include <string> #include <list> #include <vector> /*! * \file lacze_do_gnuplota.hh * * Plik zawiera definicję klasy realizującej interfejs * komunikacyjny do programu gnuplot. */ /*! * \brief Moduł narzędzi umożliwiających połącznie z GNUPlotem * * Niniejsza przestrzeń nazw stanowi moduł logiczny zawierający * narzędzia umożliwiające realizację połączenia z programem \p gnuplot. */ namespace PzG { /*! * \brief Określa tryb rysowania realizowanego przez program \p gnuplot * * Typ wyliczeniowy określające dopuszczalne tryby rysowania * realizowanego przez program \p gnuplot. Wybór trybu wiąże się * ze zmianą sposobu interpretacji danych zawartych pliku. Jeśli * np. wybrany zostanie tryb 2D, to zakłada się, że w każdej linii * pliku z danymi znajdują się wartości współrzędnych \e x, \e y. * Wartości typu: * \li \p TR_2D - rysowanie w trybie 2D, co sprowadza się do * rysowania wykresów funkcji jednej zmiennej. * \li \p TR_3D - rysowanie w trybie 3D. Oznacza to możliwość * rysowania wykresów funkcji dwóch zmiennych. * */ enum TrybRysowania { TR_2D, TR_3D }; /*! * \brief Sposób rysowania linii * * Określa sposób rysowania linii. */ enum RodzajRysowania { RR_Ciagly, RR_Punktowy }; /*! * \brief Zestaw informacji dotyczący pliku i sposobu rysowania * * Klasa modeluje zestaw informacji dotyczący pliku i sposobu * w jaki mają być wizualizowane zawarte w nim dane. */ class InfoPlikuDoRysowania { public: /*! * Inicjalizuje obiekt. * \param NazwaPliku - nazwa pliku, z którego pobierane będą dane, * \param RodzRys - rodzaj rysowania linii, * \param Szerokosc - szerokosc linii. */ InfoPlikuDoRysowania(const char* NazwaPliku, RodzajRysowania RodzRys, int Szerokosc) { _NazwaPliku = NazwaPliku; _RodzRys = RodzRys; _Szerokosc = Szerokosc; } /*! * \brief Udostępia nazwę pliku do rysowania * * Udostępnia nazwę pliku z danymi do rysowania. */ const std::string WezNazwePliku() const { return _NazwaPliku; } /*! * \brief Zmienia nazwę pliku do rysowania * * Zmienia nazwę pliku z danymi do rysowania. */ void ZmienNazwePliku(const std::string& NazwaPliku) { _NazwaPliku = NazwaPliku; } /*! * \brief Udostępnia sposób rysowanej linii * * Udostępnia informację o sposóbie rysowania linii. */ RodzajRysowania WezRodzRys() const { return _RodzRys; } /*! * \brief Udostępnia informację o szerokości linii. * * Udostępnia informację o szerokości rysowanej linii. */ int WezSzerokosc() const { return _Szerokosc; } private: /*! * \brief Nazwa pliku z danymi do rysowania * * Nazwa pliku z danymi do rysowania. */ std::string _NazwaPliku; /*! * \brief Szerokość użytego piórka * * Określa szerokość piórka, jakie ma być użyte * do rysowania obiektów graficznych. */ int _Szerokosc; /*! * \brief Sposób rysowania danej linii * * Przechowuje informacje o sposobie rysowania linii. */ RodzajRysowania _RodzRys; }; /*! * \brief Klasa realizuje interfejs do programu GNUPlot. * * Klasa realizuje interfejs do programu GNUPlot. Pozwala ona na wskazanie * zbioru punktów płaszczyzn umieszczonych w pliku lub plikach. * Każdy taki zbiór może być następnie wizualizowany przez program * gnuplot w postaci oddzielnych płaszczyzn z wycinaniem części zasłanianych. */ class LaczeDoGNUPlota { protected: /*! * \brief Lista nazw plików z danymi dla \e gnuplota. * * Pole jest zarządcą listy nazw plików, z których są wczytywane * dane dotyczące rysowania obrysu brył przez program \e gnuplot. * Operacja ta wykonywana jest po wywołaniu polecenia. * \link LaczeDoGNUPlota::Rysuj Rysuj\endlink. */ static std::list<InfoPlikuDoRysowania> _InfoPlikow; /*! * Pole przechowuje deskryptor do wejścia standardowego uruchomionego * programu gnuplot. */ int _Wejscie_GNUPlota; /*! * Pole przechowuje deskryptor do weyjścia standardowego uruchomionego * programu gnuplot. */ int _Wyjscie_GNUPlota; /*! * \brief Decyduje czy mają być wyświetlane komunikaty o błędach, * czy też nie. * * Wartość tego pola decyduje o tym czy komunikaty o błędach będą * wyświetlane na wyjście standardowe błędów (\b cerr), czy też nie. * \li \p true - komunikaty będę wyświetlane, * \li \p false - komunikaty nie będę wyświetlane. */ bool _WyswietlajKomunikatyOBledach; /*! * \brief Określa aktualny tryb rysowania * * Zawartość pola determinuje sposób rysowania, jaki zostanie * wymuszony na programie \p gnuplot poprzez wysłanie do niego * odpowiednich poleceń. Wspomniane wymuszenie jest realizowane * poprzez wywołanie polecenia * \link LaczeDoGNUPlota::Rysuj Rysuj()\endlink */ TrybRysowania _TrybRys; /*! * \brief Dolny zakres wyświetlanej skali skali dla osi \e OX. * * Określa dolny zakres wyświetlanej skali dla osi \e OX. */ float _Xmin; /*! * \brief Górny zakres wyświetlanej skali skali dla osi \e OX. * * Określa górny zakres wyświetlanej skali dla osi \e OX. */ float _Xmax; /*! * \brief Dolny zakres wyświetlanej skali skali dla osi \e OY. * * Określa dolny zakres wyświetlanej skali dla osi \e OY. */ float _Ymin; /*! * \brief Górny zakres wyświetlanej skali skali dla osi \e OY. * * Określa górny zakres wyświetlanej skali dla osi \e OY. */ float _Ymax; /*! * \brief Dolny zakres wyświetlanej skali skali dla osi \e OZ. * * Określa dolny zakres wyświetlanej skali dla osi \e OZ. */ float _Zmin; /*! * \brief Górny zakres wyświetlanej skali skali dla osi \e OZ. * * Określa górny zakres wyświetlanej skali dla osi \e OZ. */ float _Zmax; /*! * Wartość tego pola definiuje skalowanie rysunku wzdłuż osi * \e OX (oś horyzontalna ekranu). */ float _Xskala; /*! * Wartość tego pola definiuje skalowanie rysunku wzdłuż osi * \e OZ (oś wertykalna ekranu). */ float _Zskala; /*! * Wartość tego pola definiuje rotację rysunku (zmiane punktu patrzenia) * względem osi \e OX. */ float _Xrotacja; /*! * Wartość tego pola definiuje rotację rysunku (zmiane punktu patrzenia) * względem osi \e OZ. */ float _Zrotacja; /*! * \brief Czy oś OX ma być widoczna * * Przechowuje informację decydującą o tym czy oś OX będzie * widoczna na rysunku (\p true), czy też nie (\p false). */ bool _PokazOs_OX; /*! * \brief Czy oś OY ma być widoczna * * Przechowuje informację decydującą o tym czy oś OY będzie * widoczna na rysunku (\p true), czy też nie (\p false). */ bool _PokazOs_OY; /*! * \brief Czy oś OZ ma być widoczna * * Przechowuje informację decydującą o tym czy oś OZ będzie * widoczna na rysunku (\p true), czy też nie (\p false). */ bool _PokazOs_OZ; /*! * \brief Tworzy listę parametrów umożliwiających rysowanie dodatkowych elementów * * Metoda ta przewidziana jest jako element rozszerzenia pozwalającego * w klasach pochodnych powiększyć listę rysowanych elementów. * \pre Parametr \e Polecenie powinien zawierać polecenie \e plot lub \e splot, * do którego będzie możliwe dopisanie dalszego ciągu. * \param Polecenie - polecenie rysowania, do którego mają być dopisane * nazwy plików i odpowiednie parametry dla polecenia plot. * \param Sep - zawiera znak separatora między poszczególnymi * parametrami. Jeżeli parametry listy przeszkód * są generowane jako pierwsze, to zmienna ta musi * być wskaźnikiem do wskaźnika na łańcuch: " ". */ virtual bool DopiszPlikiDoPoleceniaRysowania( std::string &Polecenie, char const **Sep ); /*! * \brief Tworzy polecenie ustawiające zakres dla danej współrzędnej. * * Tworzy polecenie dla programu \e gnuplot ustawiające zakres * współrzędnych wybranej współrzędnej \e x, \e y lub \e z, * dla której ma być tworzony dany rysunek. * \param Os - zawiera znak określający współrzędną, dla której * ma zostać wygenerowane polecenie ustawienia zakresu. * \return łańcuch znaków polecenia ustawiającego żądany zakres * dla wybranej współrzędnej. */ std::string ZapiszUstawienieZakresu(char Os) const; /*! * \brief Tworzy polecenie ustawiające punkt obserwacji. * * Tworzy polecenie dla programu \e gnuplot ustawiajające punkt obserwacji * poprzez zadanie rotacji i skali dla poszczególnych osi. */ std::string ZapiszUstawienieRotacjiISkali() const; /*! * Przesyła na wejście programu \e gnuplot zadany ciąg znaków. * \param Polecenie - komunikat przeznaczony do przeslania. * * \pre Musi być zainicjowane połączenie z programem gnuplot. * * \retval true - jesli przeslanie polecenia zakończyło się powodzeniem, * \retval false - w przypadku przeciwnym. * */ bool PrzeslijDoGNUPlota(const char *Polecenie); /*! * \brief Udostępnia informację czy mają być wyświetlane informacje o błędach. * * Udostępnia wartość pola * \link LaczeDoGNUPlota::_WyswietlajKomunikatyOBledach * _WyswietlajKomunikatyOBledach\endlink. * Określa ono, czy mają być wyświetlane komunikaty o błędach na wyjście * standardowe, czy też nie. */ bool CzyWyswietlacKomunikaty() const { return _WyswietlajKomunikatyOBledach;} /*! * \brief Uruchamia program \e gnuplot jako proces potomny. */ bool UtworzProcesPotomny(); /*! * Wyświetla na wyjście "standard error" komunikat (przekazany jako * parametr), o ile pole * \link LaczeDoGNUPlota::_WyswietlajKomunikatyOBledach * _WyswietlajKomunikatyOBledach\endlink ma wartość * \p true. W przypadku przeciwnym komunikat nie jest wyświetlany. */ void KomunikatBledu(const char *Komunikat) const; /*! * \brief Tworzy preambułę poprzedzającą polecenie rysowania * * Tworzy zbiór poleceń, które ustawiają właściwy tryb rysowania * oraz zakresy współrzędnych, jak też wszystkie inne parametry * wynikające z przyjętego trybu rysowania. */ void BudujPreambulePoleceniaRysowania(std::string &Preambula) const; /*! * \brief Tworzy preambułę poprzedzającą polecenie rysowania w trybie 2D * * Tworzy zbiór poleceń, które ustawiają właściwy tryb rysowania * oraz zakresy współrzędnych, jak też wszystkie inne parametry * wynikające z trybu rysowania 2D. */ void BudujPreambule_2D(std::string &Preambula) const; /*! * \brief Tworzy preambułę poprzedzającą polecenie rysowania w trybie 3D * * Tworzy zbiór poleceń, które ustawiają właściwy tryb rysowania * oraz zakresy współrzędnych, jak też wszystkie inne parametry * wynikające z trybu rysowania 3D. */ void BudujPreambule_3D(std::string &Preambula) const; public: /*! * \brief Umożliwia lub zabrania rysowania osi OX * * Umożliwia lub zabrania rysowania osi \e OX na rysunku wykresu. * \param Pokaz - decyduje o tym czy oś \e OX będzie rysowana (\p true), * czy też nie (\p false). */ void PokazOs_OX(bool Pokaz) { _PokazOs_OX = Pokaz; } /*! * \brief Czy oś OX ma być rysowana * * Udostępnia informację czy oś \e OX ma być rysowana, * czy też nie. * \retval true - gdy oś \e OX ma być rysowana, * \retval false - w przypadku przeciwnym. */ bool PokazOs_OX() const { return _PokazOs_OX; } /*! * \brief Umożliwia lub zabrania rysowania osi OY * * Umożliwia lub zabrania rysowania osi \e OY na rysunku wykresu. * \param Pokaz - decyduje o tym czy oś \e OY będzie rysowana (\p true), * czy też nie (\p false). */ void PokazOs_OY(bool Pokaz) { _PokazOs_OY = Pokaz; } /*! * \brief Czy oś OY ma być rysowana * * Udostępnia informację czy oś \e OY ma być rysowana, * czy też nie. * \retval true - gdy oś \e OY ma być rysowana, * \retval false - w przypadku przeciwnym. */ bool PokazOs_OY() const { return _PokazOs_OY; } /*! * \brief Umożliwia lub zabrania rysowania osi OZ * * Umożliwia lub zabrania rysowania osi \e OZ na rysunku wykresu. * \param Pokaz - decyduje o tym czy oś \e OZ będzie rysowana (\p true), * czy też nie (\p false). */ void PokazOs_OZ(bool Pokaz) { _PokazOs_OZ = Pokaz; } /*! * \brief Czy oś OZ ma być rysowana * * Udostępnia informację czy oś \e OZ ma być rysowana, * czy też nie. * \retval true - gdy oś \e OZ ma być rysowana, * \retval false - w przypadku przeciwnym. */ bool PokazOs_OZ() const { return _PokazOs_OZ; } /*! * Udostępnia dolną wartość zakresu skali wzdłuż osi \e OX. */ float Xmin() const { return _Xmin; } /*! * Udostępnia górną wartość zakresu skali wzdłuż osi \e OX. */ float Xmax() const { return _Xmax; } /*! * Udostępnia dolną wartość zakresu skali wzdłuż osi \e OY. */ float Ymin() const { return _Ymin; } /*! * Udostępnia górną wartość zakresu skali wzdłuż osi \e OY. */ float Ymax() const { return _Ymax; } /*! * Udostępnia dolną wartość zakresu skali wzdłuż osi \e OZ. */ float Zmin() const { return _Zmin; } /*! * Udostępnia górną wartość zakresu skali wzdłuż osi \e OZ. */ float Zmax() const { return _Zmax; } /*! * \brief Zmienia tryb rysowania * * Zmienia tryb rysowania jaki zostanie wymuszony na programie * \p gnuplot. * \param Tryb - wartość parametru określa nowy tryb rysowania. */ void ZmienTrybRys(TrybRysowania Tryb) { _TrybRys = Tryb; } /*! * \brief Udostępnia aktualny tryb rysowania * * Udostępnia informację o aktualnym trybie rysowania. */ TrybRysowania WezTrybRys() const { return _TrybRys; } /*! * \brief Ustawia zakres osi \e OX * * Ustawia zakres osi \e OX. Ogranicza to obszar, który będzie * zwizualizowany przez programa \e gnuplot. * \param Xo - dolna granica obszaru rysowania dla osi \e OX. * \param Xn - górna granica obszaru rysowania dla osi \e OX. */ void UstawZakresX(float Xo, float Xn) { _Xmin = Xo; _Xmax = Xn; } /*! * \brief Ustawia zakres osi \e OY * * Ustawia zakres osi \e OY. Ogranicza to obszar, który będzie * zwizualizowany przez programa \e gnuplot. * \param Yo - dolna granica obszaru rysowania dla osi \e OY. * \param Yn - górna granica obszaru rysowania dla osi \e OY. */ void UstawZakresY(float Yo, float Yn) { _Ymin = Yo; _Ymax = Yn; } /*! * \brief Ustawia zakres osi \e OZ. * * Ustawia zakres osi \e OZ. Ogranicza to obszar, który będzie * zwizualizowany przez programa \e gnuplot. * \param Zo - dolna granica obszaru rysowania dla osi \e OZ. * \param Zn - górna granica obszaru rysowania dla osi \e OZ. */ void UstawZakresZ(float Zo, float Zn) { _Zmin = Zo; _Zmax = Zn; } /*! * \brief Udostępnia skalę dla osi \e OX. * * Udostępnia skalę dla osi \e OX dla tworzonego rysunku. */ float SkalaX() const { return _Xskala; } /*! * \brief Udostępnia skalę dla osi \e OZ. * * Udostępnia skalę dla osi \e OZ dla tworzonego rysunku. */ float SkalaZ() const { return _Zskala; } /*! * \brief Zadaje skalę wzdłuż osi \e OZ. * * Zadaje skalę wzdłuż osi \e OX dla tworzonego rysunku. * \param skala_x - skala wzdłuż osi \e OX. */ void UstawSkaleX( float skala_x ) { _Xskala = skala_x; } /*! * \brief Zadaje skalę wzdłuż osi \e OZ. * * Zadaje skalę wzdłuż osi \e OZ dla tworzonego rysunku. * \param skala_z - skala wzdłuż osi \e OZ. */ void UstawSkaleZ( float skala_z ) { _Zskala = skala_z; } /*! * \brief Zadaje skalę wzdłuż osi \e OX i \e OZ. * * Zadaje skalę wzdłuż osi \e OX i \e OZ dla tworzonego rysunku. * \param skala_x - skala wzdłuż osi \e OX. * \param skala_z - skala wzdłuż osi \e OZ. */ void UstawSkaleXZ( float skala_x, float skala_z ) { UstawSkaleX(skala_x); UstawSkaleZ(skala_z); } /*! * Udostępnia wartość kąta rotacji renderowanego rysunku wokół * osi \e OX. Zwracana wartość wyrażona jest w stopiniach. */ float RotacjaX() const { return _Xrotacja; } /*! * Udostępnia wartość kąta rotacji renderowanego rysunku wokół * osi \e OZ. Zwracana wartość wyrażona jest w stopiniach. */ float RotacjaZ() const { return _Zrotacja; } /*! * \brief Ustawia rotację wokół osi \e OX. * * Zadaje kąt rotacji wokół osi \e OX. Umożliwia to zmianę * punktu obserwacji renderowanego rysunku. * \param kat_x - wartość kąta rotacji. Jego wartość podawana * jest w stopniach. */ void UstawRotacjeX( float kat_x ) { _Xrotacja = kat_x; } /*! * \brief Ustawia rotację wokół osi \e OZ. * * Zadaje kąt rotacji wokół osi \e OZ. Umożliwia to zmianę * punktu obserwacji renderowanego rysunku. * \param kat_z - wartość kąta rotacji. Jego wartość podawana * jest w stopniach. */ void UstawRotacjeZ( float kat_z ) { _Zrotacja = kat_z; } /*! * \brief Ustawia rotację wokół osi \e OX i \e OZ. * * Zadaje jednocześnie kąt rotacji wokół osi \e OX i \e OZ. * Umożliwia to zmianę * punktu obserwacji renderowanego rysunku. * \param kat_x - wartość kąta rotacji względem osi \e OX. * Jego wartość podawana * jest w stopniach. * \param kat_z - wartość kąta rotacji względem osi \e OZ. * Jego wartość podawana * jest w stopniach. */ void UstawRotacjeXZ( float kat_x, float kat_z ) { UstawRotacjeX(kat_x); UstawRotacjeZ(kat_z); } /*! * \brief Zezwala lub zabrania wyświetlania komunikatów. * * Metoda pozwala, albo też zabrania wyświetlania komunikatów o blędach. * Jeżeli jakaś z operacji nie powiedzie się, to jako wynik zwracana * jest wartość \p false. Oprócz tego metody takie moga wyświetlać * komunikaty, które kierowane są na wyjście "standard error" * Domyślnie przymuje się, że programista nie chce dodatkwego wyświetlania * komunikatów. */ void WyswietlajKomunikatyBledow( bool Tryb = true ); /*! * \brief Dodaje nazwę pliku. * * Powoduje dodanie do listy plików zawierajacych dane dla \e gnuplota, * nowej nazwy pliku. * * \param[in] NazwaPliku - nazwa pliku z danymi dla gnuplota. * \param[in] RodzRys - tryb rysowania danego zbioru punktow. * Może być ciągły lub jako zbiór osobnych punktów. * \param[in] Szerokosc - szerokość rysowanego obiektu. W przypadku * punktów parametr ten jest połową szerokości * kwadratu reprezentującego dany punkt. * * \retval true - jeżeli istnieje plik o nazwie udostępnionej poprzez * parametr * \e NazwaPliku oraz jest zezwolenie na jego czytanie. * Nazwa pliku zostaje dodana do listy plików z danymi * dla \e gnuplota. * \retval false - Jeżeli nie istnieje plik o nazwie przekazanej poprzez * parametr \e NazwaPliku. * Nazwa pliku zostaje dodana do listy plików z danymi * dla \e gnuplota. */ bool DodajNazwePliku( const char * NazwaPliku, RodzajRysowania RodzRys = RR_Ciagly, int Szerokosc = 1 ); /*! * \brief Tworzy listę parametrów umożliwiających rysowanie brył z plików. */ bool DopiszRysowanieZPlikow( std::string &Polecenie, char const **Sep ); /*! * \brief Informuje, czy połączenie z \e gnuplot'em jest zainicjalizowane. * * Informuje, czy połączenie z programem \e gnuplot jest zainicjowane. * \retval true - jeśli tak, * \retval false - w przypadku przeciwnym. */ bool CzyPolaczenieJestZainicjowane() const; /*! * Jeżeli lista plików nie jest pusta, to generuje sekwencje poleceń * dla programu \e gnuplot mająca na celu narysowanie płaszczyzn na * na podstawie danych zawartych w plikach z listy. * * \pre Lista plików nie powinna być pusta. Nazwy plików na niej * można umieścić za pomoca metody * \link LaczeDoGNUPlota::DodajNazwe DodajNazwe\endlink. * Metoda nie wymaga wcześniejszego zainicjowania połączenia * z \e gnuplotem. * \retval true - gdy zostają poprawnie wysłane polecenia dla gnuplota. * Nie oznacza to jednak, że proces rysowania zakończył * się pomyślnie. * \retval false - gdy połączenie z gnuplotem nie może zostać poprawnie * zainicjalizowane lub gdy lista plików jest pusta. */ bool Rysuj(); /*! * Działa analogicznie jak metoda * \link LaczeDoGNUPlota::Rysuj Rysuj\endlink, z tą różnicą, że * rysunek robota * składowany jest w pliku o nazwie przekazanej przez parametr * \e NazwaPliku. * Rysunek jest zapisywany w formacie \e PNG. * * \post Lista plików nie powinna być pusta ponadto powinno być * możliwe otwarcie do zapisu pliku o nazwie przekazanej przez * parametr \e NazwaPliku, do której dołączane jest rozszerzenie * .ps . * Metoda nie wymaga wcześniejszego zainicjowania połączenia * z programem \e gnuplot. * * \retval true - gdy zostają poprawnie wysłane polecenia dla * \e gnuplota. * Nie oznacza to jednak, że proces rysowania zakończył * się pomyślnie. * \retval false - gdy połączenie z gnuplotem nie może zostać poprawnie * zainicjalizowane lub gdy lista plików jest pusta lub * też gdy nie można otworzyć pliku do zapisu. */ bool RysujDoPliku(const char *NazwaPliku); /*! * \brief Inicjalizuje połączenie z programem \e gnuplot. * * Inicjalizuje połączenie z programem \e gnuplot. Realizowane jest to * poprzez rozwidlenie procesu i uruchomienie jako procesu potomnego * programu \e gnuplot. Komunikacja z programem \e gnuplot realizowana jest * poprzez przejęcie jego wejścia i wyjścia standardowego. * * \retval true - gdy połączenie z programem \e 0gnuplot zostało poprawnie * zainicjalizowane lub gdy już wcześniej było * zainicjalizowane. * \retval false - gdy proces inicjalizacji połączenia zakończył się * niepowodzeniem. */ bool Inicjalizuj(); /*! * \brief Usuwa ostatnią nazwę pliku. * * Usuwa ostatnią nazwę z listy nazw plików. */ void UsunOstatniaNazwe(); /*! * \brief Kasuje zawartość listy nazw plików. * * Calkowicie kasuje zawartość listy nazw plików. */ void UsunWszystkieNazwyPlikow(); LaczeDoGNUPlota(); virtual ~LaczeDoGNUPlota(); }; inline bool LaczeDoGNUPlota::DopiszPlikiDoPoleceniaRysowania( std::string &, char const ** ) { return true; } }
23,551
9,605
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "integrations/tensorflow/compiler/dialect/tf_tensorlist/ir/tf_tensorlist_dialect.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/DialectConversion.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" namespace mlir { namespace tf_tensorlist { #include "integrations/tensorflow/compiler/dialect/tf_tensorlist/conversion/convert_tf_to_tf_tensorlist.inc" class ConvertTfToTfTensorList : public OperationPass<ConvertTfToTfTensorList, FuncOp> { public: void runOnOperation() override; }; bool isTfVariant(Type type) { if (auto tensorType = type.dyn_cast<TensorType>()) { return tensorType.getElementType().isa<TF::VariantType>(); } return false; } void ConvertTfToTfTensorList::runOnOperation() { auto func = getOperation(); // The conversion happens in 2 steps: // 1. We blindly replace all tf ops operating on TensorList's with // tf_tensorlist ops. No types change in this step (so the IR is transiently // invalid). // 2. We rewrite all the types to make the IR valid again. // // The reason we need to do the rewriting this way is that not all TF variant // types actually represent a tensorlist. Only by looking at ops that we know // produce tensorlists can we deduce which TF varaints are tensorlists. // // The MLIR type conversion infrastructure doesn't handle this situation well. // It only knows how to handle blindly convert one type to another type. OwningRewritePatternList patterns; populateWithGenerated(&getContext(), &patterns); ConversionTarget target(getContext()); target.addLegalDialect<TfTensorListDialect>(); target.addLegalDialect<TF::TensorFlowDialect>(); target.addLegalDialect<StandardOpsDialect>(); target.addIllegalOp<TF::TensorListReserveOp>(); target.addIllegalOp<TF::TensorListGetItemOp>(); target.addIllegalOp<TF::TensorListSetItemOp>(); target.addIllegalOp<TF::TensorListFromTensorOp>(); target.addIllegalOp<TF::TensorListStackOp>(); if (failed(applyPartialConversion(func, target, patterns))) { func.emitError() << "unable to lower to tf_tensorlist dialect"; return signalPassFailure(); } // The above conversions didn't do any type conversion since we don't // want to blindly update all variant types to tensorlist. So here we do a // targeted rewrite. auto *tfTensorListDialect = func.getContext()->getRegisteredDialect<TfTensorListDialect>(); auto tensorListType = TensorListType::get(func.getContext()); SmallVector<Value, 8> typeConversionWorklist; func.walk([&](Operation *op) { if (op->getDialect() != tfTensorListDialect) { return; } for (auto result : op->getResults()) { if (isTfVariant(result.getType())) { result.setType(tensorListType); typeConversionWorklist.push_back(result); } } }); while (!typeConversionWorklist.empty()) { Value v = typeConversionWorklist.pop_back_val(); for (OpOperand &use : v.getUses()) { Operation *owner = use.getOwner(); // If the user is already in the tf_tensorlist dialect, then everything is // ok. if (owner->getDialect() == tfTensorListDialect) { continue; } // If a user is just a terminator passing the value through a successor // operand, propagate through the successor operand. if (owner->isKnownTerminator()) { if (auto arg = owner->getSuccessorBlockArgument(use.getOperandNumber())) { if (!arg->getType().isa<TensorListType>()) { arg->setType(tensorListType); typeConversionWorklist.push_back(*arg); } continue; } } // !tf.variant can have various subtypes which we blindly turn into just // !tf_tensorlist.list here. So elide all casts. if (auto castOp = dyn_cast<TF::CastOp>(owner)) { assert(v == castOp.x()); castOp.y().replaceAllUsesWith(castOp.x()); castOp.erase(); // The RAUW could have added more uses of `v`, so put it back on the // worklist and process it again. typeConversionWorklist.push_back(v); break; } owner->emitError() << "unable to convert tensorlist op: " << owner->getName(); return signalPassFailure(); } } } static PassRegistration<ConvertTfToTfTensorList> pass( "convert-tf-to-tf_tensorlist", "Convert to more precise types"); std::unique_ptr<OpPassBase<FuncOp>> createConvertTfToTfTensorList() { return std::make_unique<ConvertTfToTfTensorList>(); } } // namespace tf_tensorlist } // namespace mlir
5,262
1,643
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * 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. * * * * ========================================================================= */ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ //============================================================================= // // Implements the baseclass for MeshWriter exporter modules // //============================================================================= #ifndef __BASEEXPORTER_HH__ #define __BASEEXPORTER_HH__ //=== INCLUDES ================================================================ // STL #include <vector> // OpenMesh #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/Geometry/VectorT.hh> #include <OpenMesh/Core/Mesh/BaseKernel.hh> //=== NAMESPACES ============================================================== namespace OpenMesh { namespace IO { //=== EXPORTER ================================================================ /** Base class for exporter modules. The exporter modules provide an interface between the writer modules and the target data structure. */ class OPENMESHDLLEXPORT BaseExporter { public: virtual ~BaseExporter() { } // get vertex data virtual Vec3f point(VertexHandle _vh) const = 0; virtual Vec3f normal(VertexHandle _vh) const = 0; virtual Vec3uc color(VertexHandle _vh) const = 0; virtual Vec4uc colorA(VertexHandle _vh) const = 0; virtual Vec3ui colori(VertexHandle _vh) const = 0; virtual Vec4ui colorAi(VertexHandle _vh) const = 0; virtual Vec3f colorf(VertexHandle _vh) const = 0; virtual Vec4f colorAf(VertexHandle _vh) const = 0; virtual Vec2f texcoord(VertexHandle _vh) const = 0; // get face data virtual unsigned int get_vhandles(FaceHandle _fh, std::vector<VertexHandle>& _vhandles) const=0; virtual Vec3f normal(FaceHandle _fh) const = 0; virtual Vec3uc color (FaceHandle _fh) const = 0; virtual Vec4uc colorA(FaceHandle _fh) const = 0; virtual Vec3ui colori(FaceHandle _fh) const = 0; virtual Vec4ui colorAi(FaceHandle _fh) const = 0; virtual Vec3f colorf(FaceHandle _fh) const = 0; virtual Vec4f colorAf(FaceHandle _fh) const = 0; // get edge data virtual Vec3uc color(EdgeHandle _eh) const = 0; virtual Vec4uc colorA(EdgeHandle _eh) const = 0; virtual Vec3ui colori(EdgeHandle _eh) const = 0; virtual Vec4ui colorAi(EdgeHandle _eh) const = 0; virtual Vec3f colorf(EdgeHandle _eh) const = 0; virtual Vec4f colorAf(EdgeHandle _eh) const = 0; // get reference to base kernel virtual const BaseKernel* kernel() { return 0; } // query number of faces, vertices, normals, texcoords virtual size_t n_vertices() const = 0; virtual size_t n_faces() const = 0; virtual size_t n_edges() const = 0; // property information virtual bool is_triangle_mesh() const { return false; } virtual bool has_vertex_normals() const { return false; } virtual bool has_vertex_colors() const { return false; } virtual bool has_vertex_texcoords() const { return false; } virtual bool has_edge_colors() const { return false; } virtual bool has_face_normals() const { return false; } virtual bool has_face_colors() const { return false; } }; //============================================================================= } // namespace IO } // namespace OpenMesh //============================================================================= #endif //=============================================================================
6,959
1,861
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ---------------------------------------------------------------------------- // "THE BEER-WARE LICENSE" (Revision 42): // <ztn@zurreal.com> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you think // this stuff is worth it, you can buy me a beer in return. Ziesche Til Newman // ---------------------------------------------------------------------------- // // stage-base.cpp // #include "stage-base.hpp" #include "game/game-controller.hpp" #include "gui/box-entity-info.hpp" #include "gui/box-entity.hpp" #include "gui/display.hpp" #include "gui/entity.hpp" #include "gui/font-manager.hpp" #include "gui/i-entity.hpp" #include "gui/sound-manager.hpp" #include "gui/text-info.hpp" #include "gui/texture-cache.hpp" #include "sfutil/distance.hpp" #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/Sprite.hpp> #include <algorithm> #include <exception> #include <sstream> namespace heroespath { namespace stage { const float StageBase::MOUSE_DRAG_MIN_DISTANCE_ { 3.0f }; StageBase::StageBase( const std::string & NAME, const gui::FontEnumVec_t & FONTS_TO_PRELOAD, const gui::SfxEnumVec_t & SFX_TO_PRELOAD) : STAGE_NAME_(std::string(NAME)) , stageRegion_(gui::Display::Instance()->FullScreenRect()) , entityPVec_() , entityWithFocusPtrOpt_() , hoverTextBoxUPtr_() , hoverText_() , isFading_(false) , isMouseHeldDown_(false) , isMouseHeldDownAndMoving_(false) , mouseDownPosV_(0.0f, 0.0f) { StageBaseCommonSetupTasks(FONTS_TO_PRELOAD, SFX_TO_PRELOAD); } StageBase::StageBase( const std::string & NAME, const sf::FloatRect & REGION, const gui::FontEnumVec_t & FONTS_TO_PRELOAD, const gui::SfxEnumVec_t & SFX_TO_PRELOAD) : STAGE_NAME_(std::string(NAME)) , stageRegion_(REGION) , entityPVec_() , entityWithFocusPtrOpt_() , hoverTextBoxUPtr_() , hoverText_() , isFading_(false) , isMouseHeldDown_(false) , isMouseHeldDownAndMoving_(false) , mouseDownPosV_(0.0f, 0.0f) { StageBaseCommonSetupTasks(FONTS_TO_PRELOAD, SFX_TO_PRELOAD); } void StageBase::StageBaseCommonSetupTasks( const gui::FontEnumVec_t & FONTS_TO_PRELOAD, const gui::SfxEnumVec_t & SFX_TO_PRELOAD) { gui::FontManager::Instance()->Load(FONTS_TO_PRELOAD); gui::SoundManager::Instance()->PreLoadSfx(SFX_TO_PRELOAD); } StageBase::~StageBase() = default; game::Phase::Enum StageBase::GetPhase() const { return game::GameController::Instance()->GetPhase(); } const std::string StageBase::MakeCallbackHandlerMessage( const std::string & EVENT_DESCRIPTION, const std::string & ACTION_TAKEN) const { if (ACTION_TAKEN.empty()) { return ""; } else { return GetStageName() + " finished handling callback event " + EVENT_DESCRIPTION + " and " + ACTION_TAKEN + "."; } } void StageBase::UpdateTime(const float ELAPSED_TIME_SECONDS) { for (auto & entityPtr : entityPVec_) { entityPtr->UpdateTime(ELAPSED_TIME_SECONDS); } } void StageBase::UpdateMousePos(const sf::Vector2i & NEW_MOUSE_POS) { const sf::Vector2f NEW_MOUSE_POS_F(NEW_MOUSE_POS); isMouseHeldDownAndMoving_ = (isMouseHeldDown_ && (sfutil::Distance(mouseDownPosV_, NEW_MOUSE_POS_F) > MOUSE_DRAG_MIN_DISTANCE_)); for (auto & entityPtr : entityPVec_) { entityPtr->UpdateMousePos(NEW_MOUSE_POS_F); } } void StageBase::UpdateMouseDown(const sf::Vector2f & MOUSE_POS_V) { isMouseHeldDown_ = true; mouseDownPosV_ = MOUSE_POS_V; for (auto & entityPtr : entityPVec_) { entityPtr->MouseDown(MOUSE_POS_V); } } const gui::IEntityPtrOpt_t StageBase::UpdateMouseUp(const sf::Vector2f & MOUSE_POS_V) { isMouseHeldDown_ = false; isMouseHeldDownAndMoving_ = false; for (const auto & ENTITY_PTR : entityPVec_) { if ((ENTITY_PTR->MouseUp(MOUSE_POS_V)) && ENTITY_PTR->WillAcceptFocus()) { return ENTITY_PTR; } } return boost::none; } void StageBase::UpdateMouseWheel(const sf::Vector2f & MOUSE_POS_V, const float MOUSEWHEEL_DELTA) { for (auto & entityPtr : entityPVec_) { entityPtr->UpdateMouseWheel(MOUSE_POS_V, MOUSEWHEEL_DELTA); } } bool StageBase::KeyPress(const sf::Event::KeyEvent & KE) { return (entityWithFocusPtrOpt_ && (entityWithFocusPtrOpt_.value()->KeyPress(KE))); } bool StageBase::KeyRelease(const sf::Event::KeyEvent & KE) { return (entityWithFocusPtrOpt_ && (entityWithFocusPtrOpt_.value()->KeyRelease(KE))); } void StageBase::RemoveFocus() { if (entityWithFocusPtrOpt_) { entityWithFocusPtrOpt_.value()->SetHasFocus(false); entityWithFocusPtrOpt_ = boost::none; } } void StageBase::SetFocus(const gui::IEntityPtr_t ENTITY_PTR) { const auto ORIG_ENTITY_WITH_FOCUS_NAME { ((entityWithFocusPtrOpt_) ? entityWithFocusPtrOpt_.value()->GetEntityName() : "(None)") }; const auto WAS_FOUND { std::find(std::begin(entityPVec_), std::end(entityPVec_), ENTITY_PTR) != std::end(entityPVec_) }; if (WAS_FOUND) { RemoveFocus(); ENTITY_PTR->SetHasFocus(true); entityWithFocusPtrOpt_ = ENTITY_PTR; } else { M_HP_LOG_ERR( "stage::StageBase(" << GetStageName() << ")::SetFocus(entity=" << ENTITY_PTR->GetEntityName() << ") Attempt to set focus with an IEntityPtr_t that was not in entityPVec_. " "orig_entity_withfocus=\"" << ORIG_ENTITY_WITH_FOCUS_NAME << "\""); } } void StageBase::draw(sf::RenderTarget & target, sf::RenderStates states) const { for (auto & entityPtr : entityPVec_) { entityPtr->draw(target, states); } if (hoverTextBoxUPtr_) { target.draw(*hoverTextBoxUPtr_, states); target.draw(hoverText_, states); } } void StageBase::EntityAdd(const gui::IEntityPtr_t ENTITY_PTR, const bool WILL_INSERT_AT_FRONT) { const auto WAS_FOUND { std::find(std::begin(entityPVec_), std::end(entityPVec_), ENTITY_PTR) != std::end(entityPVec_) }; if (WAS_FOUND) { M_HP_LOG_WRN( "Ignoring because this entity was already in the list. (entity_name=\"" << ENTITY_PTR->GetEntityName() << "\")" << M_HP_VAR_STR(WILL_INSERT_AT_FRONT) << "(stage=" << GetStageName() << ")"); return; } if (WILL_INSERT_AT_FRONT) { entityPVec_.insert(std::begin(entityPVec_), ENTITY_PTR); } else { entityPVec_.emplace_back(ENTITY_PTR); } } void StageBase::EntityRemove(const gui::IEntityPtr_t ENTITY_PTR) { const auto ORIG_NUM_ENTITYS { entityPVec_.size() }; entityPVec_.erase( std::remove(entityPVec_.begin(), entityPVec_.end(), ENTITY_PTR), entityPVec_.end()); bool wasEntityFoundAndRemoved { (ORIG_NUM_ENTITYS != entityPVec_.size()) }; if (entityWithFocusPtrOpt_ == ENTITY_PTR) { RemoveFocus(); wasEntityFoundAndRemoved = true; } if (false == wasEntityFoundAndRemoved) { M_HP_LOG_WRN( "Entity to remove named \"" << ENTITY_PTR->GetEntityName() << "\" was not found. " << "(stage=" << GetStageName() << ")"); } } void StageBase::SetMouseHover(const sf::Vector2f & MOUSE_POS_V, const bool IS_MOUSE_HOVERING) { if (IS_MOUSE_HOVERING) { std::string text(""); // check if focused entity is hovered first if (entityWithFocusPtrOpt_ && (entityWithFocusPtrOpt_.value()->GetEntityRegion().contains(MOUSE_POS_V))) { text = entityWithFocusPtrOpt_.value()->GetMouseHoverText(); } // if focused entity is not hovered, then look for any entity the mouse is hovering over if (text.empty()) { for (const auto & NEXT_ENTITY_PTR : entityPVec_) { if (NEXT_ENTITY_PTR->GetEntityRegion().contains(MOUSE_POS_V)) { text = NEXT_ENTITY_PTR->GetMouseHoverText(); if (text.empty() == false) { break; } } } } if (text.empty()) { if (hoverTextBoxUPtr_) { hoverTextBoxUPtr_.reset(); } return; } const gui::TextInfo TEXT_INFO( text, gui::GuiFont::System, gui::FontManager::Instance()->Size_Smallish(), sf::Color(50, 50, 50), gui::Justified::Left); hoverText_.setup(TEXT_INFO); sf::FloatRect region( MOUSE_POS_V.x - 200.0f, MOUSE_POS_V.y + 10.0f, hoverText_.getGlobalBounds().width + 20.0f, hoverText_.getGlobalBounds().height + 8.0f); const auto SCREEN_WIDTH { gui::Display::Instance()->GetWinWidth() }; if ((region.left + region.width) > SCREEN_WIDTH) { region.left = SCREEN_WIDTH - region.width; } if (region.left < 0.0f) { region.left = 0.0f; } hoverText_.setPosition(region.left + 10.0f, region.top + 2.0f); gui::BoxEntityInfo boxInfo; boxInfo.SetupColor(sfutil::color::Orange - sf::Color(20, 0, 0, 0)); boxInfo.SetupBorder(true, 1.0f); hoverTextBoxUPtr_ = std::make_unique<gui::BoxEntity>(GetStageName() + "'sHoverText", region, boxInfo); } else { if (hoverTextBoxUPtr_) { hoverTextBoxUPtr_.reset(); } } } void StageBase::TestingStrAppend(const std::string & MESSAGE) { game::GameController::Instance()->TestingStrAppend(MESSAGE); } void StageBase::TestingStrIncrement(const std::string & MESSAGE) { game::GameController::Instance()->TestingStrIncrement(MESSAGE); } void StageBase::TestingImageSet(const std::string & MESSAGE) { game::GameController::Instance()->TestingImageSet(MESSAGE); } void StageBase::ClearAllEntities() { entityWithFocusPtrOpt_ = boost::none; entityPVec_.clear(); } void StageBase::SpawnPopup( const misc::PopupCallback_t::IHandlerPtr_t POPUP_HANDLER_PTR, const popup::PopupInfo & POPUP_INFO) const { game::GameController::Instance()->SpawnPopup(POPUP_HANDLER_PTR, POPUP_INFO); } void StageBase::RemovePopup( const popup::PopupButtons::Enum TYPE, const std::size_t SELECTION) const { game::GameController::Instance()->RemovePopup(TYPE, SELECTION); } void StageBase::TransitionTo(const stage::Stage::Enum NEW_STAGE) const { game::GameController::Instance()->TransitionTo(NEW_STAGE); } void StageBase::TransitionTo(const stage::SetupPacket & SETUP_PACKET) const { game::GameController::Instance()->TransitionTo(SETUP_PACKET); } const gui::DisplayChangeResult StageBase::ChangeResolution( const misc::PopupCallback_t::IHandlerPtr_t POPUP_HANDLER_PTR, const gui::Resolution & NEW_RES, const unsigned ANTIALIAS_LEVEL) const { return game::GameController::Instance()->ChangeResolution( POPUP_HANDLER_PTR, NEW_RES, ANTIALIAS_LEVEL); } } // namespace stage } // namespace heroespath
12,732
4,051
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Base class for a Pitman Arm steering subsystem. // Derived from ChSteering, but still an abstract base class. // // ============================================================================= #include <vector> #include "chrono/assets/ChColorAsset.h" #include "chrono/assets/ChCylinderShape.h" #include "chrono/assets/ChPointPointDrawing.h" #include "chrono_vehicle/wheeled_vehicle/steering/ChPitmanArmShafts.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChPitmanArmShafts::ChPitmanArmShafts(const std::string& name, bool vehicle_frame_inertia, bool rigid_column) : ChSteering(name), m_vehicle_frame_inertia(vehicle_frame_inertia), m_rigid(rigid_column) {} // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChPitmanArmShafts::Initialize(std::shared_ptr<ChChassis> chassis, const ChVector<>& location, const ChQuaternion<>& rotation) { m_position = ChCoordsys<>(location, rotation); auto chassisBody = chassis->GetBody(); auto sys = chassisBody->GetSystem(); // Chassis orientation (expressed in absolute frame) // Recall that the suspension reference frame is aligned with the chassis. ChQuaternion<> chassisRot = chassisBody->GetFrame_REF_to_abs().GetRot(); // Express the steering reference frame in the absolute coordinate system. ChFrame<> steering_to_abs(location, rotation); steering_to_abs.ConcatenatePreTransformation(chassisBody->GetFrame_REF_to_abs()); // Transform all points and directions to absolute frame. std::vector<ChVector<>> points(NUM_POINTS); std::vector<ChVector<>> dirs(NUM_DIRS); for (int i = 0; i < NUM_POINTS; i++) { ChVector<> rel_pos = getLocation(static_cast<PointId>(i)); points[i] = steering_to_abs.TransformPointLocalToParent(rel_pos); } for (int i = 0; i < NUM_DIRS; i++) { ChVector<> rel_dir = getDirection(static_cast<DirectionId>(i)); dirs[i] = steering_to_abs.TransformDirectionLocalToParent(rel_dir); } // Unit vectors for orientation matrices. ChVector<> u; ChVector<> v; ChVector<> w; ChMatrix33<> rot; // Create and initialize the steering link body m_link = std::shared_ptr<ChBody>(sys->NewBody()); m_link->SetNameString(m_name + "_link"); m_link->SetPos(points[STEERINGLINK]); m_link->SetRot(steering_to_abs.GetRot()); m_link->SetMass(getSteeringLinkMass()); if (m_vehicle_frame_inertia) { ChMatrix33<> inertia = TransformInertiaMatrix(getSteeringLinkInertiaMoments(), getSteeringLinkInertiaProducts(), chassisRot, steering_to_abs.GetRot()); m_link->SetInertia(inertia); } else { m_link->SetInertiaXX(getSteeringLinkInertiaMoments()); m_link->SetInertiaXY(getSteeringLinkInertiaProducts()); } sys->AddBody(m_link); m_pP = m_link->TransformPointParentToLocal(points[UNIV]); m_pI = m_link->TransformPointParentToLocal(points[REVSPH_S]); m_pTP = m_link->TransformPointParentToLocal(points[TIEROD_PA]); m_pTI = m_link->TransformPointParentToLocal(points[TIEROD_IA]); // Create and initialize the Pitman arm body m_arm = std::shared_ptr<ChBody>(sys->NewBody()); m_arm->SetNameString(m_name + "_arm"); m_arm->SetPos(points[PITMANARM]); m_arm->SetRot(steering_to_abs.GetRot()); m_arm->SetMass(getPitmanArmMass()); if (m_vehicle_frame_inertia) { ChMatrix33<> inertia = TransformInertiaMatrix(getPitmanArmInertiaMoments(), getPitmanArmInertiaProducts(), chassisRot, steering_to_abs.GetRot()); m_arm->SetInertia(inertia); } else { m_arm->SetInertiaXX(getPitmanArmInertiaMoments()); m_arm->SetInertiaXY(getPitmanArmInertiaProducts()); } sys->AddBody(m_arm); // Cache points for arm visualization (expressed in the arm frame) m_pC = m_arm->TransformPointParentToLocal(points[REV]); m_pL = m_arm->TransformPointParentToLocal(points[UNIV]); // Create and initialize the revolute joint between chassis and Pitman arm. // The z direction of the joint orientation matrix is dirs[REV_AXIS], assumed // to be a unit vector. u = points[PITMANARM] - points[REV]; v = Vcross(dirs[REV_AXIS], u); v.Normalize(); u = Vcross(v, dirs[REV_AXIS]); rot.Set_A_axis(u, v, dirs[REV_AXIS]); m_revolute = chrono_types::make_shared<ChLinkLockRevolute>(); m_revolute->SetNameString(m_name + "_revolute"); m_revolute->Initialize(chassisBody, m_arm, ChCoordsys<>(points[REV], rot.Get_A_quaternion())); sys->AddLink(m_revolute); // Create and initialize the universal joint between the Pitman arm and steering link. // The x and y directions of the joint orientation matrix are given by // dirs[UNIV_AXIS_ARM] and dirs[UNIV_AXIS_LINK], assumed to be unit vectors // and orthogonal. w = Vcross(dirs[UNIV_AXIS_ARM], dirs[UNIV_AXIS_LINK]); rot.Set_A_axis(dirs[UNIV_AXIS_ARM], dirs[UNIV_AXIS_LINK], w); m_universal = chrono_types::make_shared<ChLinkUniversal>(); m_universal->SetNameString(m_name + "_universal"); m_universal->Initialize(m_arm, m_link, ChFrame<>(points[UNIV], rot.Get_A_quaternion())); sys->AddLink(m_universal); // Create and initialize the revolute-spherical joint (massless idler arm). // The length of the idler arm is the distance between the two hardpoints. // The z direction of the revolute joint orientation matrix is // dirs[REVSPH_AXIS], assumed to be a unit vector. double distance = (points[REVSPH_S] - points[REVSPH_R]).Length(); u = points[REVSPH_S] - points[REVSPH_R]; v = Vcross(dirs[REVSPH_AXIS], u); v.Normalize(); u = Vcross(v, dirs[REVSPH_AXIS]); rot.Set_A_axis(u, v, dirs[REVSPH_AXIS]); m_revsph = chrono_types::make_shared<ChLinkRevoluteSpherical>(); m_revsph->SetNameString(m_name + "_revsph"); m_revsph->Initialize(chassisBody, m_link, ChCoordsys<>(points[REVSPH_R], rot.Get_A_quaternion()), distance); sys->AddLink(m_revsph); //// TODO: Decide if shaftC should be attached to chassis or if it should be "fixed" //// Right now: fixed. // Create all shafts in steering column // Chassis --X-- shaftC --M-- shaftC1 --S-- shaftA1 --G-- shaftA --X-- Arm // All shafts are aligned with dir[REV_AXIS], assumed to be a unit vector. double inertia = getSteeringColumnInertia(); m_shaft_C = chrono_types::make_shared<ChShaft>(); m_shaft_C->SetNameString(m_name + "_shaftC"); m_shaft_C->SetInertia(inertia); m_shaft_C->SetShaftFixed(true); sys->Add(m_shaft_C); m_shaft_C1 = chrono_types::make_shared<ChShaft>(); m_shaft_C1->SetNameString(m_name + "_shaftC1"); m_shaft_C1->SetInertia(inertia); sys->Add(m_shaft_C1); m_shaft_A1 = chrono_types::make_shared<ChShaft>(); m_shaft_A1->SetNameString(m_name + "_shaftA1"); m_shaft_A1->SetInertia(inertia); sys->Add(m_shaft_A1); m_shaft_A = chrono_types::make_shared<ChShaft>(); m_shaft_A->SetNameString(m_name + "_shaftA"); m_shaft_A->SetInertia(inertia); sys->Add(m_shaft_A); // Rigidly attach shaftA to the arm body m_shaft_arm = chrono_types::make_shared<ChShaftsBody>(); m_shaft_arm->SetNameString(m_name + "_shaftA_to_arm"); m_shaft_arm->Initialize(m_shaft_A, m_arm, dirs[REV_AXIS]); sys->Add(m_shaft_arm); // Rigidly attach shaftC to the chassis body ////m_shaft_chassis = chrono_types::make_shared<ChShaftsBody>(); ////m_shaft_chassis->SetNameString(m_name + "_shaftC_to_chassis"); ////m_shaft_chassis->Initialize(m_shaft_C, chassisBody, dirs[REV_AXIS]); ////sys->Add(m_shaft_chassis); // A motor (for steering input) between shaftC and shaftC1 // The setpoint for the motor angle function is set in Synchronize() m_shaft_motor = chrono_types::make_shared<ChShaftsMotorAngle>(); m_shaft_motor->SetNameString(m_name + "_motor"); m_shaft_motor->Initialize(m_shaft_C, m_shaft_C1); auto motor_fun = chrono_types::make_shared<ChFunction_Setpoint>(); m_shaft_motor->SetAngleFunction(motor_fun); sys->Add(m_shaft_motor); // A reduction gear between shaftA and shaftA1 // (note order of connected shafts for gear_ratio > 1) m_shaft_gear = chrono_types::make_shared<ChShaftsGear>(); m_shaft_gear->SetNameString(m_name + "_transmission"); m_shaft_gear->SetTransmissionRatio(getGearRatio()); m_shaft_gear->Initialize(m_shaft_A, m_shaft_A1); sys->Add(m_shaft_gear); // Connect shaftA1 and shaftC1 (compliant or rigid connection) if (m_rigid) { // Use a gear couple with ratio=1 m_rigid_connection = chrono_types::make_shared<ChShaftsGear>(); m_rigid_connection->SetNameString(m_name + "_rigid_column"); m_rigid_connection->SetTransmissionRatio(1.0); m_rigid_connection->Initialize(m_shaft_A1, m_shaft_C1); sys->Add(m_rigid_connection); } else { // Use a torsional spring between shaftA1 and shaftC1 m_spring_connection = chrono_types::make_shared<ChShaftsTorsionSpring>(); m_spring_connection->SetNameString(m_name + "_compliant_column"); m_spring_connection->SetTorsionalStiffness(getSteeringCompliance()); ////m_spring_connection->SetTorsionalDamping(10); m_spring_connection->Initialize(m_shaft_C1, m_shaft_A1); sys->Add(m_spring_connection); } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChPitmanArmShafts::Synchronize(double time, double steering) { auto fun = std::static_pointer_cast<ChFunction_Setpoint>(m_shaft_motor->GetAngleFunction()); fun->SetSetpoint(getMaxAngle() * steering, time); } // ----------------------------------------------------------------------------- // Get the total mass of the steering subsystem // ----------------------------------------------------------------------------- double ChPitmanArmShafts::GetMass() const { return getSteeringLinkMass() + getPitmanArmMass(); } // ----------------------------------------------------------------------------- // Get the current COM location of the steering subsystem. // ----------------------------------------------------------------------------- ChVector<> ChPitmanArmShafts::GetCOMPos() const { ChVector<> com = getSteeringLinkMass() * m_link->GetPos() + getPitmanArmMass() * m_arm->GetPos(); return com / GetMass(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChPitmanArmShafts::AddVisualizationAssets(VisualizationType vis) { if (vis == VisualizationType::NONE) return; // Visualization for link { auto cyl = chrono_types::make_shared<ChCylinderShape>(); cyl->GetCylinderGeometry().p1 = m_pP; cyl->GetCylinderGeometry().p2 = m_pI; cyl->GetCylinderGeometry().rad = getSteeringLinkRadius(); m_link->AddAsset(cyl); auto cyl_P = chrono_types::make_shared<ChCylinderShape>(); cyl_P->GetCylinderGeometry().p1 = m_pP; cyl_P->GetCylinderGeometry().p2 = m_pTP; cyl_P->GetCylinderGeometry().rad = getSteeringLinkRadius(); m_link->AddAsset(cyl_P); auto cyl_I = chrono_types::make_shared<ChCylinderShape>(); cyl_I->GetCylinderGeometry().p1 = m_pI; cyl_I->GetCylinderGeometry().p2 = m_pTI; cyl_I->GetCylinderGeometry().rad = getSteeringLinkRadius(); m_link->AddAsset(cyl_I); auto col = chrono_types::make_shared<ChColorAsset>(); col->SetColor(ChColor(0.2f, 0.7f, 0.7f)); m_link->AddAsset(col); } // Visualization for arm { auto cyl = chrono_types::make_shared<ChCylinderShape>(); cyl->GetCylinderGeometry().p1 = m_pC; cyl->GetCylinderGeometry().p2 = m_pL; cyl->GetCylinderGeometry().rad = getPitmanArmRadius(); m_arm->AddAsset(cyl); auto col = chrono_types::make_shared<ChColorAsset>(); col->SetColor(ChColor(0.7f, 0.7f, 0.2f)); m_arm->AddAsset(col); } // Visualization for rev-sph link m_revsph->AddAsset(chrono_types::make_shared<ChPointPointSegment>()); } void ChPitmanArmShafts::RemoveVisualizationAssets() { m_link->GetAssets().clear(); m_arm->GetAssets().clear(); m_revsph->GetAssets().clear(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChPitmanArmShafts::LogConstraintViolations() { // Revolute joint { ChVectorDynamic<> C = m_revolute->GetC(); GetLog() << "Revolute "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << " "; GetLog() << " " << C(3) << " "; GetLog() << " " << C(4) << "\n"; } // Universal joint { ChVectorDynamic<> C = m_universal->GetC(); GetLog() << "Universal "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << " "; GetLog() << " " << C(3) << "\n"; } // Revolute-spherical joint { ChVectorDynamic<> C = m_revsph->GetC(); GetLog() << "Revolute-spherical "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << "\n"; } //// TODO //// Constraint violations for the various shaft couples } void ChPitmanArmShafts::GetShaftInformation(double time, double& motor_input, double& motor_input_der, std::vector<double>& shaft_angles, std::vector<double>& shaft_velocities, std::vector<double>& constraint_violations, ChVector<>& arm_angular_vel) const { auto fun = std::static_pointer_cast<ChFunction_Setpoint>(m_shaft_motor->GetAngleFunction()); motor_input = fun->Get_y(time); motor_input_der = fun->Get_y_dx(time); shaft_angles.push_back(m_shaft_C->GetPos()); shaft_angles.push_back(m_shaft_C1->GetPos()); shaft_angles.push_back(m_shaft_A1->GetPos()); shaft_angles.push_back(m_shaft_A->GetPos()); shaft_velocities.push_back(m_shaft_C->GetPos_dt()); shaft_velocities.push_back(m_shaft_C1->GetPos_dt()); shaft_velocities.push_back(m_shaft_A1->GetPos_dt()); shaft_velocities.push_back(m_shaft_A->GetPos_dt()); constraint_violations.push_back(m_shaft_motor->GetConstraintViolation()); constraint_violations.push_back(m_shaft_gear->GetConstraintViolation()); if (m_rigid) constraint_violations.push_back(m_rigid_connection->GetConstraintViolation()); arm_angular_vel = m_arm->GetWvel_loc(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChPitmanArmShafts::ExportComponentList(rapidjson::Document& jsonDocument) const { ChPart::ExportComponentList(jsonDocument); std::vector<std::shared_ptr<ChBody>> bodies; bodies.push_back(m_link); bodies.push_back(m_arm); ChPart::ExportBodyList(jsonDocument, bodies); std::vector<std::shared_ptr<ChShaft>> shafts; shafts.push_back(m_shaft_C); shafts.push_back(m_shaft_C1); shafts.push_back(m_shaft_A1); shafts.push_back(m_shaft_A); ChPart::ExportShaftList(jsonDocument, shafts); std::vector<std::shared_ptr<ChLink>> joints; joints.push_back(m_revolute); joints.push_back(m_revsph); joints.push_back(m_universal); ChPart::ExportJointList(jsonDocument, joints); std::vector<std::shared_ptr<ChShaftsCouple>> couples; couples.push_back(m_shaft_motor); couples.push_back(m_shaft_gear); if (m_rigid) couples.push_back(m_rigid_connection); else couples.push_back(m_spring_connection); ChPart::ExportCouplesList(jsonDocument, couples); } void ChPitmanArmShafts::Output(ChVehicleOutput& database) const { if (!m_output) return; std::vector<std::shared_ptr<ChBody>> bodies; bodies.push_back(m_link); bodies.push_back(m_arm); database.WriteBodies(bodies); std::vector<std::shared_ptr<ChShaft>> shafts; shafts.push_back(m_shaft_C); shafts.push_back(m_shaft_C1); shafts.push_back(m_shaft_A1); shafts.push_back(m_shaft_A); database.WriteShafts(shafts); std::vector<std::shared_ptr<ChLink>> joints; joints.push_back(m_revolute); joints.push_back(m_revsph); joints.push_back(m_universal); database.WriteJoints(joints); std::vector<std::shared_ptr<ChShaftsCouple>> couples; couples.push_back(m_shaft_motor); couples.push_back(m_shaft_gear); if (m_rigid) couples.push_back(m_rigid_connection); else couples.push_back(m_spring_connection); database.WriteCouples(couples); } } // end namespace vehicle } // end namespace chrono
18,214
6,253
#include <iostream> #include <string> #include <vector> using namespace std; vector<string> read_data(string file_path); int count_trees(vector<string> data, int right_step, int down_step) { int position = 0, number_of_trees = 0; int col_num = data[0].length(); string str; for (int row = 0; row < data.size(); row += down_step) { str = data[row]; if (str[position] == '#') number_of_trees++; position += right_step; if (position >= col_num) position -= col_num; } return number_of_trees; } void tree_tallies(vector<string> data) { int right_down_pairs[5][2] = {{1, 1}, {3, 1}, {5, 1}, {7, 1}, {1, 2}}; int right_step, down_step, number_of_trees; unsigned int multiple = 1; for (int i = 0; i < 5; i++) { right_step = right_down_pairs[i][0]; down_step = right_down_pairs[i][1]; number_of_trees = count_trees(data, right_step, down_step); multiple *= number_of_trees; cout << "Right " << right_step << "; Down " << down_step << ": " << number_of_trees << endl; } cout << "\tMultiple = " << multiple << endl; } void day3() { cout << "Numbers of trees (example):" << endl; tree_tallies(read_data("data/day3/example.txt")); cout << "Numbers of trees (input):" << endl; tree_tallies(read_data("data/day3/input.txt")); }
1,401
501
#include <fc/thread/future.hpp> #include <fc/thread/spin_yield_lock.hpp> #include <fc/thread/thread.hpp> #include <fc/thread/unique_lock.hpp> #include <fc/exception/exception.hpp> #include <boost/assert.hpp> namespace fc { promise_base::promise_base( const char* desc ) :_ready(false), _blocked_thread(nullptr), _blocked_fiber_count(0), _timeout(time_point::maximum()), _canceled(false), #ifndef NDEBUG _cancellation_reason(nullptr), #endif _desc(desc), _compl(nullptr) { } promise_base::~promise_base() { } const char* promise_base::get_desc()const{ return _desc; } void promise_base::cancel(const char* reason /* = nullptr */){ // wlog("${desc} canceled!", ("desc", _desc? _desc : "")); _canceled = true; #ifndef NDEBUG _cancellation_reason = reason; #endif } bool promise_base::ready()const { return _ready.load(); } bool promise_base::error()const { return std::atomic_load( &_exceptp ) != nullptr; } void promise_base::set_exception( const fc::exception_ptr& e ){ std::atomic_store( &_exceptp, e ); _set_value(nullptr); } void promise_base::_wait( const microseconds& timeout_us ){ if( timeout_us == microseconds::maximum() ) _wait_until( time_point::maximum() ); else _wait_until( time_point::now() + timeout_us ); } void promise_base::_wait_until( const time_point& timeout_us ){ if( _ready.load() ) { fc::exception_ptr ex = std::atomic_load( &_exceptp ); if( ex ) ex->dynamic_rethrow_exception(); return; } _enqueue_thread(); // Need to check _ready again to avoid a race condition. if( _ready.load() ) { _dequeue_thread(); return _wait_until( timeout_us ); // this will simply return or throw _exceptp } std::exception_ptr e; // // Create shared_ptr to take ownership of this; i.e. this will // be deleted when p_this goes out of scope. Consequently, // it would be Very Bad to let p_this go out of scope // before we're done reading/writing instance variables! // See https://github.com/cryptonomex/graphene/issues/597 // ptr p_this = shared_from_this(); try { // // We clone p_this here because the wait_until() API requires us // to use std::move(). I.e. wait_until() takes ownership of any // pointer passed to it. Since we want to keep ownership ourselves, // we need to have two shared_ptr's to this: // // - p_this to keep this alive until the end of the current function // - p_this2 to be owned by wait_until() as the wait_until() API requires // ptr p_this2 = p_this; thread::current().wait_until( std::move( p_this2 ), timeout_us ); } catch (...) { e = std::current_exception(); } _dequeue_thread(); if( e ) std::rethrow_exception(e); if( _ready.load() ) return _wait_until( timeout_us ); // this will simply return or throw _exceptp FC_THROW_EXCEPTION( timeout_exception, "" ); } void promise_base::_enqueue_thread(){ _blocked_fiber_count.fetch_add( 1 ); thread* blocked_thread = _blocked_thread.load(); // only one thread can wait on a promise at any given time do assert( !blocked_thread || blocked_thread == &thread::current() ); while( !_blocked_thread.compare_exchange_weak( blocked_thread, &thread::current() ) ); } void promise_base::_dequeue_thread(){ if( _blocked_fiber_count.fetch_add( -1 ) == 1 ) _blocked_thread.store( nullptr ); } void promise_base::_notify(){ // copy _blocked_thread into a local so that if the thread unblocks (e.g., // because of a timeout) before we get a chance to notify it, we won't be // calling notify on a null pointer thread* blocked_thread = _blocked_thread.load(); if( blocked_thread ) blocked_thread->notify( shared_from_this() ); } void promise_base::_set_value(const void* s){ bool ready = false; if( !_ready.compare_exchange_strong( ready, true ) ) //don't allow promise to be set more than once return; _notify(); auto* hdl = _compl.load(); if( nullptr != hdl ) hdl->on_complete( s, std::atomic_load( &_exceptp ) ); } void promise_base::_on_complete( detail::completion_handler* c ) { auto* hdl = _compl.load(); while( !_compl.compare_exchange_weak( hdl, c ) ); delete hdl; } }
4,471
1,487
#include <QApplication> #include "ivyservice.h" QString loadFile(QString path) { QFile f(path); f.open(QIODevice::ReadOnly); QString s = f.readAll(); f.close(); return s; } void showHelpAndExit() { puts( R"(Usage: ivyserver [arguments] Arguments: --minimized: Start with the main window minimized (Ignored if the server is running) -h | --help: Show help (this message) and exit )" ); exit(EXIT_SUCCESS); } int main(int argc, char **argv) { QApplication app(argc, argv); app.setApplicationName("ivy"); if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) showHelpAndExit(); IvyService i(&app); bool minimized = false; if (i.tryRegisterService() == false) { qCritical("ivyserver is already running. Stopping."); exit(EXIT_FAILURE); } if (argc > 1 && strcmp(argv[1], "--minimized") == 0) minimized = true; app.setStyleSheet(loadFile(":/style.css")); i.start(minimized); return app.exec(); }
1,116
397
/* Copyright 2020 The TensorFlow 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 "tensorflow/core/tpu/kernels/tpu_compilation_cache_grpc.h" #include <functional> #include "grpcpp/impl/codegen/async_stream.h" #include "grpcpp/impl/codegen/async_unary_call.h" #include "grpcpp/impl/codegen/channel_interface.h" #include "grpcpp/impl/codegen/client_callback.h" #include "grpcpp/impl/codegen/client_unary_call.h" #include "grpcpp/impl/codegen/method_handler.h" #include "grpcpp/impl/codegen/rpc_service_method.h" #include "grpcpp/impl/codegen/server_callback.h" #include "grpcpp/impl/codegen/service_type.h" #include "grpcpp/impl/codegen/sync_stream.h" namespace tensorflow { namespace tpu { static const char* grpcTpuCompilationCacheService_method_names[] = { #if defined(LIBTPU_ON_GCE) "/tensorflow.tpu.TpuCompilationCacheServiceExternal/GetTpuProgram", #else // LIBTPU_ON_GCE "/tensorflow.tpu.TpuCompilationCacheService/GetTpuProgram", #endif // LIBTPU_ON_GCE }; std::unique_ptr<grpc::TpuCompilationCacheService::Stub> grpc::TpuCompilationCacheService::NewStub( const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr<grpc::TpuCompilationCacheService::Stub> stub( new grpc::TpuCompilationCacheService::Stub(channel)); return stub; } grpc::TpuCompilationCacheService::Stub::Stub( const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_get_tpu_program_(grpcTpuCompilationCacheService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) {} ::grpc::Status grpc::TpuCompilationCacheService::Stub::GetTpuProgram( ::grpc::ClientContext* context, const RequestType& request, ResponseType* response) { return ::grpc::internal::BlockingUnaryCall( channel_.get(), rpcmethod_get_tpu_program_, context, request, response); } ::grpc::ClientAsyncResponseReader< grpc::TpuCompilationCacheService::ResponseType>* grpc::TpuCompilationCacheService::Stub::AsyncGetTpuProgramRaw( ::grpc::ClientContext* context, const RequestType& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ResponseType>::Create(channel_.get(), cq, rpcmethod_get_tpu_program_, context, request, true); } ::grpc::ClientAsyncResponseReader< grpc::TpuCompilationCacheService::ResponseType>* grpc::TpuCompilationCacheService::Stub::PrepareAsyncGetTpuProgramRaw( ::grpc::ClientContext* context, const RequestType& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ResponseType>::Create(channel_.get(), cq, rpcmethod_get_tpu_program_, context, request, false); } grpc::TpuCompilationCacheService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( grpcTpuCompilationCacheService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< grpc::TpuCompilationCacheService::Service, RequestType, ResponseType>( std::mem_fn( &grpc::TpuCompilationCacheService::Service::GetTpuProgram), this))); } grpc::TpuCompilationCacheService::Service::~Service() {} ::grpc::Status grpc::TpuCompilationCacheService::Service::GetTpuProgram( ::grpc::ServerContext* context, const RequestType* request, ResponseType* response) { (void)context; (void)request; (void)response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace tpu } // namespace tensorflow
4,303
1,374
/* * Copyright (C) 2011 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitTestServer.h" #include "WebViewTest.h" #include <gtk/gtk.h> #include <libsoup/soup.h> #include <string.h> #include <webkit2/webkit2.h> // Back forward list limit is 100 by default. static const int kBackForwardListLimit = 100; static WebKitTestServer* kServer; static void serverCallback(SoupServer* server, SoupMessage* msg, const char* path, GHashTable* query, SoupClientContext* context, gpointer data) { if (msg->method != SOUP_METHOD_GET) { soup_message_set_status(msg, SOUP_STATUS_NOT_IMPLEMENTED); return; } if (g_str_has_suffix(path, "favicon.ico")) { soup_message_set_status(msg, SOUP_STATUS_NOT_FOUND); return; } soup_message_set_status(msg, SOUP_STATUS_OK); char* body = g_strdup_printf("<html><title>%s</title><body>%s</body></html>", path + 1, path + 1); soup_message_body_append(msg->response_body, SOUP_MEMORY_TAKE, body, strlen(body)); soup_message_body_complete(msg->response_body); } class BackForwardListTest: public WebViewTest { public: MAKE_GLIB_TEST_FIXTURE(BackForwardListTest); enum { Backward, Forward }; enum { CurrentItem = 1 << 0, AddedItem = 1 << 1, RemovedItems = 1 << 2 }; static void checkItem(WebKitBackForwardListItem* item, const char* title, const char* uri, const char* originalURI) { g_assert(item); g_assert_cmpstr(webkit_back_forward_list_item_get_uri(item), ==, uri); g_assert_cmpstr(webkit_back_forward_list_item_get_title(item), == , title); g_assert_cmpstr(webkit_back_forward_list_item_get_original_uri(item), ==, originalURI); } static void checkItemIndex(WebKitBackForwardList* list) { g_assert(webkit_back_forward_list_get_nth_item(list, -1) == webkit_back_forward_list_get_back_item(list)); g_assert(webkit_back_forward_list_get_nth_item(list, 0) == webkit_back_forward_list_get_current_item(list)); g_assert(webkit_back_forward_list_get_nth_item(list, 1) == webkit_back_forward_list_get_forward_item(list)); } static void checkList(WebKitBackForwardList* list, unsigned type, WebKitBackForwardListItem** items, unsigned nItems) { GList* listItems = type == BackForwardListTest::Backward ? webkit_back_forward_list_get_back_list(list) : webkit_back_forward_list_get_forward_list(list); g_assert(listItems); unsigned i = 0; for (GList* listItem = listItems; listItem; listItem = g_list_next(listItem), i++) { g_assert_cmpuint(i, <, nItems); g_assert(listItem->data == items[i]); } g_list_free(listItems); } static void backForwardListChanged(WebKitBackForwardList* list, WebKitBackForwardListItem* addedItem, GList* removedItems, BackForwardListTest* test) { test->m_hasChanged = true; if (test->m_changedFlags & BackForwardListTest::AddedItem) { g_assert(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(addedItem)); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(addedItem)); } else g_assert(!addedItem); if (test->m_changedFlags & BackForwardListTest::RemovedItems) { g_assert(removedItems); for (GList* iter = removedItems; iter; iter = iter->next) { g_assert(WEBKIT_IS_BACK_FORWARD_LIST_ITEM(iter->data)); if (test->m_expectedRemovedItems) g_assert(g_list_find(test->m_expectedRemovedItems, iter->data)); } } else g_assert(!removedItems); } BackForwardListTest() : m_list(webkit_web_view_get_back_forward_list(m_webView)) , m_changedFlags(0) , m_hasChanged(false) , m_expectedRemovedItems(0) { g_signal_connect(m_list, "changed", G_CALLBACK(backForwardListChanged), this); assertObjectIsDeletedWhenTestFinishes(G_OBJECT(m_list)); } ~BackForwardListTest() { g_signal_handlers_disconnect_matched(m_list, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, this); } void waitUntilLoadFinished() { m_hasChanged = false; WebViewTest::waitUntilLoadFinished(); g_assert(m_hasChanged); } void waitUntilLoadFinishedAndCheckRemovedItems(GList* removedItems) { m_expectedRemovedItems = removedItems; waitUntilLoadFinished(); m_expectedRemovedItems = 0; } WebKitBackForwardList* m_list; unsigned long m_changedFlags; bool m_hasChanged; GList* m_expectedRemovedItems; }; static void testBackForwardListNavigation(BackForwardListTest* test, gconstpointer) { WebKitBackForwardListItem* items[1]; g_assert(!webkit_web_view_can_go_back(test->m_webView)); g_assert(!webkit_web_view_can_go_forward(test->m_webView)); g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 0); g_assert(!webkit_back_forward_list_get_current_item(test->m_list)); g_assert(!webkit_back_forward_list_get_back_item(test->m_list)); g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); BackForwardListTest::checkItemIndex(test->m_list); g_assert(!webkit_back_forward_list_get_back_list(test->m_list)); g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); CString uriPage1 = kServer->getURIForPath("/Page1"); test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem; test->loadURI(uriPage1.data()); test->waitUntilLoadFinished(); g_assert(!webkit_web_view_can_go_back(test->m_webView)); g_assert(!webkit_web_view_can_go_forward(test->m_webView)); g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 1); WebKitBackForwardListItem* itemPage1 = webkit_back_forward_list_get_current_item(test->m_list); BackForwardListTest::checkItem(itemPage1, "Page1", uriPage1.data(), uriPage1.data()); g_assert(!webkit_back_forward_list_get_back_item(test->m_list)); g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); BackForwardListTest::checkItemIndex(test->m_list); g_assert(!webkit_back_forward_list_get_back_list(test->m_list)); g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); CString uriPage2 = kServer->getURIForPath("/Page2"); test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem; test->loadURI(uriPage2.data()); test->waitUntilLoadFinished(); g_assert(webkit_web_view_can_go_back(test->m_webView)); g_assert(!webkit_web_view_can_go_forward(test->m_webView)); g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 2); WebKitBackForwardListItem* itemPage2 = webkit_back_forward_list_get_current_item(test->m_list); BackForwardListTest::checkItem(itemPage2, "Page2", uriPage2.data(), uriPage2.data()); g_assert(webkit_back_forward_list_get_back_item(test->m_list) == itemPage1); g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); BackForwardListTest::checkItemIndex(test->m_list); items[0] = itemPage1; BackForwardListTest::checkList(test->m_list, BackForwardListTest::Backward, items, 1); g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); test->m_changedFlags = BackForwardListTest::CurrentItem; test->goBack(); test->waitUntilLoadFinished(); g_assert(!webkit_web_view_can_go_back(test->m_webView)); g_assert(webkit_web_view_can_go_forward(test->m_webView)); g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 2); g_assert(itemPage1 == webkit_back_forward_list_get_current_item(test->m_list)); BackForwardListTest::checkItem(webkit_back_forward_list_get_current_item(test->m_list), "Page1", uriPage1.data(), uriPage1.data()); g_assert(!webkit_back_forward_list_get_back_item(test->m_list)); g_assert(webkit_back_forward_list_get_forward_item(test->m_list) == itemPage2); BackForwardListTest::checkItemIndex(test->m_list); g_assert(!webkit_back_forward_list_get_back_list(test->m_list)); items[0] = itemPage2; BackForwardListTest::checkList(test->m_list, BackForwardListTest::Forward, items, 1); test->m_changedFlags = BackForwardListTest::CurrentItem; test->goForward(); test->waitUntilLoadFinished(); g_assert(webkit_web_view_can_go_back(test->m_webView)); g_assert(!webkit_web_view_can_go_forward(test->m_webView)); g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, 2); g_assert(itemPage2 == webkit_back_forward_list_get_current_item(test->m_list)); BackForwardListTest::checkItem(webkit_back_forward_list_get_current_item(test->m_list), "Page2", uriPage2.data(), uriPage2.data()); g_assert(webkit_back_forward_list_get_back_item(test->m_list) == itemPage1); g_assert(!webkit_back_forward_list_get_forward_item(test->m_list)); BackForwardListTest::checkItemIndex(test->m_list); items[0] = itemPage1; BackForwardListTest::checkList(test->m_list, BackForwardListTest::Backward, items, 1); g_assert(!webkit_back_forward_list_get_forward_list(test->m_list)); test->m_changedFlags = BackForwardListTest::CurrentItem; test->goToBackForwardListItem(itemPage1); test->waitUntilLoadFinished(); g_assert(itemPage1 == webkit_back_forward_list_get_current_item(test->m_list)); } static void testBackForwardListLimitAndCache(BackForwardListTest* test, gconstpointer) { for (int i = 0; i < kBackForwardListLimit; i++) { GOwnPtr<char> path(g_strdup_printf("/Page%d", i)); test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem; test->loadURI(kServer->getURIForPath(path.get()).data()); test->waitUntilLoadFinished(); } g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, kBackForwardListLimit); WebKitBackForwardListItem* itemPageFirst = webkit_back_forward_list_get_nth_item(test->m_list, -(kBackForwardListLimit - 1)); GOwnPtr<GList> removedItems(g_list_prepend(0, itemPageFirst)); GOwnPtr<char> path(g_strdup_printf("/Page%d", kBackForwardListLimit)); test->m_changedFlags = BackForwardListTest::CurrentItem | BackForwardListTest::AddedItem | BackForwardListTest::RemovedItems; test->loadURI(kServer->getURIForPath(path.get()).data()); test->waitUntilLoadFinishedAndCheckRemovedItems(removedItems.get()); g_assert_cmpuint(webkit_back_forward_list_get_length(test->m_list), ==, kBackForwardListLimit); } void beforeAll() { kServer = new WebKitTestServer(); kServer->run(serverCallback); BackForwardListTest::add("BackForwardList", "navigation", testBackForwardListNavigation); BackForwardListTest::add("BackForwardList", "list-limit-and-cache", testBackForwardListLimitAndCache); } void afterAll() { delete kServer; }
11,738
4,067
/* * Copyright (c) 2018, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company 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. */ #include <stdint.h> #include <memory> #include <set> #include <string> #include "mobile/add_command_request.h" #include "gtest/gtest.h" #include "utils/helpers.h" #include "application_manager/commands/command_request_test.h" #include "application_manager/event_engine/event.h" #include "application_manager/mock_application.h" #include "application_manager/mock_application_manager.h" #include "application_manager/mock_help_prompt_manager.h" #include "application_manager/mock_hmi_interface.h" #include "application_manager/mock_message_helper.h" #include "application_manager/mock_resume_ctrl.h" #include "application_manager/resumption/resumption_data_processor.h" #include "application_manager/smart_object_keys.h" #include "smart_objects/smart_object.h" #include "utils/custom_string.h" namespace test { namespace components { namespace commands_test { namespace mobile_commands_test { namespace add_command_request { namespace am = application_manager; namespace am_test = application_manager_test; using am::ApplicationManager; using am::ApplicationSharedPtr; using am::commands::CommandImpl; using am::commands::MessageSharedPtr; using am::event_engine::EventObserver; using ns_smart_device_link::ns_smart_objects::SmartObjectSPtr; using sdl_rpc_plugin::commands::AddCommandRequest; using ::test::components::application_manager_test::MockApplication; using ::testing::_; using ::testing::InSequence; using ::testing::Return; using namespace smart_objects; using app_mngr::commands::RequestFromMobileImpl; namespace custom_str = utils::custom_string; namespace strings = ::application_manager::strings; namespace mobile_result = mobile_apis::Result; namespace hmi_response = ::application_manager::hmi_response; namespace hmi_request = ::application_manager::hmi_request; using namespace strings; namespace { const hmi_apis::FunctionID::eType kInvalidFunctionId = hmi_apis::FunctionID::INVALID_ENUM; const uint32_t kAppId = 1u; const uint32_t kCmdId = 1u; const uint32_t kConnectionKey = 2u; const std::string kMenuName = "LG"; const uint32_t kFirstParentId = 10u; const uint32_t kSecondParentId = 1u; const std::string kErroredVRCommand = "l\namer"; const std::string kFirstVrCommand = "lamer"; const std::string kSecondVrCommand = "hacker"; const uint32_t kFirstCommandId = 10u; const uint32_t kSecondCommandId = 11u; const int32_t kType = 34; const int32_t kGrammarId = 12; const int32_t kPosition = 10; } // namespace class AddCommandRequestTest : public CommandRequestTest<CommandsTestMocks::kIsNice> { public: AddCommandRequestTest() : msg_(CreateMessage()) , smart_obj_(smart_objects::SmartType_Null) , default_app_name_("test_default_app_name_") , lock_ptr_(std::make_shared<sync_primitives::Lock>()) , mock_help_prompt_manager_( std::make_shared<am_test::MockHelpPromptManager>()) , mock_app_(CreateMockApp()) { EXPECT_CALL(app_mngr_, application(kConnectionKey)) .WillRepeatedly(Return(mock_app_)); InitGetters(); InitBasicMessage(); } protected: void InitBasicMessage() { (*msg_)[params][connection_key] = kConnectionKey; (*msg_)[msg_params][app_id] = kAppId; (*msg_)[msg_params][app_name] = default_app_name_; } void InitGetters() { ON_CALL(*mock_app_, app_id()).WillByDefault(Return(kAppId)); ON_CALL(*mock_app_, FindCommand(kCmdId)).WillByDefault(Return(smart_obj_)); } void CreateBasicParamsUIRequest() { SmartObject menu_params = SmartObject(SmartType_Map); menu_params[position] = kPosition; menu_params[menu_name] = kMenuName; SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[cmd_id] = kCmdId; msg_params[strings::menu_params] = menu_params; msg_params[cmd_icon] = 1; msg_params[cmd_icon][value] = "10"; msg_params[info] = "UI info"; } void CreateBasicParamsVRRequest() { SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[cmd_id] = kCmdId; msg_params[vr_commands] = SmartObject(SmartType_Array); msg_params[vr_commands][0] = kFirstVrCommand; msg_params[type] = kPosition; msg_params[grammar_id] = kGrammarId; msg_params[info] = "VR info"; } const am::CommandsMap CreateCommandsMap(SmartObject& first_command, SmartObject& second_command) { second_command[menu_params] = SmartObject(SmartType_Map); second_command[menu_params][hmi_request::parent_id] = kFirstParentId; second_command[menu_params][menu_name] = kMenuName; second_command[vr_commands] = SmartObject(SmartType_Array); second_command[vr_commands][0] = kSecondVrCommand; am::CommandsMap commands_map; commands_map.insert(std::make_pair(kFirstCommandId, &first_command)); commands_map.insert(std::make_pair(kSecondCommandId, &second_command)); return commands_map; } void CheckOnTimeOutCommandDeletion( const hmi_apis::FunctionID::eType incoming_cmd, const hmi_apis::FunctionID::eType cmd_to_delete) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[menu_params][hmi_request::parent_id] = kSecondParentId; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); SmartObject first_command = SmartObject(SmartType_Map); SmartObject second_command = SmartObject(SmartType_Map); const am::CommandsMap commands_map = CreateCommandsMap(first_command, second_command); EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); SmartObject sub_menu(SmartType_Map); EXPECT_CALL(*mock_app_, FindSubMenu(kSecondParentId)) .WillOnce(Return(sub_menu)); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(mock_rpc_service_, ManageMobileCommand(_, _)).Times(0); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); Event event(incoming_cmd); event.set_smart_object(*msg_); request_ptr->on_event(event); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(cmd_to_delete), _)) .WillOnce(Return(true)); SmartObjectSPtr response = std::make_shared<SmartObject>(SmartType_Map); (*response)[strings::msg_params][strings::info] = "info"; EXPECT_CALL( mock_message_helper_, CreateNegativeResponse(_, _, _, mobile_apis::Result::GENERIC_ERROR)) .WillOnce(Return(response)); EXPECT_CALL( mock_rpc_service_, ManageMobileCommand(response, am::commands::Command::CommandSource::SOURCE_SDL)); std::shared_ptr<RequestFromMobileImpl> base_class_request = static_cast<std::shared_ptr<RequestFromMobileImpl> >(request_ptr); base_class_request->OnTimeOut(); } MessageSharedPtr msg_; smart_objects::SmartObject smart_obj_; const utils::custom_string::CustomString default_app_name_; std::shared_ptr<sync_primitives::Lock> lock_ptr_; std::shared_ptr<am_test::MockHelpPromptManager> mock_help_prompt_manager_; MockAppPtr mock_app_; }; TEST_F(AddCommandRequestTest, Run_AppNotExisted_EXPECT_AppNotRegistered) { CreateBasicParamsUIRequest(); EXPECT_CALL(app_mngr_, application(kConnectionKey)) .WillOnce(Return(ApplicationSharedPtr())); EXPECT_CALL( mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_result::APPLICATION_NOT_REGISTERED), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_ImageVerificationFailed_EXPECT_INVALID_DATA) { CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::INVALID_DATA)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_ImageVerificationFailed_EXPECT_WARNINGS) { CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::WARNINGS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_MenuNameHasSyntaxError_EXPECT_INVALID_DATA) { CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[menu_params][hmi_request::parent_id] = kFirstParentId; const std::string errored_menu_name = "L\nG"; msg_params[menu_params][menu_name] = errored_menu_name; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); SmartObject parent = SmartObject(SmartType_Map); EXPECT_CALL(*mock_app_, FindSubMenu(kFirstParentId)).WillOnce(Return(parent)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_VRCommandsHaveSyntaxError_EXPECT_INVALID_DATA) { CreateBasicParamsVRRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[vr_commands][0] = kErroredVRCommand; EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_CMDIconHasError_EXPECT_INVALID_DATA) { MessageSharedPtr msg = CreateMessage(); SmartObject& msg_params = (*msg)[strings::msg_params]; (*msg)[params][connection_key] = kConnectionKey; msg_params[cmd_id] = kCmdId; msg_params[cmd_icon] = 1; const std::string errored_cmd_icon_value = "1\n0"; msg_params[cmd_icon][value] = errored_cmd_icon_value; msg_params[vr_commands][0] = kFirstVrCommand; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_CommandIDAlreadyExists_EXPECT_INVALID_ID) { CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); SmartObject existing_cmd_so(smart_objects::SmartType_Map); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)) .WillOnce(Return(existing_cmd_so)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_ID), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_CommandNameAlreadyExists_EXPECT_Forwarded) { CreateBasicParamsUIRequest(); (*msg_)[msg_params][menu_name] = kMenuName; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); EXPECT_CALL(*mock_app_, AddCommand(_, (*msg_)[msg_params])); SmartObject first_command = SmartObject(SmartType_Map); SmartObject second_command = SmartObject(SmartType_Map); am::CommandsMap commands_map = CreateCommandsMap(first_command, second_command); EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_CmdAndMsgParentIDsAreDifferentSubmenuNotExisted_EXPECT_INVALID_ID) { CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[menu_params][hmi_request::parent_id] = kSecondParentId; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); SmartObject first_command = SmartObject(SmartType_Map); SmartObject second_command = SmartObject(SmartType_Map); const am::CommandsMap commands_map = CreateCommandsMap(first_command, second_command); EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); SmartObject invalid_command(SmartType_Null); EXPECT_CALL(*mock_app_, FindSubMenu(kSecondParentId)) .WillOnce(Return(invalid_command)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_ID), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_CmdAndMsgVrSynonymsAreTheSame_EXPECT_DUPLICATE_NAME) { CreateBasicParamsVRRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[menu_params][hmi_request::parent_id] = kSecondParentId; msg_params[vr_commands][0] = kSecondVrCommand; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); SmartObject first_command = SmartObject(SmartType_Map); SmartObject second_command = SmartObject(SmartType_Map); const am::CommandsMap commands_map = CreateCommandsMap(first_command, second_command); EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); SmartObject sub_menu(SmartType_Map); EXPECT_CALL(*mock_app_, FindSubMenu(kSecondParentId)) .WillOnce(Return(sub_menu)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::DUPLICATE_NAME), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_MsgDataEmpty_EXPECT_INVALID_DATA) { MessageSharedPtr msg = CreateMessage(); (*msg)[params][connection_key] = kConnectionKey; SmartObject& msg_params = (*msg)[strings::msg_params]; msg_params[app_id] = kAppId; msg_params[cmd_id] = kCmdId; EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg); request_ptr->Run(); } TEST_F(AddCommandRequestTest, Run_CmdAndMsg_UI_and_Vr_AreCorrect_EXPECT_VR_AND_UI_SENT) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; msg_params[menu_params][hmi_request::parent_id] = kSecondParentId; SmartObject& image = msg_params[cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); SmartObject first_command = SmartObject(SmartType_Map); SmartObject second_command = SmartObject(SmartType_Map); const am::CommandsMap commands_map = CreateCommandsMap(first_command, second_command); EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); SmartObject sub_menu(SmartType_Map); EXPECT_CALL(*mock_app_, FindSubMenu(kSecondParentId)) .WillOnce(Return(sub_menu)); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(mock_rpc_service_, ManageMobileCommand(_, _)).Times(0); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, GetRunMethods_SUCCESS) { CreateBasicParamsUIRequest(); SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); EXPECT_CALL(*mock_app_, AddCommand(kCmdId, (*msg_)[msg_params])); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); } TEST_F(AddCommandRequestTest, OnEvent_UI_SUCCESS) { CreateBasicParamsUIRequest(); (*msg_)[params][hmi_response::code] = hmi_apis::Common_Result::SUCCESS; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, AddCommand(kCmdId, (*msg_)[msg_params])); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly( Return(DataAccessor<am::CommandsMap>(commands_map, lock_ptr_))); Event event(hmi_apis::FunctionID::UI_AddCommand); event.set_smart_object(*msg_); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(*mock_app_, help_prompt_manager()) .WillOnce(ReturnRef(*mock_help_prompt_manager_)); EXPECT_CALL(*mock_help_prompt_manager_, OnVrCommandAdded(kCmdId, (*msg_)[msg_params], false)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); request_ptr->on_event(event); } TEST_F(AddCommandRequestTest, OnEvent_VR_SUCCESS) { CreateBasicParamsVRRequest(); MessageSharedPtr msg = CreateMessage(SmartType_Map); (*msg)[params][hmi_response::code] = hmi_apis::Common_Result::SUCCESS; (*msg)[msg_params][cmd_id] = kCmdId; Event event(hmi_apis::FunctionID::VR_AddCommand); event.set_smart_object(*msg); EXPECT_CALL(*mock_app_, AddCommand(kCmdId, (*msg_)[msg_params])); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly( Return(DataAccessor<am::CommandsMap>(commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(*mock_app_, help_prompt_manager()) .WillOnce(ReturnRef(*mock_help_prompt_manager_)); EXPECT_CALL(*mock_help_prompt_manager_, OnVrCommandAdded(kCmdId, (*msg_)[msg_params], false)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); request_ptr->on_event(event); } TEST_F(AddCommandRequestTest, OnTimeOut_EXPECT_VR_DeleteCommand) { CheckOnTimeOutCommandDeletion(hmi_apis::FunctionID::VR_AddCommand, hmi_apis::FunctionID::VR_DeleteCommand); } TEST_F(AddCommandRequestTest, OnTimeOut_EXPECT_UI_DeleteCommand) { CheckOnTimeOutCommandDeletion(hmi_apis::FunctionID::UI_AddCommand, hmi_apis::FunctionID::UI_DeleteCommand); } TEST_F(AddCommandRequestTest, OnEvent_BothSend_SUCCESS) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::WARNINGS; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); event_vr.set_smart_object(*msg_); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(*mock_app_, help_prompt_manager()) .WillOnce(ReturnRef(*mock_help_prompt_manager_)); EXPECT_CALL(*mock_help_prompt_manager_, OnVrCommandAdded(kCmdId, _, false)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)).Times(0); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); request_ptr->on_event(event_ui); request_ptr->on_event(event_vr); } TEST_F(AddCommandRequestTest, OnEvent_UnknownEvent_UNSUCCESS) { EXPECT_CALL(mock_rpc_service_, ManageMobileCommand(_, _)).Times(0); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); Event event(hmi_apis::FunctionID::INVALID_ENUM); request_ptr->on_event(event); } TEST_F(AddCommandRequestTest, OnEvent_AppNotExisted_UNSUCCESS) { CreateBasicParamsUIRequest(); EXPECT_CALL(app_mngr_, application(kConnectionKey)) .WillOnce(Return(ApplicationSharedPtr())); Event event(hmi_apis::FunctionID::UI_AddCommand); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand(_, _)).Times(0); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->on_event(event); } TEST_F(AddCommandRequestTest, OnEvent_HmiResponseCodeIsRejected_ExpectUICommandRemoved) { CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::REJECTED; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::REJECTED), _)); Event event(hmi_apis::FunctionID::UI_AddCommand); event.set_smart_object(*msg_); request_ptr->on_event(event); } TEST_F(AddCommandRequestTest, OnEvent_HmiResponseCodeIsWarnings_ExpectCommandUpdated) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::WARNINGS; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::WARNINGS), _)); EXPECT_CALL(*mock_app_, help_prompt_manager()) .WillOnce(ReturnRef(*mock_help_prompt_manager_)); EXPECT_CALL(*mock_help_prompt_manager_, OnVrCommandAdded(kCmdId, _, false)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); event_vr.set_smart_object(*msg_); request_ptr->on_event(event_ui); request_ptr->on_event(event_vr); } TEST_F( AddCommandRequestTest, OnEvent_UI_HmiResponseCodeIsGenericError_VR_HmiResponseCodeIsUnsupportedResourse_ExpectCommandRemoved) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::GENERIC_ERROR; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_); request_ptr->on_event(event_ui); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); MessageSharedPtr msg_vr = CreateMessage(SmartType_Map); (*msg_vr)[strings::params][hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; (*msg_vr)[msg_params][cmd_id] = kCmdId; event_vr.set_smart_object(*msg_vr); request_ptr->on_event(event_vr); } TEST_F( AddCommandRequestTest, OnEvent_VR_HmiResponseCodeIsGenericError_UI_HmiResponseCodeIsUnsupportedResourse_ExpectCommandRemoved) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::GENERIC_ERROR; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); event_vr.set_smart_object(*msg_); request_ptr->on_event(event_vr); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); MessageSharedPtr msg_ui = CreateMessage(SmartType_Map); (*msg_ui)[strings::params][hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; (*msg_ui)[msg_params][cmd_id] = kCmdId; event_ui.set_smart_object(*msg_ui); request_ptr->on_event(event_ui); } TEST_F( AddCommandRequestTest, OnEvent_UI_VR_HmiResponseCodeIsUnsupportedResourse_UI_NotAvailableInterfaceState_ExpectCommandRemoved) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI)) .WillRepeatedly( Return(am::HmiInterfaces::InterfaceState::STATE_NOT_AVAILABLE)); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_VR)) .WillRepeatedly(Return(am::HmiInterfaces::STATE_AVAILABLE)); EXPECT_CALL( mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::UNSUPPORTED_RESOURCE), _)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); event_vr.set_smart_object(*msg_); request_ptr->on_event(event_ui); request_ptr->on_event(event_vr); } TEST_F( AddCommandRequestTest, OnEvent_UI_VR_HmiResponseCodeIsUnsupportedResourse_VR_NotAvailableInterfaceState_ExpectCommandRemoved) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI)) .WillRepeatedly(Return(am::HmiInterfaces::STATE_AVAILABLE)); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_VR)) .WillRepeatedly( Return(am::HmiInterfaces::InterfaceState::STATE_NOT_AVAILABLE)); EXPECT_CALL( mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::UNSUPPORTED_RESOURCE), _)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); event_vr.set_smart_object(*msg_); request_ptr->on_event(event_ui); request_ptr->on_event(event_vr); } TEST_F( AddCommandRequestTest, OnEvent_UI_HmiResponseCodeIsUnsupportedResource_NotAvailableInterfaceState_ExpectCommandRemoved) { CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI)) .WillRepeatedly( Return(am::HmiInterfaces::InterfaceState::STATE_NOT_AVAILABLE)); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_VR)) .WillRepeatedly( Return(am::HmiInterfaces::InterfaceState::STATE_NOT_AVAILABLE)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); EXPECT_CALL( mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::UNSUPPORTED_RESOURCE), _)); Event event(hmi_apis::FunctionID::UI_AddCommand); event.set_smart_object(*msg_); request_ptr->on_event(event); } TEST_F( AddCommandRequestTest, OnEvent_VR_HmiResponseCodeIsUnsupportedResource_NotAvailableInterfaceState_ExpectCommandRemoved) { CreateBasicParamsVRRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); EXPECT_CALL( mock_rpc_service_, ManageHMICommand(HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI)) .WillRepeatedly( Return(am::HmiInterfaces::InterfaceState::STATE_NOT_AVAILABLE)); EXPECT_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_VR)) .WillRepeatedly( Return(am::HmiInterfaces::InterfaceState::STATE_NOT_AVAILABLE)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); EXPECT_CALL( mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::UNSUPPORTED_RESOURCE), _)); Event event(hmi_apis::FunctionID::VR_AddCommand); event.set_smart_object(*msg_); request_ptr->on_event(event); } TEST_F(AddCommandRequestTest, OnEvent_UI_EventWithNotSuccesResponseCode_ExpectVRCommandDelete) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::SUCCESS; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::GENERIC_ERROR), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); MessageSharedPtr msg_ui = CreateMessage(SmartType_Map); (*msg_ui)[strings::params][hmi_response::code] = hmi_apis::Common_Result::ABORTED; (*msg_ui)[msg_params][cmd_id] = kCmdId; Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_ui); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); event_vr.set_smart_object(*msg_); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_DeleteCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)).Times(2); request_ptr->on_event(event_ui); request_ptr->on_event(event_vr); } TEST_F(AddCommandRequestTest, OnEvent_UI_VR_Events_VRErrorPresent_ExpectRemoveCommand) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& params = (*msg_)[strings::params]; params[hmi_response::code] = hmi_apis::Common_Result::SUCCESS; SmartObject& image = (*msg_)[msg_params][cmd_icon]; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); am::CommandsMap commands_map; EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( MobileResultCodeIs(mobile_apis::Result::GENERIC_ERROR), _)); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); Event event_ui(hmi_apis::FunctionID::UI_AddCommand); event_ui.set_smart_object(*msg_); request_ptr->on_event(event_ui); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_DeleteCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)).Times(2); Event event_vr(hmi_apis::FunctionID::VR_AddCommand); MessageSharedPtr msg_vr = CreateMessage(SmartType_Map); (*msg_vr)[strings::params][hmi_response::code] = hmi_apis::Common_Result::ABORTED; (*msg_vr)[msg_params][cmd_id] = kCmdId; event_vr.set_smart_object(*msg_vr); request_ptr->on_event(event_vr); } TEST_F(AddCommandRequestTest, OnTimeOut_AppNotExisted_NoAppRemoveCommandCalled) { CreateBasicParamsUIRequest(); EXPECT_CALL(app_mngr_, application(kConnectionKey)) .WillOnce(Return(ApplicationSharedPtr())); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)).Times(0); SmartObjectSPtr response = std::make_shared<SmartObject>(SmartType_Map); (*response)[strings::msg_params][strings::info] = "info"; EXPECT_CALL( mock_message_helper_, CreateNegativeResponse(_, _, _, mobile_apis::Result::GENERIC_ERROR)) .WillOnce(Return(response)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( response, am::commands::Command::CommandSource::SOURCE_SDL)); std::shared_ptr<RequestFromMobileImpl> base_class_request = static_cast<std::shared_ptr<RequestFromMobileImpl> >( CreateCommand<AddCommandRequest>(msg_)); base_class_request->OnTimeOut(); } TEST_F(AddCommandRequestTest, OnTimeOut_AppRemoveCommandCalled) { CreateBasicParamsVRRequest(); CreateBasicParamsUIRequest(); SmartObject& msg_params = (*msg_)[strings::msg_params]; SmartObject& image = msg_params[cmd_icon]; msg_params[menu_params][hmi_request::parent_id] = kSecondParentId; EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _)) .WillOnce(Return(mobile_apis::Result::SUCCESS)); EXPECT_CALL(*mock_app_, FindCommand(kCmdId)).WillOnce(Return(smart_obj_)); SmartObject first_command = SmartObject(SmartType_Map); SmartObject second_command = SmartObject(SmartType_Map); const am::CommandsMap commands_map = CreateCommandsMap(first_command, second_command); EXPECT_CALL(*mock_app_, commands_map()) .WillRepeatedly(Return(DataAccessor<application_manager::CommandsMap>( commands_map, lock_ptr_))); SmartObject sub_menu(SmartType_Map); EXPECT_CALL(*mock_app_, FindSubMenu(kSecondParentId)) .WillOnce(Return(sub_menu)); { InSequence dummy; EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::UI_AddCommand), _)) .WillOnce(Return(true)); EXPECT_CALL(mock_rpc_service_, ManageHMICommand( HMIResultCodeIs(hmi_apis::FunctionID::VR_AddCommand), _)) .WillOnce(Return(true)); } EXPECT_CALL(mock_rpc_service_, ManageMobileCommand(_, _)).Times(0); std::shared_ptr<AddCommandRequest> request_ptr = CreateCommand<AddCommandRequest>(msg_); request_ptr->Run(); EXPECT_CALL(*mock_app_, RemoveCommand(kCmdId)); SmartObjectSPtr response = std::make_shared<SmartObject>(SmartType_Map); (*response)[strings::msg_params][strings::info] = "info"; EXPECT_CALL( mock_message_helper_, CreateNegativeResponse(_, _, _, mobile_apis::Result::GENERIC_ERROR)) .WillOnce(Return(response)); EXPECT_CALL(mock_rpc_service_, ManageMobileCommand( response, am::commands::Command::CommandSource::SOURCE_SDL)); std::shared_ptr<RequestFromMobileImpl> base_class_request = static_cast<std::shared_ptr<RequestFromMobileImpl> >(request_ptr); base_class_request->OnTimeOut(); } } // namespace add_command_request } // namespace mobile_commands_test } // namespace commands_test } // namespace components } // namespace test
47,717
16,345
// Copyright (C) 2012-2015 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <string> #include <gtest/gtest.h> #include <boost/scoped_ptr.hpp> #include <dns/nsec3hash.h> #include <dns/labelsequence.h> #include <dns/rdataclass.h> #include <util/encode/hex.h> using boost::scoped_ptr; using namespace std; using namespace isc::dns; using namespace isc::dns::rdata; using namespace isc::util; using namespace isc::util::encode; namespace { typedef scoped_ptr<NSEC3Hash> NSEC3HashPtr; // Commonly used NSEC3 suffix, defined to reduce the amount of typing const char* const nsec3_common = "2T7B4G4VSA5SMI47K61MV5BV1A22BOJR A RRSIG"; class NSEC3HashTest : public ::testing::Test { protected: NSEC3HashTest() : test_hash(NSEC3Hash::create(generic::NSEC3PARAM("1 0 12 aabbccdd"))), test_hash_nsec3(NSEC3Hash::create(generic::NSEC3 ("1 0 12 aabbccdd " + string(nsec3_common)))) { const uint8_t salt[] = {0xaa, 0xbb, 0xcc, 0xdd}; test_hash_args.reset(NSEC3Hash::create(1, 12, salt, sizeof(salt))); } ~NSEC3HashTest() { // Make sure we reset the hash creator to the default setNSEC3HashCreator(NULL); } // An NSEC3Hash object commonly used in tests. Parameters are borrowed // from the RFC5155 example. Construction of this object implicitly // checks a successful case of the creation. NSEC3HashPtr test_hash; // Similar to test_hash, but created from NSEC3 RR. NSEC3HashPtr test_hash_nsec3; // Similar to test_hash, but created from passed args. NSEC3HashPtr test_hash_args; }; TEST_F(NSEC3HashTest, unknownAlgorithm) { EXPECT_THROW(NSEC3HashPtr( NSEC3Hash::create( generic::NSEC3PARAM("2 0 12 aabbccdd"))), UnknownNSEC3HashAlgorithm); EXPECT_THROW(NSEC3HashPtr( NSEC3Hash::create( generic::NSEC3("2 0 12 aabbccdd " + string(nsec3_common)))), UnknownNSEC3HashAlgorithm); const uint8_t salt[] = {0xaa, 0xbb, 0xcc, 0xdd}; EXPECT_THROW(NSEC3HashPtr(NSEC3Hash::create(2, 12, salt, sizeof(salt))), UnknownNSEC3HashAlgorithm); } // Common checks for NSEC3 hash calculation void calculateCheck(NSEC3Hash& hash) { // A couple of normal cases from the RFC5155 example. EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", hash.calculate(Name("example"))); EXPECT_EQ("35MTHGPGCU1QG68FAB165KLNSNK3DPVL", hash.calculate(Name("a.example"))); // Check case-insensitiveness EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", hash.calculate(Name("EXAMPLE"))); // Repeat for the LabelSequence variant. // A couple of normal cases from the RFC5155 example. EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", hash.calculate(LabelSequence(Name("example")))); EXPECT_EQ("35MTHGPGCU1QG68FAB165KLNSNK3DPVL", hash.calculate(LabelSequence(Name("a.example")))); // Check case-insensitiveness EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", hash.calculate(LabelSequence(Name("EXAMPLE")))); } TEST_F(NSEC3HashTest, calculate) { { SCOPED_TRACE("calculate check with NSEC3PARAM based hash"); calculateCheck(*test_hash); } { SCOPED_TRACE("calculate check with NSEC3 based hash"); calculateCheck(*test_hash_nsec3); } { SCOPED_TRACE("calculate check with args based hash"); calculateCheck(*test_hash_args); } // Some boundary cases: 0-iteration and empty salt. Borrowed from the // .com zone data. EXPECT_EQ("CK0POJMG874LJREF7EFN8430QVIT8BSM", NSEC3HashPtr(NSEC3Hash::create(generic::NSEC3PARAM("1 0 0 -"))) ->calculate(Name("com"))); EXPECT_EQ("CK0POJMG874LJREF7EFN8430QVIT8BSM", NSEC3HashPtr(NSEC3Hash::create(generic::NSEC3PARAM("1 0 0 -"))) ->calculate(LabelSequence(Name("com")))); // Using unusually large iterations, something larger than the 8-bit range. // (expected hash value generated by BIND 9's dnssec-signzone) EXPECT_EQ("COG6A52MJ96MNMV3QUCAGGCO0RHCC2Q3", NSEC3HashPtr(NSEC3Hash::create( generic::NSEC3PARAM("1 0 256 AABBCCDD"))) ->calculate(LabelSequence(Name("example.org")))); } // Common checks for match cases template <typename RDATAType> void matchCheck(NSEC3Hash& hash, const string& postfix) { // If all parameters match, it's considered to be matched. EXPECT_TRUE(hash.match(RDATAType("1 0 12 aabbccdd" + postfix))); // Algorithm doesn't match EXPECT_FALSE(hash.match(RDATAType("2 0 12 aabbccdd" + postfix))); // Iterations doesn't match EXPECT_FALSE(hash.match(RDATAType("1 0 1 aabbccdd" + postfix))); // Salt doesn't match EXPECT_FALSE(hash.match(RDATAType("1 0 12 aabbccde" + postfix))); // Salt doesn't match: the other has an empty salt EXPECT_FALSE(hash.match(RDATAType("1 0 12 -" + postfix))); // Flags don't matter EXPECT_TRUE(hash.match(RDATAType("1 1 12 aabbccdd" + postfix))); } TEST_F(NSEC3HashTest, matchWithNSEC3) { { SCOPED_TRACE("match NSEC3PARAM based hash against NSEC3 parameters"); matchCheck<generic::NSEC3>(*test_hash, " " + string(nsec3_common)); } { SCOPED_TRACE("match NSEC3 based hash against NSEC3 parameters"); matchCheck<generic::NSEC3>(*test_hash_nsec3, " " + string(nsec3_common)); } } TEST_F(NSEC3HashTest, matchWithNSEC3PARAM) { { SCOPED_TRACE("match NSEC3PARAM based hash against NSEC3 parameters"); matchCheck<generic::NSEC3PARAM>(*test_hash, ""); } { SCOPED_TRACE("match NSEC3 based hash against NSEC3 parameters"); matchCheck<generic::NSEC3PARAM>(*test_hash_nsec3, ""); } } // A simple faked hash calculator and a dedicated creator for it. class TestNSEC3Hash : public NSEC3Hash { virtual string calculate(const Name&) const { return ("00000000000000000000000000000000"); } virtual string calculate(const LabelSequence&) const { return ("00000000000000000000000000000000"); } virtual bool match(const generic::NSEC3PARAM&) const { return (true); } virtual bool match(const generic::NSEC3&) const { return (true); } }; // This faked creator basically creates the faked calculator regardless of // the passed NSEC3PARAM or NSEC3. But if the most significant bit of flags // is set, it will behave like the default creator. class TestNSEC3HashCreator : public NSEC3HashCreator { public: virtual NSEC3Hash* create(const generic::NSEC3PARAM& param) const { if ((param.getFlags() & 0x80) != 0) { return (default_creator_.create(param)); } return (new TestNSEC3Hash); } virtual NSEC3Hash* create(const generic::NSEC3& nsec3) const { if ((nsec3.getFlags() & 0x80) != 0) { return (default_creator_.create(nsec3)); } return (new TestNSEC3Hash); } virtual NSEC3Hash* create(uint8_t, uint16_t, const uint8_t*, size_t) const { isc_throw(isc::Unexpected, "This method is not implemented here."); } private: DefaultNSEC3HashCreator default_creator_; }; TEST_F(NSEC3HashTest, setCreator) { // Re-check an existing case using the default creator/hash implementation EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(Name("example"))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(LabelSequence(Name("example")))); // Replace the creator, and confirm the hash values are faked TestNSEC3HashCreator test_creator; setNSEC3HashCreator(&test_creator); // Re-create the hash object with the new creator test_hash.reset(NSEC3Hash::create(generic::NSEC3PARAM("1 0 12 aabbccdd"))); EXPECT_EQ("00000000000000000000000000000000", test_hash->calculate(Name("example"))); EXPECT_EQ("00000000000000000000000000000000", test_hash->calculate(LabelSequence(Name("example")))); // Same for hash from NSEC3 RDATA test_hash.reset(NSEC3Hash::create(generic::NSEC3 ("1 0 12 aabbccdd " + string(nsec3_common)))); EXPECT_EQ("00000000000000000000000000000000", test_hash->calculate(Name("example"))); EXPECT_EQ("00000000000000000000000000000000", test_hash->calculate(LabelSequence(Name("example")))); // If we set a special flag big (0x80) on creation, it will act like the // default creator. test_hash.reset(NSEC3Hash::create(generic::NSEC3PARAM( "1 128 12 aabbccdd"))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(Name("example"))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(LabelSequence(Name("example")))); test_hash.reset(NSEC3Hash::create(generic::NSEC3 ("1 128 12 aabbccdd " + string(nsec3_common)))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(Name("example"))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(LabelSequence(Name("example")))); // Reset the creator to default, and confirm that setNSEC3HashCreator(NULL); test_hash.reset(NSEC3Hash::create(generic::NSEC3PARAM("1 0 12 aabbccdd"))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(Name("example"))); EXPECT_EQ("0P9MHAVEQVM6T7VBL5LOP2U3T2RP3TOM", test_hash->calculate(LabelSequence(Name("example")))); } } // end namespace
10,276
3,916
#include <cstdint> #include <stdexcept> #include <iostream> enum Side { NONE, LEFT, RIGHT }; class ChainLink { public: void append(ChainLink* rightPart) { if (this->right != NULL) throw std::logic_error("Link is already connected."); this->right = rightPart; rightPart->left = this; } Side longerSide() { /* throw std::logic_error("Waiting to be implemented"); */ auto cur = left; uint32_t leftLen{0}; uint32_t rightLen{0}; while((cur != nullptr) && (cur != right)){ cur = cur->left; ++leftLen; } if(cur == right) return Side::NONE; // reset curr cur = right; while(cur != nullptr) { cur = cur->right; ++rightLen; } if (rightLen == leftLen ) return Side::NONE; return rightLen>leftLen? Side::RIGHT : Side::LEFT; } private: ChainLink* left; ChainLink* right; }; #ifndef RunTests int main() { ChainLink* left = new ChainLink(); ChainLink* middle = new ChainLink(); ChainLink* right = new ChainLink(); left->append(middle); middle->append(right); std::cout << left->longerSide(); } #endif
1,262
400
#include <iostream> bool bipartition(std::pair<size_t, size_t>* edges, size_t* hamilton_cycle, bool* partition, size_t edges_size, bool* visited, size_t current_index, bool first_part = true) { if (visited[current_index]) { return partition[current_index] == first_part; } visited[current_index] = true; partition[current_index] = first_part; auto current = edges[current_index]; std::pair<size_t, size_t> hamilton_current({hamilton_cycle[current.first], hamilton_cycle[current.second]}); for (size_t i = 0; i < edges_size; ++i) { if (!((hamilton_current.first < hamilton_cycle[edges[i].first] && hamilton_cycle[edges[i].first] < hamilton_current.second && hamilton_current.second < hamilton_cycle[edges[i].second]) || (hamilton_current.first > hamilton_cycle[edges[i].first] && hamilton_cycle[edges[i].second] > hamilton_current.first && hamilton_current.second > hamilton_cycle[edges[i].second]))) { continue; } if (!bipartition(edges, hamilton_cycle, partition, edges_size, visited, i, !first_part)) { return false; } } return true; } int main() { size_t vertex_size; size_t edges_size; std::cin >> vertex_size >> edges_size; std::pair<size_t, size_t>* edges = new std::pair<size_t, size_t>[edges_size]; size_t* hamilton_cycle = new size_t[vertex_size]; bool* partition = new bool[edges_size]; std::fill(partition, partition + edges_size, false); for (size_t i = 0; i < edges_size; ++i) { std::cin >> edges[i].first >> edges[i].second; } for (size_t i = 0; i < vertex_size; ++i) { size_t vertex; std::cin >> vertex; hamilton_cycle[vertex - 1] = i; } for (size_t i = 0; i < edges_size; ++i) { if (hamilton_cycle[--edges[i].first] > hamilton_cycle[--edges[i].second]) { std::swap(edges[i].first, edges[i].second); } } bool* visited = new bool[edges_size]; std::fill(visited, visited + edges_size, false); for (size_t i = 0; i < edges_size; ++i) { if (!visited[i] && !bipartition(edges, hamilton_cycle, partition, edges_size, visited, i)) { std::cout << "NO\n"; return 0; } } std::cout << "YES\n"; for (size_t i = 0; i < vertex_size; ++i) { std::cout << 2 * hamilton_cycle[i] << ' ' << 0 << ' '; } std::cout << '\n'; for (size_t i = 0; i < edges_size; ++i) { size_t edge_begin = hamilton_cycle[edges[i].first]; size_t edge_end = hamilton_cycle[edges[i].second]; std::cout << edge_begin + edge_end << ' ' << (partition[i] ? 1 : -1) * abs(edge_begin - edge_end) << '\n'; } }
2,817
997
#ifndef INTERLINCK_DELPHI_SYNTAX_STATEMENTS_DELPHIRAISESTATEMENTSYNTAX_H #define INTERLINCK_DELPHI_SYNTAX_STATEMENTS_DELPHIRAISESTATEMENTSYNTAX_H #include "interlinck/Core/Syntax/SyntaxVariant.hpp" #include "interlinck/Core/Types.hpp" #include "Core/Basic/Macros.hpp" #include "Delphi/Syntax/Statements/DelphiStatementSyntax.hpp" namespace interlinck::Core::Support { class SyntaxFactory; } // end namespace interlinck::Core::Support namespace interlinck::Core::Syntax { class ISyntaxToken; } // end namespace interlinck::Core::Syntax namespace interlinck::Delphi::Syntax { class DelphiExpressionSyntax; class DelphiRaiseStatementSyntax : public DelphiStatementSyntax { public: explicit DelphiRaiseStatementSyntax(const Core::Syntax::ISyntaxToken* raiseKeyword, const Core::Syntax::ISyntaxToken* semiColonToken, const DelphiExpressionSyntax* expression = nullptr) noexcept; ~DelphiRaiseStatementSyntax() noexcept override = default; inline const Core::Syntax::ISyntaxToken* raiseKeyword() const noexcept { return _raiseKeyword; } inline const DelphiExpressionSyntax* expression() const noexcept { return _expression; } inline const Core::Syntax::ISyntaxToken* semiColonToken() const noexcept { return _semiColonToken; } inline il_size childCount() const noexcept final { return _expression != nullptr ? 3 : 2; } Core::Syntax::SyntaxVariant child(il_size index) const noexcept final; inline Core::Syntax::SyntaxVariant first() const noexcept final { return Core::Syntax::SyntaxVariant::asToken(_raiseKeyword); } inline Core::Syntax::SyntaxVariant last() const noexcept final { return Core::Syntax::SyntaxVariant::asToken(_semiColonToken); } inline il_string typeName() const noexcept override { CREATE_TYPENAME(DelphiRaiseStatementSyntax) } inline bool isRaiseStatement() const noexcept final { return true; } static const DelphiRaiseStatementSyntax* create(Core::Support::SyntaxFactory& syntaxFactory, const Core::Syntax::ISyntaxToken* raiseKeyword, const Core::Syntax::ISyntaxToken* semiColonToken, const DelphiExpressionSyntax* expression = nullptr) noexcept; private: const Core::Syntax::ISyntaxToken* _raiseKeyword; const Core::Syntax::ISyntaxToken* _semiColonToken; // might be optional; for example in an exception block // // except // raise; <-- re-raises the exception const DelphiExpressionSyntax* _expression; }; } // end namespace interlinck::Delphi::Syntax #endif // INTERLINCK_DELPHI_SYNTAX_STATEMENTS_DELPHIRAISESTATEMENTSYNTAX_H
2,778
788
#include <iostream> #include "Foo.h" using namespace std; int main (void) { Foo theFoo; cout << theFoo; theFoo.SetMsg("Hello World"); cout << theFoo; return 0; }
184
73
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "meta/MetaServiceUtils.h" #include "meta/MetaServiceHandler.h" #include "meta/processors/partsMan/CreateSpaceProcessor.h" #include "meta/processors/partsMan/DropSpaceProcessor.h" #include "meta/processors/partsMan/ListSpacesProcessor.h" #include "meta/processors/partsMan/GetSpaceProcessor.h" #include "meta/processors/partsMan/ListHostsProcessor.h" #include "meta/processors/partsMan/ListPartsProcessor.h" #include "meta/processors/partsMan/GetPartsAllocProcessor.h" #include "meta/processors/schemaMan/CreateTagProcessor.h" #include "meta/processors/schemaMan/AlterTagProcessor.h" #include "meta/processors/schemaMan/DropTagProcessor.h" #include "meta/processors/schemaMan/GetTagProcessor.h" #include "meta/processors/schemaMan/ListTagsProcessor.h" #include "meta/processors/schemaMan/CreateEdgeProcessor.h" #include "meta/processors/schemaMan/AlterEdgeProcessor.h" #include "meta/processors/schemaMan/DropEdgeProcessor.h" #include "meta/processors/schemaMan/GetEdgeProcessor.h" #include "meta/processors/schemaMan/ListEdgesProcessor.h" #include "meta/processors/indexMan/CreateTagIndexProcessor.h" #include "meta/processors/indexMan/DropTagIndexProcessor.h" #include "meta/processors/indexMan/GetTagIndexProcessor.h" #include "meta/processors/indexMan/ListTagIndexesProcessor.h" #include "meta/processors/indexMan/RebuildTagIndexProcessor.h" #include "meta/processors/indexMan/ListTagIndexStatusProcessor.h" #include "meta/processors/indexMan/CreateEdgeIndexProcessor.h" #include "meta/processors/indexMan/DropEdgeIndexProcessor.h" #include "meta/processors/indexMan/GetEdgeIndexProcessor.h" #include "meta/processors/indexMan/ListEdgeIndexesProcessor.h" #include "meta/processors/indexMan/RebuildEdgeIndexProcessor.h" #include "meta/processors/indexMan/ListEdgeIndexStatusProcessor.h" #include "meta/processors/customKV/MultiPutProcessor.h" #include "meta/processors/customKV/GetProcessor.h" #include "meta/processors/customKV/MultiGetProcessor.h" #include "meta/processors/customKV/ScanProcessor.h" #include "meta/processors/customKV/RemoveProcessor.h" #include "meta/processors/customKV/RemoveRangeProcessor.h" #include "meta/processors/admin/HBProcessor.h" #include "meta/processors/usersMan/AuthenticationProcessor.h" #include "meta/processors/admin/BalanceProcessor.h" #include "meta/processors/admin/LeaderBalanceProcessor.h" #include "meta/processors/admin/CreateSnapshotProcessor.h" #include "meta/processors/admin/DropSnapshotProcessor.h" #include "meta/processors/admin/ListSnapshotsProcessor.h" #include "meta/processors/configMan/RegConfigProcessor.h" #include "meta/processors/configMan/GetConfigProcessor.h" #include "meta/processors/configMan/SetConfigProcessor.h" #include "meta/processors/configMan/ListConfigsProcessor.h" #include "meta/processors/jobMan/AdminJobProcessor.h" #define RETURN_FUTURE(processor) \ auto f = processor->getFuture(); \ processor->process(req); \ return f; namespace nebula { namespace meta { folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createSpace(const cpp2::CreateSpaceReq& req) { auto* processor = CreateSpaceProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropSpace(const cpp2::DropSpaceReq& req) { auto* processor = DropSpaceProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListSpacesResp> MetaServiceHandler::future_listSpaces(const cpp2::ListSpacesReq& req) { auto* processor = ListSpacesProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::AdminJobResp> MetaServiceHandler::future_runAdminJob(const cpp2::AdminJobReq& req) { auto* processor = AdminJobProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetSpaceResp> MetaServiceHandler::future_getSpace(const cpp2::GetSpaceReq& req) { auto* processor = GetSpaceProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListHostsResp> MetaServiceHandler::future_listHosts(const cpp2::ListHostsReq& req) { auto* processor = ListHostsProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListPartsResp> MetaServiceHandler::future_listParts(const cpp2::ListPartsReq& req) { auto* processor = ListPartsProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetPartsAllocResp> MetaServiceHandler::future_getPartsAlloc(const cpp2::GetPartsAllocReq& req) { auto* processor = GetPartsAllocProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_multiPut(const cpp2::MultiPutReq& req) { auto* processor = MultiPutProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetResp> MetaServiceHandler::future_get(const cpp2::GetReq& req) { auto* processor = GetProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::MultiGetResp> MetaServiceHandler::future_multiGet(const cpp2::MultiGetReq& req) { auto* processor = MultiGetProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ScanResp> MetaServiceHandler::future_scan(const cpp2::ScanReq& req) { auto* processor = ScanProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_remove(const cpp2::RemoveReq& req) { auto* processor = RemoveProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_removeRange(const cpp2::RemoveRangeReq& req) { auto* processor = RemoveRangeProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createTag(const cpp2::CreateTagReq& req) { auto* processor = CreateTagProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_alterTag(const cpp2::AlterTagReq& req) { auto* processor = AlterTagProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropTag(const cpp2::DropTagReq& req) { auto* processor = DropTagProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetTagResp> MetaServiceHandler::future_getTag(const cpp2::GetTagReq &req) { auto* processor = GetTagProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListTagsResp> MetaServiceHandler::future_listTags(const cpp2::ListTagsReq& req) { auto* processor = ListTagsProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createEdge(const cpp2::CreateEdgeReq& req) { auto* processor = CreateEdgeProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_alterEdge(const cpp2::AlterEdgeReq& req) { auto* processor = AlterEdgeProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropEdge(const cpp2::DropEdgeReq& req) { auto* processor = DropEdgeProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetEdgeResp> MetaServiceHandler::future_getEdge(const cpp2::GetEdgeReq& req) { auto* processor = GetEdgeProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListEdgesResp> MetaServiceHandler::future_listEdges(const cpp2::ListEdgesReq& req) { auto* processor = ListEdgesProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createTagIndex(const cpp2::CreateTagIndexReq& req) { auto* processor = CreateTagIndexProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropTagIndex(const cpp2::DropTagIndexReq& req) { auto* processor = DropTagIndexProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetTagIndexResp> MetaServiceHandler::future_getTagIndex(const cpp2::GetTagIndexReq &req) { auto* processor = GetTagIndexProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListTagIndexesResp> MetaServiceHandler::future_listTagIndexes(const cpp2::ListTagIndexesReq& req) { auto* processor = ListTagIndexesProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_rebuildTagIndex(const cpp2::RebuildIndexReq& req) { auto* processor = RebuildTagIndexProcessor::instance(kvstore_, adminClient_.get()); RETURN_FUTURE(processor); } folly::Future<cpp2::ListIndexStatusResp> MetaServiceHandler::future_listTagIndexStatus(const cpp2::ListIndexStatusReq& req) { auto* processor = ListTagIndexStatusProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createEdgeIndex(const cpp2::CreateEdgeIndexReq& req) { auto* processor = CreateEdgeIndexProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropEdgeIndex(const cpp2::DropEdgeIndexReq& req) { auto* processor = DropEdgeIndexProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetEdgeIndexResp> MetaServiceHandler::future_getEdgeIndex(const cpp2::GetEdgeIndexReq& req) { auto* processor = GetEdgeIndexProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListEdgeIndexesResp> MetaServiceHandler::future_listEdgeIndexes(const cpp2::ListEdgeIndexesReq& req) { auto* processor = ListEdgeIndexesProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_rebuildEdgeIndex(const cpp2::RebuildIndexReq& req) { auto* processor = RebuildEdgeIndexProcessor::instance(kvstore_, adminClient_.get()); RETURN_FUTURE(processor); } folly::Future<cpp2::ListIndexStatusResp> MetaServiceHandler::future_listEdgeIndexStatus(const cpp2::ListIndexStatusReq& req) { auto* processor = ListEdgeIndexStatusProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::HBResp> MetaServiceHandler::future_heartBeat(const cpp2::HBReq& req) { auto* processor = HBProcessor::instance(kvstore_, clusterId_, &heartBeatStat_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createUser(const cpp2::CreateUserReq& req) { auto* processor = CreateUserProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropUser(const cpp2::DropUserReq& req) { auto* processor = DropUserProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_alterUser(const cpp2::AlterUserReq& req) { auto* processor = AlterUserProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_grantRole(const cpp2::GrantRoleReq& req) { auto* processor = GrantProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_revokeRole(const cpp2::RevokeRoleReq& req) { auto* processor = RevokeProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListUsersResp> MetaServiceHandler::future_listUsers(const cpp2::ListUsersReq& req) { auto* processor = ListUsersProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListRolesResp> MetaServiceHandler::future_listRoles(const cpp2::ListRolesReq& req) { auto* processor = ListRolesProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_changePassword(const cpp2::ChangePasswordReq& req) { auto* processor = ChangePasswordProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListRolesResp> MetaServiceHandler::future_getUserRoles(const cpp2::GetUserRolesReq& req) { auto* processor = GetUserRolesProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::BalanceResp> MetaServiceHandler::future_balance(const cpp2::BalanceReq& req) { auto* processor = BalanceProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_leaderBalance(const cpp2::LeaderBalanceReq& req) { auto* processor = LeaderBalanceProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_regConfig(const cpp2::RegConfigReq &req) { auto* processor = RegConfigProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::GetConfigResp> MetaServiceHandler::future_getConfig(const cpp2::GetConfigReq &req) { auto* processor = GetConfigProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_setConfig(const cpp2::SetConfigReq &req) { auto* processor = SetConfigProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ListConfigsResp> MetaServiceHandler::future_listConfigs(const cpp2::ListConfigsReq &req) { auto* processor = ListConfigsProcessor::instance(kvstore_); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_createSnapshot(const cpp2::CreateSnapshotReq& req) { auto* processor = CreateSnapshotProcessor::instance(kvstore_, adminClient_.get()); RETURN_FUTURE(processor); } folly::Future<cpp2::ExecResp> MetaServiceHandler::future_dropSnapshot(const cpp2::DropSnapshotReq& req) { auto* processor = DropSnapshotProcessor::instance(kvstore_, adminClient_.get()); RETURN_FUTURE(processor); } folly::Future<cpp2::ListSnapshotsResp> MetaServiceHandler::future_listSnapshots(const cpp2::ListSnapshotsReq& req) { auto* processor = ListSnapshotsProcessor::instance(kvstore_); RETURN_FUTURE(processor); } } // namespace meta } // namespace nebula
14,374
4,897
#pragma once #include "abstract_rule.hpp" #include "expression/abstract_expression.hpp" #include "types.hpp" namespace opossum { class AbstractExpression; class AbstractLQPNode; class AliasNode; class AggregateNode; class BinaryPredicateExpression; class LQPSubqueryExpression; class PredicateNode; class ProjectionNode; /** * Optimizes: * - (NOT) IN predicates with a subquery as the right operand * - (NOT) EXISTS predicates * - comparison (<,>,<=,>=,=,<>) predicates with subquery as the right operand * Does not currently optimize: * - (NOT) IN expressions where * - the left value is not a column expression. * - NOT IN with a correlated subquery * - Correlated subqueries where the correlated parameter * - is used outside predicates * - is used in predicates at a point where it cannot be pulled up into a join predicate (below limits, etc.) */ class SubqueryToJoinRule : public AbstractRule { public: std::string name() const override; struct PredicateNodeInfo { /** * Join predicate to achieve the semantic of the input expression type (IN, comparison, ...) in the created join. * * This can be nullptr (for (NOT) EXISTS), in this case only the join predicates from correlated predicates in the * subquery will be used in the created join. */ std::shared_ptr<BinaryPredicateExpression> join_predicate; JoinMode join_mode; std::shared_ptr<LQPSubqueryExpression> subquery; }; /** * Result of pulling up correlated predicates from an LQP. */ struct PredicatePullUpResult { std::shared_ptr<AbstractLQPNode> adapted_lqp; std::vector<std::shared_ptr<BinaryPredicateExpression>> join_predicates; size_t pulled_predicate_node_count = 0; /** * Expressions from the subquery required by the extracted join predicates. * * This list contains every expression only once, even if it is used (required) by multiple join predicates. * This is a vector instead of an unordered_set so that tests are reproducible. Since correlation is usually very * low there shouldn't be much of a performance difference. */ std::vector<std::shared_ptr<AbstractExpression>> required_output_expressions = {}; }; /** * Extract information about the input LQP into a general format. * * Returns nullopt if the LQP does not match one of the supported formats. */ static std::optional<PredicateNodeInfo> is_predicate_node_join_candidate(const PredicateNode& predicate_node); /** * Searches for usages of correlated parameters. * * The first boolean is false when a correlated parameter is used outside of PredicateNodes (for example in joins). * In this case we can never optimize this LQP. If it is true, the size_t contains the number of PredicateNodes in * the LQP that use correlated parameters. */ static std::pair<bool, size_t> assess_correlated_parameter_usage( const std::shared_ptr<AbstractLQPNode>& lqp, const std::map<ParameterID, std::shared_ptr<AbstractExpression>>& parameter_mapping); /** * Tries to safely extract new join predicates from a PredicateNode. * * Returns a binary predicate expressions where the left operand is always the expression associated with the * correlated parameter (and thus a column from the left subtree) and the right operand a column from the subqueries * LQP. Also returns a new expression containing all non-correlated parts of the original nodes expression. If * every part of the original nodes expression was turned into join predicates, nullptr is returned instead. */ static std::pair<std::vector<std::shared_ptr<BinaryPredicateExpression>>, std::shared_ptr<AbstractExpression>> try_to_extract_join_predicates(const std::shared_ptr<PredicateNode>& predicate_node, const std::map<ParameterID, std::shared_ptr<AbstractExpression>>& parameter_mapping, bool is_below_aggregate); /** * Copy an aggregate node and adapt it to group by all required columns. */ static std::shared_ptr<AggregateNode> adapt_aggregate_node( const std::shared_ptr<AggregateNode>& node, const std::vector<std::shared_ptr<AbstractExpression>>& required_output_expressions); /** * Copy an alias node and adapt it to keep all required columns. */ static std::shared_ptr<AliasNode> adapt_alias_node( const std::shared_ptr<AliasNode>& node, const std::vector<std::shared_ptr<AbstractExpression>>& required_output_expressions); /** * Copy a projection node and adapt it to keep all required columns. */ static std::shared_ptr<ProjectionNode> adapt_projection_node( const std::shared_ptr<ProjectionNode>& node, const std::vector<std::shared_ptr<AbstractExpression>>& required_output_expressions); /** * Walk the subquery LQP, removing all correlated PredicateNodes and adapting other nodes as necessary. */ static PredicatePullUpResult pull_up_correlated_predicates( const std::shared_ptr<AbstractLQPNode>& node, const std::map<ParameterID, std::shared_ptr<AbstractExpression>>& parameter_mapping); protected: void _apply_to_plan_without_subqueries(const std::shared_ptr<AbstractLQPNode>& lqp_root) const override; }; } // namespace opossum
5,344
1,506
// RUN: %clang_cc1 -fsycl -fsycl-is-device -ast-dump %s | FileCheck %s #include "Inputs/sycl.hpp" struct Base { int A, B; cl::sycl::accessor<char, 1, cl::sycl::access::mode::read> AccField; }; struct Captured : Base, cl::sycl::accessor<char, 1, cl::sycl::access::mode::read> { int C; }; int main() { Captured Obj; cl::sycl::kernel_single_task<class kernel>( [=]() { Obj.use(); }); } // Check kernel parameters // CHECK: FunctionDecl {{.*}}kernel{{.*}} 'void (int, int, __global char *, cl::sycl::range<1>, cl::sycl::range<1>, cl::sycl::id<1>, __global char *, cl::sycl::range<1>, cl::sycl::range<1>, cl::sycl::id<1>, int)' // CHECK: ParmVarDecl{{.*}} used _arg_A 'int' // CHECK: ParmVarDecl{{.*}} used _arg_B 'int' // CHECK: ParmVarDecl{{.*}} used _arg_AccField '__global char *' // CHECK: ParmVarDecl{{.*}} used _arg_AccField 'cl::sycl::range<1>' // CHECK: ParmVarDecl{{.*}} used _arg_AccField 'cl::sycl::range<1>' // CHECK: ParmVarDecl{{.*}} used _arg_AccField 'cl::sycl::id<1>' // CHECK: ParmVarDecl{{.*}} used _arg__base '__global char *' // CHECK: ParmVarDecl{{.*}} used _arg__base 'cl::sycl::range<1>' // CHECK: ParmVarDecl{{.*}} used _arg__base 'cl::sycl::range<1>' // CHECK: ParmVarDecl{{.*}} used _arg__base 'cl::sycl::id<1>' // CHECK: ParmVarDecl{{.*}} used _arg_C 'int' // Check lambda initialization // CHECK: VarDecl {{.*}} used '(lambda at {{.*}}accessor_inheritance.cpp // CHECK-NEXT: InitListExpr {{.*}} // CHECK-NEXT: InitListExpr {{.*}} 'Captured' // CHECK-NEXT: InitListExpr {{.*}} 'Base' // CHECK-NEXT: ImplicitCastExpr {{.*}} 'int' <LValueToRValue> // CHECK-NEXT: DeclRefExpr {{.*}} 'int' lvalue ParmVar {{.*}} '_arg_A' 'int' // CHECK-NEXT: ImplicitCastExpr {{.*}} 'int' <LValueToRValue> // CHECK-NEXT: DeclRefExpr {{.*}} 'int' lvalue ParmVar {{.*}} '_arg_B' 'int' // CHECK-NEXT: CXXConstructExpr {{.*}} 'cl::sycl::accessor<char, 1, cl::sycl::access::mode::read>':'cl::sycl::accessor<char, 1, cl::sycl::access::mode::read, cl::sycl::access::target::global_buffer, cl::sycl::access::placeholder::false_t, cl::sycl::ONEAPI::accessor_property_list<>>' 'void () noexcept' // CHECK-NEXT: CXXConstructExpr {{.*}} 'cl::sycl::accessor<char, 1, cl::sycl::access::mode::read>':'cl::sycl::accessor<char, 1, cl::sycl::access::mode::read, cl::sycl::access::target::global_buffer, cl::sycl::access::placeholder::false_t, cl::sycl::ONEAPI::accessor_property_list<>>' 'void () noexcept' // CHECK-NEXT: ImplicitCastExpr {{.*}} 'int' <LValueToRValue> // CHECK-NEXT: DeclRefExpr {{.*}} 'int' lvalue ParmVar {{.*}} '_arg_C' 'int' // Check __init calls // CHECK: CXXMemberCallExpr {{.*}} 'void' // CHECK-NEXT: MemberExpr {{.*}} .__init // CHECK-NEXT: MemberExpr {{.*}} .AccField // CHECK-NEXT: ImplicitCastExpr {{.*}} 'Base' lvalue <DerivedToBase (Base)> // CHECK-NEXT: MemberExpr {{.*}} 'Captured' lvalue . // CHECK-NEXT: DeclRefExpr {{.*}}'(lambda at {{.*}}accessor_inheritance.cpp // CHECK-NEXT: ImplicitCastExpr {{.*}} '__global char *' <LValueToRValue> // CHECK-NEXT: DeclRefExpr {{.*}} '__global char *' lvalue ParmVar {{.*}} '_arg_AccField' '__global char *' // CHECK: CXXMemberCallExpr {{.*}} 'void' // CHECK-NEXT: MemberExpr{{.*}} lvalue .__init // CHECK-NEXT: MemberExpr{{.*}}'Captured' lvalue . // CHECK-NEXT: DeclRefExpr {{.*}} '(lambda at {{.*}}accessor_inheritance.cpp // CHECK-NEXT: ImplicitCastExpr {{.*}} '__global char *' <LValueToRValue> // CHECK-NEXT: DeclRefExpr {{.*}} '__global char *' lvalue ParmVar {{.*}} '_arg__base' '__global char *'
3,517
1,394
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * * \file kindchecker.cc * * \brief Check that types are well formed by applying "kinding rules". * * This pass ensures we do not do things that violate the design of the * type system when writing down types. * * For example tensors are not allowed to contain functions in Relay. * * We check this by ensuring the `dtype` field of a Tensor always * contains a data type such as `int`, `float`, `uint`. */ #include <tvm/ir/type_functor.h> #include <tvm/relay/analysis.h> #include <tvm/ir/error.h> namespace tvm { namespace relay { using namespace tvm::runtime; struct KindChecker : TypeFunctor<Kind(const Type&)> { const IRModule& mod; ErrorReporter err_reporter; explicit KindChecker(const IRModule& mod) : mod(mod), err_reporter() {} void ReportFatalError(const Error& err) { this->err_reporter.Report(err); this->err_reporter.RenderErrors(mod); } void CheckKindMatches(const Type& t, const Type& outer, Kind expected, const std::string& description) { Kind k = this->VisitType(t); if (k != expected) { ReportFatalError(ErrorBuilder() << "Incorrect kind for a " << description << ". Type " << t << " inside " << outer << " is of kind " << k << " but was expected to be " << expected); } } Kind VisitType_(const IncompleteTypeNode* op) override { return op->kind; } Kind VisitType_(const TypeVarNode* op) override { return op->kind; } Kind VisitType_(const GlobalTypeVarNode* op) override { return op->kind; } Kind VisitType_(const TensorTypeNode* op) override { return Kind::kType; } Kind VisitType_(const TupleTypeNode* op) override { // tuples should only contain normal types for (const Type& t : op->fields) { CheckKindMatches(t, GetRef<TupleType>(op), Kind::kType, "tuple member"); } return Kind::kType; } Kind VisitType_(const FuncTypeNode* op) override { // Func types should only take normal types for arguments // and only return a normal type. They should also have // well-formed constraints FuncType ft = GetRef<FuncType>(op); for (const Type& t : op->arg_types) { CheckKindMatches(t, ft, Kind::kType, "function type parameter"); } CheckKindMatches(ft->ret_type, ft, Kind::kType, "function return type"); for (const TypeConstraint& tc : op->type_constraints) { CheckKindMatches(tc, ft, Kind::kConstraint, "function type constraint"); } return Kind::kType; } Kind VisitType_(const RelayRefTypeNode* op) override { // ref types should only contain normal types RelayRefType rt = GetRef<RelayRefType>(op); CheckKindMatches(op->value, rt, Kind::kType, "ref contents"); return Kind::kType; } Kind VisitType_(const TypeRelationNode* op) override { // arguments to type relation should be normal types for (const Type& t : op->args) { CheckKindMatches(t, GetRef<TypeRelation>(op), Kind::kType, "argument to type relation"); } return Kind::kConstraint; } Kind VisitType_(const TypeCallNode* op) override { // type call func should be a global type var, args should be type TypeCall tc = GetRef<TypeCall>(op); const auto* gtv = op->func.as<GlobalTypeVarNode>(); if (gtv == nullptr) { ReportFatalError( ErrorBuilder() <<"The callee in " << tc << " is not a global type var, but is " << op->func); } CheckKindMatches(op->func, tc, Kind::kAdtHandle, "type call function"); for (const Type& t : op->args) { CheckKindMatches(t, tc, Kind::kType, "type call argument"); } // finally we need to check the module to check the number of type params auto var = GetRef<GlobalTypeVar>(gtv); auto data = mod->LookupTypeDef(var); if (data->type_vars.size() != op->args.size()) { ReportFatalError(ErrorBuilder() << "Expected " << data->type_vars.size() << "arguments for " << tc << "; got " << op->args.size()); } return Kind::kType; } Kind VisitType_(const TypeDataNode* op) override { // Constructors can reference the header var, but no other GlobalTypeVars. // In theory, a TypeData could be nested, so the header scope // should be tracked recursively, but it is unclear that we need // to support it. TypeData td = GetRef<TypeData>(op); CheckKindMatches(op->header, td, Kind::kAdtHandle, "type data header"); for (const auto& var : op->type_vars) { CheckKindMatches(var, td, Kind::kType, "ADT type var"); } for (const auto& con : op->constructors) { if (!con->belong_to.same_as(op->header)) { ReportFatalError(ErrorBuilder() <<con << " has header " << con->belong_to << " but " << op << " has header " << op->header); } for (const Type& t : con->inputs) { CheckKindMatches(t, td, Kind::kType, "ADT constructor input"); } } return Kind::kTypeData; } Kind Check(const Type& t) { return this->VisitType(t); } }; Kind KindCheck(const Type& t, const IRModule& mod) { KindChecker kc(mod); return kc.Check(t); } TVM_REGISTER_GLOBAL("relay.analysis.check_kind") .set_body([](TVMArgs args, TVMRetValue* ret) { if (args.size() == 1) { *ret = KindCheck(args[0], IRModule({}, {})); } else { *ret = KindCheck(args[0], args[1]); } }); } // namespace relay } // namespace tvm
6,285
1,986
#include <stan/math/fwd/scal.hpp> #include <gtest/gtest.h> #include <math/fwd/scal/fun/nan_util.hpp> TEST(AgradFwdPow, Fvar) { using stan::math::fvar; using std::isnan; using std::log; using std::pow; fvar<double> x(0.5, 1.0); double y = 5.0; fvar<double> a = pow(x, y); EXPECT_FLOAT_EQ(pow(0.5, 5.0), a.val_); EXPECT_FLOAT_EQ(5.0 * pow(0.5, 5.0 - 1.0), a.d_); fvar<double> b = pow(y, x); EXPECT_FLOAT_EQ(pow(5.0, 0.5), b.val_); EXPECT_FLOAT_EQ(log(5.0) * pow(5.0, 0.5), b.d_); fvar<double> z(1.2, 2.0); fvar<double> c = pow(x, z); EXPECT_FLOAT_EQ(pow(0.5, 1.2), c.val_); EXPECT_FLOAT_EQ((2.0 * log(0.5) + 1.2 * 1.0 / 0.5) * pow(0.5, 1.2), c.d_); fvar<double> w(-0.4, 1.0); fvar<double> d = pow(w, x); isnan(d.val_); isnan(d.d_); } TEST(AgradFwdPow, FvarFvarDouble) { using stan::math::fvar; using std::log; using std::pow; fvar<fvar<double> > x; x.val_.val_ = 0.5; x.val_.d_ = 1.0; fvar<fvar<double> > y; y.val_.val_ = 0.5; y.d_.val_ = 1.0; fvar<fvar<double> > a = pow(x, y); EXPECT_FLOAT_EQ(pow(0.5, 0.5), a.val_.val_); EXPECT_FLOAT_EQ(0.5 * pow(0.5, -0.5), a.val_.d_); EXPECT_FLOAT_EQ(log(0.5) * pow(0.5, 0.5), a.d_.val_); EXPECT_FLOAT_EQ(pow(0.5, -0.5) * (0.5 * log(0.5) + 1.0), a.d_.d_); } struct pow_fun { template <typename T0, typename T1> inline typename boost::math::tools::promote_args<T0, T1>::type operator()( const T0 arg1, const T1 arg2) const { return pow(arg1, arg2); } }; TEST(AgradFwdPow, nan_0) { pow_fun pow_; test_nan_fwd(pow_, 3.0, 5.0, false); }
1,571
880
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard CosmeticCorrection Process Module Version 1.2.5 // ---------------------------------------------------------------------------- // CosmeticCorrectionParameters.cpp - Released 2021-04-09T19:41:49Z // ---------------------------------------------------------------------------- // This file is part of the standard CosmeticCorrection PixInsight module. // // Copyright (c) 2011-2020 Nikolay Volkov // Copyright (c) 2003-2020 Pleiades Astrophoto S.L. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All 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 names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 "CosmeticCorrectionParameters.h" namespace pcl { // ---------------------------------------------------------------------------- CCTargetFrames* TheTargetFrames = nullptr; CCTargetFrameEnabled* TheTargetFrameEnabled = nullptr; CCTargetFramePath* TheTargetFramePath = nullptr; CCOutputDir* TheOutputDir = nullptr; CCOutputExtension* TheOutputExtension = nullptr; CCPrefix* ThePrefix = nullptr; CCPostfix* ThePostfix = nullptr; CCOverwrite* TheOverwrite = nullptr; CCCFA* TheCFA = nullptr; CCAmount* TheAmount = nullptr; CCUseMasterDark* TheUseMasterDark = nullptr; CCMasterDarkPath* TheMasterPath = nullptr; CCHotDarkCheck* TheHotDarkCheck = nullptr; CCColdLevel* TheColdLevel = nullptr; CCColdDarkCheck* TheColdDarkCheck = nullptr; CCHotLevel* TheHotLevel = nullptr; CCUseAutoDetect* TheUseAutoDetect = nullptr; CCHotAutoCheck* TheHotAutoCheck = nullptr; CCHotAutoValue* TheHotAutoValue = nullptr; CCColdAutoCheck* TheColdAutoCheck = nullptr; CCColdAutoValue* TheColdAutoValue = nullptr; CCUseDefectList* TheUseDefectList = nullptr; CCDefects* TheDefects = nullptr; CCDefectEnabled* TheDefectEnabled = nullptr; CCDefectIsRow* TheDefectIsRow = nullptr; CCDefectAddress* TheDefectAddress = nullptr; CCDefectIsRange* TheDefectIsRange = nullptr; CCDefectBegin* TheDefectBegin = nullptr; CCDefectEnd* TheDefectEnd = nullptr; // ---------------------------------------------------------------------------- CCTargetFrames::CCTargetFrames( MetaProcess* P ) : MetaTable( P ) { TheTargetFrames = this; } IsoString CCTargetFrames::Id() const { return "targetFrames"; } // ---------------------------------------------------------------------------- CCTargetFrameEnabled::CCTargetFrameEnabled( MetaTable* T ) : MetaBoolean( T ) { TheTargetFrameEnabled = this; } IsoString CCTargetFrameEnabled::Id() const { return "enabled"; } bool CCTargetFrameEnabled::DefaultValue() const { return true; } // ---------------------------------------------------------------------------- CCTargetFramePath::CCTargetFramePath( MetaTable* T ) : MetaString( T ) { TheTargetFramePath = this; } IsoString CCTargetFramePath::Id() const { return "path"; } // ---------------------------------------------------------------------------- CCOutputDir::CCOutputDir( MetaProcess* P ) : MetaString( P ) { TheOutputDir = this; } IsoString CCOutputDir::Id() const { return "outputDir"; } // ---------------------------------------------------------------------------- CCOutputExtension::CCOutputExtension( MetaProcess* P ) : MetaString( P ) { TheOutputExtension = this; } IsoString CCOutputExtension::Id() const { return "outputExtension"; } String CCOutputExtension::DefaultValue() const { return ".xisf"; } // ---------------------------------------------------------------------------- CCPrefix::CCPrefix( MetaProcess* P ) : MetaString( P ) { ThePrefix = this; } IsoString CCPrefix::Id() const { return "prefix"; } String CCPrefix::DefaultValue() const { return ""; } // ---------------------------------------------------------------------------- CCPostfix::CCPostfix( MetaProcess* P ) : MetaString( P ) { ThePostfix = this; } IsoString CCPostfix::Id() const { return "postfix"; } String CCPostfix::DefaultValue() const { return "_cc"; } // ---------------------------------------------------------------------------- CCOverwrite::CCOverwrite( MetaProcess* P ) : MetaBoolean( P ) { TheOverwrite = this; } IsoString CCOverwrite::Id() const { return "overwrite"; } bool CCOverwrite::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCCFA::CCCFA( MetaProcess* P ) : MetaBoolean( P ) { TheCFA = this; } IsoString CCCFA::Id() const { return "cfa"; } bool CCCFA::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCAmount::CCAmount( MetaProcess* P ) : MetaFloat( P ) { TheAmount = this; } IsoString CCAmount::Id() const { return "amount"; } IsoString CCAmount::Aliases() const { return "transferFn"; } int CCAmount::Precision() const { return 2; } double CCAmount::DefaultValue() const { return 1; } double CCAmount::MinimumValue() const { return 0; } double CCAmount::MaximumValue() const { return 1; } // -----------------------------------------------------------Via Master Dark----------------- CCUseMasterDark::CCUseMasterDark( MetaProcess* P ) : MetaBoolean( P ) { TheUseMasterDark = this; } IsoString CCUseMasterDark::Id() const { return "useMasterDark"; } bool CCUseMasterDark::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCMasterDarkPath::CCMasterDarkPath( MetaProcess* P ) : MetaString( P ) { TheMasterPath = this; } IsoString CCMasterDarkPath::Id() const { return "masterDarkPath"; } // ---------------------------------------------------------------------------- CCHotDarkCheck::CCHotDarkCheck( MetaProcess* P ) : MetaBoolean( P ) { TheHotDarkCheck = this; } IsoString CCHotDarkCheck::Id() const { return "hotDarkCheck"; } bool CCHotDarkCheck::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCHotLevel::CCHotLevel( MetaProcess* P ) : MetaFloat( P ) { TheHotLevel = this; } IsoString CCHotLevel::Id() const { return "hotDarkLevel"; } int CCHotLevel::Precision() const { return 10; } double CCHotLevel::DefaultValue() const { return 1; } double CCHotLevel::MinimumValue() const { return 0; } double CCHotLevel::MaximumValue() const { return 1; } // ---------------------------------------------------------------------------- CCColdDarkCheck::CCColdDarkCheck( MetaProcess* P ) : MetaBoolean( P ) { TheColdDarkCheck = this; } IsoString CCColdDarkCheck::Id() const { return "coldDarkCheck"; } bool CCColdDarkCheck::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCColdLevel::CCColdLevel( MetaProcess* P ) : MetaFloat( P ) { TheColdLevel = this; } IsoString CCColdLevel::Id() const { return "coldDarkLevel"; } int CCColdLevel::Precision() const { return 10; } double CCColdLevel::DefaultValue() const { return 0; } double CCColdLevel::MinimumValue() const { return 0; } double CCColdLevel::MaximumValue() const { return 1; } // -----------------------------------------------------------Via Auto Detect----------------- CCUseAutoDetect::CCUseAutoDetect( MetaProcess* P ) : MetaBoolean( P ) { TheUseAutoDetect = this; } IsoString CCUseAutoDetect::Id() const { return "useAutoDetect"; } bool CCUseAutoDetect::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCHotAutoCheck::CCHotAutoCheck( MetaProcess* P ) : MetaBoolean( P ) { TheHotAutoCheck = this; } IsoString CCHotAutoCheck::Id() const { return "hotAutoCheck"; } bool CCHotAutoCheck::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCHotAutoValue::CCHotAutoValue( MetaProcess* P ) : MetaFloat( P ) { TheHotAutoValue = this; } IsoString CCHotAutoValue::Id() const { return "hotAutoValue"; } int CCHotAutoValue::Precision() const { return 1; } double CCHotAutoValue::DefaultValue() const { return 3; } double CCHotAutoValue::MinimumValue() const { return 0; } double CCHotAutoValue::MaximumValue() const { return 50; } // ---------------------------------------------------------------------------- CCColdAutoCheck::CCColdAutoCheck( MetaProcess* P ) : MetaBoolean( P ) { TheColdAutoCheck = this; } IsoString CCColdAutoCheck::Id() const { return "coldAutoCheck"; } bool CCColdAutoCheck::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- CCColdAutoValue::CCColdAutoValue( MetaProcess* P ) : MetaFloat( P ) { TheColdAutoValue = this; } IsoString CCColdAutoValue::Id() const { return "coldAutoValue"; } int CCColdAutoValue::Precision() const { return 1; } double CCColdAutoValue::DefaultValue() const { return 3; } double CCColdAutoValue::MinimumValue() const { return 0; } double CCColdAutoValue::MaximumValue() const { return 50; } // ---------------------------------------------------------------------------- CCUseDefectList::CCUseDefectList( MetaProcess* P ) : MetaBoolean( P ) { TheUseDefectList = this; } IsoString CCUseDefectList::Id() const { return "useDefectList"; } // ---------------------------------------------------------------------------- CCDefects::CCDefects( MetaProcess* P ) : MetaTable( P ) { TheDefects = this; } IsoString CCDefects::Id() const { return "defects"; } // ---------------------------------------------------------------------------- CCDefectEnabled::CCDefectEnabled( MetaTable* T ) : MetaBoolean( T ) { TheDefectEnabled = this; } IsoString CCDefectEnabled::Id() const { return "defectEnabled"; } // ---------------------------------------------------------------------------- CCDefectIsRow::CCDefectIsRow( MetaTable* T ) : MetaBoolean( T ) { TheDefectIsRow = this; } IsoString CCDefectIsRow::Id() const { return "defectIsRow"; } // ---------------------------------------------------------------------------- CCDefectAddress::CCDefectAddress( MetaTable* T ) : MetaUInt16( T ) { TheDefectAddress = this; } IsoString CCDefectAddress::Id() const { return "defectAddress"; } // ---------------------------------------------------------------------------- CCDefectIsRange::CCDefectIsRange( MetaTable* T ) : MetaBoolean( T ) { TheDefectIsRange = this; } IsoString CCDefectIsRange::Id() const { return "defectIsRange"; } // ---------------------------------------------------------------------------- CCDefectBegin::CCDefectBegin( MetaTable* T ) : MetaUInt16( T ) { TheDefectBegin = this; } IsoString CCDefectBegin::Id() const { return "defectBegin"; } // ---------------------------------------------------------------------------- CCDefectEnd::CCDefectEnd( MetaTable* T ) : MetaUInt16( T ) { TheDefectEnd = this; } IsoString CCDefectEnd::Id() const { return "defectEnd"; } // ---------------------------------------------------------------------------- } // namespace pcl // ---------------------------------------------------------------------------- // EOF CosmeticCorrectionParameters.cpp - Released 2021-04-09T19:41:49Z
13,660
4,368
/** * Copyright 2019 Christophe Pollet * * 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 <iostream> #include "Vm.h" #include "op/Op.h" #include "op/Nop.h" #include "op/Push.h" #include "op/Add.h" #include "op/Dump.h" #include "op/Pop.h" using namespace org::thoriumlang::vm; using namespace org::thoriumlang::vm::op; Vm::Vm(int stackSize, Code &code) : code(code), stack(stackSize) { for (Op *&op : ops) { op = Nop::get(); } ops[OPCODE::PUSH] = Push::get(); ops[OPCODE::ADD] = Add::get(); ops[OPCODE::DUMP] = Dump::get(); ops[OPCODE::POP] = Pop::get(); } int Vm::run() { uint8_t op; while ((op = fetch()) != OPCODE::HALT) { decode(op)->execute(code, &stack); } return std::get<int64_t>(stack.pop()); } inline uint8_t Vm::fetch() { return code.op(); } op::Op *Vm::decode(uint8_t opCode) { return ops[opCode]; }
1,403
520
/**************************** Copyright © 2014 Luke Salisbury This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "ffi_path.h" #include "ffi_functions.h" #include <cmath> #include "core.h" #define FIXEDPI 3.1415926535897932384626433832795 /** * @brief Lux_FFI_Path_Move_Object * @param object_id * @param fixed_speed * @param x * @param y * @param loop * @return */ int32_t Lux_FFI_Path_Move_Object( uint32_t object_id, int32_t fixed_speed, int16_t * x, int16_t * y, uint8_t loop ) { float movex, movey, speed, angle = 0; LuxPath next, prev; uint16_t next_path_point = 0; MapObject * map_object = Lux_FFI_Object_Get( object_id ); if ( map_object ) { if ( !map_object->_path.size() ) { return -2; } // Movement direction speed = MAKE_FIXED_FLOAT(fixed_speed) * MAKE_FIXED_FLOAT(lux::core->GetFrameDelta() ); if ( speed > 0.0 ) { next_path_point = map_object->path_point+1; if ( loop ) // Loop around { if ( map_object->path_point >= map_object->_path.size()-1 ) { next_path_point = 0; } } else { if ( map_object->path_point >= map_object->_path.size()-1 ) return map_object->path_point; } prev.x = map_object->position.x; prev.y = map_object->position.y; next = map_object->_path.at(next_path_point); } else if ( speed < 0.0 ) { next_path_point = map_object->path_point-1; if ( loop ) // Loop around { if ( (map_object->path_point == 0) && map_object->path_point > map_object->_path.size() ) { next_path_point = map_object->_path.size()-1; } } else { if ( (map_object->path_point == 0) && map_object->path_point > map_object->_path.size() ) return map_object->path_point; } prev.x = map_object->position.x; prev.y = map_object->position.y; prev = map_object->_path.at(map_object->path_point); next = map_object->_path.at(next_path_point); } else return -1; angle = atan2( (float)(prev.y - next.y), (float)(prev.x - next.x)); movey = sin(angle) * speed; movex = cos(angle) * speed; map_object->path_current_x -= MAKE_FLOAT_FIXED(movex); map_object->path_current_y -= MAKE_FLOAT_FIXED(movey); map_object->position.x = MAKE_FIXED_INT(map_object->path_current_x); map_object->position.y = MAKE_FIXED_INT(map_object->path_current_y); if ( map_object->position.x == next.x && map_object->position.y == next.y) { map_object->path_current_x = MAKE_INT_FIXED(map_object->position.x); map_object->path_current_y = MAKE_INT_FIXED(map_object->position.y); map_object->path_point = next_path_point; } if (x) *x = map_object->position.x; if (y) *y = map_object->position.y; return map_object->path_point; } return -1; } /** * @brief Lux_FFI_Path_Count * @param object_id * @return */ int32_t Lux_FFI_Path_Count( uint32_t object_id ) { MapObject * map_object = Lux_FFI_Object_Get( object_id ); if ( map_object ) { return (int32_t)map_object->_path.size(); } return -1; } /** * @brief Lux_FFI_Path_Point * @param object_id * @param point * @param x * @param y * @param ms_length * @return */ uint8_t Lux_FFI_Path_Point( uint32_t object_id, uint8_t point, int16_t * x, int16_t * y, uint32_t *ms_length ) { if ( point < 0 ) return 0; LuxPath next; MapObject * map_object = Lux_FFI_Object_Get( object_id ); if ( map_object ) { next = map_object->_path.at(point); if (x) *x = next.x; if (y) *y = next.y; if (ms_length) *ms_length = next.ms_length; return 1; } return 0; }
4,317
1,797
// AMD AMDUtils code // // Copyright(c) 2018 Advanced Micro Devices, Inc.All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "stdafx.h" #include "GltfPbrPass.h" #include "Misc\ThreadPool.h" #include "GltfHelpers.h" #include "Base\ShaderCompilerHelper.h" namespace CAULDRON_DX12 { //-------------------------------------------------------------------------------------- // // OnCreate // //-------------------------------------------------------------------------------------- void GltfPbrPass::OnCreate( Device *pDevice, UploadHeap* pUploadHeap, ResourceViewHeaps *pHeaps, DynamicBufferRing *pDynamicBufferRing, StaticBufferPool *pStaticBufferPool, GLTFTexturesAndBuffers *pGLTFTexturesAndBuffers, SkyDome *pSkyDome, Texture *pShadowMap, DXGI_FORMAT outFormat, uint32_t sampleCount) { m_sampleCount = sampleCount; m_pResourceViewHeaps = pHeaps; m_pStaticBufferPool = pStaticBufferPool; m_pDynamicBufferRing = pDynamicBufferRing; m_pGLTFTexturesAndBuffers = pGLTFTexturesAndBuffers; m_outFormat = outFormat; const json &j3 = m_pGLTFTexturesAndBuffers->m_pGLTFCommon->j3; ///////////////////////////////////////////// // Load BRDF look up table for the PBR shader m_BrdfLut.InitFromFile(pDevice, pUploadHeap, "BrdfLut.dds", false); // LUT images are stored as linear // Create default material // { m_defaultMaterial.m_pbrMaterialParameters.m_doubleSided = false; m_defaultMaterial.m_pbrMaterialParameters.m_blending = false; m_defaultMaterial.m_pbrMaterialParameters.m_params.m_emissiveFactor = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); m_defaultMaterial.m_pbrMaterialParameters.m_params.m_baseColorFactor = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f); m_defaultMaterial.m_pbrMaterialParameters.m_params.m_metallicRoughnessValues = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); m_defaultMaterial.m_pbrMaterialParameters.m_params.m_specularGlossinessFactor = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); std::map<std::string, Texture *> texturesBase; CreateGPUMaterialData(&m_defaultMaterial, texturesBase, pSkyDome, pShadowMap); } // Load PBR 2.0 Materials // const json::array_t &materials = j3["materials"]; m_materialsData.resize(materials.size()); for (uint32_t i = 0; i < materials.size(); i++) { PBRMaterial *tfmat = &m_materialsData[i]; // Get PBR material parameters and texture IDs // std::map<std::string, int> textureIds; ProcessMaterials(materials[i], &tfmat->m_pbrMaterialParameters, textureIds); // translate texture IDs into textureViews // std::map<std::string, Texture *> texturesBase; for (auto const& value : textureIds) texturesBase[value.first] = m_pGLTFTexturesAndBuffers->GetTextureViewByID(value.second); CreateGPUMaterialData(tfmat, texturesBase, pSkyDome, pShadowMap); } // Load Meshes // if (j3.find("meshes") != j3.end()) { const json::array_t &meshes = j3["meshes"]; const json::array_t &accessors = j3["accessors"]; m_meshes.resize(meshes.size()); for (uint32_t i = 0; i < meshes.size(); i++) { PBRMesh *tfmesh = &m_meshes[i]; const json::array_t &primitives = meshes[i]["primitives"]; tfmesh->m_pPrimitives.resize(primitives.size()); for (uint32_t p = 0; p < primitives.size(); p++) { json::object_t primitive = primitives[p]; PBRPrimitives *pPrimitive = &tfmesh->m_pPrimitives[p]; // Sets primitive's material, or set a default material if none was specified in the GLTF // auto mat = primitive.find("material"); pPrimitive->m_pMaterial = (mat != primitive.end()) ? &m_materialsData[mat->second] : &m_defaultMaterial; // Gets the geometry topology (so far we are not doing anything with this) // int32_t mode = GetElementInt(primitive, "mode", 4); // Defines for the shader compiler, they will hold the PS and VS bindings for the geometry, io and textures // DefineList attributeDefines; // Set input layout from glTF attributes and set VS bindings // const json::object_t &attribute = primitive["attributes"]; std::vector<tfAccessor> vertexBuffers(attribute.size()); std::vector<std::string> semanticNames(attribute.size()); std::vector<D3D12_INPUT_ELEMENT_DESC> layout(attribute.size()); uint32_t cnt = 0; for (auto it = attribute.begin(); it != attribute.end(); it++, cnt++) { const json::object_t &accessor = accessors[it->second]; // let the compiler know we have this stream attributeDefines[std::string("HAS_") + it->first] = "1"; // split semantic name from index, DX doesnt like the trailing number uint32_t semanticIndex = 0; SplitGltfAttribute(it->first, &semanticNames[cnt], &semanticIndex); // Create Input Layout // layout[cnt].SemanticName = semanticNames[cnt].c_str(); // we need to set it in the pipeline function (because of multithreading) layout[cnt].SemanticIndex = semanticIndex; layout[cnt].Format = GetFormat(accessor.at("type"), accessor.at("componentType")); layout[cnt].InputSlot = (UINT)cnt; layout[cnt].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; layout[cnt].InstanceDataStepRate = 0; layout[cnt].AlignedByteOffset = D3D12_APPEND_ALIGNED_ELEMENT; // Get VB accessors // m_pGLTFTexturesAndBuffers->m_pGLTFCommon->GetBufferDetails(it->second, &vertexBuffers[cnt]); } // Get Index and vertex buffer buffer accessors and create the geometry // tfAccessor indexBuffer; m_pGLTFTexturesAndBuffers->m_pGLTFCommon->GetBufferDetails(primitive["indices"], &indexBuffer); m_pGLTFTexturesAndBuffers->CreateGeometry(indexBuffer, vertexBuffers, &pPrimitive->m_geometry); // Create the descriptors, the root signature and the pipeline // { bool bUsingSkinning = m_pGLTFTexturesAndBuffers->m_pGLTFCommon->FindMeshSkinId(i) != -1; CreateDescriptors(pDevice->GetDevice(), bUsingSkinning, &attributeDefines, pPrimitive); CreatePipeline(pDevice->GetDevice(), semanticNames, layout, &attributeDefines, pPrimitive); } } } } } //-------------------------------------------------------------------------------------- // // CreateGPUMaterialData // //-------------------------------------------------------------------------------------- void GltfPbrPass::CreateGPUMaterialData(PBRMaterial *tfmat, std::map<std::string, Texture *> &texturesBase, SkyDome *pSkyDome, Texture *pShadowMap) { // count the number of textures to init bindings and descriptor { tfmat->m_textureCount = (int)texturesBase.size(); tfmat->m_textureCount += 1; // This is for the BRDF LUT texture if (pSkyDome) tfmat->m_textureCount += 2; // +2 because the skydome has a specular, diffusse and BDRF maps if (pShadowMap != NULL) // will use a shadowmap texture if present tfmat->m_textureCount += 1; } // Alloc descriptor layout and init the descriptor set if (tfmat->m_textureCount >= 0) { // allocate descriptor table for the textures m_pResourceViewHeaps->AllocCBV_SRV_UAVDescriptor(tfmat->m_textureCount, &tfmat->m_texturesTable); uint32_t cnt = 0; //create SRVs and #defines for the BRDF LUT resources tfmat->m_pbrMaterialParameters.m_defines["ID_brdfTexture"] = std::to_string(cnt); CreateSamplerForBrdfLut(cnt, &tfmat->m_samplers[cnt]); m_BrdfLut.CreateSRV(cnt, &tfmat->m_texturesTable); cnt++; //create SRVs and #defines for the IBL resources if (pSkyDome) { tfmat->m_pbrMaterialParameters.m_defines["ID_diffuseCube"] = std::to_string(cnt); pSkyDome->SetDescriptorDiff(cnt, &tfmat->m_texturesTable, cnt, &tfmat->m_samplers[cnt]); cnt++; tfmat->m_pbrMaterialParameters.m_defines["ID_specularCube"] = std::to_string(cnt); pSkyDome->SetDescriptorSpec(cnt, &tfmat->m_texturesTable, cnt, &tfmat->m_samplers[cnt]); cnt++; tfmat->m_pbrMaterialParameters.m_defines["USE_IBL"] = "1"; } // Create SRV for the shadowmap if (pShadowMap != NULL) { tfmat->m_pbrMaterialParameters.m_defines["ID_shadowMap"] = std::to_string(cnt); pShadowMap->CreateSRV(cnt, &tfmat->m_texturesTable); CreateSamplerForShadowMap(cnt, &tfmat->m_samplers[cnt]); cnt++; } //create SRVs and #defines so the shader compiler knows what the index of each texture is for (auto it = texturesBase.begin(); it != texturesBase.end(); it++) { tfmat->m_pbrMaterialParameters.m_defines[std::string("ID_") + it->first] = std::to_string(cnt); it->second->CreateSRV(cnt, &tfmat->m_texturesTable); CreateSamplerForPBR(cnt, &tfmat->m_samplers[cnt]); cnt++; } } } //-------------------------------------------------------------------------------------- // // OnDestroy // //-------------------------------------------------------------------------------------- void GltfPbrPass::OnDestroy() { for (uint32_t m = 0; m < m_meshes.size(); m++) { PBRMesh *pMesh = &m_meshes[m]; for (uint32_t p = 0; p < pMesh->m_pPrimitives.size(); p++) { PBRPrimitives *pPrimitive = &pMesh->m_pPrimitives[p]; pPrimitive->m_PipelineRender->Release(); pPrimitive->m_RootSignature->Release(); } } m_BrdfLut.OnDestroy(); } //-------------------------------------------------------------------------------------- // // CreateDescriptors for a combination of material and geometry // //-------------------------------------------------------------------------------------- void GltfPbrPass::CreateDescriptors(ID3D12Device* pDevice, bool bUsingSkinning, DefineList *pAttributeDefines, PBRPrimitives *pPrimitive) { CD3DX12_DESCRIPTOR_RANGE DescRange[1]; DescRange[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, pPrimitive->m_pMaterial->m_textureCount, 0); // texture table int params = 0; CD3DX12_ROOT_PARAMETER RTSlot[4]; // b0 <- Constant buffer 'per frame' RTSlot[params++].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); // textures table if (pPrimitive->m_pMaterial->m_textureCount > 0) { RTSlot[params++].InitAsDescriptorTable(1, &DescRange[0], D3D12_SHADER_VISIBILITY_PIXEL); } // b1 <- Constant buffer 'per object', these are mainly the material data RTSlot[params++].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_ALL); // b2 <- Constant buffer holding the skinning matrices if (bUsingSkinning) { RTSlot[params++].InitAsConstantBufferView(2, 0, D3D12_SHADER_VISIBILITY_VERTEX); (*pAttributeDefines)["ID_SKINNING_MATRICES"] = std::to_string(2); } // the root signature contains 3 slots to be used CD3DX12_ROOT_SIGNATURE_DESC descRootSignature = CD3DX12_ROOT_SIGNATURE_DESC(); descRootSignature.pParameters = RTSlot; descRootSignature.NumParameters = params; descRootSignature.pStaticSamplers = pPrimitive->m_pMaterial->m_samplers; descRootSignature.NumStaticSamplers = pPrimitive->m_pMaterial->m_textureCount; // deny uneccessary access to certain pipeline stages descRootSignature.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE | D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; ID3DBlob *pOutBlob, *pErrorBlob = NULL; ThrowIfFailed(D3D12SerializeRootSignature(&descRootSignature, D3D_ROOT_SIGNATURE_VERSION_1, &pOutBlob, &pErrorBlob)); ThrowIfFailed(pDevice->CreateRootSignature(0, pOutBlob->GetBufferPointer(), pOutBlob->GetBufferSize(), IID_PPV_ARGS(&pPrimitive->m_RootSignature))); pPrimitive->m_RootSignature->SetName(L"GltfPbr::D3D12SerializeRootSignature"); pOutBlob->Release(); if (pErrorBlob) pErrorBlob->Release(); } //-------------------------------------------------------------------------------------- // // CreatePipeline // //-------------------------------------------------------------------------------------- void GltfPbrPass::CreatePipeline(ID3D12Device* pDevice, std::vector<std::string> semanticNames, std::vector<D3D12_INPUT_ELEMENT_DESC> layout, DefineList *pAttributeDefines, PBRPrimitives *pPrimitive) { ///////////////////////////////////////////// // Compile and create shaders D3D12_SHADER_BYTECODE shaderVert, shaderPixel; { // Create #defines based on material properties and vertex attributes DefineList defines = pPrimitive->m_pMaterial->m_pbrMaterialParameters.m_defines + (*pAttributeDefines); CompileShaderFromFile("GLTFPbrPass-VS.hlsl", &defines, "mainVS", "vs_5_0", 0, &shaderVert); CompileShaderFromFile("GLTFPbrPass-PS.hlsl", &defines, "mainPS", "ps_5_0", 0, &shaderPixel); } // Set blending // CD3DX12_BLEND_DESC blendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); blendState.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { (pPrimitive->m_pMaterial->m_pbrMaterialParameters.m_defines.Has("DEF_alphaMode_BLEND")), FALSE, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL, }; ///////////////////////////////////////////// // Create a PSO description D3D12_GRAPHICS_PIPELINE_STATE_DESC descPso = {}; descPso.InputLayout = { layout.data(), (UINT)layout.size() }; descPso.pRootSignature = pPrimitive->m_RootSignature; descPso.VS = shaderVert; descPso.PS = shaderPixel; descPso.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); descPso.RasterizerState.CullMode = (pPrimitive->m_pMaterial->m_pbrMaterialParameters.m_doubleSided) ? D3D12_CULL_MODE_NONE : D3D12_CULL_MODE_FRONT; descPso.BlendState = blendState; descPso.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); descPso.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; descPso.SampleMask = UINT_MAX; descPso.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; descPso.NumRenderTargets = 1; descPso.RTVFormats[0] = m_outFormat; descPso.DSVFormat = DXGI_FORMAT_D32_FLOAT; descPso.SampleDesc.Count = m_sampleCount; descPso.NodeMask = 0; ThrowIfFailed( pDevice->CreateGraphicsPipelineState(&descPso, IID_PPV_ARGS(&pPrimitive->m_PipelineRender)) ); } //-------------------------------------------------------------------------------------- // // Draw // //-------------------------------------------------------------------------------------- void GltfPbrPass::Draw(ID3D12GraphicsCommandList* pCommandList) { UserMarker(pCommandList, "gltfPBR"); struct Transparent { float m_depth; PBRPrimitives *m_pPrimitive; D3D12_GPU_VIRTUAL_ADDRESS m_perFrameDesc; D3D12_GPU_VIRTUAL_ADDRESS m_perObjectDesc; D3D12_GPU_VIRTUAL_ADDRESS m_pPerSkeleton; operator float() { return -m_depth; } }; std::vector<Transparent> m_transparent; // Set descriptor heaps pCommandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ID3D12DescriptorHeap *pDescriptorHeaps[] = { m_pResourceViewHeaps->GetCBV_SRV_UAVHeap(), m_pResourceViewHeaps->GetSamplerHeap() }; pCommandList->SetDescriptorHeaps(2, pDescriptorHeaps); // loop through nodes // std::vector<tfNode> *pNodes = &m_pGLTFTexturesAndBuffers->m_pGLTFCommon->m_nodes; XMMATRIX *pNodesMatrices = m_pGLTFTexturesAndBuffers->m_pGLTFCommon->m_transformedData.m_worldSpaceMats.data(); for (uint32_t i = 0; i < pNodes->size(); i++) { tfNode *pNode = &pNodes->at(i); if ((pNode == NULL) || (pNode->meshIndex < 0)) continue; // skinning matrices constant buffer D3D12_GPU_VIRTUAL_ADDRESS pPerSkeleton = m_pGLTFTexturesAndBuffers->GetSkinningMatricesBuffer(pNode->skinIndex); // loop through primitives // PBRMesh *pMesh = &m_meshes[pNode->meshIndex]; for (uint32_t p = 0; p < pMesh->m_pPrimitives.size(); p++) { PBRPrimitives *pPrimitive = &pMesh->m_pPrimitives[p]; if (pPrimitive->m_PipelineRender == NULL) continue; // Set per Object constants // per_object *cbPerObject; D3D12_GPU_VIRTUAL_ADDRESS perObjectDesc; m_pDynamicBufferRing->AllocConstantBuffer(sizeof(per_object), (void **)&cbPerObject, &perObjectDesc); cbPerObject->mWorld = pNodesMatrices[i]; PBRMaterialParameters *pPbrParams = &pPrimitive->m_pMaterial->m_pbrMaterialParameters; cbPerObject->m_pbrParams = pPbrParams->m_params; // Draw primitive // if (pPbrParams->m_blending == false) { // If solid draw it // pPrimitive->DrawPrimitive(pCommandList, m_pGLTFTexturesAndBuffers->m_perFrameConstants, perObjectDesc, pPerSkeleton); } else { // If transparent queue it for sorting // XMMATRIX mat = pNodesMatrices[i] * m_pGLTFTexturesAndBuffers->m_pGLTFCommon->m_perFrameData.mCameraViewProj; XMVECTOR v = m_pGLTFTexturesAndBuffers->m_pGLTFCommon->m_meshes[pNode->meshIndex].m_pPrimitives[p].m_center; Transparent t; t.m_depth = XMVectorGetW(XMVector4Transform(v, mat)); t.m_pPrimitive = pPrimitive; t.m_perFrameDesc = m_pGLTFTexturesAndBuffers->m_perFrameConstants; t.m_perObjectDesc = perObjectDesc; t.m_pPerSkeleton = pPerSkeleton; m_transparent.push_back(t); } } } // sort transparent primitives // std::sort(m_transparent.begin(), m_transparent.end()); // Draw them sorted front to back // int tt = 0; for (auto &t : m_transparent) { t.m_pPrimitive->DrawPrimitive(pCommandList, t.m_perFrameDesc, t.m_perObjectDesc, t.m_pPerSkeleton); } } void PBRPrimitives::DrawPrimitive(ID3D12GraphicsCommandList *pCommandList, D3D12_GPU_VIRTUAL_ADDRESS perFrameDesc, D3D12_GPU_VIRTUAL_ADDRESS perObjectDesc, D3D12_GPU_VIRTUAL_ADDRESS pPerSkeleton) { // Bind indices and vertices using the right offsets into the buffer // pCommandList->IASetIndexBuffer(&m_geometry.m_IBV); pCommandList->IASetVertexBuffers(0, (UINT)m_geometry.m_VBV.size(), m_geometry.m_VBV.data()); // Bind Descriptor sets // pCommandList->SetGraphicsRootSignature(m_RootSignature); int paramIndex = 0; // bind the per scene constant buffer descriptor pCommandList->SetGraphicsRootConstantBufferView(paramIndex++, perFrameDesc); // bind the textures and samplers descriptors if (m_pMaterial->m_textureCount > 0) { pCommandList->SetGraphicsRootDescriptorTable(paramIndex++, m_pMaterial->m_texturesTable.GetGPU()); } // bind the per object constant buffer descriptor pCommandList->SetGraphicsRootConstantBufferView(paramIndex++, perObjectDesc); // bind the skeleton bind matrices constant buffer descriptor if (pPerSkeleton != 0) pCommandList->SetGraphicsRootConstantBufferView(paramIndex++, pPerSkeleton); // Bind Pipeline // pCommandList->SetPipelineState(m_PipelineRender); // Draw // pCommandList->DrawIndexedInstanced(m_geometry.m_NumIndices, 1, 0, 0, 0); } }
23,581
7,469
#ifndef OSMIUM_IO_READER_HPP #define OSMIUM_IO_READER_HPP /* This file is part of Osmium (https://osmcode.org/libosmium). Copyright 2013-2021 Jochen Topf <jochen@topf.org> and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <osmium/io/compression.hpp> #include <osmium/io/detail/input_format.hpp> #include <osmium/io/detail/queue_util.hpp> #include <osmium/io/detail/read_thread.hpp> #include <osmium/io/detail/read_write.hpp> #include <osmium/io/error.hpp> #include <osmium/io/file.hpp> #include <osmium/io/header.hpp> #include <osmium/memory/buffer.hpp> #include <osmium/osm/entity_bits.hpp> #include <osmium/thread/pool.hpp> #include <osmium/thread/util.hpp> #include <osmium/util/config.hpp> #include <cerrno> #include <cstdlib> #include <fcntl.h> #include <future> #include <memory> #include <string> #include <system_error> #include <thread> #include <utility> #ifndef _WIN32 # include <sys/wait.h> #endif #ifndef _MSC_VER # include <unistd.h> #endif namespace osmium { namespace io { namespace detail { inline std::size_t get_input_queue_size() noexcept { return osmium::config::get_max_queue_size("INPUT", 20); } inline std::size_t get_osmdata_queue_size() noexcept { return osmium::config::get_max_queue_size("OSMDATA", 20); } } // namespace detail /** * This is the user-facing interface for reading OSM files. Instantiate * an object of this class with a file name or osmium::io::File object * and then call read() on it in a loop until it returns an invalid * Buffer. */ class Reader { // The Reader::read() function reads from a queue of buffers which // can contain nested buffers. These nested buffers will be in // here, because read() can only return a single unnested buffer. osmium::memory::Buffer m_back_buffers{}; osmium::io::File m_file; osmium::thread::Pool* m_pool = nullptr; std::atomic<std::size_t> m_offset{0}; detail::ParserFactory::create_parser_type m_creator; enum class status { okay = 0, // normal reading error = 1, // some error occurred while reading closed = 2, // close() called eof = 3 // eof of file was reached without error } m_status = status::okay; int m_childpid = 0; detail::future_string_queue_type m_input_queue; int m_fd = -1; std::size_t m_file_size = 0; std::unique_ptr<osmium::io::Decompressor> m_decompressor; osmium::io::detail::ReadThreadManager m_read_thread_manager; detail::future_buffer_queue_type m_osmdata_queue; detail::queue_wrapper<osmium::memory::Buffer> m_osmdata_queue_wrapper; std::future<osmium::io::Header> m_header_future{}; osmium::io::Header m_header{}; osmium::thread::thread_handler m_thread{}; osmium::osm_entity_bits::type m_read_which_entities = osmium::osm_entity_bits::all; osmium::io::read_meta m_read_metadata = osmium::io::read_meta::yes; osmium::io::buffers_type m_buffers_kind = osmium::io::buffers_type::any; void set_option(osmium::thread::Pool& pool) noexcept { m_pool = &pool; } void set_option(osmium::osm_entity_bits::type value) noexcept { m_read_which_entities = value; } void set_option(osmium::io::read_meta value) noexcept { // Ignore this setting if we have a history/change file, // because if this is set to "no", we don't see the difference // between visible and deleted objects. if (!m_file.has_multiple_object_versions()) { m_read_metadata = value; } } void set_option(osmium::io::buffers_type value) noexcept { m_buffers_kind = value; } // This function will run in a separate thread. static void parser_thread(osmium::thread::Pool& pool, int fd, const detail::ParserFactory::create_parser_type& creator, detail::future_string_queue_type& input_queue, detail::future_buffer_queue_type& osmdata_queue, std::promise<osmium::io::Header>&& header_promise, std::atomic<std::size_t>* offset_ptr, osmium::osm_entity_bits::type read_which_entities, osmium::io::read_meta read_metadata, osmium::io::buffers_type buffers_kind, bool want_buffered_pages_removed) { std::promise<osmium::io::Header> promise{std::move(header_promise)}; osmium::io::detail::parser_arguments args = { pool, fd, input_queue, osmdata_queue, promise, offset_ptr, read_which_entities, read_metadata, buffers_kind, want_buffered_pages_removed }; creator(args)->parse(); } #ifndef _WIN32 /** * Fork and execute the given command in the child. * A pipe is created between the child and the parent. * The child writes to the pipe, the parent reads from it. * This function never returns in the child. * * @param command Command to execute in the child. * @param filename Filename to give to command as argument. * @returns File descriptor of pipe in the parent. * @throws std::system_error if a system call fails. */ static int execute(const std::string& command, const std::string& filename, int* childpid) { int pipefd[2]; if (pipe(pipefd) < 0) { throw std::system_error{errno, std::system_category(), "opening pipe failed"}; } const pid_t pid = fork(); if (pid < 0) { throw std::system_error{errno, std::system_category(), "fork failed"}; } if (pid == 0) { // child // close all file descriptors except one end of the pipe for (int i = 0; i < 32; ++i) { if (i != pipefd[1]) { ::close(i); } } if (dup2(pipefd[1], 1) < 0) { // put end of pipe as stdout/stdin std::exit(1); // NOLINT(concurrency-mt-unsafe) } ::open("/dev/null", O_RDONLY); // stdin ::open("/dev/null", O_WRONLY); // stderr // hack: -g switches off globbing in curl which allows [] to be used in file names // this is important for XAPI URLs // in theory this execute() function could be used for other commands, but it is // only used for curl at the moment, so this is okay. if (::execlp(command.c_str(), command.c_str(), "-g", filename.c_str(), nullptr) < 0) { std::exit(1); // NOLINT(concurrency-mt-unsafe) } } // parent *childpid = pid; ::close(pipefd[1]); return pipefd[0]; } #endif /** * Open File for reading. Handles URLs or normal files. URLs * are opened by executing the "curl" program (which must be installed) * and reading from its output. * * @returns File descriptor of open file or pipe. * @throws std::system_error if a system call fails. */ static int open_input_file_or_url(const std::string& filename, int* childpid) { const std::string protocol{filename.substr(0, filename.find_first_of(':'))}; if (protocol == "http" || protocol == "https" || protocol == "ftp" || protocol == "file") { #ifndef _WIN32 return execute("curl", filename, childpid); #else throw io_error{"Reading OSM files from the network currently not supported on Windows."}; #endif } const int fd = osmium::io::detail::open_for_reading(filename); #if __linux__ if (fd >= 0) { // Tell the kernel we are going to read this file sequentially ::posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); } #endif return fd; } static std::unique_ptr<Decompressor> make_decompressor(const osmium::io::File& file, int fd, std::atomic<std::size_t>* offset_ptr) { const auto& factory = osmium::io::CompressionFactory::instance(); std::unique_ptr<Decompressor> decompressor; if (file.buffer()) { decompressor = factory.create_decompressor(file.compression(), file.buffer(), file.buffer_size()); } else if (file.format() == file_format::pbf) { decompressor = std::unique_ptr<Decompressor>{new DummyDecompressor{}}; } else { decompressor = factory.create_decompressor(file.compression(), fd); } decompressor->set_offset_ptr(offset_ptr); return decompressor; } public: /** * Create new Reader object. * * @param file The file (contains name and format info) to open. * @param args All further arguments are optional and can appear * in any order: * * * osmium::osm_entities::bits: Which OSM entities (nodes, ways, * relations, and/or changesets) should be read from the * input file. It can speed the read up significantly if * objects that are not needed anyway are not parsed. * * * osmium::io::read_meta: Read meta data or not. The default is * osmium::io::read_meta::yes which means that meta data * is read normally. If you set this to * osmium::io::read_meta::no, meta data (like version, uid, * etc.) is not read possibly speeding up the read. Not all * file formats use this setting. Do *not* set this to * osmium::io::read_meta::no for history or change files * because you will loose the information whether an object * is visible! * * * osmium::io::buffers_type: Fill entities into buffers until * the buffers are full (osmium::io::buffers_type::any) or * only fill entities of the same type into a buffer * (osmium::io::buffers_type::single). Every time a new * entity type is seen a new buffer will be started. Do not * use in "single" mode if the input file is not sorted by * type, otherwise this will be rather inefficient. * * * osmium::thread::Pool&: Reference to a thread pool that should * be used for reading instead of the default pool. Usually * it is okay to use the statically initialized shared * default pool, but sometimes you want or need your own. * For instance when your program will fork, using the * statically initialized pool will not work. * * @throws osmium::io_error If there was an error. * @throws std::system_error If the file could not be opened. */ template <typename... TArgs> explicit Reader(const osmium::io::File& file, TArgs&&... args) : m_file(file.check()), m_creator(detail::ParserFactory::instance().get_creator_function(m_file)), m_input_queue(detail::get_input_queue_size(), "raw_input"), m_fd(m_file.buffer() ? -1 : open_input_file_or_url(m_file.filename(), &m_childpid)), m_file_size(m_fd > 2 ? osmium::file_size(m_fd) : 0), m_decompressor(make_decompressor(m_file, m_fd, &m_offset)), m_read_thread_manager(*m_decompressor, m_input_queue), m_osmdata_queue(detail::get_osmdata_queue_size(), "parser_results"), m_osmdata_queue_wrapper(m_osmdata_queue) { (void)std::initializer_list<int>{ (set_option(args), 0)... }; if (!m_pool) { m_pool = &thread::Pool::default_instance(); } std::promise<osmium::io::Header> header_promise; m_header_future = header_promise.get_future(); const auto cpc = osmium::config::clean_page_cache_after_read(); if (cpc >= 0) { m_decompressor->set_want_buffered_pages_removed(true); } const int fd_for_parser = m_decompressor->is_real() ? -1 : m_fd; m_thread = osmium::thread::thread_handler{parser_thread, std::ref(*m_pool), fd_for_parser, std::ref(m_creator), std::ref(m_input_queue), std::ref(m_osmdata_queue), std::move(header_promise), &m_offset, m_read_which_entities, m_read_metadata, m_buffers_kind, m_decompressor->want_buffered_pages_removed()}; } template <typename... TArgs> explicit Reader(const std::string& filename, TArgs&&... args) : Reader(osmium::io::File(filename), std::forward<TArgs>(args)...) { } template <typename... TArgs> explicit Reader(const char* filename, TArgs&&... args) : Reader(osmium::io::File(filename), std::forward<TArgs>(args)...) { } Reader(const Reader&) = delete; Reader& operator=(const Reader&) = delete; Reader(Reader&&) = delete; Reader& operator=(Reader&&) = delete; ~Reader() noexcept { try { close(); } catch (...) { // Ignore any exceptions because destructor must not throw. } } /** * Close down the Reader. A call to this is optional, because the * destructor of Reader will also call this. But if you don't call * this function first, you might miss an exception, because the * destructor is not allowed to throw. * * @throws Some form of osmium::io_error when there is a problem. */ void close() { m_status = status::closed; m_read_thread_manager.stop(); m_osmdata_queue_wrapper.drain(); try { m_read_thread_manager.close(); } catch (...) { // Ignore any exceptions. } #ifndef _WIN32 if (m_childpid) { int status = 0; const pid_t pid = ::waitpid(m_childpid, &status, 0); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { // NOLINT(hicpp-signed-bitwise) throw std::system_error{errno, std::system_category(), "subprocess returned error"}; } #pragma GCC diagnostic pop m_childpid = 0; } #endif } /** * Get the header data from the file. * * @returns Header. * @throws Some form of osmium::io_error if there is an error. */ osmium::io::Header header() { if (m_status == status::error) { throw io_error{"Can not get header from reader when in status 'error'"}; } try { if (m_header_future.valid()) { m_header = m_header_future.get(); } } catch (...) { close(); m_status = status::error; throw; } return m_header; } /** * Reads the next buffer from the input. An invalid buffer signals * end-of-file. After end-of-file all read() calls will throw an * osmium::io_error. * * @returns Buffer. * @throws Some form of osmium::io_error if there is an error. */ osmium::memory::Buffer read() { osmium::memory::Buffer buffer; // If there are buffers on the stack, return those first. if (m_back_buffers) { if (m_back_buffers.has_nested_buffers()) { buffer = std::move(*m_back_buffers.get_last_nested()); } else { buffer = std::move(m_back_buffers); m_back_buffers = osmium::memory::Buffer{}; } return buffer; } if (m_status != status::okay) { throw io_error{"Can not read from reader when in status 'closed', 'eof', or 'error'"}; } if (m_read_which_entities == osmium::osm_entity_bits::nothing) { m_status = status::eof; return buffer; } try { // m_input_format.read() can return an invalid buffer to signal EOF, // or a valid buffer with or without data. A valid buffer // without data is not an error, it just means we have to // keep getting the next buffer until there is one with data. while (true) { buffer = m_osmdata_queue_wrapper.pop(); if (detail::at_end_of_data(buffer)) { m_status = status::eof; m_read_thread_manager.close(); return buffer; } if (buffer.has_nested_buffers()) { m_back_buffers = std::move(buffer); buffer = std::move(*m_back_buffers.get_last_nested()); } if (buffer.committed() > 0) { return buffer; } } } catch (...) { close(); m_status = status::error; throw; } } /** * Has the end of file been reached? This is set after the last * data has been read. It is also set by calling close(). */ bool eof() const { return m_status == status::eof || m_status == status::closed; } /** * Get the size of the input file. Returns 0 if the file size * is not available (for instance when reading from stdin). */ std::size_t file_size() const noexcept { return m_file_size; } /** * Returns the current offset into the input file. Returns 0 if * the offset is not available (for instance when reading from * stdin). * * The offset can be used together with the result of file_size() * to estimate how much of the file has been read. Note that due * to buffering inside Osmium, this value will be larger than * the amount of data actually available to the application. * * Do not call this function too often, certainly not for every * object you are reading. Depending on the file type it might * do an expensive system call. */ std::size_t offset() const noexcept { return m_offset; } }; // class Reader /** * Read contents of the given file into a buffer in one go. Takes * the same arguments as any of the Reader constructors. * * The buffer can take up quite a lot of memory, so don't do this * unless you are working with small OSM files and/or have lots of * RAM. */ template <typename... TArgs> osmium::memory::Buffer read_file(TArgs&&... args) { osmium::memory::Buffer buffer{1024UL * 1024UL, osmium::memory::Buffer::auto_grow::yes}; Reader reader{std::forward<TArgs>(args)...}; while (auto read_buffer = reader.read()) { buffer.add_buffer(read_buffer); buffer.commit(); } return buffer; } } // namespace io } // namespace osmium #endif // OSMIUM_IO_READER_HPP
23,510
6,362
#pragma once #include <map> #include <ostream> #include <boost/test/unit_test.hpp> #include "api/Packet.hh" #include "oxm/field_set.hh" #include "maple/Backend.hh" #include "maple/Flow.hh" namespace runos { class MockSwitch : public maple::Backend { using Flow = maple::Flow; using FlowPtr = maple::FlowPtr; struct Classifier { unsigned prio; oxm::field_set match; friend bool operator== (const Classifier& lhs, const Classifier& rhs) { return lhs.prio == rhs.prio && lhs.match == rhs.match; } friend bool operator< (const Classifier& lhs, const Classifier& rhs) { return lhs.prio > rhs.prio; } friend std::ostream& operator<< (std::ostream& out, const Classifier& c) { return out << "prio=" << c.prio << ", " << c.match; } }; typedef std::map< Classifier, FlowPtr > FlowTable; FlowPtr miss; FlowTable flow_table; public: explicit MockSwitch(FlowPtr miss) : miss(miss) { } virtual void install(unsigned priority, oxm::field_set const& fs, FlowPtr flow) override { Classifier classifier {priority, fs}; BOOST_TEST_MESSAGE("Installing flow " << classifier); BOOST_REQUIRE_MESSAGE(flow_table.emplace(classifier, flow).second, "Overlapping flow " << classifier); } virtual void remove(FlowPtr flow) override { BOOST_TEST_MESSAGE("Removing flow " << flow); for (auto it = flow_table.begin(); it != flow_table.end(); ++it) { if (it->second == flow) flow_table.erase(it); } } virtual void remove(unsigned priority, oxm::field_set const& match) override { Classifier key{ priority, std::move(match) }; BOOST_TEST_MESSAGE("Removing flow " << key); for (auto it = flow_table.begin(); it != flow_table.end(); ++it) { if (it->first == key) flow_table.erase(it); } } virtual void remove(oxm::field_set const& match) override { BOOST_TEST_MESSAGE("Removing flow " << match); for (auto it = flow_table.begin(); it != flow_table.end(); ++it) { if (it->first.match == match) flow_table.erase(it); } } FlowPtr operator()(const Packet& pkt) const { auto it = flow_table.cbegin(); auto match = flow_table.cend(); for (; it != flow_table.cend(); ++it) { if (it->first.match & pkt) { match = it; break; } } if (it != flow_table.cend()) ++it; for (; it != flow_table.cend() && it->first.prio == match->first.prio; ++it) { BOOST_REQUIRE( not (it->first.match & pkt) ); } if (match != flow_table.cend()) return match->second; else return miss; } }; }
3,040
950
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ #include <fstream> #include <iostream> #include <list> #include <map> #include <memory> #include <sstream> #include <typeinfo> #include <vector> extern "C" { #include "libavcodec/avcodec.h" #include "libavcodec/cabac.h" #include "libavcodec/coding_hooks.h" #include "libavformat/avformat.h" #include "libavformat/avio.h" #include "libavutil/error.h" #include "libavutil/file.h" } #include "arithmetic_code.h" #include "cabac_code.h" #include "recode.pb.h" #include "framebuffer.h" // CABAC blocks smaller than this will be skipped. const int SURROGATE_MARKER_BYTES = 8; //#define DO_NEIGHBOR_LOGGING #ifdef DO_NEIGHBOR_LOGGING #define LOG_NEIGHBORS printf #else #define LOG_NEIGHBORS(...) #endif template <typename T> std::unique_ptr<T, std::function<void(T*&)>> av_unique_ptr(T* p, const std::function<void(T*&)>& deleter) { if (p == nullptr) { throw std::bad_alloc(); } return std::unique_ptr<T, std::function<void(T*&)>>(p, deleter); } template <typename T> std::unique_ptr<T, std::function<void(T*&)>> av_unique_ptr(T* p, void (*deleter)(T**)) { return av_unique_ptr<T>(p, [deleter](T*& to_delete){ deleter(&to_delete); }); } template <typename T> std::unique_ptr<T, std::function<void(T*&)>> av_unique_ptr(T* p, void (*deleter)(void*) = av_free) { return av_unique_ptr<T>(p, [deleter](T*& to_delete){ deleter(to_delete); }); } template <typename T = std::function<void()>> struct defer { T to_defer; explicit defer(const T& to_defer) : to_defer(to_defer) {} defer(const defer&) = delete; ~defer() { to_defer(); } }; int av_check(int return_value, int expected_error = 0, const std::string& message = "") { if (return_value >= 0 || return_value == expected_error) { return return_value; } else { char err[AV_ERROR_MAX_STRING_SIZE]; av_make_error_string(err, AV_ERROR_MAX_STRING_SIZE, return_value); throw std::runtime_error(message + ": " + err); } } bool av_check(int return_value, const std::string& message = "") { return av_check(return_value, 0, message); } // Sets up a libavcodec decoder with I/O and decoding hooks. template <typename Driver> class av_decoder { public: av_decoder(Driver *driver, const std::string& input_filename) : driver(driver) { const size_t avio_ctx_buffer_size = 1024*1024; uint8_t *avio_ctx_buffer = static_cast<uint8_t*>( av_malloc(avio_ctx_buffer_size) ); format_ctx = avformat_alloc_context(); if (avio_ctx_buffer == nullptr || format_ctx == nullptr) throw std::bad_alloc(); format_ctx->pb = avio_alloc_context( avio_ctx_buffer, // input buffer avio_ctx_buffer_size, // input buffer size false, // stream is not writable this, // first argument for read_packet() read_packet, // read callback nullptr, // write_packet() nullptr); // seek() if (avformat_open_input(&format_ctx, input_filename.c_str(), nullptr, nullptr) < 0) { throw std::invalid_argument("Failed to initialize decoding context: " + input_filename); } } ~av_decoder() { for (size_t i = 0; i < format_ctx->nb_streams; i++) { avcodec_close(format_ctx->streams[i]->codec); } av_freep(&format_ctx->pb->buffer); // May no longer be the same buffer we initially malloced. av_freep(&format_ctx->pb); avformat_close_input(&format_ctx); } // Read enough frames to display stream diagnostics. Only used by compressor, // because hooks are not yet set. Reads from already in-memory blocks. void dump_stream_info() { av_check( avformat_find_stream_info(format_ctx, nullptr), "Invalid input stream information" ); av_dump_format(format_ctx, 0, format_ctx->filename, 0); } // Decode all video frames in the file in single-threaded mode, calling the driver's hooks. void decode_video() { auto frame = av_unique_ptr(av_frame_alloc(), av_frame_free); AVPacket packet; // TODO(ctl) add better diagnostics to error results. while (!av_check( av_read_frame(format_ctx, &packet), AVERROR_EOF, "Failed to read frame" )) { AVCodecContext *codec = format_ctx->streams[packet.stream_index]->codec; if (codec->codec_type == AVMEDIA_TYPE_VIDEO) { if (!avcodec_is_open(codec)) { codec->thread_count = 1; codec->hooks = &hooks; av_check( avcodec_open2(codec, avcodec_find_decoder(codec->codec_id), nullptr), "Failed to open decoder for stream " + std::to_string(packet.stream_index) ); } int got_frame = 0; av_check( avcodec_decode_video2(codec, frame.get(), &got_frame, &packet), "Failed to decode video frame" ); } av_packet_unref(&packet); } } private: // Hook stubs - wrap driver into opaque pointers. static int read_packet(void *opaque, uint8_t *buffer_out, int size) { av_decoder *self = static_cast<av_decoder*>(opaque); return self->driver->read_packet(buffer_out, size); } struct cabac { static void* init_decoder(void *opaque, CABACContext *ctx, const uint8_t *buf, int size) { av_decoder *self = static_cast<av_decoder*>(opaque); auto *cabac_decoder = new typename Driver::cabac_decoder(self->driver, ctx, buf, size); self->cabac_contexts[ctx].reset(cabac_decoder); return cabac_decoder; } static int get(void *opaque, uint8_t *state) { auto *self = static_cast<typename Driver::cabac_decoder*>(opaque); return self->get(state); } static int get_bypass(void *opaque) { auto *self = static_cast<typename Driver::cabac_decoder*>(opaque); return self->get_bypass(); } static int get_terminate(void *opaque) { auto *self = static_cast<typename Driver::cabac_decoder*>(opaque); return self->get_terminate(); } static const uint8_t* skip_bytes(void *opaque, int n) { throw std::runtime_error("Not implemented: CABAC decoder doesn't use skip_bytes."); } }; struct model_hooks { static void frame_spec(void *opaque, int frame_num, int mb_width, int mb_height) { auto *self = static_cast<av_decoder*>(opaque)->driver->get_model(); self->update_frame_spec(frame_num, mb_width, mb_height); } static void mb_xy(void *opaque, int x, int y) { auto *self = static_cast<av_decoder*>(opaque)->driver->get_model(); self->mb_coord.mb_x = x; self->mb_coord.mb_y = y; } static void begin_sub_mb(void *opaque, int cat, int scan8index, int max_coeff, int is_dc, int chroma422) { auto *self = static_cast<av_decoder*>(opaque)->driver->get_model(); self->sub_mb_cat = cat; self->mb_coord.scan8_index = scan8index; self->sub_mb_size = max_coeff; self->sub_mb_is_dc = is_dc; self->sub_mb_chroma422 = chroma422; } static void end_sub_mb(void *opaque, int cat, int scan8index, int max_coeff, int is_dc, int chroma422) { auto *self = static_cast<av_decoder*>(opaque)->driver->get_model(); assert(self->sub_mb_cat == cat); assert(self->mb_coord.scan8_index == scan8index); assert(self->sub_mb_size == max_coeff); assert(self->sub_mb_is_dc == is_dc); assert(self->sub_mb_chroma422 == chroma422); self->sub_mb_cat = -1; self->mb_coord.scan8_index = -1; self->sub_mb_size = -1; self->sub_mb_is_dc = 0; self->sub_mb_chroma422 = 0; } static void begin_coding_type(void *opaque, CodingType ct, int zigzag_index, int param0, int param1) { auto &cabac_contexts = static_cast<av_decoder*>(opaque)->cabac_contexts; assert(cabac_contexts.size() == 1); typename Driver::cabac_decoder*self = cabac_contexts.begin()->second.get(); self->begin_coding_type(ct, zigzag_index, param0, param1); } static void end_coding_type(void *opaque, CodingType ct) { auto &cabac_contexts = static_cast<av_decoder*>(opaque)->cabac_contexts; assert(cabac_contexts.size() == 1); typename Driver::cabac_decoder*self = cabac_contexts.begin()->second.get(); self->end_coding_type(ct); } }; Driver *driver; AVFormatContext *format_ctx; AVCodecHooks hooks = { this, { cabac::init_decoder, cabac::get, cabac::get_bypass, cabac::get_terminate, cabac::skip_bytes, }, { model_hooks::frame_spec, model_hooks::mb_xy, model_hooks::begin_sub_mb, model_hooks::end_sub_mb, model_hooks::begin_coding_type, model_hooks::end_coding_type, }, }; std::map<CABACContext*, std::unique_ptr<typename Driver::cabac_decoder>> cabac_contexts; }; struct r_scan8 { uint16_t scan8_index; bool neighbor_left; bool neighbor_up; bool is_invalid() const { return scan8_index == 0 && neighbor_left && neighbor_up; } static constexpr r_scan8 inv() { return {0, true, true}; } }; /* Scan8 organization: * 0 1 2 3 4 5 6 7 * 0 DY y y y y y * 1 y Y Y Y Y * 2 y Y Y Y Y * 3 y Y Y Y Y * 4 du y Y Y Y Y * 5 DU u u u u u * 6 u U U U U * 7 u U U U U * 8 u U U U U * 9 dv u U U U U * 10 DV v v v v v * 11 v V V V V * 12 v V V V V * 13 v V V V V * 14 v V V V V * DY/DU/DV are for luma/chroma DC. */ constexpr uint8_t scan_8[16 * 3 + 3] = { 4 + 1 * 8, 5 + 1 * 8, 4 + 2 * 8, 5 + 2 * 8, 6 + 1 * 8, 7 + 1 * 8, 6 + 2 * 8, 7 + 2 * 8, 4 + 3 * 8, 5 + 3 * 8, 4 + 4 * 8, 5 + 4 * 8, 6 + 3 * 8, 7 + 3 * 8, 6 + 4 * 8, 7 + 4 * 8, 4 + 6 * 8, 5 + 6 * 8, 4 + 7 * 8, 5 + 7 * 8, 6 + 6 * 8, 7 + 6 * 8, 6 + 7 * 8, 7 + 7 * 8, 4 + 8 * 8, 5 + 8 * 8, 4 + 9 * 8, 5 + 9 * 8, 6 + 8 * 8, 7 + 8 * 8, 6 + 9 * 8, 7 + 9 * 8, 4 + 11 * 8, 5 + 11 * 8, 4 + 12 * 8, 5 + 12 * 8, 6 + 11 * 8, 7 + 11 * 8, 6 + 12 * 8, 7 + 12 * 8, 4 + 13 * 8, 5 + 13 * 8, 4 + 14 * 8, 5 + 14 * 8, 6 + 13 * 8, 7 + 13 * 8, 6 + 14 * 8, 7 + 14 * 8, 0 + 0 * 8, 0 + 5 * 8, 0 + 10 * 8 }; constexpr r_scan8 reverse_scan_8[15][8] = { //Y {{16 * 3, false, false}, r_scan8::inv(), r_scan8::inv(), {15, true, true}, {10, false, true}, {11, false, true}, {14, false, true}, {15, false, true}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {5, true, false}, {0, false, false}, {1, false, false}, {4, false, false}, {5, false, false}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {7, true, false}, {2, false, false}, {3, false, false}, {6, false, false}, {7, false, false}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {13, true, false}, {8, false, false}, {9, false, false}, {12, false, false}, {13, false, false}}, {{16 * 3 + 1,false, true}, r_scan8::inv(), r_scan8::inv(), {15, true, false}, {10, false, false}, {11, false, false}, {14, false, false}, {15, false, false}}, // U {{16 * 3 + 1,false, false}, r_scan8::inv(), r_scan8::inv(), {16 + 15, true, true}, {16 + 10, false, true}, {16 + 11, false, true}, {16 + 14, false, true}, {16 + 15, false, true}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {16 + 5, true, false}, {16 + 0, false, false}, {16 + 1, false, false}, {16 + 4, false, false}, {16 + 5, false, false}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {16 + 7, true, false}, {16 + 2, false, false}, {16 + 3, false, false}, {16 + 6, false, false}, {16 + 7, false, false}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {16 + 13, true, false}, {16 + 8, false, false}, {16 + 9, false, false}, {16 + 12, false, false}, {16 + 13, false, false}}, {{16 * 3 + 2,false, true}, r_scan8::inv(), r_scan8::inv(), {16 + 15, true, false}, {16 + 10, false, false}, {16 + 11, false, false}, {16 + 14, false, false}, {16 + 15, false, false}}, // V {{16 * 3 + 2,false, false}, r_scan8::inv(), r_scan8::inv(), {32 + 15, true, true}, {32 + 10, false, true}, {32 + 11, false, true}, {32 + 14, false, true}, {32 + 15, false, true}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {32 + 5, true, false}, {32 + 0, false, false}, {32 + 1, false, false}, {32 + 4, false, false}, {32 + 5, false, false}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {32 + 7, true, false}, {32 + 2, false, false}, {32 + 3, false, false}, {32 + 6, false, false}, {32 + 7, false, false}}, {r_scan8::inv(), r_scan8::inv(), r_scan8::inv(), {32 + 13, true, false}, {32 + 8, false, false}, {32 + 9, false, false}, {32 + 12, false, false}, {32 + 13, false, false}}, {{32 + 16 * 3 + 1,false, true}, r_scan8::inv(), r_scan8::inv(), {32 + 15, true, false}, {32 + 10, false, false}, {32 + 11, false, false}, {32 + 14, false, false}, {32 + 15, false, false}}}; // Encoder / decoder for recoded CABAC blocks. typedef uint64_t range_t; typedef arithmetic_code<range_t, uint8_t> recoded_code; typedef std::tuple<const void*, int, int> model_key; /* not sure these tables are the ones we want to use constexpr uint8_t unzigzag16[16] = { 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4, 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4, 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4, 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4, }; constexpr uint8_t zigzag16[16] = { 0, 2, 8, 12, 1, 5, 9, 13, 3, 6, 10, 14, 4, 7, 11, 15 }; constexpr uint8_t zigzag_field64[64] = { 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8, 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8, 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8, 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8, 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8, 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8, 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8, 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8, 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8, 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8, 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8, 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8, 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8, 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8, 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8, 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8, }; */ constexpr uint8_t zigzag4[4] = { 0, 1, 2, 3 }; constexpr uint8_t unzigzag4[4] = { 0, 1, 2, 3 }; constexpr uint8_t unzigzag16[16] = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }; constexpr uint8_t zigzag16[16] = { 0, 1, 5, 6, 2, 4, 7, 12, 3, 8, 11, 13, 9, 10, 14, 15 }; constexpr uint8_t unzigzag64[64] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 }; constexpr uint8_t zigzag64[64] = { 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 }; int test_reverse_scan8() { for (size_t i = 0; i < sizeof(scan_8)/ sizeof(scan_8[0]); ++i) { auto a = reverse_scan_8[scan_8[i] >> 3][scan_8[i] & 7]; assert(a.neighbor_left == false && a.neighbor_up == false); assert(a.scan8_index == i); if (a.scan8_index != i) { return 1; } } for (int i = 0;i < 16; ++i) { assert(zigzag16[unzigzag16[i]] == i); assert(unzigzag16[zigzag16[i]] == i); } return 0; } int make_sure_reverse_scan8 = test_reverse_scan8(); struct CoefficientCoord { int mb_x; int mb_y; int scan8_index; int zigzag_index; }; bool get_neighbor_sub_mb(bool above, int sub_mb_size, CoefficientCoord input, CoefficientCoord *output) { int mb_x = input.mb_x; int mb_y = input.mb_y; int scan8_index = input.scan8_index; output->scan8_index = scan8_index; output->mb_x = mb_x; output->mb_y = mb_y; output->zigzag_index = input.zigzag_index; if (scan8_index >= 16 * 3) { if (above) { if (mb_y > 0) { output->mb_y -= 1; return true; } return false; } else { if (mb_x > 0) { output->mb_x -= 1; return true; } return false; } } int scan8 = scan_8[scan8_index]; int left_shift = (above ? 0 : -1); int above_shift = (above ? -1 : 0); auto neighbor = reverse_scan_8[(scan8 >> 3) + above_shift][(scan8 & 7) + left_shift]; if (neighbor.neighbor_left) { if (mb_x == 0){ return false; } else { --mb_x; } } if (neighbor.neighbor_up) { if (mb_y == 0) { return false; } else { --mb_y; } } output->scan8_index = neighbor.scan8_index; if (sub_mb_size >= 32) { output->scan8_index /= 4; output->scan8_index *= 4; // round down to the nearest multiple of 4 } output->zigzag_index = input.zigzag_index; output->mb_x = mb_x; output->mb_y = mb_y; return true; } int log2(int y) { int x = -1; while (y) { y/=2; x++; } return x; } bool get_neighbor(bool above, int sub_mb_size, CoefficientCoord input, CoefficientCoord *output) { int mb_x = input.mb_x; int mb_y = input.mb_y; int scan8_index = input.scan8_index; unsigned int zigzag_index = input.zigzag_index; int dimension = 2; if (sub_mb_size > 15) { dimension = 4; } if (sub_mb_size > 32) { dimension = 8; } if (scan8_index >= 16 * 3) { // we are DC... int linear_index = unzigzag4[zigzag_index & 0x3]; if (sub_mb_size == 16) { linear_index = unzigzag16[zigzag_index & 0xf]; } else { assert(sub_mb_size <= 4); } if ((above && linear_index >= dimension) // if is inner || ((linear_index & (dimension - 1)) && !above)) { if (above) { linear_index -= dimension; } else { -- linear_index; } if (sub_mb_size == 16) { output->zigzag_index = zigzag16[linear_index]; } else { output->zigzag_index = zigzag4[linear_index]; } output->mb_x = mb_x; output->mb_y = mb_y; output->scan8_index = scan8_index; return true; } if (above) { if (mb_y == 0) { return false; } linear_index += dimension * (dimension - 1);//go to bottom --mb_y; } else { if (mb_x == 0) { return false; } linear_index += dimension - 1;//go to end of row --mb_x; } if (sub_mb_size == 16) { output->zigzag_index = zigzag16[linear_index]; } else { output->zigzag_index = linear_index; } output->mb_x = mb_x; output->mb_y = mb_y; output->scan8_index = scan8_index; return true; } int scan8 = scan_8[scan8_index]; int left_shift = (above ? 0 : -1); int above_shift = (above ? -1 : 0); auto neighbor = reverse_scan_8[(scan8 >> 3) + above_shift][(scan8 & 7) + left_shift]; if (neighbor.neighbor_left) { if (mb_x == 0){ return false; } else { --mb_x; } } if (neighbor.neighbor_up) { if (mb_y == 0) { return false; } else { --mb_y; } } output->scan8_index = neighbor.scan8_index; if (sub_mb_size >= 32) { output->scan8_index /= 4; output->scan8_index *= 4; // round down to the nearest multiple of 4 } output->zigzag_index = zigzag_index; output->mb_x = mb_x; output->mb_y = mb_y; return true; } bool get_neighbor_coefficient(bool above, int sub_mb_size, CoefficientCoord input, CoefficientCoord *output) { if (input.scan8_index >= 16 * 3) { return get_neighbor(above, sub_mb_size, input, output); } int zigzag_addition = 0; if ((sub_mb_size & (sub_mb_size - 1)) != 0) { zigzag_addition = 1;// the DC is not included } const uint8_t *zigzag_to_raster = unzigzag16; const uint8_t *raster_to_zigzag = zigzag16; int dim = 4; if (sub_mb_size <= 4) { dim = 2; zigzag_to_raster = zigzag4; raster_to_zigzag = unzigzag4; } if (sub_mb_size > 16) { dim = 16; zigzag_to_raster = zigzag64; raster_to_zigzag = unzigzag64; } int raster_coord = zigzag_to_raster[input.zigzag_index + zigzag_addition]; //fprintf(stderr, "%d %d %d -> %d\n", sub_mb_size, zigzag_addition, input.zigzag_index, raster_coord); if (above) { if (raster_coord >= dim) { raster_coord -= dim; } else { return false; } } else { if (raster_coord & (dim - 1)) { raster_coord -= 1; } else { return false; } } *output = input; output->zigzag_index = raster_to_zigzag[raster_coord] - zigzag_addition; return true; } #define STRINGIFY_COMMA(s) #s , const char * billing_names [] = {EACH_PIP_CODING_TYPE(STRINGIFY_COMMA)}; #undef STRINGIFY_COMMA class h264_model { public: CodingType coding_type = PIP_UNKNOWN; size_t bill[sizeof(billing_names)/sizeof(billing_names[0])]; size_t cabac_bill[sizeof(billing_names)/sizeof(billing_names[0])]; FrameBuffer frames[2]; int cur_frame = 0; uint8_t STATE_FOR_NUM_NONZERO_BIT[6]; bool do_print; public: h264_model() { reset(); do_print = false; memset(bill, 0, sizeof(bill)); memset(cabac_bill, 0, sizeof(cabac_bill));} void enable_debug() { do_print = true; } void disable_debug() { do_print = false; } ~h264_model() { bool first = true; for (size_t i = 0; i < sizeof(billing_names)/sizeof(billing_names[i]); ++i) { if (bill[i]) { if (first) { fprintf(stderr, "Avrecode Bill\n=============\n"); } first = false; fprintf(stderr, "%s : %ld\n", billing_names[i], bill[i]); } } for (size_t i = 0; i < sizeof(billing_names)/sizeof(billing_names[i]); ++i) { if (cabac_bill[i]) { if (first) { fprintf(stderr, "CABAC Bill\n=============\n"); } first = false; fprintf(stderr, "%s : %ld\n", billing_names[i], cabac_bill[i]); } } } void billable_bytes(size_t num_bytes_emitted) { bill[coding_type] += num_bytes_emitted; } void billable_cabac_bytes(size_t num_bytes_emitted) { cabac_bill[coding_type] += num_bytes_emitted; } void reset() { // reset should do nothing as we wish to remember what we've learned memset(STATE_FOR_NUM_NONZERO_BIT, 0, sizeof(STATE_FOR_NUM_NONZERO_BIT)); } bool fetch(bool previous, bool match_type, CoefficientCoord coord, int16_t*output) const{ if (match_type && (previous || coord.mb_x != mb_coord.mb_x || coord.mb_y != mb_coord.mb_y)) { BlockMeta meta = frames[previous ? !cur_frame : cur_frame].meta_at(coord.mb_x, coord.mb_y); if (!meta.coded) { // when we populate mb_type in the metadata, then we can use it here return false; } } *output = frames[previous ? !cur_frame : cur_frame].at(coord.mb_x, coord.mb_y).residual[coord.scan8_index * 16 + coord.zigzag_index]; return true; } model_key get_model_key(const void *context)const { switch(coding_type) { case PIP_SIGNIFICANCE_NZ: return model_key(context, 0, 0); case PIP_UNKNOWN: case PIP_UNREACHABLE: case PIP_RESIDUALS: return model_key(context, 0, 0); case PIP_SIGNIFICANCE_MAP: { static const uint8_t sig_coeff_flag_offset_8x8[2][63] = { { 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9,10, 9, 8, 7, 7, 6,11,12,13,11, 6, 7, 8, 9,14,10, 9, 8, 6,11, 12,13,11, 6, 9,14,10, 9,11,12,13,11,14,10,12 }, { 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5, 6, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,11,12,11, 9, 9,10,10, 8,13,13, 9, 9,10,10, 8,13,13, 9, 9,10,10,14,14,14,14,14 } }; int cat_lookup[14] = { 105+0, 105+15, 105+29, 105+44, 105+47, 402, 484+0, 484+15, 484+29, 660, 528+0, 528+15, 528+29, 718 }; static const uint8_t sig_coeff_offset_dc[7] = { 0, 0, 1, 1, 2, 2, 2 }; int zigzag_offset = mb_coord.zigzag_index; if (sub_mb_is_dc && sub_mb_chroma422) { assert(mb_coord.zigzag_index < 7); zigzag_offset = sig_coeff_offset_dc[mb_coord.zigzag_index]; } else { if (sub_mb_size > 32) { assert(mb_coord.zigzag_index < 63); zigzag_offset = sig_coeff_flag_offset_8x8[0][mb_coord.zigzag_index]; } } assert(sub_mb_cat < (int)(sizeof(cat_lookup)/sizeof(cat_lookup[0]))); int neighbor_above = 2; int neighbor_left = 2; int coeff_neighbor_above = 2; int coeff_neighbor_left = 2; if (do_print) { LOG_NEIGHBORS("["); } { CoefficientCoord neighbor_left_coord = {0, 0, 0, 0}; if (get_neighbor(false, sub_mb_size, mb_coord, &neighbor_left_coord)) { int16_t tmp = 0; if (fetch(false, true, neighbor_left_coord, &tmp)){ neighbor_left = !!tmp; if (do_print) { LOG_NEIGHBORS("%d,", tmp); } } else { neighbor_left = 3; if (do_print) { LOG_NEIGHBORS("_,"); } } } else { if (do_print) { LOG_NEIGHBORS("x,"); } } } { CoefficientCoord neighbor_above_coord = {0, 0, 0, 0}; if (get_neighbor(true, sub_mb_size, mb_coord, &neighbor_above_coord)) { int16_t tmp = 0; if (fetch(false, true, neighbor_above_coord, &tmp)){ neighbor_above = !!tmp; if (do_print) { LOG_NEIGHBORS("%d,", tmp); } } else { neighbor_above = 3; if (do_print) { LOG_NEIGHBORS("_,"); } } } else { if (do_print) { LOG_NEIGHBORS("x,"); } } } { CoefficientCoord neighbor_left_coord = {0, 0, 0, 0}; if (get_neighbor_coefficient(false, sub_mb_size, mb_coord, &neighbor_left_coord)) { int16_t tmp = 0; if (fetch(false, true, neighbor_left_coord, &tmp)){ coeff_neighbor_left = !!tmp; } else { coeff_neighbor_left = 3; } } else { } } { CoefficientCoord neighbor_above_coord = {0, 0, 0, 0}; if (get_neighbor_coefficient(true, sub_mb_size, mb_coord, &neighbor_above_coord)) { int16_t tmp = 0; if (fetch(false, true, neighbor_above_coord, &tmp)){ coeff_neighbor_above = !!tmp; } else { coeff_neighbor_above = 3; } } else { } } // FIXM: why doesn't this prior help at all { int16_t output = 0; if (fetch(true, true, mb_coord, &output)) { if (do_print) LOG_NEIGHBORS("%d] ", output); } else { if (do_print) LOG_NEIGHBORS("x] "); } } //const BlockMeta &meta = frames[!cur_frame].meta_at(mb_x, mb_y); int num_nonzeros = frames[cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y).num_nonzeros[mb_coord.scan8_index]; (void)neighbor_above; (void)neighbor_left; (void)coeff_neighbor_above; (void)coeff_neighbor_left;//haven't found a good way to utilize these priors to make the results better return model_key(&significance_context, 64 * num_nonzeros + nonzeros_observed, sub_mb_is_dc + zigzag_offset * 2 + 16 * 2 * cat_lookup[sub_mb_cat]); } case PIP_SIGNIFICANCE_EOB: { // FIXME: why doesn't this prior help at all static int fake_context = 0; int num_nonzeros = frames[cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y).num_nonzeros[mb_coord.scan8_index]; return model_key(&fake_context, num_nonzeros == nonzeros_observed, 0); } default: break; } assert(false && "Unreachable"); abort(); } range_t probability_for_model_key(range_t range, model_key key) { auto* e = &estimators[key]; int total = e->pos + e->neg; return (range/total) * e->pos; } range_t probability_for_state(range_t range, const void *context) { return probability_for_model_key(range, get_model_key(context)); } void update_frame_spec(int frame_num, int mb_width, int mb_height) { if (frames[cur_frame].width() != (uint32_t)mb_width || frames[cur_frame].height() != (uint32_t)mb_height || !frames[cur_frame].is_same_frame(frame_num)) { cur_frame = !cur_frame; if (frames[cur_frame].width() != (uint32_t)mb_width || frames[cur_frame].height() != (uint32_t)mb_height) { frames[cur_frame].init(mb_width, mb_height, mb_width * mb_height); if (frames[!cur_frame].width() != (uint32_t)mb_width || frames[!cur_frame].height() != (uint32_t)mb_height) { frames[!cur_frame].init(mb_width, mb_height, mb_width * mb_height); } //fprintf(stderr, "Init(%d=%d) %d x %d\n", frame_num, cur_frame, mb_width, mb_height); } else { frames[cur_frame].bzero(); //fprintf(stderr, "Clear (%d=%d)\n", frame_num, cur_frame); } frames[cur_frame].set_frame_num(frame_num); } } template <class Functor> void finished_queueing(CodingType ct, const Functor &put_or_get) { if (ct == PIP_SIGNIFICANCE_MAP) { bool block_of_interest = (sub_mb_cat == 1 || sub_mb_cat == 2); CodingType last = coding_type; coding_type = PIP_SIGNIFICANCE_NZ; BlockMeta &meta = frames[cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y); int nonzero_bits[6] = {}; for (int i= 0; i < 6; ++i) { nonzero_bits[i] = (meta.num_nonzeros[mb_coord.scan8_index] & (1 << i)) >> i; } #define QUEUE_MODE #ifdef QUEUE_MODE const uint32_t serialized_bits = sub_mb_size > 16 ? 6 : sub_mb_size > 4 ? 4 : 2; { uint32_t i = 0; uint32_t serialized_so_far = 0; CoefficientCoord neighbor; uint32_t left_nonzero = 0; uint32_t above_nonzero = 0; bool has_left = get_neighbor_sub_mb(false, sub_mb_size, mb_coord, &neighbor); if (has_left) { left_nonzero = frames[cur_frame].meta_at(neighbor.mb_x, neighbor.mb_y).num_nonzeros[neighbor.scan8_index]; } bool has_above = get_neighbor_sub_mb(true, sub_mb_size, mb_coord, &neighbor); if (has_above) { above_nonzero = frames[cur_frame].meta_at(neighbor.mb_x, neighbor.mb_y).num_nonzeros[neighbor.scan8_index]; } do { uint32_t cur_bit = (1<<i); int left_nonzero_bit = 2; if (has_left) { left_nonzero_bit = (left_nonzero >= cur_bit); } int above_nonzero_bit = 2; if (above_nonzero) { above_nonzero_bit = (above_nonzero >= cur_bit); } put_or_get(model_key(&(STATE_FOR_NUM_NONZERO_BIT[i]), serialized_so_far + 64 * (frames[!cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y).num_nonzeros[mb_coord.scan8_index] >= cur_bit) + 128 * left_nonzero_bit + 384 * above_nonzero_bit, meta.is_8x8 + sub_mb_is_dc * 2 + sub_mb_chroma422 + sub_mb_cat * 4), &nonzero_bits[i]); if (nonzero_bits[i]) { serialized_so_far |= cur_bit; } } while (++i < serialized_bits); if (block_of_interest) { LOG_NEIGHBORS("<{"); } if (has_left) { if (block_of_interest) { LOG_NEIGHBORS("%d,", left_nonzero); } } else { if (block_of_interest) { LOG_NEIGHBORS("X,"); } } if (has_above) { if (block_of_interest) { LOG_NEIGHBORS("%d,", above_nonzero); } } else { if (block_of_interest) { LOG_NEIGHBORS("X,"); } } if (frames[!cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y).coded) { if (block_of_interest) { LOG_NEIGHBORS("%d",frames[!cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y).num_nonzeros[mb_coord.scan8_index]); } } else { if (block_of_interest) { LOG_NEIGHBORS("X"); } } } #endif meta.num_nonzeros[mb_coord.scan8_index] = 0; for (int i= 0; i < 6; ++i) { meta.num_nonzeros[mb_coord.scan8_index] |= nonzero_bits[i] << i; } if (block_of_interest) { LOG_NEIGHBORS("} %d> ",meta.num_nonzeros[mb_coord.scan8_index]); } coding_type = last; } } void end_coding_type(CodingType ct) { if (ct == PIP_SIGNIFICANCE_MAP) { assert(coding_type == PIP_UNREACHABLE || (coding_type == PIP_SIGNIFICANCE_MAP && mb_coord.zigzag_index == 0)); uint8_t num_nonzeros = 0; for (int i = 0; i < sub_mb_size; ++i) { int16_t res = frames[cur_frame].at(mb_coord.mb_x, mb_coord.mb_y).residual[mb_coord.scan8_index * 16 + i]; assert(res == 1 || res == 0); if (res != 0) { num_nonzeros += 1; } } BlockMeta &meta = frames[cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y); meta.is_8x8 = meta.is_8x8 || (sub_mb_size > 32); // 8x8 will have DC be 2x2 meta.coded = true; assert(meta.num_nonzeros[mb_coord.scan8_index] == 0 || meta.num_nonzeros[mb_coord.scan8_index] == num_nonzeros); meta.num_nonzeros[mb_coord.scan8_index] = num_nonzeros; } coding_type = PIP_UNKNOWN; } bool begin_coding_type(CodingType ct, int zz_index, int param0, int param1) { bool begin_queueing = false; coding_type = ct; switch (ct) { case PIP_SIGNIFICANCE_MAP: { BlockMeta &meta = frames[cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y); meta.num_nonzeros[mb_coord.scan8_index] = 0; } assert(!zz_index); nonzeros_observed = 0; if (sub_mb_is_dc) { mb_coord.zigzag_index = 0; } else { mb_coord.zigzag_index = 0; } begin_queueing = true; break; default: break; } return begin_queueing; } void reset_mb_significance_state_tracking() { mb_coord.zigzag_index = 0; nonzeros_observed = 0; coding_type = PIP_SIGNIFICANCE_MAP; } void update_state_tracking(int symbol) { switch (coding_type) { case PIP_SIGNIFICANCE_NZ: break; case PIP_SIGNIFICANCE_MAP: frames[cur_frame].at(mb_coord.mb_x, mb_coord.mb_y).residual[mb_coord.scan8_index * 16 + mb_coord.zigzag_index] = symbol; nonzeros_observed += symbol; if (mb_coord.zigzag_index + 1 == sub_mb_size) { coding_type = PIP_UNREACHABLE; mb_coord.zigzag_index = 0; } else { if (symbol) { coding_type = PIP_SIGNIFICANCE_EOB; } else { ++mb_coord.zigzag_index; if (mb_coord.zigzag_index + 1 == sub_mb_size) { // if we were a zero and we haven't eob'd then the // next and last must be a one frames[cur_frame].at(mb_coord.mb_x, mb_coord.mb_y).residual[mb_coord.scan8_index * 16 + mb_coord.zigzag_index] = 1; ++nonzeros_observed; coding_type = PIP_UNREACHABLE; mb_coord.zigzag_index = 0; } } } break; case PIP_SIGNIFICANCE_EOB: if (symbol) { mb_coord.zigzag_index = 0; coding_type = PIP_UNREACHABLE; } else if (mb_coord.zigzag_index + 2 == sub_mb_size) { frames[cur_frame].at(mb_coord.mb_x, mb_coord.mb_y).residual[mb_coord.scan8_index * 16 + mb_coord.zigzag_index + 1] = 1; coding_type = PIP_UNREACHABLE; } else { coding_type = PIP_SIGNIFICANCE_MAP; ++mb_coord.zigzag_index; } break; case PIP_RESIDUALS: case PIP_UNKNOWN: break; case PIP_UNREACHABLE: assert(false); default: assert(false); } } void update_state(int symbol, const void *context) { update_state_for_model_key(symbol, get_model_key(context)); } void update_state_for_model_key(int symbol, model_key key) { if (coding_type == PIP_SIGNIFICANCE_EOB) { int num_nonzeros = frames[cur_frame].meta_at(mb_coord.mb_x, mb_coord.mb_y).num_nonzeros[mb_coord.scan8_index]; assert(symbol == (num_nonzeros == nonzeros_observed)); } auto* e = &estimators[key]; if (symbol) { e->pos++; } else { e->neg++; } if ((coding_type != PIP_SIGNIFICANCE_MAP && e->pos + e->neg > 0x60) || (coding_type == PIP_SIGNIFICANCE_MAP && e->pos + e->neg > 0x50)) { e->pos = (e->pos + 1) / 2; e->neg = (e->neg + 1) / 2; } update_state_tracking(symbol); } const uint8_t bypass_context = 0, terminate_context = 0, significance_context = 0; CoefficientCoord mb_coord; int nonzeros_observed = 0; int sub_mb_cat = -1; int sub_mb_size = -1; int sub_mb_is_dc = 0; int sub_mb_chroma422 = 0; private: struct estimator { int pos = 1, neg = 1; }; std::map<model_key, estimator> estimators; }; class h264_symbol { public: h264_symbol(int symbol, const void*state) : symbol(symbol), state(state) { } template <class T> void execute(T &encoder, h264_model *model, Recoded::Block *out, std::vector<uint8_t> &encoder_out) { bool in_significance_map = (model->coding_type == PIP_SIGNIFICANCE_MAP); bool block_of_interest = (model->sub_mb_cat == 1 || model->sub_mb_cat == 2); bool print_priors = in_significance_map && block_of_interest; if (model->coding_type != PIP_SIGNIFICANCE_EOB) { size_t billable_bytes = encoder.put(symbol, [&](range_t range){ return model->probability_for_state(range, state); }); if (billable_bytes) { model->billable_bytes(billable_bytes); } }else if (block_of_interest) { if (symbol) { LOG_NEIGHBORS("\n"); } } if (print_priors) { model->enable_debug(); } model->update_state(symbol, state); if (print_priors) { LOG_NEIGHBORS("%d ", symbol); model->disable_debug(); } if (state == &model->terminate_context && symbol) { encoder.finish(); out->set_cabac(&encoder_out[0], encoder_out.size()); } } private: int symbol; const void* state; }; class compressor { public: compressor(const std::string& input_filename, std::ostream& out_stream) : input_filename(input_filename), out_stream(out_stream) { if (av_file_map(input_filename.c_str(), &original_bytes, &original_size, 0, NULL) < 0) { throw std::invalid_argument("Failed to open file: " + input_filename); } } ~compressor() { av_file_unmap(original_bytes, original_size); } void run() { // Run through all the frames in the file, building the output using our hooks. av_decoder<compressor> d(this, input_filename); d.dump_stream_info(); d.decode_video(); // Flush the final block to the output and write to stdout. out.add_block()->set_literal( &original_bytes[prev_coded_block_end], original_size - prev_coded_block_end); out_stream << out.SerializeAsString(); } int read_packet(uint8_t *buffer_out, int size) { size = std::min(size, int(original_size - read_offset)); memcpy(buffer_out, &original_bytes[read_offset], size); read_offset += size; return size; } class cabac_decoder { public: cabac_decoder(compressor *c, CABACContext *ctx_in, const uint8_t *buf, int size) { out = c->find_next_coded_block_and_emit_literal(buf, size); model = nullptr; if (out == nullptr) { // We're skipping this block, so disable calls to our hooks. ctx_in->coding_hooks = nullptr; ctx_in->coding_hooks_opaque = nullptr; ::ff_reset_cabac_decoder(ctx_in, buf, size); return; } out->set_size(size); ctx = *ctx_in; ctx.coding_hooks = nullptr; ctx.coding_hooks_opaque = nullptr; ::ff_reset_cabac_decoder(&ctx, buf, size); this->c = c; model = &c->model; model->reset(); } ~cabac_decoder() { assert(out == nullptr || out->has_cabac()); } void execute_symbol(int symbol, const void* state) { h264_symbol sym(symbol, state); #define QUEUE_MODE #ifdef QUEUE_MODE if (queueing_symbols == PIP_SIGNIFICANCE_MAP || queueing_symbols == PIP_SIGNIFICANCE_EOB || !symbol_buffer.empty()) { symbol_buffer.push_back(sym); model->update_state_tracking(symbol); } else { #endif sym.execute(encoder, model, out, encoder_out); #ifdef QUEUE_MODE } #endif } int get(uint8_t *state) { int symbol = ::ff_get_cabac(&ctx, state); execute_symbol(symbol, state); return symbol; } int get_bypass() { int symbol = ::ff_get_cabac_bypass(&ctx); execute_symbol(symbol, &model->bypass_context); return symbol; } int get_terminate() { int n = ::ff_get_cabac_terminate(&ctx); int symbol = (n != 0); execute_symbol(symbol, &model->terminate_context); return symbol; } void begin_coding_type( CodingType ct, int zigzag_index, int param0, int param1) { if (!model) { return; } bool begin_queue = model->begin_coding_type(ct, zigzag_index, param0, param1); if (begin_queue && (ct == PIP_SIGNIFICANCE_MAP || ct == PIP_SIGNIFICANCE_EOB)) { push_queueing_symbols(ct); } } void end_coding_type(CodingType ct) { if (!model) { return; } model->end_coding_type(ct); if ((ct == PIP_SIGNIFICANCE_MAP || ct == PIP_SIGNIFICANCE_EOB)) { stop_queueing_symbols(); model->finished_queueing(ct, [&](model_key key, int*symbol) { size_t billable_bytes = encoder.put(*symbol, [&](range_t range){ return model->probability_for_model_key(range, key); }); model->update_state_for_model_key(*symbol, key); if (billable_bytes) { model->billable_bytes(billable_bytes); } }); static int i = 0; if (i++ < 10) { std::cerr << "FINISHED QUEUING DECODE: " << (int)(model->frames[model->cur_frame].meta_at(model->mb_coord.mb_x, model->mb_coord.mb_y).num_nonzeros[model->mb_coord.scan8_index]) << std::endl; } pop_queueing_symbols(ct); model->coding_type = PIP_UNKNOWN; } } private: void push_queueing_symbols(CodingType ct) { // Does not currently support nested queues. assert (queueing_symbols == PIP_UNKNOWN); assert (symbol_buffer.empty()); queueing_symbols = ct; } void stop_queueing_symbols() { assert (queueing_symbols != PIP_UNKNOWN); queueing_symbols = PIP_UNKNOWN; } void pop_queueing_symbols(CodingType ct) { //std::cerr<< "FINISHED QUEUEING "<< symbol_buffer.size()<<std::endl; if (ct == PIP_SIGNIFICANCE_MAP || ct == PIP_SIGNIFICANCE_EOB) { if (model) { model->reset_mb_significance_state_tracking(); } } for (auto &sym : symbol_buffer) { sym.execute(encoder, model, out, encoder_out); } symbol_buffer.clear(); } Recoded::Block *out; CABACContext ctx; compressor *c; h264_model *model; std::vector<uint8_t> encoder_out; recoded_code::encoder<std::back_insert_iterator<std::vector<uint8_t>>, uint8_t> encoder{ std::back_inserter(encoder_out)}; CodingType queueing_symbols = PIP_UNKNOWN; std::vector<h264_symbol> symbol_buffer; }; h264_model *get_model() { return &model; } private: Recoded::Block* find_next_coded_block_and_emit_literal(const uint8_t *buf, int size) { uint8_t *found = static_cast<uint8_t*>( memmem( &original_bytes[prev_coded_block_end], read_offset - prev_coded_block_end, buf, size) ); if (found && size >= SURROGATE_MARKER_BYTES) { size_t gap = found - &original_bytes[prev_coded_block_end]; out.add_block()->set_literal(&original_bytes[prev_coded_block_end], gap); prev_coded_block_end += gap + size; Recoded::Block *newBlock = out.add_block(); newBlock->set_length_parity(size & 1); if (size > 1) { newBlock->set_last_byte(&(buf[size - 1]), 1); } return newBlock; // Return a block for the recoder to fill. } else { // Can't recode this block, probably because it was NAL-escaped. Place // a skip marker in the block list. Recoded::Block* block = out.add_block(); block->set_skip_coded(true); block->set_size(size); return nullptr; // Tell the recoder to ignore this block. } } std::string input_filename; std::ostream& out_stream; uint8_t *original_bytes = nullptr; size_t original_size = 0; int read_offset = 0; int prev_coded_block_end = 0; h264_model model; Recoded out; }; class decompressor { // Used to track the decoding state of each block. struct block_state { bool coded = false; std::string surrogate_marker; std::string out_bytes; bool done = false; int8_t length_parity = -1; uint8_t last_byte; }; public: decompressor(const std::string& input_filename, std::ostream& out_stream) : input_filename(input_filename), out_stream(out_stream) { uint8_t *bytes; size_t size; if (av_file_map(input_filename.c_str(), &bytes, &size, 0, NULL) < 0) { throw std::invalid_argument("Failed to open file: " + input_filename); } in.ParseFromArray(bytes, size); } decompressor(const std::string& input_filename, const std::string& in_bytes, std::ostream& out_stream) : input_filename(input_filename), out_stream(out_stream) { in.ParseFromString(in_bytes); } void run() { blocks.clear(); blocks.resize(in.block_size()); av_decoder<decompressor> d(this, input_filename); d.decode_video(); for (auto& block : blocks) { if (!block.done) throw std::runtime_error("Not all blocks were decoded."); if (block.length_parity != -1) { // Correct for x264 padding: replace last byte or add an extra byte. if (block.length_parity != (int)(block.out_bytes.size() & 1)) { block.out_bytes.insert(block.out_bytes.end(), block.last_byte); } else { block.out_bytes[block.out_bytes.size() - 1] = block.last_byte; } } out_stream << block.out_bytes; } } int read_packet(uint8_t *buffer_out, int size) { uint8_t *p = buffer_out; while (size > 0 && read_index < in.block_size()) { if (read_block.empty()) { const Recoded::Block& block = in.block(read_index); if (int(block.has_literal()) + int(block.has_cabac()) + int(block.has_skip_coded()) != 1) { throw std::runtime_error("Invalid input block: must have exactly one type"); } if (block.has_literal()) { // This block is passed through without any re-coding. blocks[read_index].out_bytes = block.literal(); blocks[read_index].done = true; read_block = block.literal(); } else if (block.has_cabac()) { // Re-coded CABAC coded block. out_bytes will be filled by cabac_decoder. blocks[read_index].coded = true; blocks[read_index].surrogate_marker = next_surrogate_marker(); blocks[read_index].done = false; if (!block.has_size()) { throw std::runtime_error("CABAC block requires size field."); } if (block.has_length_parity() && block.has_last_byte() && !block.last_byte().empty()) { blocks[read_index].length_parity = block.length_parity(); blocks[read_index].last_byte = block.last_byte()[0]; } read_block = make_surrogate_block(blocks[read_index].surrogate_marker, block.size()); } else if (block.has_skip_coded() && block.skip_coded()) { // Non-re-coded CABAC coded block. The bytes of this block are // emitted in a literal block following this one. This block is // a flag to expect a cabac_decoder without a surrogate marker. blocks[read_index].coded = true; blocks[read_index].done = true; } else { throw std::runtime_error("Unknown input block type"); } } if ((size_t)read_offset < read_block.size()) { int n = read_block.copy(reinterpret_cast<char*>(p), size, read_offset); read_offset += n; p += n; size -= n; } if ((size_t)read_offset >= read_block.size()) { read_block.clear(); read_offset = 0; read_index++; } } return p - buffer_out; } class cabac_decoder { public: cabac_decoder(decompressor *d, CABACContext *ctx_in, const uint8_t *buf, int size) { index = d->recognize_coded_block(buf, size); block = &d->in.block(index); out = &d->blocks[index]; model = nullptr; if (block->has_cabac()) { model = &d->model; model->reset(); decoder.reset(new recoded_code::decoder<const char*, uint8_t>( block->cabac().data(), block->cabac().data() + block->cabac().size())); } else if (block->has_skip_coded() && block->skip_coded()) { // We're skipping this block, so disable calls to our hooks. ctx_in->coding_hooks = nullptr; ctx_in->coding_hooks_opaque = nullptr; ::ff_reset_cabac_decoder(ctx_in, buf, size); } else { throw std::runtime_error("Expected CABAC block."); } } ~cabac_decoder() { assert(out->done); } int get(uint8_t *state) { int symbol; if (model->coding_type == PIP_SIGNIFICANCE_EOB) { symbol = std::get<1>(model->get_model_key(state)); } else { symbol = decoder->get([&](range_t range){ return model->probability_for_state(range, state); }); } size_t billable_bytes = cabac_encoder.put(symbol, state); if (billable_bytes) { model->billable_cabac_bytes(billable_bytes); } model->update_state(symbol, state); return symbol; } int get_bypass() { int symbol = decoder->get([&](range_t range){ return model->probability_for_state(range, &model->bypass_context); }); model->update_state(symbol, &model->bypass_context); size_t billable_bytes = cabac_encoder.put_bypass(symbol); if (billable_bytes) { model->billable_cabac_bytes(billable_bytes); } return symbol; } int get_terminate() { int symbol = decoder->get([&](range_t range){ return model->probability_for_state(range, &model->terminate_context); }); model->update_state(symbol, &model->terminate_context); size_t billable_bytes = cabac_encoder.put_terminate(symbol); if (billable_bytes) { model->billable_cabac_bytes(billable_bytes); } if (symbol) { finish(); } return symbol; } void begin_coding_type( CodingType ct, int zigzag_index, int param0, int param1) { bool begin_queue = model && model->begin_coding_type(ct, zigzag_index, param0, param1); if (begin_queue && ct) { model->finished_queueing(ct, [&](model_key key, int * symbol) { *symbol = decoder->get([&](range_t range){ return model->probability_for_model_key(range, key); }); model->update_state_for_model_key(*symbol, key); }); static int i = 0; if (i++ < 10) { std::cerr << "FINISHED QUEUING RECODE: " << (int)model->frames[model->cur_frame].meta_at(model->mb_coord.mb_x, model->mb_coord.mb_y).num_nonzeros[model->mb_coord.scan8_index] << std::endl; } } } void end_coding_type(CodingType ct) { if (!model) { return; } model->end_coding_type(ct); } private: void finish() { // Omit trailing byte if it's only a stop bit. if (cabac_out.back() == 0x80) { cabac_out.pop_back(); } out->out_bytes.assign(reinterpret_cast<const char*>(cabac_out.data()), cabac_out.size()); out->done = true; } int index; const Recoded::Block *block; block_state *out = nullptr; h264_model *model; std::unique_ptr<recoded_code::decoder<const char*, uint8_t>> decoder; std::vector<uint8_t> cabac_out; cabac::encoder<std::back_insert_iterator<std::vector<uint8_t>>> cabac_encoder{ std::back_inserter(cabac_out)}; }; h264_model *get_model() { return &model; } private: // Return a unique 8-byte string containing no zero bytes (NAL-encoding-safe). std::string next_surrogate_marker() { uint64_t n = surrogate_marker_sequence_number++; std::string surrogate_marker(SURROGATE_MARKER_BYTES, '\x01'); for (int i = 0; i < (int)surrogate_marker.size(); i++) { surrogate_marker[i] = (n % 255) + 1; n /= 255; } return surrogate_marker; } std::string make_surrogate_block(const std::string& surrogate_marker, size_t size) { if (size < surrogate_marker.size()) { throw std::runtime_error("Invalid coded block size for surrogate: " + std::to_string(size)); } std::string surrogate_block = surrogate_marker; surrogate_block.resize(size, 'X'); // NAL-encoding-safe padding. return surrogate_block; } int recognize_coded_block(const uint8_t* buf, int size) { while (!blocks[next_coded_block].coded) { if (next_coded_block >= read_index) { throw std::runtime_error("Coded block expected, but not recorded in the compressed data."); } next_coded_block++; } int index = next_coded_block++; // Validate the decoder init call against the coded block's size and surrogate marker. const Recoded::Block& block = in.block(index); if (block.has_cabac()) { if (block.size() != size) { throw std::runtime_error("Invalid surrogate block size."); } std::string buf_header(reinterpret_cast<const char*>(buf), blocks[index].surrogate_marker.size()); if (blocks[index].surrogate_marker != buf_header) { throw std::runtime_error("Invalid surrogate marker in coded block."); } } else if (block.has_skip_coded()) { if (block.size() != size) { throw std::runtime_error("Invalid skip_coded block size."); } } else { throw std::runtime_error("Internal error: expected coded block."); } return index; } std::string input_filename; std::ostream& out_stream; Recoded in; int read_index = 0, read_offset = 0; std::string read_block; std::vector<block_state> blocks; // Counter used to generate surrogate markers for coded blocks. uint64_t surrogate_marker_sequence_number = 1; // Head of the coded block queue - blocks that have been produced by // read_packet but not yet decoded. Tail of the queue is read_index. int next_coded_block = 0; h264_model model; }; int roundtrip(const std::string& input_filename, std::ostream* out) { std::stringstream original, compressed, decompressed; original << std::ifstream(input_filename).rdbuf(); compressor c(input_filename, compressed); c.run(); decompressor d(input_filename, compressed.str(), decompressed); d.run(); if (original.str() == decompressed.str()) { if (out) { (*out) << compressed.str(); } double ratio = compressed.str().size() * 1.0 / original.str().size(); Recoded compressed_proto; compressed_proto.ParseFromString(compressed.str()); int proto_block_bytes = 0; for (const auto& block : compressed_proto.block()) { proto_block_bytes += block.literal().size() + block.cabac().size(); } double proto_overhead = (compressed.str().size() - proto_block_bytes) * 1.0 / compressed.str().size(); std::cout << "Compress-decompress roundtrip succeeded:" << std::endl; std::cout << " compression ratio: " << ratio*100. << "%" << std::endl; std::cout << " protobuf overhead: " << proto_overhead*100. << "%" << std::endl; return 0; } else { std::cerr << "Compress-decompress roundtrip failed." << std::endl; return 1; } } int main(int argc, char **argv) { av_register_all(); if (argc < 3 || argc > 4) { std::cerr << "Usage: " << argv[0] << " [compress|decompress|roundtrip] <input> [output]" << std::endl; return 1; } std::string command = argv[1]; std::string input_filename = argv[2]; std::ofstream out_file; if (argc > 3) { out_file.open(argv[3]); } try { if (command == "compress") { compressor c(input_filename, out_file.is_open() ? out_file : std::cout); c.run(); } else if (command == "decompress") { decompressor d(input_filename, out_file.is_open() ? out_file : std::cout); d.run(); } else if (command == "roundtrip") { return roundtrip(input_filename, out_file.is_open() ? &out_file : nullptr); } else { throw std::invalid_argument("Unknown command: " + command); } } catch (const std::exception& e) { std::cerr << "Exception (" << typeid(e).name() << "): " << e.what() << std::endl; return 1; } return 0; }
59,976
23,249
/* * This Kalman filter is implemented as a learning exercise. * It is used in the final version of the cube, but could be * almost drag and drop replaced by a more efficient library. * * Uses a custom Matrix<T> class to perform matrix operations * in an arduino friendly (space saving) way. */ #include "kalman.hpp" #include <algorithm> #include <functional> Kalman_Filter::Kalman_Filter( Matrix<float> &_cov_mat, // Covariance Matrix. //[0.5,0,0,0.01] Matrix<float> &_trans_mat, // State transition Matrix Matrix<float> &_Q, // Process noise// Time Step Matrix<float> &_R, // Measurement Noise Matrix<float> &_x_hat, // State vector. 2 states in this case, MPU roll, and MPU drift [ROLL,DRIFT] Matrix<float> &_kal_gain, // Kalman Gain, [0,0]. Matrix<float> &_psi, float _dt) // Timestep : cov_mat(_cov_mat), trans_mat(_trans_mat), Q(_Q), R(_R), x_hat(_x_hat), kal_gain(_kal_gain), psi(_psi), dt(_dt) { H = Matrix<float> I = Matrix<float> {H.GetRows(),H.GetRows(),0}; } //initialize the kalman filter with time 0 and the //current states at time 0. void Kalman_Filter::init(float t0 , Matrix<float>&x0) { this->t=t0; this->x_hat = x0; } void Kalman_Filter::update(const int gyro_deg, const long acc_roll) { //Calculate zk and uk Matrix<float> uk = {gyro_deg / 65.5}; //gyro roll rate per second Matrix<float> zk {acc_roll}; //accel angle measurement in degrees //Predict States using a priori state estimation equation. Matrix<float> xhat_minus = trans_mat * x_hat + psi * uk; Matrix<float> cov_mat_minus = trans_mat * cov_mat * trans_mat.Transpose() + Q; //Calculate Kalman Gain Matrix<float> S = H * cov_mat_minus * H.Transpose() + R; Matrix<float> K = cov_mat_minus * H.Transpose() * S.Invert(); //Update States based on measurements x_hat = xhat_minus + K * (zk - (H * xhat_minus)); cov_mat = (I - K * H) * cov_mat_minus; }
2,006
736