text
stringlengths
8
6.88M
#include <bits/stdc++.h> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int n) { int i,j, min_idx; //One by one move boundary of unsorted subarray for(i=0;i < n-1;i++) { //Find the minmum element int unsorted array min_idx = i; for (j= i+1; j< n; j++) if(arr[j] < arr[min_idx]) min_idx = j; //Swap the found minmum element with the first elemetn swap(&arr[min_idx],&arr[i]); } } /* Function to print an array */ void printArray(int arr[],int size) { int i; for (i=0; i<size;i++) cout << arr[i] << " "; cout << endl; } // Driver program to test above functions int main() { int arr[] = {64,25,12,22,11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr,n); cout << "Sorted array: \n"; printArray(arr,n); return 0; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Gaming.UI.3.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Gaming::UI::IGameBarStatics> : produce_base<D, Windows::Gaming::UI::IGameBarStatics> { HRESULT __stdcall add_VisibilityChanged(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Foundation::IInspectable>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().VisibilityChanged(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_VisibilityChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().VisibilityChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_IsInputRedirectedChanged(impl::abi_arg_in<Windows::Foundation::EventHandler<Windows::Foundation::IInspectable>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().IsInputRedirectedChanged(*reinterpret_cast<const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_IsInputRedirectedChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().IsInputRedirectedChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Visible(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Visible()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IsInputRedirected(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsInputRedirected()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Gaming::UI::IGameChatMessageReceivedEventArgs> : produce_base<D, Windows::Gaming::UI::IGameChatMessageReceivedEventArgs> { HRESULT __stdcall get_AppId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AppId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_AppDisplayName(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AppDisplayName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SenderName(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SenderName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Message(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Message()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Origin(Windows::Gaming::UI::GameChatMessageOrigin * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Origin()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Gaming::UI::IGameChatOverlay> : produce_base<D, Windows::Gaming::UI::IGameChatOverlay> { HRESULT __stdcall get_DesiredPosition(Windows::Gaming::UI::GameChatOverlayPosition * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DesiredPosition()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_DesiredPosition(Windows::Gaming::UI::GameChatOverlayPosition value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().DesiredPosition(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_AddMessage(impl::abi_arg_in<hstring> sender, impl::abi_arg_in<hstring> message, Windows::Gaming::UI::GameChatMessageOrigin origin) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().AddMessage(*reinterpret_cast<const hstring *>(&sender), *reinterpret_cast<const hstring *>(&message), origin); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Gaming::UI::IGameChatOverlayMessageSource> : produce_base<D, Windows::Gaming::UI::IGameChatOverlayMessageSource> { HRESULT __stdcall add_MessageReceived(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Gaming::UI::GameChatOverlayMessageSource, Windows::Gaming::UI::GameChatMessageReceivedEventArgs>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().MessageReceived(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Gaming::UI::GameChatOverlayMessageSource, Windows::Gaming::UI::GameChatMessageReceivedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_MessageReceived(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().MessageReceived(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetDelayBeforeClosingAfterMessageReceived(impl::abi_arg_in<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetDelayBeforeClosingAfterMessageReceived(*reinterpret_cast<const Windows::Foundation::TimeSpan *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Gaming::UI::IGameChatOverlayStatics> : produce_base<D, Windows::Gaming::UI::IGameChatOverlayStatics> { HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Gaming::UI::IGameChatOverlay> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; } namespace Windows::Gaming::UI { template <typename D> event_token impl_IGameChatOverlayMessageSource<D>::MessageReceived(const Windows::Foundation::TypedEventHandler<Windows::Gaming::UI::GameChatOverlayMessageSource, Windows::Gaming::UI::GameChatMessageReceivedEventArgs> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IGameChatOverlayMessageSource)->add_MessageReceived(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IGameChatOverlayMessageSource> impl_IGameChatOverlayMessageSource<D>::MessageReceived(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Gaming::UI::GameChatOverlayMessageSource, Windows::Gaming::UI::GameChatMessageReceivedEventArgs> & handler) const { return impl::make_event_revoker<D, IGameChatOverlayMessageSource>(this, &ABI::Windows::Gaming::UI::IGameChatOverlayMessageSource::remove_MessageReceived, MessageReceived(handler)); } template <typename D> void impl_IGameChatOverlayMessageSource<D>::MessageReceived(event_token token) const { check_hresult(WINRT_SHIM(IGameChatOverlayMessageSource)->remove_MessageReceived(token)); } template <typename D> void impl_IGameChatOverlayMessageSource<D>::SetDelayBeforeClosingAfterMessageReceived(const Windows::Foundation::TimeSpan & value) const { check_hresult(WINRT_SHIM(IGameChatOverlayMessageSource)->abi_SetDelayBeforeClosingAfterMessageReceived(get_abi(value))); } template <typename D> hstring impl_IGameChatMessageReceivedEventArgs<D>::AppId() const { hstring value; check_hresult(WINRT_SHIM(IGameChatMessageReceivedEventArgs)->get_AppId(put_abi(value))); return value; } template <typename D> hstring impl_IGameChatMessageReceivedEventArgs<D>::AppDisplayName() const { hstring value; check_hresult(WINRT_SHIM(IGameChatMessageReceivedEventArgs)->get_AppDisplayName(put_abi(value))); return value; } template <typename D> hstring impl_IGameChatMessageReceivedEventArgs<D>::SenderName() const { hstring value; check_hresult(WINRT_SHIM(IGameChatMessageReceivedEventArgs)->get_SenderName(put_abi(value))); return value; } template <typename D> hstring impl_IGameChatMessageReceivedEventArgs<D>::Message() const { hstring value; check_hresult(WINRT_SHIM(IGameChatMessageReceivedEventArgs)->get_Message(put_abi(value))); return value; } template <typename D> Windows::Gaming::UI::GameChatMessageOrigin impl_IGameChatMessageReceivedEventArgs<D>::Origin() const { Windows::Gaming::UI::GameChatMessageOrigin value {}; check_hresult(WINRT_SHIM(IGameChatMessageReceivedEventArgs)->get_Origin(&value)); return value; } template <typename D> event_token impl_IGameBarStatics<D>::VisibilityChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IGameBarStatics)->add_VisibilityChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IGameBarStatics> impl_IGameBarStatics<D>::VisibilityChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) const { return impl::make_event_revoker<D, IGameBarStatics>(this, &ABI::Windows::Gaming::UI::IGameBarStatics::remove_VisibilityChanged, VisibilityChanged(handler)); } template <typename D> void impl_IGameBarStatics<D>::VisibilityChanged(event_token token) const { check_hresult(WINRT_SHIM(IGameBarStatics)->remove_VisibilityChanged(token)); } template <typename D> event_token impl_IGameBarStatics<D>::IsInputRedirectedChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IGameBarStatics)->add_IsInputRedirectedChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IGameBarStatics> impl_IGameBarStatics<D>::IsInputRedirectedChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) const { return impl::make_event_revoker<D, IGameBarStatics>(this, &ABI::Windows::Gaming::UI::IGameBarStatics::remove_IsInputRedirectedChanged, IsInputRedirectedChanged(handler)); } template <typename D> void impl_IGameBarStatics<D>::IsInputRedirectedChanged(event_token token) const { check_hresult(WINRT_SHIM(IGameBarStatics)->remove_IsInputRedirectedChanged(token)); } template <typename D> bool impl_IGameBarStatics<D>::Visible() const { bool value {}; check_hresult(WINRT_SHIM(IGameBarStatics)->get_Visible(&value)); return value; } template <typename D> bool impl_IGameBarStatics<D>::IsInputRedirected() const { bool value {}; check_hresult(WINRT_SHIM(IGameBarStatics)->get_IsInputRedirected(&value)); return value; } template <typename D> Windows::Gaming::UI::GameChatOverlay impl_IGameChatOverlayStatics<D>::GetDefault() const { Windows::Gaming::UI::GameChatOverlay value { nullptr }; check_hresult(WINRT_SHIM(IGameChatOverlayStatics)->abi_GetDefault(put_abi(value))); return value; } template <typename D> Windows::Gaming::UI::GameChatOverlayPosition impl_IGameChatOverlay<D>::DesiredPosition() const { Windows::Gaming::UI::GameChatOverlayPosition value {}; check_hresult(WINRT_SHIM(IGameChatOverlay)->get_DesiredPosition(&value)); return value; } template <typename D> void impl_IGameChatOverlay<D>::DesiredPosition(Windows::Gaming::UI::GameChatOverlayPosition value) const { check_hresult(WINRT_SHIM(IGameChatOverlay)->put_DesiredPosition(value)); } template <typename D> void impl_IGameChatOverlay<D>::AddMessage(hstring_view sender, hstring_view message, Windows::Gaming::UI::GameChatMessageOrigin origin) const { check_hresult(WINRT_SHIM(IGameChatOverlay)->abi_AddMessage(get_abi(sender), get_abi(message), origin)); } inline event_token GameBar::VisibilityChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) { return get_activation_factory<GameBar, IGameBarStatics>().VisibilityChanged(handler); } inline factory_event_revoker<IGameBarStatics> GameBar::VisibilityChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) { auto factory = get_activation_factory<GameBar, IGameBarStatics>(); return { factory, &ABI::Windows::Gaming::UI::IGameBarStatics::remove_VisibilityChanged, factory.VisibilityChanged(handler) }; } inline void GameBar::VisibilityChanged(event_token token) { get_activation_factory<GameBar, IGameBarStatics>().VisibilityChanged(token); } inline event_token GameBar::IsInputRedirectedChanged(const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) { return get_activation_factory<GameBar, IGameBarStatics>().IsInputRedirectedChanged(handler); } inline factory_event_revoker<IGameBarStatics> GameBar::IsInputRedirectedChanged(auto_revoke_t, const Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> & handler) { auto factory = get_activation_factory<GameBar, IGameBarStatics>(); return { factory, &ABI::Windows::Gaming::UI::IGameBarStatics::remove_IsInputRedirectedChanged, factory.IsInputRedirectedChanged(handler) }; } inline void GameBar::IsInputRedirectedChanged(event_token token) { get_activation_factory<GameBar, IGameBarStatics>().IsInputRedirectedChanged(token); } inline bool GameBar::Visible() { return get_activation_factory<GameBar, IGameBarStatics>().Visible(); } inline bool GameBar::IsInputRedirected() { return get_activation_factory<GameBar, IGameBarStatics>().IsInputRedirected(); } inline Windows::Gaming::UI::GameChatOverlay GameChatOverlay::GetDefault() { return get_activation_factory<GameChatOverlay, IGameChatOverlayStatics>().GetDefault(); } inline GameChatOverlayMessageSource::GameChatOverlayMessageSource() : GameChatOverlayMessageSource(activate_instance<GameChatOverlayMessageSource>()) {} } } template<> struct std::hash<winrt::Windows::Gaming::UI::IGameBarStatics> { size_t operator()(const winrt::Windows::Gaming::UI::IGameBarStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::IGameChatMessageReceivedEventArgs> { size_t operator()(const winrt::Windows::Gaming::UI::IGameChatMessageReceivedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::IGameChatOverlay> { size_t operator()(const winrt::Windows::Gaming::UI::IGameChatOverlay & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::IGameChatOverlayMessageSource> { size_t operator()(const winrt::Windows::Gaming::UI::IGameChatOverlayMessageSource & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::IGameChatOverlayStatics> { size_t operator()(const winrt::Windows::Gaming::UI::IGameChatOverlayStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::GameChatMessageReceivedEventArgs> { size_t operator()(const winrt::Windows::Gaming::UI::GameChatMessageReceivedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::GameChatOverlay> { size_t operator()(const winrt::Windows::Gaming::UI::GameChatOverlay & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Gaming::UI::GameChatOverlayMessageSource> { size_t operator()(const winrt::Windows::Gaming::UI::GameChatOverlayMessageSource & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
void salidas(uint8_t pin1, uint8_t pin2) { analogWrite(pin1, brillo); if (vBat > 0 && vBat < VBAT_MIN) digitalWrite(pin2, HIGH); } //-------------------------------------------------------------
#include "task_15.h" string task::getMatrix(int m, int n) { static int counter = 0, arr[100][100]; bool isBreak = false; int round = 0; while (true) { for (int j = round; j != n - round; ++j) if (arr[round][j] != 0) { isBreak = true; break; } else arr[round][j] = ++counter; if (isBreak) break; // down for (int i = 1 + round; i != m - round; ++i) if (arr[i][n - 1 - round] != 0) { isBreak = true; break; } else arr[i][n - 1 - round] = ++counter; if (isBreak) break; // right for (int j = n - 2 - round; j != round - 1; --j) if (arr[m - 1 - round][j] != 0) { isBreak = true; break; } else arr[m - 1 - round][j] = ++counter; if (isBreak) break; // up for (int i = m - 2 - round; i != round; --i) if (arr[i][round] != 0) { isBreak = true; break; } else arr[i][round] = ++counter; if (isBreak) break; ++round; } stringstream ss; for (int i = 0; i < m; i++){ for (int j = 0; j < n; j++) ss << setw(4) << arr[i][j]; ss << endl; } return ss.str(); }
#ifndef __SHAPE_H__ #define __SHAPE_H__ #include "base.h" template <int dimension> struct Shape { enum { kDimension = dimension, kSubdim = dimension - 1, }; inline Shape(void) {} inline Shape(const Shape<kDimension> &s) { for (int i = 0; i < kDimension; i++) { shape_[i] = s[i]; } } inline index_t& operator [](index_t idx) { SM_DbgAssert(idx < kDimension); return shape_[idx]; } inline const index_t& operator [](index_t idx) const { SM_DbgAssert(idx < kDimension); return shape_[idx]; } inline bool operator ==(const Shape<kDimension> &s) const { for (int i = 0; i < kDimension; i++) { if (s[i] != shape_[i]) return false; } return true; } inline bool operator !=(const Shape<kDimension> &s) const { return !(*this == s); } // flatten the higher dimension to second dimension, return a 2D shape inline Shape<2> FlatTo2D(void) const { Shape<2> s; s[1] = shape_[kSubdim]; index_t ymax = 1; for (int i = 0; i < kSubdim; ++i) { ymax *= shape_[i]; } s[0] = ymax; return s; } // return number of valid elements inline size_t Size(void) const { size_t size = shape_[0]; for (int i = 1; i < kDimension; ++i) { size *= shape_[i]; } return size; } // get subshape that takes off largest dimension inline Shape<kSubdim> SubShape(void) const { Shape<kSubdim> s; for (int i = 0; i < kSubdim; ++i) { s[i] = shape_[i + 1]; } return s; } // slice the shape from start to end template<int dimstart, int dimend> inline Shape<dimend - dimstart> Slice(void) const { Shape<dimend - dimstart> s; for (int i = dimstart; i < dimend; ++i) { s[i - dimstart] = shape_[i]; } return s; } private: index_t shape_[kDimension]; }; //--------------------------------------------------- // useful construction functions to generate shape //--------------------------------------------------- inline Shape<1> Shape1(index_t s0) { Shape<1> s; s[0] = s0; return s; } inline Shape<2> Shape2(index_t s0, index_t s1) { Shape<2> s; s[0] = s0; s[1] = s1; return s; } inline Shape<3> Shape3(index_t s0, index_t s1, index_t s2) { Shape<3> s; s[0] = s0; s[1] = s1; s[2] = s2; return s; } inline Shape<4> Shape4(index_t s0, index_t s1, index_t s2, index_t s3) { Shape<4> s; s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; return s; } #endif /* end of include guard */
#pragma once #include <string> #include "ParseTree.h" #include <vector> #include <set> class Parser { public: Parser(); Parser(std::vector<std::string> tokens, std::string filename); ParseTree* parse(); private: //Pre parse functions void scrapeClassIdentifiers(); //Parse fucntions ParseTree* parseFunction(); ParseTree* parseParameters(); ParseTree* parseParameter(); ParseTree* parseStatement(); ParseTree* parseExpression(std::string stopToken); //Statement Paths ParseTree* parseCompound(); ParseTree* parseIf(); ParseTree* parseWhile(); ParseTree* parseFor(); ParseTree* parseReturn(); ParseTree* parseDeclaration(std::string); ParseTree* parseExpressionStatement(); //Variables std::string filename; ParseTree* parseTree; std::set<std::string> classes; std::vector<std::string> tokens; std::vector<std::string>::iterator it; std::string precedingType; };
 /// @file ImpAnd.cc /// @brief ImpAnd の実装ファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2012 Yusuke Matsunaga /// All rights reserved. #include "ImpAnd.h" #include "ImpMgr.h" #define DEBUG_CHANGE_VALUE 0 BEGIN_NAMESPACE_YM_NETWORKS ////////////////////////////////////////////////////////////////////// // クラス ImpAnd ////////////////////////////////////////////////////////////////////// // @brief コンストラクタ // @param[in] handle0 ファンイン0のハンドル // @param[in] handle1 ファンイン1のハンドル ImpAnd::ImpAnd(ImpNodeHandle handle0, ImpNodeHandle handle1) : ImpNode(handle0, handle1) { mState = kStXX_X; } // @brief デストラクタ ImpAnd::~ImpAnd() { } // @brief AND タイプのときに true を返す. bool ImpAnd::is_and() const { return true; } // @brief 出力値を返す. Bool3 ImpAnd::val() const { switch ( mState ) { case kStXX_X: case kSt1X_X: case kStX1_X: return kB3X; case kStXX_0: case kStX0_0: case kSt0X_0: case kSt00_0: case kSt10_0: case kSt01_0: return kB3False; case kSt11_1: return kB3True; default: ASSERT_NOT_REACHED; break; } return kB3X; } // @brief ビットベクタ値の計算を行なう. void ImpAnd::calc_bitval() { ymuint64 val0 = fanin0().src_node()->bitval(); if ( fanin0().src_inv() ) { val0 = ~val0; } ymuint64 val1 = fanin1().src_node()->bitval(); if ( fanin1().src_inv() ) { val1 = ~val1; } set_bitval(val0 & val1); } // @brief 状態を初期化する. void ImpAnd::clear() { cout << "node#" << id() << " clear" << endl; mState = kStXX_X; } // @brief 状態を返す. ymuint32 ImpAnd::cur_state() const { return static_cast<ymuint32>(mState); } // @brief 状態を表す文字列を返す. string ImpAnd::cur_state_str() const { switch ( mState ) { case kStXX_X: return "XX:X"; case kSt1X_X: return "1X:X"; case kStX1_X: return "X1:X"; case kStXX_0: return "XX:0"; case kStX0_0: return "X0:0"; case kSt0X_0: return "0X:0"; case kSt00_0: return "00:0"; case kSt10_0: return "10:0"; case kSt01_0: return "01:0"; case kSt11_1: return "11:1"; default: ASSERT_NOT_REACHED; break; } return ""; } // @brief 状態を元にもどす. void ImpAnd::restore(ImpMgr& mgr, ymuint32 val) { change_value(mgr, static_cast<tState>(val), false); } // @brief unjustified ノードの時 true を返す. bool ImpAnd::is_unjustified() const { switch ( mState ) { case kSt1X_X: case kStX1_X: case kStXX_0: return true; default: break; } return false; } // @brief justification パタン数を得る. ymuint ImpAnd::justification_num() { switch ( mState ) { case kSt1X_X: // 10:0 と 11:1 return 2; case kStX1_X: // 01:0 と 11:1 return 2; case kStXX_0: // 0X:0 と X0:0 return 2; default: break; } return 0; } BEGIN_NONAMESPACE inline ImpDst imp(const ImpEdge& e, ymuint val) { if ( e.src_inv() ) { val ^= 1; } return ImpDst(e.src_node(), val); } END_NONAMESPACE // @brief justification パタン を得る. // @param[in] pos 位置番号 ( 0 <= pos < justification_num() ) // @return 値割り当て ImpDst ImpAnd::get_justification(ymuint pos) { switch ( mState ) { case kSt1X_X: // 10:0 と 11:1 if ( pos == 0 ) { // 10:0 return imp(fanin1(), 0); } else if ( pos == 1 ) { // 11:1 return imp(fanin1(), 1); } break; case kStX1_X: // 01:0 と 11:1 if ( pos == 0 ) { return imp(fanin0(), 0); } else if ( pos == 1 ) { return imp(fanin0(), 1); } break; case kStXX_0: // 0X:0 と X0:0 if ( pos == 0 ) { return imp(fanin0(), 0); } else if ( pos == 1 ) { return imp(fanin1(), 0); } break; default: break; } ASSERT_NOT_REACHED; return ImpDst(NULL, 0); } // @brief ファンイン0を0にする. // @param[in] mgr ImpMgr // @param[in] rec 含意を記録するオブジェクト bool ImpAnd::fwd0_imp0(ImpMgr& mgr, ImpRec& rec) { switch ( mState ) { case kStXX_X: // XX:X -> 0X:0 change_value(mgr, kSt0X_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL, rec); case kStX1_X: // X1:X -> 01:0 change_value(mgr, kSt01_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL, rec); case kStXX_0: // XX:0 -> 0X:0 change_value(mgr, kSt0X_0); break; case kStX0_0: // X0:0 -> 00:0 change_value(mgr, kSt00_0); break; case kSt1X_X: // illegal case kSt10_0: // illegal case kSt11_1: // illegal return false; case kSt0X_0: // no change case kSt01_0: // no change case kSt00_0: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン0を1にする. // @param[in] mgr ImpMgr // @param[in] rec 含意を記録するオブジェクト bool ImpAnd::fwd0_imp1(ImpMgr& mgr, ImpRec& rec) { switch ( mState ) { case kStXX_X: // XX:X -> 1X:X change_value(mgr, kSt1X_X); break; case kStX1_X: // X1:X -> 11:1 change_value(mgr, kSt11_1); // ファンアウト先に1を伝搬する. return fanout_prop1(mgr, NULL, rec); case kStXX_0: // XX:0 -> 10:0 change_value(mgr, kSt10_0); // ファンイン1に0を伝搬する. return fanin1_prop0(mgr, rec); case kStX0_0: // X0:0 -> 10:0 change_value(mgr, kSt10_0); break; case kSt0X_0: // illegal case kSt00_0: // illegal case kSt01_0: // illegal return false; case kSt1X_X: // no change case kSt10_0: // no change case kSt11_1: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン1を0にする. // @param[in] mgr ImpMgr // @param[in] rec 含意を記録するオブジェクト bool ImpAnd::fwd1_imp0(ImpMgr& mgr, ImpRec& rec) { switch ( mState ) { case kStXX_X: // XX:X -> X0:0 change_value(mgr, kStX0_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL, rec); case kSt1X_X: // 1X:X -> 10:0 change_value(mgr, kSt10_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL, rec); case kSt0X_0: // 0X:0 -> 00:0 change_value(mgr, kSt00_0); break; case kStXX_0: // XX:0 -> X0:0 change_value(mgr, kStX0_0); break; case kStX1_X: // illegal case kSt01_0: // illegal case kSt11_1: // illegal return false; case kStX0_0: // no change case kSt00_0: // no change case kSt10_0: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン1を1にする. // @param[in] mgr ImpMgr // @param[in] rec 含意を記録するオブジェクト bool ImpAnd::fwd1_imp1(ImpMgr& mgr, ImpRec& rec) { switch ( mState ) { case kStXX_X: // XX:X -> X1:X change_value(mgr, kStX1_X); break; case kSt1X_X: // 1X:X -> 11:1 change_value(mgr, kSt11_1); // ファンアウト先に1を伝搬する. return fanout_prop1(mgr, NULL, rec); case kStXX_0: // XX:0 -> 01:0 change_value(mgr, kSt01_0); // ファンイン0に0を伝搬する. return fanin0_prop0(mgr, rec); case kSt0X_0: // 0X:0 -> 01:0 change_value(mgr, kSt01_0); break; case kStX0_0: // illegal case kSt00_0: // illegal case kSt10_0: // illegal return false; case kStX1_X: // no change case kSt01_0: // no change case kSt11_1: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief 出力を0にする. // @param[in] mgr ImpMgr // @param[in] rec 含意を記録するオブジェクト bool ImpAnd::bwd_imp0(ImpMgr& mgr, ImpRec& rec) { switch ( mState ) { case kStXX_X: // XX:X -> XX:0 change_value(mgr, kStXX_0); break; case kSt1X_X: // 1X:X -> 10:0 change_value(mgr, kSt10_0); // ファンイン1に0を伝搬する. return fanin1_prop0(mgr, rec); case kStX1_X: // X1:X -> 01:0 change_value(mgr, kSt01_0); // ファンイン0に0を伝搬する. return fanin0_prop0(mgr, rec); case kStXX_0: // no change case kStX0_0: // no change case kSt0X_0: // no change case kSt00_0: // no change case kSt10_0: // no change case kSt01_0: // no change break; case kSt11_1: // illegal return false; default: ASSERT_NOT_REACHED; break; } return true; } // @brief 出力を1にする. // @param[in] mgr ImpMgr // @param[in] rec 含意を記録するオブジェクト bool ImpAnd::bwd_imp1(ImpMgr& mgr, ImpRec& rec) { switch ( mState ) { case kStXX_X: // XX:X -> 11:1 change_value(mgr, kSt11_1); // ファンイン0に1を伝搬する. // ファンイン1に1を伝搬する. return fanin0_prop1(mgr, rec) && fanin1_prop1(mgr, rec); case kSt1X_X: // 1X:X -> 11:1 change_value(mgr, kSt11_1); // ファンイン1に1を伝搬する. return fanin1_prop1(mgr, rec); case kStX1_X: // X1:X -> 11:1 change_value(mgr, kSt11_1); // ファンイン0に1を伝搬する. return fanin0_prop1(mgr, rec); case kStXX_0: // illegal case kStX0_0: // illegal case kSt0X_0: // illegal case kSt00_0: // illegal case kSt10_0: // illegal case kSt01_0: // illegal return false; case kSt11_1: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン0を0にする. // @param[in] mgr ImMgr bool ImpAnd::fwd0_imp0(ImpMgr& mgr) { switch ( mState ) { case kStXX_X: // XX:X -> 0X:0 change_value(mgr, kSt0X_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL); case kStX1_X: // X1:X -> 01:0 change_value(mgr, kSt01_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL); case kStXX_0: // XX:0 -> 0X:0 change_value(mgr, kSt0X_0); break; case kStX0_0: // X0:0 -> 00:0 change_value(mgr, kSt00_0); break; case kSt1X_X: // illegal case kSt10_0: // illegal case kSt11_1: // illegal return false; case kSt0X_0: // no change case kSt01_0: // no change case kSt00_0: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン0を1にする. // @param[in] mgr ImMgr bool ImpAnd::fwd0_imp1(ImpMgr& mgr) { switch ( mState ) { case kStXX_X: // XX:X -> 1X:X change_value(mgr, kSt1X_X); break; case kStX1_X: // X1:X -> 11:1 change_value(mgr, kSt11_1); // ファンアウト先に1を伝搬する. return fanout_prop1(mgr, NULL); case kStXX_0: // XX:0 -> 10:0 change_value(mgr, kSt10_0); // ファンイン1に0を伝搬する. return fanin1_prop0(mgr); case kStX0_0: // X0:0 -> 10:0 change_value(mgr, kSt10_0); break; case kSt0X_0: // illegal case kSt00_0: // illegal case kSt01_0: // illegal return false; case kSt1X_X: // no change case kSt10_0: // no change case kSt11_1: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン1を0にする. // @param[in] mgr ImMgr bool ImpAnd::fwd1_imp0(ImpMgr& mgr) { switch ( mState ) { case kStXX_X: // XX:X -> X0:0 change_value(mgr, kStX0_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL); case kSt1X_X: // 1X:X -> 10:0 change_value(mgr, kSt10_0); // ファンアウト先に0を伝搬する. return fanout_prop0(mgr, NULL); case kSt0X_0: // 0X:0 -> 00:0 change_value(mgr, kSt00_0); break; case kStXX_0: // XX:0 -> X0:0 change_value(mgr, kStX0_0); break; case kStX1_X: // illegal case kSt01_0: // illegal case kSt11_1: // illegal return false; case kStX0_0: // no change case kSt00_0: // no change case kSt10_0: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief ファンイン1を1にする. // @param[in] mgr ImMgr bool ImpAnd::fwd1_imp1(ImpMgr& mgr) { switch ( mState ) { case kStXX_X: // XX:X -> X1:X change_value(mgr, kStX1_X); break; case kSt1X_X: // 1X:X -> 11:1 change_value(mgr, kSt11_1); // ファンアウト先に1を伝搬する. return fanout_prop1(mgr, NULL); case kStXX_0: // XX:0 -> 01:0 change_value(mgr, kSt01_0); // ファンイン0に0を伝搬する. return fanin0_prop0(mgr); case kSt0X_0: // 0X:0 -> 01:0 change_value(mgr, kSt01_0); break; case kStX0_0: // illegal case kSt00_0: // illegal case kSt10_0: // illegal return false; case kStX1_X: // no change case kSt01_0: // no change case kSt11_1: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief 出力を0にする. // @param[in] mgr ImMgr bool ImpAnd::bwd_imp0(ImpMgr& mgr) { switch ( mState ) { case kStXX_X: // XX:X -> XX:0 change_value(mgr, kStXX_0); break; case kSt1X_X: // 1X:X -> 10:0 change_value(mgr, kSt10_0); // ファンイン1に0を伝搬する. return fanin1_prop0(mgr); case kStX1_X: // X1:X -> 01:0 change_value(mgr, kSt01_0); // ファンイン0に0を伝搬する. return fanin0_prop0(mgr); case kStXX_0: // no change case kStX0_0: // no change case kSt0X_0: // no change case kSt00_0: // no change case kSt10_0: // no change case kSt01_0: // no change break; case kSt11_1: // illegal return false; default: ASSERT_NOT_REACHED; break; } return true; } // @brief 出力を1にする. // @param[in] mgr ImMgr bool ImpAnd::bwd_imp1(ImpMgr& mgr) { switch ( mState ) { case kStXX_X: // XX:X -> 11:1 change_value(mgr, kSt11_1); // ファンイン0に1を伝搬する. // ファンイン1に1を伝搬する. return fanin0_prop1(mgr) && fanin1_prop1(mgr); case kSt1X_X: // 1X:X -> 11:1 change_value(mgr, kSt11_1); // ファンイン1に1を伝搬する. return fanin1_prop1(mgr); case kStX1_X: // X1:X -> 11:1 change_value(mgr, kSt11_1); // ファンイン0に1を伝搬する. return fanin0_prop1(mgr); case kStXX_0: // illegal case kStX0_0: // illegal case kSt0X_0: // illegal case kSt00_0: // illegal case kSt10_0: // illegal case kSt01_0: // illegal return false; case kSt11_1: // no change break; default: ASSERT_NOT_REACHED; break; } return true; } // @brief 定数伝搬を行なう. // @param[in] mgr ImMgr // @param[in] val 値 // @param[in] ipos 入力位置 void ImpAnd::prop_const(ImpMgr& mgr, ymuint val, ymuint ipos) { switch ( mState ) { case kStXX_X: if ( ipos == 0 ) { if ( val == 0 ) { change_value(mgr, kSt0X_0, false); cout << "Node#" << id() << " is const0" << endl; set_const(mgr, 0); } else { change_value(mgr, kSt1X_X, false); } } else { if ( val == 0 ) { change_value(mgr, kStX0_0, false); cout << "Node#" << id() << " is const0" << endl; set_const(mgr, 0); } else { change_value(mgr, kStX1_X, false); } } break; case kStX1_X: if ( ipos == 0 ) { if ( val == 0 ) { change_value(mgr, kSt01_0, false); cout << "Node#" << id() << " is const0" << endl; set_const(mgr, 0); } else { change_value(mgr, kSt11_1, false); cout << "Node#" << id() << " is const1" << endl; set_const(mgr, 1); } } else { ASSERT_COND( val == 1 ); } break; case kSt1X_X: if ( ipos == 0 ) { ASSERT_COND( val == 1 ); } else { if ( val == 0 ) { change_value(mgr, kSt10_0, false); cout << "Node#" << id() << " is const0" << endl; set_const(mgr, 0); } else { change_value(mgr, kSt11_1, false); cout << "Node#" << id() << " is const1" << endl; set_const(mgr, 1); } } break; case kStXX_0: if ( ipos == 0 ) { if ( val == 0 ) { change_value(mgr, kSt0X_0, false); } else { change_value(mgr, kSt10_0, false); } } else { if ( val == 0 ) { change_value(mgr, kStX0_0, false); } else { change_value(mgr, kSt01_0, false); } } break; case kStX0_0: if ( ipos == 0 ) { // どうでもいい } else { ASSERT_COND( val == 0 ); } break; case kSt0X_0: if ( ipos == 0 ) { ASSERT_COND( val == 0 ); } else { // どうでもいい } break; case kSt00_0: ASSERT_COND( val == 0 ); break; case kSt01_0: if ( ipos == 0 ) { ASSERT_COND( val == 0 ); } else { ASSERT_COND( val == 1 ); } break; case kSt10_0: if ( ipos == 0 ) { ASSERT_COND( val == 1 ); } else { ASSERT_COND( val == 0 ); } break; case kSt11_1: ASSERT_COND( val == 1 ); break; default: ASSERT_NOT_REACHED; break; } } END_NAMESPACE_YM_NETWORKS
/*************************************************************************** Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. 2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD FileName: QTSServerInterface.h Description: define an interface for getting and setting server-wide attributes, and storing global server resources. Comment: copy from Darwin Streaming Server 5.5.5 Author: taoyunxing@dadimedia.com Version: v1.0.0.1 CreateDate: 2010-08-16 LastUpdate: 2010-08-16 ****************************************************************************/ #ifndef __QTSSERVERINTERFACE_H__ #define __QTSSERVERINTERFACE_H__ #include "QTSS.h" #include "QTSSDictionary.h" #include "QTSServerPrefs.h" #include "QTSSMessages.h" #include "QTSSModule.h" #include "atomic.h" #include "OSMutex.h" #include "Task.h" #include "TCPListenerSocket.h" #include "ResizeableStringFormatter.h" class UDPSocketPool; class QTSServerPrefs; class QTSSMessages; class RTPSessionInterface; // This object also functions as our assert logger // This QTSSStream is used by modules to write to the error log class QTSSErrorLogStream : public QTSSStream, public AssertLogger { public: QTSSErrorLogStream() {} virtual ~QTSSErrorLogStream() {} virtual QTSS_Error Write(void* inBuffer, UInt32 inLen, UInt32* outLenWritten, UInt32 inFlags); virtual void LogAssert(char* inMessage); }; class QTSServerInterface : public QTSSDictionary { public: //Initialize must be called right off the bat to initialize dictionary resources static void Initialize(); // CONSTRUCTOR / DESTRUCTOR QTSServerInterface(); virtual ~QTSServerInterface() {} // STATISTICS MANIPULATION // These functions are how the server keeps its statistics current /* 更新当前RTSPSession的总个数 */ void AlterCurrentRTSPSessionCount(SInt32 inDifference) { OSMutexLocker locker(&fMutex); fNumRTSPSessions += inDifference; } void AlterCurrentRTSPHTTPSessionCount(SInt32 inDifference) { OSMutexLocker locker(&fMutex); fNumRTSPHTTPSessions += inDifference; } void SwapFromRTSPToHTTP() { OSMutexLocker locker(&fMutex); fNumRTSPSessions--; fNumRTSPHTTPSessions++; } //total rtp bytes sent by the server void IncrementTotalRTPBytes(UInt32 bytes) { (void)atomic_add(&fPeriodicRTPBytes, bytes); } //total rtp packets sent by the server void IncrementTotalPackets() { (void)atomic_add(&fPeriodicRTPPackets, 1); } //total rtp bytes reported as lost by the clients void IncrementTotalRTPPacketsLost(UInt32 packets) { (void)atomic_add(&fPeriodicRTPPacketsLost, packets); } // Also increments current RTP session count /* used in RTPSession::Activate() */ void IncrementTotalRTPSessions() { OSMutexLocker locker(&fMutex); fNumRTPSessions++; fTotalRTPSessions++; } void AlterCurrentRTPSessionCount(SInt32 inDifference) { OSMutexLocker locker(&fMutex); fNumRTPSessions += inDifference; } //track how many sessions are playing /* used by RTPSession::Play() */ void AlterRTPPlayingSessions(SInt32 inDifference) { OSMutexLocker locker(&fMutex); fNumRTPPlayingSessions += inDifference; } /* 增加总延迟 */ void IncrementTotalLate(SInt64 milliseconds) { OSMutexLocker locker(&fMutex); fTotalLate += milliseconds; if (milliseconds > fCurrentMaxLate) fCurrentMaxLate = milliseconds; if (milliseconds > fMaxLate) fMaxLate = milliseconds; } /* 增加总qualitylevel */ void IncrementTotalQuality(SInt32 level) { OSMutexLocker locker(&fMutex); fTotalQuality += level; } /* 增加打薄数(thinning) */ void IncrementNumThinned(SInt32 inDifference) { OSMutexLocker locker(&fMutex); fNumThinned += inDifference; } // clear void ClearTotalLate() { OSMutexLocker locker(&fMutex); fTotalLate = 0; } void ClearCurrentMaxLate() { OSMutexLocker locker(&fMutex); fCurrentMaxLate = 0; } void ClearTotalQuality() { OSMutexLocker locker(&fMutex); fTotalQuality = 0; } // ACCESSORS QTSS_ServerState GetServerState() { return fServerState; } UInt32 GetNumRTPSessions() { return fNumRTPSessions; } UInt32 GetNumRTSPSessions() { return fNumRTSPSessions; } UInt32 GetNumRTSPHTTPSessions(){ return fNumRTSPHTTPSessions; } UInt32 GetTotalRTPSessions() { return fTotalRTPSessions; } UInt32 GetNumRTPPlayingSessions() { return fNumRTPPlayingSessions; } UInt32 GetCurBandwidthInBits() { return fCurrentRTPBandwidthInBits; } UInt32 GetAvgBandwidthInBits() { return fAvgRTPBandwidthInBits; } UInt32 GetRTPPacketsPerSec() { return fRTPPacketsPerSecond; } UInt64 GetTotalRTPBytes() { return fTotalRTPBytes; } UInt64 GetTotalRTPPacketsLost(){ return fTotalRTPPacketsLost; } UInt64 GetTotalRTPPackets() { return fTotalRTPPackets; } Float32 GetCPUPercent() { return fCPUPercent; } Bool16 SigIntSet() { return fSigInt; } Bool16 SigTermSet() { return fSigTerm; } UInt32 GetNumMP3Sessions() { return fNumMP3Sessions; } UInt32 GetTotalMP3Sessions() { return fTotalMP3Sessions; } UInt64 GetTotalMP3Bytes() { return fTotalMP3Bytes; } //得到/设置服务器Debug信息 UInt32 GetDebugLevel() { return fDebugLevel; } UInt32 GetDebugOptions() { return fDebugOptions; } void SetDebugLevel(UInt32 debugLevel) { fDebugLevel = debugLevel; } void SetDebugOptions(UInt32 debugOptions){ fDebugOptions = debugOptions; } SInt64 GetMaxLate() { return fMaxLate; }; SInt64 GetTotalLate() { return fTotalLate; }; SInt64 GetCurrentMaxLate() { return fCurrentMaxLate; }; SInt64 GetTotalQuality() { return fTotalQuality; }; SInt32 GetNumThinned() { return fNumThinned; }; // GLOBAL OBJECTS REPOSITORY(全局对象库) // This object is in fact global, so there is an accessor for it as well. /* 注意下面这几个都非常重要 */ /* needed by RTPSession::run()/Play() */ /* 获得唯一的Server接口指针,这个非常重要!! */ static QTSServerInterface* GetServer() { return sServer; } QTSServerPrefs* GetPrefs() { return fSrvrPrefs; } QTSSMessages* GetMessages() { return fSrvrMessages; } //Allows you to map RTP session IDs (strings) to actual RTP session objects OSRefTable* GetRTPSessionMap() { return fRTPMap; } //Server provides a statically created & bound UDPSocket / Demuxer pair //for each IP address setup to serve RTP. You access those pairs through //this function. This returns a pair pre-bound to the IPAddr specified. /* 得到UDPSocketPool指针 */ UDPSocketPool* GetSocketPool() { return fSocketPool; } // SERVER NAME & VERSION static StrPtrLen& GetServerName() { return sServerNameStr; } static StrPtrLen& GetServerVersion() { return sServerVersionStr; } static StrPtrLen& GetServerPlatform() { return sServerPlatformStr; } static StrPtrLen& GetServerBuildDate() { return sServerBuildDateStr; } static StrPtrLen& GetServerHeader() { return sServerHeaderPtr; } static StrPtrLen& GetServerBuild() { return sServerBuildStr; } static StrPtrLen& GetServerComment() { return sServerCommentStr; } // PUBLIC HEADER static StrPtrLen* GetPublicHeader() { return &sPublicHeaderStr; } // KILL ALL void KillAllRTPSessions(); // SIGINT - to interrupt the server, set this flag and the server will shut down, SigInt - Signal Interrupt void SetSigInt() { fSigInt = true; } // SIGTERM - to kill(terminate) the server, set this flag and the server will shut down, SigTerm - Signal Terminate void SetSigTerm() { fSigTerm = true; } // MODULE STORAGE // All module objects are stored here, and are accessable through these routines. // Returns the number of modules that act in a given role /* needed by RTPSession::run(),得到注册指定Role的Module数目 */ static UInt32 GetNumModulesInRole(QTSSModule::RoleIndex inRole) { Assert(inRole < QTSSModule::kNumRoles); return sNumModulesInRole[inRole]; } // Allows the caller to iterate over all modules that act in a given role /* needed by RTPSession::run(),得到ModuleArray数组中指定Role的二维指针数组中指定索引的元素(是个 QTSSModule*) */ static QTSSModule* GetModule(QTSSModule::RoleIndex inRole, UInt32 inIndex) { Assert(inRole < QTSSModule::kNumRoles); Assert(inIndex < sNumModulesInRole[inRole]); return sModuleArray[inRole][inIndex]; } // 调用模块用入参设置服务器新状态 // We need to override this. This is how we implement the QTSS_StateChange_Role virtual void SetValueComplete(UInt32 inAttrIndex, QTSSDictionaryMap* inMap,UInt32 inValueIndex, void* inNewValue, UInt32 inNewValueLen); // ERROR LOGGING // Invokes the error logging modules with some data static void LogError(QTSS_ErrorVerbosity inVerbosity, char* inBuffer); // Returns the error log stream static QTSSErrorLogStream* GetErrorLogStream() { return &sErrorLogStream; } // LOCKING DOWN THE SERVER OBJECT OSMutex* GetServerObjectMutex() { return &fMutex; } protected: // Setup by the derived RTSPServer object,下面的数据成员和成员函被派生子类RTSPServer类型的QTSServer所创建 //Sockets are allocated global to the server, and arbitrated through this pool here. //RTCP data is processed completely within the following task. /* TCP/UDP Socket在服务器内部被全局分配,RTCPTask与UDP Socket上的RTCP数据处理紧密相连 */ UDPSocketPool* fSocketPool; // Array of pointers to TCPListenerSockets.侦听Socket数组,注意这两个值的设置在QTSServer::CreateListeners()中定义 TCPListenerSocket** fListeners;/* 指向指针数组的指针 */ UInt32 fNumListeners; // Number of elements in the array UInt32 fDefaultIPAddr; //默认绑定的IP地址,它是预设的IP地址数组的第一个分量,参见QTSServer::SetDefaultIPAddr() // All RTP sessions are put into this map /* 所有的RTP Session组成一个Hash Table,名为RTPSessionMap,该表中每个表元都有一个随机的唯一的Session ID */ OSRefTable* fRTPMap; // Server prefers,服务器预设值对象 QTSServerPrefs* fSrvrPrefs; QTSSMessages* fSrvrMessages; // Stub Server prefers(RTSP/RTP Server etc),存根服务器预设值对象 QTSServerPrefs* fStubSrvrPrefs; QTSSMessages* fStubSrvrMessages; //Server state and IP addr QTSS_ServerState fServerState;/* QTSS.h中定义了6种服务器状态信息 */ // startup time SInt64 fStartupTime_UnixMilli;//服务器启动的时间 SInt32 fGMTOffset; //本地时区与GMT时间的偏移小时数 /* 对服务器使用的RTSP方法作统计,并给出一个字符串,见QTSServer::SetupPublicHeader() */ static ResizeableStringFormatter sPublicHeaderFormatter; static StrPtrLen sPublicHeaderStr; // MODULE DATA /* 每个role对应的module指针的指针,QTSSModule**,作为分量组成的数组,参见QTSServer::BuildModuleRoleArrays() */ static QTSSModule** sModuleArray[QTSSModule::kNumRoles];//24 /* 每个role所关联的module数目为分量组成的数组 */ static UInt32 sNumModulesInRole[QTSSModule::kNumRoles]; /* 由module组成的队列,务必要读懂OSQueue.h/cpp */ static OSQueue sModuleQueue;/* used in QTSServer::AddModule() */ static QTSSErrorLogStream sErrorLogStream;/* 处理module过程的错误日志流 */ private: enum { kMaxServerHeaderLen = 1000 }; static void* TimeConnected(QTSSDictionary* inConnection, UInt32* outLen); static UInt32 sServerAPIVersion; //0x00040000 static StrPtrLen sServerNameStr; //"DSS" static StrPtrLen sServerVersionStr; //"5.5.1" static StrPtrLen sServerBuildStr; //"489.8" static StrPtrLen sServerCommentStr; //"Release/Darwin; " static StrPtrLen sServerPlatformStr; //"Linux" static StrPtrLen sServerBuildDateStr;//__DATE__ ", "__TIME__ static char sServerHeader[kMaxServerHeaderLen]; //1000个字节的字符数组 static StrPtrLen sServerHeaderPtr; //"Server: DSS/5.5.3.7 (Build/489.8; Platform/Linux; Release/Darwin; )" OSMutex fMutex; //num of current RTSP/HTTP/RTP Session UInt32 fNumRTSPSessions; UInt32 fNumRTSPHTTPSessions; UInt32 fNumRTPSessions; //当前RTPSession数目 //stores the current number of playing connections. UInt32 fNumRTPPlayingSessions; //下面几个是累计属性 //stores the total number of connections since startup.自服务器启动至今,总的RTPSession数目 UInt32 fTotalRTPSessions; //stores the total number of bytes served since startup UInt64 fTotalRTPBytes; //total number of rtp packets sent since startup UInt64 fTotalRTPPackets; //stores the total number of bytes lost (as reported by clients) since startup UInt64 fTotalRTPPacketsLost; //because there is no 64 bit atomic add (for obvious reasons), we efficiently //implement total byte counting by atomic adding to this variable, then every //once in a while updating the sTotalBytes. /* for calculate the above global quantities using theses temp variable,参见RTPStatsUpdaterTask::Run() */ unsigned int fPeriodicRTPBytes; unsigned int fPeriodicRTPPacketsLost; unsigned int fPeriodicRTPPackets; //stores the current served bandwidth in BITS per second UInt32 fCurrentRTPBandwidthInBits; UInt32 fAvgRTPBandwidthInBits; UInt32 fRTPPacketsPerSecond; // CPU Float32 fCPUPercent; Float32 fCPUTimeUsedInSec; /************** 下面这几个用Param retrieval functions在服务器字典中设置 *********************/ // stores # of UDP sockets in the server currently (gets updated lazily via.param retrieval function) // 服务器当前的UDP Socket总数,它是RTP/RTCP Socket pair队列长度的2倍 UInt32 fTotalUDPSockets; // are we out of descriptors? 文件描述符用光了吗? Bool16 fIsOutOfDescriptors; // Storage for current time attribute,服务器的当前操作系统时间的Unix时间(ms) SInt64 fCurrentTime_UnixMilli; // Stats for UDP retransmits UInt32 fUDPWastageInBytes; /* 累计缓存池OSBufferPool中未使用的缓存字节总数 */ UInt32 fNumUDPBuffers; /* 缓存池OSBufferPool中定长缓存的当前个数 */ /************** 上面这几个用Param retrieval functions在服务器字典中设置 ********************/ // MP3 Client Session params UInt32 fNumMP3Sessions; UInt32 fTotalMP3Sessions; UInt32 fCurrentMP3BandwidthInBits; UInt64 fTotalMP3Bytes; UInt32 fAvgMP3BandwidthInBits; //interrupt server signals Bool16 fSigInt; /* Signal Interrupt server? */ Bool16 fSigTerm;/* Signal Terminate server? */ //Debug params level/options UInt32 fDebugLevel; /* debug 级别 */ UInt32 fDebugOptions;/* debug 选项 */ //late SInt64 fMaxLate; SInt64 fTotalLate; SInt64 fCurrentMaxLate; SInt64 fTotalQuality; SInt32 fNumThinned; //总薄化次数 // Param retrieval functions for ServerDict, see QTSServerInterface::sAttributes[]赋值 static void* CurrentUnixTimeMilli(QTSSDictionary* inServer, UInt32* outLen); static void* GetTotalUDPSockets(QTSSDictionary* inServer, UInt32* outLen); static void* IsOutOfDescriptors(QTSSDictionary* inServer, UInt32* outLen); static void* GetNumUDPBuffers(QTSSDictionary* inServer, UInt32* outLen); static void* GetNumWastedBytes(QTSSDictionary* inServer, UInt32* outLen); /* 重要的三个静态参数: */ static QTSServerInterface* sServer; /* 指向QTSServerInterface类的指针,注意这种用法很奇特,needed by RTPSession::run() */ static QTSSAttrInfoDict::AttrInfo sAttributes[];/* 服务器的属性 */ static QTSSAttrInfoDict::AttrInfo sConnectedUserAttributes[];/* 服务器的ConnectedUser属性 */ friend class RTPStatsUpdaterTask;/* def see below */ friend class SessionTimeoutTask; }; /* 实时更新RTPSession状态的Task类 */ class RTPStatsUpdaterTask : public Task { public: // This class runs periodically(配置值为1s) to compute current totals & averages RTPStatsUpdaterTask(); virtual ~RTPStatsUpdaterTask() {} private: /* 这是主函数,会调用其他两个函数 */ virtual SInt64 Run(); RTPSessionInterface* GetNewestSession(OSRefTable* inRTPSessionMap); Float32 GetCPUTimeInSeconds(); /* 计算上次带宽的时间 */ SInt64 fLastBandwidthTime; /* 上次计算平均带宽的时间 */ SInt64 fLastBandwidthAvg; /* 上次发出的RTP包字节总数 */ SInt64 fLastBytesSent; /* 上次发出的MP3总字节数 */ SInt64 fLastTotalMP3Bytes; }; #endif // __QTSSERVERINTERFACE_H__
/*********************************************************************** created: Sat Dec 26 2009 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #ifndef _CEGUIRenderEffectFactory_h_ #define _CEGUIRenderEffectFactory_h_ #include "CEGUI/RenderEffect.h" // Start of CEGUI namespace section namespace CEGUI { /*! \brief Interface for factory objects that create RenderEffect instances. Currently this interface is intended for internal use only. */ class RenderEffectFactory { public: //! base class virtual destructor. virtual ~RenderEffectFactory() {} //! Create an instance of the RenderEffect that this factory creates. virtual RenderEffect& create(Window* window) = 0; //! Destroy an instance of the RenderEffect that this factory creates. virtual void destroy(RenderEffect& effect) = 0; }; //! Templatised RenderEffectFactory subclass used internally by the system. template <typename T> class TplRenderEffectFactory : public RenderEffectFactory { public: // Implement RenderEffectFactory interface RenderEffect& create(Window* window) override; void destroy(RenderEffect& effect) override; }; //---------------------------------------------------------------------------// template <typename T> RenderEffect& TplRenderEffectFactory<T>::create(Window* window) { return *new T(window); } //---------------------------------------------------------------------------// template <typename T> void TplRenderEffectFactory<T>::destroy(RenderEffect& effect) { delete &effect; } //---------------------------------------------------------------------------// } // End of CEGUI namespace section #endif // end of guard _CEGUIRenderEffectFactory_h_
#include <cstdio> #include <cstdlib> #include <string.h> #include "gkfn.h" #define SELET 1 #define SPOTS 25 #define MAX_BUF 1024 #define DATAS 17520 #define DAYS 730 #define VER1 0 #define VER2 1 #if VER2 #define DAY 1 #define HOUR 0 #endif #if 0 #define TRATE_MIN 0.7f #define TRATE_MAX 0.9f #define TAU_MIN 3 #define TAU_MAX 7 #define E_MIN 9 #define E_MAX 11 #define T_RATE_MIN 0.4f #define T_RATE_MAX 0.7f #define NOK_MIN 6 #define NOK_MAX 10 #endif double *ts; void calSmoothnessMeasure(int num, double threshold, int n, double* ts, int M, int &rE, int &rTau); GKFN* predictSeries(int n, double *ts, int E, int Tau, int PredictionStep, double TrainingRate, int NumberOfKernels, int Epochs, int aq, char *spot); #if VER1 int extract_data(char *spot_name, int ele); int interpolation(char *file); #endif #if VER2 int interpolation(double *data); bool daily_avg(double *data, double *data_days); #endif bool dispose_mem(); double atod(char *str); void rtrim(char *str); double get_intpol(int d1, int d2, double x1, double x2); int TAU_MIN = 1; int TAU_MAX = 10; int E_MIN = 1; int E_MAX = 12; double T_RATE_MIN = 0.4; double T_RATE_MAX = 0.6; int NOK_MIN = 3; int NOK_MAX = 10; #if VER2 double **data; double **data_days; #endif int main() { int i, j, n; int E, Tau, nok; char fname[50]; #if VER1 char data[20]; #endif int year; GKFN *model; FILE *fi, *fo, *foo; #if VER1 ts = (double*)malloc(sizeof(double) * 20000); #endif double avg; char spot[SPOTS][20] = { "강남구", "강동구", "강북구", "강서구", "관악구", "광진구", "구로구", "금천구", "노원구", "도봉구", "동대문구", "동작구", "마포구", "서대문구", "서초구", "성동구", "성북구", "송파구", "양천구", "영등포구", "용산구", "은평구", "종로구", "중구", "중랑구" }; double rsq_max[39][4]; int mode, all; int ele = 1; int ele_max; /* 1 : SO2 2 : CO 3 : O3 4 : NO2 5 : PM10 6 : PM2.5 */ #if VER1 printf("!1 : All spots, 1 : select spot\n"); scanf("%d", &all); if (all == 1) { printf("Select spot\n"); scanf("%s", data); } printf("Select element\n"); printf("1 : SO2\n" "2 : CO\n" "3 : O3\n" "4 : NO2\n" "5 : PM10\n" "6 : All of these\n"); scanf("%d", &ele); printf("!1 : Preset, 1 : Range setting \n"); scanf("%d", &mode); if (mode == 1) { printf("Training rate min(0.1~0.9) : "); scanf("%lf", &T_RATE_MIN); printf("Training rate max(0.1~0.9) : "); scanf("%lf", &T_RATE_MAX); if (T_RATE_MAX < T_RATE_MIN) { printf("MAX value should be bigger then MIN value\n"); free(ts); return 0; } printf("Tau min : "); scanf("%d", &TAU_MIN); printf("Tau max : "); scanf("%d", &TAU_MAX); if (TAU_MAX < TAU_MIN) { printf("MAX value should be bigger then MIN value\n"); free(ts); return 0; } printf("Embedding dimension min : "); scanf("%d", &E_MIN); printf("Embedding dimension max : "); scanf("%d", &E_MAX); if (E_MAX < E_MIN) { printf("MAX value should be bigger then MIN value\n"); free(ts); return 0; } printf("Number of Kernals min : "); scanf("%d", &NOK_MIN); printf("Number of Kernals max : "); scanf("%d", &NOK_MAX); if (NOK_MAX < NOK_MIN) { printf("MAX value should be bigger then MIN value\n"); free(ts); return 0; } } if (ele != 6) { i = ele; ele_max = ele; } else { i = 1; ele = 1; ele_max = 5; } for (i; i <= ele_max; i++) { for (int spot_index = 0; spot_index < 39; spot_index++) { if (all == 1) { spot_index = 100; } else { strcpy(data, spot[spot_index]); rsq_max[spot_index][0] = 0; } extract_data(data, i); sprintf(fname, "data/%s_%d.csv", data, i); fi = fopen(fname, "r"); avg = 0.f; for (j = 1; fscanf(fi, "%lf", &ts[j]) == 1; ++j) avg += ts[j]; fclose(fi); n = j - 1; avg /= n; calSmoothnessMeasure(i, 0.5f, n, ts, 1, E, Tau); sprintf(fname, "result/%s_%d.csv", data, i); fo = fopen(fname, "w"); fprintf(fo, "E,Tau,Trate,nok,TrainRsq,TestRsq,TrainRmse,TestRmse\n"); printf("E\tTau\tTrate\tnok\tTrainRsq\tTestRsq\t\tTrainRmse\tTestRmse\n"); for (double trate = T_RATE_MIN; trate <= T_RATE_MAX; trate += 0.1) { for (nok = NOK_MIN; nok <= NOK_MAX; nok++) { double trrsq, trrmse, tersq, termse, ytrue, yest; model = predictSeries(n, ts, E, Tau, 1, trate, nok, 5, i); trrsq = model->getTrainRsquared(); tersq = model->getTestRsquared(); trrmse = model->getTrainRMSE(); termse = model->getTestRMSE(); // 이거 if (isnan(trrsq) || isnan(tersq) || isnan(trrmse) || isnan(termse)) { delete model; break; } fprintf(fo, "%d,%d,%.1lf,%d,%lf,%lf,%lf,%lf\n", E, Tau, trate, nok, trrsq, tersq, trrmse, termse); printf("%d\t%d\t%.1lf\t%d\t%lf\t%lf\t%lf\t%lf\n", E, Tau, trate, nok, trrsq, tersq, trrmse, termse); if (all != 1) { if (rsq_max[spot_index][0] < tersq) { rsq_max[spot_index][0] = tersq; rsq_max[spot_index][1] = E; rsq_max[spot_index][2] = Tau; rsq_max[spot_index][3] = nok; } } delete model; } } fclose(fo); } if (all != 1) { sprintf(fname, "result/서울전체_%d.csv", i); foo = fopen(fname, "w"); fprintf(foo, "측정소,E,Tau,NoK,TrainRsq\n"); for (int ii = 0; i < 39; ii++) { fprintf(foo, "%s,", spot[ii]); fprintf(foo, "%f,", rsq_max[ii][1]); fprintf(foo, "%f,", rsq_max[ii][2]); fprintf(foo, "%f,", rsq_max[ii][3]); fprintf(foo, "%lf\n", rsq_max[ii][0]); } fclose(foo); } } free(ts); #endif #if VER2 char buf[500]; char *token; data = (double **)malloc(sizeof(double*) * SPOTS); for (int i = 0; i < SPOTS; i++) { data[i] = (double *)malloc(sizeof(double) * DATAS); } #if DAY data_days = (double **)malloc(sizeof(double*) * SPOTS); for (int i = 0; i < SPOTS; i++) { data_days[i] = (double *)malloc(sizeof(double) * DAYS); } #endif for (int ele = 1; ele <= 5; ele++) { i = 0; j = 0; sprintf(fname, "data/%d.csv", ele); fi = fopen(fname, "r"); if (fi == NULL) { printf("[ERROR] file open error"); dispose_mem(); return 0; } while (fgets(buf, MAX_BUF, fi) != NULL) { rtrim(buf); token = strtok(buf, ","); while (token != NULL) { data[i][j] = atod(token); token = strtok(NULL, ","); i++; } j++; i = 0; } for (i = 0; i < SPOTS; i++) interpolation(data[i]); #if DAY for (i = 0; i < SPOTS; i++) daily_avg(data[i], data_days[i]); #endif for (i = 0; i < SPOTS; i++) { #if DAY calSmoothnessMeasure(ele, 0.5f, DAYS, data_days[i], 1, E, Tau); sprintf(fname, "result/%s_%d.csv", spot[i], ele); fo = fopen(fname, "w"); fprintf(fo, "E,Tau,Trate,nok,TrainRsq,TestRsq,TrainRmse,TestRmse\n"); printf("E\tTau\tTrate\tnok\tTrainRsq\tTestRsq\t\tTrainRmse\tTestRmse\n"); for (double trate = T_RATE_MIN; trate <= T_RATE_MAX; trate += 0.1) { for (nok = NOK_MIN; nok <= NOK_MAX; nok++) { double trrsq, trrmse, tersq, termse, ytrue, yest; model = predictSeries(DAYS, data_days[i], E, Tau, 1, trate, nok, 5, ele, spot[i]); trrsq = model->getTrainRsquared(); tersq = model->getTestRsquared(); trrmse = model->getTrainRMSE(); termse = model->getTestRMSE(); // 이거 if (isnan(trrsq) || isnan(tersq) || isnan(trrmse) || isnan(termse)) { delete model; break; } fprintf(fo, "%d,%d,%.1lf,%d,%lf,%lf,%lf,%lf\n", E, Tau, trate, nok, trrsq, tersq, trrmse, termse); printf("%d\t%d\t%.1lf\t%d\t%lf\t%lf\t%lf\t%lf\n", E, Tau, trate, nok, trrsq, tersq, trrmse, termse); delete model; } } #else calSmoothnessMeasure(ele, 0.5f, DATAS, data[i], 1, E, Tau); sprintf(fname, "result/%s_%d.csv", spot[i], ele); fo = fopen(fname, "w"); fprintf(fo, "E,Tau,Trate,nok,TrainRsq,TestRsq,TrainRmse,TestRmse\n"); printf("E\tTau\tTrate\tnok\tTrainRsq\tTestRsq\t\tTrainRmse\tTestRmse\n"); for (double trate = T_RATE_MIN; trate <= T_RATE_MAX; trate += 0.1) { for (nok = NOK_MIN; nok <= NOK_MAX; nok++) { double trrsq, trrmse, tersq, termse, ytrue, yest; model = predictSeries(DATAS, data[i], E, Tau, 1, trate, nok, 5, i); trrsq = model->getTrainRsquared(); tersq = model->getTestRsquared(); trrmse = model->getTrainRMSE(); termse = model->getTestRMSE(); // 이거 if (isnan(trrsq) || isnan(tersq) || isnan(trrmse) || isnan(termse)) { delete model; break; } fprintf(fo, "%d,%d,%.1lf,%d,%lf,%lf,%lf,%lf\n", E, Tau, trate, nok, trrsq, tersq, trrmse, termse); printf("%d\t%d\t%.1lf\t%d\t%lf\t%lf\t%lf\t%lf\n", E, Tau, trate, nok, trrsq, tersq, trrmse, termse); delete model; } } #endif fclose(fo); } fclose(fi); } dispose_mem(); #endif return 0; } #if VER2 bool daily_avg(double *data, double *data_days) { int j = 0; double temp = 0.; for (int i = 0; i < DATAS; i++) { temp += data[i]; if ((i + 1) % 24 == 23) { data_days[j] = (temp / 24); j++; temp = 0.; } } return true; } bool dispose_mem() { for (int i = 0; i < SPOTS; i++) { free(data[i]); } free(data); return true; } void rtrim(char *str) { int len = strlen(str); len--; while (str[len] == '\n' || str[len] == ' ') { str[len] = '\0'; len--; } } double atod(char *str) { int len = strlen(str); int i; double ret_val = 0., pos = 1.; int f = 0; if (str[0] == '-') return 0.; for (i = 0; i < len; i++) { if (str[i] == '.') { f = i; } else { if (f == 0) { ret_val *= 10.; ret_val += str[i] - 48; } else { ret_val += (str[i] - 48) * pow(0.1, (i - f)); } } } return pos * ret_val; } #endif #if VER1 int extract_data(char *spot_name, int ele) { FILE *fi, *fo; char foname[50]; char fname[50]; char buf[500]; char *token; bool flag; sprintf(foname, "data/%s_%d.csv", spot_name, ele); fo = fopen(foname, "w"); for (int year = 2014; year <= 2015; year++) { for (int i = 1; i <= 4; i++) { sprintf(fname, "data/%d/%d년%d분기.csv", year, year, i); fi = fopen(fname, "r"); fgets(buf, 500, fi); while (fgets(buf, 500, fi) != NULL) { flag = true; token = strtok(buf, ","); for (int j = 1; j <= 9; j++) { token = strtok(NULL, ","); if (j == 1) { if (strcmp(token, spot_name) != 0) { flag = false; break; } } else { if (j - 2 < ele) { continue; } else if (j - 2 == ele) { if (strcmp(token, "-999") == 0) fprintf(fo, "0\n"); else fprintf(fo, "%s\n", token); } else { break; } } } } fclose(fi); } } fclose(fo); interpolation(foname); return 1; } int interpolation(char *file) { FILE *fp; int i, j, k; int x2; int data_cnt; int cnt = 0; double data[20000]; cnt = 0; printf("Adjusting '%s'\n\n", file); fp = fopen(file, "r"); if (fp == NULL) { printf("[ERROR] Can't open file\n"); return 0; } for (j = 0; fscanf(fp, "%lf", &data[j]) == 1; j++); data_cnt = j; printf("%d data read\n", data_cnt); fclose(fp); for (j = 0; j < data_cnt; j++) { if (data[j] == 0) { k = j; while (data[k] == 0) k++; x2 = k; k--; for (k; k >= j; k--) { data[k] = get_intpol(k - j + 1, x2 - k, data[j - 1], data[x2]); cnt++; } j = x2 - 1; } } printf("%d changed\n", cnt); fp = fopen(file, "w"); for (j = 0; j < data_cnt; j++) { fprintf(fp, "%lf\n", data[j]); } fclose(fp); return 1; } #endif #if VER2 int interpolation(double *data) { int i, j, k; int x2; int data_cnt; int cnt = 0; for (j = 0; j < DATAS; j++) { if (data[j] == 0.) { k = j; while (data[k] == 0.) k++; x2 = k; k--; for (k; k >= j; k--) { data[k] = get_intpol(k - j + 1, x2 - k, data[j - 1], data[x2]); cnt++; } j = x2 - 1; } } //printf("%d changed\n", cnt); return 1; } #endif double get_intpol(int d1, int d2, double x1, double x2) { return ((d2*x1) / (d1 + d2)) + ((d1*x2) / (d1 + d2)); } GKFN* predictSeries(int n, double *ts, int E, int Tau, int PredictionStep, double TrainingRate, int NumberOfKernels, int Epochs, int aq, char *spot) { GKFN *model; model = new GKFN(n, ts, E, Tau, PredictionStep, TrainingRate, aq, spot); model->learn(NumberOfKernels, Epochs); return model; } void calSmoothnessMeasure(int num, double threshold, int n, double* ts, int M, int &rE, int &rTau) { int i, j, k; FILE *ifp; char ch, fname[20]; int E, Tau, Ns; double **x, *y; int l; double dist, mdist; double sm, msm; int mE = 0, mTau; rTau = 0; sprintf(fname, "sm/sm_%d.csv", num); ifp = fopen(fname, "w"); fprintf(ifp, "E,Tau,Smoothness\n"); for (E = E_MIN; E <= E_MAX; E++) { for (Tau = TAU_MIN; Tau <= TAU_MAX; Tau++) { sm = 0.f; Ns = n - (E - 1) * Tau - 1; if (Ns < 100) continue; x = (double**)calloc(Ns+1, sizeof(double*)); y = (double*)calloc(Ns+1, sizeof(double)); k = 1 + (E - 1) * Tau; for (i = 1; i <= Ns; i++) { x[i] = (double*)calloc(E, sizeof(double)); y[i] = ts[k + M]; for (j = 0; j < E; j++) { x[i][j] = ts[k - j * Tau]; } k++; } for (i = 1; i <= Ns; i++) { mdist = -1.f; for (j = 1; j <= Ns; j++) { if (i == j) continue; dist = 0.f; for (k = 0; k < E; k++) dist += (x[i][k] - x[j][k])*(x[i][k] - x[j][k]); if (dist != 0.f && (mdist == -1.f || mdist > dist)) { mdist = dist; l = j; } } sm += abs(y[i] - y[l]) / sqrt(mdist); } sm = 1.f - sm / Ns; fprintf(ifp, "%d,%d,%lf\n", E, Tau, sm); printf( "%d,%d,%lf\n", E, Tau, sm); for (i = 1; i <= Ns; i++) free(x[i]); free(x); free(y); if (rTau == 0 && sm > threshold) { rE = E; rTau = Tau; printf("%d,%d,%lf\n", E, Tau, sm); return; } if (mE == 0 || msm < sm) { msm = sm; mE = E; mTau = Tau; } } } rE = mE; rTau = mTau; printf("%d,%d,%lf\n", mE, mTau, msm); fclose(ifp); }
#include<Keypad.h> const byte ROWS = 4; const byte COLS = 4; char keys[ROWS][COLS] = {{'F', 'B', '7', '3'}, {'E', 'A', '6', '2'}, {'D', '9', '5', '1'}, {'C', '8', '4', '0'}}; byte rowPins[ROWS] = {8,9,10,11}; byte colPins[COLS] = {12,13,14,15}; Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); void setup() { Serial.begin(9600); } void loop() { char key = keypad.getKey(); if (key != NO_KEY) { Serial.println(key); } }
#include <iostream> #include <tuple> #include <vector> using namespace std; // ----- ReadGraph ----- // Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7016619 struct Edge { int src, dst, id; // ll cost; Edge() {} Edge(int src, int dst, int id) : src{src}, dst{dst}, id{id} {} // Edge(int src, int dst, ll cost) : src{src}, dst{dst}, cost{cost} {} void added_edge(vector<vector<Edge>> &V) { V[src].push_back(*this); } void added_rev(vector<vector<Edge>> &V) { V[dst].push_back(rev()); } Edge rev() { Edge edge{*this}; swap(edge.src, edge.dst); return edge; } }; tuple<vector<vector<Edge>>, vector<Edge>> ReadGraphWithEdges(int N, int M, bool is_undirected = true, bool is_one_indexed = true) { vector<vector<Edge>> V(N); vector<Edge> E(M); for (auto i = 0; i < M; ++i) { int v, w; cin >> v >> w; if (is_one_indexed) { --v; --w; } Edge edge{v, w, i}; edge.added_edge(V); if (is_undirected) { edge.added_rev(V); } E.push_back(edge); } return make_tuple(V, E); } vector<vector<Edge>> ReadGraph(int N, int M, bool is_undirected = true, bool is_one_indexed = true) { return get<0>(ReadGraphWithEdges(N, M, is_undirected, is_one_indexed)); } tuple<vector<vector<Edge>>, vector<Edge>> ReadTreeWithEdges(int N) { return ReadGraphWithEdges(N, N - 1); } vector<vector<Edge>> ReadTree(int N) { return ReadGraph(N, N - 1); }
#include "cskin.h" #include "base/style_box.h" #define SET_STYLEBOX( m_which , m_style )\ set_stylebox_name(m_which,#m_which);\ set_stylebox(m_which,m_style); #define SET_CONSTANT( m_which , m_constant )\ set_constant_name(m_which,#m_which);\ set_constant(m_which,m_constant); #define SET_FONT( m_which , m_font )\ set_font_name(m_which,#m_which);\ set_font(m_which,m_font); #define SET_BITMAP( m_which , m_bitmap )\ set_bitmap_name(m_which,#m_which);\ set_bitmap(m_which,m_bitmap); #define SET_COLOR( m_which , m_color )\ set_color_name(m_which,#m_which);\ set_color(m_which,m_color); void CSkin::set_default_extra() { /* PAttern Editor */ StyleBox sbaux=StyleBox(1,Color(0),Color(255,50,50),Color(255,50,50),false); sbaux.draw_center=false; SET_STYLEBOX(SB_PATTERN_EDITOR_CURSOR,sbaux); SET_COLOR(COLOR_PATTERN_EDITOR_BG,Color(255)); SET_COLOR(COLOR_PATTERN_EDITOR_ROW_BAR,Color(0)); SET_COLOR(COLOR_PATTERN_EDITOR_ROW_BEAT,Color(20)); SET_COLOR(COLOR_PATTERN_EDITOR_ROW_SUB_BEAT,Color(80)); SET_COLOR(COLOR_PATTERN_EDITOR_NOTE,Color(110,110,255)); SET_COLOR(COLOR_PATTERN_EDITOR_NOTE_NOFIT,Color(200,200,255)); SET_COLOR(COLOR_PATTERN_EDITOR_NOTE_SELECTED,Color(255,255,255)); SET_COLOR(COLOR_PATTERN_EDITOR_HL_BAR,Color(200,200,255)); SET_COLOR(COLOR_PATTERN_EDITOR_HL_BEAT,Color(230,230,255)); SET_COLOR(COLOR_PATTERN_EDITOR_TRACK_SEPARATOR,Color(150,150,150)); SET_COLOR(COLOR_PATTERN_EDITOR_ROW_SEPARATOR,Color(0,0,0)); SET_COLOR(COLOR_PATTERN_EDITOR_TRACK_NAME,Color(180,180,255)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_NAME,Color(220,220,140)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_VALUE,Color(155,155,32)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_VALUE_NOFIT,Color(190,190,60)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_VALUE_SELECTED,Color(255,255,255)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_HL_BEAT,Color(255,255,170)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_HL_BAR,Color(231,231,110)); SET_COLOR(COLOR_PATTERN_EDITOR_AUTOMATION_POINT,Color(255,50,0)); SET_COLOR(COLOR_PATTERN_EDITOR_CURSOR,Color(255,40,40)); SET_CONSTANT(C_PATTERN_EDITOR_COLUMN_SEPARATION,5); SET_CONSTANT(C_PATTERN_EDITOR_ROW_SEPARATION,1); SET_CONSTANT(C_PATTERN_EDITOR_TRACK_SEPARATION,8); SET_FONT(FONT_PATTERN_EDITOR,0); SET_FONT(FONT_PATTERN_EDITOR_TOP,0); SET_FONT(FONT_PATTERN_EDITOR_ROWS,0); SET_FONT(FONT_PATTERN_EDITOR_COLUMN_NAME,0); set_bitmap(BITMAP_PATTERN_EDITOR_TRACK_POPUP,-1); set_bitmap(BITMAP_PATTERN_EDITOR_TRACK_POPUP_PRESSED,-1); /* Orderlist */ SET_FONT(FONT_ORDERLIST,0); sbaux=StyleBox(1,Color(0),Color(255,50,50),Color(255,50,50),false); sbaux.draw_center=false; SET_STYLEBOX(SB_ORDERLIST_CURSOR,sbaux); /* Sample Editor */ StyleBox msf; for (int i=0;i<4;i++) msf.margins[i]=5; SET_STYLEBOX( SB_MAIN_STACK_FRAME, msf ); SET_STYLEBOX( SB_TOP_STACK_FRAME, msf ); /* Sample Table */ SET_FONT(FONT_SAMPLETABLE,0); /* Envelope */ SET_FONT(FONT_ENVELOPE,0); /* PlayBack Button */ SET_STYLEBOX( SB_PLAYBACK_BUTTON_NORMAL, StyleBox( 2, Color( 150,150,150 ), Color( 250,250,250 ), Color( 50,50,50 ) ) ); SET_STYLEBOX( SB_PLAYBACK_BUTTON_PRESSED, StyleBox( 2, Color( 110,110,110 ), Color( 50,50,50 ), Color( 200,200,200 ) ) ); SET_STYLEBOX( SB_PLAYBACK_BUTTON_HOVER, StyleBox( 2, Color( 190,190,190 ), Color( 250,250,250 ), Color( 50,50,50 ) ) ); SET_STYLEBOX( SB_PLAYBACK_BUTTON_FOCUS, StyleBox( 1, Color( 0,0,0 ), Color( 255,50,50 ), Color( 255,50,50 ) ) ); for (int i=0;i<4;i++) { StyleBox sb=get_stylebox( SB_PLAYBACK_BUTTON_NORMAL ); sb.margins[i]=6; SET_STYLEBOX( SB_PLAYBACK_BUTTON_NORMAL, sb ); } } CSkin::CSkin() : Skin(C_SB_MAX,C_C_MAX,C_BITMAP_MAX,C_FONT_MAX,C_COLOR_MAX) { set_default_extra(); } CSkin::~CSkin() { }
#ifndef __ENTITYMANAGER_H__ #define __ENTITYMANAGER_H__ #include <unordered_map> #include <unordered_set> #include <string> #include <memory> #include <sstream> #include <cassert> #include <typeinfo> #include <typeindex> #include <set> #include <type_traits> #include <yanecos/IData.h> #include <yanecos/Data.h> #include <json.hpp> #include <blurryroots/throwif.h> //#define DEBUG_SERIALIZE namespace Yanecos { typedef unsigned long int EntityID ; typedef unsigned long int DataID ; typedef //std::unordered_map<DataID, std::shared_ptr<IData>> std::unordered_map<DataID, IData*> DataMap ; typedef std::unordered_set<DataID> EntityDataCollection ; typedef std::unordered_map<EntityID, EntityDataCollection> EntityDataMap ; typedef std::unordered_set<EntityID> EntityCollection ; typedef std::unordered_map<std::string, EntityCollection> DataOwnerMap ; typedef std::unordered_map<std::string, EntityDataCollection> DataTypeLookupMap ; // Template array of bool template<bool... TBool> struct BoolArray {}; // Template checklist template<bool... TBool> struct all_types_derived : std::is_same<BoolArray<TBool...>, BoolArray<(TBool, true)...>> {}; // Template check for data type inheritance template<class... TDataType> struct all_derived_from_data : all_types_derived<std::is_base_of<Data<TDataType>, TDataType>::value...> {}; class EntityManager { private: DataMap data; DataOwnerMap data_owner; DataTypeLookupMap type_lookup; DataID data_id_counter; DataID generate_data_id () { return ++this->data_id_counter; } EntityDataMap entity_data; EntityID entity_id_counter; EntityID generate_entity_id () { return ++this->entity_id_counter; } public: EntityManager (void) : data () , data_owner () , type_lookup () , data_id_counter (0) , entity_data () , entity_id_counter (0) { // }; virtual ~EntityManager (void) { #ifdef DEBUG_SERIALIZE std::cout << this->serialize () << std::endl << std::endl; #endif for (auto entry : this->data) { delete entry.second; } this->data.clear (); this->data_owner.clear (); this->type_lookup.clear (); this->entity_data.clear (); } std::string serialize (void) const { using json = nlohmann::json; json j; j["data_owner"] = json (this->data_owner); j["type_lookup"] = json (this->type_lookup); json entity_data_json = json::array(); for (auto &entry : this->entity_data) { auto key = std::to_string (entry.first); auto value = json (entry.second); json jentry = json::object (); jentry[key] = value; entity_data_json.push_back (jentry); } j["entity_data"] = entity_data_json; return j.dump (); } EntityID create_entity (void) { EntityID id = this->generate_entity_id (); // Check if emplacing collided const auto &report = this->entity_data.emplace (id, EntityDataCollection ()); if (! report.second) { std::stringstream ss; ss << "Entity " << id << " already exists!"; throw std::runtime_error (ss.str ()); } return id; } template<class TDataType> TDataType* get_entity_data (EntityID entity_id) const { static_assert ( all_derived_from_data<TDataType>::value, "Given type has to be derived from Data<>!" ); // Fetch type name const auto &type_name = typeid (TDataType).name (); // Get all data contained in entity const auto &collection = this->entity_data.at (entity_id); if (0 == collection.size ()) { std::stringstream ss; ss << "Entity " << entity_id << " has no data!"; throw std::runtime_error (ss.str ()); } for (auto &data_id : collection) { std::string cur = this->data.at (data_id)->get_type (); if (cur == type_name) { return dynamic_cast<TDataType*> (this->data.at (data_id)); } } std::stringstream ss; ss << "No data of type " << type_name; throw std::runtime_error (ss.str ()); } template<class TDataType, class... TArgs> TDataType* add_data (EntityID entity_id, TArgs&&... args) { static_assert ( all_derived_from_data<TDataType>::value, "Given type has to be derived from Data<>!" ); const auto &type_name = typeid (TDataType).name (); if (0 == this->data_owner.count (type_name)) { this->data_owner.emplace (type_name, EntityCollection ()); } auto &owners = this->data_owner.at (type_name); if (owners.end () != owners.find (entity_id)) { std::stringstream ss; ss << "Entity " << entity_id << " already has " << type_name << "!"; throw std::runtime_error (ss.str ()); } owners.emplace (entity_id); auto data_ptr = new TDataType (std::forward<TArgs> (args)...); assert (data_ptr); DataID data_id = this->generate_data_id (); assert (0 == this->data.count (data_id)); auto report = this->data.emplace (data_id, data_ptr); assert (report.second); // already in map ??? wuut? EntityDataCollection& collection = this->entity_data.at (entity_id); collection.emplace (data_id); if (0 == this->type_lookup.count (type_name)) { this->type_lookup.emplace (type_name, EntityDataCollection ()); } this->type_lookup.at (type_name).emplace (data_id); return dynamic_cast<TDataType*> (data_ptr); } EntityCollection get_all_entities () const { EntityCollection collection; for (auto &entry : this->entity_data) { collection.emplace (entry.first); } return collection; } template<class TDataType> EntityCollection get_entities_with () const { static_assert ( all_derived_from_data<TDataType>::value, "Given type has to be derived from Data<>!" ); const auto &type_name = typeid (TDataType).name (); THROW_IF (1 != this->data_owner.count (type_name), "missing data_owner for typename: ", type_name ); return this->data_owner.at (type_name); } template<class TArg> std::string get_type_name (TArg arg) const { return typeid (TArg).name (); } template<class... TDataType> EntityCollection get_entities_with_all (void) const { static_assert ( all_derived_from_data<TDataType...>::value, "All types must be derived from Data<>" ); std::unordered_set<std::type_index> types { std::type_index (typeid (TDataType))... }; std::unordered_set<EntityID> ids; for (auto &type : types) { for (auto &id : this->data_owner.at (type.name ())) { ids.emplace (id); } } return EntityCollection (ids.begin (), ids.end ()); } }; } #endif
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** 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 //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include "skin.h" #include "main.h" #include "commands.h" #include "../../common/Common.h" #include "../../common/common_defs.h" #include "../../common/strings.h" void R_InitSkins() { tr.numSkins = 1; // make the default skin have all default shaders skin_t* skin = tr.skins[ 0 ] = new skin_t; Com_Memset( skin, 0, sizeof ( skin_t ) ); String::NCpyZ( skin->name, "<default skin>", sizeof ( skin->name ) ); skin->numSurfaces = 1; skin->surfaces[ 0 ] = new skinSurface_t; skin->surfaces[ 0 ]->name[ 0 ] = 0; skin->surfaces[ 0 ]->shader = tr.defaultShader; } qhandle_t R_LoadQuakeWorldSkinData( const char* name, const idSkinTranslation& translation ) { int width; int height; byte* pixels; R_LoadPCX( name, &pixels, NULL, &width, &height ); if ( !pixels ) { return 0; } idList<byte> out; out.SetNum( QUAKEWORLD_SKIN_WIDTH * QUAKEWORLD_SKIN_HEIGHT ); Com_Memset( out.Ptr(), 0, QUAKEWORLD_SKIN_WIDTH * QUAKEWORLD_SKIN_HEIGHT ); byte* outp = out.Ptr(); byte* pixp = pixels; int copyWidth = Min( width, static_cast<int>( QUAKEWORLD_SKIN_WIDTH ) ); int copyHeight = Min ( height , static_cast<int>( QUAKEWORLD_SKIN_HEIGHT ) ); for ( int y = 0; y < copyHeight; y++, outp += QUAKEWORLD_SKIN_WIDTH, pixp += width ) { Com_Memcpy( outp, pixp, copyWidth ); } delete[] pixels; idList<byte> pixelsTop; pixelsTop.SetNum( QUAKEWORLD_SKIN_WIDTH * QUAKEWORLD_SKIN_HEIGHT * 4 ); idList<byte> pixelsBottom; pixelsBottom.SetNum( QUAKEWORLD_SKIN_WIDTH * QUAKEWORLD_SKIN_HEIGHT * 4 ); R_ExtractTranslatedImages( translation, out.Ptr(), pixelsTop.Ptr(), pixelsBottom.Ptr(), QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT ); byte* pic32 = R_ConvertImage8To32( out.Ptr(), QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT, IMG8MODE_Skin ); byte* picFullBright = R_GetFullBrightImage( out.Ptr(), pic32, QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT ); image_t* base = R_CreateImage( name, pic32, QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT, true, true, GL_CLAMP ); delete[] pic32; image_t* top = R_CreateImage( va( "%s*top", name ), pixelsTop.Ptr(), QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT, true, true, GL_CLAMP ); image_t* bottom = R_CreateImage( va( "%s*bottom", name ), pixelsBottom.Ptr(), QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT, true, true, GL_CLAMP ); image_t* fullBright = NULL; if ( picFullBright ) { fullBright = R_CreateImage( va( "%s*fb", name ), picFullBright, QUAKEWORLD_SKIN_WIDTH, QUAKEWORLD_SKIN_HEIGHT, true, true, GL_CLAMP ); delete[] picFullBright; } return R_BuildQuakeWorldCustomSkin( name, base, top, bottom, fullBright )->index; } qhandle_t R_RegisterSkinQ2( const char* name ) { if ( !name || !name[ 0 ] ) { common->Printf( "Empty name passed to R_RegisterSkinQ2\n" ); return 0; } if ( String::Length( name ) >= MAX_QPATH ) { common->Printf( "Skin name exceeds MAX_QPATH\n" ); return 0; } // see if the skin is already loaded qhandle_t hSkin; for ( hSkin = 1; hSkin < tr.numSkins; hSkin++ ) { skin_t* skin = tr.skins[ hSkin ]; if ( !String::ICmp( skin->name, name ) ) { if ( skin->numSurfaces == 0 ) { return 0; // default skin } return hSkin; } } // allocate a new skin if ( tr.numSkins == MAX_SKINS ) { common->Printf( S_COLOR_YELLOW "WARNING: R_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); return 0; } image_t* image = R_FindImageFile( name, true, true, GL_CLAMP, IMG8MODE_Skin ); if ( !image ) { return 0; } // make sure the render thread is stopped R_SyncRenderThread(); tr.numSkins++; skin_t* skin = new skin_t; Com_Memset( skin, 0, sizeof ( skin_t ) ); tr.skins[ hSkin ] = skin; String::NCpyZ( skin->name, name, sizeof ( skin->name ) ); skin->numSurfaces = 1; skin->numModels = 0; skin->surfaces[ 0 ] = new skinSurface_t; skin->surfaces[ 0 ]->name[ 0 ] = 0; skin->surfaces[ 0 ]->shader = R_BuildMd2Shader( image ); return hSkin; } // This is unfortunate, but the skin files aren't compatable with our normal // parsing rules. static const char* CommaParse( char** data_p ) { int c = 0, len; char* data; static char com_token[ MAX_TOKEN_CHARS_Q3 ]; data = *data_p; len = 0; com_token[ 0 ] = 0; // make sure incoming data is valid if ( !data ) { *data_p = NULL; return com_token; } while ( 1 ) { // skip whitespace while ( ( c = *data ) <= ' ' ) { if ( !c ) { break; } data++; } c = *data; // skip double slash comments if ( c == '/' && data[ 1 ] == '/' ) { while ( *data && *data != '\n' ) { data++; } } // skip /* */ comments else if ( c == '/' && data[ 1 ] == '*' ) { while ( *data && ( *data != '*' || data[ 1 ] != '/' ) ) { data++; } if ( *data ) { data += 2; } } else { break; } } if ( c == 0 ) { return ""; } // handle quoted strings if ( c == '\"' ) { data++; while ( 1 ) { c = *data++; if ( c == '\"' || !c ) { com_token[ len ] = 0; *data_p = data; return com_token; } if ( len < MAX_TOKEN_CHARS_Q3 ) { com_token[ len ] = c; len++; } } } // parse a regular word do { if ( len < MAX_TOKEN_CHARS_Q3 ) { com_token[ len ] = c; len++; } data++; c = *data; } while ( c > 32 && c != ',' ); if ( len == MAX_TOKEN_CHARS_Q3 ) { // common->Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS_Q3); len = 0; } com_token[ len ] = 0; *data_p = data; return com_token; } qhandle_t R_RegisterSkin( const char* name ) { if ( !name || !name[ 0 ] ) { common->Printf( "Empty name passed to R_RegisterSkin\n" ); return 0; } if ( String::Length( name ) >= MAX_QPATH ) { common->Printf( "Skin name exceeds MAX_QPATH\n" ); return 0; } // see if the skin is already loaded qhandle_t hSkin; for ( hSkin = 1; hSkin < tr.numSkins; hSkin++ ) { skin_t* skin = tr.skins[ hSkin ]; if ( !String::ICmp( skin->name, name ) ) { if ( skin->numSurfaces == 0 ) { return 0; // default skin } return hSkin; } } // allocate a new skin if ( tr.numSkins == MAX_SKINS ) { common->Printf( S_COLOR_YELLOW "WARNING: R_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); return 0; } //----(SA) moved things around slightly to fix the problem where you restart // a map that has ai characters who had invalid skin names entered // in thier "skin" or "head" field skin_t* skin; if ( !( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) ) ) { tr.numSkins++; skin = new skin_t; Com_Memset( skin, 0, sizeof ( skin_t ) ); tr.skins[ hSkin ] = skin; String::NCpyZ( skin->name, name, sizeof ( skin->name ) ); skin->numSurfaces = 0; skin->numModels = 0; } // make sure the render thread is stopped R_SyncRenderThread(); // If not a .skin file, load as a single shader if ( !( GGameType & GAME_ET ) && String::Cmp( name + String::Length( name ) - 5, ".skin" ) ) { if ( GGameType & ( GAME_WolfSP | GAME_WolfMP ) ) { tr.numSkins++; skin = new skin_t; Com_Memset( skin, 0, sizeof ( skin_t ) ); tr.skins[ hSkin ] = skin; String::NCpyZ( skin->name, name, sizeof ( skin->name ) ); skin->numSurfaces = 0; skin->numModels = 0; } skin->numSurfaces = 1; skin->surfaces[ 0 ] = new skinSurface_t; skin->surfaces[ 0 ]->name[ 0 ] = 0; skin->surfaces[ 0 ]->shader = R_FindShader( name, LIGHTMAP_NONE, true ); return hSkin; } // load and parse the skin file char* text; FS_ReadFile( name, ( void** )&text ); if ( !text ) { return 0; } if ( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) ) { tr.numSkins++; skin = new skin_t; Com_Memset( skin, 0, sizeof ( skin_t ) ); tr.skins[ hSkin ] = skin; String::NCpyZ( skin->name, name, sizeof ( skin->name ) ); skin->numSurfaces = 0; skin->numModels = 0; } char* text_p = text; while ( text_p && *text_p ) { // get surface name const char* token = CommaParse( &text_p ); char surfName[ MAX_QPATH ]; String::NCpyZ( surfName, token, sizeof ( surfName ) ); if ( !token[ 0 ] ) { break; } // lowercase the surface name so skin compares are faster String::ToLower( surfName ); if ( *text_p == ',' ) { text_p++; } if ( !String::NICmp( token, "tag_", 4 ) ) { continue; } if ( GGameType & ( GAME_WolfSP | GAME_WolfMP | GAME_ET ) && !String::NICmp( token, "md3_", 4 ) ) { // this is specifying a model skinModel_t* model = skin->models[ skin->numModels ] = new skinModel_t; String::NCpyZ( model->type, token, sizeof ( model->type ) ); model->hash = Com_HashKey( model->type, sizeof ( model->type ) ); // get the model name token = CommaParse( &text_p ); String::NCpyZ( model->model, token, sizeof ( model->model ) ); skin->numModels++; continue; } if ( GGameType & ( GAME_WolfSP | GAME_WolfMP ) && strstr( token, "playerscale" ) ) { token = CommaParse( &text_p ); skin->scale[ 0 ] = String::Atof( token ); // uniform scaling for now skin->scale[ 1 ] = String::Atof( token ); skin->scale[ 2 ] = String::Atof( token ); continue; } // parse the shader name token = CommaParse( &text_p ); skinSurface_t* surf = new skinSurface_t; skin->surfaces[ skin->numSurfaces ] = surf; String::NCpyZ( surf->name, surfName, sizeof ( surf->name ) ); surf->hash = Com_HashKey( surf->name, sizeof ( surf->name ) ); surf->shader = R_FindShader( token, LIGHTMAP_NONE, true ); skin->numSurfaces++; } FS_FreeFile( text ); // never let a skin have 0 shaders if ( skin->numSurfaces == 0 ) { //----(SA) allow this for the (current) special case of the loper's upper body // (it's upper body has no surfaces, only tags) if ( !( GGameType & ( GAME_WolfSP | GAME_WolfMP ) ) || !( strstr( name, "loper" ) && strstr( name, "upper" ) ) ) { return 0; // use default skin } } return hSkin; } skin_t* R_GetSkinByHandle( qhandle_t hSkin ) { if ( hSkin < 1 || hSkin >= tr.numSkins ) { return tr.skins[ 0 ]; } return tr.skins[ hSkin ]; } //----(SA) added so client can see what model or scale for the model was specified in a skin bool R_GetSkinModel( qhandle_t skinid, const char* type, char* name ) { skin_t* skin = tr.skins[ skinid ]; int hash = Com_HashKey( ( char* )type, String::Length( type ) ); if ( GGameType & ( GAME_WolfSP | GAME_WolfMP ) && !String::ICmp( type, "playerscale" ) ) { // client is requesting scale from the skin rather than a model String::Sprintf( name, MAX_QPATH, "%.2f %.2f %.2f", skin->scale[ 0 ], skin->scale[ 1 ], skin->scale[ 2 ] ); return true; } for ( int i = 0; i < skin->numModels; i++ ) { if ( GGameType & GAME_ET && hash != skin->models[ i ]->hash ) { continue; } if ( !String::ICmp( skin->models[ i ]->type, type ) ) { // (SA) whoops, should've been this way String::NCpyZ( name, skin->models[ i ]->model, sizeof ( skin->models[ i ]->model ) ); return true; } } return false; } // Return a shader index for a given model's surface // 'withlightmap' set to '0' will create a new shader that is a copy of the one found // on the model, without the lighmap stage, if the shader has a lightmap stage // NOTE: only works for bmodels right now. Could modify for other models (md3's etc.) qhandle_t R_GetShaderFromModel( qhandle_t modelid, int surfnum, int withlightmap ) { if ( surfnum < 0 ) { surfnum = 0; } idRenderModel* model = R_GetModelByHandle( modelid ); // (SA) should be correct now if ( model ) { mbrush46_model_t* bmodel = model->q3_bmodel; if ( bmodel && bmodel->firstSurface ) { if ( surfnum >= bmodel->numSurfaces ) { // if it's out of range, return the first surface surfnum = 0; } idWorldSurface* surf = bmodel->firstSurface[ surfnum ]; // RF, check for null shader (can happen on func_explosive's with botclips attached) if ( !surf->shader ) { return 0; } shader_t* shd; if ( surf->shader->lightmapIndex > LIGHTMAP_NONE ) { bool mip = true; // mip generation on by default // get mipmap info for original texture image_t* image = R_FindImage( surf->shader->name ); if ( image ) { mip = image->mipmap; } shd = R_FindShader( surf->shader->name, LIGHTMAP_NONE, mip ); shd->stages[ 0 ]->rgbGen = CGEN_LIGHTING_DIFFUSE; // (SA) new } else { shd = surf->shader; } return shd->index; } } return 0; } void R_SkinList_f() { common->Printf( "------------------\n" ); for ( int i = 0; i < tr.numSkins; i++ ) { skin_t* skin = tr.skins[ i ]; common->Printf( "%3i:%s\n", i, skin->name ); for ( int j = 0; j < skin->numSurfaces; j++ ) { common->Printf( " %s = %s\n", skin->surfaces[ j ]->name, skin->surfaces[ j ]->shader->name ); } } common->Printf( "------------------\n" ); }
// // Created by wiktor on 15.03.18. // #include "XorCypherBreaker.h" int main() { return 0; }
#include "american_option.h" #include "plainvanilla_payoff.h" #include "plainvanilla_option.h" #include "u_math.h" #include <cmath> #include <iostream> #include <algorithm> /* Constructor */ AmericanOption::AmericanOption(double strike, double maturity, OptionType type) :Option(strike, maturity, type) { payoff_.reset(new PlainVanillaPayoff(strike, type)); } /* Copy Constructors */ AmericanOption::AmericanOption(AmericanOption& option) { strike_ = option.strike_; t_ = option.t_; type_ = option.type_; this -> setMarketVariable(option.mktVar_); payoff_.reset(new PlainVanillaPayoff(option.strike_, option.type_)); } AmericanOption::AmericanOption(const AmericanOption& option) { strike_ = option.strike_; t_ = option.t_; type_ = option.type_; this -> setMarketVariable(option.mktVar_); payoff_.reset(new PlainVanillaPayoff(option.strike_, option.type_)); } /* Assignment operators */ AmericanOption& AmericanOption::operator= (AmericanOption& option) { AmericanOption copy(option); Swap(*this, copy); return *this; } AmericanOption& AmericanOption::operator= (const AmericanOption& option) { AmericanOption copy(option); Swap(*this, copy); return *this; } /* Evaluate price by using binomial tree */ double AmericanOption::bntprice(unsigned int steps, BinomialType bntType) { std::vector<double> tree; if (bntType == BD) { /* Broadie and Detemple Method */ tree.resize(steps); /* Tree at N - 1 */ /* Use parameters of CRR */ dt_ = t_ / steps; u_ = exp(sigma_ * sqrt(dt_)); /* Upward node */ d_ = 1 / u_; /* Downward node */ q_ = (exp((r_ - div_) * dt_) - d_) / (u_ - d_); /* Risk neutral probability */ PlainVanillaOption vOption(strike_, dt_, type_); /* European option for calculating last node */ vOption.setMarketVariable(mktVar_); /* Payoff setting at last node */ for (int i = 0; i < tree.size(); ++i) { double spot = s_ * pow(u_, steps - i - 1) * pow(d_, i); vOption.setSpot(spot); tree[i] = MAX(vOption.bsprice(), (*payoff_)(spot)); } } else { /* Other Method */ tree = makeTree(steps, bntType); } /* Backward induction */ double prevSpot; /* Spot price at previous period */ double exValue, contValue; /* Exercise Value and Continuation Value */ exerTree_.clear(); /* Initialize exercise tree */ for (int i = tree.size() - 1; i > 0; --i) { std::vector<ExerDummy> exer; for (int j = 0; j < i; ++j) { prevSpot = s_ * pow(u_, i - j - 1) * pow(d_, j); exValue = (*payoff_)(prevSpot); contValue = exp(-r_ * dt_) * (q_ * tree[j] + (1 - q_) * tree[j + 1]); /* Write exercise tree at time i */ if (exValue > contValue) exer.push_back(Exercise); else exer.push_back(Continue); tree[j] = MAX(exValue, contValue); } /* Write exercise tree */ exerTree_.push_back(exer); } return tree[0]; } void AmericanOption::printExer() { for (int i = 0; i < exerTree_.size(); ++i) { for (int j = 0; j < exerTree_[i].size(); ++j) { std::cout << exerTree_[i][j] << " "; } std::cout << std::endl; } } std::vector<double> AmericanOption::exerciseBound(unsigned int steps, BinomialType bntType) { bntprice(steps, bntType); std::vector<double> bound; for (int i = 0; i < exerTree_.size(); ++i) { for (int j = 0; j < exerTree_[i].size() - 1; ++j) { /* If no early exercise */ if (exerTree_[i][exerTree_[i].size() - 1] == 0) { bound.push_back(0); break; } /* If early exercise */ if (exerTree_[i][j] == 0 && exerTree_[i][j+1] == 1) { bound.push_back(s_ * pow(u_, exerTree_[i].size() - (j + 1)) * pow(d_, j + 1)); break; } } } return bound; } /* Swap function */ void AmericanOption::Swap(AmericanOption& lhs, AmericanOption& rhs) { Option::Swap(&lhs, &rhs); }
#ifndef __GENERATOR_H__ #define __GENERATOR_H__ #include "VehicleBase.h" #include <random> using namespace std; class Generator { private: double prob_new_vehicle_northbound; double prob_new_vehicle_southbound; double prob_new_vehicle_eastbound; double prob_new_vehicle_westbound; double proportion_of_cars; double proportion_of_SUVs; double proportion_of_trucks; double prob_right_turn_cars; double prob_left_turn_cars; double prob_right_turn_SUVs; double prob_left_turn_SUVs; double prob_right_turn_trucks; double prob_left_turn_trucks; int initialSeed; mt19937 rng; public: Generator(); Generator(int initialSeed, double prob_new_vehicle_northbound, double prob_new_vehicle_southbound, double prob_new_vehicle_eastbound, double prob_new_vehicle_westbound, double proportion_of_cars, double proportion_of_SUVs, double proportion_of_trucks, double prob_right_turn_cars, double prob_left_turn_cars, double prob_right_turn_SUVs, double prob_left_turn_SUVs,double prob_right_turn_trucks, double prob_left_turn_trucks); ~Generator(); VehicleBase* genNorth(); VehicleBase* genSouth(); VehicleBase* genEast(); VehicleBase* genWest(); bool isTurn(VehicleType type); VehicleType generateType(); }; #endif
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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 "CellAgesWriter.hpp" #include "AbstractCellPopulation.hpp" template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> CellAgesWriter<ELEMENT_DIM, SPACE_DIM>::CellAgesWriter() : AbstractCellWriter<ELEMENT_DIM, SPACE_DIM>("cellages.dat") { this->mVtkCellDataName = "Ages"; } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> double CellAgesWriter<ELEMENT_DIM, SPACE_DIM>::GetCellDataForVtkOutput(CellPtr pCell, AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation) { return pCell->GetAge(); } template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void CellAgesWriter<ELEMENT_DIM, SPACE_DIM>::VisitCell(CellPtr pCell, AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation) { // Write location index corresponding to cell *this->mpOutStream << pCellPopulation->GetLocationIndexUsingCell(pCell) << " "; // Write cell location c_vector<double, SPACE_DIM> cell_location = pCellPopulation->GetLocationOfCellCentre(pCell); for (unsigned i=0; i<SPACE_DIM; i++) { *this->mpOutStream << cell_location[i] << " "; } // Write cell age *this->mpOutStream << pCell->GetAge() << " "; } // Explicit instantiation template class CellAgesWriter<1,1>; template class CellAgesWriter<1,2>; template class CellAgesWriter<2,2>; template class CellAgesWriter<1,3>; template class CellAgesWriter<2,3>; template class CellAgesWriter<3,3>; #include "SerializationExportWrapperForCpp.hpp" // Declare identifier for the serializer EXPORT_TEMPLATE_CLASS_ALL_DIMS(CellAgesWriter)
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef TESTCRYPTSIMULATION2DNIGHTLY_HPP_ #define TESTCRYPTSIMULATION2DNIGHTLY_HPP_ #include <cxxtest/TestSuite.h> #include "CheckpointArchiveTypes.hpp" #include "CryptSimulation2d.hpp" #include "MeshBasedCellPopulationWithGhostNodes.hpp" #include "CryptCellsGenerator.hpp" #include "GeneralisedLinearSpringForce.hpp" #include "WntConcentration.hpp" #include "RandomCellKiller.hpp" #include "SloughingCellKiller.hpp" #include "CylindricalHoneycombMeshGenerator.hpp" #include "CellBasedEventHandler.hpp" #include "ApcTwoHitCellMutationState.hpp" #include "WildTypeCellMutationState.hpp" #include "WntCellCycleModel.hpp" #include "SimpleWntCellCycleModel.hpp" #include "SmartPointers.hpp" // Cell population writers #include "CellProliferativeTypesCountWriter.hpp" #include "VoronoiDataWriter.hpp" #include "AbstractCellBasedWithTimingsTestSuite.hpp" #include "FakePetscSetup.hpp" class TestCryptSimulation2dNightly : public AbstractCellBasedWithTimingsTestSuite { private: void setUp() { CellBasedEventHandler::Disable(); // these tests fail with event-handling on AbstractCellBasedWithTimingsTestSuite::setUp(); } public: ///////// NON-PERIODIC TESTS - these test the spring system and cell birth etc. ///////// /** * Provides a reasonable test for the ghost node system... */ void Test2DHoneycombMeshNotPeriodic() { // Create mesh unsigned num_cells_depth = 11; unsigned num_cells_width = 6; double crypt_length = num_cells_depth-1.0; double crypt_width = num_cells_width-1.0; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 2); MutableMesh<2,2>* p_mesh = generator.GetMesh(); // Get location indices corresponding to real cells std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Set up cells std::vector<CellPtr> cells; CryptCellsGenerator<FixedG1GenerationalCellCycleModel> cells_generator; cells_generator.Generate(cells, p_mesh, location_indices, true); TS_ASSERT_EQUALS(cells.size(), location_indices.size()); unsigned original_number_of_ghosts = p_mesh->GetNumNodes() - cells.size(); TS_ASSERT_EQUALS(original_number_of_ghosts, 84u); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); crypt.AddCellPopulationCountWriter<CellProliferativeTypesCountWriter>(); // Create crypt simulation from cell population CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Crypt2DHoneycombMesh"); simulator.SetEndTime(12.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Create cell killer and pass in to crypt simulation MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&crypt, crypt_length, true, crypt_width)); simulator.AddCellKiller(p_killer); // Run simulation simulator.Solve(); // Work out where the previous test wrote its files OutputFileHandler handler("Crypt2DHoneycombMesh", false); unsigned number_of_cells = crypt.GetNumRealCells(); unsigned number_of_nodes = p_mesh->GetNumNodes(); /// \future This test is really fragile - gets different answers with Intel and Gcc compilers // 61 <= number_of_cells <= 63 TS_ASSERT_LESS_THAN_EQUALS(number_of_cells, 63u); TS_ASSERT_LESS_THAN_EQUALS(61u, number_of_cells); // 145 <= number_of_nodes <= 147 TS_ASSERT_LESS_THAN_EQUALS(number_of_nodes, 147u); TS_ASSERT_LESS_THAN_EQUALS(145u, number_of_nodes); std::set<unsigned> ghost_indices = crypt.GetGhostNodeIndices(); TS_ASSERT_EQUALS(number_of_cells + ghost_indices.size(), number_of_nodes); std::vector<unsigned> cell_type_count = crypt.GetCellProliferativeTypeCount(); TS_ASSERT_EQUALS(cell_type_count.size(), 4u); TS_ASSERT_EQUALS(cell_type_count[0], 6u); // Stem TS_ASSERT_LESS_THAN_EQUALS(cell_type_count[1], 23u); // 21 <= Transit <= 23 TS_ASSERT_LESS_THAN_EQUALS(21u, cell_type_count[1]); TS_ASSERT_LESS_THAN_EQUALS(cell_type_count[2], 35u); // 33 <= Differentiated <= 35 TS_ASSERT_LESS_THAN_EQUALS(33u, cell_type_count[2]); TS_ASSERT_EQUALS(cell_type_count[3], 0u); // Default } void TestMonolayer() { // Create mesh unsigned num_cells_depth = 11; unsigned num_cells_width = 6; //double crypt_length = num_cells_depth - 1.0; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 2); MutableMesh<2,2>* p_mesh = generator.GetMesh(); // Get location indices corresponding to real cells std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Set up cells std::vector<CellPtr> cells; CryptCellsGenerator<FixedG1GenerationalCellCycleModel> cells_generator; cells_generator.Generate(cells, p_mesh, location_indices, true, -1.0); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); crypt.AddPopulationWriter<VoronoiDataWriter>(); crypt.AddCellPopulationCountWriter<CellProliferativeTypesCountWriter>(); // Set the first cell to be logged crypt.Begin()->SetLogged(); // Create crypt simulation from cell population CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Monolayer"); simulator.SetEndTime(1); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Run simulation simulator.Solve(); unsigned number_of_cells = crypt.GetNumRealCells(); unsigned number_of_nodes = p_mesh->GetNumNodes(); TS_ASSERT_EQUALS(number_of_cells, 69u); TS_ASSERT_EQUALS(number_of_nodes, 153u); std::set<unsigned> ghost_indices = crypt.GetGhostNodeIndices(); TS_ASSERT_EQUALS(number_of_cells + ghost_indices.size(), number_of_nodes); std::vector<unsigned> cell_type_count = crypt.GetCellProliferativeTypeCount(); TS_ASSERT_EQUALS(cell_type_count.size(), 4u); TS_ASSERT_EQUALS(cell_type_count[0], 0u); // Stem TS_ASSERT_EQUALS(cell_type_count[1], 33u); // Transit TS_ASSERT_EQUALS(cell_type_count[2], 36u); // Differentiated TS_ASSERT_EQUALS(cell_type_count[3], 0u); // Default TS_ASSERT_EQUALS(crypt.GetVoronoiTessellation()->GetNumElements(), number_of_nodes); TS_ASSERT_EQUALS(crypt.GetVoronoiTessellation()->GetNumNodes(), 280u); } /** * Starting with a small mesh with one stem cell and the rest * differentiated, check that the number of cells at the end * of the simulation is as expected. */ void Test2DCorrectCellNumbers() { // Create mesh unsigned num_cells_width = 7; unsigned num_cells_depth = 5; HoneycombMeshGenerator generator(num_cells_width, num_cells_depth, 2); MutableMesh<2,2>* p_mesh = generator.GetMesh(); // Get location indices corresponding to real cells std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); double crypt_width = num_cells_width - 1.0; double crypt_length = num_cells_depth - 1.0; // Set up cells by iterating through the mesh nodes unsigned num_cells = location_indices.size(); std::vector<CellPtr> cells; for (unsigned i=0; i<num_cells; i++) { MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); unsigned generation = 4; if (location_indices[i] == 27) // middle of bottom row of cells { generation = 0; } p_model->SetGeneration(generation); // Check the stem cell cycle time is still 24 hrs, otherwise this test might not pass //TS_ASSERT_DELTA(p_model->GetStemCellG1Duration(), 14, 1e-12); //These lines may trip up the Intel compiler with heavy optimization - don't know why? //TS_ASSERT_DELTA(p_model->GetTransitCellG1Duration(), 2, 1e-12); TS_ASSERT_DELTA(p_model->GetSG2MDuration(), 10, 1e-12); CellPtr p_cell(new Cell(p_state, p_model)); p_cell->SetCellProliferativeType(p_diff_type); if (location_indices[i] == 27) // middle of bottom row of cells { p_cell->SetCellProliferativeType(p_stem_type); } p_cell->SetBirthTime(-1.0); cells.push_back(p_cell); } // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); // Create crypt simulation from cell population CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Crypt2DSpringsCorrectCellNumbers"); simulator.SetEndTime(40); // hours // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Create cell killer and pass in to crypt simulation MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&crypt, crypt_length, true, crypt_width)); simulator.AddCellKiller(p_killer); // Run simulation simulator.Solve(); // Now count the number of each type of cell unsigned num_stem = 0; unsigned num_transit = 0; unsigned num_differentiated = 0; for (AbstractCellPopulation<2>::Iterator cell_iter = crypt.Begin(); cell_iter != crypt.End(); ++cell_iter) { if (cell_iter->GetCellProliferativeType()->IsType<StemCellProliferativeType>()) { num_stem++; } else if (cell_iter->GetCellProliferativeType()->IsType<TransitCellProliferativeType>()) { num_transit++; } else if (cell_iter->GetCellProliferativeType()->IsType<DifferentiatedCellProliferativeType>()) { num_differentiated++; } else { // shouldn't get here TS_ASSERT(false); } } TS_ASSERT_EQUALS(num_stem, 1u); TS_ASSERT_EQUALS(num_transit, 2u); TS_ASSERT_LESS_THAN(num_differentiated, 25u); TS_ASSERT_LESS_THAN(15u, num_differentiated); } ///////// PERIODIC TESTS - These test the system as a whole ///////// void Test2DPeriodicNightly() { // Create mesh unsigned cells_across = 6; unsigned cells_up = 12; unsigned thickness_of_ghost_layer = 4; CylindricalHoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer); Cylindrical2dMesh* p_mesh = generator.GetCylindricalMesh(); double crypt_length = cells_up*(sqrt(3.0)/2); // Get location indices corresponding to real cells std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Set up cells std::vector<CellPtr> cells; CryptCellsGenerator<FixedG1GenerationalCellCycleModel> cells_generator; cells_generator.Generate(cells, p_mesh, location_indices, true); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); // Create crypt simulation from cell population CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Crypt2DPeriodicNightly"); simulator.SetEndTime(12.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Create cell killer and pass in to crypt simulation MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&crypt, crypt_length)); simulator.AddCellKiller(p_killer); // Run simulation simulator.Solve(); // Test we have the same number of cells and nodes at the end of each time // (if we do then the boundaries are probably working!) unsigned number_of_cells = crypt.GetNumRealCells(); unsigned number_of_nodes = crypt.rGetMesh().GetNumNodes(); TS_ASSERT_EQUALS(number_of_cells, 87u); TS_ASSERT_EQUALS(number_of_nodes, 135u); } void TestCrypt2DPeriodicWntNightly() { CellBasedEventHandler::Enable(); unsigned cells_across = 6; unsigned cells_up = 12; unsigned thickness_of_ghost_layer = 4; CylindricalHoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer); Cylindrical2dMesh* p_mesh = generator.GetCylindricalMesh(); double crypt_length = cells_up*(sqrt(3.0)/2); std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Set up cells std::vector<CellPtr> cells; CryptCellsGenerator<WntCellCycleModel> cells_generator; cells_generator.Generate(cells, p_mesh, location_indices, true); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); // Create an instance of a Wnt concentration WntConcentration<2>::Instance()->SetType(LINEAR); WntConcentration<2>::Instance()->SetCellPopulation(crypt); WntConcentration<2>::Instance()->SetCryptLength(crypt_length); // Create crypt simulation from cell population CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Crypt2DPeriodicWntNightly"); simulator.SetEndTime(24.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Create cell killer and pass in to crypt simulation MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&crypt, crypt_length)); simulator.AddCellKiller(p_killer); // Run simulation simulator.Solve(); // Test we have the same number of cells and nodes at the end of each time // (if we do then the boundaries are probably working!) unsigned number_of_nodes = crypt.rGetMesh().GetNumNodes(); #ifdef CHASTE_CVODE // divisions occur marginally earlier with CVODE TS_ASSERT_EQUALS(crypt.GetNumRealCells(), 99u); TS_ASSERT_EQUALS(number_of_nodes, 147u); #else TS_ASSERT_EQUALS(crypt.GetNumRealCells(), 99u); TS_ASSERT_EQUALS(number_of_nodes, 147u); #endif //CHASTE_CVODE // Tidy up WntConcentration<2>::Destroy(); /* * HOW_TO_TAG Cell Based/Simulation * Time various aspects of a cell-based simulation using `CellBasedEventHandler`. Do not forget #include "CellBasedEventHandler.hpp" and to call CellBasedEventHandler::Enable(); at the top of the test. If you are running multiple simulations then either place a CellBasedEventHandler::Reset(); before or after each solve or add the reset to the tearDown() method as above */ CellBasedEventHandler::Headings(); CellBasedEventHandler::Report(); } /** * This test is dontTest-ed out and not run every night as it * doesn't really test anything. It does show how to set up a * mutant simulation. Mutant viscosities are tested elsewhere * directly. */ void dontRunTestWithMutantCellsUsingDifferentViscosities() { unsigned cells_across = 6; unsigned cells_up = 12; unsigned thickness_of_ghost_layer = 4; CylindricalHoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer); Cylindrical2dMesh* p_mesh = generator.GetCylindricalMesh(); double crypt_length = cells_up*(sqrt(3.0)/2); std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Set up cells std::vector<CellPtr> cells; CryptCellsGenerator<WntCellCycleModel> cells_generator; cells_generator.Generate(cells, p_mesh, location_indices, true); for (unsigned i=0; i<p_mesh->GetNumAllNodes(); i++) { double x = p_mesh->GetNode(i)->GetPoint().rGetLocation()[0]; double y = p_mesh->GetNode(i)->GetPoint().rGetLocation()[1]; double dist_from_3_6 = sqrt((x-3)*(x-3)+(y-6)*(y-6)); MAKE_PTR(WildTypeCellMutationState, p_healthy); MAKE_PTR(ApcTwoHitCellMutationState, p_apc2); if (dist_from_3_6 < 1.1) { cells[i]->SetMutationState(p_apc2); } else { cells[i]->SetMutationState(p_healthy); } } // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); // Create an instance of a Wnt concentration WntConcentration<2>::Instance()->SetType(LINEAR); WntConcentration<2>::Instance()->SetCellPopulation(crypt); WntConcentration<2>::Instance()->SetCryptLength(crypt_length); // Create crypt simulation from cell population CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Crypt2DPeriodicMutant"); simulator.SetEndTime(12.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Create cell killer and pass in to crypt simulation MAKE_PTR_ARGS(SloughingCellKiller<2>, p_killer, (&crypt, crypt_length)); simulator.AddCellKiller(p_killer); // Run simulation simulator.Solve(); // Test we have the same number of cells and nodes at the end of each time // (if we do then the boundaries are probably working!) std::vector<bool> ghost_cells = crypt.rGetGhostNodes(); unsigned number_of_nodes = crypt.rGetMesh().GetNumNodes(); TS_ASSERT_EQUALS(number_of_nodes,ghost_cells.size()); unsigned number_of_cells = 0; unsigned number_of_mutant_cells = 0; for (AbstractCellPopulation<2>::Iterator cell_iter = crypt.Begin(); cell_iter != crypt.End(); ++cell_iter) { number_of_cells++; if (cell_iter->GetMutationState()->IsType<ApcTwoHitCellMutationState>()) { number_of_mutant_cells++; } } // Tidy up WntConcentration<2>::Destroy(); } void TestRandomDeathWithPeriodicMesh() { unsigned cells_across = 7; unsigned cells_up = 12; double crypt_width = 6.0; unsigned thickness_of_ghost_layer = 4; CylindricalHoneycombMeshGenerator generator(cells_across, cells_up, thickness_of_ghost_layer, crypt_width/cells_across); Cylindrical2dMesh* p_mesh = generator.GetCylindricalMesh(); std::vector<unsigned> location_indices = generator.GetCellLocationIndices(); // Set up cells std::vector<CellPtr> cells; CryptCellsGenerator<FixedG1GenerationalCellCycleModel> cells_generator; cells_generator.Generate(cells, p_mesh, location_indices, true); // Create cell population MeshBasedCellPopulationWithGhostNodes<2> crypt(*p_mesh, cells, location_indices); // Create crypt simulation from cell population and force law CryptSimulation2d simulator(crypt); simulator.SetOutputDirectory("Crypt2DRandomDeathPeriodic"); simulator.SetEndTime(4.0); // Create a force law and pass it to the simulation MAKE_PTR(GeneralisedLinearSpringForce<2>, p_linear_force); simulator.AddForce(p_linear_force); // Create cell killer and pass in to crypt simulation MAKE_PTR_ARGS(RandomCellKiller<2>, p_killer, (&crypt, 0.700619609)); simulator.AddCellKiller(p_killer); // Run simulation simulator.Solve(); // There should be no cells left after this amount of time TS_ASSERT_EQUALS(crypt.GetNumRealCells(), 1u); } }; #endif /*TESTCRYPTSIMULATION2DNIGHTLY_HPP_*/
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> all; vector<int>::iterator it1, it2; if (nums1.size() + nums2.size() == 0) return 0; it1 = nums1.begin(); it2 = nums2.begin(); while (it1 != nums1.end() || it2 != nums2.end()) { if (it1 != nums1.end() && it2 != nums2.end()) { if (*it1 > *it2) { all.push_back(*it2); ++it2; } else { all.push_back(*it1); ++it1; } } else if (it1 == nums1.end()) { all.push_back(*it2); ++it2; } else { all.push_back(*it1); ++it1; } } int pos = (all.size()-1)/2; if (all.size() % 2 == 0) return (*(all.begin()+pos) + *(all.begin()+pos+1))/(double)2; else return *(all.begin()+pos); } };
/** Filename: interface.hpp * Description: contains declarations of methods used to interact with the user (i.e., get, clean up, and validate input from the user) * Author: Khoa Tran */ #ifndef INTERFACE_HPP #define INTERFACE_HPP #include <vector> #include <string> #include <iostream> #include <vector> #include <string> #include <iostream> using namespace std; /** Function: displayInstructions * Description: display usage instructions to the user * TODO: method will not be called at the start of the program; instead, it will be called when the command line argument "-h" is passed. * Input: none * Output: none */ void displayInstructions(); /** Function: getMatrixFromUser * Description: * - get matrix input from user as a single string, in the following format: * 1. Elements are entered by row, each separated by a space." * 2. Each row is separated by a comma. * - get matrix input (string) from the user * - parse the matrix input for matrix entries * - convert the entries to doubles and push them to the 2D vector * TODO: (upcoming feature) take matrix input as a command line argument, preceded by the type of operation to be performed on the matrix (e.g. -d "1 2, 3 4" -- this will be interpreted as "calculate the determinant of this matrix") * Input: a 2D vector, representing a matrix (passed by reference) * Change: fill the input 2D vector with matrix entries * Output: none */ void getMatrixFromUser(vector <vector <double>> &matrix); #endif
#include "aulibdefs.h" #include "auplcdrive.h" #include <aulib.h> #include <QObject> AuPlcDrive::~AuPlcDrive() { }
// // Copyright (c) 2003--2009 // Toon Knapen, Karl Meerbergen, Kresimir Fresl, // Thomas Klimpel and Rutger ter Borg // // 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) // // THIS FILE IS AUTOMATICALLY GENERATED // PLEASE DO NOT EDIT! // #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_LARGV_HPP #define BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_LARGV_HPP #include <boost/assert.hpp> #include <boost/mpl/bool.hpp> #include <boost/numeric/bindings/lapack/detail/lapack.h> #include <boost/numeric/bindings/traits/is_complex.hpp> #include <boost/numeric/bindings/traits/is_real.hpp> #include <boost/numeric/bindings/traits/traits.hpp> #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace boost { namespace numeric { namespace bindings { namespace lapack { //$DESCRIPTION // overloaded functions to call lapack namespace detail { inline void largv( integer_t const n, float* x, integer_t const incx, float* y, integer_t const incy, float* c, integer_t const incc ) { LAPACK_SLARGV( &n, x, &incx, y, &incy, c, &incc ); } inline void largv( integer_t const n, double* x, integer_t const incx, double* y, integer_t const incy, double* c, integer_t const incc ) { LAPACK_DLARGV( &n, x, &incx, y, &incy, c, &incc ); } inline void largv( integer_t const n, traits::complex_f* x, integer_t const incx, traits::complex_f* y, integer_t const incy, float* c, integer_t const incc ) { LAPACK_CLARGV( &n, traits::complex_ptr(x), &incx, traits::complex_ptr(y), &incy, c, &incc ); } inline void largv( integer_t const n, traits::complex_d* x, integer_t const incx, traits::complex_d* y, integer_t const incy, double* c, integer_t const incc ) { LAPACK_ZLARGV( &n, traits::complex_ptr(x), &incx, traits::complex_ptr(y), &incy, c, &incc ); } } // value-type based template template< typename ValueType, typename Enable = void > struct largv_impl{}; // real specialization template< typename ValueType > struct largv_impl< ValueType, typename boost::enable_if< traits::is_real<ValueType> >::type > { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; // templated specialization template< typename VectorX, typename VectorY, typename VectorC > static void invoke( integer_t const n, VectorX& x, integer_t const incx, VectorY& y, integer_t const incy, VectorC& c, integer_t const incc ) { BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits< VectorX >::value_type, typename traits::vector_traits< VectorY >::value_type >::value) ); BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits< VectorX >::value_type, typename traits::vector_traits< VectorC >::value_type >::value) ); BOOST_ASSERT( traits::vector_size(x) >= 1+(n-1)*incx ); BOOST_ASSERT( traits::vector_size(y) >= 1+(n-1)*incy ); BOOST_ASSERT( traits::vector_size(c) >= 1+(n-1)*incc ); detail::largv( n, traits::vector_storage(x), incx, traits::vector_storage(y), incy, traits::vector_storage(c), incc ); } }; // complex specialization template< typename ValueType > struct largv_impl< ValueType, typename boost::enable_if< traits::is_complex<ValueType> >::type > { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; // templated specialization template< typename VectorX, typename VectorY, typename VectorC > static void invoke( integer_t const n, VectorX& x, integer_t const incx, VectorY& y, integer_t const incy, VectorC& c, integer_t const incc ) { BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits< VectorX >::value_type, typename traits::vector_traits< VectorY >::value_type >::value) ); BOOST_ASSERT( traits::vector_size(x) >= 1+(n-1)*incx ); BOOST_ASSERT( traits::vector_size(y) >= 1+(n-1)*incy ); BOOST_ASSERT( traits::vector_size(c) >= 1+(n-1)*incc ); detail::largv( n, traits::vector_storage(x), incx, traits::vector_storage(y), incy, traits::vector_storage(c), incc ); } }; // template function to call largv template< typename VectorX, typename VectorY, typename VectorC > inline integer_t largv( integer_t const n, VectorX& x, integer_t const incx, VectorY& y, integer_t const incy, VectorC& c, integer_t const incc ) { typedef typename traits::vector_traits< VectorX >::value_type value_type; integer_t info(0); largv_impl< value_type >::invoke( n, x, incx, y, incy, c, incc ); return info; } }}}} // namespace boost::numeric::bindings::lapack #endif
// // Hrocker.cpp // CatchGirl // // Created by xin on 16/4/6. // // #include "Hrocker.hpp" #define PI 3.141596 HRocker * HRocker::createHRocker(const char * rockerImageName,const char * rockerBGImage ,Vec2 posisition){ HRocker * layer = HRocker::create(); if (layer) { layer->rockInit(rockerImageName, rockerBGImage, posisition); return layer; } CC_SAFE_DELETE(layer); return nullptr; } void HRocker::startRocker(bool _isStopOther){ auto rocker = (Sprite*) getChildByTag(tag_rocker); rocker->setVisible(true); auto rockerBG = (Sprite*)getChildByTag(tag_rockerBG); rockerBG->setVisible(true); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(HRocker::touchBegin,this); listener->onTouchMoved = CC_CALLBACK_2(HRocker::touchMvoed,this); listener->onTouchEnded = CC_CALLBACK_2(HRocker::touchEnd,this); listener->onTouchCancelled = CC_CALLBACK_2(HRocker::touchCanceld,this); getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, rocker); isCanMove = false; } void HRocker::stopRocker(){ } float HRocker::getRad(Vec2 pos1,Vec2 pos2){ float px1 = pos1.x; float py1 = pos1.y; float px2 = pos2.x; float py2 = pos2.y; float x = px2 - px1; float y = py2 - py1; float xie =sqrtf( pow(x, 2)+pow(y, 2)); float cosAngle = x/xie; float sinAngle = y/xie; float rad = acos(cosAngle); if (py2 < py1) { rad = - rad; } return rad; } Vec2 getAnglePosition(float r,float angle){ return Vec2(r*cos(angle) , r*sin(angle)); } void HRocker::rockInit(const char * rockerImageName,const char * rockerBGImageName,Vec2 position){ auto spRockerBG = Sprite::create(rockerBGImageName); spRockerBG->setPosition(position); spRockerBG->setVisible(false); this->addChild(spRockerBG, 0, tag_rockerBG); auto spRocker = Sprite::create(rockerImageName); spRocker->setPosition(position); spRocker->setVisible(false); this->addChild(spRocker,0,tag_rocker); rockerBGPosition = position; rockerBGR = spRockerBG->getContentSize().width/2; rockerDirection = -1; } bool HRocker::touchBegin(Touch * touch ,Event * event){ Vec2 point = touch->getLocation(); auto rocker = (Sprite*)this->getChildByTag(tag_rocker); if (rocker->getBoundingBox().containsPoint(point)) { isCanMove = true; log("begin"); } return true; } void HRocker::touchMvoed(Touch * touch ,Event * event){ log("move"); if (!isCanMove) { return; } Vec2 point = touch->getLocation(); auto rocker = (Sprite*)this->getChildByTag(tag_rocker); float angle = getRad(rockerBGPosition,point); if (sqrtf(pow(rockerBGPosition.x - point.x, 2) + pow(rockerBGPosition.y - point.y, 2)) >rockerBGR) { rocker->setPosition(ccpAdd(getAnglePosition(rockerBGR, angle), rockerBGPosition)); }else{ rocker->setPosition(point); } if (angle >= -PI/4 && angle < PI /4) { rockerDirection = rock_right; rockerRun = false; }else if (angle >= PI/4 && angle < 3*PI /4) { rockerDirection = rock_up; }else if (angle >= 3*PI/4 && angle < PI) { rockerDirection = rock_left; }else if (angle >= -3*PI/4 && angle < -PI /4) { rockerDirection = rock_down; } } void HRocker::touchEnd(Touch * touch ,Event * event){ if (!isCanMove) { return; } auto rocker = (Sprite*)this->getChildByTag(tag_rocker); auto rockerBG = (Sprite*)this->getChildByTag(tag_rockerBG); rocker->stopAllActions(); rocker->runAction(MoveTo::create(0.08f, rockerBGPosition)); rockerRun = false; rockerDirection = rock_stay; } void HRocker::touchCanceld(Touch * touch ,Event * event){ }
/* Copyright (C) 2014 Digipen Institute of Technology */ #include "LowPassFilter.h" LowPassFilter::LowPassFilter(int sampleSize): counter(0) // constructor { if(sampleSize < 0) { sampleSize = 0; } _data = new float[sampleSize-1]; } LowPassFilter::~LowPassFilter() // destructor { delete [] _data; } bool LowPassFilter::ApplyFilter(float data, float & XFilter) { if(counter == 0) { _data[0] = data; ++counter; return false; } else if(counter == 1) { _data[1] = data; ++counter; return false; } else if(counter == 2) { ++counter; return false; } else if(counter == 3) { _data[2] = data; ++counter; return false; } else if(counter == 4) { _data[3] = data; ++counter; return false; } else if(counter == 5) { //Filter XFilter = (1.0f/5.0f)*(_data[0] + _data[1] + data + _data[2] + _data[3]); counter = 0; return true; } return true; }
/* * SPDX-FileCopyrightText: 2020 Rolf Eike Beer <eike@sf-mail.de> * * SPDX-License-Identifier: GPL-3.0-or-later */ #pragma once #include <osm.h> #include <QAbstractTableModel> #include <QScopedPointer> enum { MEMBER_COL_TYPE = 0, MEMBER_COL_ID, MEMBER_COL_NAME, MEMBER_COL_ROLE, MEMBER_NUM_COLS }; class RelationMemberModel : public QAbstractTableModel { Q_OBJECT Q_DISABLE_COPY(RelationMemberModel) class RelationMemberModelPrivate; const QScopedPointer<RelationMemberModelPrivate> d_ptr; Q_DECLARE_PRIVATE(RelationMemberModel) public: RelationMemberModel(relation_t *rel, osm_t::ref o, QObject *parent = nullptr) __attribute__((nonnull(2))); ~RelationMemberModel() override; int rowCount(const QModelIndex &parent) const override; int columnCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) override; bool commit(); };
// // Copyright (c) 2003--2009 // Toon Knapen, Karl Meerbergen, Kresimir Fresl, // Thomas Klimpel and Rutger ter Borg // // 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) // // THIS FILE IS AUTOMATICALLY GENERATED // PLEASE DO NOT EDIT! // #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_OPGTR_HPP #define BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_OPGTR_HPP #include <boost/assert.hpp> #include <boost/mpl/bool.hpp> #include <boost/numeric/bindings/lapack/detail/lapack.h> #include <boost/numeric/bindings/lapack/workspace.hpp> #include <boost/numeric/bindings/traits/detail/array.hpp> #include <boost/numeric/bindings/traits/traits.hpp> #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace numeric { namespace bindings { namespace lapack { //$DESCRIPTION // overloaded functions to call lapack namespace detail { inline void opgtr( char const uplo, integer_t const n, float* ap, float* tau, float* q, integer_t const ldq, float* work, integer_t& info ) { LAPACK_SOPGTR( &uplo, &n, ap, tau, q, &ldq, work, &info ); } inline void opgtr( char const uplo, integer_t const n, double* ap, double* tau, double* q, integer_t const ldq, double* work, integer_t& info ) { LAPACK_DOPGTR( &uplo, &n, ap, tau, q, &ldq, work, &info ); } } // value-type based template template< typename ValueType > struct opgtr_impl { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; // user-defined workspace specialization template< typename VectorAP, typename VectorTAU, typename MatrixQ, typename WORK > static void invoke( char const uplo, VectorAP& ap, VectorTAU& tau, MatrixQ& q, integer_t& info, detail::workspace1< WORK > work ) { BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits< VectorAP >::value_type, typename traits::vector_traits< VectorTAU >::value_type >::value) ); BOOST_STATIC_ASSERT( (boost::is_same< typename traits::vector_traits< VectorAP >::value_type, typename traits::matrix_traits< MatrixQ >::value_type >::value) ); BOOST_ASSERT( uplo == 'U' || uplo == 'L' ); BOOST_ASSERT( traits::matrix_num_columns(q) >= 0 ); BOOST_ASSERT( traits::vector_size(ap) >= traits::matrix_num_columns(q)*(traits::matrix_num_columns(q)+ 1)/2 ); BOOST_ASSERT( traits::vector_size(tau) >= traits::matrix_num_columns(q)-1 ); BOOST_ASSERT( traits::leading_dimension(q) >= std::max(1, traits::matrix_num_columns(q)) ); BOOST_ASSERT( traits::vector_size(work.select(real_type())) >= min_size_work( traits::matrix_num_columns(q) )); detail::opgtr( uplo, traits::matrix_num_columns(q), traits::vector_storage(ap), traits::vector_storage(tau), traits::matrix_storage(q), traits::leading_dimension(q), traits::vector_storage(work.select(real_type())), info ); } // minimal workspace specialization template< typename VectorAP, typename VectorTAU, typename MatrixQ > static void invoke( char const uplo, VectorAP& ap, VectorTAU& tau, MatrixQ& q, integer_t& info, minimal_workspace work ) { traits::detail::array< real_type > tmp_work( min_size_work( traits::matrix_num_columns(q) ) ); invoke( uplo, ap, tau, q, info, workspace( tmp_work ) ); } // optimal workspace specialization template< typename VectorAP, typename VectorTAU, typename MatrixQ > static void invoke( char const uplo, VectorAP& ap, VectorTAU& tau, MatrixQ& q, integer_t& info, optimal_workspace work ) { invoke( uplo, ap, tau, q, info, minimal_workspace() ); } static integer_t min_size_work( integer_t const n ) { return n-1; } }; // template function to call opgtr template< typename VectorAP, typename VectorTAU, typename MatrixQ, typename Workspace > inline integer_t opgtr( char const uplo, VectorAP& ap, VectorTAU& tau, MatrixQ& q, Workspace work ) { typedef typename traits::vector_traits< VectorAP >::value_type value_type; integer_t info(0); opgtr_impl< value_type >::invoke( uplo, ap, tau, q, info, work ); return info; } // template function to call opgtr, default workspace type template< typename VectorAP, typename VectorTAU, typename MatrixQ > inline integer_t opgtr( char const uplo, VectorAP& ap, VectorTAU& tau, MatrixQ& q ) { typedef typename traits::vector_traits< VectorAP >::value_type value_type; integer_t info(0); opgtr_impl< value_type >::invoke( uplo, ap, tau, q, info, optimal_workspace() ); return info; } }}}} // namespace boost::numeric::bindings::lapack #endif
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cassert> using namespace std; int main(void) { //static_assert(常量表达式条件, "提示的字符串") static_assert(sizeof(void *) == 4, "64位系统不支持"); cout << "hello C++\n"; system("pause"); return 0; } int main01(void) { bool flag = false; //运行时,检查条件,如果条件为真,往下执行,如果条件为假,中断,提示错误 //assert(flag == true); //条件为假, 中断 assert(flag == false);//条件为真,往下执行 cout << "hello C++\n"; system("pause"); return 0; }
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define debug printf("I am here\n") int main() { ll m,n,i,k,l,j, pow[63], ans=0; fr(i,62) pow[i]=1<<i; cin>>n; ll a[n]; map<ll,ll>mp; fr(i,n){ cin>>a[i]; mp[a[i] ]++;} vector<ll>v; set<ll>s; fr(i,n) { ll flag=0; fr(j,62) { ll diff=pow[j]-a[i]; //cout<<pow[j]<<" "<<a[i]<<" "<<tmp<<" "<<endl; if(diff==a[i]) { if(mp[diff]>1) flag=1; } else { if(mp[diff]>0) flag=1; } } if(flag==0) ans++; } cout<<ans<<endl; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ /// gcov doesn't like this file... // LCOV_EXCL_START /** * @file * * Defines some macros to register versions of templated classes with the * serialization library, for all space dimensions. Also contains wrappers * around BOOST_CLASS_EXPORT and related functionality, which take care of * the differences introduced in new versions of Boost. * * In Boost 1.33.1 and 1.34, BOOST_CLASS_EXPORT should be placed in the .hpp * file for each class, and archive headers included only in tests, or special * 'archiver' class header files (e.g. CardiacSimulationArchiver.hpp). * * Serialization is broken in Boost 1.35. * * In Boost 1.36 (and up to 1.40) both the archive header includes and the * BOOST_CLASS_EXPORT should go in .cpp files. * * We also support 1.41 and above, which introduce BOOST_CLASS_EXPORT_KEY * and BOOST_CLASS_EXPORT_IMPLEMENT. Note 1.41.1 has bugs in serialization. * See https://chaste.cs.ox.ac.uk/trac/wiki/InstallGuides/DependencyVersions * for recommended versions. * * To handle all situations in Chaste: * 1. In .hpp files, include this header after the class definition. * 2. In .cpp files, after any other includes, include SerializationExportWrapperForCpp.hpp. * In both cases, CHASTE_CLASS_EXPORT should be used instead of BOOST_CLASS_EXPORT. * * There are also variant macros for common cases of templated classes: * - EXPORT_TEMPLATE_CLASS_SAME_DIMS * - EXPORT_TEMPLATE_CLASS_ALL_DIMS * - EXPORT_TEMPLATE_CLASS1 * - EXPORT_TEMPLATE_CLASS2 * - EXPORT_TEMPLATE_CLASS3 * * The latter 3 macros are usable in any situation where a class has up to 3 template parameters, * and you know what values will be needed. Unfortunately a fully general template solution seems * to be impossible in any Boost version (the library makes use of either explicit instantiation or * singleton class instantiation). */ #include <boost/version.hpp> //////////////////////////////////////////////////////////////////////////////// // Make sure includes happen in the correct place. This has to go before // the SERIALIZATIONEXPORTWRAPPER_HPP_ guard, since we need it to be seen // by both .hpp and .cpp files. #if BOOST_VERSION < 103600 // Boost 1.34 and older - export goes in headers #ifndef CHASTE_SERIALIZATION_CPP #include <boost/serialization/export.hpp> #endif // CHASTE_SERIALIZATION_CPP #elif BOOST_VERSION < 104100 // Boost 1.36-1.40 - export goes in .cpp, along with archive includes #ifdef CHASTE_SERIALIZATION_CPP #include "CheckpointArchiveTypes.hpp" #include <boost/serialization/export.hpp> #endif // CHASTE_SERIALIZATION_CPP #else // Boost 1.41 and newer - export goes in both, with archive includes in .cpp #include <boost/serialization/extended_type_info.hpp> // We get compile errors without this... #include <boost/serialization/export.hpp> #ifdef CHASTE_SERIALIZATION_CPP #include "CheckpointArchiveTypes.hpp" #endif // CHASTE_SERIALIZATION_CPP #endif // Done includes //////////////////////////////////////////////////////////////////////////////// #if BOOST_VERSION >= 104100 && defined(CHASTE_SERIALIZATION_CPP) // .cpp file needs to use BOOST_CLASS_EXPORT_IMPLEMENT, so we need // to redefine the macros from the .hpp file. Hence this can't go // in the include guard. #undef CHASTE_CLASS_EXPORT_TEMPLATED /** * General export for templated classes. * @param T a type * @param S a unique string for the class + specific template parameter values */ #define CHASTE_CLASS_EXPORT_TEMPLATED(T, S) \ BOOST_CLASS_EXPORT_IMPLEMENT(T) #undef CHASTE_CLASS_EXPORT_INTERNAL /** * What CHASTE_CLASS_EXPORT expands to when it isn't a no-op. * @param T the class to export */ #define CHASTE_CLASS_EXPORT_INTERNAL(T) \ BOOST_CLASS_EXPORT_IMPLEMENT(T) #endif // BOOST_VERSION >= 104100 && defined(CHASTE_SERIALIZATION_CPP) //////////////////////////////////////////////////////////////////////////////// #ifndef SERIALIZATIONEXPORTWRAPPER_HPP_ /** \cond */ #define SERIALIZATIONEXPORTWRAPPER_HPP_ /** \endcond */ // Code in the next block is only compiled when the .hpp is first seen //////////////////////////////////////////////////////////////////////////////// #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/stringize.hpp> // The interface changes yet again in Boost 1.41, and we need something in both .hpp and .cpp... #if BOOST_VERSION >= 104100 // .hpp file needs to use BOOST_CLASS_EXPORT_KEY /** * General export for templated classes. * @param T a type * @param S a unique string for the class + specific template parameter values */ #define CHASTE_CLASS_EXPORT_TEMPLATED(T, S) \ BOOST_CLASS_EXPORT_KEY(T) /** * What CHASTE_CLASS_EXPORT expands to when it isn't a no-op. * @param T the class to export */ #define CHASTE_CLASS_EXPORT_INTERNAL(T) \ BOOST_CLASS_EXPORT_KEY(T) #else // BOOST_VERSION < 103600 || (BOOST_VERSION >= 103800 && BOOST_VERSION < 104100) //Do exactly as we did before (so that archives created with 1.33 don't have to be re-generated) /** * General export for templated classes. * @param T a type * @param S a unique string for the class + specific template parameter values */ #define CHASTE_CLASS_EXPORT_TEMPLATED(T, S) \ BOOST_CLASS_EXPORT(T) /** * What CHASTE_CLASS_EXPORT expands to when it isn't a no-op. * @param T the class to export */ #define CHASTE_CLASS_EXPORT_INTERNAL(T) \ BOOST_CLASS_EXPORT(T) #endif // BOOST_VERSION >= 103600 && BOOST_VERSION < 103800 template<class> struct pack; /** * Argument pack for macros. Used to give a type for templated classes when exporting. * See http://lists.boost.org/Archives/boost/2004/08/70149.php for more. * * \todo Check if we need this on Boost>=1.38. Even if it's not needed there, we might still need it to load earlier archives. */ template<class T> struct pack<void (T)> { typedef T type; /**< Type definition. */ }; /** * Defines the export key for a class templated over 1 parameter. * @param CLASS the class * @param P1 the template parameter */ #define CHASTE_EXPORT_KEY_1(CLASS, P1) \ BOOST_PP_CAT(CLASS, P1) /** * Defines the export key for a class templated over 2 parameters. * @param CLASS the class * @param P1 the first template parameter * @param P2 the second template parameter */ #define CHASTE_EXPORT_KEY_2(CLASS, P1, P2) \ BOOST_PP_CAT(BOOST_PP_CAT(CLASS, P1), P2) /** * Defines the export key for a class templated over 3 parameters. * @param CLASS the class * @param P1 the first template parameter * @param P2 the second template parameter * @param P3 the third template parameter */ #define CHASTE_EXPORT_KEY_3(CLASS, P1, P2, P3) \ BOOST_PP_CAT(BOOST_PP_CAT(BOOST_PP_CAT(CLASS, P1), P2), P3) /** * Defines the export type for a class templated over 1 parameter. * @param CLASS the class * @param P1 the template parameter */ #define CHASTE_PACK_1(CLASS, P1) pack<void (CLASS< P1 >)>::type /** * Defines the export type for a class templated over 2 parameters. * @param CLASS the class * @param P1 the first template parameter * @param P2 the second template parameter */ #define CHASTE_PACK_2(CLASS, P1, P2) pack<void (CLASS< P1,P2 >)>::type /** * Defines the export type for a class templated over 3 parameters. * @param CLASS the class * @param P1 the first template parameter * @param P2 the second template parameter * @param P3 the third template parameter */ #define CHASTE_PACK_3(CLASS, P1, P2, P3) pack<void (CLASS< P1,P2,P3 >)>::type // End of include guard - code below here is executed in both .hpp and .cpp #endif // SERIALIZATIONEXPORTWRAPPER_HPP_ //////////////////////////////////////////////////////////////////////////////// // Since CHASTE_CLASS_EXPORT_TEMPLATED and CHASTE_CLASS_EXPORT_INTERNAL are re-defined for the .cpp file // in some Boost versions, the following macros will also need re-defining. #ifdef EXPORT_TEMPLATE_CLASS3_INTERNAL // Avoid re-definition when called from a .cpp file #undef EXPORT_TEMPLATE_CLASS3_INTERNAL #undef EXPORT_TEMPLATE_CLASS2_INTERNAL #undef EXPORT_TEMPLATE_CLASS1_INTERNAL #undef EXPORT_TEMPLATE_CLASS_ALL_DIMS_INTERNAL #undef EXPORT_TEMPLATE_CLASS_SAME_DIMS_INTERNAL #endif // EXPORT_TEMPLATE_CLASS3_INTERNAL // Macros for templated classes /** * Export a templated class with 3 parameters. * This is the definition of EXPORT_TEMPLATE_CLASS3 when it isn't a no-op. * @param CLASS the class (without parameters) * @param E first template parameter * @param S second template parameter * @param P third template parameter */ #define EXPORT_TEMPLATE_CLASS3_INTERNAL(CLASS, E, S, P) \ CHASTE_CLASS_EXPORT_TEMPLATED( CHASTE_PACK_3(CLASS, E, S, P), CHASTE_EXPORT_KEY_3(CLASS, E, S, P) ) /** * Export a templated class with 2 parameters. * This is the definition of EXPORT_TEMPLATE_CLASS2 when it isn't a no-op. * @param CLASS the class (without parameters) * @param E first template parameter * @param S second template parameter */ #define EXPORT_TEMPLATE_CLASS2_INTERNAL(CLASS, E, S) \ CHASTE_CLASS_EXPORT_TEMPLATED( CHASTE_PACK_2(CLASS, E, S), CHASTE_EXPORT_KEY_2(CLASS, E, S) ) /** * Export a templated class with 1 parameter. * This is the definition of EXPORT_TEMPLATE_CLASS1 when it isn't a no-op. * @param CLASS the class (without parameters) * @param D template parameter */ #define EXPORT_TEMPLATE_CLASS1_INTERNAL(CLASS, D) \ CHASTE_CLASS_EXPORT_TEMPLATED( CHASTE_PACK_1(CLASS, D), CHASTE_EXPORT_KEY_1(CLASS, D) ) /** * Export a class templated over both element and space dimension, for all valid * combinations. * This is the definition of EXPORT_TEMPLATE_CLASS_ALL_DIMS when it isn't a no-op. * @param CLASS the class (without parameters) */ #define EXPORT_TEMPLATE_CLASS_ALL_DIMS_INTERNAL(CLASS) \ EXPORT_TEMPLATE_CLASS2(CLASS, 1, 1) \ EXPORT_TEMPLATE_CLASS2(CLASS, 1, 2) \ EXPORT_TEMPLATE_CLASS2(CLASS, 1, 3) \ EXPORT_TEMPLATE_CLASS2(CLASS, 2, 2) \ EXPORT_TEMPLATE_CLASS2(CLASS, 2, 3) \ EXPORT_TEMPLATE_CLASS2(CLASS, 3, 3) /** * Export a class templated over a single dimension, for 1, 2 and 3 dimensions. * This is the definition of EXPORT_TEMPLATE_CLASS_SAME_DIMS when it isn't a no-op. * @param CLASS the class (without parameters) */ #define EXPORT_TEMPLATE_CLASS_SAME_DIMS_INTERNAL(CLASS) \ EXPORT_TEMPLATE_CLASS1(CLASS, 1) \ EXPORT_TEMPLATE_CLASS1(CLASS, 2) \ EXPORT_TEMPLATE_CLASS1(CLASS, 3) // Now define the macros that users actually call. // Again this goes outside the include guard, so it is seen by both .hpp and .cpp files. // However, we don't want to define things twice, so... #if !defined(CHASTE_CLASS_EXPORT) || defined(CHASTE_SERIALIZATION_CPP) #ifdef CHASTE_SERIALIZATION_CPP // Remove the definitions from when we were included via an .hpp file #undef CHASTE_CLASS_EXPORT #undef EXPORT_TEMPLATE_CLASS_SAME_DIMS #undef EXPORT_TEMPLATE_CLASS_ALL_DIMS #undef EXPORT_TEMPLATE_CLASS1 #undef EXPORT_TEMPLATE_CLASS2 #undef EXPORT_TEMPLATE_CLASS3 #endif // CHASTE_SERIALIZATION_CPP #if (BOOST_VERSION < 103600 && ! defined(CHASTE_SERIALIZATION_CPP)) || \ (BOOST_VERSION >= 103600 && defined(CHASTE_SERIALIZATION_CPP)) || \ (BOOST_VERSION >= 104100) // Boost 1.34 and older - export goes in headers // Boost 1.36 and newer - export goes in .cpp // Boost 1.41 and newer - key goes in .hpp, implement goes in .cpp /** * Define the serialization export key for this class. * @param T the class */ #define CHASTE_CLASS_EXPORT(T) CHASTE_CLASS_EXPORT_INTERNAL(T) /** * Export a class templated over a single dimension, for 1, 2 and 3 dimensions. * @param CLASS the class (without parameters) */ #define EXPORT_TEMPLATE_CLASS_SAME_DIMS(CLASS) EXPORT_TEMPLATE_CLASS_SAME_DIMS_INTERNAL(CLASS) /** * Export a class templated over both element and space dimension, for all valid * combinations. * @param CLASS the class (without parameters) */ #define EXPORT_TEMPLATE_CLASS_ALL_DIMS(CLASS) EXPORT_TEMPLATE_CLASS_ALL_DIMS_INTERNAL(CLASS) /** * Export a templated class with 1 parameter. * @param CLASS the class (without parameters) * @param D template parameter */ #define EXPORT_TEMPLATE_CLASS1(CLASS, D) EXPORT_TEMPLATE_CLASS1_INTERNAL(CLASS, D) /** * Export a templated class with 2 parameters. * @param CLASS the class (without parameters) * @param E first template parameter * @param S second template parameter */ #define EXPORT_TEMPLATE_CLASS2(CLASS, E, S) EXPORT_TEMPLATE_CLASS2_INTERNAL(CLASS, E, S) /** * Export a templated class with 3 parameters. * @param CLASS the class (without parameters) * @param E first template parameter * @param S second template parameter * @param P third template parameter */ #define EXPORT_TEMPLATE_CLASS3(CLASS, E, S, P) EXPORT_TEMPLATE_CLASS3_INTERNAL(CLASS, E, S, P) #else /** * No-op for this Boost version in this setting. * @param T */ #define CHASTE_CLASS_EXPORT(T) /** * No-op for this Boost version in this setting. * @param CLASS */ #define EXPORT_TEMPLATE_CLASS_SAME_DIMS(CLASS) /** * No-op for this Boost version in this setting. * @param CLASS */ #define EXPORT_TEMPLATE_CLASS_ALL_DIMS(CLASS) /** * No-op for this Boost version in this setting. * @param CLASS * @param D */ #define EXPORT_TEMPLATE_CLASS1(CLASS, D) /** * No-op for this Boost version in this setting. * @param CLASS * @param E * @param S */ #define EXPORT_TEMPLATE_CLASS2(CLASS, E, S) /** * No-op for this Boost version in this setting. * @param CLASS * @param E * @param S * @param P */ #define EXPORT_TEMPLATE_CLASS3(CLASS, E, S, P) #endif // Long if! #endif // !defined(CHASTE_CLASS_EXPORT) || defined(CHASTE_SERIALIZATION_CPP) // LCOV_EXCL_STOP
/* Self-service bike station notifier ESP-8266 that connects to a WiFi network and chats with an MQTT server (publish & subscribe) Antoine de Chassey. */ #include <ArduinoJson.h> #include <ESP8266WiFi.h> #include <PubSubClient.h> #include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal #include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic // Leds #define FASTLED_ESP8266_NODEMCU_PIN_ORDER #include <FastLED.h> #define NUM_LEDS 2 #define DATA_PIN 1 CRGB leds[NUM_LEDS]; const String application = "Self-service bike notifier"; // name of the application, used in the log MQTT payloads and topics // WiFi setup const String ssid = "ESP_" + application; const char* password = ""; const char* client_mac; // MQTT setup const char* mqtt_server = "broker.hivemq.com"; const int mqtt_port = 1883; const char* mqtt_username = "esp"; // used while connecting to the broker const char* mqtt_password = ""; // leave empty if not needed const char* mqtt_topic = "notifier"; // used to fetch the coming data from the server const char* mqtt_topic_log = "log"; // used to log the hardware status to broker char* mqtt_payload; boolean retained = false; WiFiClient espClient; PubSubClient client(espClient); void setup() { // Leds pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS); FastLED.clear(); // Setup serial port Serial.begin(115200); // Setup WiFi WiFiManager wifiManager; //reset saved settings //wifiManager.resetSettings(); wifiManager.autoConnect(String(ssid).c_str(), password); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); Serial.println("Application name: "); Serial.print(application); Serial.println("MQTT Server: "); Serial.print(mqtt_server); Serial.println("MQTT Topic: "); Serial.print(mqtt_topic) ; client_mac = client_MAC(); Serial.println("ESP mac: "); Serial.print(client_mac); // Connect to the MQTT broker and send status connect_MQTT(); digitalWrite(LED_BUILTIN, HIGH); // Turn the LED_BUILTIN off (Note that HIGH is the voltage level) } void loop() { if (!client.connected()) { connect_MQTT(); } client.loop(); }
#include "HeaderHandler.h" #include "Registry.h" #include <iostream> using RegistryeHandlerRegistry = Registry<std::string, IHandler>; template<>template<> bool RegistryeHandlerRegistry::SelfRegister<HeaderHandler>::_registered = RegistryeHandlerRegistry::SelfRegister<HeaderHandler>::selfRegister(); HeaderHandler::HeaderHandler() {} HeaderHandler::~HeaderHandler() {} const std::string& HeaderHandler::getRegistryType() const { static std::string name {"Header"}; return name; } HandlerResult HeaderHandler::handle(std::string msg) { HandlerResult result(HandlerResult::Fail, std::string()); std::cout << "HeaderHandler handled." << std::endl; return result; }
#ifndef ORDERUI_H #define ORDERUI_H class OrderUI { public: OrderUI(); void start_orderUI(); private: }; #endif // ORDERUI_H
// This file has been generated by Py++. #ifndef ListboxTextItem_hpp__pyplusplus_wrapper #define ListboxTextItem_hpp__pyplusplus_wrapper void register_ListboxTextItem_class(); #endif//ListboxTextItem_hpp__pyplusplus_wrapper
/* This file is part of the ArduinoBLE library. Copyright (c) 2018 Arduino SA. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _HCI_H_ #define _HCI_H_ #include <Arduino.h> class HCIClass { public: HCIClass(); virtual ~HCIClass(); int begin(); void end(); void poll(); void poll(unsigned long timeout); int reset(); int readLocalVersion(uint8_t& hciVer, uint16_t& hciRev, uint8_t& lmpVer, uint16_t& manufacturer, uint16_t& lmpSubVer); int readBdAddr(uint8_t addr[6]); int readRssi(uint16_t handle); int setEventMask(uint64_t eventMask); int readLeBufferSize(uint16_t& pktLen, uint8_t& maxPkt); int leSetRandomAddress(uint8_t addr[6]); int leSetAdvertisingParameters(uint16_t minInterval, uint16_t maxInterval, uint8_t advType, uint8_t ownBdaddrType, uint8_t directBdaddrType, uint8_t directBdaddr[6], uint8_t chanMap, uint8_t filter); int leSetAdvertisingData(uint8_t length, uint8_t data[]); int leSetScanResponseData(uint8_t length, uint8_t data[]); int leSetAdvertiseEnable(uint8_t enable); int leSetScanParameters(uint8_t type, uint16_t interval, uint16_t window, uint8_t ownBdaddrType, uint8_t filter); int leSetScanEnable(uint8_t enabled, uint8_t duplicates); int leCreateConn(uint16_t interval, uint16_t window, uint8_t initiatorFilter, uint8_t peerBdaddrType, uint8_t peerBdaddr[6], uint8_t ownBdaddrType, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t supervisionTimeout, uint16_t minCeLength, uint16_t maxCeLength); int leConnUpdate(uint16_t handle, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t supervisionTimeout); int leCancelConn(); int sendAclPkt(uint16_t handle, uint8_t cid, uint8_t plen, void* data); int disconnect(uint16_t handle); void debug(Stream& stream); void noDebug(); private: int sendCommand(uint16_t opcode, uint8_t plen = 0, void* parameters = NULL); void handleAclDataPkt(uint8_t plen, uint8_t pdata[]); void handleNumCompPkts(uint16_t handle, uint16_t numPkts); void handleEventPkt(uint8_t plen, uint8_t pdata[]); void dumpPkt(const char* prefix, uint8_t plen, uint8_t pdata[]); Stream* _debug; int _recvIndex; uint8_t _recvBuffer[3 + 255]; uint16_t _cmdCompleteOpcode; int _cmdCompleteStatus; uint8_t _cmdResponseLen; uint8_t* _cmdResponse; uint8_t _maxPkt; uint8_t _pendingPkt; uint8_t _aclPktBuffer[255]; }; extern HCIClass HCI; #endif
#include "difference_of_squares.h" int squares::square_of_sum(int number) { int sum = 0; for (int i = 1; i <= number; i++) sum += i; return pow(sum, 2); } int squares::sum_of_squares(int number) { if (number > 1) return pow(number, 2) + sum_of_squares(number - 1); else return 1; } int squares::difference(int number) { return square_of_sum(number) - sum_of_squares(number); }
#include <cstdio> #include <algorithm> using namespace std; const int MAX_N = 100; const int MAX_W = 10000; int n,W; int w[MAX_N],v[MAX_N]; int dp[MAX_W +1]; void read(); void solve(); int main(){ read(); solve(); return 0; } void read(){ scanf("%d\n", &n); for(int i=0; i<n; i++){ scanf("%d %d", &w[i],&v[i]); } scanf("%d\n", &W); } void solve(){ for (int i=0; i<n; i++){ for (int j=w[i]; j <= W; j++){ dp[j] = max(dp[j], dp[j-w[i]]+v[i]); } } printf("%d\n", dp[W]); }
#ifndef _CHARACTER_HEADER #define _CHARACTER_HEADER #include "smPacket.h" #define PLAYBUFF_SIZE 256 #define PLAYBUFF_MASK 255 //초당 프로그램 진행 카운터 #define PLAYCOUNT_PER_SECOND 70 /* #define DIST_TRANSLEVEL_NEAR 0x12000 //((64*3)^2)*2 #define DIST_TRANSLEVEL_HIGH 0xC8000 //((64*8)^2)*2 #define DIST_TRANSLEVEL_MHIGH 0x120000 //((64*12)^2)*2 #define DIST_TRANSLEVEL_MID 0x200000 //((64*16)^2)*2 #define DIST_TRANSLEVEL_LOW 0x320000 //((64*20)^2)*2 #define DIST_TRANSLEVEL_DISCONNECT 0x320000 //((64*20)^2)*2 #define DIST_TRANSLEVEL_CONNECT 0x200000 //((64*16)^2)*2 */ #define DIST_TRANSLEVEL_NEAR 0x12000 //((64*3)^2)*2 #define DIST_TRANSLEVEL_HIGH 0x48000 //((64*6)^2)*2 #define DIST_TRANSLEVEL_MHIGH 0xC8000 //((64*10)^2)*2 #define DIST_TRANSLEVEL_MID 0x120000 //((64*12)^2)*2 #define DIST_TRANSLEVEL_LOW 0x320000 //((64*20)^2)*2 #define DIST_TRANSLEVEL_DISCONNECT 0x320000 //((64*20)^2)*2 #define DIST_TRANSLEVEL_CONNECT 0x120000 //((64*12)^2)*2 //파티 공유 제한 거리 #define PARTY_GETTING_DIST (18*64*18*64) //파티 공유 제한 거리 ( 표시용 ) #define PARTY_GETTING_DIST2 (17*64*17*64) #define PLAYSERVER_SENDCOUNTER (70*1) //1초다 //###################################################################################### //작 성 자 : 오 영 석 #define ICE_FOOT_COUNT_MAX 20 #define ICE_FOOT_LIFE_TIME 5000 #define ICE_FOOT_ALPHA_STEP (200.f / float(ICE_FOOT_LIFE_TIME)) struct SIceFootInfo { int Life; int TypeNum; DWORD dwPlayTime; POINT3D FootPos; POINT3D FootAngle; }; //###################################################################################### //#define DPAT_MAX 1024 #define DPAT_MAX 2048 struct smDPAT { //###################################################################################### //작 성 자 : 오 영 석 smDPAT *lpTalkLink; // 표정 패턴 포인터. //###################################################################################### smDPAT *smDinaLink; smPAT3D *Pat; char szPatName[64]; int UseCount; DWORD dwSpeedFindSum; //고속 검색용 첵크섬 smMODELINFO *lpModelInfo; DWORD LastUsedTime; }; class smPATTERN { public: smPATTERN *BipPattern; //동작 모션 패턴 포인터 smDPAT DinaPat[ DPAT_MAX ]; //###################################################################################### // 작 성 자 : 오 영 석 smPATTERN(void); ~smPATTERN(void); //###################################################################################### void Init(); int Close(); int GetNew(); int FindFromName( char *szName ); int FindFromCode( DWORD dwCode ); smDPAT *LoadCharactor( char *szFileName ) ; smDPAT *LoadBipPattern( char *szFileName ) ; }; #define DISP_MODE_PATMAIN 1 #define DISP_MODE_PATSUB 2 //###################################################################################### //작 성 자 : 오 영 석 #define DISP_MODE_PATTALK 4 //###################################################################################### #define CHAR_FRAME_MASK 0x00FFFFFF #define CHAR_FRAME_SELSHIFT 24 struct smCHARTOOL { smOBJ3D *ObjBip; smPAT3D *PatTool; DWORD dwItemCode; int SizeMax,SizeMin; int ColorBlink; short sColors[4]; DWORD DispEffect; int BlinkScale; int EffectKind; int TexMixCode,TexScroll; }; //////////// 메카니션 스킬 ////////////// #define SKILL_PLAY_EXTREME_SHIELD 0x01 #define SKILL_PLAY_MECHANIC_BOMB 0x02 #define SKILL_PLAY_PHYSICAL_ABSORB 0x03 #define SKILL_PLAY_POISON_ATTRIBUTE 0x04 #define SKILL_PLAY_GREAT_SMASH 0x05 #define SKILL_PLAY_MAXIMIZE 0x06 #define SKILL_PLAY_AUTOMATION 0x07 #define SKILL_PLAY_SPARK 0x08 #define SKILL_PLAY_METAL_ARMOR 0x09 #define SKILL_PLAY_GRAND_SMASH 0x0A #define SKILL_PLAY_SPARK_SHIELD 0x0B #define SKILL_PLAY_IMPULSION 0x0C #define SKILL_PLAY_COMPULSION 0x0D #define SKILL_PLAY_MAGNETIC_SPHERE 0x0E #define SKILL_PLAY_METAL_GOLEM 0x0F //////////// 파이크맨 스킬 ////////////// #define SKILL_PLAY_PIKEWIND 0x12 // 박재원 - 매직 포스 사용시 1차스킬로 인식 못하여서 할당된 코드 수정(0x10 -> 0x12 로 수정함) #define SKILL_PLAY_CRITICAL_HIT 0x13 #define SKILL_PLAY_JUMPING_CRASH 0x14 #define SKILL_PLAY_GROUND_PIKE 0x15 #define SKILL_PLAY_TORNADO 0x16 #define SKILL_PLAY_EXPANSION 0x18 #define SKILL_PLAY_VENOM_SPEAR 0x19 #define SKILL_PLAY_BLADE_OF_BLAZE 0x1A //(구) #define SKILL_PLAY_VANISH 0x1A //SKILL_PLAY_BLADE_OF_BLAZE 랑 같은 코드 #define SKILL_PLAY_CHAIN_LANCE 0x1B #define SKILL_PLAY_ASSASSIN_EYE 0x1C #define SKILL_PLAY_CHARGING_STRIKE 0x1D #define SKILL_PLAY_VAGUE 0x1E #define SKILL_PLAY_SHADOW_MASTER 0x1F //////////// 파이터 스킬 ////////////// #define SKILL_PLAY_RAVING 0x23 #define SKILL_PLAY_IMPACT 0x24 #define SKILL_PLAY_TRIPLE_IMPACT 0x25 #define SKILL_PLAY_BRUTAL_SWING 0x26 #define SKILL_PLAY_ROAR 0x27 #define SKILL_PLAY_RAGEOF_ZECRAM 0x28 #define SKILL_PLAY_CONCENTRATION 0x29 #define SKILL_PLAY_AVANGING_CRASH 0x2A #define SKILL_PLAY_SWIFT_AXE 0x2B #define SKILL_PLAY_BONE_SMASH 0x2C #define SKILL_PLAY_DESTROYER 0x2D #define SKILL_PLAY_BERSERKER 0x2E #define SKILL_PLAY_CYCLONE_STRIKE 0x2F //////////// 아쳐 스킬 ////////////// #define SKILL_PLAY_SCOUT_HAWK 0x41 #define SKILL_PLAY_WIND_ARROW 0x43 #define SKILL_PLAY_PERFECT_AIM 0x44 #define SKILL_PLAY_FALCON 0x46 #define SKILL_PLAY_ARROWOF_RAGE 0x47 #define SKILL_PLAY_AVALANCHE 0x48 #define SKILL_PLAY_ELEMENTAL_SHOT 0x49 #define SKILL_PLAY_GOLDEN_FALCON 0x4A #define SKILL_PLAY_BOMB_SHOT 0x4B #define SKILL_PLAY_PERFORATION 0x4C #define SKILL_PLAY_RECALL_WOLVERIN 0x4D #define SKILL_PLAY_PHOENIX_SHOT 0x4E #define SKILL_PLAY_FORCE_OF_NATURE 0x4F ////////////// 나이트 스킬 ////////////// #define SKILL_PLAY_SWORD_BLAST 0x51 #define SKILL_PLAY_HOLY_BODY 0x52 #define SKILL_PLAY_DOUBLE_CRASH 0x54 #define SKILL_PLAY_HOLY_VALOR 0x55 #define SKILL_PLAY_BRANDISH 0x56 #define SKILL_PLAY_PIERCING 0x57 #define SKILL_PLAY_DRASTIC_SPIRIT 0x58 #define SKILL_PLAY_FLAME_BRANDISH 0x59 #define SKILL_PLAY_DIVINE_INHALATION 0x5A #define SKILL_PLAY_HOLY_INCANTATION 0x5B #define SKILL_PLAY_GRAND_CROSS 0x5C #define SKILL_PLAY_DIVINE_PIERCING 0x5D #define SKILL_PLAY_GODLY_SHIELD 0x5E #define SKILL_PLAY_GODS_BLESS 0x5F #define SKILL_PLAY_SWORD_OF_JUSTICE 0x50 ////////////// 아탈란타 스킬 /////////////// #define SKILL_PLAY_SHIELD_STRIKE 0x61 #define SKILL_PLAY_FARINA 0x62 #define SKILL_PLAY_VIGOR_SPEAR 0x64 #define SKILL_PLAY_WINDY 0x65 #define SKILL_PLAY_TWIST_JAVELIN 0x66 #define SKILL_PLAY_SOUL_SUCKER 0x67 #define SKILL_PLAY_FIRE_JAVELIN 0x68 #define SKILL_PLAY_SPLIT_JAVELIN 0x69 #define SKILL_PLAY_TRIUMPH_OF_VALHALLA 0x6A #define SKILL_PLAY_LIGHTNING_JAVELIN 0x6B #define SKILL_PLAY_STORM_JAVELIN 0x6C #define SKILL_PLAY_HALL_OF_VALHALLA 0x6D #define SKILL_PLAY_X_RAGE 0x6E #define SKILL_PLAY_FROST_JAVELIN 0x6F #define SKILL_PLAY_VENGEANCE 0x60 ////////////// 프리스티스 스킬 /////////////// #define SKILL_PLAY_HEALING 0x71 #define SKILL_PLAY_HOLY_BOLT 0x72 #define SKILL_PLAY_MULTI_SPARK 0x73 #define SKILL_PLAY_HOLY_MIND 0x74 //#define SKILL_PLAY_MEDITATION 0x75 #define SKILL_PLAY_DIVINE_LIGHTNING 0x76 #define SKILL_PLAY_HOLY_REFLECTION 0x77 #define SKILL_PLAY_GREAT_HEALING 0x78 #define SKILL_PLAY_VIGOR_BALL 0x79 #define SKILL_PLAY_RESURRECTION 0x7A #define SKILL_PLAY_EXTINCTION 0x7B #define SKILL_PLAY_VIRTUAL_LIFE 0x7C #define SKILL_PLAY_GLACIAL_SPIKE 0x7D #define SKILL_PLAY_REGENERATION_FIELD 0x7E #define SKILL_PLAY_CHAIN_LIGHTNING 0x7F #define SKILL_PLAY_SUMMON_MUSPELL 0x70 ////////////// 매지션 스킬 /////////////// #define SKILL_PLAY_AGONY 0x81 #define SKILL_PLAY_FIRE_BOLT 0x82 #define SKILL_PLAY_ZENITH 0x83 #define SKILL_PLAY_FIRE_BALL 0x84 //#define SKILL_PLAY_MENTAL_MASTERY 0x85 #define SKILL_PLAY_COLUMN_OF_WATER 0x86 #define SKILL_PLAY_ENCHANT_WEAPON 0x87 #define SKILL_PLAY_DEAD_RAY 0x88 #define SKILL_PLAY_ENERGY_SHIELD 0x89 #define SKILL_PLAY_DIASTROPHISM 0x8A #define SKILL_PLAY_SPIRIT_ELEMENTAL 0x8B #define SKILL_PLAY_DANCING_SWORD 0x8C #define SKILL_PLAY_FIRE_ELEMENTAL 0x8D #define SKILL_PLAY_FLAME_WAVE 0x8E #define SKILL_PLAY_DISTORTION 0x8F #define SKILL_PLAY_METEO 0x80 ///////////// 모션 확장 ////////////////// #define SKILL_PLAY_DIVINE_PIERCING2 0x90 #define SKILL_PLAY_DIVINE_PIERCING3 0x91 //////////////////////////////////////////// #define SKILL_PLAY_BLESS_ABSORB 0xA0 #define SKILL_PLAY_BLESS_DAMAGE 0xA1 #define SKILL_PLAY_BLESS_EVADE 0xA2 #define SKILL_PLAY_BLESS_SIEGE_ITEM 0xA8 #define SKILL_PLAY_FIRE_CRYSTAL 0xB0 #define SKILL_PLAY_LIGHTNING_CRYSTAL 0xB1 #define SKILL_PLAY_ICE_CRYSTAL 0xB2 #define SKILL_PLAY_CHAOSCARA_VAMP 0xB8 #define SKILL_PLAY_PET_ATTACK 0xC0 #define SKILL_PLAY_PET_ATTACK2 0xC1 #define SKILL_PLAY_SOD_ITEM 0xD0 //#define SKILL_PLAY_METEO 0xE0 #define SKILL_PLAY_SPEACIAL 0xF0 #define SKILL_PLAY_LOVELY_LIFE 0xF1 #define SKILL_EFFECT_FIREFLOWER 0x12000010 //스킬 적용 마스크 #define SKILL_APPMASK_EXTREME_SHIELD 0x0001 #define SKILL_APPMASK_PHYSICAL_ABSORB 0x0002 #define SKILL_APPMASK_AUTOMATION 0x0004 #define SKILL_APPMASK_ANGER 0x0008 #define SKILL_APPMASK_SPARK_SHIELD 0x0010 #define SKILL_APPMASK_GODLY_SHIELD 0x0020 #define SKILL_APPMASK_HOLY_BODY 0x00010000 //스킬 적용 마스크 ( 몬스터 속성 ) //#define SKILL_APPMASK_ICE 0x0010 //데미지를 준 유저를 기억시킴 struct ATTACK_DAMAGE_LIST { DWORD dwUserCode; int DamageCount; int Count; }; #define ATTACK_DAMAGE_LIST_MAX 100 class smCHAR { DWORD Head; public: int DisplayFlag; //화면 출력 여부 //int DisplayHead; //머리 츨력 여부 int DisplayTools; //무기 출력 여부 smSTAGE3D *lpStage; //해당 배경 포인트 DWORD dwObjectSerial; //객체 고유 번호 int AutoPlayer; //자동 플레이어 ( TRUE 일 경우 서버로 부터 움직임을 받는다 ) smPAT3D *Pattern; //일차 패턴 smPAT3D *Pattern2; //머리 패턴 smPAT3D *AnimPattern; //###################################################################################### //작 성 자 : 오 영 석 smPAT3D *TalkPattern; // 표정 패턴. ( 다이나믹 패턴은 ini 에 따라서 lpDinaPattern 또는 lpDinaPattern2 ) //###################################################################################### smDPAT *lpDinaPattern; //다이나믹 패턴 포인터 (패턴의 관리자) smDPAT *lpDinaPattern2; //다이나믹 패턴 포인터 머리(패턴의 관리자) smDPAT *lpDinaLeftPattern; //왼쪽 무기 smDPAT *lpDinaRightPattern; //오른쪽 무기 smCHARTOOL HvLeftHand; //왼손에 착용 도구 smCHARTOOL HvRightHand; //오른손에 착용 도구 smMATRIX HvLeftHand_Matrix; //왼손 무기 행렬 복사 smMATRIX HvRightHand_Matrix; //오른손 무기 행렬 복사 int Rend_HvLeftHand; //무기 렌더링 유무 int Rend_HvRightHand; //무기 렌더링 유무 smOBJ3D *BackObjBip[3]; //등쪽 무기 착용 smOBJ3D *AttackObjBip; //공격 패드 오브젝트 smOBJ3D *ShieldObjBip; //방패 패드 오브젝트 int AttackToolRange; //공격 사정거리 int AttackAnger; //공격시 분도치 ( 그냥 보기 좋게 하기 위함 ) int AttackIce; //얼음 공격 받음 int Flag; int pX,pY,pZ; // 좌표 int AttackX,AttackY,AttackZ; // 좌표 int PHeight; // 바닥 높이 좌표 int FallHeight; // 떨어진 높이 int OnStageField; // 밟고 서있는 바닥 필드 번호 int OnStageFieldState; //바닥 필드의 속성값 int PatLoading; //현재 로딩 중인지... int PatWidth; //캐릭터 넓이 int PatHeight; //캐릭터 높이 int PatSizeLevel; //캐릭터 크기 단계 ( 0 ~ 3 ) int OverLapPosi; //다른 캐릭터와 위치가 겹침 int OverLapPosi2; //다른 캐릭터와 위치가 겹침 smCHAR *lpCharOverLap; //겹친 캐릭터의 포인트 POINT3D Posi; POINT3D Angle; int MoveMode; //이동 모드 ( 0 - 걷기 1-달리기 ) int MoveFlag; int MoveCnt; // 통신시 받은 데이타가 없을경우 자동 이동할때 거리 제한 카운터 int tx,tz; // 목표 이동 좌표 int TargetMoveCount; //목표 이동 좌표 카운터 int WaterHeight; //물 높이 DWORD dwActionItemCode; //주 움직임에 관련된 코드 DWORD dwItemSetting; //아이템 세팅 방법( 0-구분 없음 1-마을필드 구분 ) DWORD dwActionItemTwoHand; //양손 무기 첵크 short wStickItems[4]; //장착 아이템 번호 //화살 및 던지기 모드 int ShootingMode; //발사형 공격 모드 ( TRUE ) int ShootingFlag; //현재 발사됬는지 여부 int ShootingKind; //발사 구분 POINT3D ShootingPosi; //발사 위치 POINT3D ShootingAngle; //발사 방향 int ShootingCount; //발사 카운터 smCHAR *chrAttackTarget; //공격 목표 캐릭터 int AttackCritcal; //크리티컬 공격 유무 int AttackCriticalCount;//크리티컬 공격 카운터 ( 연속 공격시 ) int AttackExp; //공격시 경험치 int AttackSkil; //스킬 공격 코드 int AttackEffect; //공격시 특수 이펙트 표시 int LastSkillParam; //최근 스킬공격 구분 코드 ( 카오스카라 땜에 땜빵용으로 추가 ) int RecvExp; //경험치 부여 받음 POINT3D ptNextTarget; //다음 이동 목표 POINT3D PosiAround; // 주변 위치 이곳을 멀리 벗어나지 못하게 함 (근처에서만..) int DistAroundDbl; // 주변 경계 거리 한계치 int TragetTraceMode; //추적 모드 값 (서버사용 ) POINT3D PosBeginMove; //이동 시작시의 좌표 DWORD PosBeginCount; DWORD dwNextMotionCode; //다음 동작 예약 int ChargingFlag; //차징 플랙 //###################################################################################### //작 성 자 : 오 영 석 DWORD TalkFrame; // 표정 프레임 DWORD TalkSoundSum; SMotionStEndInfo FrameInfo; //###################################################################################### int action; DWORD frame; int FrameCnt; int FrameStep; //프레임 바뀜 값 int MoveSpeed; //이동 움직임 값 int AttackSpeed; //공격 속도 int ActionPattern; // 움직임 패턴 DWORD dwEventFrameExt[4]; //이벤트 프레임 확장 int NearPlayCount; //근처에 다른 유저가 존재 하는지 확인 ( NPC/몬스터 ) int ReopenCount; //몬스터 시간이 지나 재출현 시킬 카운터 int AutoMoveStep; //자동 이동시 스텝 카운터 short sMoveStepCount[2]; //이동 스텝 루프 가운터 int Counter; int FrameCounter; //모션 시작부터 끝날때 까지 사용되는 카운터 int RendSucess; //화면상의 렌더링 성공 여부 RECT RendRect2D; //렌더링된 2D 좌표 영역 POINT3D RendPoint; //렌더링된 2D 좌표 ( x,y,z ) int FlagShow; //화면표시 플랙 ( 0 - 화면 출력 불허 ) //채팅 char szChatMessage[256]; //채팅 문자열 DWORD dwChatMessageTimer; //채팅 문자를 표시 종료시간 기록 //상점 char szTradeMessage[128]; //상점 메세지 문자열 DWORD dwTradeMsgCode; //상점 메세지 코드 char srTransBuff[TRANS_BUFF_SIZE]; //전송할 데이타 대기용 버퍼 int srTransBuffSize; //전송할 데이타 대기용 버퍼 크기 //통신 관련 int ServerCode; //해당 캐릭터 서버 코드 smWINSOCK *TransSock; int TransSendWait; //통신 포트 기다림 int TransLastSendCnt; //통신 마지막 전송 시간 int TransLastSendTime; //통신 마지막 전송의 시간차 ( 속도 첵크용 ) int TransMinCnt; //최소 교신 카운터 int TransLevel; //통신의 중요 단계 int TransDelayMax; //통신 지연 최대치 ( 이시간을 넘으면 재시도 ) smPLAYBUFF PlayBuff[PLAYBUFF_SIZE]; //플레이 진행 상황을 버퍼에 저장하여 통신시 버퍼링함 int PlayBuffCnt; //PlayBuff 의 카운터 int PlayBuffPosi_End; //PlayBuff 버퍼링 끝 위치 DWORD dwLastTransTime; //마지막 교신 시간 int LastPlayDataType; //마지막 교신한 데이타 타입 smCHAR_INFO smCharInfo; //유저 정보 smCHAR_MONSTER_INFO smMonsterInfo; //몬스터 관련 구조 int AnimDispMode; //동작 표시 모드 ( 0-모두 표시 1-한개씩 표시) int PatDispMode; //패턴 표시 모드 ( 0-비표시 1-메인 2-서브만 3-모두 ) int MotionSelectFrame; //현재의 프레임의 모션의 번호 ( 0 , 1 ) smMODELINFO *smMotionInfo; //모델의 동작별 프레임과 정보 smMODELINFO *smMotionInfo2; //모델이 2개일 경우 1차모델에서 데이타가 없는경우 2차모델의 데이타를 출력 smMOTIONINFO *MotionInfo; //###################################################################################### //작 성 자 : 오 영 석 smMODELINFO *lpTalkModelParent; smMOTIONINFO *lpTalkMotionInfo; //###################################################################################### DWORD OldMotionState; //이전의 모션 속성 정보 DWORD dwTarget; //상대방이 주인공을 겨냥한 액션일경우 //소환된 캐릭터 ( 마스터 유저가 존재 ) rsPLAYINFO *lpMasterPlayInfo; //주인 캐릭터 (서버용) int nCheckChar; //내가 불러낸 공격 캐릭터 구분 (서버용) // 장별 - 소울스톤 //목적 캐릭터 ~~ rsPLAYINFO *lpTargetPlayInfo; //목표 캐릭터 (서버용) smCHAR *lpTargetChar; //목표 캐릭터 (클라이언트용) int AttackUserFlag; //몬스터가 유저를 공격함 DWORD dwTargetLockTime; //목표 변경 금지 DWORD dwLinkObjectCode; //연결된 오브젝트 코드 rsPLAYINFO *lpLinkPlayInfo; //연결된 플레이어 smCHAR *lpLinkChar; //연결된 캐랙터 //공격당한 캐릭터 정보 ( 몬스터 경험치 배분을 목적 - 서버용 ) rsPLAYINFO *lpExpAttackPlayInfo; int ExpAttackLife; DWORD dwExpAttackTime; TRANS_ATTACKDATA AttackTrans; //공격 데이타 버퍼 DWORD dwAttackPlayTime; //공격 적용 시간 int PotionLog; //포션 사용 기록 int LevelLog; //레벨 변화 기록 int CriticalLog; //크리티컬 로그 int EnableStateBar; //체력바 그리기 옵션 int MotionRecordCount; //모션 정보 기록 카운터 int OpenStartPostion; //캐릭터의 시작 출신깃발 번호 (서버용) int DisplayAlpha; //반투명도 ( 임시 반투명 출력 ) int RendAlpha; //반투명도 ( 원래 반투명 캐릭터 ) int RenderLatter; //렌더링 나중에 DWORD dwDispAppSkill; //스킬 적용표시 DWORD dwDispAppSkillMask; //스킬 적용표시 마스크 ( 동기를 맞추기 위함 ) int HideWeapon; //무기 숨김 int MotionLoop; //반복 모션 횟수 int MotionLoopSpeed; //반복 모션용 프레임 속도 int MotionEvent; //모션 이벤트 플랙 int WeaponEffect; //무기용 속성 이펙트 DWORD dwWeaponEffectTime; //무기용 속성 이펙트 카운터 int EnchantEffect_Point; //스킬 EnchantWeapon 의 스킬 포인트 rsPLAYINFO *lpCompulsionPlayInfo; //시선끌기 캐릭터 DWORD dwCompulsionTime; //시선끌기 시간 DWORD dwAssassinEyeTime; //어세신아이 적용 몬스터 int AssassinEyeParam; //어세신아이 적용 몬스터 ////////////////////// 클랜 ////////////////////////// int ClanInfoNum; //클랜 정보 번호 DWORD dwClanInfoTime; //클랜 정보 받은 시간 DWORD dwClanManageBit; //클랜 관리 표시 int Clan_CastleMasterFlag; //성주 클랜원 이다! //확장용 void *lpExt1; //(서버) 필드 구조체 연결 포인터 void *lpExt2; void *lpExt3; void *lpExt4; POINT3D HoSkillPos; //스킬 관련 좌표 int HoSkillCode; //관련 스킬 코드 int HoSkillMode; //스킬 소환수 행동모드 int PartyFlag; //파티 플랙 int PartyParam; //파티 파라메터 // 공격 받은 속성 int PlaySlowCount; //느려지는 공격 받음 int PlaySlowSpeed; //느려지는 속도 int PlayStunCount; //중립 상태 카운터 int PlayStopCount; //움직임이 멈춤 카운터 short PlayHolyMind[2]; //데미지 약화 기능 ( [0] 감소된 데미지% [1] 유지시간 ) short PlayHolyPower[2]; //데미지 강화 기능 ( [0] 강화된 데미지% [1] 유지시간 ) short PlayPoison[2]; //독에 공격 ( [0] 감소될 데미지 [1] 해독시간 ) short PlayHolyIncantation[2]; //몬스터 현혹 스킬 ( [0] 임시 [1] 유지시간 ) int PlayVanish; //배니쉬 스킬적용 int PlayCurseQuest; //저주 퀘스트 모드 int PlayVague; //보그 스킬적용 int PlayDistortion; //디스토션 (몬스터 왜곡) int PlayInvincible; //무적 아이템 BOOL CheckFlagIce; //아이스 속성 플래그값 int DispPoison; //독감염 표시 DWORD dwForceOfNatureTime; //포스오브 네이쳐 유지시간 DWORD dwHallOfValhallaTime; //홀오브발할라 유지시간 int AttackSkillRange; //몬스터가 스킬 범위 공격 사용 int EventAttackCount; //이벤트 공격 카운터 ( 뿅망치 등 ) DWORD dwEventAttackParam; short sAddColorEffect[4]; //색상추가 int DispLifeBar; //생명바 표시 DWORD dwUpdateCharInfoTime; //업데이트 시도 시간 DWORD dwLastRecvAttackTime; //마지막 공격 받은 시간 int TryAttackCount; //공격시도 횟수 ///////////////// Force Orb //////////////////// DWORD dwForceOrbCode; //포스오브 적용 코드 DWORD dwForceOrbTime; //포스오브 유지시간 // 박재원 - 데미지 부스터(생명력) DWORD dwLifeBoosterCode; // 박재원 - 부스터 아이템(생명력) 코드 DWORD dwLifeBoosterTime; // 박재원 - 부스터 아이템(생명력) 유지시간 // 박재원 - 데미지 부스터(기력) DWORD dwManaBoosterCode; // 박재원 - 부스터 아이템(기력) 코드 DWORD dwManaBoosterTime; // 박재원 - 부스터 아이템(기력) 유지시간 // 박재원 - 데미지 부스터(근력) DWORD dwStaminaBoosterCode; // 박재원 - 부스터 아이템(근력) 코드 DWORD dwStaminaBoosterTime; // 박재원 - 부스터 아이템(근력) 유지시간 //박재원 - 이터널 라이프, 페이틀 에지, 어버트 스크롤(공성 아이템 스크롤) DWORD dwSiegeItem_ScrollCode_Eternal; // 이터널 라이프 DWORD dwSiegeItem_ScrollTime_Eternal; DWORD dwSiegeItem_ScrollCode_Fatal; //페이틀 에지 DWORD dwSiegeItem_ScrollTime_Fatal; DWORD dwSiegeItem_ScrollCode_Avert; //어버트 스크롤 DWORD dwSiegeItem_ScrollTime_Avert; // 장별 - 스킬 딜레이 DWORD dwSkillDelayCode; DWORD dwSkillDelayTime; ////////////// 공성모드 State 백업 ////////////// int PkMode_CharState; //공성모드 객체의 속성 백업 ( smCHAR_STATE_NPC / ENEMY / USER ) int DontMoveFlag; //움직이지 않는 물체 DWORD dwClanCode; //클랜코드 int UseObject_VirtualLife; //물체 가상 생명력 사용 short sObject_VirtualLife[2]; //물체 가상의 생명력 short sObject_DisplayLife[2]; //물체 가상의 생명력 출력용 short sBlessCastle_Damage[2]; //0-Damage 1-Killing Count ATTACK_DAMAGE_LIST *lpAttackDamageList; //공격을 한 유저와 공격치를 저장하는 경우 ATTACK_DAMAGE_LIST *lpAttackDamageList_BlessCastle; //공격을 한 유저와 공격치를 저장하는 경우 (블레스캐슬) smCHAR(); ~smCHAR(); void Init(); int Close(); int SetPosi( int x, int y, int z , int angX, int angY, int angZ ); int SetTargetPosi( int x, int z ); int SetTargetPosi2( int x, int z ); //공격 포인트 좌표를 구한다 int GetAttackPoint( int *nX, int *nY, int *nZ ); //도구 위치 포인트 구하기 int GetToolBipPoint( smCHARTOOL *ChrTool, int *nX, int *nY, int *nZ ); //다음 목적 좌표 설정 int SetNextTarget( int x, int y, int z ); int MoveAngle( int step ); //이동 int MoveAngle2( int step ); //이동 ( 정밀 ) int ChangeMoveMode(); //이동 모드 변경 int StartHandEffect( int Mode ); //손에 효과 주기 ( 파이곤 용 ) int SetAction( int nAction ); //움직임 동작 설정 int ChangeMotion( int Motion , int DpMode=0 ); //###################################################################################### //작 성 자 : 오 영 석 int AutoChangeTalkMotion( int TalkModeType ); //###################################################################################### //프레임 번호로 동작을 찾는다 int FindActionFromFrame( int sframe ); //패턴 등록 int SetDinaPattern( smDPAT *lpDPat ); int SetDinaPattern2( smDPAT *lpDPat ); // int SetAnimatioInfo( smMODELINFO *ModelInfo ); //무기 장착 int SetTool( DWORD dwItemCode , int hvPosi ); //패턴설정 int SetPattern( smPAT3D *pat ); //2차 패턴 설정 int SetPattern2( smPAT3D *pat ); //PlayBuff에 동작을 저장 int SavePlayBuff(); //PlayBuff에 동작을 저장 / 몬스터 및 자동캐릭터용 프레임 저장 (서버용) int SavePlayBuff2(); int Main(); int Draw(); int VirtualDraw(); //가상으로 그린다 ( 실제로는 그리지 않고 값만 세팅 ) int ShootingMain(); //발사형 무기 메인함수 int ChargingSkill(); //스킬 차징 int EventAttack( int Flag=0 ); //공격 이벤트 int CheckShootingTest(smCHAR *lpChrTarget); //발사형 무기 발사 테스트 int CheckShootingTest_LastAttackTime( smCHAR *lpChar ); //공격받은 시간 검사하여 원거리 공격 탐지 int SetSmoking( int level ); //먼지 생성 //###################################################################################### //작 성 자 : 오 영 석 SIceFootInfo m_IceFootInfo[ ICE_FOOT_COUNT_MAX ]; void SetIceFoot( int TypeNum, DWORD dwPlayTime, int x, int z ); int DrawIceFoot(void); //###################################################################################### //그림자 그리기 int DrawShadow(); // 체력바 그리기 int DrawStateBar( int x, int y ); // 체력바 그리기 int DrawStateBar2( int x, int y ); // 차징 게이지 그리기 int DrawChargingBar( int x, int y , int Charging , int ChargingMax ); //무기 움직임에 잔상 남기기 int DrawMotionBlurTool( smCHARTOOL *ChrTool ); //움직임에 잔상 남기기 int DrawMotionBlur(); //캐릭터에 패턴을 설정 int SetLoadPattern( char *szName ); //위치를 받아 예측데이타를 만들어 넣는다 int MakePlayBuffFromPosi( int px, int py, int pz , int anX,int anY, int anZ , int act ); //전송 받은 데이타로 PLAYBUFF에 예측 데이타를 만들어 넣는다 int MakePlayBuffFromRecvData( smPLAYBUFF *StartBuff , smPLAYBUFF *EndBuff , int len ); //통신용 플레이 데이타를 지정한 버퍼에 작성 int MakeTransPlayData( char *lpTargetBuff , int SendTime , int pBuffStep=1 ); //수신된 데이타의 장착 아이템에 이펙트 적용 int SetTransEffectItems(smEFFECT_ITEM *lpEffectItem); //수신된 데이타의 장착 무기에 속성 이펙트 적용 int SetTransEffectWeapon(smEFFECT_ITEM *lpEffectItem); //통신 오류 체크하여 보정 int TransDelayCheck(); //거리별 전송 시간차를 조절 한다 int SetDistSendCnt( smCHAR *player ); //모션 분류 코드로 모션을 바꾼다 int SetMotionFromCode( DWORD MotionCode ); //해당 모션의 갯수를 구한다 int FindMotionCountFromCode( DWORD MotionCode ); //상대 플레이어의 데이타 초기 설정 int FormSetPlayerInfo(); //수신 받은 상대 플레이어의 데이타 설정 int SetTransPlayerInfo( smTRNAS_PLAYERINFO *lpTransPlayerInfo ); //수신 받은 상대 플레이어의 데이타 설정 int SetTransPlayerInfoQuick( smTRNAS_PLAYERINFO_QUICK *lpTransPlayerInfo ); //받은 데미지 암화화 코드 DWORD GetAttackTrans_XorCode(); //받은데미지 수치 초기화 int ResetAttackTrans(); //받은데미지 수치 암호화 반전 int XorAttackTrans(); //공격 실행 int PlayAttack( int EventFlag=0 ); //데이타 입수 ( 그룹 처리용 ) int RecvPlayData2( char *lpData ); //데이타 입수 int RecvPlayData( smTHREADSOCK *RecvData ); //데이타 전송 int SendPlayData( smCHAR *player ); //캐릭터의 포괄적 정보를 소켓으로 상대방에 전송 int SendCharInfo( smWINSOCK *lpsmsock ); //자신의 데이타를 소켓을 통하여 다른 곳으로 전송 ( 서버에서 클라이언트로 전송용 ) int SendPlayDataSock( smWINSOCK *lpsmsock , char *lpTransBuff , int ex, int ey, int ez ); //특정 상대에게 공격을 가한다 ( 상대방의 소켓값 또는 캐릭터 포인터 [둘중 선택] ) int SendTransAttack( smCHAR *lpChar , smWINSOCK *lpsmsock , int AttackCode , int Add_Damage=0 , int Resistance=0 ); //공격 사정거리에 들어왔으면 공격 ( 좌표 와 사정거리 ) int PlayAttackFromPosi( int ex, int ey, int ez, int Dist ,int attack=TRUE ); //스킬시작 int BeginSkill( int SkilCode , int Level , smCHAR *lpTarChar , int x, int y, int z ); //스킬이벤트 int EventSkill(); //몬스터 스킬 시작 int BeginSkill_Monster(); //몬스터 스킬 이벤트 int EventSkill_Monster(); //몬스터 공격 시작 int BeginAttack_Monster(); //스킬동작종료 int EndSkill(); }; /* #define CHRMOTION_STAND 0 #define CHRMOTION_WALK 1 #define CHRMOTION_RUN 2 #define CHRMOTION_JUMP 3 #define CHRMOTION_ATTACK 4 */ #define CHRMOTION_EXT 10 #define hvPOSI_RHAND 0x0001 #define hvPOSI_LHAND 0x0002 #define CHRMOTION_STATE_STAND 0x40 #define CHRMOTION_STATE_WALK 0x50 #define CHRMOTION_STATE_RUN 0x60 #define CHRMOTION_STATE_FALLDOWN 0x80 #define CHRMOTION_STATE_ATTACK 0x100 #define CHRMOTION_STATE_DAMAGE 0x110 #define CHRMOTION_STATE_DEAD 0x120 #define CHRMOTION_STATE_SOMETIME 0x130 #define CHRMOTION_STATE_EAT 0x140 #define CHRMOTION_STATE_SKILL 0x150 #define CHRMOTION_STATE_FALLSTAND 0x170 #define CHRMOTION_STATE_FALLDAMAGE 0x180 #define CHRMOTION_STATE_RESTART 0x200 #define CHRMOTION_STATE_WARP 0x210 #define CHRMOTION_STATE_YAHOO 0x220 //사운드 구분용 으로만 사용 #define CHRMOTION_STATE_HAMMER 0x300 //###################################################################################### //작 성 자 : 오 영 석 #define CHRMOTION_STATE_TALK_AR 0x400 #define CHRMOTION_STATE_TALK_E 0x410 #define CHRMOTION_STATE_TALK_OH 0x420 #define CHRMOTION_STATE_TALK_EYE 0x430 #define CHRMOTION_STATE_TALK_BLANK 0 #define CHRMOTION_STATE_TALK_SMILE 0x440 #define CHRMOTION_STATE_TALK_GRUMBLE 0x450 #define CHRMOTION_STATE_TALK_SORROW 0x460 #define CHRMOTION_STATE_TALK_STARTLED 0x470 #define CHRMOTION_STATE_TALK_NATURE 0x480 #define CHRMOTION_STATE_TALK_SPECIAL 0x490 //###################################################################################### // 캐릭터에 사용할 카메라 위치를 설정한다 int smCHAR_SetCameraPosi( int x,int y,int z, int angX,int angY,int angZ ); //크리티컬 섹션 extern CRITICAL_SECTION cLoadSection; //제거 int smDPAT_Delete( smDPAT *dPat ); //특정 오브젝트의 트리를 추적하여 애니메이션 시킴 int AnimObjectTree( smOBJ3D *tObj , int frame , int ax, int ay, int az ); int TestSetNewText( char *str ) ; //모션부려 초기화 int InitMotionBlur(); //아이템 번호 찾기 코드로 int GetSinItemNumFromCode( DWORD CODE ); //패턴버퍼를 초기화 int InitPatterns(); //패턴버퍼를 말기화 int ClosePatterns(); //캐릭터에 패턴을 설정 int SetLoadPattern( smCHAR *smChar , char *szName , POINT3D *Posi , POINT3D *Angle ); //캐릭터에 패턴을 설정2 int SetLoadPattern( smCHAR *smChar , char *szName , char *szName2 , POINT3D *Posi , POINT3D *Angle ); int AddLoaderPattern( smCHAR *lpChar , char *szName , char *szName2=0 ); //배경을 새 쓰레드에 통하여 로드 한다 int AddLoaderStage( smSTAGE3D *lpStage , char *szName ); //특정 오브젝트의 트리를 추적하여 애니메이션 시킴 int AnimObjectTree( smOBJ3D *tObj , int frame , int ax, int ay, int az ); class scITEM { public: DWORD Head; int DisplayFlag; //화면 출력 여부 int Flag; int pX,pY,pZ; char szModelName[64]; char szName[64]; void *lpStgArea; //존재하는 구역 smPAT3D *Pattern; smDPAT *lpDinaPattern; //다이나믹 패턴 포인터 (패턴의 관리자) int PatLoading; int ItemCode; DWORD dwLastTransTime; // 마지막으로 전송된 시간 int ServerCode; //해당 캐릭터 서버 코드 POINT3D RendPoint; //렌더링된 2D 좌표 ( x,y,z ) POINT3D Posi; POINT3D Angle; scITEM(); ~scITEM(); void Init(); int Close(); int SetPosi( int x, int y, int z ); //위치 설정 int SetTransItem( TRANS_ITEM *lpTransItem ); //수신된 아이템 설정 int SetPattern( smPAT3D *pat ); //패턴설정 int SetPosi( int x, int y, int z , int angX, int angY, int angZ ); int Draw(); //아이템 그리기 }; //아이템을새 쓰레드에 통하여 로드 한다 int AddLoaderItem( scITEM *lpItem , char *szName ); //고속 첵크용 코드 제작 DWORD GetSpeedSum( char *szName ); extern smPATTERN smBipPattern; extern smPATTERN smPattern; //공격 마크 보안 카운터 증가 int Ptect_IncAttackCount( int Flag ); //공격 마크 보안 카운터 얻기 DWORD Ptect_GetAttackCount(); extern int SkillChargingFlag; //스킬 차징 플랙 extern TRANS_SKIL_ATTACKDATA Trans_SplashCharList; //팅겨서 맞는 공격 데이타 임시저장 extern int smCHAR_CameraX; extern int smCHAR_CameraY; extern int smCHAR_CameraZ; //공성전 필드 좌표 정보 extern int CastleBattleZone_LineZ; extern int CastleBattleZone_DoorLineZ; //성문 입구 extern int CastleBattleZone_DoorLineX[2]; //성문 입구 extern int CastleBattleZone_BridgeZ; //다리 입구 extern int CastleSoulFountain_Area[4]; //영혼의샘터 //캐슬 마스터 업데이트 int UpdateCastleMasterClan( DWORD dwMasterClan ); //플레이어 클랜 마스터 확인 int SetClanMaster_Player( DWORD dwMasterClan ); #endif
#include <iostream> using namespace std; struct node { int data; node* left, *right; node(){ left = right = NULL; } node (int _data) : data(_data){ left = right = NULL; } }; void preOrder(node*); void showNodes(node*); int levelOfTree(node*); void insertData(int, node**); int main(void){ node* tree = nullptr; insertData(30, &tree); insertData(10, &tree); insertData(12, &tree); insertData(28, &tree); insertData(9, &tree); insertData(11, &tree); insertData(7, &tree); insertData(15, &tree); insertData(65, &tree); insertData(100, &tree); cout << "******************** PreOrder traversal 1 ********************" << endl; preOrder(tree); cout << "******************** Cantidad de niveles ********************" << endl; levelOfTree(tree); return 0; } void preOrder(node* tree) { if(tree) { cout << tree->data << endl; preOrder(tree->left); preOrder(tree->right); } } void insertData(int number, node** root){ if(!*root){ *root = new node(number); }else{ if(number < (*root)->data){ insertData(number, &(*root)->left); }else{ insertData(number, &(*root)->right); } } } int levelOfTree(node* level){ if(!level){ return 0; }else if(level->left!= NULL){ return 1 + levelOfTree(level->left); }else{ return 1 + levelOfTree(level->right); } return 0; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef CELLSGENERATOR_HPP_ #define CELLSGENERATOR_HPP_ #include <vector> #include "Cell.hpp" #include "WildTypeCellMutationState.hpp" #include "StemCellProliferativeType.hpp" #include "TransitCellProliferativeType.hpp" #include "RandomNumberGenerator.hpp" /** * A helper class for generating a vector of cells for a given mesh. * * It is templated over types of cell-cycle model and spatial dimension. */ template<class CELL_CYCLE_MODEL, unsigned DIM> class CellsGenerator { public: /** * Fills a vector of cells with a specified cell-cycle model, to match * a given number of cells. Gives them birth times of 0 for node 0, * -1 for node 1, -2 for node 2 etc... * * @param rCells An empty vector of cells to fill up. * @param numCells The number of cells to generate. * @param locationIndices is used when a birth-time hint is needed for individual cell. * Defaults to an empty vector -- otherwise must be of length numCells * @param pCellProliferativeType the cell proliferative type to give each cell (defaults to StemCellProliferativeType) */ void GenerateBasic(std::vector<CellPtr>& rCells, unsigned numCells, const std::vector<unsigned> locationIndices=std::vector<unsigned>(), boost::shared_ptr<AbstractCellProperty> pCellProliferativeType=boost::shared_ptr<AbstractCellProperty>()); /** * Fills a vector of cells with a specified cell-cycle model, to match * a given number of cells. Gives cells a random birth time drawn uniformly * from 0 to the AverageStemCellCycleTime. * * @param rCells An empty vector of cells to fill up. * @param numCells The number of cells to generate. * @param pCellProliferativeType the cell proliferative type to give each cell (defaults to StemCellProliferativeType) */ void GenerateBasicRandom(std::vector<CellPtr>& rCells, unsigned numCells, boost::shared_ptr<AbstractCellProperty> pCellProliferativeType=boost::shared_ptr<AbstractCellProperty>()); /** * Fills a vector of cells with birth times to match a given vector of location indices. * * @param rCells An empty vector of cells to fill up. * @param locationIndices The indices of the cell population to assign real cells to. * @param pCellProliferativeType the cell proliferative type to give each cell (defaults to StemCellProliferativeType) */ void GenerateGivenLocationIndices(std::vector<CellPtr>& rCells, const std::vector<unsigned> locationIndices, boost::shared_ptr<AbstractCellProperty> pCellProliferativeType=boost::shared_ptr<AbstractCellProperty>()); }; template<class CELL_CYCLE_MODEL, unsigned DIM> void CellsGenerator<CELL_CYCLE_MODEL,DIM>::GenerateBasic(std::vector<CellPtr>& rCells, unsigned numCells, const std::vector<unsigned> locationIndices, boost::shared_ptr<AbstractCellProperty> pCellProliferativeType) { rCells.clear(); if (!locationIndices.empty()) { // If location indices is given, then it needs to match the number of output cells if (numCells != locationIndices.size()) { EXCEPTION("The size of the locationIndices vector must match the required number of output cells"); } } rCells.reserve(numCells); // Create cells for (unsigned i=0; i<numCells; i++) { CELL_CYCLE_MODEL* p_cell_cycle_model = new CELL_CYCLE_MODEL; p_cell_cycle_model->SetDimension(DIM); boost::shared_ptr<AbstractCellProperty> p_state(CellPropertyRegistry::Instance()->Get<WildTypeCellMutationState>()); CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); if (!pCellProliferativeType) { p_cell->SetCellProliferativeType(CellPropertyRegistry::Instance()->Get<StemCellProliferativeType>()); } else { p_cell->SetCellProliferativeType(pCellProliferativeType); } double birth_time; if (!locationIndices.empty()) { birth_time = 0.0 - locationIndices[i]; } else { birth_time = 0.0 - i; } p_cell->SetBirthTime(birth_time); rCells.push_back(p_cell); } } template<class CELL_CYCLE_MODEL, unsigned DIM> void CellsGenerator<CELL_CYCLE_MODEL,DIM>::GenerateBasicRandom(std::vector<CellPtr>& rCells, unsigned numCells, boost::shared_ptr<AbstractCellProperty> pCellProliferativeType) { rCells.clear(); rCells.reserve(numCells); // Create cells for (unsigned i=0; i<numCells; i++) { CELL_CYCLE_MODEL* p_cell_cycle_model = new CELL_CYCLE_MODEL; p_cell_cycle_model->SetDimension(DIM); boost::shared_ptr<AbstractCellProperty> p_state(CellPropertyRegistry::Instance()->Get<WildTypeCellMutationState>()); CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); if (!pCellProliferativeType) { p_cell->SetCellProliferativeType(CellPropertyRegistry::Instance()->Get<StemCellProliferativeType>()); } else { p_cell->SetCellProliferativeType(pCellProliferativeType); } double birth_time = -p_cell_cycle_model->GetAverageStemCellCycleTime()*RandomNumberGenerator::Instance()->ranf(); if (p_cell->GetCellProliferativeType()->IsType<TransitCellProliferativeType>()) { birth_time = -p_cell_cycle_model->GetAverageTransitCellCycleTime()*RandomNumberGenerator::Instance()->ranf(); } p_cell->SetBirthTime(birth_time); rCells.push_back(p_cell); } } template<class CELL_CYCLE_MODEL, unsigned DIM> void CellsGenerator<CELL_CYCLE_MODEL,DIM>::GenerateGivenLocationIndices(std::vector<CellPtr>& rCells, const std::vector<unsigned> locationIndices, boost::shared_ptr<AbstractCellProperty> pCellProliferativeType) { assert(!locationIndices.empty()); unsigned num_cells = locationIndices.size(); rCells.clear(); rCells.reserve(num_cells); CellPropertyRegistry::Instance()->Clear(); for (unsigned i=0; i<num_cells; i++) { CELL_CYCLE_MODEL* p_cell_cycle_model = new CELL_CYCLE_MODEL; p_cell_cycle_model->SetDimension(DIM); boost::shared_ptr<AbstractCellProperty> p_state(CellPropertyRegistry::Instance()->Get<WildTypeCellMutationState>()); CellPtr p_cell(new Cell(p_state, p_cell_cycle_model)); if (!pCellProliferativeType) { p_cell->SetCellProliferativeType(CellPropertyRegistry::Instance()->Get<StemCellProliferativeType>()); } else { p_cell->SetCellProliferativeType(pCellProliferativeType); } double birth_time = 0.0 - locationIndices[i]; p_cell->SetBirthTime(birth_time); rCells.push_back(p_cell); } } #endif /* CELLSGENERATOR_HPP_ */
#include "cpptools_Logger.hpp" #include <mutex> namespace imog { // ====================================================================== // // ====================================================================== // // Define loggers // ====================================================================== // _LogType Logger::m_info = spdlog::stdout_color_mt("INFO"); _LogType Logger::m_error = spdlog::stderr_color_mt("ERROR"); _LogType Logger::m_print = spdlog::stdout_color_mt("PRINT"); // ====================================================================== // // ====================================================================== // // Getter of info logger // ====================================================================== // _LogType& Logger::info() { static std::once_flag infoOnceFlag; std::call_once(infoOnceFlag, [&]() { m_info->set_pattern(PATTERN_ALERT); }); return m_info; } // ====================================================================== // // ====================================================================== // // Getter of error logger // ====================================================================== // _LogType& Logger::error() { static std::once_flag errorOnceFlag; std::call_once(errorOnceFlag, [&]() { m_error->set_pattern(PATTERN_ALERT); }); return m_error; } // ====================================================================== // // ====================================================================== // // Getter of print logger // ====================================================================== // _LogType& Logger::print() { static std::once_flag printOnceFlag; std::call_once(printOnceFlag, [&]() { m_print->set_pattern(PATTERN_PRINT); }); return m_print; } } // namespace imog
#pragma once #include <Urho3D/Engine/Application.h> #include <Urho3D/UI/Text.h> #include "Level.h" using namespace Urho3D; class Demo : public Application { URHO3D_OBJECT(Demo, Application); SharedPtr<Viewport> viewport_; SharedPtr<Scene> mainScene_; SharedPtr<DebugRenderer> debugRenderer_; SharedPtr<Node> cameraNode_; SharedPtr<Text> debugText_; Level* level_; float mapShiftDistance_; public: Demo(Context* context); virtual void Setup(); virtual void Start(); private: void CreateUI(); void HandleUpdate(StringHash eventType, VariantMap &eventData); void Render(StringHash eventType, VariantMap &eventData); void HandlePostRenderUpdate(StringHash eventType, VariantMap &eventData); void HandleDistanceSliderChanged(StringHash eventType, VariantMap& eventData); void MoveCamera(float step); };
#include "RangeColor.h" RangeColor::RangeColor(void) { Min = SDL_Color(); Max = SDL_Color(); } RangeColor::RangeColor(SDL_Color color) { Min = color; Max = color; } RangeColor::RangeColor(SDL_Color min, SDL_Color max) { Min = min; Max = max; } RangeColor::~RangeColor(void) { }
/* @brief askValues.c * This program get contents of the files and * save it in a variable */ #include <bits/stdc++.h> using namespace std; extern string nameMessage; void obtainContent( string nameFile, string *vartoSave, string *nameWithoutExtension ){ ifstream filetoOpen; int txtPosicion; filetoOpen.open( nameFile.c_str(), ios::in ); if( filetoOpen.fail() ){ cout<< "Error opening file"; exit(EXIT_FAILURE); } txtPosicion = nameFile.find( ".txt" ) + 4; *nameWithoutExtension = nameFile.substr(0, txtPosicion); while( !filetoOpen.eof() ) getline( filetoOpen, *vartoSave ); filetoOpen.close(); } void writeKeytoFile( string typeCipher, string *key ){ ofstream fileGenerate; string nameFile = "KeyGenerate" + typeCipher + ".txt"; fileGenerate.open( nameFile.c_str(), ios :: out ); if( fileGenerate.fail() ){ cout<< "Error writing the generated key"; exit( EXIT_FAILURE ); } fileGenerate<< *key; fileGenerate.close(); } void saveFile( string texttoSave, string typeCipher, string operationtoDo ){ ofstream fileEncrypt; string nametoSave = nameMessage + typeCipher; if( !(operationtoDo.compare("Decrypt")) ) nametoSave = operationtoDo + nameMessage + typeCipher; fileEncrypt.open( nametoSave.c_str() , ios :: out ); if( fileEncrypt.fail() ){ cout<< "Error writing the generated key"; exit( EXIT_FAILURE ); } fileEncrypt<< texttoSave; fileEncrypt.close(); }
#ifndef MENU_H #define MENU_H #include <allegro.h> #include "Instrucoes.h" class Menu { private: BITMAP* buffer; BITMAP* bmp; BITMAP* bmp_instrucoes; BITMAP* bmp_selection; int pos_x; int pos_y; int select; bool jogo; public: Menu(); virtual ~Menu(); void Set_menu(BITMAP* buffer, BITMAP* bmp); int Executar(); void Print(); protected: private: }; #endif // MENU_H
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> res; // multiset: ascending sort by default, allow duplicates multiset<int, greater<int>> ms; // descending order for (int i = 0; i < (int)nums.size(); ++i) { if (i >= k) ms.erase(ms.find(nums[i - k])); // ms.erase(nums[i-k]) will erase all duplicates ms.insert(nums[i]); if (i >= k -1) res.push_back(*ms.begin()); } return res; } };
//Problem link:-https://www.hackerrank.com/challenges/maxsubarray #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int t;int n,i; scanf("%d",&t); while(t--) { scanf("%d",&n); int arr[n];int temp=0,max=0,sum=0; for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n;i++){ temp+=arr[i]; if(temp<0) temp=0; if(temp>max) max=temp; } for(i=0;i<n;i++) if(arr[i]>0) sum+=arr[i]; if(sum==0){sum=-100000; for(i=0;i<n;i++) if(arr[i]>sum) sum=arr[i]; max=sum; } printf("%d %d\n",max,sum); } /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // //----------------------------------------------------------------------------- // Test of PatchSizeSyncer //----------------------------------------------------------------------------- // Include files #include "Pooma/Pooma.h" #include "Tulip/Messaging.h" #include "Tulip/CollectFromContexts.h" #include "Utilities/Tester.h" int main(int argc, char *argv[]) { Pooma::initialize(argc, argv); Pooma::Tester tester(argc, argv); const int numContexts = Pooma::contexts(); const int myContext = Pooma::context(); tester.out() << "Running with " << numContexts << " contexts." << std::endl; CollectFromContexts<int> ranks(2*(Pooma::context()+1)); if (Pooma::context() == 0) { bool check = true; for (int i=0; i<Pooma::contexts(); ++i) if (ranks[i] != 2*(i+1)) { tester.out() << "[" << i << "] should be " << 2*(i+1) << ", but is " << ranks[i] << "\n"; check = false; } tester.check("Collecting ranks", check); } // We can't do the following test on !MESSAGING, as invalid data on // context 0 is not supported in this case. #if POOMA_MESSAGING CollectFromContexts<int> ranks2(Pooma::context()+1, 0, Pooma::context() > 0 && Pooma::context() < Pooma::contexts()-1); if (Pooma::context() == 0) { bool check = true; for (int i=1; i<Pooma::contexts()-1; ++i) if (ranks2[i] != i+1) { tester.out() << "[" << i << "] should be " << (i+1) << ", but is " << ranks[i] << "\n"; check = false; } tester.check("Collecting ranks, but not first and last", check); } #endif int ret = tester.results("CollectFromContextsTest"); Pooma::finalize(); return ret; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. 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 University of Oxford 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. */ #ifndef _GENERICMESHREADER_HPP_ #define _GENERICMESHREADER_HPP_ #include <memory> #include <string> #include "AbstractMeshReader.hpp" // Possible mesh reader classes to create #include "TrianglesMeshReader.hpp" #include "MemfemMeshReader.hpp" #include "VtkMeshReader.hpp" /** * This function creates a mesh reader of a suitable type to read the mesh file given. * It can use any of the following readers: * - TrianglesMeshReader * - MemfemMeshReader * - VtkMeshReader * * The created mesh reader is returned as a std::shared_ptr to ease memory management. * * @param rPathBaseName the base name of the files from which to read the mesh data * (either absolute, or relative to the current directory) * @param orderOfElements the order of each element: 1 for linear, 2 for quadratic (defaults to 1) * @param orderOfBoundaryElements the order of each boundary element: 1 for linear, 2 for quadratic (defaults to 1. May * or may not be different to orderOfElements (Note tetgen with the -o2 flag creates quadratic elements but doesn't * create quadratic faces, hence the need for this third parameter) * @param readContainingElementsForBoundaryElements Whether to read in the containing element information * for each boundary element (in the .face file if tetgen was run with '-nn'). */ template <unsigned ELEMENT_DIM, unsigned SPACE_DIM> std::shared_ptr<AbstractMeshReader<ELEMENT_DIM, SPACE_DIM> > GenericMeshReader(const std::string& rPathBaseName, unsigned orderOfElements=1, unsigned orderOfBoundaryElements=1, bool readContainingElementsForBoundaryElements=false) { std::shared_ptr<AbstractMeshReader<ELEMENT_DIM, SPACE_DIM> > p_reader; try { p_reader.reset(new TrianglesMeshReader<ELEMENT_DIM, SPACE_DIM>(rPathBaseName, orderOfElements, orderOfBoundaryElements, readContainingElementsForBoundaryElements)); } catch (const Exception& r_triangles_exception) { if (orderOfElements!=1 || orderOfBoundaryElements!=1 || readContainingElementsForBoundaryElements) { EXCEPTION("Quadratic meshes are only supported in Triangles format."); } try { p_reader.reset(new MemfemMeshReader<ELEMENT_DIM, SPACE_DIM>(rPathBaseName)); } catch (const Exception& r_memfem_exception) { #ifdef CHASTE_VTK try { p_reader.reset(new VtkMeshReader<ELEMENT_DIM, SPACE_DIM>(rPathBaseName)); } catch (const Exception& r_vtk_exception) { #endif // CHASTE_VTK std::string eol("\n"); std::string combined_message = "Could not open appropriate mesh files for " + rPathBaseName + eol; combined_message += "Triangle format: " + r_triangles_exception.GetShortMessage() + eol; combined_message += "Memfem format: " + r_memfem_exception.GetShortMessage() + eol; #ifdef CHASTE_VTK combined_message += "Vtk format: " + r_vtk_exception.GetShortMessage() + eol; #endif // CHASTE_VTK EXCEPTION(combined_message); #ifdef CHASTE_VTK } #endif // CHASTE_VTK } } return p_reader; } #endif //_GENERICMESHREADER_HPP_
#include <iostream> #include <vector> using namespace std; vector<int> difs; int valores[200000] = {0}; vector<int> cur_solution; int cont_max = 1, cont = 1; int main(int argc, char *argv[]) { int n, a; cin >> n; for(int i = 0; i < n; i++){ cin >> a; difs.push_back(a); } for(int i = 0; i < n-1; i++){ if (cont > cont_max) cont_max = cont; if (difs[i] << 1 >= difs[i+1]){ cont++; } else { cont = 1; } //if (cur_solution.size() > max_num) max_num = cur_solution.size(); } if (cont > cont_max) cont_max = cont; cout << cont_max << endl; return 0; }
#include <iostream> #include <stdio.h> #include <queue> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,k; cin >> n >> k; queue<int> q; vector<int> v; for (int i=0; i<n; i++) { q.push(i+1); } int cnt=0; int count =0; while(!q.empty()) { if (cnt == q.size()) cnt = 0; if (count == k-1) { v.push_back(q.front()); count = 0; q.pop(); } else { q.push(q.front()); q.pop(); count++; } cnt++; } cout << "<"; for (int i=0; i<n; i++) { cout <<v[i]; if (i!= n-1) cout << ", "; } cout << ">"; return 0; }
/* XBFOG.H FOG CLASS (c) g0at3r FOG MODES:.. D3DFOG_LINEAR D3DFOG_EXP (USED AS DEFAULT - BEST IMO) D3DFOG_EXP2 */ #ifndef __FOGHELPER_H__ #define __FOGHELPER_H__ #include <xtl.h> #include "XbUtil.h" class CXBFog { private: D3DXMATRIX m_matWorld, m_matView, m_matProj; FLOAT m_fFogStartValue, m_fFogEndValue, m_fFogDensity; DWORD m_dwFogColor; DWORD m_dwVertexShader; DWORD m_dwFogMode; DWORD m_dwVertexDecl[5]; bool m_bUseFog; void SetupVertexShader(); public: CXBFog(); ~CXBFog(); void SetVertexShader(char* szVertexShader); void Render(); void ChangeFog(DWORD dwFogMode, FLOAT fFogStart, FLOAT fFogEnd, FLOAT fFogDensity, DWORD dwFogColor); void Enable(); void Disable(); }; #endif
#include <iostream> using namespace std; int main() { double n, r; cin >> n; r = n / 2 / 3.14; cout << (int)((r*r*3.14) + 0.5); }
/****************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt PDF Module. ** ** $QT_BEGIN_LICENSE:COMM$ ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** $QT_END_LICENSE$ ** ******************************************************************************/ #ifndef SEQUENTIALPAGEWIDGET_H #define SEQUENTIALPAGEWIDGET_H #include <QWidget> class QPdfDocument; class PageRenderer; class SequentialPageWidget : public QWidget { Q_OBJECT public: explicit SequentialPageWidget(QWidget *parent = 0); ~SequentialPageWidget(); void paintEvent(QPaintEvent * event); qreal zoom() { return m_zoom; } qreal yForPage(int page); int topPageShowing() { return m_topPageShowing; } int bottomPageShowing() { return m_bottomPageShowing; } public slots: void openDocument(const QUrl &url); void setZoom(qreal factor); void invalidate(); signals: void showingPageRange(int start, int end); void zoomChanged(qreal factor); private slots: void pageLoaded(int page, qreal zoom, QImage image); private: int pageCount(); QSizeF pageSize(int page); void render(int page); private: QHash<int, QImage> m_pageCache; QList<int> m_cachedPagesLRU; int m_pageCacheLimit; QVector<QSizeF> m_pageSizes; PageRenderer *m_pageRenderer; QBrush m_background; QPixmap m_placeholderIcon; QBrush m_placeholderBackground; int m_pageSpacing; int m_topPageShowing; int m_bottomPageShowing; QSize m_totalSize; qreal m_zoom; qreal m_screenResolution; // pixels per point }; #endif // SEQUENTIALPAGEWIDGET_H
#include "TextureArray.h" #include "Player.h" #include "Chunk.h" #include "ChunkManager.h" #include "VertexBuffer.h" #include "Globals.h" #include "VertexArray.h" #include "Rectangle.h" #include "SkyBox.h" #include "glm/gtc/noise.hpp" #include "glm/gtc/matrix_transform.hpp" #include "ShaderHandler.h" #include "Frustum.h" #include "Gui.h" #include "DestroyBlockVisual.h" #include "SelectedVoxelVisual.h" #include "FrameBuffer.h" #include "PickupManager.h" #include <string> #include <iostream> #include <fstream> #include <sstream> #include <array> #include <memory> #include <unordered_map> #include <thread> #include "BoundingBox.h" #ifdef DEBUG_GL_ERRORS #define glCheck(expr) expr; if(!GLAD_GL_KHR_debug){ glCheckError(__FILE__, __LINE__, #expr) }; #else #define glCheck(call) call #endif #define DEBUG_GL_ERRORS //https://hacknplan.com/ //https://www.reddit.com/r/Minecraft/comments/2ikiaw/opensimplex_noise_for_terrain_generation_instead/ //Discourage use of VAOs all the time //https://www.youtube.com/watch?v=Bcs56Mm-FJY&list=PLlrATfBNZ98foTJPJ_Ev03o2oq3-GGOS2&index=12 //Run Tests - benchmarks/profile //1. One global VAO //2. VAO for each gameobject //OpenGL is a state machine //Select buffer - state - then draw me a triangle //Based off of which buffer has been selected, it determines what/how will be //https://www.reddit.com/r/VoxelGameDev/comments/376vmv/how_do_you_implement_threading_in_your_game/ //View == Frustrum //The reason why it can get away with that is because of other rendering optimizations. //Try refraining from rendering any blocks that are not adjacent to air(less bandwidth), //buildingand optimizing meshes from chunk data(less vertices to draw), //or cutting down on the size of each vertex element(less bandwidth).There are plenty of other ways to increase performance with such an engine. //https://devtalk.nvidia.com/default/topic/720651/opengl/access-violation-in-nvoglv32-dll-how-do-i-track-down-the-problem-/ //https://community.khronos.org/t/how-do-you-implement-texture-arrays/75315 //http://ogldev.atspace.co.uk/index.html //Good OpenGL Tutorials //https://ahbejarano.gitbook.io/lwjglgamedev/chapter12 //x + (y * width) int main() { sf::ContextSettings settings; settings.depthBits = 24; settings.stencilBits = 8; settings.antialiasingLevel = 4; settings.majorVersion = 3; settings.minorVersion = 3; settings.attributeFlags = sf::ContextSettings::Core; glm::uvec2 windowSize(1920, 1080); sf::Window window(sf::VideoMode::getDesktopMode(), "Minecraft Clone", sf::Style::Fullscreen, settings); window.setFramerateLimit(60); window.setMouseCursorVisible(false); window.setMouseCursorGrabbed(true); gladLoadGL(); glCheck(glViewport(0, 0, windowSize.x, windowSize.y)); glEnable(GL_DEPTH_TEST); std::unique_ptr<ShaderHandler> shaderHandler = ShaderHandler::create(windowSize); assert(shaderHandler); if (!shaderHandler) { std::cout << "Unable to load shader handler\n"; return -1; } std::unique_ptr<TextureArray> textureArray = TextureArray::create(); assert(textureArray); if (!textureArray) { std::cout << "Failed to load textures\n"; return -1; } textureArray->bind(); std::unique_ptr<SkyBox> skybox = SkyBox::create(); assert(skybox); if (!skybox) { std::cout << "Failed to load Skybox\n"; return -1; } std::unique_ptr<Texture> widjetsTexture = Texture::create("widgets.png"); assert(widjetsTexture); if (!widjetsTexture) { std::cout << "Couldn't load widjets texture\n"; return -1; } std::unique_ptr<Texture> fontTexture = Texture::create("ExportedFont.bmp"); assert(fontTexture); if (!fontTexture) { std::cout << "Couldn't load font texture\n"; return -1; } std::unique_ptr<Texture> destroyBlockTexture = Texture::create("blockDestroy.png"); assert(destroyBlockTexture); if (!destroyBlockTexture) { std::cout << "Couldn't load blockDestroy texture\n"; return -1; } std::unique_ptr<Texture> voxelSelectionTexture = Texture::create("voxelSelection.png"); assert(voxelSelectionTexture); if (!voxelSelectionTexture) { std::cout << "Couldn't load voxel selection texture\n"; return -1; } std::unique_ptr<ChunkManager> chunkManager = std::make_unique<ChunkManager>(); PickupManager pickupManager; FrameBuffer frameBuffer(windowSize); Gui gui(windowSize); Frustum frustum; Player player; std::atomic<bool> resetGame = false; std::mutex renderingMutex; std::mutex chunkInteractionMutex; float deltaTime = 0.0f; sf::Clock deltaClock; deltaClock.restart(); std::thread chunkGenerationThread([&](std::unique_ptr<ChunkManager>* chunkGenerator) {chunkGenerator->get()->update(std::ref(player), std::ref(window), std::ref(resetGame), std::ref(chunkInteractionMutex), std::ref(renderingMutex)); }, &chunkManager ); player.spawn(*chunkManager, chunkInteractionMutex); std::cout << glGetError() << "\n"; std::cout << glGetError() << "\n"; std::cout << glGetError() << "\n"; std::cout << glGetError() << "\n\n\n"; while (window.isOpen()) { deltaTime = deltaClock.restart().asSeconds(); //Handle Inputs sf::Event currentSFMLEvent; while (window.pollEvent(currentSFMLEvent)) { if (currentSFMLEvent.type == sf::Event::Closed) { window.close(); } else if (currentSFMLEvent.type == sf::Event::KeyPressed) { switch (currentSFMLEvent.key.code) { case sf::Keyboard::R: resetGame = true; chunkGenerationThread.join(); resetGame = false; chunkManager.reset(); chunkManager = std::make_unique<ChunkManager>(); chunkGenerationThread = std::thread{ [&](std::unique_ptr<ChunkManager>* chunkManager) {chunkManager->get()->update(std::ref(player), std::ref(window), std::ref(resetGame), std::ref(chunkInteractionMutex), std::ref(renderingMutex)); }, &chunkManager }; player.spawn(*chunkManager, chunkInteractionMutex); break; case sf::Keyboard::Escape: window.close(); break; } } player.handleInputEvents(currentSFMLEvent, *chunkManager, chunkInteractionMutex, window); } //Update player.update(deltaTime, chunkInteractionMutex, *chunkManager.get(), window); pickupManager.update(deltaTime, player, chunkInteractionMutex, *chunkManager); glm::mat4 view = glm::lookAt(player.getPosition(), player.getPosition() + player.getCamera().front, player.getCamera().up); glm::mat4 projection = glm::perspective(glm::radians(player.getCamera().FOV), static_cast<float>(windowSize.x) / static_cast<float>(windowSize.y), player.getCamera().nearPlaneDistance, player.getCamera().farPlaneDistance); frustum.update(projection * view); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderHandler->switchToShader(eShaderType::Chunk); shaderHandler->setUniformMat4f(eShaderType::Chunk, "uView", view); shaderHandler->setUniformMat4f(eShaderType::Chunk, "uProjection", projection); std::lock_guard<std::mutex> renderingLock(renderingMutex); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); textureArray->bind(); chunkManager->renderOpaque(frustum); pickupManager.render(frustum, *shaderHandler, view, projection); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); shaderHandler->switchToShader(eShaderType::Chunk); shaderHandler->setUniformMat4f(eShaderType::Chunk, "uView", view); shaderHandler->setUniformMat4f(eShaderType::Chunk, "uProjection", projection); chunkManager->renderTransparent(frustum); destroyBlockTexture->bind(); shaderHandler->switchToShader(eShaderType::DestroyBlock); shaderHandler->setUniformMat4f(eShaderType::DestroyBlock, "uView", view); shaderHandler->setUniformMat4f(eShaderType::DestroyBlock, "uProjection", projection); player.renderDestroyBlock(); if (!player.getDestroyCubeTimer().isActive()) { glPolygonOffset(-1.f, -2.f); glEnable(GL_POLYGON_OFFSET_FILL); //https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glPolygonOffset.xml voxelSelectionTexture->bind(); shaderHandler->switchToShader(eShaderType::SelectedVoxel); shaderHandler->setUniformMat4f(eShaderType::SelectedVoxel, "uView", view); shaderHandler->setUniformMat4f(eShaderType::SelectedVoxel, "uProjection", projection); player.renderSelectedVoxel(); glDisable(GL_POLYGON_OFFSET_FILL); } glDisable(GL_BLEND); //Draw Skybox glDepthFunc(GL_LEQUAL); shaderHandler->switchToShader(eShaderType::Skybox); shaderHandler->setUniformMat4f(eShaderType::Skybox, "uView", glm::mat4(glm::mat3(view))); shaderHandler->setUniformMat4f(eShaderType::Skybox, "uProjection", projection); skybox->render(); glDepthFunc(GL_LESS); //Draw GUI textureArray->bind(); gui.render(*shaderHandler, *widjetsTexture, *fontTexture); window.display(); } chunkGenerationThread.join(); return 0; }
#include "efecto_colision_recogedor.h" using namespace App_Juego_Logica; Efecto_colision_recogedor::Efecto_colision_recogedor(App_Juego_Sistemas::Contador_tiempo& t, App_Juego::Jugador& j) :salida_nivel(false), tiempo(t), jugador(j) { } bool Efecto_colision_recogedor::puede_recoger_salud() { return jugador.puede_recoger_salud(); } void Efecto_colision_recogedor::sumar_tiempo(float v) { tiempo.sumar_tiempo(v); } void Efecto_colision_recogedor::sumar_salud(float v) { jugador.sumar_salud(v); } void Efecto_colision_recogedor::recibir_impacto(float v) { jugador.recibir_impacto(v); }
class ValidWordAbbr { public: ValidWordAbbr(vector<string>& dictionary) { for (string s : dictionary) { string abbr = s; if (s.size() > 2) abbr = s[0] + to_string(s.size() -2) + s.back(); m[abbr].insert(s); } } bool isUnique(string word) { string abbr = word; if (word.size() > 2) abbr = word[0] + to_string(word.size() - 2) + word.back(); // if no word in dict has the same abbr as word; // or, all words in dict that have same abbr of "word" are the same as "word" if (!m.count(abbr) || m[abbr].count(word) == m[abbr].size()) return true; return false; } private: unordered_map<string, unordered_set<string>> m; // abbr--strings }; /** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr* obj = new ValidWordAbbr(dictionary); * bool param_1 = obj->isUnique(word); */
#pragma once #include <iostream> #include "bubble.h" #include "quick.h" #include "insert.h" #include "select.h"
/************************************************************* * > File Name : P3372_2.cpp * > Author : Tony * > Created Time : 2019/05/29 15:08:58 * > Algorithm : [DataStructure]SegmentTree **************************************************************/ #include <bits/stdc++.h> using namespace std; const int maxn = 100010; struct SegmentTree { int l, r; long long sum, add; #define l(x) tree[x].l #define r(x) tree[x].r #define sum(x) tree[x].sum #define add(x) tree[x].add } tree[maxn * 4]; int a[maxn], n, m; void build(int p, int l, int r) { l(p) = l, r(p) = r; if (l == r) { sum(p) = a[l]; return; } int mid = (l + r) >> 1; build(p * 2, l, mid); build(p * 2 + 1, mid + 1, r); sum(p) = sum(p * 2) + sum(p * 2 + 1); } void pushdown(int p) { if (add(p)) { sum(p * 2) += add(p) * (r(p * 2) - l(p * 2) + 1); sum(p * 2 + 1) += add(p) * (r(p * 2 + 1) - l(p * 2 + 1) + 1); add(p * 2) += add(p); add(p * 2 + 1) += add(p); add(p) = 0; } } void update(int p, int l, int r, int d) { if (l <= l(p) && r >= r(p)) { sum(p) += (long long)d * (r(p) - l(p) + 1); add(p) += d; return; } pushdown(p); int mid = (l(p) + r(p)) >> 1; if (l <= mid) update(p * 2, l, r, d); if (r > mid) update(p * 2 + 1, l, r, d); sum(p) = sum(p * 2) + sum(p * 2 + 1); } long long query(int p, int l, int r) { if (l <= l(p) && r >= r(p)) return sum(p); pushdown(p); int mid = (l(p) + r(p)) >> 1; long long ans = 0; if (l <= mid) ans += query(p * 2, l, r); if (r > mid) ans += query(p * 2 + 1, l, r); return ans; } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); build(1, 1, n); while (m--) { int opt, x, y, k; scanf("%d %d %d", &opt, &x, &y); if (opt == 1) { scanf("%d", &k); update(1, x, y, k); } else { printf("%lld\n", query(1, x, y)); } } return 0; }
/*题目:给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。*/ /*先对原数组排序,则收尾相减即为最大差值初始值high,最小差值初始值为low; 每次取最大差值和最小差值的中值mid,判断小于中值的个数count: 若count小于k,则mid = (mid + 1 + r) / 2; 若count大于k,则mid = (l + mid) / 2; 依次取中值,比较k和n,直到l<=r */ #include<stdio.h> #include<math.h> int main() { int k; int temp; int nums[3]={1,3,1}; int len = sizeof(nums); //排序 for(int i = 0;i < len-1;i++) for(int j = 0;j < len-i;j++) if(nums[j] > nums[j+1]) { temp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = temp; } //二分查找 int low=nums[1]-nums[0]; int high=nums[len-1]-nums[0]; while(low<high){ int mid=(low+high)/2; int count=0; int r= len-1; for (int i = len - 2; i >= 0; i--) { while (r > i && nums[r] - nums[i] > mid) { r--; } count += r - i; } if(count>=k){ high=mid; }else{ low=mid+1; } } scanf("%d",&k); printf("%d",low); }
/* =================================================================== ! REPITION PROBLEM on DNA You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a maximum-length substring containing only one type of character. Input: ATTCGGGA Output: 3 ======================================================================*/ #include <bits/stdc++.h> using namespace std; int find_max_len(string s) { int ans = 0, i = 0, j = 0; while (j < s.length()) { if (s[j] == s[i]) { j++; ans = max(ans, j - i); } else i = j; } return ans; } int main() { string s; cin >> s; cout << find_max_len(s) << endl; return 0; }
/* * SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #ifndef CUTELYST_ACTION_P_H #define CUTELYST_ACTION_P_H #include "action.h" #include "component_p.h" namespace Cutelyst { class ActionPrivate : public ComponentPrivate { public: virtual ~ActionPrivate() override = default; QString ns; QMetaMethod method; QMultiMap<QString, QString> attributes; Controller *controller = nullptr; QStringList emptyArgs = { QString(), QString(), QString(), QString(), QString(), QString(), QString(), QString(), QString(), }; qint8 numberOfArgs = -1; qint8 numberOfCaptures = -1; bool evaluateBool = false; bool listSignature = false; }; } // namespace Cutelyst #endif // CUTELYST_ACTION_P_H
#include "FileSpecificParameters.h" #include "../EngineLayer/MetaMorpheusException.h" #include "../EngineLayer/CommonParameters.h" using namespace EngineLayer; using namespace MzLibUtil; using namespace Proteomics::ProteolyticDigestion; using namespace MassSpectrometry; namespace TaskLayer { FileSpecificParameters::FileSpecificParameters(toml::Table tomlTable) { for (auto const& keyValuePair : tomlTable) { // we're using the name of the variable here and not a fixed string // in case the variable name changes at some point if (keyValuePair.first == "PrecursorMassTolerance") { Tolerance* t = Tolerance::ParseToleranceString(keyValuePair.second.as<std::string>()); setPrecursorMassTolerance(t); } else if (keyValuePair.first == "ProductMassTolerance") { Tolerance* t = Tolerance::ParseToleranceString(keyValuePair.second.as<std::string>()); setProductMassTolerance(t); } else if (keyValuePair.first == "Protease") { std::string name = keyValuePair.second.as<std::string>(); Protease *p = ProteaseDictionary::getDictionary()[name]; if ( p != nullptr ) { setProtease(p); } else { std::cout << "cound not find Protease " << name << " in dictionary\n"; } } else if (keyValuePair.first == "MinPeptideLength") { int MinPeptideLength = keyValuePair.second.as<int>(); setMinPeptideLength(std::make_optional(MinPeptideLength)); } else if (keyValuePair.first == "MaxPeptideLength") { int MaxPeptideLength = keyValuePair.second.as<int>(); setMaxPeptideLength(std::make_optional(MaxPeptideLength)); } else if (keyValuePair.first == "MaxMissedCleavages") { int MaxMissedCleavages = keyValuePair.second.as<int>(); setMaxMissedCleavages(std::make_optional(MaxMissedCleavages)); } else if (keyValuePair.first == "MaxModsForPeptide") { int MaxModsForPeptide = keyValuePair.second.as<int>(); setMaxModsForPeptide(std::make_optional(MaxModsForPeptide)); } else if (keyValuePair.first == "DissociationType") { // setDissociationType(keyValuePair.second->Get<MassSpectrometry::DissociationType*>()); std::string type = keyValuePair.second.as<std::string>(); MassSpectrometry::DissociationType d = MassSpectrometry::GetDissocationType::GetDissocationTypeFromString(type); setDissociationType(std::make_optional(&d)); } } } FileSpecificParameters::FileSpecificParameters() { // everything initialized to null } FileSpecificParameters::FileSpecificParameters(FileSpecificParameters *filep) { if ( filep != nullptr ) { privatePrecursorMassTolerance = filep->getPrecursorMassTolerance(); privateProductMassTolerance = filep->getProductMassTolerance(); privateProtease = filep->getProtease(); privateMinPeptideLength = filep->getMinPeptideLength(); privateMaxPeptideLength = filep->getMaxPeptideLength(); privateMaxMissedCleavages = filep->getMaxMissedCleavages(); privateMaxModsForPeptide = filep->getMaxModsForPeptide(); privateDissociationType = filep->getDissociationType(); } } Tolerance *FileSpecificParameters::getPrecursorMassTolerance() const { return privatePrecursorMassTolerance; } void FileSpecificParameters::setPrecursorMassTolerance(Tolerance *value) { privatePrecursorMassTolerance = value; } Tolerance *FileSpecificParameters::getProductMassTolerance() const { return privateProductMassTolerance; } void FileSpecificParameters::setProductMassTolerance(Tolerance *value) { privateProductMassTolerance = value; } Protease *FileSpecificParameters::getProtease() const { return privateProtease; } void FileSpecificParameters::setProtease(Protease *value) { privateProtease = value; } std::optional<int> FileSpecificParameters::getMinPeptideLength() const { return privateMinPeptideLength; } void FileSpecificParameters::setMinPeptideLength(std::optional<int> value) { privateMinPeptideLength = value; } std::optional<int> FileSpecificParameters::getMaxPeptideLength() const { return privateMaxPeptideLength; } void FileSpecificParameters::setMaxPeptideLength(std::optional<int> value) { privateMaxPeptideLength = value; } std::optional<int> FileSpecificParameters::getMaxMissedCleavages() const { return privateMaxMissedCleavages; } void FileSpecificParameters::setMaxMissedCleavages(std::optional<int> value) { privateMaxMissedCleavages = value; } std::optional<int> FileSpecificParameters::getMaxModsForPeptide() const { return privateMaxModsForPeptide; } void FileSpecificParameters::setMaxModsForPeptide(std::optional<int> value) { privateMaxModsForPeptide = value; } std::optional<DissociationType*> FileSpecificParameters::getDissociationType() const { return privateDissociationType; } void FileSpecificParameters::setDissociationType(std::optional<DissociationType*> value) { privateDissociationType = value; } toml::Table FileSpecificParameters::getFileSpecificParametersTomlTable() { toml::Table FileParameters; Tolerance *precursorMassTolerance = FileSpecificParameters::getPrecursorMassTolerance(); Tolerance *productMassTolerance = FileSpecificParameters::getProductMassTolerance(); Protease *protease = FileSpecificParameters::getProtease(); std::optional<int> minPeptideLength = FileSpecificParameters::getMinPeptideLength(); std::optional<int> maxPeptideLength = FileSpecificParameters::getMaxPeptideLength(); std::optional<int> maxMissedCleavages = FileSpecificParameters::getMaxMissedCleavages(); std::optional<int> maxModsforPeptide = FileSpecificParameters::getMaxModsForPeptide(); std::optional<DissociationType*> dissociationType = FileSpecificParameters::getDissociationType(); if (precursorMassTolerance != nullptr){ FileParameters["PrecursorMassTolerance"] = std::to_string(precursorMassTolerance->getValue()); } if (productMassTolerance != nullptr){ FileParameters["ProductMassTolerance"] = std::to_string(productMassTolerance->getValue()); } if (protease != nullptr){ FileParameters["Protease"] = protease->getName(); FileParameters["CleavageSpecificity"] = Proteomics::ProteolyticDigestion::CleavageSpecificityExtension::GetCleavageSpecificityAsString(protease->getCleavageSpecificity()); FileParameters["PsiMsAccessionNumber"] = protease->getPsiMsAccessionNumber(); FileParameters["PsiMsName"] = protease->getPsiMsName(); //how to handle DigestionMotif? Protease has a vector of DigestionMotifs. //Each DigestionMotif has 3 public string attributes: InducingCleavage, PreventingCleavage, ExcludeFromWildcard //And one int attribute: CutIndex } if (minPeptideLength.has_value()){ FileParameters["MinPeptideLength"] = std::to_string(minPeptideLength.value()); } if (maxPeptideLength.has_value()){ FileParameters["MaxPeptideLength"] = std::to_string(maxPeptideLength.value()); } if (maxMissedCleavages.has_value()){ FileParameters["MaxMissedCleavages"] = std::to_string(maxMissedCleavages.value()); } if (maxModsforPeptide.has_value()){ FileParameters["MaxModsforPeptide"] = std::to_string(maxModsforPeptide.value()); } if (dissociationType.has_value()){ FileParameters["DissociationType"] = MassSpectrometry::GetDissocationType::GetDissocationTypeAsString(*dissociationType.value()); } return FileParameters; } #ifdef NONSENSE void FileSpecificParameters::ValidateFileSpecificVariableNames() { CommonParameters *temp = new CommonParameters(); if ("PrecursorMassTolerance" != "PrecursorMassTolerance") { delete temp; throw MetaMorpheusException("Precursor tol variable name is inconsistent"); } if ("ProductMassTolerance" != "ProductMassTolerance") { delete temp; throw MetaMorpheusException("Product tol variable name is inconsistent"); } if ("Protease" != "Protease") { delete temp; throw MetaMorpheusException("Protease variable name is inconsistent"); } if ("MinPeptideLength" != "MinPeptideLength") { delete temp; throw MetaMorpheusException("Min peptide length variable name is inconsistent"); } if ("MaxPeptideLength" != "MaxPeptideLength") { delete temp; throw MetaMorpheusException("Max peptide length variable name is inconsistent"); } if ("MaxMissedCleavages" != "MaxMissedCleavages") { delete temp; throw MetaMorpheusException("Max missed cleavages variable name is inconsistent"); } if ("MaxModsForPeptide" != "MaxModsForPeptide") { delete temp; throw MetaMorpheusException("Max mods per peptide variable name is inconsistent"); } delete temp; } #endif }
#include <algorithm> #include <iostream> int main() { int a = 2; int b = 50; std::cout << "a = " << a << '\n' << "b = " << b << '\n' << '\n'; std::swap(a, b); std::cout << "a = " << a << '\n' << "b = " << b << '\n'; return 0; }
/************************************************************* Author : qmeng MailTo : qmeng1128@163.com QQ : 1163306125 Blog : http://blog.csdn.net/Mq_Go/ Create : 2018-03-14 14:45:37 Version: 1.0 **************************************************************/ #include <cstdio> #include <iostream> #include <vector> #include <algorithm> using namespace std; struct stu{ string name; int a; int b; int grade; }; bool cmp(stu s1,stu s2){ return s1.grade!=s2.grade ? s1.grade>s2.grade : s1.a!=s2.a ? s1.a > s2.a : s1.name < s2.name; } int n,t1,t2; vector<stu> ss,sm,mm,ms; int main(){ cin >> n >> t1 >> t2; stu s; int k = 0; for(int i = 0 ; i < n ; i++){ cin >> s.name >> s.a >> s.b; s.grade = s.a + s.b; if(s.a>=t1 && s.b>=t1){ if(s.a>=t2 && s.b>=t2){ss.push_back(s); }else if(s.a>=t2){sm.push_back(s); }else if(s.b<s.a){mm.push_back(s); }else{ms.push_back(s); } k++; } } cout << k << endl; sort(ss.begin(),ss.end(),cmp); for(int i = 0 ; i < ss.size() ; i++)cout<<ss[i].name<<" "<<ss[i].a<<" "<<ss[i].b<<endl; sort(sm.begin(),sm.end(),cmp); for(int i = 0 ; i < sm.size() ; i++)cout<<sm[i].name<<" "<<sm[i].a<<" "<<sm[i].b<<endl; sort(mm.begin(),mm.end(),cmp); for(int i = 0 ; i < mm.size() ; i++)cout<<mm[i].name<<" "<<mm[i].a<<" "<<mm[i].b<<endl; sort(ms.begin(),ms.end(),cmp); for(int i = 0 ; i < ms.size() ; i++)cout<<ms[i].name<<" "<<ms[i].a<<" "<<ms[i].b<<endl; return 0; }
#ifndef WEBXX_HTTP_SERVER #define WEBXX_HTTP_SERVER #define BOOST_ALL_DYN_LINK #include "../log.hh" #include <iostream> #include <fstream> #include <functional> #include <vector> #include <algorithm> #include <boost/asio.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/sources/severity_feature.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/utility/manipulators/add_value.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/utility/setup/common_attributes.hpp> namespace webxx { namespace http { static constexpr size_t data_chunk_size{1024}; std::string rcv_msg(boost::asio::ip::tcp::socket &socket); std::string requestHost(const std::string & request); std::string extractContent(const std::string & request); std::string http200(const std::string & content); std::string http404(); class Handler { public: using RouteHandler = std::function<std::string(std::string)>; enum class ReturnType { HTTP200, HTTP404, HTML }; Handler(std::string route, RouteHandler impl); const std::string & route() const; std::string operator()(std::string) const; ReturnType return_type{ReturnType::HTTP200}; private: std::string m_route; RouteHandler m_impl; }; class Server { public: Server(unsigned short port, std::string root, std::string homepage); unsigned short port(); std::string root(); void start(); static bool isGet(const std::string & request); static bool isPost(const std::string & request); void addHandler(Handler); std::string getStaticContent(std::string path); private: unsigned short m_port; std::string m_root; std::string m_homepage; boost::asio::io_service m_io_service; boost::asio::ip::tcp::acceptor m_acceptor; boost::log::sources::severity_logger<LogLevel> m_logger; std::vector<Handler> m_handlers; void handleGet(boost::asio::ip::tcp::socket &, const std::string & request); void handlePost(boost::asio::ip::tcp::socket &, const std::string & request); std::string getRoute(const std::string & request) const; std::string globRequestRoute(std::string route) const; void logRoute(std::string route); void logRequestor(boost::asio::ip::tcp::socket & socket); void handleOr(boost::asio::ip::tcp::socket & socket, const std::string & request, std::string orElse); void serveStaticContent(boost::asio::ip::tcp::socket & socket, std::string path); }; }}//namespace webxx::http #endif
// // SMFontColor.cpp // SMFrameWork // // Created by KimSteve on 2016. 11. 14.. // // #include "SMFontColor.h" #include "../Util/ViewUtil.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID const char* SMFontConst::SystemFontRegular = "Arial"; const char* SMFontConst::SystemFontBold = "Arial-medium"; const char* SMFontConst::SystemFontLight = "Arial-light"; #elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC const char* SMFontConst::SystemFontRegular = "Helvetica"; const char* SMFontConst::SystemFontBold = "Helvetica-Bold"; const char* SMFontConst::SystemFontLight = "Helvetica-Light"; // do not use #else const char* SMFontConst::SystemFontRegular = "sans-serif"; const char* SMFontConst::SystemFontBold = "sans-serif-medium"; const char* SMFontConst::SystemFontLight = "sans-serif-light"; #endif const char* SMFontConst::MontSerratRegular = "fonts/Montserrat-Regular.ttf"; const char* SMFontConst::MontSerratBold = "fonts/Montserrat-Bold.ttf"; const char* SMFontConst::NotoSansLight = "fonts/NotoSansKR-Light.otf"; const char* SMFontConst::NotoSansRegular = "fonts/NotoSansKR-Regular.otf"; const char* SMFontConst::NotoSansMedium = "fonts/NotoSansKR-Medium.otf"; const char* SMFontConst::NotoSansBold = "fonts/NotoSansKR-Bold.otf"; const char* SMFontConst::SFProDisplayThin = "fonts/SFProDisplay-Thin.ttf"; const char* SMFontConst::SFProDisplayLight = "fonts/SFProDisplay-Light.ttf"; const char* SMFontConst::SFProDisplayMedium = "fonts/SFProDisplay-Medium.ttf"; const char* SMFontConst::SFProDisplayBold = "fonts/SFProDisplay-Bold.ttf"; // RGB, A const cocos2d::Color4F SMColorConst::COLOR_F_WHITE = MAKE_COLOR4F(0xffffff, 1);; const cocos2d::Color4F SMColorConst::COLOR_F_BLACK = MAKE_COLOR4F(0x000000, 1); const cocos2d::Color4F SMColorConst::COLOR_F_EEEFF1 = MAKE_COLOR4F(0xeeeff1, 1); const cocos2d::Color4F SMColorConst::COLOR_F_ADAFB3 = MAKE_COLOR4F(0xadafb3, 1); const cocos2d::Color4F SMColorConst::COLOR_F_DBDCDF = MAKE_COLOR4F(0xdbdcdf, 1); const cocos2d::Color4F SMColorConst::COLOR_F_666666 = MAKE_COLOR4F(0x666666, 1); const cocos2d::Color4F SMColorConst::COLOR_F_999999 = MAKE_COLOR4F(0x999999, 1); const cocos2d::Color4F SMColorConst::COLOR_F_dddddd = MAKE_COLOR4F(0xdddddd, 1); const cocos2d::Color4F SMColorConst::COLOR_F_333333 = MAKE_COLOR4F(0x333333, 1); const cocos2d::Color4F SMColorConst::COLOR_F_222222 = MAKE_COLOR4F(0x222222, 1); const cocos2d::Color4F SMColorConst::COLOR_F_e94253 = MAKE_COLOR4F(0xe94253, 1); const cocos2d::Color4F SMColorConst::COLOR_F_37c267 = MAKE_COLOR4F(0x37c267, 1); const cocos2d::Color4F SMColorConst::COLOR_F_8b6bff = MAKE_COLOR4F(0x8b6bff, 1); const cocos2d::Color4F SMColorConst::COLOR_F_8768f8 = MAKE_COLOR4F(0x8768f8, 1); const cocos2d::Color4F SMColorConst::COLOR_F_26cec1 = MAKE_COLOR4F(0x26cec1, 1); const cocos2d::Color4F SMColorConst::COLOR_F_eeeeee = MAKE_COLOR4F(0xeeeeee, 1); const cocos2d::Color4F SMColorConst::COLOR_F_cccccc = MAKE_COLOR4F(0xcccccc, 1); const cocos2d::Color4F SMColorConst::COLOR_F_f3f3f3 = MAKE_COLOR4F(0xf3f3f3, 1); // RGB const cocos2d::Color3B SMColorConst::COLOR_B_WHITE = MAKE_COLOR3B(0xffffff); const cocos2d::Color3B SMColorConst::COLOR_B_BLACK = MAKE_COLOR3B(0x000000); const cocos2d::Color3B SMColorConst::COLOR_B_EEEFF1 = MAKE_COLOR3B(0xeeeff1); const cocos2d::Color3B SMColorConst::COLOR_B_ADAFB3 = MAKE_COLOR3B(0xadafb3); const cocos2d::Color3B SMColorConst::COLOR_B_DBDCDF = MAKE_COLOR3B(0xdbdcdf); const cocos2d::Color3B SMColorConst::COLOR_B_666666 = MAKE_COLOR3B(0x666666); const cocos2d::Color3B SMColorConst::COLOR_B_999999 = MAKE_COLOR3B(0x999999); const cocos2d::Color3B SMColorConst::COLOR_B_dddddd = MAKE_COLOR3B(0xdddddd); const cocos2d::Color3B SMColorConst::COLOR_B_333333 = MAKE_COLOR3B(0x333333); const cocos2d::Color3B SMColorConst::COLOR_B_222222 = MAKE_COLOR3B(0x222222); const cocos2d::Color3B SMColorConst::COLOR_B_e94253 = MAKE_COLOR3B(0xe94253); const cocos2d::Color3B SMColorConst::COLOR_B_37c267 = MAKE_COLOR3B(0x37c267); const cocos2d::Color3B SMColorConst::COLOR_B_8b6bff = MAKE_COLOR3B(0x8b6bff); const cocos2d::Color3B SMColorConst::COLOR_B_8768f8 = MAKE_COLOR3B(0x8768f8); const cocos2d::Color3B SMColorConst::COLOR_B_26cec1 = MAKE_COLOR3B(0x26cec1); const cocos2d::Color3B SMColorConst::COLOR_B_eeeeee = MAKE_COLOR3B(0xeeeeee); const cocos2d::Color3B SMColorConst::COLOR_B_cccccc = MAKE_COLOR3B(0xcccccc); const cocos2d::Color3B SMColorConst::COLOR_B_f3f3f3 = MAKE_COLOR3B(0xf3f3f3); // ARGB const cocos2d::Color4B SMColorConst::COLOR_4B_WHITE = MAKE_COLOR4B(0xffffffff); const cocos2d::Color4B SMColorConst::COLOR_4B_BLACK = MAKE_COLOR4B(0xff000000); const cocos2d::Color4B SMColorConst::COLOR_4B_EEEFF1 = MAKE_COLOR4B(0xffeeeff1); const cocos2d::Color4B SMColorConst::COLOR_4B_ADAFB3 = MAKE_COLOR4B(0xffadafb3); const cocos2d::Color4B SMColorConst::COLOR_4B_DBDCDF = MAKE_COLOR4B(0xffdbdcdf); const cocos2d::Color4B SMColorConst::COLOR_4B_666666 = MAKE_COLOR4B(0xff666666); const cocos2d::Color4B SMColorConst::COLOR_4B_999999 = MAKE_COLOR4B(0xff999999); const cocos2d::Color4B SMColorConst::COLOR_4B_dddddd = MAKE_COLOR4B(0xffdddddd); const cocos2d::Color4B SMColorConst::COLOR_4B_333333 = MAKE_COLOR4B(0xff333333); const cocos2d::Color4B SMColorConst::COLOR_4B_222222 = MAKE_COLOR4B(0xff222222); const cocos2d::Color4B SMColorConst::COLOR_4B_e94253 = MAKE_COLOR4B(0xffe94253); const cocos2d::Color4B SMColorConst::COLOR_4B_37c267 = MAKE_COLOR4B(0xff37c267); const cocos2d::Color4B SMColorConst::COLOR_4B_8b6bff = MAKE_COLOR4B(0xff8b6bff); const cocos2d::Color4B SMColorConst::COLOR_4B_8768f8 = MAKE_COLOR4B(0xff8768f8); const cocos2d::Color4B SMColorConst::COLOR_4B_26cec1 = MAKE_COLOR4B(0xff26cec1); const cocos2d::Color4B SMColorConst::COLOR_4B_eeeeee = MAKE_COLOR4B(0xffeeeeee); const cocos2d::Color4B SMColorConst::COLOR_4B_cccccc = MAKE_COLOR4B(0xffcccccc); const cocos2d::Color4B SMColorConst::COLOR_4B_f3f3f3 = MAKE_COLOR4B(0xfff3f3f3);
/* Polynomial addition in C++ program */ #include <iostream> class Polynomial { double a, b, c; public: Polynomial() {} Polynomial(const Polynomial &poly) { a = poly.a; b = poly.b; c = poly.c; } Polynomial(double d1, double d2, double d3) { a = d1; b = d2; c = d3; } Polynomial operator+(const Polynomial &poly) { double temp1 = a + poly.a; double temp2 = b + poly.b; double temp3 = c + poly.c; Polynomial polynomial(temp1, temp2, temp3); return polynomial; } friend std::ostream &operator<<(std::ostream &out, const Polynomial &poly) { if (poly.a != 0) { out << poly.a << "x2"; } if (poly.b != 0) { out << ((poly.b > 0) ? " + " : " "); out << poly.b << "x"; } out << ((poly.c > 0) ? " + " : " "); out << poly.c; return out; } }; int main() { Polynomial q1(3, 4, -2), q2(0, -4, 10); std::cout << "First Polynomial: " << q1 << std::endl; std::cout << "Second Polynomial: " << q2 << std::endl; Polynomial sum; sum = q1 + q2; std::cout << q1 << " : q1\n"; std::cout << q2 << " : q2\n"; std::cout << sum << " : q1 + q2\n"; }
/* "Minimal" sketch to demonstrate emonLibCM This sketch assumes that the default values for the emonTx V3.4 are applicable, that no input calibration is required, mains frequency is 50 Hz and data logging period interval is 10 s, pulse counting and temperature monitoring are not required, and that 4 'standard' 100 A CTs and the UK a.c. adapter from the OEM Shop are being used. */ #include <Arduino.h> #include "emonLibCM.h" #define RF69_COMPAT 1 // Set to 1 if using RFM69CW, or 0 if using RFM12B #include <JeeLib.h> // https://github.com/jcw/jeelib - Tested with JeeLib 10 April 2017 // ISR(WDT_vect) { Sleepy::watchdogEvent(); } #define RF_freq RF12_433MHZ // Frequency of radio module can be RF12_433MHZ, RF12_868MHZ or RF12_915MHZ. // - You must use the one matching the module you have. const int nodeID = 10; // node ID for this emonTx. This sketch does NOT interrogate the DIP switch. const int networkGroup = 210; // wireless network group // - needs to be same as emonBase / emonPi and emonGLCD. OEM default is 210 /* emonhub.conf nodeid is 10 - switch is ignored) See: https://github.com/openenergymonitor/emonhub/blob/emon-pi/configuration.md [[10]] nodename = emontx1 [[[rx]]] names = power1, power2, power3, power4, vrms, temp1, temp2, temp3, temp4, temp5, temp6, pulse datacode = h scales = 1,1,1,1,0.01,0.1,0.1,0.1,0.1,0.1,0.1,1 units =W,W,W,W,V,C,C,C,C,C,C,p */ typedef struct {int power1, power2, power3, power4, Vrms, T1, T2, T3, T4, T5, T6; unsigned long pulseCount; } PayloadTX; // package the data for RF comms PayloadTX emontx; // create an instance void setup() { Serial.begin(9600); Serial.println("Set baud=115200"); Serial.end(); Serial.begin(115200); Serial.println("\nEmonTx v3.4 EmonLibCM Continuous Monitoring Minimal Demo"); rf12_initialize(nodeID, RF_freq, networkGroup); // initialize radio module EmonLibCM_Init(); // Start continuous monitoring. } void loop() { if (EmonLibCM_Ready()) { Serial.println(EmonLibCM_acPresent()?"AC present ":"AC missing "); delay(5); emontx.power1 = EmonLibCM_getRealPower(0); // Copy the desired variables ready for transmission emontx.power2 = EmonLibCM_getRealPower(1); emontx.power3 = EmonLibCM_getRealPower(2); emontx.power4 = EmonLibCM_getRealPower(3); emontx.Vrms = EmonLibCM_getVrms() * 100; rf12_sendNow(0, &emontx, sizeof emontx); //send data delay(50); Serial.print(" V=");Serial.println(EmonLibCM_getVrms()); for (byte ch=0; ch<4; ch++) { Serial.print("Ch ");Serial.print(ch+1); Serial.print(" I=");Serial.print(EmonLibCM_getIrms(ch),3); Serial.print(" W=");Serial.print(EmonLibCM_getRealPower(ch)); Serial.print(" VA=");Serial.print(EmonLibCM_getApparentPower(ch)); Serial.print(" Wh=");Serial.print(EmonLibCM_getWattHour(ch)); Serial.print(" pf=");Serial.print(EmonLibCM_getPF(ch),4); Serial.println(); delay(10); } delay(10); } else rf12_recvDone(); }
#ifndef __ItemFinalPoint_H__ #define __ItemFinalPoint_H__ #include "Item.h" class ItemFinalPoint : public Item { public: static ItemFinalPoint* create(CCDictionary* dict); bool init(CCDictionary* dict); void collision(); }; #endif
#include <stdio.h> #include <string.h> #include <stdlib.h> const int MAX_ELEMENT = 10; struct node { char name[255]; node *next; // buat Friends kalau di project Study Network // node *up; // buat post kalau di project Study Network }*head[MAX_ELEMENT], *tail[MAX_ELEMENT]; // hash angka -- simplenya angka modulo MAX_ELEMENT kalau misalkan angka cukup random // kalau angka mirip dan kurang random, buat random terlebih dahulu dengan memperlebar range-nya. // 20 * 20 % MAX_ELEMENT; // 20 -> '2' + '0' = ASCII 2 + ASCII 0 + ASCII X % MAX_ELEMENT; // di mana X ini adalah rand() -> random value kelipatan 13 // ATAU // di mana X ini adalah rand() -> random value kelipatan Y // di mana Y adalah random prime number dari 0 sampai 100. Ini akan semakin memperbesar kemungkinan range. // random sama pas dicek run meski random banyak // ini yang dinamakan dengan Prime Hashing // Cari saja Fibonacci Hashing node *create_node(const char *string) { node *temp = (node*)malloc(sizeof(node)); strcpy(temp -> name, string); temp -> next = NULL; return temp; } void push_friends() { // pakai next } void push_post() { // pakai up } unsigned long djb2(const char *string) // hashing function algorithm untuk menghasilkan angka dari sebuah string { unsigned long hash = 5381; int c; while ((c = *string++)) { hash = ((hash << 5) + hash) + c; } } // tergantung soal -- biasa diberitahu nama hash function apa // biasa keluar di BINUS hash function -- ASCII sum sesuai nama ditambhakn di karakter void insert(const char *string) { // 0 -> .. -> .. // .. 1 -> .. // int index = djb2(string); if (head[index] == NULL) // jika head kosong { head[index] = tail[index]; } else // jika head telah terisi { node *new_node = create_node(string); tail[index] -> next = new_node; tail[index] = new_node; } } void traverse_linked_list (int i) { if (head[i]) { node *current = head[i]; while (current) { printf("%s -> ", current -> name); current = current -> next; } } } void view() { for (int i = 0; i < MAX_ELEMENT; i++) { if (head[i]) // kalau ada head, dia akan taruh head di current { // node *current = head[i]; // kalau kalian mau ada versi yang lebih modular-nya traverse_linked_list(i); puts(""); } else { puts("NULL"); } } }
#include <bits/stdc++.h> using namespace std; int main() { int N; bool xx = false; while (cin >> N, N) { if (xx) cout << endl; xx = true; string id[100001]; priority_queue<int, vector<int>, greater<int>> ordem; while (N--) { string a; int b; cin >> a >> b; id[b] = a; ordem.push(b); } while (!ordem.empty()) { cout << id[ordem.top()] << endl; ordem.pop(); } } return 0; }
#include "graphicscontroller.h" #include "options.h" #include <random> GraphicsController::GraphicsController() { d3dClass = 0; m_camera = 0; m_lights = 0; shaderManager = 0; models = 0; m_Frustum = 0; } GraphicsController::GraphicsController(const GraphicsController&) { } GraphicsController::~GraphicsController() { } bool GraphicsController::Initialize(int screenWidth, int screenHeight, HWND hwnd) { bool result; D3DXMATRIX baseViewMatrix; // Create the Direct3D object. d3dClass = new D3DClass; if (!d3dClass) { return false; } // Initialize the Direct3D object. result = d3dClass->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR); if (!result) { MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK); return false; } //create Camera m_camera = new Camera(D3DXVECTOR3(0.0f, 0.0f, -3.0f), D3DXVECTOR3(0.0f, 0.0f, 1.0f)); // Create the frustum object. m_Frustum = new Frustum(); //create light-vector m_lights = new std::vector<Light>(); addLight(D3DXVECTOR3(-10.0f, 1.0f, -10.0), D3DXVECTOR3(0.0, 0.0, 1.0), D3DXVECTOR4(1.0, 1.0, 1.0, 0.9)); addLight(D3DXVECTOR3(10.0f, 10.0f, -10.0), D3DXVECTOR3(0.0, 0.0, 1.0), D3DXVECTOR4(1.0, 1.0, 1.0, 0.9)); addLight(D3DXVECTOR3(10.0f, 10.0f, 10.0), D3DXVECTOR3(0.0, 0.0, 1.0), D3DXVECTOR4(1.0, 1.0, 1.0, 0.9)); addLight(D3DXVECTOR3(-10.0f, 1.0f, 10.0), D3DXVECTOR3(0.0, 0.0, 1.0), D3DXVECTOR4(1.0, 1.0, 1.0, 0.9)); //Create models models = new std::vector<StandardModel*>(); //Add the first model StandardModel* catModel = new StandardModel("../WeberEngine/data/models/cat.txt", L"../WeberEngine/data/textures/cat.dds", d3dClass->GetDevice()); models->push_back(catModel); //Add the second model StandardModel* appleModel = new StandardModel("../WeberEngine/data/models/apple.txt", L"../WeberEngine/data/textures/apple.dds", d3dClass->GetDevice()); models->push_back(appleModel); //Add the cube model //StandardModel* cubeModel = new StandardModel("../WeberEngine/data/models/cube.txt", L"../WeberEngine/data/textures/apple.dds", d3dClass->GetDevice()); //models->push_back(cubeModel); //Add the boden StandardModel* bodenModel = new StandardModel("../WeberEngine/data/models/boden.txt", L"../WeberEngine/data/textures/boden.dds", d3dClass->GetDevice()); models->push_back(bodenModel); //Initialize all models for each (StandardModel* model in *models) { //normal initialize model->Initialize(); } shaderManager = new ShaderManager(); if (!shaderManager) { MessageBox(hwnd, L"Could not create the shaderManager.", L"Error", MB_OK); return false; } result = shaderManager->InitializeAll(d3dClass->GetDevice(), hwnd); if (!result) { MessageBox(hwnd, L"Could not initialize the shader-objects.", L"Error", MB_OK); return false; } //Perform Model transformations: appleModel->scaleAndTranslateModel(0.002f, 0.002f, 0.002f, 1.0f, 0.0f, 0.0f); } void GraphicsController::ShutDown() { if (m_Frustum) { delete m_Frustum; m_Frustum = 0; } if (d3dClass) { d3dClass->Shutdown(); delete d3dClass; d3dClass = 0; } delete(m_camera); m_lights->clear(); delete(m_lights); for each (StandardModel* model in *models) { model->ShutDown(); } delete(models); if (shaderManager) { shaderManager->ShutDownAll(); } } float RandomNumber(float Min, float Max) { return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min; } /** * This Method is executed in every cycle of the Display Run-Method. It produces one Frame * on the graphics card by rendering all models/texts etc on the graphics card. */ void GraphicsController::buildFrame() { D3DXMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix; viewMatrix = *m_camera->GetViewMatrix(); d3dClass->GetWorldMatrix(worldMatrix); d3dClass->GetProjectionMatrix(projectionMatrix); d3dClass->GetOrthoMatrix(orthoMatrix); // Construct the frustum. m_Frustum->ConstructFrustum(SCREEN_DEPTH, projectionMatrix, viewMatrix); D3DXVECTOR4 lightPositions[4]; lightPositions[0] = D3DXVECTOR4(*m_camera->GetPosition(), 1.0f); //lightPositions[0] = D3DXVECTOR4(m_lights->at(0).getPosition(), 1.0f); for (size_t i = 1; i < 4; i++) { lightPositions[i] = D3DXVECTOR4(m_lights->at(i).getPosition(), 1.0f); } //TEST //lightPositions[3] = D3DXVECTOR4(RandomNumber(-10.0f, 10.0f), RandomNumber(-5.0f, 20.0f), RandomNumber(0.0f, 10.0f), 1.0f); D3DXVECTOR4 lightColors[4]; lightColors[0] = D3DXVECTOR4(1.0f, 1.0f, 1.0f, 1.0f); lightColors[1] = D3DXVECTOR4(1.0f, 0.0f, 0.0f, 1.0f); lightColors[2] = D3DXVECTOR4(0.0f, 1.0f, 0.0f, 1.0f); lightColors[3] = D3DXVECTOR4(0.0f, 0.0f, 1.0f, 1.0f); int modelIndex; RenderData renderData; renderData.cameraPosition = *m_camera->GetPosition(); renderData.deviceContext = d3dClass->GetDeviceContext(); renderData.k_s = D3DXVECTOR3(0.4, 0.4, 0.4); renderData.n = 80.0f; renderData.projectionMatrix = projectionMatrix; renderData.viewMatrix = viewMatrix; renderData.worldMatrix = worldMatrix; renderData.lightPositions = lightPositions; // Clear the buffers to begin the scene. d3dClass->BeginScene(0.0f, 0.0f, 0.0f, 1.0f); // Turn off alpha blending after rendering the text. d3dClass->TurnOffAlphaBlending(); // Turn the Z buffer back on now that all 2D rendering has completed. d3dClass->TurnZBufferOn(); bool renderSuccessful = false; for (modelIndex = 0; modelIndex < models->size(); modelIndex++) { //check if the model lies in the frustum D3DXVECTOR3 minPoint = D3DXVECTOR3(0.0f, 0.0f, 0.0f); D3DXVECTOR3 maxPoint = D3DXVECTOR3(0.0f, 0.0f, 0.0f); models->at(modelIndex)->getBoundingBox(minPoint, maxPoint); if (m_Frustum->CheckBB(minPoint, maxPoint)) { //first load model data to graphics card, then render it models->at(modelIndex)->LoadModelDataToGraphicsCard(d3dClass->GetDeviceContext()); //load model-internal data to RenderData int indexCount = models->at(modelIndex)->GetIndexCount(); ID3D11ShaderResourceView* texture = models->at(modelIndex)->GetTexture(); //renderData.indexCount = indexCount; //renderData.texture = texture; //PhongShader Auffuf //renderSuccessful = phongShadering->Render(&renderData); //LightShader-Aufruf shaderManager->RenderLightShader(d3dClass->GetDeviceContext(), indexCount, worldMatrix, viewMatrix, projectionMatrix, texture, lightColors, lightPositions); } } d3dClass->EndScene(); } void GraphicsController::addLight(D3DXVECTOR3 position, D3DXVECTOR3 direction, D3DXVECTOR4 color) { Light light = Light(position, direction, color); m_lights->push_back(light); } Camera* GraphicsController::getCamera() { return m_camera; }
#include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; typedef unordered_map<string, int> stringmap; int main(int argc, char *argv[]) { vector<string> answers; stringmap hash; stringmap::const_iterator got; int n; string request; cin >> n; for(int i = 0; i < n; i++){ cin >> request; got = hash.find(request); if (got == hash.end() ){ //new word hash[request] = 0; answers.push_back("OK"); } else { hash[request]++; answers.push_back(got->first + to_string(got->second)); //cout << got->first << got->second << endl; } } for (int i = 0; i < answers.size(); i++){ cout << answers[i] << endl; } //stringmap::hasher fn = hash.hash_function(); //cout << fn("lol"); return 0; }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* AWeapon.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/06 22:02:30 by eyohn #+# #+# */ /* Updated: 2021/07/07 13:24:05 by eyohn ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #ifndef _AWEAPON_HPP_ #define _AWEAPON_HPP_ #include <iostream> #include <string> class AWeapon { protected: std::string m_name; unsigned int m_apcost; unsigned int m_damage; public: AWeapon(std::string const &name, int apcost, int damage); AWeapon(const AWeapon &other); virtual ~AWeapon(); std::string const *getName() const; int getAPCost() const; int getDamage() const; virtual void attack() const = 0; AWeapon &operator= (const AWeapon &aweapon); }; std::ostream &operator<< (std::ostream &out, const AWeapon &fix); #endif
#include "../../include/Entities/Powerup.hpp" namespace Dungeon { namespace Entities { Powerup::Powerup(PowerupType type, int x, int y, int cost, std::function<void(Player*)> powerUpEffect) : Collectable(x, y) { this->cost = cost; this->powerUpEffect = powerUpEffect; this->type = type; } void Powerup::update(const InteractionData_t& interactionData, const Map* map) {} std::pair<bool, CollectableResult_t> Powerup::tryCollect(Player& player) { if (player.getCoins() < this->cost) return std::pair<bool, CollectableResult_t>(false, CollectableResult_t()); return std::pair<bool, CollectableResult_t>(true, CollectableResult_t(this->cost * -1, 0, this->powerUpEffect)); } int Powerup::getCost() { return this->cost; } PowerupType Powerup::getType() { return this->type; } void Powerup::handleCollision(GameObject& other) { return; } Powerup::~Powerup() { } } }
// // Created by Sweet Acid on 02.05.2021. // #pragma once #include <pch.h> #include <Snow/GUI/GUI.h> namespace Snow { class GUIWindow { friend class GUI; private: bool begin() { return ImGui::Begin(name.c_str(), &collapsed, window_flags); } static void end() { ImGui::End(); } protected: std::string name = "Default"; bool collapsed = false; ImGuiWindowFlags window_flags = ImGuiWindowFlags_None; virtual void pre_begin() = 0; public: GUIWindow() = default; virtual ~GUIWindow() = default; virtual void update() = 0; }; }
// This program doesn't need any description. #include<iostream> using namespace std; int main() { int x; cout<<"Enter a Number : "; cin>>x; if (x%2==0) cout<<x<<" is even Number.\n"; else cout<<x<<" is odd Number.\n"; return 0; }
#include "Application.h" #include "EnemyNinja.h" #include "ModuleEnemies.h" #include "ModuleCollision.h" EnemyNinja::EnemyNinja(int x, int y) :Enemy(x, y, time) { air.PushBack({ 19, 113, 30, 42 }); recharging.PushBack({ 414, 65, 22, 34 }); shoot.PushBack({ 458, 64, 41, 37 }); raise.PushBack({ 159, 113, 30, 42 }); raise.PushBack({ 65,113,30,42 }); raise.PushBack({ 112,113,30,42 }); raise.PushBack({ 158,113,30,42 }); raise.speed = 0.2f; run.PushBack({ 206,14,43,34 }); run.PushBack({ 253,14,48,34 }); run.PushBack({ 312,14,27,34 }); run.PushBack({ 362,14,36,34 }); run.PushBack({ 414,8,37,39 }); run.PushBack({ 206,66,43,34 }); run.PushBack({ 253,66,27,35 }); run.PushBack({ 312,67,43,34 }); run.PushBack({ 253,66,27,35 }); up.PushBack({ 362,68,27,33 }); idle.PushBack({ 362,68,27,33 }); move.PushBack({ 1.75f, 3.0f }, 8, &air); move.PushBack({ 1.75f, 3.0f }, 10, &recharging); move.PushBack({ 1.75f, 3.0f }, 40, &shoot); move.PushBack({ 1.0f, 0.0f }, 20, &raise); move.PushBack({ -1.5f, 0.0f }, 40, &run); move.PushBack({ 5.50f,-4.00f }, 80, &up); move.PushBack({ 0.0f,0.0f }, 10000, &idle); animation = &air; collider = App->collision->AddCollider({ 0, 0, 30, 30 }, COLLIDER_TYPE::COLLIDER_ENEMY_NINJA, (Module*)App->enemies); originalpos.y = y; originalpos.x = x; }
/* * UAE - The Un*x Amiga Emulator * * Custom chip emulation * * (c) 1995 Bernd Schmidt, Alessandro Bissacco * (c) 2002 - 2021 Toni Wilen */ #define SPEEDUP 1 #define BLITTER_DEBUG 0 #include "sysconfig.h" #include "sysdeps.h" #include "options.h" #include "uae.h" #include "memory.h" #include "custom.h" #include "events.h" #include "newcpu.h" #include "blitter.h" #include "blit.h" #include "savestate.h" #include "debug.h" // 1 = logging // 2 = no wait detection // 4 = no D // 8 = instant // 16 = activate debugger if weird things // 32 = logging (no line) #if BLITTER_DEBUG int log_blitter = 1 | 16; #else int log_blitter = 0; #endif #define BLTCHA 0x800 #define BLTCHB 0x400 #define BLTCHC 0x200 #define BLTCHD 0x100 #define BLTDOFF 0x80 #define BLTEFE 0x10 #define BLTIFE 0x08 #define BLTFILL (BLTEFE | BLTIFE) #define BLTFC 0x04 #define BLTDESC 0x02 #define BLTLINE 0x01 #define BLTSIGN 0x40 #define BLTOVF 0x20 #define BLTSUD 0x10 #define BLTSUL 0x08 #define BLTAUL 0x04 #define BLTSING 0x02 #define BLITTER_PIPELINE_BLIT 0x0008 #define BLITTER_PIPELINE_ADDMOD 0x0010 #define BLITTER_PIPELINE_LINE 0x0020 #define BLITTER_PIPELINE_PROCESS 0x0200 #define BLITTER_PIPELINE_FINISHED 0x0400 #define BLITTER_PIPELINE_LASTD 0x1000 #define BLITTER_PIPELINE_FIRST 0x2000 #define BLITTER_PIPELINE_LAST 0x4000 /* we must not change ce-mode while blitter is running.. */ static int blitter_cycle_exact, immediate_blits; static int blt_statefile_type; uae_u16 bltcon0, bltcon1; uae_u32 bltapt, bltbpt, bltcpt, bltdpt; uae_u32 bltptx; int bltptxpos, bltptxc; static uae_u16 blineb; static int blitline, blitfc, blitfill, blitife, blitdesc, blit_ovf; static bool blitfill_idle; static int blitline_started, blitlineloop; static int blitonedot, blitlinepixel; static int blit_add; static int blit_modadda, blit_modaddb, blit_modaddc, blit_modaddd; static int blit_ch; static bool shifter_skip_b, shifter_skip_y; static bool shifter_skip_b_old, shifter_skip_y_old; static uae_u16 bltcon0_old, bltcon1_old; static bool shifter[4], shifter_out; static int shifter_first; static bool blitline_c, blitfill_c; static int blitter_delayed_debug; #ifdef BLITTER_SLOWDOWNDEBUG static int blitter_slowdowndebug; #endif struct bltinfo blt_info; static uae_u8 blit_filltable[256][4][2]; uae_u32 blit_masktable[BLITTER_MAX_WORDS]; static int blit_cyclecounter, blit_waitcyclecounter; static int blit_maxcyclecounter, blit_slowdown, blit_totalcyclecounter; static int blit_misscyclecounter; #ifdef CPUEMU_13 static int blitter_cyclecounter; static int blitter_hcounter; static int blitter_vcounter; #endif static evt_t blit_firstline_cycles; static evt_t blit_first_cycle; static int blit_last_cycle, blit_dmacount, blit_cyclecount; static int blit_faulty; static int blt_delayed_irq; static uae_u16 ddat; static int ddatuse; static int blit_dof; static int last_blitter_hpos; static uae_u16 debug_bltcon0, debug_bltcon1; static uae_u32 debug_bltapt, debug_bltbpt, debug_bltcpt, debug_bltdpt; static uae_u16 debug_bltamod, debug_bltbmod, debug_bltcmod, debug_bltdmod; static uae_u32 debug_bltafwm, debug_bltalwm; static uae_u32 debug_bltpc; static int debug_bltcop; static uae_u16 debug_bltsizev, debug_bltsizeh; static uae_u16 debug_bltadat, debug_bltbdat, debug_bltcdat; #define BLITTER_MAX_PIPELINED_CYCLES 4 #define CYCLECOUNT_FINISHED -1000 #define CYCLECOUNT_START 3 /* Blitter Idle Cycle: Cycles that are free cycles (available for CPU) and are not used by any other Agnus DMA channel. Blitter idle cycle is not "used" by blitter, CPU can still use it normally if it needs the bus. same in both block and line modes number of cycles, initial cycle, main cycle */ #if 0 #define DIAGSIZE 10 static const int blit_cycle_diagram[][DIAGSIZE] = { { 2, 0,0, 0,0 }, /* 0 -- */ { 2, 0,0, 0,4 }, /* 1 -D */ { 2, 0,3, 0,3 }, /* 2 -C */ { 3, 0,3,0, 0,3,4 }, /* 3 -CD */ { 3, 0,2,0, 0,2,0 }, /* 4 -B- */ { 3, 0,2,0, 0,2,4 }, /* 5 -BD */ { 3, 0,2,3, 0,2,3 }, /* 6 -BC */ { 4, 0,2,3,0, 0,2,3,4 }, /* 7 -BCD */ { 2, 1,0, 1,0 }, /* 8 A- */ { 2, 1,0, 1,4 }, /* 9 AD */ { 2, 1,3, 1,3 }, /* A AC */ { 3, 1,3,0, 1,3,4, }, /* B ACD */ { 3, 1,2,0, 1,2,0 }, /* C AB- */ { 3, 1,2,0, 1,2,4 }, /* D ABD */ { 3, 1,2,3, 1,2,3 }, /* E ABC */ { 4, 1,2,3,0, 1,2,3,4 } /* F ABCD */ }; #endif /* following 4 channel combinations in fill mode have extra idle cycle added (still requires free bus cycle) Condition: If D without C: Add extra cycle. */ #if 0 // Cycle sequences are now generated using same // logic as real blitter. Tables are not used anymore. static const int blit_cycle_diagram_fill[][DIAGSIZE] = { { 0 }, /* 0 -- */ { 3, 0,0,0, 0,4,0 }, /* 1 -D */ { 0 }, /* 2 -C */ { 0 }, /* 3 -CD */ { 0 }, /* 4 -B- */ { 4, 0,2,0,0, 0,2,4,0 }, /* 5 -BD */ { 0 }, /* 6 -BC */ { 0 }, /* 7 -BCD */ { 0 }, /* 8 A- */ { 3, 1,0,0, 1,4,0 }, /* 9 AD */ { 0 }, /* A AC */ { 0 }, /* B ACD */ { 0 }, /* C AB- */ { 4, 1,2,0,0, 1,2,4,0 }, /* D ABD */ { 0 }, /* E ABC */ { 0 }, /* F ABCD */ }; #endif /* -C-D C-D- ... C-D- -- line draw takes 4 cycles (-C-D) idle cycles do the same as above, 2 dma fetches (read from C, write to D, but see below) Oddities: - first word is written to address pointed by BLTDPT but all following writes go to address pointed by BLTCPT! (some kind of internal copy because all bus cyles are using normal BLTDDAT) - BLTDMOD is ignored by blitter (BLTCMOD is used) - state of D-channel enable bit does not matter! - disabling A-channel freezes the content of BPLAPT - C-channel disabled: nothing is written There is one tricky situation, writing to DFF058 just before last D write cycle (which is normally free) does not disturb blitter operation, final D is still written correctly before blitter starts normally (after 2 idle cycles) There is at least one demo that does this.. */ /* Copper pointer to Blitter register copy bug 1: -d = D (-D) 2: -c = C (-C) 3: - (-CD) 4: - (-B-) 5: - (-BD) 6: - (-BC) 7: -BcD = C, -BCd = D 8: - (A-) 9: - (AD) A: - (AC) B: A (ACD) C: - (AB-) D: - (ABD-) E: - (ABC) F: AxBxCxD = -, aBxCxD = A, 1FE,8C,RGA,8C */ void build_blitfilltable (void) { unsigned int d, fillmask; int i; for (i = 0; i < BLITTER_MAX_WORDS; i++) blit_masktable[i] = 0xFFFF; for (d = 0; d < 256; d++) { for (i = 0; i < 4; i++) { int fc = i & 1; uae_u8 data = d; for (fillmask = 1; fillmask != 0x100; fillmask <<= 1) { uae_u16 tmp = data; if (fc) { if (i & 2) data |= fillmask; else data ^= fillmask; } if (tmp & fillmask) fc = !fc; } blit_filltable[d][i][0] = data; blit_filltable[d][i][1] = fc; } } } static void record_dma_blit_val(uae_u32 v) { #ifdef DEBUGGER if (debug_dma && blitter_cycle_exact) { record_dma_read_value(v); } if (memwatch_enabled) { debug_getpeekdma_value(v); } #endif } static void record_dma_blit(uae_u16 reg, uae_u16 v, uae_u32 addr, int hpos) { #ifdef DEBUGGER if (debug_dma && blitter_cycle_exact) { if (reg == 0) { record_dma_write(reg, v, addr, hpos, vpos, DMARECORD_BLITTER, 3 + (blitline_c ? 0x20 : (blitfill_c ? 0x10 : 0))); } else { int r = 0; if (reg == 0x70) r = 2; if (reg == 0x72) r = 1; if (reg == 0x74) r = 0; record_dma_read(reg, addr, hpos, vpos, DMARECORD_BLITTER, r + (blitline_c ? 0x20 : (blitfill_c ? 0x10 : 0))); } } if (memwatch_enabled) { if (reg == 0) { uae_u32 mask = MW_MASK_BLITTER_D_N; if (blitfill_c) mask = MW_MASK_BLITTER_D_F; if (blitline_c) mask = MW_MASK_BLITTER_D_L; debug_putpeekdma_chipram(addr, v, mask, reg, 0x054); } else if (reg == 0x70) { debug_getpeekdma_chipram(addr, MW_MASK_BLITTER_C, reg, 0x48); } else if (reg == 0x72) { debug_getpeekdma_chipram(addr, MW_MASK_BLITTER_B, reg, 0x4c); } else if (reg == 0x74) { debug_getpeekdma_chipram(addr, MW_MASK_BLITTER_A, reg, 0x52); } } #endif } static void blitter_debugsave(int copper, uaecptr pc) { debug_bltcon0 = bltcon0; debug_bltcon1 = bltcon1; debug_bltsizev = blt_info.vblitsize; debug_bltsizeh = blt_info.hblitsize; debug_bltapt = bltapt; debug_bltbpt = bltbpt; debug_bltcpt = bltcpt; debug_bltdpt = bltdpt; debug_bltadat = blt_info.bltadat; debug_bltbdat = blt_info.bltbdat; debug_bltcdat = blt_info.bltcdat; debug_bltamod = blt_info.bltamod; debug_bltbmod = blt_info.bltbmod; debug_bltcmod = blt_info.bltcmod; debug_bltdmod = blt_info.bltdmod; debug_bltafwm = blt_info.bltafwm; debug_bltalwm = blt_info.bltalwm; debug_bltpc = pc; debug_bltcop = copper; } static void blitter_dump (void) { int chipsize = currprefs.chipmem.size; console_out_f(_T("PT A=%08X B=%08X C=%08X D=%08X\n"), bltapt, bltbpt, bltcpt, bltdpt); console_out_f(_T("CON0=%04X CON1=%04X DAT A=%04X B=%04X C=%04X\n"), bltcon0, bltcon1, blt_info.bltadat, blt_info.bltbdat, blt_info.bltcdat); console_out_f(_T("AFWM=%04X ALWM=%04X MOD A=%04X B=%04X C=%04X D=%04X\n"), blt_info.bltafwm, blt_info.bltalwm, blt_info.bltamod & 0xffff, blt_info.bltbmod & 0xffff, blt_info.bltcmod & 0xffff, blt_info.bltdmod & 0xffff); console_out_f(_T("PC=%08X DMA=%d\n"), m68k_getpc(), dmaen (DMA_BLITTER)); if (((bltcon0 & BLTCHA) && bltapt >= chipsize) || ((bltcon0 & BLTCHB) && bltbpt >= chipsize) || ((bltcon0 & BLTCHC) && bltcpt >= chipsize) || ((bltcon0 & BLTCHD) && bltdpt >= chipsize)) console_out_f(_T("PT outside of chipram\n")); } void blitter_debugdump(void) { console_out(_T("Blitter registers at start:\n")); console_out_f(_T("PT A=%08X B=%08X C=%08X D=%08X\n"), debug_bltapt, debug_bltbpt, debug_bltcpt, debug_bltdpt); console_out_f(_T("CON0=%04X CON1=%04X DAT A=%04X B=%04X C=%04X\n"), debug_bltcon0, debug_bltcon1, debug_bltadat, debug_bltbdat, debug_bltcdat); console_out_f(_T("AFWM=%04X ALWM=%04X MOD A=%04X B=%04X C=%04X D=%04X\n"), debug_bltafwm, debug_bltalwm, debug_bltamod, debug_bltbmod, debug_bltcmod, debug_bltdmod); console_out_f(_T("COP=%d PC=%08X\n"), debug_bltcop, debug_bltpc); console_out(_T("Blitter registers now:\n")); blitter_dump(); } static void markidlecycle(int hpos) { #ifdef DEBUGGER if (debug_dma) { record_dma_event(DMA_EVENT_BLITSTARTFINISH, hpos, vpos); } #endif } static void check_channel_mods(int hpos, int ch, uaecptr *pt) { static int blit_warned = 100; if (bltptxpos < 0) return; if (bltptxpos != hpos) return; // if CPU write and non-CE: skip if (bltptxc < 0) { if (currprefs.cpu_model >= 68020 || !currprefs.cpu_cycle_exact) { bltptxpos = -1; return; } } if (ch == bltptxc || ch == -bltptxc) { if (blit_warned > 0) { write_log(_T("BLITTER: %08X -> %08X write to %cPT ignored! %08x\n"), bltptx, *pt, ch + 'A' - 1, m68k_getpc()); blit_warned--; } bltptxpos = -1; *pt = bltptx; } } // blitter interrupt is set (and busy bit cleared) when // last "main" cycle has been finished, any non-linedraw // D-channel blit still needs 2 more cycles before final // D is written (idle cycle, final D write) // // According to schematics, AGA has workaround delay circuit // that adds 2 extra cycles if D is enabled and not line mode. // // line draw interrupt triggers when last D is written // (or cycle where last D write would have been if // ONEDOT was active) static void blitter_interrupt(void) { if (blt_info.blit_interrupt) { return; } blt_info.blit_interrupt = 1; INTREQ_INT(6, 3); #ifdef DEBUGGER if (debug_dma) { record_dma_event(DMA_EVENT_BLITIRQ, current_hpos(), vpos); } #endif } static void blitter_end(void) { blt_info.blit_main = 0; blt_info.blit_finald = 0; blt_info.blit_queued = 0; event2_remevent(ev2_blitter); unset_special(SPCFLAG_BLTNASTY); if (log_blitter & 1) { write_log(_T("cycles %d, missed %d, total %d\n"), blit_totalcyclecounter, blit_misscyclecounter, blit_totalcyclecounter + blit_misscyclecounter); } blt_info.blitter_dangerous_bpl = 0; } static void blitter_done_all(int hpos) { blt_info.blit_main = 0; blt_info.blit_finald = 0; if (m68k_interrupt_delay && hpos >= 0) { blt_info.finishhpos = hpos; } else { blt_info.finishhpos = -1; } blitter_interrupt(); blitter_done_notify(blitline); if (!blt_info.blit_queued && !blt_info.blit_finald) { blitter_end(); } } static void blitter_done_except_d(int hpos) { blt_info.blit_main = 0; if (m68k_interrupt_delay && hpos >= 0) { blt_info.finishhpos = hpos; } else { blt_info.finishhpos = -1; } blitter_interrupt(); blitter_done_notify(blitline); } static void blit_chipmem_agnus_wput(uaecptr addr, uae_u32 w, uae_u32 typemask) { if (!(log_blitter & 4)) { if (blit_dof) { w = regs.chipset_latch_rw; } #ifdef DEBUGGER debug_putpeekdma_chipram(addr, w, typemask, 0x000, 0x054); #endif chipmem_wput_indirect(addr, w); regs.chipset_latch_rw = w; } } static void blitter_dofast (void) { int i,j; uaecptr bltadatptr = 0, bltbdatptr = 0, bltcdatptr = 0, bltddatptr = 0; uae_u8 mt = bltcon0 & 0xFF; uae_u16 ashift = bltcon0 >> 12; uae_u16 bshift = bltcon1 >> 12; blit_masktable[0] = blt_info.bltafwm; blit_masktable[blt_info.hblitsize - 1] &= blt_info.bltalwm; if (bltcon0 & BLTCHA) { bltadatptr = bltapt; bltapt += (blt_info.hblitsize * 2 + blt_info.bltamod) * blt_info.vblitsize; } if (bltcon0 & BLTCHB) { bltbdatptr = bltbpt; bltbpt += (blt_info.hblitsize * 2 + blt_info.bltbmod) * blt_info.vblitsize; } if (bltcon0 & BLTCHC) { bltcdatptr = bltcpt; bltcpt += (blt_info.hblitsize * 2 + blt_info.bltcmod) * blt_info.vblitsize; } if (bltcon0 & BLTCHD) { bltddatptr = bltdpt; bltdpt += (blt_info.hblitsize * 2 + blt_info.bltdmod) * blt_info.vblitsize; } #if SPEEDUP if (blitfunc_dofast[mt] && !blitfill) { (*blitfunc_dofast[mt])(bltadatptr, bltbdatptr, bltcdatptr, bltddatptr, &blt_info); } else #endif { uae_u32 blitbhold = blt_info.bltbhold; int ashift = bltcon0 >> 12; int bshift = bltcon1 >> 12; uaecptr dstp = 0; int dodst = 0; for (j = 0; j < blt_info.vblitsize; j++) { blitfc = !!(bltcon1 & BLTFC); for (i = 0; i < blt_info.hblitsize; i++) { uae_u32 bltadat, blitahold; if (bltadatptr) { blt_info.bltadat = bltadat = chipmem_wget_indirect (bltadatptr); bltadatptr += 2; } else bltadat = blt_info.bltadat; bltadat &= blit_masktable[i]; blitahold = (((uae_u32)blt_info.bltaold << 16) | bltadat) >> ashift; blt_info.bltaold = bltadat; if (bltbdatptr) { uae_u16 bltbdat = chipmem_wget_indirect (bltbdatptr); bltbdatptr += 2; blitbhold = (((uae_u32)blt_info.bltbold << 16) | bltbdat) >> bshift; blt_info.bltbold = bltbdat; blt_info.bltbdat = bltbdat; } if (bltcdatptr) { blt_info.bltcdat = chipmem_wget_indirect (bltcdatptr); bltcdatptr += 2; } if (dodst) blit_chipmem_agnus_wput(dstp, blt_info.bltddat, MW_MASK_BLITTER_D_N); blt_info.bltddat = blit_func (blitahold, blitbhold, blt_info.bltcdat, mt) & 0xFFFF; if (blitfill) { uae_u16 d = blt_info.bltddat; int ifemode = blitife ? 2 : 0; int fc1 = blit_filltable[d & 255][ifemode + blitfc][1]; blt_info.bltddat = (blit_filltable[d & 255][ifemode + blitfc][0] + (blit_filltable[d >> 8][ifemode + fc1][0] << 8)); blitfc = blit_filltable[d >> 8][ifemode + fc1][1]; } if (blt_info.bltddat) blt_info.blitzero = 0; if (bltddatptr) { dodst = 1; dstp = bltddatptr; bltddatptr += 2; } } if (bltadatptr) bltadatptr += blt_info.bltamod; if (bltbdatptr) bltbdatptr += blt_info.bltbmod; if (bltcdatptr) bltcdatptr += blt_info.bltcmod; if (bltddatptr) bltddatptr += blt_info.bltdmod; } if (dodst) blit_chipmem_agnus_wput(dstp, blt_info.bltddat, MW_MASK_BLITTER_D_N); blt_info.bltbhold = blitbhold; } blit_masktable[0] = 0xFFFF; blit_masktable[blt_info.hblitsize - 1] = 0xFFFF; blt_info.blit_main = 0; } static void blitter_dofast_desc (void) { int i,j; uaecptr bltadatptr = 0, bltbdatptr = 0, bltcdatptr = 0, bltddatptr = 0; uae_u8 mt = bltcon0 & 0xFF; uae_u16 ashift = 16 - (bltcon0 >> 12); uae_u16 bshift = 16 - (bltcon1 >> 12); blit_masktable[0] = blt_info.bltafwm; blit_masktable[blt_info.hblitsize - 1] &= blt_info.bltalwm; if (bltcon0 & BLTCHA) { bltadatptr = bltapt; bltapt -= (blt_info.hblitsize * 2 + blt_info.bltamod) * blt_info.vblitsize; } if (bltcon0 & BLTCHB) { bltbdatptr = bltbpt; bltbpt -= (blt_info.hblitsize * 2 + blt_info.bltbmod) * blt_info.vblitsize; } if (bltcon0 & BLTCHC) { bltcdatptr = bltcpt; bltcpt -= (blt_info.hblitsize * 2 + blt_info.bltcmod) * blt_info.vblitsize; } if (bltcon0 & BLTCHD) { bltddatptr = bltdpt; bltdpt -= (blt_info.hblitsize * 2 + blt_info.bltdmod) * blt_info.vblitsize; } #if SPEEDUP if (blitfunc_dofast_desc[mt] && !blitfill) { (*blitfunc_dofast_desc[mt])(bltadatptr, bltbdatptr, bltcdatptr, bltddatptr, &blt_info); } else #endif { uae_u32 blitbhold = blt_info.bltbhold; uaecptr dstp = 0; int dodst = 0; for (j = 0; j < blt_info.vblitsize; j++) { blitfc = !!(bltcon1 & BLTFC); for (i = 0; i < blt_info.hblitsize; i++) { uae_u32 bltadat, blitahold; if (bltadatptr) { bltadat = blt_info.bltadat = chipmem_wget_indirect (bltadatptr); bltadatptr -= 2; } else bltadat = blt_info.bltadat; bltadat &= blit_masktable[i]; blitahold = (((uae_u32)bltadat << 16) | blt_info.bltaold) >> ashift; blt_info.bltaold = bltadat; if (bltbdatptr) { uae_u16 bltbdat = chipmem_wget_indirect (bltbdatptr); bltbdatptr -= 2; blitbhold = (((uae_u32)bltbdat << 16) | blt_info.bltbold) >> bshift; blt_info.bltbold = bltbdat; blt_info.bltbdat = bltbdat; } if (bltcdatptr) { blt_info.bltcdat = blt_info.bltbdat = chipmem_wget_indirect (bltcdatptr); bltcdatptr -= 2; } if (dodst) blit_chipmem_agnus_wput(dstp, blt_info.bltddat, MW_MASK_BLITTER_D_N); blt_info.bltddat = blit_func (blitahold, blitbhold, blt_info.bltcdat, mt) & 0xFFFF; if (blitfill) { uae_u16 d = blt_info.bltddat; int ifemode = blitife ? 2 : 0; int fc1 = blit_filltable[d & 255][ifemode + blitfc][1]; blt_info.bltddat = (blit_filltable[d & 255][ifemode + blitfc][0] + (blit_filltable[d >> 8][ifemode + fc1][0] << 8)); blitfc = blit_filltable[d >> 8][ifemode + fc1][1]; } if (blt_info.bltddat) blt_info.blitzero = 0; if (bltddatptr) { dstp = bltddatptr; dodst = 1; bltddatptr -= 2; } } if (bltadatptr) bltadatptr -= blt_info.bltamod; if (bltbdatptr) bltbdatptr -= blt_info.bltbmod; if (bltcdatptr) bltcdatptr -= blt_info.bltcmod; if (bltddatptr) bltddatptr -= blt_info.bltdmod; } if (dodst) blit_chipmem_agnus_wput(dstp, blt_info.bltddat, MW_MASK_BLITTER_D_N); blt_info.bltbhold = blitbhold; } blit_masktable[0] = 0xFFFF; blit_masktable[blt_info.hblitsize - 1] = 0xFFFF; blt_info.blit_main = 0; } static void blitter_line_read_b(void) { if (bltcon0 & BLTCHB) { // B (normally not enabled) record_dma_blit(0x72, 0, bltbpt, last_blitter_hpos); blt_info.bltbdat = chipmem_wget_indirect(bltbpt); regs.chipset_latch_rw = blt_info.bltbdat; record_dma_blit_val(blt_info.bltbdat); bltbpt += blt_info.bltbmod; } } static void blitter_line_read_c(void) { if (bltcon0 & BLTCHC) { // C record_dma_blit(0x70, 0, bltcpt, last_blitter_hpos); blt_info.bltcdat = chipmem_wget_indirect(bltcpt); regs.chipset_latch_rw = blt_info.bltcdat; record_dma_blit_val(blt_info.bltcdat); } } static void blitter_line_write(void) { /* D-channel state has no effect on linedraw, but C must be enabled or nothing is drawn! */ if (bltcon0 & BLTCHC) { blit_chipmem_agnus_wput(bltdpt, blt_info.bltddat, MW_MASK_BLITTER_D_L); } } static void blitter_line_minterm(uae_u16 dat) { uae_u16 mask = blt_info.bltafwm; if (dat & BLITTER_PIPELINE_LAST) { mask &= blt_info.bltalwm; } int ashift = bltcon0 >> 12; uae_u16 blitahold = (blt_info.bltadat & mask) >> ashift; if (bltcon0 & BLTCHB) { // B special case if enabled int bshift = bltcon1 >> 12; blineb = (((uae_u32)blt_info.bltbold << 16) | blt_info.bltbdat) >> bshift; } blt_info.bltbhold = (blineb & 0x0001) ? 0xFFFF : 0; blt_info.bltddat = blit_func(blitahold, blt_info.bltbhold, blt_info.bltcdat, bltcon0 & 0xFF); if (blt_info.bltddat) { blt_info.blitzero = 0; } } static void blitter_line_minterm_extra(void) { int ashift = bltcon0 >> 12; // never first or last, no masking needed. uae_u16 blitahold = blt_info.bltadat >> ashift; blt_info.bltddat = blit_func(blitahold, blt_info.bltbhold, blt_info.bltcdat, bltcon0 & 0xFF); } static void blitter_line_adat(void) { int ashift = bltcon0 >> 12; blt_info.bltaold = (((uae_u32)blt_info.bltaold << 16) | (blt_info.bltadat & blt_info.bltafwm)) >> ashift; } static void blitter_line_proc_apt(void) { if (bltcon0 & BLTCHA) { bool sign = (bltcon1 & BLTSIGN) != 0; if (sign) bltapt += (uae_s16)blt_info.bltbmod; else bltapt += (uae_s16)blt_info.bltamod; } } static void blitter_line_ovf(void) { uae_u16 ashift = bltcon0 >> 12; ashift += blit_ovf; ashift &= 15; bltcon0 &= 0x0fff; bltcon0 |= ashift << 12; blit_ovf = 0; } static void blitter_line_incx(void) { uae_u16 ashift = bltcon0 >> 12; if (ashift == 15) { bltcpt += 2; } blit_ovf = 1; } static void blitter_line_decx(void) { uae_u16 ashift = bltcon0 >> 12; if (ashift == 0) { bltcpt -= 2; } blit_ovf = -1; } static void blitter_line_decy(void) { if (bltcon0 & BLTCHC) { bltcpt -= blt_info.bltcmod; blitonedot = 0; } } static void blitter_line_incy(void) { if (bltcon0 & BLTCHC) { bltcpt += blt_info.bltcmod; blitonedot = 0; } } static void blitter_line_proc_cpt_y(void) { bool sign = (bltcon1 & BLTSIGN) != 0; if (!sign) { if (bltcon1 & BLTSUD) { if (bltcon1 & BLTSUL) blitter_line_decy(); else blitter_line_incy(); } } if (!(bltcon1 & BLTSUD)) { if (bltcon1 & BLTAUL) blitter_line_decy(); else blitter_line_incy(); } } static void blitter_line_proc_cpt_x(void) { bool sign = (bltcon1 & BLTSIGN) != 0; if (!sign) { if (!(bltcon1 & BLTSUD)) { if (bltcon1 & BLTSUL) blitter_line_decx(); else blitter_line_incx(); } } if (bltcon1 & BLTSUD) { if (bltcon1 & BLTAUL) blitter_line_decx(); else blitter_line_incx(); } } static void blitter_line_proc_status(void) { blitlinepixel = !(bltcon1 & BLTSING) || ((bltcon1 & BLTSING) && !blitonedot); blitonedot = 1; } static void blitter_line_sign(void) { bool blitsign = (uae_s16)bltapt < 0; if (blitsign) { bltcon1 |= BLTSIGN; } else { bltcon1 &= ~BLTSIGN; } } static void blitter_nxline(void) { int bshift = bltcon1 >> 12; bshift--; bshift &= 15; blineb = (blt_info.bltbdat >> bshift) | (blt_info.bltbdat << (16 - bshift)); bltcon1 &= 0x0fff; bltcon1 |= bshift << 12; } static void actually_do_blit (void) { if (blitline) { do { blitter_line_proc_status(); blitter_line_proc_apt(); if (blt_info.hblitsize > 1) { blitter_line_read_b(); blitter_line_read_c(); blitter_line_minterm(BLITTER_PIPELINE_FIRST); blitter_line_proc_cpt_x(); } if (blt_info.hblitsize > 2) { if (blitlineloop && !(bltcon1 & BLTSUD)) { blitter_line_proc_cpt_y(); blitlineloop = 0; } blitter_line_read_c(); blitter_line_minterm_extra(); } blitter_line_adat(); blitter_line_ovf(); if (blt_info.hblitsize >= 2) { if (blitlineloop) { blitter_line_proc_cpt_y(); blitlineloop = 0; } } blitter_line_sign(); blitter_nxline(); if (blitlinepixel) { blitter_line_write(); blitlinepixel = 0; } bltdpt = bltcpt; blitter_line_minterm(BLITTER_PIPELINE_FIRST | BLITTER_PIPELINE_LAST); blitlineloop = 1; blt_info.vblitsize--; } while (blt_info.vblitsize != 0); } else { if (blitdesc) blitter_dofast_desc(); else blitter_dofast(); } blt_info.blit_main = 0; } static void blitter_doit (int hpos) { if (blt_info.vblitsize == 0) { blitter_done_all(hpos); return; } actually_do_blit(); blitter_done_all(hpos); } static int makebliteventtime(int delay) { if (delay) { delay += delay - (int)(delay * (1 + currprefs.blitter_speed_throttle) + 0.5); if (delay <= 0) delay = 1; } return delay; } void blitter_handler(uae_u32 data) { static int blitter_stuck; if (!dmaen (DMA_BLITTER)) { event2_newevent (ev2_blitter, 10, 0); blitter_stuck++; if (blitter_stuck < 20000 || !immediate_blits) return; /* gotta come back later. */ /* "free" blitter in immediate mode if it has been "stuck" ~3 frames * fixes some JIT game incompatibilities */ #ifdef DEBUGGER debugtest (DEBUGTEST_BLITTER, _T("force-unstuck!\n")); #endif } blitter_stuck = 0; if (blit_slowdown > 0 && !immediate_blits) { event2_newevent (ev2_blitter, makebliteventtime(blit_slowdown), 0); blit_slowdown = -1; return; } blitter_doit(-1); } #ifdef CPUEMU_13 static bool blitshifterdebug(uae_u16 con0, bool check) { int cnt = 0; for (int i = 0; i < 4; i++) { if (shifter[i]) { cnt++; } } if (cnt != 1 || !check) { write_log(_T("Blitter shifter bits %d: CH=%c%c%c%c (%d-%d-%d-%d O=%d) PC=%08x\n"), cnt, ((con0 >> 11) & 1) ? 'A' : '-', ((con0 >> 10) & 1) ? 'B' : '-', ((con0 >> 9) & 1) ? 'C' : '-', ((con0 >> 8) & 1) ? 'D' : '-', shifter[0], shifter[1], shifter[2], shifter[3], shifter_out, M68K_GETPC); return true; } return false; } static void blit_bltset(int con) { static int blit_warned = 100; bool blit_changed = false; uae_u16 con0_old = bltcon0_old; if (con & 2) { blitdesc = bltcon1 & BLTDESC; if (!savestate_state && blit_warned > 0) { if ((bltcon1 & BLTLINE) && !blitline_started) { write_log(_T("BLITTER: linedraw enabled when blitter is active! %08x\n"), M68K_GETPC); blit_warned--; #ifdef DEBUGGER if (log_blitter & 16) activate_debugger(); #endif } else if (!(bltcon1 & BLTLINE) && blitline_started) { write_log(_T("BLITTER: linedraw disabled when blitter is active! %08x\n"), M68K_GETPC); blit_warned--; #ifdef DEBUGGER if (log_blitter & 16) activate_debugger(); #endif } if ((bltcon1 & BLTFILL) && !(bltcon1_old & BLTFILL)) { write_log(_T("BLITTER: fill enabled when blitter is active! %08x\n"), M68K_GETPC); blit_warned--; #ifdef DEBUGGER if (log_blitter & 16) activate_debugger(); #endif } else if (!(bltcon1 & BLTFILL) && (bltcon1_old & BLTFILL)) { write_log(_T("BLITTER: fill disabled when blitter is active! %08x\n"), M68K_GETPC); blit_warned--; #ifdef DEBUGGER if (log_blitter & 16) activate_debugger(); #endif } } } if (!savestate_state && blt_info.blit_main && (bltcon0_old != bltcon0 || bltcon1_old != bltcon1)) { blit_changed = true; if (blit_warned > 0) { write_log(_T("BLITTER: BLTCON0 %04x -> %04x BLTCON1 %04x -> %04x PC=%08x (%d %d)\n"), bltcon0_old, bltcon0, bltcon1_old, bltcon1, M68K_GETPC, current_hpos(), vpos); //blitter_dump(); blitshifterdebug(bltcon0_old, false); blit_warned--; if (log_blitter & 16) activate_debugger(); } bltcon0_old = bltcon0; bltcon1_old = bltcon1; } blit_ch = (bltcon0 & 0x0f00) >> 8; blitline = bltcon1 & BLTLINE; blit_ovf = (bltcon1 & BLTOVF) != 0; blitfill_idle = false; shifter_skip_b = (bltcon0 & BLTCHB) == 0; if (blitline) { shifter_skip_y = true; blitfill = 0; shifter_out = shifter_skip_y ? shifter[2] : shifter[3]; } else { int oldfill = blitfill; blitfill = (bltcon1 & BLTFILL) != 0; blitfc = !!(bltcon1 & BLTFC); blitife = !!(bltcon1 & BLTIFE); if ((bltcon1 & BLTFILL) == BLTFILL) { #ifdef DEBUGGER debugtest(DEBUGTEST_BLITTER, _T("weird fill mode\n")); #endif blitife = 0; } if (blitfill && !blitdesc) { #ifdef DEBUGGER debugtest(DEBUGTEST_BLITTER, _T("fill without desc\n")); if (log_blitter & 16) { activate_debugger(); } #endif } shifter_skip_y = (bltcon0 & (BLTCHD | BLTCHC)) != 0x300; // fill mode idle cycle needed? (D enabled but C not enabled) if (blitfill && (bltcon0 & (BLTCHD | BLTCHC)) == 0x100) { shifter_skip_y = false; blitfill_idle = true; } shifter_out = shifter_skip_y ? shifter[2] : shifter[3]; } blit_cyclecount = 4 - (shifter_skip_b + shifter_skip_y); blit_dmacount = ((bltcon0 & BLTCHA) ? 1 : 0) + ((bltcon0 & BLTCHB) ? 1 : 0) + ((bltcon0 & BLTCHC) ? 1 : 0) + (((bltcon0 & BLTCHD) && !blitline) ? 1 : 0); if (blt_info.blit_main || blt_info.blit_pending) { blitfill_c = blitfill; blitline_c = blitline; } blit_dof = 0; if ((bltcon1 & BLTDOFF) && ecs_agnus) { blit_dof = 1; #ifdef DEBUGGER debugtest(DEBUGTEST_BLITTER, _T("ECS BLTCON1 DOFF-bit set\n")); if (log_blitter & 16) activate_debugger(); #endif } if (blit_changed && blit_warned > 0 && !savestate_state) { blitshifterdebug(bltcon0, false); } } static int get_current_channel(void) { if (blit_cyclecounter < 0) { return 0; } if (blitline) { if (shifter[0]) { // A or idle if (blitter_hcounter + 1 == blt_info.hblitsize) return 5; if (bltcon0 & BLTCHA) return 1; return 0; } // B if (shifter[1] && (bltcon0 & BLTCHB)) { return 2; } // C or D if (shifter[2]) { // enabled C if (bltcon0 & BLTCHC) { if (blitter_hcounter + 1 == blt_info.hblitsize) return 4; return 3; } else { // disabled C if (blitter_hcounter + 1 == blt_info.hblitsize) return 6; } } } else { // order is important when multiple bits in shift register // C if (shifter[2] && (bltcon0 & BLTCHC)) { return 3; } // Shift stage 4 active, C enabled and other stage(s) also active: // normally would be D but becomes C. if (shifter[3] && (bltcon0 & BLTCHC) && (shifter[0] || shifter[1])) { return 3; } // A if (shifter[0] && (bltcon0 & BLTCHA)) { return 1; } // B if (shifter[1] && (bltcon0 & BLTCHB)) { return 2; } // D is disabled if position A is non-zero, even if A is disabled. if (shifter[0]) { return 0; } if (shifter_first >= 0) { return 0; } // D only if A, B and C is not currently active if (ddatuse) { // idle fill cycle: 3 = D, 4 = idle if (blitfill_idle) { // if stage 4: idle if (shifter[3]) { return 0; } // if stage 3: D if (shifter[2] && (bltcon0 & BLTCHD)) { return 4; } } else { // if stage 3 and C disabled and D enabled: D if (shifter[2] && !(bltcon0 & BLTCHC) && (bltcon0 & BLTCHD)) { return 4; } // if stage 4 and C enabled and D enabled: D if (shifter[3] && (bltcon0 & BLTCHC) && (bltcon0 & BLTCHD)) { return 4; } } } } return 0; } static uae_u16 blitter_doblit(uae_u16 dat) { uae_u32 blitahold; uae_u16 bltadat, ddat; uae_u8 mt = bltcon0 & 0xFF; uae_u16 ashift = bltcon0 >> 12; bltadat = blt_info.bltadat; if (dat & BLITTER_PIPELINE_FIRST) { bltadat &= blt_info.bltafwm; } if (dat & BLITTER_PIPELINE_LAST) { bltadat &= blt_info.bltalwm; } if (blitdesc) { blitahold = (((uae_u32)bltadat << 16) | blt_info.bltaold) >> (16 - ashift); } else { blitahold = (((uae_u32)blt_info.bltaold << 16) | bltadat) >> ashift; } blt_info.bltaold = bltadat; ddat = blit_func (blitahold, blt_info.bltbhold, blt_info.bltcdat, mt) & 0xFFFF; if (blitfill) { uae_u16 d = ddat; int ifemode = blitife ? 2 : 0; int fc1 = blit_filltable[d & 255][ifemode + blitfc][1]; ddat = (blit_filltable[d & 255][ifemode + blitfc][0] + (blit_filltable[d >> 8][ifemode + fc1][0] << 8)); blitfc = blit_filltable[d >> 8][ifemode + fc1][1]; } if (ddat) { blt_info.blitzero = 0; } return ddat; } static int blitter_next_cycle(void) { bool tmp[4]; bool out = false; bool blitchanged = false; bool dodat = false; memcpy(tmp, shifter, sizeof(shifter)); memset(shifter, 0, sizeof(shifter)); if (shifter_skip_b_old && !shifter_skip_b) { // if B skip was disabled: A goes both to B and C tmp[1] = tmp[0]; tmp[2] = tmp[0]; shifter_skip_b_old = shifter_skip_b; blitchanged = true; } else if (!shifter_skip_b_old && shifter_skip_b) { // if B skip was enabled: A goes nowhere tmp[0] = false; shifter_skip_b_old = shifter_skip_b; blitchanged = true; } if (shifter_skip_y_old && !shifter_skip_y) { // if Y skip was disabled: X goes both to Y and OUT tmp[3] = tmp[2]; shifter_skip_y_old = shifter_skip_y; blitchanged = true; } else if (!shifter_skip_y_old && shifter_skip_y) { // if Y skip was enabled: X goes nowhere tmp[2] = false; shifter_out = false; shifter_skip_y_old = shifter_skip_y; blitchanged = true; } if (shifter_out) { dodat = true; if (!blitline) { if (bltcon0 & BLTCHD) { ddatuse = true; } } blitter_hcounter++; if (blitter_hcounter >= blt_info.hblitsize) { blitter_hcounter = 0; blitter_vcounter++; if (blitter_vcounter >= blt_info.vblitsize) { shifter_out = false; blit_cyclecounter = CYCLECOUNT_FINISHED; if (!blitline) { // do we need final D write? if (ddatuse && (bltcon0 & BLTCHD)) { if (blt_info.blit_finald) { write_log(_T("blit finald already set!?\n")); } blt_info.blit_finald = 1 + 2; blt_info.blit_queued = BLITTER_MAX_PIPELINED_CYCLES; } } } } shifter[0] = shifter_out; } if (shifter_first > 0) { shifter_first = -1; shifter[0] = true; blitfc = !!(bltcon1 & BLTFC); } else { if (shifter_skip_b) { shifter[2] = tmp[0]; } else { shifter[1] = tmp[0]; shifter[2] = tmp[1]; } if (shifter_skip_y) { out = shifter[2]; } else { shifter[3] = tmp[2]; out = shifter[3]; } } shifter_out = out; if (blit_cyclecounter > 0 && blitchanged) { static int blit_warned = 100; if (blit_warned > 0) { if (blitshifterdebug(bltcon0, true)) { blit_faulty = 1; } blit_warned--; } } return dodat; } static void blitter_doddma_new(int hpos, bool addmod) { uaecptr *hpt = NULL; bool skip = false; check_channel_mods(hpos, 4, &bltdpt); bltdpt |= alloc_cycle_blitter_conflict_or(hpos, 4, &skip); // alloc_cycle_blitter() can change modulo, old modulo is used during this cycle. int mod = blit_modaddd; if (!skip) { record_dma_blit(0x00, ddat, bltdpt, hpos); blit_chipmem_agnus_wput(bltdpt, ddat, MW_MASK_BLITTER_D_N); } bool skipadd = alloc_cycle_blitter(hpos, &bltdpt, 4, addmod ? mod : 0); if (!blitline && !skipadd) { bltdpt += blit_add; } if (addmod) { bltdpt += mod; } } static void blitter_dodma_new(int ch, int hpos, bool addmod) { uae_u16 dat; uae_u32 *addr; bool skipadd = false; int mod; bool skip = false; uaecptr orptr = alloc_cycle_blitter_conflict_or(hpos, ch, &skip); switch (ch) { case 1: // A { bltapt |= orptr; check_channel_mods(hpos, 1, &bltapt); if (!skip) { uae_u16 reg = 0x74; record_dma_blit(reg, 0, bltapt, hpos); blt_info.bltadat = dat = chipmem_wget_indirect(bltapt); record_dma_blit_val(dat); regs.chipset_latch_rw = blt_info.bltadat; } addr = &bltapt; mod = blit_modadda; skipadd = alloc_cycle_blitter(hpos, &bltapt, 1, addmod ? mod : 0); break; } case 2: // B { int bshift = bltcon1 >> 12; bltbpt |= orptr; check_channel_mods(hpos, 2, &bltbpt); if (!skip) { uae_u16 reg = 0x72; record_dma_blit(reg, 0, bltbpt, hpos); blt_info.bltbdat = dat = chipmem_wget_indirect(bltbpt); record_dma_blit_val(dat); regs.chipset_latch_rw = blt_info.bltbdat; } addr = &bltbpt; mod = blit_modaddb; if (blitdesc) blt_info.bltbhold = (((uae_u32)blt_info.bltbdat << 16) | blt_info.bltbold) >> (16 - bshift); else blt_info.bltbhold = (((uae_u32)blt_info.bltbold << 16) | blt_info.bltbdat) >> bshift; blineb = blt_info.bltbhold; blt_info.bltbold = blt_info.bltbdat; skipadd = alloc_cycle_blitter(hpos, &bltbpt, 2, addmod ? mod : 0); break; } case 3: // C { bltcpt |= orptr; check_channel_mods(hpos, 3, &bltcpt); if (!skip) { uae_u16 reg = 0x70; record_dma_blit(reg, 0, bltcpt, hpos); blt_info.bltcdat = dat = chipmem_wget_indirect(bltcpt); record_dma_blit_val(dat); regs.chipset_latch_rw = blt_info.bltcdat; } addr = &bltcpt; mod = blit_modaddc; skipadd = alloc_cycle_blitter(hpos, &bltcpt, 3, addmod ? mod : 0); break; } default: abort(); } if (!blitline && !skipadd) { (*addr) += blit_add; } if (addmod) { (*addr) += mod; } } static bool blitter_idle_cycle_register_write(uaecptr addr, uae_u32 v) { addrbank *ab = &get_mem_bank(addr); if (ab != &custom_bank) return false; addr &= 0x1fe; if (v == 0xffffffff) { v = regs.chipset_latch_rw; } if (addr == 0x40) { bltcon0 = v; blit_bltset(1); return true; } else if (addr == 0x42) { bltcon1 = v; blit_bltset(2); return true; } return false; } static bool decide_blitter_idle(int lasthpos, int hpos, uaecptr addr, uae_u32 value) { markidlecycle(last_blitter_hpos); if (addr != 0xffffffff && lasthpos + 1 == hpos) { shifter_skip_b_old = shifter_skip_b; shifter_skip_y_old = shifter_skip_y; return blitter_idle_cycle_register_write(addr, value); } return false; } uae_u16 blitter_pipe[MAX_CHIPSETSLOTS + RGA_PIPELINE_ADJUST + MAX_CHIPSETSLOTS_EXTRA]; void set_blitter_last(int hp) { last_blitter_hpos = hp; } static bool decide_blitter_maybe_write2(int until_hpos, uaecptr addr, uae_u32 value) { bool written = false; int hsync = until_hpos < 0; if (scandoubled_line) { return 0; } if (hsync && blt_delayed_irq) { if (blt_delayed_irq > 0) blt_delayed_irq--; if (blt_delayed_irq <= 0) { blt_delayed_irq = 0; INTREQ_INT(6, 3); } } if (until_hpos < 0 || until_hpos > maxhposm0) { until_hpos = maxhposm0; } if (last_blitter_hpos >= until_hpos) { goto end; } if (immediate_blits) { if (!blt_info.blit_main) { return false; } if (dmaen(DMA_BLITTER)) { blitter_doit(last_blitter_hpos); } goto end2; } if (log_blitter && blitter_delayed_debug) { blitter_delayed_debug = 0; blitter_dump(); } if (!blitter_cycle_exact) { goto end2; } while (last_blitter_hpos < until_hpos) { int hpos = last_blitter_hpos; // dma transfers and processing for (;;) { if (!cycle_line_slot[hpos] && blt_info.blit_queued > 0) { blt_info.blit_queued--; if (!blt_info.blit_queued && !blt_info.blit_finald) { blitter_end(); } } uae_u16 dat = blitter_pipe[hpos]; if (dat) { blitter_pipe[hpos] = 0; } if (!(dat & CYCLE_PIPE_BLITTER)) { break; } cycle_line_pipe[hpos] = 0; if (dat & CYCLE_PIPE_CPUSTEAL) { #ifdef DEBUGGER if (debug_dma) { record_dma_event(DMA_EVENT_CPUBLITTERSTOLEN, hpos, vpos); } #endif break; } int c = dat & 7; bool line = (dat & BLITTER_PIPELINE_LINE) != 0; // last D write? if (dat & BLITTER_PIPELINE_LASTD) { line = false; #ifdef DEBUGGER if (debug_dma) { record_dma_event(DMA_EVENT_BLITFINALD, hpos, vpos); } #endif if (cycle_line_slot[hpos]) { write_log("Blitter cycle allocated by %d!?\n", cycle_line_slot[hpos]); } if (!blt_info.blit_main && !blt_info.blit_finald && !blt_info.blit_queued) { blitter_end(); } //activate_debugger(); } // finished? if (dat & BLITTER_PIPELINE_FINISHED) { if (line) { #ifdef DEBUGGER if (debug_dma) { record_dma_event(DMA_EVENT_BLITFINALD, hpos, vpos); //activate_debugger(); } #endif } } bool addmod = (dat & BLITTER_PIPELINE_ADDMOD) != 0; blit_totalcyclecounter++; if (c == 0) { written = decide_blitter_idle(hpos, until_hpos, addr, value); } else if (c == 1 && line) { // line 1/4 (A, free) written = decide_blitter_idle(hpos, until_hpos, addr, value); if (dat & BLITTER_PIPELINE_FIRST) { blitter_line_proc_status(); blitter_line_proc_apt(); } } else if (c == 3 && line) { // line 2/4 (C) if (!(dat & BLITTER_PIPELINE_FIRST) && blitlineloop && !(bltcon1 & BLTSUD)) { blitter_line_proc_cpt_y(); blitlineloop = 0; } bool skip = false; uaecptr orptr = alloc_cycle_blitter_conflict_or(hpos, 3, &skip); record_dma_blit(0x70, 0, bltcpt | orptr, hpos); check_channel_mods(hpos, 3, &bltcpt); if (!skip) { blt_info.bltcdat = chipmem_wget_indirect(bltcpt | orptr); regs.chipset_latch_rw = blt_info.bltcdat; record_dma_blit_val(blt_info.bltcdat); } alloc_cycle_blitter(hpos, &bltcpt, 3, 0); if (dat & BLITTER_PIPELINE_FIRST) { blitter_line_minterm(dat); blitter_line_proc_cpt_x(); } else { // W>2 special case blitter_line_minterm_extra(); } } else if (c == 5 && line) { // line 3/4 (free) written = decide_blitter_idle(hpos, until_hpos, addr, value); } else if ((c == 4 || c == 6) && line) { // line 4/4 (C/D) blitter_line_adat(); blitter_line_ovf(); if (blt_info.hblitsize == 1) { blitter_line_proc_status(); } else { if (blitlineloop) { blitter_line_proc_cpt_y(); blitlineloop = 0; } } blitter_line_sign(); blitter_nxline(); /* onedot mode and no pixel = bus write access is skipped */ if (blitlinepixel && c == 4) { bool skip = false; uaecptr orptr = alloc_cycle_blitter_conflict_or(hpos, 4, &skip); record_dma_blit(0x00, blt_info.bltddat, bltdpt | orptr, hpos); check_channel_mods(hpos, 4, &bltdpt); if (!skip) { blit_chipmem_agnus_wput(bltdpt | orptr, blt_info.bltddat, MW_MASK_BLITTER_D_L); } alloc_cycle_blitter(hpos, &bltdpt, 4, 0); } else { markidlecycle(hpos); } blitlinepixel = 0; blitlineloop = 1; bltdpt = bltcpt; blitter_line_minterm(dat); } else { // normal mode channels if (c == 4) { blitter_doddma_new(hpos, addmod); } else { if (c == 5) { c = 1; } blitter_dodma_new(c, hpos, addmod); } } if ((dat & BLITTER_PIPELINE_BLIT) && !blitline) { ddat = blitter_doblit(dat); blt_info.bltddat = ddat; } if (dat & BLITTER_PIPELINE_PROCESS) { blitfc = !!(bltcon1 & BLTFC); } break; } if (blt_info.blit_finald || blt_info.blit_main) { blt_info.blit_queued = BLITTER_MAX_PIPELINED_CYCLES; // cycle allocations for (;;) { // final D idle cycle // does not need free bus if (blt_info.blit_finald > 1) { blt_info.blit_finald--; } // Skip BLTSIZE write cycle if (blit_waitcyclecounter) { blit_waitcyclecounter = 0; break; } bool cant = blitter_cant_access(hpos); if (cant) { blit_misscyclecounter++; break; } // CPU steals the cycle if CPU has waited long enough and current cyle is not free. if (!(dmacon & DMA_BLITPRI) && blt_info.nasty_cnt >= BLIT_NASTY_CPU_STEAL_CYCLE_COUNT && currprefs.cpu_memory_cycle_exact && ((cycle_line_slot[hpos] & CYCLE_MASK) != 0 || bitplane_dma_access(hpos, 0) != 0)) { int offset = get_rga_pipeline(hpos, RGA_PIPELINE_OFFSET_BLITTER); blitter_pipe[offset] = CYCLE_PIPE_BLITTER | CYCLE_PIPE_CPUSTEAL; cycle_line_pipe[offset] = CYCLE_PIPE_BLITTER | CYCLE_PIPE_CPUSTEAL; blt_info.nasty_cnt = -1; break; } if (blt_info.blit_finald == 1) { // final D write. Only if BLTCON D and line mode is off. if ((bltcon0 & BLTCHD) && !(bltcon1 & BLTLINE)) { int offset = get_rga_pipeline(hpos, RGA_PIPELINE_OFFSET_BLITTER); cycle_line_pipe[offset] = CYCLE_PIPE_BLITTER; blitter_pipe[offset] = CYCLE_PIPE_BLITTER | 4 | BLITTER_PIPELINE_ADDMOD | BLITTER_PIPELINE_LASTD; } if (currprefs.chipset_mask & CSMASK_AGA) { blitter_done_all(hpos); } blt_info.blit_finald = 0; if (!blt_info.blit_queued) { blitter_end(); } break; } if (blt_info.blit_main) { blit_cyclecounter++; if (blit_cyclecounter == 0) { shifter_first = 1; // clear possible still pending final D write blt_info.blit_finald = 0; blitter_next_cycle(); } int c = get_current_channel(); blt_info.got_cycle = 1; bool addmod = false; if (c == 1 || c == 2 || c == 3) { if (blitter_hcounter + 1 == blt_info.hblitsize) { addmod = true; } } else if (c == 4) { if (blitter_hcounter == 0) { addmod = true; } } uae_u16 v = CYCLE_PIPE_BLITTER | c | (addmod ? BLITTER_PIPELINE_ADDMOD : 0); if (blitter_hcounter == 0) { v |= BLITTER_PIPELINE_FIRST; } if (blitter_hcounter == blt_info.hblitsize - 1) { v |= BLITTER_PIPELINE_LAST; } if (blitline) { v |= BLITTER_PIPELINE_LINE; } bool doddat = false; if (blit_cyclecounter >= 0) { doddat = blitter_next_cycle(); } int offset = get_rga_pipeline(hpos, RGA_PIPELINE_OFFSET_BLITTER); if (cycle_line_pipe[offset]) { write_log("Blitter cycle conflict %d\n", cycle_line_pipe[offset]); } if (doddat) { v |= BLITTER_PIPELINE_BLIT; if (blitter_hcounter == 0) { v |= BLITTER_PIPELINE_PROCESS; } } // finished? if (blit_cyclecounter < -CYCLECOUNT_START) { v |= BLITTER_PIPELINE_FINISHED; if (!blt_info.blit_main) { write_log(_T("blitter blit_main already cleared!?\n")); } // has final D write? if (blt_info.blit_finald) { if (!(currprefs.chipset_mask & CSMASK_AGA)) { blitter_done_except_d(hpos); } } else { blitter_done_all(hpos); } } cycle_line_pipe[offset] = CYCLE_PIPE_BLITTER; blitter_pipe[offset] = v; } break; } } last_blitter_hpos++; bltptxpos = -1; } end2: bltptxpos = -1; end: if (hsync) { last_blitter_hpos = 0; } return written; } bool decide_blitter_maybe_write(int until_hpos, uaecptr addr, uae_u32 value) { int reg = addr & 0x1fe; // early exit check if (reg != 0x40 && reg != 0x42) { addr = 0xffffffff; } else { return decide_blitter_maybe_write2(until_hpos, addr, value); } return decide_blitter_maybe_write2(until_hpos, addr, value); } void decide_blitter(int until_hpos) { decide_blitter_maybe_write2(until_hpos, 0xffffffff, 0xffffffff); } #else void decide_blitter (int hpos) { } #endif static void blitter_force_finish(bool state) { uae_u16 odmacon; if (!blt_info.blit_main && !blt_info.blit_finald) return; /* blitter is currently running * force finish (no blitter state support yet) */ odmacon = dmacon; dmacon |= DMA_MASTER | DMA_BLITTER; if (state) write_log(_T("forcing blitter finish\n")); if (blitter_cycle_exact && !immediate_blits) { int rounds = 10000; while ((blt_info.blit_main || blt_info.blit_finald) && rounds > 0) { memset(cycle_line_slot, 0, sizeof(cycle_line_slot)); decide_blitter(-1); rounds--; } if (rounds == 0) write_log(_T("blitter froze!?\n")); } else { actually_do_blit(); } blitter_done_all(-1); dmacon = odmacon; } static void blit_modset (void) { int mult; blit_add = blitdesc ? -2 : 2; mult = blitdesc ? -1 : 1; blit_modadda = mult * blt_info.bltamod; blit_modaddb = mult * blt_info.bltbmod; blit_modaddc = mult * blt_info.bltcmod; blit_modaddd = mult * blt_info.bltdmod; } void reset_blit (int bltcon) { if (!blt_info.blit_main && !blt_info.blit_finald) return; if (bltcon) blit_bltset (bltcon); blit_modset(); } static bool waitingblits (void) { static int warned = 10; // crazy large blit size? don't wait.. (Vital / Mystic) if (blt_info.vblitsize * blt_info.hblitsize * 2 > 2 * 1024 * 1024) { if (warned) { warned--; write_log(_T("Crazy waiting_blits detected PC=%08x W=%d H=%d\n"), M68K_GETPC, blt_info.vblitsize, blt_info.hblitsize); } return false; } bool waited = false; int waiting = 0; int vpos_prev = vpos; while ((blt_info.blit_main || blt_info.blit_finald) && dmaen (DMA_BLITTER)) { waited = true; x_do_cycles (8 * CYCLE_UNIT); if (vpos_prev != vpos) { vpos_prev = vpos; waiting++; if (waiting > maxvpos * 5) { break; } } if (blitter_cycle_exact && blit_cyclecounter > 0 && !shifter[0] && !shifter[1] && !shifter[2] && !shifter[3]) { break; } } if (warned && waited) { warned--; write_log (_T("waiting_blits detected PC=%08x\n"), M68K_GETPC); } if (!blt_info.blit_main && !blt_info.blit_finald) return true; return false; } static void blitter_start_init (void) { shifter_first = 0; blt_info.blit_queued = 0; blit_faulty = 0; blt_info.blitzero = 1; blitline_started = bltcon1 & BLTLINE; blitlineloop = 1; blit_bltset(1 | 2); blit_modset(); ddatuse = 0; blt_info.blit_interrupt = 0; blt_info.bltaold = 0; blt_info.bltbold = 0; int bshift = bltcon1 >> 12; blineb = (blt_info.bltbdat >> bshift) | (blt_info.bltbdat << (16 - bshift)); blitonedot = 0; blitlinepixel = 0; if (!(dmacon & DMA_BLITPRI) && blt_info.nasty_cnt >= BLIT_NASTY_CPU_STEAL_CYCLE_COUNT) { blt_info.wait_nasty = 1; } else { blt_info.wait_nasty = 0; } } void do_blitter(int hpos, int copper, uaecptr pc) { int cycles; if ((log_blitter & 2)) { if (blt_info.blit_main) { write_log (_T("blitter was already active! PC=%08x\n"), M68K_GETPC); } } bltcon0_old = bltcon0; bltcon1_old = bltcon1; blitter_cycle_exact = currprefs.blitter_cycle_exact; immediate_blits = currprefs.immediate_blits; blt_info.got_cycle = 0; blit_firstline_cycles = blit_first_cycle = get_cycles(); blit_misscyclecounter = 0; blit_last_cycle = 0; blit_maxcyclecounter = 0; blit_cyclecounter = 0; blit_totalcyclecounter = 0; blt_info.blit_pending = 1; blitter_start_init(); if (blitline) { cycles = blt_info.vblitsize * blt_info.hblitsize; } else { cycles = blt_info.vblitsize * blt_info.hblitsize; blit_firstline_cycles = blit_first_cycle + (blit_cyclecount * blt_info.hblitsize) * CYCLE_UNIT + cpu_cycles; } #ifdef DEBUGGER if (memwatch_enabled || BLITTER_DEBUG) { blitter_debugsave(copper, pc); } #endif if ((log_blitter & 1) || ((log_blitter & 32) && !blitline)) { if (1) { int ch = 0; if (blit_ch & 1) ch++; if (blit_ch & 2) ch++; if (blit_ch & 4) ch++; if (blit_ch & 8) ch++; write_log(_T("blitstart: %dx%d ch=%d %d d=%d f=%02x n=%d pc=%08x l=%d dma=%04x %s\n"), blt_info.hblitsize, blt_info.vblitsize, ch, cycles, blitdesc ? 1 : 0, blitfill, dmaen(DMA_BLITPRI) ? 1 : 0, M68K_GETPC, blitline, dmacon, ((dmacon & (DMA_MASTER | DMA_BLITTER)) == (DMA_MASTER | DMA_BLITTER)) ? _T("") : _T(" off!")); blitter_dump(); } } blit_slowdown = 0; unset_special (SPCFLAG_BLTNASTY); if (dmaen(DMA_BLITPRI)) { set_special(SPCFLAG_BLTNASTY); } if (dmaen(DMA_BLITTER)) { blt_info.blit_main = 1; blt_info.blit_pending = 0; } blit_maxcyclecounter = 0x7fffffff; blit_waitcyclecounter = 0; last_blitter_hpos = hpos; if (blitter_cycle_exact) { if (immediate_blits) { if (dmaen(DMA_BLITTER)) { blitter_doit(-1); } return; } if (log_blitter & 8) { blitter_handler (0); } else { blitter_hcounter = 0; blitter_vcounter = 0; blit_cyclecounter = -CYCLECOUNT_START; blit_waitcyclecounter = 1; blit_maxcyclecounter = blt_info.hblitsize * blt_info.vblitsize + 2; blt_info.blit_pending = 0; blt_info.blit_main = 1; blt_info.blit_queued = BLITTER_MAX_PIPELINED_CYCLES; } return; } if (blt_info.vblitsize == 0) { if (dmaen(DMA_BLITTER)) { blitter_done_all(-1); } return; } if (dmaen (DMA_BLITTER)) { blt_info.got_cycle = 1; } if (immediate_blits) { if (dmaen(DMA_BLITTER)) { blitter_doit(-1); } return; } blit_cyclecounter = cycles * blit_cyclecount; event2_newevent (ev2_blitter, makebliteventtime(blit_cyclecounter), 0); } void blitter_check_start (void) { if (blt_info.blit_pending && !blt_info.blit_main) { blt_info.blit_pending = 0; blt_info.blit_main = 1; blitter_start_init(); if (immediate_blits) { blitter_doit(-1); } } } void maybe_blit (int hpos, int hack) { static int warned = 10; if (!blt_info.blit_main) { decide_blitter(hpos); return; } if (savestate_state) return; if (dmaen (DMA_BLITTER) && (currprefs.cpu_model >= 68020 || !currprefs.cpu_memory_cycle_exact)) { bool doit = false; if (currprefs.waiting_blits == 3) { // always doit = true; } else if (currprefs.waiting_blits == 2) { // noidle if (blit_dmacount == blit_cyclecount && (regs.spcflags & SPCFLAG_BLTNASTY)) doit = true; } else if (currprefs.waiting_blits == 1) { // automatic if (blit_dmacount == blit_cyclecount && (regs.spcflags & SPCFLAG_BLTNASTY)) doit = true; else if (currprefs.m68k_speed < 0) doit = true; } if (doit) { if (waitingblits()) return; } } if (warned && dmaen (DMA_BLITTER) && blt_info.got_cycle) { warned--; #ifdef DEBUGGER debugtest (DEBUGTEST_BLITTER, _T("program does not wait for blitter tc=%d\n"), blit_cyclecounter); #endif if (log_blitter) warned = 0; if (log_blitter & 2) { warned = 10; write_log (_T("program does not wait for blitter PC=%08x\n"), M68K_GETPC); //activate_debugger(); //blitter_done (hpos); } } if (blitter_cycle_exact) { decide_blitter(hpos); goto end; } if (hack == 1 && get_cycles() < blit_firstline_cycles) goto end; blitter_handler(0); end:; if (log_blitter) blitter_delayed_debug = 1; } void check_is_blit_dangerous (uaecptr *bplpt, int planes, int words) { blt_info.blitter_dangerous_bpl = 0; if ((!blt_info.blit_main && !blt_info.blit_finald) || !blitter_cycle_exact) return; // too simple but better than nothing for (int i = 0; i < planes; i++) { uaecptr bpl = bplpt[i]; uaecptr dpt = bltdpt & chipmem_bank.mask; if (dpt >= bpl - 2 * words && dpt < bpl + 2 * words) { blt_info.blitter_dangerous_bpl = 1; return; } } } int blitnasty (void) { int cycles, ccnt; if (!blt_info.blit_main) return -1; if (!dmaen(DMA_BLITTER)) return -1; if (blitter_cycle_exact) { return -1; } if (blit_last_cycle >= blit_cyclecount && blit_dmacount == blit_cyclecount) return 0; cycles = int((get_cycles() - blit_first_cycle) / CYCLE_UNIT); ccnt = 0; while (blit_last_cycle + blit_cyclecount < cycles) { ccnt += blit_dmacount; blit_last_cycle += blit_cyclecount; } return ccnt; } /* very approximate emulation of blitter slowdown caused by bitplane DMA */ void blitter_slowdown (int ddfstrt, int ddfstop, int totalcycles, int freecycles) { static int oddfstrt, oddfstop, ototal, ofree; static int slow; if (!totalcycles || ddfstrt < 0 || ddfstop < 0) return; if (ddfstrt != oddfstrt || ddfstop != oddfstop || totalcycles != ototal || ofree != freecycles) { int linecycles = ((ddfstop - ddfstrt + totalcycles - 1) / totalcycles) * totalcycles; int freelinecycles = ((ddfstop - ddfstrt + totalcycles - 1) / totalcycles) * freecycles; int dmacycles = (linecycles * blit_dmacount) / blit_cyclecount; oddfstrt = ddfstrt; oddfstop = ddfstop; ototal = totalcycles; ofree = freecycles; slow = 0; if (dmacycles > freelinecycles) slow = dmacycles - freelinecycles; } if (blit_slowdown < 0 || blitline) return; blit_slowdown += slow; blit_misscyclecounter += slow; } void blitter_reset (void) { bltptxpos = -1; blitter_cycle_exact = currprefs.blitter_cycle_exact; immediate_blits = currprefs.immediate_blits; shifter[0] = shifter[1] = shifter[2] = shifter[3] = 0; shifter_skip_b = false; shifter_skip_y = false; bltcon0 = 0; bltcon1 = 0; blitter_start_init(); blt_info.blit_main = 0; blt_info.blit_pending = 0; blt_info.blit_finald = 0; blt_info.blit_queued = 0; } #ifdef SAVESTATE void restore_blitter_start(void) { blitter_reset(); } void restore_blitter_finish (void) { #ifdef DEBUGGER record_dma_reset(0); record_dma_reset(0); #endif blitter_cycle_exact = currprefs.blitter_cycle_exact; immediate_blits = currprefs.immediate_blits; if (blt_statefile_type == 0) { blt_info.blit_interrupt = 1; if (blt_info.blit_pending) { write_log (_T("blitter was started but DMA was inactive during save\n")); //do_blitter (0); } if (blt_delayed_irq < 0) { if (intreq & 0x0040) blt_delayed_irq = 3; intreq &= ~0x0040; } } else { last_blitter_hpos = 0; blit_modset(); } } uae_u8 *restore_blitter (uae_u8 *src) { uae_u32 flags = restore_u32(); if (!(flags & 8)) { blt_statefile_type = 0; blt_delayed_irq = 0; blt_info.blit_pending = 0; blt_info.blit_finald = 0; blt_info.blit_main = 0; if (flags & 4) { if (!(flags & 1)) { blt_info.blit_pending = 1; } } if (flags & 2) { write_log (_T("blitter was force-finished when this statefile was saved\n")); write_log (_T("contact the author if restored program freezes\n")); // there is a problem. if system ks vblank is active, we must not activate // "old" blit's intreq until vblank is handled or ks 1.x thinks it was blitter // interrupt.. blt_delayed_irq = -1; } } bltcon0_old = bltcon0; bltcon1_old = bltcon1; return src; } uae_u8 *save_blitter (size_t *len, uae_u8 *dstptr, bool newstate) { uae_u8 *dstbak,*dst; if (dstptr) dstbak = dst = dstptr; else dstbak = dst = xmalloc(uae_u8, 16); if (blt_info.blit_main || blt_info.blit_finald) { save_u32(8); } else { save_u32(1 | 4); } *len = dst - dstbak; return dstbak; } // totally non-real-blitter-like state save but better than nothing.. uae_u8 *restore_blitter_new(uae_u8 *src) { uae_u8 state, tmp; blt_statefile_type = 1; blitter_cycle_exact = restore_u8(); if (blitter_cycle_exact & 2) { blt_statefile_type = 2; blitter_cycle_exact = 1; } state = restore_u8(); blit_first_cycle = restore_u32(); blit_last_cycle = restore_u32(); blit_waitcyclecounter = restore_u32(); restore_u32(); blit_maxcyclecounter = restore_u32(); blit_firstline_cycles = restore_u32(); blit_cyclecounter = restore_u32(); blit_slowdown = restore_u32(); blit_misscyclecounter = restore_u32(); blitter_hcounter = restore_u16(); restore_u16(); blitter_vcounter = restore_u16(); restore_u16(); blit_ch = restore_u8(); restore_u8(); restore_u8(); restore_u8(); blt_info.blit_finald = restore_u8(); blitfc = restore_u8(); blitife = restore_u8(); restore_u8(); restore_u8(); restore_u8(); restore_u8(); ddatuse = restore_u8(); restore_u8(); ddat = restore_u16(); restore_u16(); blitline = restore_u8(); blitfill = restore_u8(); restore_u16(); //blinea = restore_u16(); blineb = restore_u16(); restore_u8(); blitonedot = restore_u8(); blitlinepixel = restore_u8(); restore_u8(); tmp = restore_u8(); blitlinepixel = (tmp & 1) != 0; blitlineloop = (tmp & 2) != 0; blt_info.blit_interrupt = restore_u8(); blt_delayed_irq = restore_u8(); blt_info.blitzero = restore_u8(); blt_info.got_cycle = restore_u8(); restore_u8(); blit_faulty = restore_u8(); restore_u8(); restore_u8(); restore_u8(); restore_u8(); if (restore_u16() != 0x1234) { write_log(_T("blitter state restore error\n")); } blt_info.blitter_nasty = restore_u8(); tmp = restore_u8(); if (blt_statefile_type < 2) { tmp = 0; blt_info.blit_finald = 0; } else { shifter[0] = (tmp & 1) != 0; shifter[1] = (tmp & 2) != 0; shifter[2] = (tmp & 4) != 0; shifter[3] = (tmp & 8) != 0; shifter_skip_b_old = (tmp & 16) != 0; shifter_skip_y_old = (tmp & 32) != 0; blt_info.blit_finald = restore_u8(); blit_ovf = restore_u8(); } blt_info.blit_main = 0; blt_info.blit_pending = 0; if (!blitter_cycle_exact) { if (state > 0) do_blitter(0, 0, 0); } else { // if old blitter active state file: // stop blitter. We can't support them anymore. if (state == 2 && blt_statefile_type < 2) { blt_info.blit_pending = 0; blt_info.blit_main = 0; } else { if (state == 1) { blt_info.blit_pending = 1; } else if (state == 2) { blt_info.blit_main = 1; blt_info.blit_queued = BLITTER_MAX_PIPELINED_CYCLES; } if (blt_info.blit_finald) { blt_info.blit_queued = BLITTER_MAX_PIPELINED_CYCLES; blt_info.blit_main = 0; } if (blt_statefile_type == 2) { blit_bltset(0); } } shifter_skip_b_old = shifter_skip_b; shifter_skip_y_old = shifter_skip_y; } blit_first_cycle |= ((uae_u64)restore_u32()) << 32; blit_firstline_cycles |= ((uae_u64)restore_u32()) << 32; blt_info.bltaold = restore_u16(); blt_info.bltbold = restore_u16(); blt_info.nasty_cnt = restore_u8(); blt_info.wait_nasty = restore_u8(); shifter_first = (uae_s8)restore_u8(); blt_info.finishhpos = restore_u8(); blit_cyclecounter = restore_u32(); for (int i = 0; i < 4; i++) { blitter_pipe[i] = restore_u16(); if (blitter_pipe[i]) { blt_info.blit_queued = BLITTER_MAX_PIPELINED_CYCLES; } cycle_line_pipe[i] = restore_u16(); cycle_line_slot[i] = restore_u8(); } //activate_debugger(); return src; } uae_u8 *save_blitter_new(size_t *len, uae_u8 *dstptr) { uae_u8 *dstbak,*dst; if (dstptr) dstbak = dst = dstptr; else dstbak = dst = xmalloc (uae_u8, 1000); uae_u8 state; save_u8(blitter_cycle_exact ? 3 : 0); if (!blt_info.blit_main && !blt_info.blit_finald) { state = 0; } else if (blt_info.blit_pending) { state = 1; } else if (blt_info.blit_finald) { state = 3; } else { state = 2; } save_u8(state); if (blt_info.blit_main || blt_info.blit_finald) { write_log(_T("BLITTER active while saving state\n")); if (log_blitter) blitter_dump(); } save_u32((uae_u32)blit_first_cycle); save_u32(blit_last_cycle); save_u32(blit_waitcyclecounter); save_u32(0); //(blit_startcycles); save_u32(blit_maxcyclecounter); save_u32((uae_u32)blit_firstline_cycles); save_u32(blit_cyclecounter); save_u32(blit_slowdown); save_u32(blit_misscyclecounter); save_u16(blitter_hcounter); save_u16(0); //(blitter_hcounter2); save_u16(blitter_vcounter); save_u16(0); //(blitter_vcounter2); save_u8(blit_ch); save_u8(blit_dmacount); save_u8(blit_cyclecount); save_u8(0); //(blit_nod); save_u8(blt_info.blit_finald); save_u8(blitfc); save_u8(blitife); save_u8(bltcon1 >> 12); save_u8((16 - (bltcon1 >> 12))); save_u8(bltcon0 >> 12); save_u8(16 - (bltcon0 >> 12)); save_u8(ddatuse); save_u8(0); //(ddat2use); save_u16(ddat); save_u16(0); //(ddat2); save_u8(blitline); save_u8(blitfill); save_u16(blt_info.bltadat); save_u16(blineb); save_u8(bltcon0 >> 12); save_u8(blitonedot); save_u8(blitlinepixel); save_u8((bltcon1 & BLTSING) != 0); save_u8((blitlinepixel ? 1 : 0) | (blitlineloop ? 2 : 0)); save_u8(blt_info.blit_interrupt); save_u8(blt_delayed_irq); save_u8(blt_info.blitzero); save_u8(blt_info.got_cycle); save_u8(0); //(blit_frozen); save_u8(blit_faulty); save_u8(0); //original_ch); save_u8(0); //original_fill); save_u8(0); //original_line); save_u8(0); //get_cycle_diagram_type (blit_diag)); save_u16(0x1234); save_u8(blt_info.blitter_nasty); save_u8((shifter[0] ? 1 : 0) | (shifter[1] ? 2 : 0) | (shifter[2] ? 4 : 0) | (shifter[3] ? 8 : 0) | (shifter_skip_b_old ? 16 : 0) | (shifter_skip_y_old ? 32 : 0)); save_u8(blt_info.blit_finald); save_u8(blit_ovf); save_u32(blit_first_cycle >> 32); save_u32(blit_firstline_cycles >> 32); save_u16(blt_info.bltaold); save_u16(blt_info.bltbold); save_u8(blt_info.nasty_cnt); save_u8(blt_info.wait_nasty); save_u8(shifter_first); save_u8(blt_info.finishhpos); save_u32(blit_cyclecounter); for (int i = 0; i < 4; i++) { save_u16(blitter_pipe[i]); save_u16(cycle_line_pipe[i]); save_u8(cycle_line_slot[i]); } *len = dst - dstbak; return dstbak; } #endif /* SAVESTATE */
#include "Atom.h" #include <SFML/Graphics.hpp> Atom::Atom(Atom* location) { //ctor } Atom::Atom(unsigned long _x, unsigned long _y, unsigned long _z, unsigned short _region) { } Atom::~Atom() { //dtor }
//uva 231 //Undefined_Error //Dept. ICE, NSTU-11 Batch #include<bits/stdc++.h> using namespace std; #define INF 1<<28 #define ll long long #define SZ 100005 #define MX 100000000 #define sfint(a) scanf("%d",&a) #define sfint2(a,b) scanf("%d%d",&a,&b) #define sfint3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define forlp0(i,n) for(int i=0;i<n;i++) #define forlp1(i,n) for(int i=1;i<=n;i++) #define forlpa(i,a,n) for(int i=a;i<=n;i++) #define rvforlp(i,n) for(int i=n-1;i>=0;i--) int dp[SZ],dir[SZ]; int input[SZ]; int i=1; int longest(int u) { if(dp[u]!=-1) return dp[u]; int max=0; forlpa(v,u+1,i-1) { if(input[v]<=input[u]) { if(longest(v)>max) max=longest(v); } } return dp[u]=max+1; } int main() { int n,result=0,t=0; memset(dp,-1,sizeof dp); while(1) { sfint(n); if(n==-1) { forlp1(t,i-1) { if(longest(t)>result) result=longest(t); } if(result==0) return 0; if(t) { printf("\n"); } printf("Test #%d:\n", ++t); printf(" maximum possible interceptions: %d\n", result); memset(input,0,sizeof input); memset(dp,-1,sizeof dp); result=0; i=1; } else { input[i++]=n; } } return 0; }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Nicolas Jinchereau. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ #pragma once #include <ax/Common.h> #include <ax/UIElement.h> #include <cstdlib> #include <AppKit/AppKit.h> #include <vector> #include <functional> #include <unordered_set> #include <unordered_map> #include <memory> using namespace std; namespace ax { class UIElement; class Application; class Observer { public: friend class UIElement; friend class Window; friend class Application; friend class workspace; Observer(); Observer(Observer &&other); explicit Observer(Application *app); ~Observer(); Observer& operator=(nullptr_t); Observer& operator=(Observer &&other); inline operator bool() const; inline bool operator!() const; inline friend bool operator==(const Observer &x, const Observer &y); inline friend bool operator==(const Observer &x, nullptr_t); inline friend bool operator!=(const Observer &x, const Observer &y); inline friend bool operator!=(const Observer &x, nullptr_t); bool addNotification(const UIElement &element, CFStringRef notification); void removeNotification(const UIElement &element, CFStringRef notification); void removeNotifications(const UIElement &element); bool hasNotification(const UIElement &element, CFStringRef notification); bool hasNotifications(const UIElement &element); private: Observer(const Observer &other); Observer& operator=(const Observer &other); static void _proxy(AXObserverRef observer, AXUIElementRef element, CFStringRef notification, void *userdata); struct ElemHash { size_t operator()(const UIElement& elem) const { return elem.hashCode(); } }; std::unordered_multimap<UIElement, CFStringRef, ElemHash> _callbacks; AXObserverRef _observer_ref; Application *_app; }; inline Observer::operator bool() const { return _observer_ref != nullptr; } inline bool Observer::operator!() const { return _observer_ref == nullptr; } inline bool operator==(const Observer &x, const Observer &y) { return equal_pointees(x._observer_ref, y._observer_ref); } inline bool operator==(const Observer &x, nullptr_t) { return x._observer_ref == nullptr; } inline bool operator!=(const Observer &x, const Observer &y) { return unequal_pointees(x._observer_ref, y._observer_ref); } inline bool operator!=(const Observer &x, nullptr_t) { return x._observer_ref != nullptr; } }
#include "stdafx.h" #include "NormalRules.h" NormalRules::NormalRules() { } std::vector<bool*> NormalRules::applyRules(std::vector<bool*> field, int fieldWidth, int fieldHeight) { std::vector<bool*> tempField; for (size_t i = 0; i < field.size(); i++) { tempField.push_back(new bool(*field[i])); } for (int i = 0; i < field.size(); i++) { int amtOfLiveNeighbors = getAmtOfNeighbours(i, field, fieldWidth, fieldHeight); if (*(field[i]) == true && amtOfLiveNeighbors < 2) { *(tempField[i]) = false; } else if (*(field[i]) == true && amtOfLiveNeighbors > 3) { *(tempField[i]) = false; } else if (*(field[i]) == false && amtOfLiveNeighbors == 3) { *(tempField[i]) = true; } } return tempField; } NormalRules::~NormalRules() { }
/* ------------------------------------------------------------------------ */ /* LHa for UNIX */ /* lharc.c -- append to archive */ /* */ /* Copyright (C) MCMLXXXIX Yooichi.Tagawa */ /* Modified Nobutaka Watazaki */ /* Thanks to H.Yoshizaki. (MS-DOS LHarc) */ /* */ /* Ver. 0.00 Original 1988.05.23 Y.Tagawa */ /* Ver. 0.01 Alpha Version (for 4.2BSD) 1989.05.28 Y.Tagawa */ /* Ver. 0.02 Alpha Version Rel.2 1989.05.29 Y.Tagawa */ /* Ver. 0.03 Release #3 Beta Version 1989.07.02 Y.Tagawa */ /* Ver. 0.03a Debug 1989.07.03 Y.Tagawa */ /* Ver. 0.03b Modified 1989.07.13 Y.Tagawa */ /* Ver. 0.03c Debug (Thanks to void@rena.dit.junet) */ /* 1989.08.09 Y.Tagawa */ /* Ver. 0.03d Modified (quiet and verbose) 1989.09.14 Y.Tagawa */ /* V1.00 Fixed 1989.09.22 Y.Tagawa */ /* V1.01 Bug Fixed 1989.12.25 Y.Tagawa */ /* */ /* DOS-Version Original LHx V C2.01 (C) H.Yohizaki */ /* */ /* V2.00 UNIX Lharc + DOS LHx -> OSK LHx 1990.11.01 Momozou */ /* V2.01 Minor Modified 1990.11.24 Momozou */ /* */ /* Ver. 0.02 LHx for UNIX 1991.11.18 M.Oki */ /* Ver. 0.03 LHa for UNIX 1991.12.17 M.Oki */ /* Ver. 0.04 LHa for UNIX beta version 1992.01.20 M.Oki */ /* Ver. 1.00 LHa for UNIX Fixed 1992.03.19 M.Oki */ /* */ /* Ver. 1.10 for Symblic Link 1993.06.25 N.Watazaki */ /* Ver. 1.11 for Symblic Link Bug Fixed 1993.08.18 N.Watazaki */ /* Ver. 1.12 for File Date Check 1993.10.28 N.Watazaki */ /* Ver. 1.13 Bug Fixed (Idicator calcurate) 1994.02.21 N.Watazaki */ /* Ver. 1.13a Bug Fixed (Sym. Link delete) 1994.03.11 N.Watazaki */ /* Ver. 1.13b Bug Fixed (Sym. Link delete) 1994.07.29 N.Watazaki */ /* Ver. 1.14 Source All chagned 1995.01.14 N.Watazaki */ /* Ver. 1.14b,c Bug Fixed 1996.03.07 t.okamoto */ /* Ver. 1.14d Version up 1997.01.12 t.okamoto */ /* Ver. 1.14g Bug Fixed 2000.05.06 t.okamoto */ /* Ver. 1.14i Modified 2000.10.06 t.okamoto */ /* ------------------------------------------------------------------------ */ #define LHA_MAIN_SRC #include "lha.h" /* ------------------------------------------------------------------------ */ /* PROGRAM */ /* ------------------------------------------------------------------------ */ static int cmd = CMD_UNKNOWN; /* 1996.8.13 t.okamoto */ #if 0 char **cmd_filev; int cmd_filec; char *archive_name; char expanded_archive_name[FILENAME_LENGTH]; char temporary_name[FILENAME_LENGTH]; char backup_archive_name[FILENAME_LENGTH]; #endif /* static functions */ static void sort_files(); static void print_version(); char *extract_directory = NULL; char **xfilev; int xfilec = 257; /* 1996.8.13 t.okamoto */ #if 0 char *writting_filename; char *reading_filename; int archive_file_mode; int archive_file_gid; #endif /* ------------------------------------------------------------------------ */ static void init_variable() /* Added N.Watazaki */ { /* options */ quiet = FALSE; text_mode = FALSE; verbose = FALSE; noexec = FALSE; /* debugging option */ force = FALSE; prof = FALSE; #ifndef SUPPORT_LH7 compress_method = LZHUFF5_METHOD_NUM; #endif #ifdef SUPPORT_LH7 compress_method = LZHUFF7_METHOD_NUM; #endif header_level = HEADER_LEVEL1; quiet_mode = 0; #ifdef EUC euc_mode = FALSE; #endif /* view command flags */ verbose_listing = FALSE; /* extract command flags */ output_to_stdout = FALSE; /* append command flags */ new_archive = FALSE; update_if_newer = FALSE; delete_after_append = FALSE; generic_format = FALSE; remove_temporary_at_error = FALSE; recover_archive_when_interrupt = FALSE; remove_extracting_file_when_interrupt = FALSE; get_filename_from_stdin = FALSE; ignore_directory = FALSE; verify_mode = FALSE; noconvertcase = FALSE; extract_directory = NULL; xfilec = 257; } /* ------------------------------------------------------------------------ */ /* */ /* ------------------------------------------------------------------------ */ static int sort_by_ascii(char **a, char **b) { char *p, *q; int c1, c2; p = *a, q = *b; if (generic_format) { do { c1 = *(unsigned char *) p++; c2 = *(unsigned char *) q++; if (!c1 || !c2) break; if (islower(c1)) c1 = toupper(c1); if (islower(c2)) c2 = toupper(c2); } while (c1 == c2); return c1 - c2; } else { while (*p == *q && *p != '\0') p++, q++; return *(unsigned char *) p - *(unsigned char *) q; } } /* ------------------------------------------------------------------------ */ char *xxrealloc(char *old, int size) { char *p = (char *) xrealloc(char, old, size); if (!p) fatal_error(_T("Not enough memory")); return p; } /* ------------------------------------------------------------------------ */ /* STRING POOL */ /* ------------------------------------------------------------------------ */ /* string pool : +-------------+-------------+------+-------------+----------+ | N A M E 1 \0| N A M E 2 \0| .... | N A M E n \0| | +-------------+-------------+------+-------------+----------+ ^ ^ ^ buffer+0 buffer+used buffer+size vector : +---------------+---------------+------------- -----------------+ | pointer to | pointer to | pointer to ... pointer to | | stringpool | N A M E 1 | N A M E 2 ... N A M E n | +---------------+---------------+------------- -------------+ ^ malloc base returned */ /* ------------------------------------------------------------------------ */ void init_sp(struct string_pool *sp) { sp->size = 1024 - 8; /* any ( >=0 ) */ sp->used = 0; sp->n = 0; sp->buffer = (char *) xmalloc(char, sp->size); } /* ------------------------------------------------------------------------ */ void add_sp(struct string_pool *sp, char *name, int len) { while (sp->used + len > sp->size) { sp->size *= 2; sp->buffer = (char *) xxrealloc(sp->buffer, sp->size * sizeof(char)); } bcopy(name, sp->buffer + sp->used, len); sp->used += len; sp->n++; } /* ------------------------------------------------------------------------ */ void finish_sp(struct string_pool *sp, int *v_count, char ***v_vector) { int i; char *p; char **v; v = (char **) xmalloc(char*, sp->n + 1); *v++ = sp->buffer; *v_vector = v; *v_count = sp->n; p = sp->buffer; for (i = sp->n; i; i--) { *v++ = p; if (i - 1) p += strlen(p) + 1; } } /* ------------------------------------------------------------------------ */ void free_sp(char **vector) { vector--; free(*vector); /* free string pool */ free(vector); } /* ------------------------------------------------------------------------ */ /* READ DIRECTORY FILES */ /* ------------------------------------------------------------------------ */ static boolean include_path_p(char *path, char *name) { char *n = name; while (*path) if (*path++ != *n++) return (path[-1] == '/' && *n == '\0'); return (*n == '/' || (n != name && path[-1] == '/' && n[-1] == '/')); }
#include <iostream> #include <queue> using namespace std; void printBFS(int **edges, int n, int startVertex, bool *visited){ queue<int> pendingVertices; pendingVertices.push(startVertex); visited[startVertex] = true; while(!pendingVertices.empty()){ int currVertex = pendingVertices.front(); pendingVertices.pop(); cout<< currVertex<<endl; for(int i=0; i<n; i++){ if(visited[i]){ continue; } if(edges[currVertex][i] ){ pendingVertices.push(i); visited[i] = true; } } } } //--------------------------------------------------------------------------------------------------------- void BFS(int **edges, int n, bool *visited){ for(int i=0; i<n; i++){ if(!visited[i]){ printBFS(edges, n, i, visited); } } } //---------------------------------------------------------------------------------------------------------- int main() { int n; //no. of vertices int e; //no. of edges cin >> n >> e; //Taking Adjacency matrix of size n x n and initializing all its cells with value 0. int **edges = new int*[n]; for(int i=0; i<n; i++){ edges[i] = new int[n]; for(int j=0; j<n; j++){ edges[i][j] = 0; } } for(int i=0; i<e; i++){ int first; int second; cin>>first>>second; edges[first][second] = 1; edges[second][first] = 1; } bool *visited = new bool[n]; for(int i=0; i<n; i++){ visited[i] = false; } // //printing in BFS fashion // printBFS(edges, n, 0, visited); BFS(edges, n, visited); }
/******************************** ITSP 2K15 TEAM ID 148 PROJECT SURVEILLANCE BOT MICROCONTROLLER CODE ********************************/ #include<VarSpeedServo.h> VarSpeedServo servo_x,servo_y,servo_gun_x,servo_gun_y,gun_trigger; long int err_sum_x=0; long int err_sum_y=0; int last_err_x=0; int last_err_y=0; int diff_err_x; int diff_err_y; int error_x; int error_y; int a; int b; int i= 0; int flag=1; float angle_x=90.0; float angle_y=20.0; float angle_x_g=90; float angle_y_g=20; double speed_x=0; double speed_y=0; double kp=0.15 ,ki=0.015,kd=15; int start=0; int shoot=0; int control=0; void setup() { Serial1.begin(9600); servo_x.attach(10); servo_y.attach(12); servo_gun_x.attach(3); servo_gun_y.attach(5); gun_trigger.attach(7); servo_x.write(90,50,true); servo_y.write(20,50,true); servo_gun_x.write(90,50,true); servo_gun_y.write(35,50,true); gun_trigger.write(170,50,true); Serial.begin(9600); pinMode(5,OUTPUT); digitalWrite(5,LOW); flag=1; } void loop() { if(Serial1.available()>0) { start=Serial1.read(); if(start=='a') { while(flag==1) { if(Serial.available()>0) { a=Serial.read(); delay(10); b=Serial.read(); Serial.write(a); Serial.write(b); if( (a*2.5)<640 && (b*1.875)<480 && (a*2.5)>5 && (b*1.875)>4 ) { i=0; error_x=(a*2.5)- 320; error_y=(b*1.875)- 240; err_sum_x+=error_x; err_sum_y+=error_y; diff_err_x=error_x-last_err_x; diff_err_y=error_y-last_err_y; angle_x=-float(err_sum_x*0.035)+90; angle_y=-float(err_sum_y*0.035)+20; speed_x = error_x*kp + err_sum_x*ki + diff_err_x*kd; speed_y = error_y*kp + err_sum_y*ki + diff_err_y*kd; if(abs(error_x)>60) { servo_x.write(int(angle_x),abs(speed_x),false); } if(abs(error_y)>40) { servo_y.write(int(angle_y),abs(speed_y),false); } delay(200); last_err_x=error_x; last_err_y=error_y; } if(a*2.5<=5 && b*1.875<=4) { if(angle_x>90) servo_x.write(int(angle_x)-5*i,5,false); else servo_x.write(int(angle_x)+5*i,5,false); if(angle_y>20) servo_y.write(int(angle_y)-5*i,5,false); else servo_y.write(int(angle_y)+5*i,5,false); delay(200); i++; } } if(Serial1.available()>0) { shoot=Serial1.read(); if(shoot=='s') { servo_gun_x.write(int(angle_x+10),30,false); servo_gun_y.write(int(angle_y-5),30,false); delay(1000); gun_trigger.write(135,50,true); gun_trigger.write(170,50,true); delay(100); flag=0; break; } } } } else if(start=='m') { Serial.println("Received"); while(1) { if(Serial1.available()) { control= Serial1.read(); if(control=='r') { angle_x+=3; angle_x_g+=3; } else if (control=='l') { angle_x-=3; angle_x_g-=3; } else if (control=='u') { angle_y+=3; angle_y_g+=3; } else if(control=='d') { angle_y-=3; angle_y_g-=3; } else if(control =='s') { delay(100); delay(500); gun_trigger.write(135,50,true); gun_trigger.write(170,50,true); delay(100); break; } servo_x.write(angle_x,20,false); servo_y.write(angle_y,20,false); servo_gun_x.write(angle_x_g,20,false); servo_gun_y.write(angle_y_g,20,false); } } } } }
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include "pdmatrix.h" #include "wyarray.h" #include "inout.h" using namespace std; /* * G x = g * G'G x = G'g * A x = b * * where G is ny x nx matrix */ PDMatrix::PDMatrix (double *g, int nx, int ny) { this->nx = nx; this->ny = ny; this->nm = ny; this->n = nx * ny; this->g = new double[n]; memcpy(this->g, g, n * sizeof(double)); } void PDMatrix::Init (double *x, int nx, int ny) { this->nx = nx; this->ny = ny; this->nm = ny; this->n = nx * ny; this->g = new double[n]; memcpy(this->g, x, n * sizeof(double)); } void PDMatrix::Forward(double *y, double *x) { int k; for (int i=0; i<nx; i++) { k=i*nx; for (int j=0; j<ny; j++) y[i] += this->g[k+j]*x[j]; } } void PDMatrix::Adjoint(double *y, double *x) { int k; for (int i=0; i<nx; i++) { k=i*nx; for (int j=0; j<ny; j++) y[j] += this->g[k+j]*x[i]; } } void PDMatrix::Opr (double *y, double *x) { double *p = new double[nx]; memset(p, 0, nx * sizeof(double)); memset(y, 0, ny * sizeof(double)); this->Forward(p, x); this->Adjoint(y, p); delete [] p; } void PDMatrix::Free () { delete [] this->g; } void PDMatrix::PrintVector(double *x, int m, char *str) { cout << endl << str << endl; for (int i = 0; i < m; i ++) cout << " i = " << i << ", " << x[i] << endl; }
#include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <string.h> class StdCapture { public: StdCapture(): m_capturing(false), m_init(false), m_oldStdOut(0), m_oldStdErr(0); ~StdCapture(); void BeginCapture(); bool EndCapture(); std::string GetCapture() const; private: enum PIPES { READ, WRITE }; int m_pipe[2]; int m_oldStdOut; int m_oldStdErr; bool m_capturing; bool m_init; std::string m_captured; };
#pragma once #include <chrono> #include <string> #define PROF_ENABLED 1 namespace TProfiler { // // profiler timer // using ProfilerTicks = int64_t; ProfilerTicks GetTime(); double ToSeconds(ProfilerTicks ticks); // // profiler section // struct Section; using SectionPtr = Section *; SectionPtr GetSection(const char *name); SectionPtr AddSection(const char *name, const char *categories = nullptr); SectionPtr ResolveSection(SectionPtr *ppsection, const char *name, const char *categories = nullptr); void AddSpan(SectionPtr section, ProfilerTicks start); void AddEvent(SectionPtr section); void AddAsyncBegin(SectionPtr section, uintptr_t async_id); void AddAsyncNext(SectionPtr section, uintptr_t async_id); void AddAsyncEnd(SectionPtr section, uintptr_t async_id); void AddGPUSpan(SectionPtr section, ProfilerTicks start, ProfilerTicks end); void OnGUI(bool *popen); void OnGUIPanel(); void NextFrame(); void SkipFrame(); void AddCaptureLocation(std::string url); void CaptureNextFrame(); bool CaptureToJsonString(std::string &json); void CaptureToFile(const std::string &path); void Clear(); class ProfilerScope { public: inline ProfilerScope(SectionPtr section) : m_section(section), m_startTime(GetTime()) { } inline ~ProfilerScope() { AddSpan(m_section, m_startTime); } protected: SectionPtr m_section; ProfilerTicks m_startTime; }; } // // profile section macros // #ifdef WIN32 #define __PRETTY_FUNCTION__ __FUNCTION__ #endif #if PROF_ENABLED #define PROFILE_DECLARE_SECTION(__section_var, __name, __categories) \ static TProfiler::SectionPtr __section_var; \ if (!__section_var) TProfiler::ResolveSection(&__section_var, __name, __categories); #define __PROFILE_SCOPE(__section_var, __name, __categories) \ static TProfiler::SectionPtr __section_var; \ if (!__section_var) TProfiler::ResolveSection(&__section_var, __name, __categories); \ TProfiler::ProfilerScope __scope_##__section_var (__section_var); #define CONCAT_IMPL( x, y ) x##y #define MACRO_CONCAT( x, y ) CONCAT_IMPL( x, y ) #define _PROFILE_SCOPE(__section_var, __name, __categories) __PROFILE_SCOPE( __section_var , __name, __categories) #define PROFILE_SCOPE(__name) _PROFILE_SCOPE( MACRO_CONCAT(_profiler_, __COUNTER__), __name, nullptr) #define PROFILE_SCOPE_CAT(__name, __categories) _PROFILE_SCOPE( MACRO_CONCAT(_profiler_, __COUNTER__), __name, __categories) #define PROFILE_FUNCTION() PROFILE_SCOPE(__PRETTY_FUNCTION__) #define PROFILE_FUNCTION_CAT(__categories) PROFILE_SCOPE_CAT(__PRETTY_FUNCTION__, __categories) #else #define __PROFILE_SCOPE(__section_var, __name, __categories) #define _PROFILE_SCOPE(__counter, __name, __categories) #define PROFILE_DECLARE_SECTION(__section_var, __name, __categories) #define PROFILE_SCOPE(__name) #define PROFILE_SCOPE_CAT(__name, __categories) #define PROFILE_FUNCTION() #define PROFILE_FUNCTION_CAT(__categories) #endif #define PROFILE_FRAME() \ TProfiler::NextFrame(); \ PROFILE_FUNCTION() //PROFILE_SCOPE(".frame") #define PROFILE_GPU() PROFILE_SCOPE_CAT(".gpu.wait", "gpu")
#pragma once #include <memory> #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> namespace imog { typedef std::shared_ptr<spdlog::logger> _LogType; class Logger { #define PATTERN_PRINT "%v" #define PATTERN_ALERT "%t %@ : %^%v%$" private: // Patterns static const char* m_patternPrints; static const char* m_patternAlerts; // Loggers static _LogType m_info; static _LogType m_error; static _LogType m_print; public: // Getter of info logger static _LogType& info(); // Getter of error logger static _LogType& error(); // Getter of print logger static _LogType& print(); }; } // namespace imog #define LOG(...) SPDLOG_LOGGER_INFO(imog::Logger::print(), __VA_ARGS__); #define LOGD(...) SPDLOG_LOGGER_INFO(imog::Logger::info(), __VA_ARGS__); #define LOGE(...) SPDLOG_LOGGER_ERROR(imog::Logger::error(), __VA_ARGS__);
/* Copyright (c) 2013-2014 Sam Hardeman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "Platforms.h" #include "Threading.h" /* ICECAT Networking v2.0 class PacketReceiver: This class receives packets and puts them in the handler. */ namespace IceNet { class Client; class PacketReceiver { public: PacketReceiver( Client* parentClient ); ~PacketReceiver( void ); static THREAD_FUNC PacketReceiverLoop( void* packetReceiver ); Thread* m_Thread; private: Client* m_ParentClient; }; };
#include "GraphicLoader.h" #include "Log.h" #include "Testing.h" #include "Timer.h" #include "3dAnimation.h" #include "StringUtils.h" #include "Timer.h" #include "SpriteManager.h" #include "ResourceManager.h" #include "Crypt.h" #include "GraphicStructures.h" #include "Version_Include.h" StrVec GraphicLoader::processedFiles; BoneVec GraphicLoader::loadedModels; StrVec GraphicLoader::loadedModelNames; PtrVec GraphicLoader::loadedAnimations; Bone* GraphicLoader::LoadModel( const string& fname ) { // Find already loaded for( size_t i = 0, j = loadedModelNames.size(); i < j; i++ ) if( _str( loadedModelNames[ i ] ).compareIgnoreCase( fname ) ) return loadedModels[ i ]; // Add to already processed for( size_t i = 0, j = processedFiles.size(); i < j; i++ ) if( _str( processedFiles[ i ] ).compareIgnoreCase( fname ) ) return nullptr; processedFiles.push_back( fname ); // Load file data File file; if( !file.LoadFile( fname ) ) { WriteLog( "3d file '{}' not found.\n", fname ); return nullptr; } // Load bones Bone* root_bone = new Bone(); root_bone->Load( file ); root_bone->FixAfterLoad( root_bone ); // Load animations uint anim_sets_count = file.GetBEUInt(); for( uint i = 0; i < anim_sets_count; i++ ) { AnimSet* anim_set = new AnimSet(); anim_set->Load( file ); loadedAnimations.push_back( anim_set ); } // Add to collection loadedModels.push_back( root_bone ); loadedModelNames.push_back( fname ); return root_bone; } void GraphicLoader::DestroyModel( Bone* root_bone ) { for( size_t i = 0, j = loadedModels.size(); i < j; i++ ) { if( loadedModels[ i ] == root_bone ) { processedFiles.erase( std::find( processedFiles.begin(), processedFiles.end(), loadedModelNames[ i ] ) ); loadedModels.erase( loadedModels.begin() + i ); loadedModelNames.erase( loadedModelNames.begin() + i ); break; } } delete root_bone; } AnimSet* GraphicLoader::LoadAnimation( const string& anim_fname, const string& anim_name ) { // Find in already loaded bool take_first = anim_name == "Base"; for( size_t i = 0; i < loadedAnimations.size(); i++ ) { AnimSet* anim = (AnimSet*) loadedAnimations[ i ]; if( _str( anim->GetFileName() ).compareIgnoreCase( anim_fname ) && ( take_first || _str( anim->GetName() ).compareIgnoreCase( anim_name ) ) ) return anim; } // Check maybe file already processed and nothing founded for( size_t i = 0; i < processedFiles.size(); i++ ) if( _str( processedFiles[ i ] ).compareIgnoreCase( anim_fname ) ) return nullptr; // File not processed, load and recheck animations if( LoadModel( anim_fname ) ) return LoadAnimation( anim_fname, anim_name ); return nullptr; } /************************************************************************/ /* Textures */ /************************************************************************/ MeshTextureVec GraphicLoader::loadedMeshTextures; MeshTexture* GraphicLoader::LoadTexture( const string& texture_name, const string& model_path ) { if( texture_name.empty() ) return nullptr; // Try find already loaded texture for( auto it = loadedMeshTextures.begin(), end = loadedMeshTextures.end(); it != end; ++it ) { MeshTexture* texture = *it; if( _str( texture->Name ).compareIgnoreCase( texture_name ) ) return texture && texture->Id ? texture : nullptr; } // Allocate structure MeshTexture* mesh_tex = new MeshTexture(); mesh_tex->Name = texture_name; mesh_tex->Id = 0; loadedMeshTextures.push_back( mesh_tex ); // First try load from textures folder SprMngr.PushAtlasType( RES_ATLAS_TEXTURES ); AnyFrames* anim = SprMngr.LoadAnimation( _str( model_path ).extractDir() + texture_name ); SprMngr.PopAtlasType(); if( !anim ) return nullptr; SpriteInfo* si = SprMngr.GetSpriteInfo( anim->Ind[ 0 ] ); mesh_tex->Id = si->Atlas->TextureOwner->Id; memcpy( mesh_tex->SizeData, si->Atlas->TextureOwner->SizeData, sizeof( mesh_tex->SizeData ) ); mesh_tex->AtlasOffsetData[ 0 ] = si->SprRect[ 0 ]; mesh_tex->AtlasOffsetData[ 1 ] = si->SprRect[ 1 ]; mesh_tex->AtlasOffsetData[ 2 ] = si->SprRect[ 2 ] - si->SprRect[ 0 ]; mesh_tex->AtlasOffsetData[ 3 ] = si->SprRect[ 3 ] - si->SprRect[ 1 ]; AnyFrames::Destroy( anim ); return mesh_tex; } void GraphicLoader::DestroyTextures() { for( auto it = loadedMeshTextures.begin(), end = loadedMeshTextures.end(); it != end; ++it ) delete *it; loadedMeshTextures.clear(); } /************************************************************************/ /* Effects */ /************************************************************************/ EffectVec GraphicLoader::loadedEffects; Effect* GraphicLoader::LoadEffect( const string& effect_name, bool use_in_2d, const string& defines /* = "" */, const string& model_path /* = "" */, EffectDefault* defaults /* = nullptr */, uint defaults_count /* = 0 */ ) { // Erase extension string fname = _str( effect_name ).eraseFileExtension(); // Reset defaults to nullptr if it's count is zero if( defaults_count == 0 ) defaults = nullptr; // Try find already loaded effect string loaded_fname = fname; for( auto it = loadedEffects.begin(), end = loadedEffects.end(); it != end; ++it ) { Effect* effect = *it; if( _str( effect->Name ).compareIgnoreCase( loaded_fname ) && effect->Defines == defines && effect->Defaults == defaults ) return effect; } // Add extension fname += ".glsl"; // Load text file File file; string path = _str( model_path ).extractDir() + fname; if( !file.LoadFile( path ) ) { WriteLog( "Effect file '{}' not found.\n", path ); return nullptr; } // Parse effect commands vector< StrVec > commands; while( true ) { string line = file.GetNonEmptyLine(); if( line.empty() ) break; if( _str( line ).startsWith( "Effect " ) ) { StrVec tokens = _str( line.substr( _str( "Effect " ).length() ) ).split( ' ' ); if( !tokens.empty() ) commands.push_back( tokens ); } else if( _str( line ).startsWith( "#version" ) ) { break; } } // Find passes count bool fail = false; uint passes = 1; for( size_t i = 0; i < commands.size(); i++ ) if( commands[ i ].size() >= 2 && commands[ i ][ 0 ] == "Passes" ) passes = ConvertParamValue( commands[ i ][ 1 ], fail ); // New effect Effect effect; effect.Name = loaded_fname; effect.Defines = defines; // Load passes for( uint pass = 0; pass < passes; pass++ ) if( !LoadEffectPass( &effect, fname, file, pass, use_in_2d, defines, defaults, defaults_count ) ) return nullptr; // Process commands for( size_t i = 0; i < commands.size(); i++ ) { static auto get_gl_blend_func = [] ( const string &s ) { if( s == "GL_ZERO" ) return GL_ZERO; if( s == "GL_ONE" ) return GL_ONE; if( s == "GL_SRC_COLOR" ) return GL_SRC_COLOR; if( s == "GL_ONE_MINUS_SRC_COLOR" ) return GL_ONE_MINUS_SRC_COLOR; if( s == "GL_DST_COLOR" ) return GL_DST_COLOR; if( s == "GL_ONE_MINUS_DST_COLOR" ) return GL_ONE_MINUS_DST_COLOR; if( s == "GL_SRC_ALPHA" ) return GL_SRC_ALPHA; if( s == "GL_ONE_MINUS_SRC_ALPHA" ) return GL_ONE_MINUS_SRC_ALPHA; if( s == "GL_DST_ALPHA" ) return GL_DST_ALPHA; if( s == "GL_ONE_MINUS_DST_ALPHA" ) return GL_ONE_MINUS_DST_ALPHA; if( s == "GL_CONSTANT_COLOR" ) return GL_CONSTANT_COLOR; if( s == "GL_ONE_MINUS_CONSTANT_COLOR" ) return GL_ONE_MINUS_CONSTANT_COLOR; if( s == "GL_CONSTANT_ALPHA" ) return GL_CONSTANT_ALPHA; if( s == "GL_ONE_MINUS_CONSTANT_ALPHA" ) return GL_ONE_MINUS_CONSTANT_ALPHA; if( s == "GL_SRC_ALPHA_SATURATE" ) return GL_SRC_ALPHA_SATURATE; return -1; }; static auto get_gl_blend_equation = [] ( const string &s ) { if( s == "GL_FUNC_ADD" ) return GL_FUNC_ADD; if( s == "GL_FUNC_SUBTRACT" ) return GL_FUNC_SUBTRACT; if( s == "GL_FUNC_REVERSE_SUBTRACT" ) return GL_FUNC_REVERSE_SUBTRACT; if( s == "GL_MAX" ) return GL_MAX; if( s == "GL_MIN" ) return GL_MIN; return -1; }; StrVec& tokens = commands[ i ]; if( tokens[ 0 ] == "Pass" && tokens.size() >= 3 ) { uint pass = ConvertParamValue( tokens[ 1 ], fail ); if( pass < passes ) { EffectPass& effect_pass = effect.Passes[ pass ]; if( tokens[ 2 ] == "BlendFunc" && tokens.size() >= 5 ) { effect_pass.IsNeedProcess = effect_pass.IsChangeStates = true; effect_pass.BlendFuncParam1 = get_gl_blend_func( tokens[ 3 ] ); effect_pass.BlendFuncParam2 = get_gl_blend_func( tokens[ 4 ] ); if( effect_pass.BlendFuncParam1 == -1 || effect_pass.BlendFuncParam2 == -1 ) fail = true; } else if( tokens[ 2 ] == "BlendEquation" && tokens.size() >= 4 ) { effect_pass.IsNeedProcess = effect_pass.IsChangeStates = true; effect_pass.BlendEquation = get_gl_blend_equation( tokens[ 3 ] ); if( effect_pass.BlendEquation == -1 ) fail = true; } else if( tokens[ 2 ] == "Shadow" ) { effect_pass.IsShadow = true; } else { fail = true; } } else { fail = true; } } } if( fail ) { WriteLog( "Invalid commands in effect '{}'.\n", fname ); return nullptr; } // Assign identifier and return static uint effect_id = 0; effect.Id = ++effect_id; loadedEffects.push_back( new Effect( effect ) ); return loadedEffects.back(); } bool GraphicLoader::LoadEffectPass( Effect* effect, const string& fname, File& file, uint pass, bool use_in_2d, const string& defines, EffectDefault* defaults, uint defaults_count ) { EffectPass effect_pass; memzero( &effect_pass, sizeof( effect_pass ) ); GLuint program = 0; // Make effect binary file name string binary_cache_name; if( GL_HAS( get_program_binary ) ) { binary_cache_name = _str( "Shader/{}", fname ).eraseFileExtension(); if( !defines.empty() ) { binary_cache_name += _str( "_" + defines ). replace( '\t', ' ' ). // Tabs to spaces replace( ' ', ' ', ' ' ). // Multiple spaces to single replace( '\r', '\n', '_' ). // EOL's to '_' replace( '\r', '_' ). // EOL's to '_' replace( '\n', '_' ); // EOL's to '_' } #ifdef FO_X64 binary_cache_name += "_x64"; #endif binary_cache_name += "_"; binary_cache_name += _str( "{}", pass ); binary_cache_name += ".glslb"; } // Load from binary File file_binary; if( GL_HAS( get_program_binary ) ) { UCharVec data; if( Crypt.GetCache( binary_cache_name, data ) && data.size() > sizeof( uint64 ) ) { uint64 write_time = *(uint64*) &data[ data.size() - sizeof( uint64 ) ]; if( write_time >= file.GetWriteTime() ) file_binary.LoadStream( &data[ 0 ], (uint) data.size() - sizeof( uint64 ) ); } } if( file_binary.IsLoaded() ) { bool loaded = false; uint version = file_binary.GetBEUInt(); if( version == (uint) FO_VERSION ) { GLenum format = file_binary.GetBEUInt(); UNUSED_VARIABLE( format ); // OGL ES GLsizei length = file_binary.GetBEUInt(); if( file_binary.GetFsize() >= length + sizeof( uint ) * 3 ) { GL( program = glCreateProgram() ); glProgramBinary( program, format, file_binary.GetCurBuf(), length ); glGetError(); // Skip error from glProgramBinary, if it has GLint linked; GL( glGetProgramiv( program, GL_LINK_STATUS, &linked ) ); if( linked ) { loaded = true; } else { WriteLog( "Failed to link binary shader program '{}', effect '{}'.\n", binary_cache_name, fname ); GL( glDeleteProgram( program ) ); } } else { WriteLog( "Binary shader program '{}' truncated, effect '{}'.\n", binary_cache_name, fname ); } } if( !loaded ) file_binary.UnloadFile(); } // Load from text if( !file_binary.IsLoaded() ) { // Get version string file_content = _str( file.GetCStr() ).normalizeLineEndings(); string version; size_t ver_begin = file_content.find( "#version" ); if( ver_begin != string::npos ) { size_t ver_end = file_content.find( '\n', ver_begin ); if( ver_end != string::npos ) { version = file_content.substr( ver_begin, ver_end - ver_begin ); file_content = file_content.substr( ver_end + 1 ); } } #ifdef FO_OGL_ES version = "precision lowp float;\n"; #endif // Internal definitions string internal_defines = _str( "#define PASS{}\n#define MAX_BONES {}\n", pass, Effect::MaxBones ); // Create shaders GLuint vs, fs; GL( vs = glCreateShader( GL_VERTEX_SHADER ) ); GL( fs = glCreateShader( GL_FRAGMENT_SHADER ) ); string buf = _str( "{}{}{}{}{}{}{}", version, "\n", "#define VERTEX_SHADER\n", internal_defines, defines, "\n", file_content ); const GLchar* vs_str = &buf[ 0 ]; GL( glShaderSource( vs, 1, &vs_str, nullptr ) ); buf = _str( "{}{}{}{}{}{}{}", version, "\n", "#define FRAGMENT_SHADER\n", internal_defines, defines, "\n", file_content ); const GLchar* fs_str = &buf[ 0 ]; GL( glShaderSource( fs, 1, &fs_str, nullptr ) ); // Info parser struct ShaderInfo { static void Log( const char* shader_name, GLint shader ) { int len = 0; GL( glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &len ) ); if( len > 0 ) { GLchar* str = new GLchar[ len ]; int chars = 0; glGetShaderInfoLog( shader, len, &chars, str ); WriteLog( "{} output:\n{}", shader_name, str ); delete[] str; } } static void LogProgram( GLint program ) { int len = 0; GL( glGetProgramiv( program, GL_INFO_LOG_LENGTH, &len ) ); if( len > 0 ) { GLchar* str = new GLchar[ len ]; int chars = 0; glGetProgramInfoLog( program, len, &chars, str ); WriteLog( "Program info output:\n{}", str ); delete[] str; } } }; // Compile vs GLint compiled; GL( glCompileShader( vs ) ); GL( glGetShaderiv( vs, GL_COMPILE_STATUS, &compiled ) ); if( !compiled ) { WriteLog( "Vertex shader not compiled, effect '{}'.\n", fname ); ShaderInfo::Log( "Vertex shader", vs ); GL( glDeleteShader( vs ) ); GL( glDeleteShader( fs ) ); return false; } // Compile fs GL( glCompileShader( fs ) ); GL( glGetShaderiv( fs, GL_COMPILE_STATUS, &compiled ) ); if( !compiled ) { WriteLog( "Fragment shader not compiled, effect '{}'.\n", fname ); ShaderInfo::Log( "Fragment shader", fs ); GL( glDeleteShader( vs ) ); GL( glDeleteShader( fs ) ); return false; } // Make program GL( program = glCreateProgram() ); GL( glAttachShader( program, vs ) ); GL( glAttachShader( program, fs ) ); if( use_in_2d ) { GL( glBindAttribLocation( program, 0, "InPosition" ) ); GL( glBindAttribLocation( program, 1, "InColor" ) ); GL( glBindAttribLocation( program, 2, "InTexCoord" ) ); #ifndef DISABLE_EGG GL( glBindAttribLocation( program, 3, "InTexEggCoord" ) ); #endif } else { GL( glBindAttribLocation( program, 0, "InPosition" ) ); GL( glBindAttribLocation( program, 1, "InNormal" ) ); GL( glBindAttribLocation( program, 2, "InTexCoord" ) ); GL( glBindAttribLocation( program, 3, "InTexCoordBase" ) ); GL( glBindAttribLocation( program, 4, "InTangent" ) ); GL( glBindAttribLocation( program, 5, "InBitangent" ) ); GL( glBindAttribLocation( program, 6, "InBlendWeights" ) ); GL( glBindAttribLocation( program, 7, "InBlendIndices" ) ); } #ifndef FO_OGL_ES if( GL_HAS( get_program_binary ) ) GL( glProgramParameteri( program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE ) ); #endif GL( glLinkProgram( program ) ); GLint linked; GL( glGetProgramiv( program, GL_LINK_STATUS, &linked ) ); if( !linked ) { WriteLog( "Failed to link shader program, effect '{}'.\n", fname ); ShaderInfo::LogProgram( program ); GL( glDetachShader( program, vs ) ); GL( glDetachShader( program, fs ) ); GL( glDeleteShader( vs ) ); GL( glDeleteShader( fs ) ); GL( glDeleteProgram( program ) ); return false; } // Save in binary if( GL_HAS( get_program_binary ) ) { GLsizei buf_size; GL( glGetProgramiv( program, GL_PROGRAM_BINARY_LENGTH, &buf_size ) ); GLsizei length = 0; GLenum format = 0; UCharVec buf; buf.resize( buf_size ); GL( glGetProgramBinary( program, buf_size, &length, &format, &buf[ 0 ] ) ); file_binary.SetBEUInt( (uint) FO_VERSION ); file_binary.SetBEUInt( format ); file_binary.SetBEUInt( length ); file_binary.SetData( &buf[ 0 ], length ); uint64 write_time = file.GetWriteTime() + 1; file_binary.SetData( &write_time, sizeof( write_time ) ); Crypt.SetCache( binary_cache_name, file_binary.GetOutBuf(), file_binary.GetOutBufLen() ); } } // Bind data GL( effect_pass.ProjectionMatrix = glGetUniformLocation( program, "ProjectionMatrix" ) ); GL( effect_pass.ZoomFactor = glGetUniformLocation( program, "ZoomFactor" ) ); GL( effect_pass.ColorMap = glGetUniformLocation( program, "ColorMap" ) ); GL( effect_pass.ColorMapSize = glGetUniformLocation( program, "ColorMapSize" ) ); GL( effect_pass.ColorMapSamples = glGetUniformLocation( program, "ColorMapSamples" ) ); GL( effect_pass.EggMap = glGetUniformLocation( program, "EggMap" ) ); GL( effect_pass.EggMapSize = glGetUniformLocation( program, "EggMapSize" ) ); GL( effect_pass.SpriteBorder = glGetUniformLocation( program, "SpriteBorder" ) ); GL( effect_pass.GroundPosition = glGetUniformLocation( program, "GroundPosition" ) ); GL( effect_pass.LightColor = glGetUniformLocation( program, "LightColor" ) ); GL( effect_pass.WorldMatrices = glGetUniformLocation( program, "WorldMatrices" ) ); GL( effect_pass.Time = glGetUniformLocation( program, "Time" ) ); effect_pass.TimeCurrent = 0.0f; effect_pass.TimeLastTick = Timer::AccurateTick(); GL( effect_pass.TimeGame = glGetUniformLocation( program, "TimeGame" ) ); effect_pass.TimeGameCurrent = 0.0f; effect_pass.TimeGameLastTick = Timer::AccurateTick(); effect_pass.IsTime = ( effect_pass.Time != -1 || effect_pass.TimeGame != -1 ); GL( effect_pass.Random1 = glGetUniformLocation( program, "Random1Effect" ) ); GL( effect_pass.Random2 = glGetUniformLocation( program, "Random2Effect" ) ); GL( effect_pass.Random3 = glGetUniformLocation( program, "Random3Effect" ) ); GL( effect_pass.Random4 = glGetUniformLocation( program, "Random4Effect" ) ); effect_pass.IsRandom = ( effect_pass.Random1 != -1 || effect_pass.Random2 != -1 || effect_pass.Random3 != -1 || effect_pass.Random4 != -1 ); effect_pass.IsTextures = false; for( int i = 0; i < EFFECT_TEXTURES; i++ ) { GL( effect_pass.Textures[ i ] = glGetUniformLocation( program, _str( "Texture{}", i ).c_str() ) ); if( effect_pass.Textures[ i ] != -1 ) { effect_pass.IsTextures = true; GL( effect_pass.TexturesSize[ i ] = glGetUniformLocation( program, _str( "Texture%dSize", i ).c_str() ) ); GL( effect_pass.TexturesAtlasOffset[ i ] = glGetUniformLocation( program, _str( "Texture{}AtlasOffset", i ).c_str() ) ); } } effect_pass.IsScriptValues = false; for( int i = 0; i < EFFECT_SCRIPT_VALUES; i++ ) { GL( effect_pass.ScriptValues[ i ] = glGetUniformLocation( program, _str( "EffectValue{}", i ).c_str() ) ); if( effect_pass.ScriptValues[ i ] != -1 ) effect_pass.IsScriptValues = true; } GL( effect_pass.AnimPosProc = glGetUniformLocation( program, "AnimPosProc" ) ); GL( effect_pass.AnimPosTime = glGetUniformLocation( program, "AnimPosTime" ) ); effect_pass.IsAnimPos = ( effect_pass.AnimPosProc != -1 || effect_pass.AnimPosTime != -1 ); effect_pass.IsNeedProcess = ( effect_pass.IsTime || effect_pass.IsRandom || effect_pass.IsTextures || effect_pass.IsScriptValues || effect_pass.IsAnimPos || effect_pass.IsChangeStates ); // Set defaults if( defaults ) { GL( glUseProgram( program ) ); for( uint d = 0; d < defaults_count; d++ ) { EffectDefault& def = defaults[ d ]; GLint location = -1; GL( location = glGetUniformLocation( program, def.Name ) ); if( !IS_EFFECT_VALUE( location ) ) continue; switch( def.Type ) { case EffectDefault::String: break; case EffectDefault::Float: GL( glUniform1fv( location, def.Size / sizeof( float ), (GLfloat*) def.Data ) ); break; case EffectDefault::Int: GL( glUniform1iv( location, def.Size / sizeof( int ), (GLint*) def.Data ) ); break; default: break; } } GL( glUseProgram( 0 ) ); } effect_pass.Program = program; effect->Passes.push_back( effect_pass ); return true; } void GraphicLoader::EffectProcessVariables( EffectPass& effect_pass, bool start, float anim_proc /* = 0.0f */, float anim_time /* = 0.0f */, MeshTexture** textures /* = NULL */ ) { // Process effect if( start ) { if( effect_pass.IsTime ) { double tick = Timer::AccurateTick(); if( IS_EFFECT_VALUE( effect_pass.Time ) ) { effect_pass.TimeCurrent += (float) ( tick - effect_pass.TimeLastTick ) / 1000.0f; effect_pass.TimeLastTick = tick; if( effect_pass.TimeCurrent >= 120.0f ) effect_pass.TimeCurrent = fmod( effect_pass.TimeCurrent, 120.0f ); SET_EFFECT_VALUE( effect, effect_pass.Time, effect_pass.TimeCurrent ); } if( IS_EFFECT_VALUE( effect_pass.TimeGame ) ) { if( !Timer::IsGamePaused() ) { effect_pass.TimeGameCurrent += (float) ( tick - effect_pass.TimeGameLastTick ) / 1000.0f; effect_pass.TimeGameLastTick = tick; if( effect_pass.TimeGameCurrent >= 120.0f ) effect_pass.TimeGameCurrent = fmod( effect_pass.TimeGameCurrent, 120.0f ); } else { effect_pass.TimeGameLastTick = tick; } SET_EFFECT_VALUE( effect, effect_pass.TimeGame, effect_pass.TimeGameCurrent ); } } if( effect_pass.IsRandom ) { if( IS_EFFECT_VALUE( effect_pass.Random1 ) ) SET_EFFECT_VALUE( effect, effect_pass.Random1, (float) ( (double) Random( 0, 2000000000 ) / 2000000000.0 ) ); if( IS_EFFECT_VALUE( effect_pass.Random2 ) ) SET_EFFECT_VALUE( effect, effect_pass.Random2, (float) ( (double) Random( 0, 2000000000 ) / 2000000000.0 ) ); if( IS_EFFECT_VALUE( effect_pass.Random3 ) ) SET_EFFECT_VALUE( effect, effect_pass.Random3, (float) ( (double) Random( 0, 2000000000 ) / 2000000000.0 ) ); if( IS_EFFECT_VALUE( effect_pass.Random4 ) ) SET_EFFECT_VALUE( effect, effect_pass.Random4, (float) ( (double) Random( 0, 2000000000 ) / 2000000000.0 ) ); } if( effect_pass.IsTextures ) { for( int i = 0; i < EFFECT_TEXTURES; i++ ) { if( IS_EFFECT_VALUE( effect_pass.Textures[ i ] ) ) { GLuint id = ( textures && textures[ i ] ? textures[ i ]->Id : 0 ); GL( glActiveTexture( GL_TEXTURE2 + i ) ); GL( glBindTexture( GL_TEXTURE_2D, id ) ); GL( glActiveTexture( GL_TEXTURE0 ) ); GL( glUniform1i( effect_pass.Textures[ i ], 2 + i ) ); if( effect_pass.TexturesSize[ i ] != -1 && textures && textures[ i ] ) GL( glUniform4fv( effect_pass.TexturesSize[ i ], 1, textures[ i ]->SizeData ) ); if( effect_pass.TexturesAtlasOffset[ i ] != -1 && textures && textures[ i ] ) GL( glUniform4fv( effect_pass.TexturesAtlasOffset[ i ], 1, textures[ i ]->AtlasOffsetData ) ); } } } if( effect_pass.IsScriptValues ) { for( int i = 0; i < EFFECT_SCRIPT_VALUES; i++ ) if( IS_EFFECT_VALUE( effect_pass.ScriptValues[ i ] ) ) SET_EFFECT_VALUE( effect, effect_pass.ScriptValues[ i ], GameOpt.EffectValues[ i ] ); } if( effect_pass.IsAnimPos ) { if( IS_EFFECT_VALUE( effect_pass.AnimPosProc ) ) SET_EFFECT_VALUE( effect, effect_pass.AnimPosProc, anim_proc ); if( IS_EFFECT_VALUE( effect_pass.AnimPosTime ) ) SET_EFFECT_VALUE( effect, effect_pass.AnimPosTime, anim_time ); } if( effect_pass.IsChangeStates ) { if( effect_pass.BlendFuncParam1 ) GL( glBlendFunc( effect_pass.BlendFuncParam1, effect_pass.BlendFuncParam2 ) ); if( effect_pass.BlendEquation ) GL( glBlendEquation( effect_pass.BlendEquation ) ); } } // Finish processing else { if( effect_pass.IsChangeStates ) { if( effect_pass.BlendFuncParam1 ) GL( glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ); if( effect_pass.BlendEquation ) GL( glBlendEquation( GL_FUNC_ADD ) ); } } } uint Effect::MaxBones; Effect* Effect::Contour, * Effect::ContourDefault; Effect* Effect::Generic, * Effect::GenericDefault; Effect* Effect::Critter, * Effect::CritterDefault; Effect* Effect::Tile, * Effect::TileDefault; Effect* Effect::Roof, * Effect::RoofDefault; Effect* Effect::Rain, * Effect::RainDefault; Effect* Effect::Iface, * Effect::IfaceDefault; Effect* Effect::Primitive, * Effect::PrimitiveDefault; Effect* Effect::Light, * Effect::LightDefault; Effect* Effect::Fog, * Effect::FogDefault; Effect* Effect::FlushRenderTarget, * Effect::FlushRenderTargetDefault; Effect* Effect::FlushRenderTargetMS, * Effect::FlushRenderTargetMSDefault; Effect* Effect::FlushPrimitive, * Effect::FlushPrimitiveDefault; Effect* Effect::FlushMap, * Effect::FlushMapDefault; Effect* Effect::FlushLight, * Effect::FlushLightDefault; Effect* Effect::FlushFog, * Effect::FlushFogDefault; Effect* Effect::Font, * Effect::FontDefault; Effect* Effect::Skinned3d, * Effect::Skinned3dDefault; #define LOAD_EFFECT( effect_handle, effect_name, use_in_2d, defines ) \ effect_handle ## Default = LoadEffect( effect_name, use_in_2d, defines, "Effects/" ); \ if( effect_handle ## Default ) \ effect_handle = new Effect( *effect_handle ## Default ); \ else \ effect_errors++ bool GraphicLoader::LoadMinimalEffects() { uint effect_errors = 0; LOAD_EFFECT( Effect::Font, "Font_Default", true, "" ); LOAD_EFFECT( Effect::FlushRenderTarget, "Flush_RenderTarget", true, "" ); if( effect_errors > 0 ) { WriteLog( "Minimal effects not loaded.\n" ); return false; } return true; } bool GraphicLoader::LoadDefaultEffects() { // Default effects uint effect_errors = 0; #ifndef DISABLE_EGG LOAD_EFFECT( Effect::Generic, "2D_Default", true, "" ); LOAD_EFFECT( Effect::Critter, "2D_Default", true, "" ); LOAD_EFFECT( Effect::Roof, "2D_Default", true, "" ); #else LOAD_EFFECT( Effect::Generic, "2D_WithoutEgg", true, "" ); LOAD_EFFECT( Effect::Critter, "2D_WithoutEgg", true, "" ); LOAD_EFFECT( Effect::Roof, "2D_WithoutEgg", true, "" ); #endif LOAD_EFFECT( Effect::Rain, "2D_WithoutEgg", true, "" ); LOAD_EFFECT( Effect::Iface, "Interface_Default", true, "" ); LOAD_EFFECT( Effect::Primitive, "Primitive_Default", true, "" ); LOAD_EFFECT( Effect::Light, "Primitive_Light", true, "" ); LOAD_EFFECT( Effect::Fog, "Primitive_Fog", true, "" ); LOAD_EFFECT( Effect::Font, "Font_Default", true, "" ); LOAD_EFFECT( Effect::Tile, "2D_WithoutEgg", true, "" ); LOAD_EFFECT( Effect::FlushRenderTarget, "Flush_RenderTarget", true, "" ); LOAD_EFFECT( Effect::FlushPrimitive, "Flush_Primitive", true, "" ); LOAD_EFFECT( Effect::FlushMap, "Flush_Map", true, "" ); LOAD_EFFECT( Effect::FlushLight, "Flush_Light", true, "" ); LOAD_EFFECT( Effect::FlushFog, "Flush_Fog", true, "" ); if( effect_errors > 0 ) { WriteLog( "Default effects not loaded.\n" ); return false; } LOAD_EFFECT( Effect::Contour, "Contour_Default", true, "" ); return true; } bool GraphicLoader::Load3dEffects() { uint effect_errors = 0; LOAD_EFFECT( Effect::Skinned3d, "3D_Skinned", false, "" ); if( effect_errors > 0 ) { WriteLog( "3D effects not loaded.\n" ); return false; } return true; }
#pragma once #include "nginx.h" class NgxDatetime final { public: NgxDatetime() = default; ~NgxDatetime() = default; public: static std::time_t since() { return ngx_time(); } static ngx_str_t today() { ngx_tm_t tm; ngx_localtime(since(), &tm); static u_char buf[20] = {}; auto p = ngx_snprintf(buf, 20, "%d-%02d-%02d", tm.ngx_tm_year, tm.ngx_tm_mon, tm.ngx_tm_mday); return ngx_str_t{static_cast<std::size_t>(p - buf), buf}; } static ngx_str_t http(std::time_t t = since()) { static u_char buf[50] = {}; auto p = ngx_http_time(buf, t); return ngx_str_t(static_cast<std::size_t>(p - buf), buf); } static std::time_t http(ngx_str_t& str) { return ngx_http_parse_time(str.data, str.len); } };
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Graphics.DirectX.3.h" #include "internal/Windows.Storage.Streams.3.h" #include "internal/Windows.Perception.Spatial.3.h" #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Perception.Spatial.Surfaces.3.h" #include "Windows.Perception.Spatial.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceInfo> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceInfo> { HRESULT __stdcall get_Id(GUID * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Id()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_UpdateTime(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().UpdateTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_TryGetBounds(impl::abi_arg_in<Windows::Perception::Spatial::ISpatialCoordinateSystem> coordinateSystem, impl::abi_arg_out<Windows::Foundation::IReference<Windows::Perception::Spatial::SpatialBoundingOrientedBox>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TryGetBounds(*reinterpret_cast<const Windows::Perception::Spatial::SpatialCoordinateSystem *>(&coordinateSystem))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_TryComputeLatestMeshAsync(double maxTrianglesPerCubicMeter, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TryComputeLatestMeshAsync(maxTrianglesPerCubicMeter)); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_TryComputeLatestMeshWithOptionsAsync(double maxTrianglesPerCubicMeter, impl::abi_arg_in<Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptions> options, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TryComputeLatestMeshAsync(maxTrianglesPerCubicMeter, *reinterpret_cast<const Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions *>(&options))); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMesh> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMesh> { HRESULT __stdcall get_SurfaceInfo(impl::abi_arg_out<Windows::Perception::Spatial::Surfaces::ISpatialSurfaceInfo> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SurfaceInfo()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CoordinateSystem(impl::abi_arg_out<Windows::Perception::Spatial::ISpatialCoordinateSystem> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CoordinateSystem()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_TriangleIndices(impl::abi_arg_out<Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TriangleIndices()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VertexPositions(impl::abi_arg_out<Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().VertexPositions()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_VertexPositionScale(impl::abi_arg_out<Windows::Foundation::Numerics::float3> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().VertexPositionScale()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_VertexNormals(impl::abi_arg_out<Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().VertexNormals()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer> { HRESULT __stdcall get_Format(Windows::Graphics::DirectX::DirectXPixelFormat * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Format()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Stride(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Stride()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ElementCount(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ElementCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Data(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Data()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptions> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptions> { HRESULT __stdcall get_VertexPositionFormat(Windows::Graphics::DirectX::DirectXPixelFormat * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().VertexPositionFormat()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_VertexPositionFormat(Windows::Graphics::DirectX::DirectXPixelFormat value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().VertexPositionFormat(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_TriangleIndexFormat(Windows::Graphics::DirectX::DirectXPixelFormat * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TriangleIndexFormat()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_TriangleIndexFormat(Windows::Graphics::DirectX::DirectXPixelFormat value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().TriangleIndexFormat(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_VertexNormalFormat(Windows::Graphics::DirectX::DirectXPixelFormat * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().VertexNormalFormat()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_VertexNormalFormat(Windows::Graphics::DirectX::DirectXPixelFormat value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().VertexNormalFormat(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IncludeVertexNormals(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IncludeVertexNormals()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_IncludeVertexNormals(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().IncludeVertexNormals(value); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptionsStatics> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptionsStatics> { HRESULT __stdcall get_SupportedVertexPositionFormats(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SupportedVertexPositionFormats()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SupportedTriangleIndexFormats(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SupportedTriangleIndexFormats()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SupportedVertexNormalFormats(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SupportedVertexNormalFormats()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserver> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserver> { HRESULT __stdcall abi_GetObservedSurfaces(impl::abi_arg_out<Windows::Foundation::Collections::IMapView<GUID, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetObservedSurfaces()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_SetBoundingVolume(impl::abi_arg_in<Windows::Perception::Spatial::ISpatialBoundingVolume> bounds) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetBoundingVolume(*reinterpret_cast<const Windows::Perception::Spatial::SpatialBoundingVolume *>(&bounds)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetBoundingVolumes(impl::abi_arg_in<Windows::Foundation::Collections::IIterable<Windows::Perception::Spatial::SpatialBoundingVolume>> bounds) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetBoundingVolumes(*reinterpret_cast<const Windows::Foundation::Collections::IIterable<Windows::Perception::Spatial::SpatialBoundingVolume> *>(&bounds)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ObservedSurfacesChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver, Windows::Foundation::IInspectable>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().ObservedSurfacesChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver, Windows::Foundation::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ObservedSurfacesChanged(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ObservedSurfacesChanged(token); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics> { HRESULT __stdcall abi_RequestAccessAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus>> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().RequestAccessAsync()); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics2> : produce_base<D, Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics2> { HRESULT __stdcall abi_IsSupported(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IsSupported()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; } namespace Windows::Perception::Spatial::Surfaces { template <typename D> Windows::Graphics::DirectX::DirectXPixelFormat impl_ISpatialSurfaceMeshBuffer<D>::Format() const { Windows::Graphics::DirectX::DirectXPixelFormat value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshBuffer)->get_Format(&value)); return value; } template <typename D> uint32_t impl_ISpatialSurfaceMeshBuffer<D>::Stride() const { uint32_t value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshBuffer)->get_Stride(&value)); return value; } template <typename D> uint32_t impl_ISpatialSurfaceMeshBuffer<D>::ElementCount() const { uint32_t value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshBuffer)->get_ElementCount(&value)); return value; } template <typename D> Windows::Storage::Streams::IBuffer impl_ISpatialSurfaceMeshBuffer<D>::Data() const { Windows::Storage::Streams::IBuffer value; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshBuffer)->get_Data(put_abi(value))); return value; } template <typename D> Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo impl_ISpatialSurfaceMesh<D>::SurfaceInfo() const { Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo value { nullptr }; check_hresult(WINRT_SHIM(ISpatialSurfaceMesh)->get_SurfaceInfo(put_abi(value))); return value; } template <typename D> Windows::Perception::Spatial::SpatialCoordinateSystem impl_ISpatialSurfaceMesh<D>::CoordinateSystem() const { Windows::Perception::Spatial::SpatialCoordinateSystem value { nullptr }; check_hresult(WINRT_SHIM(ISpatialSurfaceMesh)->get_CoordinateSystem(put_abi(value))); return value; } template <typename D> Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer impl_ISpatialSurfaceMesh<D>::TriangleIndices() const { Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer value { nullptr }; check_hresult(WINRT_SHIM(ISpatialSurfaceMesh)->get_TriangleIndices(put_abi(value))); return value; } template <typename D> Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer impl_ISpatialSurfaceMesh<D>::VertexPositions() const { Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer value { nullptr }; check_hresult(WINRT_SHIM(ISpatialSurfaceMesh)->get_VertexPositions(put_abi(value))); return value; } template <typename D> Windows::Foundation::Numerics::float3 impl_ISpatialSurfaceMesh<D>::VertexPositionScale() const { Windows::Foundation::Numerics::float3 value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMesh)->get_VertexPositionScale(put_abi(value))); return value; } template <typename D> Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer impl_ISpatialSurfaceMesh<D>::VertexNormals() const { Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer value { nullptr }; check_hresult(WINRT_SHIM(ISpatialSurfaceMesh)->get_VertexNormals(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> impl_ISpatialSurfaceMeshOptionsStatics<D>::SupportedVertexPositionFormats() const { Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> value; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptionsStatics)->get_SupportedVertexPositionFormats(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> impl_ISpatialSurfaceMeshOptionsStatics<D>::SupportedTriangleIndexFormats() const { Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> value; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptionsStatics)->get_SupportedTriangleIndexFormats(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> impl_ISpatialSurfaceMeshOptionsStatics<D>::SupportedVertexNormalFormats() const { Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> value; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptionsStatics)->get_SupportedVertexNormalFormats(put_abi(value))); return value; } template <typename D> Windows::Graphics::DirectX::DirectXPixelFormat impl_ISpatialSurfaceMeshOptions<D>::VertexPositionFormat() const { Windows::Graphics::DirectX::DirectXPixelFormat value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->get_VertexPositionFormat(&value)); return value; } template <typename D> void impl_ISpatialSurfaceMeshOptions<D>::VertexPositionFormat(Windows::Graphics::DirectX::DirectXPixelFormat value) const { check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->put_VertexPositionFormat(value)); } template <typename D> Windows::Graphics::DirectX::DirectXPixelFormat impl_ISpatialSurfaceMeshOptions<D>::TriangleIndexFormat() const { Windows::Graphics::DirectX::DirectXPixelFormat value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->get_TriangleIndexFormat(&value)); return value; } template <typename D> void impl_ISpatialSurfaceMeshOptions<D>::TriangleIndexFormat(Windows::Graphics::DirectX::DirectXPixelFormat value) const { check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->put_TriangleIndexFormat(value)); } template <typename D> Windows::Graphics::DirectX::DirectXPixelFormat impl_ISpatialSurfaceMeshOptions<D>::VertexNormalFormat() const { Windows::Graphics::DirectX::DirectXPixelFormat value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->get_VertexNormalFormat(&value)); return value; } template <typename D> void impl_ISpatialSurfaceMeshOptions<D>::VertexNormalFormat(Windows::Graphics::DirectX::DirectXPixelFormat value) const { check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->put_VertexNormalFormat(value)); } template <typename D> bool impl_ISpatialSurfaceMeshOptions<D>::IncludeVertexNormals() const { bool value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->get_IncludeVertexNormals(&value)); return value; } template <typename D> void impl_ISpatialSurfaceMeshOptions<D>::IncludeVertexNormals(bool value) const { check_hresult(WINRT_SHIM(ISpatialSurfaceMeshOptions)->put_IncludeVertexNormals(value)); } template <typename D> GUID impl_ISpatialSurfaceInfo<D>::Id() const { GUID value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceInfo)->get_Id(&value)); return value; } template <typename D> Windows::Foundation::DateTime impl_ISpatialSurfaceInfo<D>::UpdateTime() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceInfo)->get_UpdateTime(put_abi(value))); return value; } template <typename D> Windows::Foundation::IReference<Windows::Perception::Spatial::SpatialBoundingOrientedBox> impl_ISpatialSurfaceInfo<D>::TryGetBounds(const Windows::Perception::Spatial::SpatialCoordinateSystem & coordinateSystem) const { Windows::Foundation::IReference<Windows::Perception::Spatial::SpatialBoundingOrientedBox> value; check_hresult(WINRT_SHIM(ISpatialSurfaceInfo)->abi_TryGetBounds(get_abi(coordinateSystem), put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh> impl_ISpatialSurfaceInfo<D>::TryComputeLatestMeshAsync(double maxTrianglesPerCubicMeter) const { Windows::Foundation::IAsyncOperation<Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh> value; check_hresult(WINRT_SHIM(ISpatialSurfaceInfo)->abi_TryComputeLatestMeshAsync(maxTrianglesPerCubicMeter, put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh> impl_ISpatialSurfaceInfo<D>::TryComputeLatestMeshAsync(double maxTrianglesPerCubicMeter, const Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions & options) const { Windows::Foundation::IAsyncOperation<Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh> value; check_hresult(WINRT_SHIM(ISpatialSurfaceInfo)->abi_TryComputeLatestMeshWithOptionsAsync(maxTrianglesPerCubicMeter, get_abi(options), put_abi(value))); return value; } template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> impl_ISpatialSurfaceObserverStatics<D>::RequestAccessAsync() const { Windows::Foundation::IAsyncOperation<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> result; check_hresult(WINRT_SHIM(ISpatialSurfaceObserverStatics)->abi_RequestAccessAsync(put_abi(result))); return result; } template <typename D> bool impl_ISpatialSurfaceObserverStatics2<D>::IsSupported() const { bool value {}; check_hresult(WINRT_SHIM(ISpatialSurfaceObserverStatics2)->abi_IsSupported(&value)); return value; } template <typename D> Windows::Foundation::Collections::IMapView<GUID, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo> impl_ISpatialSurfaceObserver<D>::GetObservedSurfaces() const { Windows::Foundation::Collections::IMapView<GUID, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo> value; check_hresult(WINRT_SHIM(ISpatialSurfaceObserver)->abi_GetObservedSurfaces(put_abi(value))); return value; } template <typename D> void impl_ISpatialSurfaceObserver<D>::SetBoundingVolume(const Windows::Perception::Spatial::SpatialBoundingVolume & bounds) const { check_hresult(WINRT_SHIM(ISpatialSurfaceObserver)->abi_SetBoundingVolume(get_abi(bounds))); } template <typename D> void impl_ISpatialSurfaceObserver<D>::SetBoundingVolumes(iterable<Windows::Perception::Spatial::SpatialBoundingVolume> bounds) const { check_hresult(WINRT_SHIM(ISpatialSurfaceObserver)->abi_SetBoundingVolumes(get_abi(bounds))); } template <typename D> event_token impl_ISpatialSurfaceObserver<D>::ObservedSurfacesChanged(const Windows::Foundation::TypedEventHandler<Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver, Windows::Foundation::IInspectable> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(ISpatialSurfaceObserver)->add_ObservedSurfacesChanged(get_abi(handler), &token)); return token; } template <typename D> event_revoker<ISpatialSurfaceObserver> impl_ISpatialSurfaceObserver<D>::ObservedSurfacesChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver, Windows::Foundation::IInspectable> & handler) const { return impl::make_event_revoker<D, ISpatialSurfaceObserver>(this, &ABI::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserver::remove_ObservedSurfacesChanged, ObservedSurfacesChanged(handler)); } template <typename D> void impl_ISpatialSurfaceObserver<D>::ObservedSurfacesChanged(event_token token) const { check_hresult(WINRT_SHIM(ISpatialSurfaceObserver)->remove_ObservedSurfacesChanged(token)); } inline SpatialSurfaceMeshOptions::SpatialSurfaceMeshOptions() : SpatialSurfaceMeshOptions(activate_instance<SpatialSurfaceMeshOptions>()) {} inline Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> SpatialSurfaceMeshOptions::SupportedVertexPositionFormats() { return get_activation_factory<SpatialSurfaceMeshOptions, ISpatialSurfaceMeshOptionsStatics>().SupportedVertexPositionFormats(); } inline Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> SpatialSurfaceMeshOptions::SupportedTriangleIndexFormats() { return get_activation_factory<SpatialSurfaceMeshOptions, ISpatialSurfaceMeshOptionsStatics>().SupportedTriangleIndexFormats(); } inline Windows::Foundation::Collections::IVectorView<winrt::Windows::Graphics::DirectX::DirectXPixelFormat> SpatialSurfaceMeshOptions::SupportedVertexNormalFormats() { return get_activation_factory<SpatialSurfaceMeshOptions, ISpatialSurfaceMeshOptionsStatics>().SupportedVertexNormalFormats(); } inline SpatialSurfaceObserver::SpatialSurfaceObserver() : SpatialSurfaceObserver(activate_instance<SpatialSurfaceObserver>()) {} inline Windows::Foundation::IAsyncOperation<winrt::Windows::Perception::Spatial::SpatialPerceptionAccessStatus> SpatialSurfaceObserver::RequestAccessAsync() { return get_activation_factory<SpatialSurfaceObserver, ISpatialSurfaceObserverStatics>().RequestAccessAsync(); } inline bool SpatialSurfaceObserver::IsSupported() { return get_activation_factory<SpatialSurfaceObserver, ISpatialSurfaceObserverStatics2>().IsSupported(); } } } template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceInfo> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMesh> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMesh & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshBuffer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptions> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptions & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptionsStatics> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceMeshOptionsStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserver> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserver & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics2> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::ISpatialSurfaceObserverStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshOptions & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver> { size_t operator()(const winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
/////////////////////////////////////////////////////////////////// //Copyright 2019-2020 Perekupenko Stanislav. All Rights Reserved.// //@Author Perekupenko Stanislav (stanislavperekupenko@gmail.com) // /////////////////////////////////////////////////////////////////// #pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" #include "CPPW_SpawnButtonArea.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE(FTouchDelegate); UCLASS() class SACPP_API UCPPW_SpawnButtonArea : public UUserWidget { GENERATED_BODY() public: virtual void NativeOnDragLeave(const FDragDropEvent& _inDragDropEvent, UDragDropOperation* _inOperation) override; virtual FReply NativeOnMouseButtonDown(const FGeometry& _inGeometry, const FPointerEvent& _inDragDropEvent) override; virtual void NativeOnDragDetected(const FGeometry& _inGeometry,const FPointerEvent& _inPointerEvent, UDragDropOperation*& _outOperation) override; UPROPERTY(BlueprintAssignable, Category = "EventDispatcher")FTouchDelegate OnTouchDelegate; };
#ifndef RENDERVIEWTEST_H #define RENDERVIEWTEST_H #include <QtTest/QTest> #include <QtCore/QObject> #include <QRegularExpression> #include "coverageobject.h" #include <Cutelyst/application.h> #include <Cutelyst/controller.h> #include <Cutelyst/View> #include <Cutelyst/Plugins/View/JSON/viewjson.h> using namespace Cutelyst; class TestViewJSON : public Controller { Q_OBJECT public: explicit TestViewJSON(QObject *parent) : Controller(parent) {} C_ATTR(test0, :Local) void test0(Context *c) { c->response()->setContentType(QStringLiteral("text/plain")); c->setStash(QStringLiteral("foo"), QByteArrayLiteral("bar")); c->setStash(QStringLiteral("bar"), QByteArrayLiteral("baz")); c->forward(c->view(QString())); } C_ATTR(test1, :Local) void test1(Context *c) { c->setStash(QStringLiteral("foo"), QByteArrayLiteral("bar")); c->setStash(QStringLiteral("bar"), QByteArrayLiteral("baz")); c->setStash(QStringLiteral("SingleKey"), QByteArrayLiteral("ok")); c->forward(c->view(QStringLiteral("view1"))); } C_ATTR(test2, :Local) void test2(Context *c) { c->setStash(QStringLiteral("foo"), QByteArrayLiteral("bar")); c->setStash(QStringLiteral("bar"), QByteArrayLiteral("baz")); c->setStash(QStringLiteral("SingleKey"), QByteArrayLiteral("ok")); c->setStash(QStringLiteral("One"), 1); c->setStash(QStringLiteral("Two"), 2); c->forward(c->view(QStringLiteral("view2"))); } C_ATTR(test3, :Local) void test3(Context *c) { c->setStash(QStringLiteral("foo"), QByteArrayLiteral("bar")); c->setStash(QStringLiteral("bar"), QByteArrayLiteral("baz")); c->setStash(QStringLiteral("SingleKey"), QByteArrayLiteral("ok")); c->setStash(QStringLiteral("One"), 1); c->setStash(QStringLiteral("Two"), 2); c->setStash(QStringLiteral("3"), 3); c->setStash(QStringLiteral("4"), 4); c->forward(c->view(QStringLiteral("view3"))); } C_ATTR(test4, :Local) void test4(Context *c) { c->setStash(QStringLiteral("1"), 1); c->forward(c->view(QStringLiteral("view4"))); } }; class TestActionRenderView : public CoverageObject { Q_OBJECT public: explicit TestActionRenderView(QObject *parent = nullptr) : CoverageObject(parent) {} private Q_SLOTS: void initTestCase(); void testController_data(); void testController() { doTest(); } void cleanupTestCase(); private: TestEngine *m_engine; TestEngine* getEngine(); void doTest(); }; void TestActionRenderView::initTestCase() { m_engine = getEngine(); QVERIFY(m_engine); } TestEngine* TestActionRenderView::getEngine() { auto app = new TestApplication; auto engine = new TestEngine(app, QVariantMap()); new TestViewJSON(app); new ViewJson(app); auto v1 = new ViewJson(app, QStringLiteral("view1")); v1->setExposeStash(QStringLiteral("SingleKey")); v1->setXJsonHeader(true); auto v2 = new ViewJson(app, QStringLiteral("view2")); v2->setExposeStash({ QStringLiteral("One"), QStringLiteral("Two") }); v2->setXJsonHeader(true); auto v3 = new ViewJson(app, QStringLiteral("view3")); v3->setExposeStash(QRegularExpression(QStringLiteral("\\d"))); auto v4 = new ViewJson(app, QStringLiteral("view4")); v4->setOutputFormat(ViewJson::Indented); if (!engine->init()) { return nullptr; } return engine; } void TestActionRenderView::cleanupTestCase() { delete m_engine; } void TestActionRenderView::doTest() { QFETCH(QString, method); QFETCH(QString, url); QFETCH(bool, sendXJsonVersion); QFETCH(int, statusCode); QFETCH(QByteArray, output); QFETCH(QString, contentType); QFETCH(bool, hasXJson); QUrl urlAux(url.mid(1)); Headers sendHeaders; if (sendXJsonVersion) { sendHeaders.pushRawHeader(QStringLiteral("X_PROTOTYPE_VERSION"), QStringLiteral("1.5.0")); } QVariantMap result = m_engine->createRequest(method, urlAux.path(), urlAux.query(QUrl::FullyEncoded).toLatin1(), sendHeaders, nullptr); QCOMPARE(result.value(QStringLiteral("statusCode")).toInt(), statusCode); QCOMPARE(result.value(QStringLiteral("body")).toByteArray(), output); Headers headers = result.value(QStringLiteral("headers")).value<Headers>(); QCOMPARE(headers.header(QStringLiteral("CONTENT_TYPE")), contentType); QCOMPARE(headers.contains(QStringLiteral("X_JSON")), hasXJson); } void TestActionRenderView::testController_data() { QTest::addColumn<QString>("method"); QTest::addColumn<QString>("url"); QTest::addColumn<bool>("sendXJsonVersion"); QTest::addColumn<int>("statusCode"); QTest::addColumn<QByteArray>("output"); QTest::addColumn<QString>("contentType"); QTest::addColumn<bool>("hasXJson"); QTest::newRow("viewjson-test-00") << QStringLiteral("GET") << QStringLiteral("/test/view/json/test0") << true << 200 << QByteArrayLiteral("{\"bar\":\"baz\",\"foo\":\"bar\"}") << QStringLiteral("application/json") << false; QTest::newRow("viewjson-test-01") << QStringLiteral("GET") << QStringLiteral("/test/view/json/test1") << true << 200 << QByteArrayLiteral("{\"SingleKey\":\"ok\"}") << QStringLiteral("application/json") << true; QTest::newRow("viewjson-test-02") << QStringLiteral("GET") << QStringLiteral("/test/view/json/test2") << false << 200 << QByteArrayLiteral("{\"One\":1,\"Two\":2}") << QStringLiteral("application/json") << false; QTest::newRow("viewjson-test-03") << QStringLiteral("GET") << QStringLiteral("/test/view/json/test3") << true << 200 << QByteArrayLiteral("{\"3\":3,\"4\":4}") << QStringLiteral("application/json") << false; QTest::newRow("viewjson-test-04") << QStringLiteral("GET") << QStringLiteral("/test/view/json/test4") << false << 200 << QByteArrayLiteral("{\n \"1\": 1\n}\n") << QStringLiteral("application/json") << false; } QTEST_MAIN(TestActionRenderView) #include "testviewjson.moc" #endif
#ifndef ROSE_MemoryMap_H #define ROSE_MemoryMap_H #include <boost/shared_ptr.hpp> /* Increase ADDR if necessary to make it a multiple of ALMNT */ #define ALIGN_UP(ADDR,ALMNT) ((((ADDR)+(ALMNT)-1)/(ALMNT))*(ALMNT)) /* Decrease ADDR if necessary to make it a multiple of ALMNT */ #define ALIGN_DN(ADDR,ALMNT) (((ADDR)/(ALMNT))*(ALMNT)) /** An efficient mapping from an address space to stored data. * * This class maps addresses in a 64-bit virtual address space to data stored in buffers. The address space is segmented into * non-overlapping, contiguous regions called "segments" (see MemoryMap::Segment) and the addresses in a segment are mapped * 1:1 onto data storage containers (see MemoryMap::Buffer). A MemoryMap stores pairs of address ranges and segments, and * each Segment points to a Buffer. * * Buffers come in a variety of kinds, all derived from MemoryMap::Buffer, and they are reference counted via Boost smart * pointers. Always refer to a buffer with the MemoryMap::BufferPtr type. They should be created with various create() class * methods, and they should never be explicitly freed. * * Here's an example of mapping a file into an address space at virtual address 0x08040000 and then temporarily replacing the * second 8k page of the file with our own data. We demonstrate using an MmapBuffer because these are very fast for large * files, especially if only small parts of the file are accessed. We could have also used * MemoryMap::ByteBuffer::create_from_file(), but this copies the entire file contents into a heap-allocated buffer, which is * slower. * * @code * // Create and initialize the overlay data * my_data_size = 8192; * uint8_t *my_data = new uint8_t[my_data_size]; * initialize(my_data, my_data_size); * * // Create the two buffers: one for the file, one for the overlay data * MemoryMap::BufferPtr file_buf = MemoryMap::MmapBuffer("the_file", O_RDONLY, PROT_READ, MAP_PRIVATE); * MemoryMap::BufferPtr data_buf = MemoryMap::ByteBuffer(my_data, my_data_size); * my_data = NULL; // it is now owned by data_buf and will be deleted automatically * * // Create the memory map. * MemoryMap map; * map.insert(Extent(0x08040000, file_buf->size()), * MemoryMap::Segment(file_buf, 0, MemoryMap::MM_PROT_READ, "the file contents")); * map.insert(Extent(0x08042000, data_buf->size()), * MemoryMap::Segment(data_buf, 0, MemoryMap::MM_PROT_RW, "data overlay")); * @endcode * * A MemoryMap provides methods to easily read from and write to the underlying data storage, addressing it in terms of the * virtual address space. These functions return the number of bytes copied. * * @code * // read part of the data, right across the file/overlay boundary * uint8_t data[4096]; * size_t nread = map.read(data, 0x0804ff00, sizeof data); * assert(nread==sizeof data); * @endcode * * A MemoryMap is built on top of a RangeMap<Extent,Segment> and the map is available with via the segments() method. * Therefore, all the usual RangeMap operations are available. For instance, here's one way to determine if there's a large * free area at 0xc0000000: * * @code * // The set of addresses that are unmapped * ExtentMap free_areas = map.segments().invert<ExtentMap>(); * bool b = free_areas.contains(Extent(0xc0000000,0x20000000)); * @endcode */ class MemoryMap { public: /** Mapping permissions. */ enum Protection { /* Protection bits */ MM_PROT_BITS = 0x00000007, /**< Bits used to indication memory region protections. */ /*NO_STRINGIFY*/ MM_PROT_READ = 0x00000001, /**< Pages can be read. */ MM_PROT_WRITE = 0x00000002, /**< Pages can be written. */ MM_PROT_EXEC = 0x00000004, /**< Pages can be executed. */ /* Protection convenience stuff */ MM_PROT_NONE = 0x00000000, /**< Pages cannot be accessed. */ MM_PROT_ANY = 0x00000007, /**< Any access. */ MM_PROT_RW = (MM_PROT_READ|MM_PROT_WRITE), /**< Read or write. */ /*NO_STRINGIFY*/ MM_PROT_RX = (MM_PROT_READ|MM_PROT_EXEC), /**< Read or execute. */ /*NO_STRINGIFY*/ MM_PROT_RWX = (MM_PROT_ANY), /*NO_STRINGIFY*/ /* Other flags. These generally aren't interpreted by MemoryMap, but can be used to pass info. When merging memory * segments, MemoryMap::Segment::merge() will not treat two regions as being consistent if they have different * bits set. */ MM_PROT_FLAGS = 0xfffffff0, /**< Mask of protection bits that are available for use by other layers. */ MM_PROT_PRIVATE = 0x00000010, /**< Pages are not shared between mapped regions. */ }; /** Map copying. */ enum CopyLevel { COPY_SHALLOW, /**< Copy segments, but not the buffers to which they point. */ COPY_DEEP, /**< Copy segments and their buffers. This copies buffer data. */ COPY_ON_WRITE /**< Copy segments and mark them so they copy buffers on write. */ }; /************************************************************************************************************************** * Buffers **************************************************************************************************************************/ public: class Buffer; typedef boost::shared_ptr<Buffer> BufferPtr; /** Base class for data associated with a memory segment. Memory map buffers are reference counted and managed by * boost::shared_ptr. Use the class' create methods to allocate new Buffer objects. A Buffer object usually (but not * necessarily) points to an array of bytes, and it is up to the Buffer subclass as to how to manage that array. The * Buffer desctructor is only called when its reference count reaches zero. */ class Buffer { public: virtual ~Buffer() {} /** Create a new buffer from an existing buffer. The new buffer will point to a different copy of the data so that * writing data into one buffer will not cause it to appear when reading from the other buffer. The type of the new * buffer might not be the same as this buffer because not all buffers are able to copy their data. For instance, * cloning an ExternBuffer or a MmapBuffer will create a ByteBuffer. */ virtual BufferPtr clone() const = 0; /** Property indicating whether buffer is read-only. The "modifiability" of a buffer is orthogonal to whether segments * pointing to this buffer have the MemoryMap::MM_PROT_WRITE bit set. For instance, the storage for the buffer can be * a const buffer (is_read_only() returning true) even though a MemoryMap::Segment could be marked as writable. * @{ */ virtual bool is_read_only() const { return read_only; } virtual void set_read_only(bool b=true) { read_only = b; } void clear_read_only() { set_read_only(false); } // final /** @} */ /** Debug name for buffer. Rather than print buffer pointers to distinguish one buffer from another, we use a three * character name composed of the 26 lower-case letters. The user can set this name to something else if they like. * @{ */ virtual std::string get_name() const { return name; } virtual void set_name(const std::string &s) { name = s; } /** @} */ /** Size of buffer in bytes. * @{ */ virtual size_t size() const { return p_size; } virtual void resize(size_t n) { p_size = n; } /** @} */ /** Reads data from a buffer. Reads up to @p nbytes of data from this buffer and copies it to the caller-supplied * address, the @p buf argument. Reading starts at the specified byte offset from the beginning of this buffer. * Returns the number of bytes copied. The output buffer is not zero-padded for short reads. * * If @p buf is the null pointer, then no data is copied and the return value is the number of bytes that would have * been copied if @p buf had not been null. */ virtual size_t read(void *buf, size_t offset, size_t nbytes) const = 0; /** Writes data into a buffer. Writes up to @p nbytes of data from @p buf into this buffer starting at the specified * byte offset within this buffer. Returns the number of bytes written. The return value will be less than @p nbytes * if an error occurs. */ virtual size_t write(const void *buf, size_t offset, size_t nbytes) = 0; /** Saves data to a file. Writes the entire buffer contents to the specified file, creating or truncating the file if * necessary. */ virtual void save(const std::string &filename) const; /** Return pointer to low-level data. This probably shouldn't be used to access the data because it makes assumptions * about the implementation (use read() and write() methods instead). But it is sometimes useful when trying to * determine if a buffer was initialized with data known to the caller. */ virtual const void* get_data_ptr() const = 0; /** Returns true if the buffer's data is all zero. Some subclasses will be able to do something more efficient than * reading all the data. */ virtual bool is_zero() const; protected: Buffer(size_t size): read_only(false), p_size(size) { name=new_name(); } std::string new_name() /*final*/; bool read_only; /**< If true, buffer data cannot be modified. */ std::string name; /**< Name for debugging. */ size_t p_size; /**< Size of buffer in bytes. */ }; /** Buffer that has no data. This can be useful to reserve areas of the virtual memory address space without actually * storing any data at them. All reads and writes using such a buffer will fail (return zero). */ class NullBuffer: public Buffer { public: /** Construct a new buffer. The buffer contains no data and all reads and writes will fail by returning zero. */ static BufferPtr create(size_t size); /** Always returns the null pointer. */ virtual const void *get_data_ptr() const /*overrides*/ { return NULL; } virtual BufferPtr clone() const { return create(size()); } virtual size_t read(void*, size_t offset, size_t nbytes) const /*overrides*/ { return 0; } virtual size_t write(const void*, size_t offset, size_t nbytes) /*overrides*/ { return 0; } protected: NullBuffer(size_t size): Buffer(size) {} }; /** Buffer of data owned by someone else. The data is not deleted when the buffer is deleted. This class is mostly for * backward compatibility with older versions of ROSE where memory maps never owned the data to which they pointed. */ class ExternBuffer: public Buffer { public: /** Construct from caller-supplied data. The caller supplies a pointer to data and the size of that data. The new * buffer object does not take ownership of the data or copy it, thus the caller-supplied data must continue to exist * for as long as the Buffer exists. This is mostly for backward compatibility with older versions of ROSE. * @{ */ static BufferPtr create(void *data, size_t size); static BufferPtr create(const void *data, size_t size); /** @} */ virtual BufferPtr clone() const; virtual void resize(size_t n) /*overrides*/; virtual const void *get_data_ptr() const /*overrides*/ { return p_data; } virtual size_t read(void*, size_t offset, size_t nbytes) const /*overrides*/; virtual size_t write(const void*, size_t offset, size_t nbytes) /*overrides*/; protected: ExternBuffer(const uint8_t *data, size_t size) : Buffer(size), p_data(const_cast<uint8_t*>(data)) { set_read_only(); } ExternBuffer(uint8_t *data, size_t size) : Buffer(size), p_data(data) {} mutable uint8_t *p_data; }; /** Buffer of bytes. The bytes are deleted when the buffer is deleted. */ class ByteBuffer: public ExternBuffer { public: virtual ~ByteBuffer() { delete[] p_data; } /** Construct from caller-supplied data. The caller supplies a pointer to data allocated on the heap (with new) and * the size of that data. The new buffer object takes ownership of the data, which is deleted when the buffer object * is destroyed. */ static BufferPtr create(void *data, size_t size); /** Construct from a file. The new buffer is created by reading all data from the specified file beginning at byte * offset @p start_offset. */ static BufferPtr create_from_file(const std::string &filename, size_t start_offset=0); protected: ByteBuffer(uint8_t *data, size_t size): ExternBuffer(data, size) {} }; /** Buffer whose underlying storage is from mmap. */ class MmapBuffer: public ExternBuffer { public: virtual ~MmapBuffer(); /** Construct a new buffer from part of a file. The file is mapped into memory via mmap and unmapped when the last * reference to the buffer is deleted. The arguments are the same as for mmap. A MemoryMap::Exception is thrown if * the file cannot be mapped. The file is not closed after mapping. */ static BufferPtr create(size_t length, int prot, int flags, int fd, off_t offset); /** Construct a new buffer from part of a file. The file is opened with the flags @p oflags and then mapped into * memory by calling mmap with the @p mprot and @p mflags arguments. The entire file is mapped. A * MemoryMap::Exception is thrown if the file cannot be opened or the memory cannot be mapped. The file is closed * immediately after mapping. */ static BufferPtr create(const std::string &filename, int oflags, int mprot, int mflags); /** Mmap buffers cannot be resized. This method will abort if called. */ virtual void resize(size_t n) /*overrides*/; protected: MmapBuffer(uint8_t *data, size_t size, bool read_only): ExternBuffer(data, size) { set_read_only(read_only); } }; /** Buffer of bytes. The bytes are initialized to all zero and storage is allocated only when a non-zero value is written * to the buffer. */ class AnonymousBuffer: public ExternBuffer { public: virtual ~AnonymousBuffer() { delete[] p_data; } /** Construct an anonymous buffer. Storage for the buffer is allocated when a non-zero value is written to the buffer. * Reads from unallocated buffers return all zero bytes. */ static BufferPtr create(size_t size); virtual BufferPtr clone() const /*overrides*/; virtual const void *get_data_ptr() const /*overrides*/; virtual size_t read(void*, size_t offset, size_t nbytes) const /*overrides*/; virtual size_t write(const void*, size_t offset, size_t nbytes) /*overrides*/; virtual bool is_zero() const /*overrides*/; protected: AnonymousBuffer(size_t size): ExternBuffer((uint8_t*)NULL, size) {} }; /************************************************************************************************************************** * Segments **************************************************************************************************************************/ public: /** A contiguous, homogeneous region of an address space. A Segment is a contiguous region of the address space that does * not overlap with any other segment of the address space, and which corresponds with (part of) a single MemoryMap::Buffer * object. The addresses described by a Segment all have the same set of properties, such as the permission properties. * * A segment doesn't know to which part of the virtual memory address space it's mapped--that's the responsibility of the * MemoryMap class and the RangeMap on which it's implemented. * * Segments reference count the MemoryMap::Buffer objects to which they point. */ class Segment { public: Segment(): buffer_offset(0), mapperms(0), copy_on_write(false) {} /** Constructor. Constructs a segment that points to a particular offset in a buffer. The segment also has certain * access permissions. */ Segment(const BufferPtr &buffer, rose_addr_t offset, unsigned perms, std::string name="") : buffer(buffer), buffer_offset(offset), mapperms(perms), name(name), copy_on_write(false) {} /** Underlying buffer. Every segment must point to some underlying buffer that contains the data for the segment. The * addresses in the segment correspond 1:1 with the bytes in the buffer, although the segment's addresses can be * shifted a constant offset within the buffer. All addresses defined by the segment must correspond to valid data * elements within the buffer. Buffers are reference counted using boost::shared_ptr, so the caller should never free * the buffer. * @{ */ BufferPtr get_buffer() const { return buffer; } void set_buffer(const BufferPtr &b) { buffer = b; } /** @} */ /** Check segment-buffer compatibility. The segment is verified to point to a Buffer object and that the addresses * specified in the given @p range map to valid data in the buffer. Returns true if everything checks out, false * otherwise. * * This method is necessary because a Segment doesn't actually know its range of addresses. The association between * address ranges and segments is managed by the MemoryMap object and the RangeMap on which it's based. * * If the @p first_bad_va pointer is non-null, then it will be initialized with the lowest address in @p range which * is invalid. The initialization only occurs when check() returns false. */ bool check(const Extent &range, rose_addr_t *first_bad_va=NULL) const; /** Mapping permissions. The mapping permissions are a bit vector of MemoryMap::Protection bits. These bits describe * what operations can be performed on a segment's address space. The set of operations can be further restricted by * the underlying Buffer object. * @{ */ unsigned get_mapperms() const { return mapperms; } void set_mapperms(unsigned p) { mapperms = p; } /** @} */ /** Offset with respect to underlying Buffer. The addresses of a segment correspond 1:1 with the bytes of the * underlying Buffer object, but they can be shifted by a constant amount. The shift amount is measured as a byte * offset from the beginning of the buffer. * * When setting an offset, the new offset must be compatible with the underlying buffer. In other words, the * addresses represented by the Segment must all continue to map to valid data locations in the buffer. The actual * consistency check is delayed until an operation like read() or write() because we don't have all the necessary * information at the time of the set_buffer_offset() call. * * The two-argument version of get_buffer_offset() computes the buffer offset for a virtual address that must be * within the range of virtual addresses represented by this segment. * @{ */ rose_addr_t get_buffer_offset() const { return buffer_offset; } rose_addr_t get_buffer_offset(const Extent &my_range, rose_addr_t va) const; void set_buffer_offset(rose_addr_t n); /** @} */ /** Copy on write property. If the copy-on-write property is set then the next write operation on this segment will * cause its buffer to be copied first. Once the buffer is copied the copy-on-write property is cleared. Doing a deep * copy of a memory map will also clear the copy-on-write property in the new segments. * @{ */ bool is_cow() const { return copy_on_write; } void set_cow(bool b=true) { copy_on_write = b; } void clear_cow() { set_cow(false); } /** @} */ /** Segment equality. Segments are equal if they point to the same buffer, have the same buffer offset, and have the * same permissions. Segment names are not used in the equality test. */ bool operator==(const Segment &other) const; /** Name for debugging. * @{ */ const std::string &get_name() const { return name; } void set_name(const std::string &s) { name = s; } /** @} */ friend std::ostream& operator<<(std::ostream&, const Segment&); private: // Stuff for manipulating segment debug names typedef std::map<std::string, std::set<std::string> > NamePairings; void merge_names(const Segment &other); std::string get_name_pairings(NamePairings*) const; void set_name(const NamePairings&, const std::string &s1, const std::string &s2); // The following methods are part of the RangeMap interface. See documentation in RangeMap::RangeMapVoid. friend class RangeMap<Extent, Segment>; void removing(const Extent &range); void truncate(const Extent &range, rose_addr_t new_end); bool merge(const Extent &range, const Extent &other_range, const Segment &other_segment); Segment split(const Extent &range, rose_addr_t new_end); void print(std::ostream&) const; private: BufferPtr buffer; /**< The buffer holding data for this segment. */ rose_addr_t buffer_offset; /**< Starting byte offset into the buffer. */ unsigned mapperms; /**< Permissions for this segment. */ std::string name; /**< Name used for debugging purposes. */ bool copy_on_write; /**< Does the buffer need to be copied on the next write operation? */ }; /************************************************************************************************************************** * RangeMap-related things **************************************************************************************************************************/ public: typedef RangeMap<Extent, Segment> Segments; typedef Segments::iterator iterator; typedef Segments::const_iterator const_iterator; typedef Segments::reverse_iterator reverse_iterator; typedef Segments::const_reverse_iterator const_reverse_iterator; /************************************************************************************************************************** * Visitors **************************************************************************************************************************/ public: /** Visitor for traversing a memory map. The return value is used when the visitor is employed by the prune() method. */ class Visitor { public: virtual ~Visitor() {} virtual bool operator()(const MemoryMap*, const Extent&, const Segment&) = 0; }; /************************************************************************************************************************** * Exceptions **************************************************************************************************************************/ public: /** Exception for MemoryMap operations. */ class Exception { public: Exception(const std::string &mesg, const MemoryMap *map): mesg(mesg), map(map) {} virtual ~Exception() {} virtual std::string leader(std::string dflt="memory map problem") const; /**< Leading part of the error message. */ virtual std::string details(bool) const; /**< Details emitted on following lines, indented two spaces. */ virtual void print(std::ostream&, bool verbose=true) const; friend std::ostream& operator<<(std::ostream&, const Exception&); public: std::string mesg; /**< Error message. Details of the exception. */ const MemoryMap *map; /**< Map that caused the exception if available, null otherwise. */ }; /** Exception for an inconsistent mapping. This exception occurs when an attemt is made to insert a new segment but the * address range of the new segment is alread defined by an existing segment. The @p new_range and @p new_segment are * information about the segment that was being inserted, and the @p old_range and @p old_segment is information about * an existing segment that conflicts with the new one. */ struct Inconsistent : public Exception { Inconsistent(const std::string &mesg, const MemoryMap *map, const Extent &new_range, const Segment &new_segment, const Extent &old_range, const Segment &old_segment) : Exception(mesg, map), new_range(new_range), old_range(old_range), new_segment(new_segment), old_segment(old_segment) {} virtual void print(std::ostream&, bool verbose=true) const; friend std::ostream& operator<<(std::ostream&, const Inconsistent&); Extent new_range, old_range; Segment new_segment, old_segment; }; /** Exception for when we try to access a virtual address that isn't mapped. */ struct NotMapped : public Exception { NotMapped(const std::string &mesg, const MemoryMap *map, rose_addr_t va) : Exception(mesg, map), va(va) {} virtual void print(std::ostream&, bool verbose=true) const; friend std::ostream& operator<<(std::ostream&, const NotMapped&); rose_addr_t va; }; /** Exception thrown by find_free() when there's not enough free space left. */ struct NoFreeSpace : public Exception { NoFreeSpace(const std::string &mesg, const MemoryMap *map, size_t size) : Exception(mesg, map), size(size) {} virtual void print(std::ostream&, bool verbose=true) const; friend std::ostream& operator<<(std::ostream&, const NoFreeSpace&); size_t size; }; /** Exception thrown by load() when there's a syntax error in the index file. */ struct SyntaxError: public Exception { SyntaxError(const std::string &mesg, const MemoryMap *map, const std::string &filename, unsigned linenum, int colnum=-1) : Exception(mesg, map), filename(filename), linenum(linenum), colnum(colnum) {} virtual void print(std::ostream&, bool verbose=true) const; friend std::ostream& operator<<(std::ostream&, const SyntaxError&); std::string filename; /**< Name of index file where error occurred. */ unsigned linenum; /**< Line number (1 origin) where error occurred. */ int colnum; /**< Optional column number (0-origin; negative if unknown). */ }; /************************************************************************************************************************** * Public Methods for MemoryMap **************************************************************************************************************************/ /** Constructs an empty memory map. */ MemoryMap() {} /** Shallow copy constructor. The new memory map describes the same mapping and points to shared copies of the underlying * data. In other words, changing the mapping of one map (clear(), insert(), erase()) does not change the mapping of the * other, but changing the data (write()) in one map changes it in the other. See also init(), which takes an argument * describing how to copy. */ MemoryMap(const MemoryMap &other, CopyLevel copy_level=COPY_SHALLOW) { init(other, copy_level); } /** Initialize this memory map with info from another. This map is first cleared and then initialized with a copy of the * @p source map. A reference to this map is returned for convenience since init is often used in conjunction with * constructors. */ MemoryMap& init(const MemoryMap &source, CopyLevel copy_level=COPY_SHALLOW); /** Clear the entire memory map by erasing all addresses that are defined. */ void clear(); /** Define a new area of memory. The @p segment is copied into the memory map and the reference count for the Buffer to * which it points (if any) is incremented. A check is performed to ensure that the @p range and @p segment are * compatible (that the size of the range is not greater than the size of the segment's underlying buffer). This * operation is somewhat like the POSIX mmap() function. * * If the @p range overlaps with existing segments and @p erase_prior is set (the default), then the overlapping parts of * the virtual address space are first removed from the mapping. Otherwise an overlap throws a MemoryMap::Inconsistent * exception. If an exception is thrown, then the memory map is not changed. */ void insert(const Extent &range, const Segment &segment, bool erase_prior=true); /** Determines whether a virtual address is defined. Returns true if the specified virtual address (or all addresses in a * range of addresses) are defined, false otherwise. An address is defined if it is associated with a Segment. If @p * required_perms is non-zero, then the address (or all addresses in the range) must be mapped with at least those * permission bits. * @{ */ bool exists(rose_addr_t va, unsigned required_perms=0) const { return exists(Extent(va), required_perms); } bool exists(Extent range, unsigned required_perms=0) const; /** @} */ /** Erase parts of the mapping that correspond to the specified virtual address range. The addresses to be erased don't * necessarily need to correspond to a similar add() call; for instance, it's possible to add a large address space and * then erase parts of it to make holes. This operation is somewhat like the POSIX munmap() function. * * It is not an error to erase parts of the virtual address space that are not defined. Note that it is more efficient to * call clear() than to erase the entire virtual address space. */ void erase(const Extent &range); /** Erase a single extent from a memory map. Erasing by range is more efficient (O(ln N) vs O(N)) but sometimes it's more * convenient to erase a single segment when we don't know it's range. */ void erase(const Segment&); /** Get information about an address. The return value is a pair containing the range of virtual addresses in the * segment and a copy of the Segment object. If the value is not found, then a RangeMap::NotMapped exception is thrown. * See also, exists(). */ std::pair<Extent, Segment> at(rose_addr_t va) const; /** Search for free space in the mapping. This is done by looking for the lowest possible address not less than @p * start_va and with the specified alignment where there are at least @p size free bytes. Throws a MemoryMap::NoFreeSpace * exception if the search fails to find free space. */ rose_addr_t find_free(rose_addr_t start_va, size_t size, rose_addr_t mem_alignment=1) const; /** Finds the highest area of unmapped addresses. The return value is the starting address of the highest contiguous * region of unmapped address space that starts at or below the specified maximum. If no unmapped region exists then a * MemoryMap::NoFreeSpace exception is thrown. */ rose_addr_t find_last_free(rose_addr_t max=(rose_addr_t)(-1)) const; /** Traverses the segments of a map. The visitor is called for each segment. The visitor's return value is ignored. */ void traverse(Visitor &visitor) const; /** Removes segments for which @p predicate returns true. If the predicate always returns false then nothing is removed * from the map, and the predicate can be used for its side effect (such as counting how many map segments satisfy certain * criteria. */ void prune(Visitor &predicate); /** Removes segments based on permissions. Keeps segments that have any of the required bits and none of the * prohibited bits. No bits are required if @p required is zero. */ void prune(unsigned required, unsigned prohibited=MM_PROT_NONE); /** List of map segments. */ const Segments &segments() const { return p_segments; } /** Copies data from a contiguous region of the virtual address space into a user supplied buffer. The portion of the * virtual address space to copy begins at @p start_va and continues for @p desired bytes. The data is copied into the * beginning of the @p dst_buf buffer. The return value is the number of bytes that were copied, which might be fewer * than the number of bytes desired if the mapping does not include part of the address space requested or part of the * address space does not have MM_PROT_READ permission (or the specified permissions). The @p dst_buf bytes that do not * correpond to mapped virtual addresses will be zero filled so that @p desired bytes are always initialized. * * If @p dst_buf is the null pointer then this method only measures how many bytes could have been read. * * The read() and read1() methods behave identically except read1() restricts the readable area to be from a single * segment. Thus, read1() may return fewer bytes than read(). * * @{ */ size_t read(void *dst_buf, rose_addr_t start_va, size_t desired, unsigned req_perms=MM_PROT_READ) const; size_t read1(void *dst_buf, rose_addr_t start_va, size_t desired, unsigned req_perms=MM_PROT_READ) const; /** @} */ /** Reads data from a memory map. Reads data beginning at the @p start_va virtual address in the memory map and continuing * for up to @p desired bytes, returning the result as an SgUnsignedCharList. The read may be shorter than requested if * we reach a point in the memory map that is not defined or which does not have the requested permissions. The size of * the return value indicates that number of bytes that were read (i.e., the return value is not zero-filled). */ SgUnsignedCharList read(rose_addr_t start_va, size_t desired, unsigned req_perms=MM_PROT_READ) const; /** Copies data from a supplied buffer into the specified virtual addresses. If part of the destination address space is * not mapped, then all bytes up to that location are copied and no additional bytes are copied. The write is also * aborted early if a segment lacks the MM_PROT_WRITE bit (or specified bits) or its buffer is marked as read-only. The * return value is the number of bytes copied. * * If @p src_buf is the null pointer then this method only measures how many bytes could have been written. * * The write() and write1() methods behave identically, except write1() restricts the operation to a single segment. Thus, * write1() may write fewer bytes than write(). * * @{ */ size_t write(const void *src_buf, rose_addr_t start_va, size_t desired, unsigned req_perms=MM_PROT_WRITE); size_t write1(const void *src_buf, rose_addr_t start_va, size_t desired, unsigned req_perms=MM_PROT_WRITE); /** @} */ /** Returns just the virtual address extents for a memory map. */ ExtentMap va_extents() const; /** Sets protection bits for the specified address range. The entire address range must already be mapped, but if @p * relax is set then no exception is thrown if part of the range is not mapped (that part is just ignored). This * operation is somewhat like the POSIX mprotect() function. */ void mprotect(Extent range, unsigned perms, bool relax=false); /** Prints the contents of the map for debugging. The @p prefix string is added to the beginning of every line of output * and typically is used to indent the output. * @{ */ void dump(FILE*, const char *prefix="") const; void dump(std::ostream&, std::string prefix="") const; void print(std::ostream &o, std::string prefix="") const { dump(o, prefix); } /** @} */ /** Dumps the entire map and its contents into a set of files. The file names are constructed from the @p basename by * appending a hypen and a hexadecimal address (without the leading "0x") and the extension ".data". The text file whose * name is constructed by appending ".index" to the @p basename contains an index of the memory map. */ void dump(const std::string &basename) const; /** Read a memory map from a set of memory dump files. The argument should be the same basename that was given to an * invocation of the dump() method. The memory map is adjusted according to the contents of the index file. Returns true * if the data was successfully read in its entirety; note that when returning false, this memory map object might be * partially changed (although still in a consistent state). * * This method also understands a more user-friendly dump index format. Each line of the index is either blank (containing * only white space), a comment (introduced with a '#') or a segment specification. A segment specification contains the * following fields separated by white space (and/or a comma): * * <ul> * <li>The virtual address for the start of this memory area.</li> * <li>The size of this memory area in bytes.</li> * <li>Mapping permissions consisting of the letters "r" (read), "w" (write), "x" (execute), or "p" (private). * Hyphens also be present in this field and do not affect the permissions.</li> * <li>The source of the data. This field consists of everything up to the next "0x" string (but leading and trailing * white space is stripped). It may be the name of a file or the name of a buffer. Buffer names are only used for * debugging.</li> * <li>The byte offset of the start of data within the file. It allows a single file to contain multiple memory areas.</li> * <li>An optional comment which will appear as the map element name for debugging.</li> * </ul> * * If an error occurs an exception is thrown. */ bool load(const std::string &basename); friend std::ostream& operator<<(std::ostream&, const MemoryMap&); /************************************************************************************************************************** * Data members **************************************************************************************************************************/ protected: Segments p_segments; }; #endif
#include "app/ServerApp.hpp" #include <utils/Config.hpp> #include <logger/Logger.hpp> namespace app { ServerApp::ServerApp() : m_configPath{ "AppConfig.json" } { utils::AppConfig::Instance().ReadConfig(m_configPath); InitLogger(); lg::LOG(lg::Severity::info) << "Server configuration: " << "\n\t Host: " << utils::AppConfig::Instance().server.host << "\n\t Port: " << utils::AppConfig::Instance().server.port << "\n\tThreads: " << utils::AppConfig::Instance().server.threads; } void ServerApp::InitLogger() { uint8_t severities{ 0 }; if (utils::AppConfig::Instance().logger.enableDebug) { severities |= lg::Severity::debug; } if (utils::AppConfig::Instance().logger.enableError) { severities |= lg::Severity::error; } if (utils::AppConfig::Instance().logger.enableInfo) { severities |= lg::Severity::info; } if (utils::AppConfig::Instance().logger.enableWarning) { severities |= lg::Severity::warning; } lg::Logger::Instance().setLoggedSeverities(severities); const auto path = utils::AppConfig::Instance().logger.logFilePath; if (!path.empty()) { lg::Logger::Instance().setGlobalLogFile(path); } } int ServerApp::Run() { return bs::Server{ utils::AppConfig::Instance().server.host, utils::AppConfig::Instance().server.port, utils::AppConfig::Instance().server.threads }.Run(); } } // namespace app