hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
874995fe98ffeae177797375b13cf239a4796968
3,339
cpp
C++
src/agent/Shared/Fundamentals/Utils.cpp
m5o/passenger
9640816af708867d0994bd2eddb80ac24399f855
[ "MIT" ]
2,728
2015-01-01T10:06:45.000Z
2022-03-30T18:12:58.000Z
src/agent/Shared/Fundamentals/Utils.cpp
philson-philip/passenger
144a6f39722987921c7fce0be9d64befb125a88b
[ "MIT" ]
1,192
2015-01-01T06:03:19.000Z
2022-03-31T09:14:36.000Z
src/agent/Shared/Fundamentals/Utils.cpp
philson-philip/passenger
144a6f39722987921c7fce0be9d64befb125a88b
[ "MIT" ]
334
2015-01-08T20:47:03.000Z
2022-02-18T07:07:01.000Z
/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2010-2017 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <Shared/Fundamentals/Utils.h> #include <oxt/backtrace.hpp> #include <cstdlib> #include <cstring> #include <signal.h> #include <fcntl.h> #include <unistd.h> namespace Passenger { namespace Agent { namespace Fundamentals { using namespace std; const char * getEnvString(const char *name, const char *defaultValue) { const char *value = getenv(name); if (value != NULL && *value != '\0') { return value; } else { return defaultValue; } } bool getEnvBool(const char *name, bool defaultValue) { const char *value = getEnvString(name); if (value != NULL) { return strcmp(value, "yes") == 0 || strcmp(value, "y") == 0 || strcmp(value, "1") == 0 || strcmp(value, "on") == 0 || strcmp(value, "true") == 0; } else { return defaultValue; } } void ignoreSigpipe() { struct sigaction action; action.sa_handler = SIG_IGN; action.sa_flags = 0; sigemptyset(&action.sa_mask); sigaction(SIGPIPE, &action, NULL); } /** * Linux-only way to change OOM killer configuration for * current process. Requires root privileges, which we * should have. * * Returns 0 on success, or an errno code on error. * * This function is async signal-safe. */ int tryRestoreOomScore(const StaticString &scoreString, bool &isLegacy) { TRACE_POINT(); if (scoreString.empty()) { return 0; } int fd, ret, e; size_t written = 0; StaticString score; if (scoreString.at(0) == 'l') { isLegacy = true; score = scoreString.substr(1); fd = open("/proc/self/oom_adj", O_WRONLY | O_TRUNC, 0600); } else { isLegacy = false; score = scoreString; fd = open("/proc/self/oom_score_adj", O_WRONLY | O_TRUNC, 0600); } if (fd == -1) { return errno; } do { ret = write(fd, score.data() + written, score.size() - written); if (ret != -1) { written += ret; } } while (ret == -1 && errno != EAGAIN && written < score.size()); e = errno; close(fd); if (ret == -1) { return e; } else { return 0; } } } // namespace Fundamentals } // namespace Agent } // namespace Passenger
26.085938
81
0.685235
m5o
874af4cb08261e47f30739b862bc3d57b47678b2
533
cpp
C++
0039-Recover Rotated Sorted Array/0039-Recover Rotated Sorted Array.cpp
nmdis1999/LintCode-1
316fa395c9a6de9bfac1d9c9cf58acb5ffb384a6
[ "MIT" ]
77
2017-12-30T13:33:37.000Z
2022-01-16T23:47:08.000Z
0001-0100/0039-Recover Rotated Sorted Array/0039-Recover Rotated Sorted Array.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
1
2018-05-14T14:15:40.000Z
2018-05-14T14:15:40.000Z
0001-0100/0039-Recover Rotated Sorted Array/0039-Recover Rotated Sorted Array.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
39
2017-12-07T14:36:25.000Z
2022-03-10T23:05:37.000Z
class Solution { public: void recoverRotatedSortedArray(vector<int> &nums) { // write your code here if (nums.size() == 0) { return; } for (int i = 0; i < nums.size() - 1; ++i) { if (nums[i] > nums[i + 1]) { reverse(nums.begin(), nums.begin() + i + 1); reverse(nums.begin() + i + 1, nums.end()); reverse(nums.begin(), nums.end()); return; } } } };
24.227273
60
0.390244
nmdis1999
874eecfc044abe477b2fe62ff1a046715e61152f
3,949
cpp
C++
src/mame/drivers/aid80f.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/aid80f.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/aid80f.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:AJR /**************************************************************************** AID-80F was Mostek's development system for the Z80 and 3870 families. It was later advertised as the development system for the MATRIX-80 (MDX) STD bus microcomputer. Boards available for this modular system included: * SDB-80E/OEM-80E CPU Module * FLP-80E Floppy Controller * CRT-80E Video Terminal Controller * PPG-8/16 2708/2758/2716 PROM Programmer * AIM-80 Z80 Application Interface Module — later replaced by AIM-Z80AE (4 MHz) and AIM-Z80BE (6 MHz) * AIM-72 3870 Application Interface Module — later replaced by AIM-7XE ****************************************************************************/ #include "emu.h" #include "cpu/z80/z80.h" #include "machine/ram.h" #include "machine/wd_fdc.h" #include "machine/z80ctc.h" #include "machine/z80pio.h" #include "machine/z80sio.h" class aid80f_state : public driver_device { public: aid80f_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_ram(*this, RAM_TAG) , m_monitor(*this, "monitor") { } void aid80f(machine_config &config); protected: virtual void machine_start() override; virtual void machine_reset() override; private: u8 ram_r(offs_t offset); void ram_w(offs_t offset, u8 data); u8 monitor_r(offs_t offset); void mem_map(address_map &map); void io_map(address_map &map); required_device<z80_device> m_maincpu; required_device<ram_device> m_ram; required_region_ptr<u8> m_monitor; bool m_ram_enabled; }; void aid80f_state::machine_start() { save_item(NAME(m_ram_enabled)); } void aid80f_state::machine_reset() { m_ram_enabled = false; } u8 aid80f_state::ram_r(offs_t offset) { if (m_ram_enabled) return m_ram->read(offset); else return m_monitor[offset & 0xfff]; } void aid80f_state::ram_w(offs_t offset, u8 data) { if (m_ram_enabled) m_ram->write(offset, data); } u8 aid80f_state::monitor_r(offs_t offset) { if (!machine().side_effects_disabled()) m_ram_enabled = true; return m_monitor[offset]; } void aid80f_state::mem_map(address_map &map) { map(0x0000, 0xffff).rw(FUNC(aid80f_state::ram_r), FUNC(aid80f_state::ram_w)); map(0xe000, 0xefff).r(FUNC(aid80f_state::monitor_r)); } void aid80f_state::io_map(address_map &map) { map.global_mask(0xff); map(0xd8, 0xdb).rw("ctc", FUNC(z80ctc_device::read), FUNC(z80ctc_device::write)); map(0xdc, 0xdf).rw("pio", FUNC(z80pio_device::read_alt), FUNC(z80pio_device::write_alt)); map(0xe4, 0xe7).rw("fdc", FUNC(fd1771_device::read), FUNC(fd1771_device::write)); } static INPUT_PORTS_START(aid80f) INPUT_PORTS_END static const z80_daisy_config daisy_chain[] = { { "ctc" }, { "pio" }, { "sio" }, { nullptr } }; void aid80f_state::aid80f(machine_config &config) { Z80(config, m_maincpu, 4.9152_MHz_XTAL / 2); m_maincpu->set_addrmap(AS_PROGRAM, &aid80f_state::mem_map); m_maincpu->set_addrmap(AS_IO, &aid80f_state::io_map); m_maincpu->set_daisy_config(daisy_chain); RAM(config, m_ram).set_default_size("64K"); Z80CTC(config, "ctc", 4.9152_MHz_XTAL / 2); Z80PIO(config, "pio", 4.9152_MHz_XTAL / 2); Z80SIO(config, "sio", 4.9152_MHz_XTAL / 2); FD1771(config, "fdc", 4_MHz_XTAL / 4); } ROM_START(aid80f) ROM_REGION(0x1000, "monitor", 0) ROM_LOAD("ddt1.u48", 0x0000, 0x0400, CRC(c9e5dc59) SHA1(3143bca7472900e7255ec0e39ca4121d1cb74c5f)) ROM_LOAD("ddt2.u49", 0x0400, 0x0400, CRC(dd37f628) SHA1(6da130a3678fd84070dd4ae3487c5212db5604ef)) ROM_LOAD("ddt3.u50", 0x0800, 0x0400, CRC(646d5fd2) SHA1(b9d0a4b3658835c5d724d709ca3cd70d69474caa)) ROM_LOAD("ddt4.u51", 0x0c00, 0x0400, CRC(c78e34c2) SHA1(5f3a4631d0b806a077b817f566ebbddd77ad7ba5)) // U52 socket is empty ROM_END COMP(1978, aid80f, 0, 0, aid80f, aid80f, aid80f_state, empty_init, "Mostek", "AID-80F Development System", MACHINE_IS_SKELETON)
27.615385
127
0.708787
Robbbert
87509160f6dcfb7d192723537785b4342edce344
781
cpp
C++
src/Core/Grammar/LoopBreaker.cpp
johnzeng/SimpleCompletor
e54b57242b7e624fea2d240bc50733ab6be72f6d
[ "MIT" ]
1
2016-06-10T05:30:32.000Z
2016-06-10T05:30:32.000Z
src/Core/Grammar/LoopBreaker.cpp
johnzeng/SimpleCompletor
e54b57242b7e624fea2d240bc50733ab6be72f6d
[ "MIT" ]
1
2016-07-19T02:36:39.000Z
2016-08-12T02:11:51.000Z
src/Core/Grammar/LoopBreaker.cpp
johnzeng/CppParser
e54b57242b7e624fea2d240bc50733ab6be72f6d
[ "MIT" ]
null
null
null
#include "LoopBreaker.h" #include "StringUtil.h" LoopBreaker::LoopBreaker(){} LoopBreaker::~LoopBreaker(){} bool LoopBreaker::insert(const string& file, int line, int index) { if (false == check(file, line, index)) { return false; } mLoopMark[getKey(file, line, index)] = 1; return true; } bool LoopBreaker::check(const string& file, int line, int index) { auto it = mLoopMark.find(getKey(file,line, index)) ; if (mLoopMark.end() == it) { return true; } return it->second == 0; } void LoopBreaker::remomve(const string& file, int line, int index) { mLoopMark[getKey(file, line, index)] = 0; } string LoopBreaker::getKey(const string& file, int line, int index) { return file + ":" + StringUtil::tostr(line) + ":" + StringUtil::tostr(index); }
21.108108
79
0.664533
johnzeng
87533d1b52000d8b1b0c24f6dee2047a209b9453
61,404
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/Fragment.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/Fragment.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/Fragment.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include <Elastos.CoreLibrary.IO.h> #include "Elastos.Droid.Os.h" #include "Elastos.Droid.Utility.h" #include "elastos/droid/app/Fragment.h" #include "elastos/droid/app/FragmentManagerImpl.h" #include "elastos/droid/app/Activity.h" #include "elastos/droid/app/SharedElementCallback.h" #include "elastos/droid/os/Build.h" #include "elastos/droid/transition/TransitionInflater.h" #include "elastos/droid/transition/CTransitionSet.h" #include "elastos/droid/R.h" #include <elastos/utility/logging/Slogger.h> #include <elastos/core/StringBuilder.h> #include <elastos/core/StringUtils.h> using Elastos::Droid::Os::IBinder; using Elastos::Droid::Os::Build; using Elastos::Droid::Content::EIID_IComponentCallbacks; using Elastos::Droid::Content::EIID_IComponentCallbacks2; using Elastos::Droid::Content::Pm::IApplicationInfo; using Elastos::Droid::Transition::TransitionInflater; using Elastos::Droid::Transition::ITransitionInflater; using Elastos::Droid::Transition::CTransitionSet; using Elastos::Droid::Transition::ITransitionSet; using Elastos::Droid::Utility::ISparseArray; using Elastos::Droid::View::EIID_IViewOnCreateContextMenuListener; using Elastos::Droid::R; using Elastos::Core::StringBuilder; using Elastos::Core::StringUtils; using Elastos::Core::IClassLoader; using Elastos::Utility::IMap; using Elastos::Utility::Logging::Slogger; namespace Elastos { namespace Droid { namespace App { static const String TAG("Fragment"); //============================================================================ // FragmentContainerLocal //============================================================================ class FragmentContainerLocal : public Object , public IFragmentContainer { public: CAR_INTERFACE_DECL() FragmentContainerLocal( /* [in] */ Fragment* host) : mHost(host) {} ECode FindViewById( /* [in] */ Int32 id, /* [out] */ IView** view) { VALIDATE_NOT_NULL(view) *view = NULL; if (mHost->mView == NULL) { // throw new IllegalStateException("Fragment does not have a view"); return E_ILLEGAL_STATE_EXCEPTION; } return mHost->mView->FindViewById(id, view); } ECode HasView( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = (mHost->mView != NULL); return NOERROR; } public: Fragment* mHost; }; CAR_INTERFACE_IMPL(FragmentContainerLocal, Object, IFragmentContainer) //=================================================================== // FragmentState //=================================================================== CAR_INTERFACE_IMPL_2(FragmentState, Object, IFragmentState, IParcelable) FragmentState::FragmentState() : mIndex(0) , mFromLayout(FALSE) , mFragmentId(0) , mContainerId(0) , mRetainInstance(FALSE) , mDetached(FALSE) {} FragmentState::~FragmentState() {} ECode FragmentState::constructor() { return NOERROR; } ECode FragmentState::constructor( /* [in] */ IFragment* frag) { // mClassName = frag.getClass().getName(); mClassName = Object::GetFullClassName(frag); frag->GetIndex(&mIndex); frag->GetFromLayout(&mFromLayout); frag->GetFragmentId(&mFragmentId); frag->GetContainerId(&mContainerId); frag->GetTag(&mTag); frag->GetRetainInstance(&mRetainInstance); frag->IsDetached(&mDetached); frag->GetArguments((IBundle**)&mArguments); return NOERROR; } ECode FragmentState::ReadFromParcel( /* [in] */ IParcel* in) { FAIL_RETURN(in->ReadString(&mClassName)); FAIL_RETURN(in->ReadInt32(&mIndex)); Int32 value; FAIL_RETURN(in->ReadInt32(&value)) mFromLayout = value != 0; FAIL_RETURN(in->ReadInt32(&mFragmentId)); FAIL_RETURN(in->ReadInt32(&mContainerId)); FAIL_RETURN(in->ReadString(&mTag)); FAIL_RETURN(in->ReadInt32(&value)) mRetainInstance = value != 0; FAIL_RETURN(in->ReadInt32(&value)) mDetached = value != 0; FAIL_RETURN(in->ReadInterfacePtr((Handle32*)(IBundle**)&mArguments)); FAIL_RETURN(in->ReadInterfacePtr((Handle32*)(IBundle**)&mSavedFragmentState)); return NOERROR; } ECode FragmentState::Instantiate( /* [in] */ IActivity* activity, /* [in] */ IFragment* parent, /* [out] */ IFragment** fragment) { VALIDATE_NOT_NULL(fragment); *fragment = NULL; VALIDATE_NOT_NULL(activity); if (mInstance != NULL) { *fragment = mInstance; REFCOUNT_ADD(*fragment); return NOERROR; } if (mArguments != NULL) { AutoPtr<IClassLoader> classLoader; IContext::Probe(activity)->GetClassLoader((IClassLoader**)&classLoader); mArguments->SetClassLoader(classLoader); } Fragment::Instantiate(IContext::Probe(activity), mClassName, mArguments, (IFragment**)&mInstance); if (mSavedFragmentState != NULL) { AutoPtr<IClassLoader> classLoader; IContext::Probe(activity)->GetClassLoader((IClassLoader**)&classLoader); mSavedFragmentState->SetClassLoader(classLoader); mInstance->SetSavedFragmentState(mSavedFragmentState); } AutoPtr<Activity> act = (Activity*)activity; mInstance->SetIndex(mIndex, parent); mInstance->SetFromLayout(mFromLayout); mInstance->SetRestored(TRUE); mInstance->SetFragmentId(mFragmentId); mInstance->SetContainerId(mContainerId); mInstance->SetTag(mTag); mInstance->SetRetainInstance(mRetainInstance); mInstance->SetDetached(mDetached); mInstance->SetFragmentManager(act->mFragments); if (FragmentManagerImpl::DEBUG) Slogger::V(FragmentManagerImpl::TAG, "Instantiated fragment %p", mInstance.Get()); *fragment = mInstance; REFCOUNT_ADD(*fragment); return NOERROR; } ECode FragmentState::WriteToParcel( /* [in] */ IParcel* dest) { VALIDATE_NOT_NULL(dest); FAIL_RETURN(dest->WriteString(mClassName)); FAIL_RETURN(dest->WriteInt32(mIndex)); FAIL_RETURN(dest->WriteInt32(mFromLayout ? 1 : 0)); FAIL_RETURN(dest->WriteInt32(mFragmentId)); FAIL_RETURN(dest->WriteInt32(mContainerId)); FAIL_RETURN(dest->WriteString(mTag)); FAIL_RETURN(dest->WriteInt32(mRetainInstance ? 1 : 0)); FAIL_RETURN(dest->WriteInt32(mDetached ? 1 : 0)); FAIL_RETURN(dest->WriteInterfacePtr(mArguments)); FAIL_RETURN(dest->WriteInterfacePtr(mSavedFragmentState)); return NOERROR; } ECode FragmentState::GetClassName( /* [out] */ String* name) { VALIDATE_NOT_NULL(name) *name = mClassName; return NOERROR; } ECode FragmentState::GetIndex( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mIndex; return NOERROR; } ECode FragmentState::IsFromLayout( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = mFromLayout; return NOERROR; } ECode FragmentState::GetFragmentId( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mFragmentId; return NOERROR; } ECode FragmentState::GetContainerId( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mContainerId; return NOERROR; } ECode FragmentState::GetTag( /* [out] */ String* tag) { VALIDATE_NOT_NULL(tag) *tag = mTag; return NOERROR; } ECode FragmentState::IsRetainInstance( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = mRetainInstance; return NOERROR; } ECode FragmentState::IsDetached( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = mDetached; return NOERROR; } ECode FragmentState::GetArguments( /* [out] */ IBundle** arguments) { VALIDATE_NOT_NULL(arguments) *arguments = mArguments; REFCOUNT_ADD(*arguments) return NOERROR; } ECode FragmentState::GetSavedFragmentState( /* [out] */ IBundle** state) { VALIDATE_NOT_NULL(state) *state = mSavedFragmentState; REFCOUNT_ADD(*state) return NOERROR; } ECode FragmentState::GetInstance( /* [out] */ IFragment** fragment) { VALIDATE_NOT_NULL(fragment) *fragment = mInstance; REFCOUNT_ADD(*fragment) return NOERROR; } //============================================================================= // Activity::ViewCreateContextMenuListener //============================================================================= CAR_INTERFACE_IMPL(Fragment::ViewCreateContextMenuListener, Object, IViewOnCreateContextMenuListener) Fragment::ViewCreateContextMenuListener::ViewCreateContextMenuListener( /* [in] */ Fragment* host) : mHost(host) { } ECode Fragment::ViewCreateContextMenuListener::OnCreateContextMenu( /* [in] */ IContextMenu* menu, /* [in] */ IView* v, /* [in] */ IContextMenuInfo* menuInfo) { return mHost->OnCreateContextMenu(menu, v, menuInfo); } //=================================================================== // Fragment //=================================================================== AutoPtr<ITransition> InitUSE_DEFAULT_TRANSITION() { AutoPtr<ITransition> transit; CTransitionSet::New((ITransition**)&transit); return transit; } const AutoPtr<ITransition> Fragment::USE_DEFAULT_TRANSITION = InitUSE_DEFAULT_TRANSITION(); HashMap<String, AutoPtr<IClassInfo> > Fragment::sClassMap; CAR_INTERFACE_IMPL_4(Fragment, Object, IFragment, IComponentCallbacks, IComponentCallbacks2, IViewOnCreateContextMenuListener) Fragment::Fragment() : mState(INITIALIZING) , mStateAfterAnimating(0) , mIndex(-1) , mTargetIndex(-1) , mTargetRequestCode(0) , mAdded(FALSE) , mRemoving(FALSE) , mResumed(FALSE) , mFromLayout(FALSE) , mInLayout(FALSE) , mRestored(FALSE) , mBackStackNesting(0) , mActivity(NULL) , mParentFragment(NULL) , mFragmentId(0) , mContainerId(0) , mHidden(FALSE) , mDetached(FALSE) , mRetainInstance(FALSE) , mRetaining(FALSE) , mHasMenu(FALSE) , mMenuVisible(TRUE) , mCalled(FALSE) , mNextAnim(0) , mDeferStart(FALSE) , mUserVisibleHint(TRUE) , mLoadersStarted(FALSE) , mCheckedForLoaderManager(FALSE) , mAllowReturnTransitionOverlap(TRUE) , mAllowEnterTransitionOverlap(TRUE) #if defined(_DEBUG) , mIsConstructed(FALSE) #endif {} Fragment::~Fragment() {} ECode Fragment::constructor() { mViewCreateContextMenuListener = new ViewCreateContextMenuListener(this); #if defined(_DEBUG) mIsConstructed = TRUE; #endif return NOERROR; } ECode Fragment::GetState( /* [out] */ Int32* state) { VALIDATE_NOT_NULL(state); *state = mState; return NOERROR; } ECode Fragment::SetState( /* [in] */ Int32 state) { mState = state; return NOERROR; } ECode Fragment::GetAnimatingAway( /* [out] */ IAnimator** animator) { VALIDATE_NOT_NULL(animator); *animator = mAnimatingAway; REFCOUNT_ADD(*animator); return NOERROR; } ECode Fragment::SetAnimatingAway( /* [in] */ IAnimator* animator) { mAnimatingAway = animator; return NOERROR; } ECode Fragment::GetStateAfterAnimating( /* [out] */ Int32* state) { VALIDATE_NOT_NULL(state); *state = mStateAfterAnimating; return NOERROR; } ECode Fragment::SetStateAfterAnimating( /* [in] */ Int32 state) { mStateAfterAnimating = state; return NOERROR; } ECode Fragment::GetSavedFragmentState( /* [out] */ IBundle** fState) { VALIDATE_NOT_NULL(fState); *fState = mSavedFragmentState; REFCOUNT_ADD(*fState); return NOERROR; } ECode Fragment::SetSavedFragmentState( /* [in] */ IBundle* fState) { mSavedFragmentState = fState; return NOERROR; } ECode Fragment::GetSavedViewState( /* [out] */ ISparseArray** viewState) { VALIDATE_NOT_NULL(viewState); *viewState = mSavedViewState; REFCOUNT_ADD(*viewState); return NOERROR; } ECode Fragment::SetSavedViewState( /* [in] */ ISparseArray* viewState) { mSavedViewState = viewState; return NOERROR; } ECode Fragment::GetIndex( /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index); *index = mIndex; return NOERROR; } ECode Fragment::GetWho( /* [out] */ String* who) { VALIDATE_NOT_NULL(who); *who = mWho; return NOERROR; } ECode Fragment::SetWho( /* [in] */ const String& who) { mWho = who; return NOERROR; } ECode Fragment::GetTarget( /* [out] */ IFragment** target) { VALIDATE_NOT_NULL(target); *target = mTarget; REFCOUNT_ADD(*target); return NOERROR; } ECode Fragment::SetTarget( /* [in] */ IFragment* target) { mTarget = target; return NOERROR; } ECode Fragment::GetTargetIndex( /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index); *index = mTargetIndex; return NOERROR; } ECode Fragment::SetTargetIndex( /* [in] */ Int32 index) { mTargetIndex = index; return NOERROR; } ECode Fragment::SetTargetRequestCode( /* [in] */ Int32 code) { mTargetRequestCode = code; return NOERROR; } ECode Fragment::GetAdded( /* [out] */ Boolean* added) { VALIDATE_NOT_NULL(added); *added = mAdded; return NOERROR; } ECode Fragment::SetAdded( /* [in] */ Boolean added) { mAdded = added; return NOERROR; } ECode Fragment::SetRemoving( /* [in] */ Boolean removing) { mRemoving = removing; return NOERROR; } ECode Fragment::SetResumed( /* [in] */ Boolean resumed) { mResumed = resumed; return NOERROR; } ECode Fragment::GetFromLayout( /* [out] */ Boolean* fLayout) { VALIDATE_NOT_NULL(fLayout); *fLayout = mFromLayout; return NOERROR; } ECode Fragment::SetFromLayout( /* [in] */ Boolean fLayout) { mFromLayout = fLayout; return NOERROR; } ECode Fragment::SetInLayout( /* [in] */ Boolean inLayout) { mInLayout = inLayout; return NOERROR; } ECode Fragment::GetRestored( /* [out] */ Boolean* restored) { VALIDATE_NOT_NULL(restored); *restored = mRestored; return NOERROR; } ECode Fragment::SetRestored( /* [in] */ Boolean restored) { mRestored = restored; return NOERROR; } ECode Fragment::GetBackStackNesting( /* [out] */ Int32* bsNesting) { VALIDATE_NOT_NULL(bsNesting); *bsNesting = mBackStackNesting; return NOERROR; } ECode Fragment::SetBackStackNesting( /* [in] */ Int32 bsNesting) { mBackStackNesting = bsNesting; return NOERROR; } ECode Fragment::SetFragmentManager( /* [in] */ IFragmentManagerImpl* fManager) { mFragmentManager = fManager; return NOERROR; } ECode Fragment::SetActivity( /* [in] */ IActivity* activity) { mActivity = activity; return NOERROR; } ECode Fragment::SetParentFragment( /* [in] */ IFragment* pFragment) { mParentFragment = pFragment; return NOERROR; } ECode Fragment::GetFragmentId( /* [out] */ Int32* fid) { VALIDATE_NOT_NULL(fid); *fid = mFragmentId; return NOERROR; } ECode Fragment::SetFragmentId( /* [in] */ Int32 fid) { mFragmentId = fid; return NOERROR; } ECode Fragment::GetContainerId( /* [out] */ Int32* cid) { VALIDATE_NOT_NULL(cid); *cid = mContainerId; return NOERROR; } ECode Fragment::SetContainerId( /* [in] */ Int32 cid) { mContainerId = cid; return NOERROR; } ECode Fragment::SetTag( /* [in] */ const String& tag) { mTag = tag; return NOERROR; } ECode Fragment::SetHidden( /* [in] */ Boolean hidden) { mHidden = hidden; return NOERROR; } ECode Fragment::SetDetached( /* [in] */ Boolean detached) { mDetached = detached; return NOERROR; } ECode Fragment::GetRetaining( /* [out] */ Boolean* retaining) { VALIDATE_NOT_NULL(retaining); *retaining = mRetaining; return NOERROR; } ECode Fragment::SetRetaining( /* [in] */ Boolean retaining) { mRetaining = retaining; return NOERROR; } ECode Fragment::GetHasMenu( /* [out] */ Boolean* hasMenu) { VALIDATE_NOT_NULL(hasMenu); *hasMenu = mHasMenu; return NOERROR; } ECode Fragment::SetHasMenu( /* [in] */ Boolean hasMenu) { mHasMenu = hasMenu; return NOERROR; } ECode Fragment::GetMenuVisible( /* [out] */ Boolean* visible) { VALIDATE_NOT_NULL(visible); *visible = mMenuVisible; return NOERROR; } ECode Fragment::SetMenuVisible( /* [in] */ Boolean visible) { mMenuVisible = visible; return NOERROR; } ECode Fragment::GetCalled( /* [out] */ Boolean* called) { VALIDATE_NOT_NULL(called); *called = mCalled; return NOERROR; } ECode Fragment::SetCalled( /* [in] */ Boolean called) { mCalled = called; return NOERROR; } ECode Fragment::GetNextAnim( /* [out] */ Int32* anim) { VALIDATE_NOT_NULL(anim); *anim = mNextAnim; return NOERROR; } ECode Fragment::SetNextAnim( /* [in] */ Int32 anim) { mNextAnim = anim; return NOERROR; } ECode Fragment::GetContainer( /* [out] */ IViewGroup** container) { VALIDATE_NOT_NULL(container); *container = mContainer; REFCOUNT_ADD(*container); return NOERROR; } ECode Fragment::SetContainer( /* [in] */ IViewGroup* container) { mContainer = container; return NOERROR; } ECode Fragment::SetView( /* [in] */ IView* view) { mView = view; return NOERROR; } ECode Fragment::GetDeferStart( /* [out] */ Boolean* start) { VALIDATE_NOT_NULL(start); *start = mDeferStart; return NOERROR; } ECode Fragment::SetDeferStart( /* [in] */ Boolean start) { mDeferStart = start; return NOERROR; } ECode Fragment::SetLoaderManager( /* [in] */ ILoaderManagerImpl* lManager) { mLoaderManager = lManager; return NOERROR; } ECode Fragment::GetLoaderManagerValue( /* [out] */ ILoaderManagerImpl** lManager) { VALIDATE_NOT_NULL(lManager); *lManager = mLoaderManager; REFCOUNT_ADD(*lManager); return NOERROR; } ECode Fragment::GetLoadersStarted( /* [out] */ Boolean* started) { VALIDATE_NOT_NULL(started); *started = mLoadersStarted; return NOERROR; } ECode Fragment::SetLoadersStarted( /* [in] */ Boolean started) { mLoadersStarted = started; return NOERROR; } ECode Fragment::GetCheckedForLoaderManager( /* [out] */ Boolean* cfManager) { VALIDATE_NOT_NULL(cfManager); *cfManager = mCheckedForLoaderManager; return NOERROR; } ECode Fragment::SetCheckedForLoaderManager( /* [in] */ Boolean cfManager) { mCheckedForLoaderManager = cfManager; return NOERROR; } ECode Fragment::Instantiate( /* [in] */ IContext* context, /* [in] */ const String& fname, /* [out] */ IFragment** fragment) { VALIDATE_NOT_NULL(fragment); return Instantiate(context, fname, NULL, fragment); } ECode Fragment::Instantiate( /* [in] */ IContext* context, /* [in] */ const String& fname, /* [in] */ IBundle* args, /* [out] */ IFragment** fragment) { VALIDATE_NOT_NULL(fragment); *fragment = NULL; // try { AutoPtr<IClassInfo> clazz; HashMap<String, AutoPtr<IClassInfo> >::Iterator it = sClassMap.Find(fname); if (it == sClassMap.End()) { // // Class not found in the cache, see if it's real, and try to add it AutoPtr<IClassLoader> classLoader; context->GetClassLoader((IClassLoader**)&classLoader); classLoader->LoadClass(fname, (IClassInfo**)&clazz); if (clazz == NULL) { Slogger::E(TAG, "Trying to instantiate a class %s failed", fname.string()); return E_INSTANTIATION_EXCEPTION; } // if (!Fragment.class.isAssignableFrom(clazz)) { // throw new InstantiationException("Trying to instantiate a class " + fname // + " that is not a Fragment", new ClassCastException()); // } sClassMap[fname] = clazz; } else { clazz = it->mSecond; } AutoPtr<IInterface> obj; ECode ec = clazz->CreateObject((IInterface**)&obj); FAIL_RETURN(ec); //FAIL_RETURN(clazz->CreateObject((IInterface**)&obj)); AutoPtr<IFragment> f = IFragment::Probe(obj); if (args != NULL) { AutoPtr<IClassLoader> cl = Object::GetClassLoader(f.Get()); args->SetClassLoader(cl); f->SetArguments(args); } *fragment = f; REFCOUNT_ADD(*fragment); return NOERROR; // } catch (ClassNotFoundException e) { // throw new InstantiationException("Unable to instantiate fragment " + fname // + ": make sure class name exists, is public, and has an" // + " empty constructor that is public", e); // } catch (java.lang.InstantiationException e) { // throw new InstantiationException("Unable to instantiate fragment " + fname // + ": make sure class name exists, is public, and has an" // + " empty constructor that is public", e); // } catch (IllegalAccessException e) { // throw new InstantiationException("Unable to instantiate fragment " + fname // + ": make sure class name exists, is public, and has an" // + " empty constructor that is public", e); // } } ECode Fragment::RestoreViewState( /* [in] */ IBundle* savedInstanceState) { if (mSavedViewState != NULL) { mView->RestoreHierarchyState(mSavedViewState); mSavedViewState = NULL; } mCalled = FALSE; OnViewStateRestored(savedInstanceState); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnViewStateRestored()"); return E_SUPER_NOT_CALLED_EXCEPTION; } return NOERROR; } ECode Fragment::SetIndex( /* [in] */ Int32 index, /* [in] */ IFragment* parent) { mIndex = index; if (parent != NULL) { String who; parent->GetWho(&who); StringBuilder sb(who); sb += ":"; sb += mIndex; mWho = sb.ToString(); } else { StringBuilder sb("android:fragment:"); sb += mIndex; mWho = sb.ToString(); } return NOERROR; } ECode Fragment::IsInBackStack( /* [out] */ Boolean* inbs) { VALIDATE_NOT_NULL(inbs); *inbs = mBackStackNesting > 0; return NOERROR; } ECode Fragment::Equals( /* [in] */ IInterface* o, /* [out] */ Boolean* equal) { return Object::Equals(o, equal); } ECode Fragment::GetHashCode( /* [out] */ Int32* code) { return Object::GetHashCode(code); } ECode Fragment::ToString( /* [out] */ String* string) { VALIDATE_NOT_NULL(string) StringBuilder sb(128); AutoPtr<IClassInfo> classInfo = Object::GetClassInfo(TO_IINTERFACE(this)); String className("Fragment"); if (classInfo != NULL) { classInfo->GetName(&className); } sb += className; sb += "{0x"; sb += StringUtils::ToHexString((Int32)this); if (mIndex >= 0) { sb.Append(" #"); sb.Append(mIndex); } if (mFragmentId != 0) { sb.Append(" id=0x"); sb.Append(StringUtils::ToHexString(mFragmentId)); } if (mTag != NULL) { sb.Append(" tag="); sb.Append(mTag); } sb.Append("}"); *string = sb.ToString(); return NOERROR; } ECode Fragment::GetId( /* [out] */ Int32* id) { VALIDATE_NOT_NULL(id); *id = mFragmentId; return NOERROR; } ECode Fragment::GetTag( /* [out] */ String* tag) { VALIDATE_NOT_NULL(tag); *tag = mTag; return NOERROR; } ECode Fragment::SetArguments( /* [in] */ IBundle* args) { if (mIndex >= 0) { Slogger::E(TAG, "Fragment already active"); return E_ILLEGAL_STATE_EXCEPTION; } mArguments = args; return NOERROR; } ECode Fragment::GetArguments( /* [out] */ IBundle** args) { VALIDATE_NOT_NULL(args); *args = mArguments; REFCOUNT_ADD(*args); return NOERROR; } ECode Fragment::SetInitialSavedState( /* [in] */ IFragmentSavedState* state) { if (mIndex >= 0) { Slogger::E(TAG, "Fragment already active"); return E_ILLEGAL_STATE_EXCEPTION; } AutoPtr<IBundle> fState; mSavedFragmentState = state != NULL && (state->GetState((IBundle**)&fState), fState != NULL) ? fState : NULL; return NOERROR; } ECode Fragment::SetTargetFragment( /* [in] */ IFragment* fragment, /* [in] */ Int32 requestCode) { mTarget = fragment; mTargetRequestCode = requestCode; return NOERROR; } ECode Fragment::GetTargetFragment( /* [out] */ IFragment** fragment) { VALIDATE_NOT_NULL(fragment); *fragment = mTarget; REFCOUNT_ADD(*fragment); return NOERROR; } ECode Fragment::GetTargetRequestCode( /* [out] */ Int32* code) { VALIDATE_NOT_NULL(code); *code = mTargetRequestCode; return NOERROR; } ECode Fragment::GetActivity( /* [out] */ IActivity** activity) { VALIDATE_NOT_NULL(activity); *activity = mActivity; REFCOUNT_ADD(*activity); return NOERROR; } ECode Fragment::GetResources( /* [out] */ IResources** resources) { VALIDATE_NOT_NULL(resources); if (mActivity == NULL) { // throw new IllegalStateException("Fragment " + this + " not attached to Activity"); return E_ILLEGAL_STATE_EXCEPTION; } IContext::Probe(mActivity)->GetResources(resources); return NOERROR; } ECode Fragment::GetText( /* [in] */ Int32 resId, /* [out] */ ICharSequence** text) { VALIDATE_NOT_NULL(text); AutoPtr<IResources> resources; GetResources((IResources**)&resources); resources->GetText(resId, text); return NOERROR; } ECode Fragment::GetString( /* [in] */ Int32 resId, /* [out] */ String* string) { VALIDATE_NOT_NULL(string); AutoPtr<IResources> resources; GetResources((IResources**)&resources); resources->GetString(resId, string); return NOERROR; } ECode Fragment::GetString( /* [in] */ Int32 resId, /* [in] */ ArrayOf<IInterface*>* formatArgs, /* [out] */ String* string) { VALIDATE_NOT_NULL(string); AutoPtr<IResources> resources; GetResources((IResources**)&resources); resources->GetString(resId, formatArgs, string); return NOERROR; } ECode Fragment::GetFragmentManager( /* [out] */ IFragmentManager** manager) { VALIDATE_NOT_NULL(manager); *manager = IFragmentManager::Probe(mFragmentManager); REFCOUNT_ADD(*manager); return NOERROR; } ECode Fragment::GetChildFragmentManager( /* [out] */ IFragmentManager** manager) { VALIDATE_NOT_NULL(manager); if (mChildFragmentManager == NULL) { InstantiateChildFragmentManager(); if (mState >= IFragment::RESUMED) { mChildFragmentManager->DispatchResume(); } else if (mState >= IFragment::STARTED) { mChildFragmentManager->DispatchStart(); } else if (mState >= IFragment::ACTIVITY_CREATED) { mChildFragmentManager->DispatchActivityCreated(); } else if (mState >= IFragment::CREATED) { mChildFragmentManager->DispatchCreate(); } } *manager = IFragmentManager::Probe(mChildFragmentManager); REFCOUNT_ADD(*manager); return NOERROR; } ECode Fragment::GetParentFragment( /* [out] */ IFragment** fragment) { VALIDATE_NOT_NULL(fragment); *fragment = mParentFragment; REFCOUNT_ADD(*fragment); return NOERROR; } ECode Fragment::IsAdded( /* [out] */ Boolean* added) { VALIDATE_NOT_NULL(added); *added = mActivity != NULL && mAdded; return NOERROR; } ECode Fragment::IsDetached( /* [out] */ Boolean* detached) { VALIDATE_NOT_NULL(detached); *detached = mDetached; return NOERROR; } ECode Fragment::IsRemoving( /* [out] */ Boolean* removing) { VALIDATE_NOT_NULL(removing); *removing = mRemoving; return NOERROR; } ECode Fragment::IsInLayout( /* [out] */ Boolean* inlayout) { VALIDATE_NOT_NULL(inlayout); *inlayout = mInLayout; return NOERROR; } ECode Fragment::IsResumed( /* [out] */ Boolean* resumed) { VALIDATE_NOT_NULL(resumed); *resumed = mResumed; return NOERROR; } ECode Fragment::IsVisible( /* [out] */ Boolean* visible) { VALIDATE_NOT_NULL(visible); Boolean added, hidden; IsAdded(&added); IsHidden(&hidden); AutoPtr<IBinder> token; mView->GetWindowToken((IBinder**)&token); Int32 visibility; mView->GetVisibility(&visibility); *visible = added && !hidden && mView != NULL && token != NULL && visibility == IView::VISIBLE; return NOERROR; } ECode Fragment::IsHidden( /* [out] */ Boolean* hidden) { VALIDATE_NOT_NULL(hidden); *hidden = mHidden; return NOERROR; } ECode Fragment::OnHiddenChanged( /* [in] */ Boolean hidden) { return NOERROR; } ECode Fragment::SetRetainInstance( /* [in] */ Boolean retain) { if (retain && mParentFragment != NULL) { // throw new IllegalStateException( // "Can't retain fragements that are nested in other fragments"); return E_ILLEGAL_STATE_EXCEPTION; } mRetainInstance = retain; return NOERROR; } ECode Fragment::GetRetainInstance( /* [out] */ Boolean* retainInstance) { VALIDATE_NOT_NULL(retainInstance); *retainInstance = mRetainInstance; return NOERROR; } ECode Fragment::SetHasOptionsMenu( /* [in] */ Boolean hasMenu) { if (mHasMenu != hasMenu) { mHasMenu = hasMenu; Boolean added, hidden; IsAdded(&added); IsHidden(&hidden); if (added && !hidden) { IFragmentManager::Probe(mFragmentManager)->InvalidateOptionsMenu(); } } return NOERROR; } ECode Fragment::SetMenuVisibility( /* [in] */ Boolean menuVisible) { if (mMenuVisible != menuVisible) { mMenuVisible = menuVisible; Boolean added, hidden; IsAdded(&added); IsHidden(&hidden); if (mHasMenu && added && !hidden) { IFragmentManager::Probe(mFragmentManager)->InvalidateOptionsMenu(); } } return NOERROR; } ECode Fragment::SetUserVisibleHint( /* [in] */ Boolean isVisibleToUser) { if (!mUserVisibleHint && isVisibleToUser && mState < IFragment::STARTED) { mFragmentManager->PerformPendingDeferredStart(this); } mUserVisibleHint = isVisibleToUser; mDeferStart = !isVisibleToUser; return NOERROR; } ECode Fragment::GetUserVisibleHint( /* [out] */ Boolean* hint) { VALIDATE_NOT_NULL(hint); *hint = mUserVisibleHint; return NOERROR; } ECode Fragment::GetLoaderManager( /* [out] */ ILoaderManager** manager) { VALIDATE_NOT_NULL(manager); if (mLoaderManager != NULL) { *manager = ILoaderManager::Probe(mLoaderManager); REFCOUNT_ADD(*manager); return NOERROR; } if (mActivity == NULL) { Slogger::E(TAG, "Fragment not attached to Activity"); return E_ILLEGAL_STATE_EXCEPTION; } mCheckedForLoaderManager = TRUE; AutoPtr<Activity> act = (Activity*)mActivity; mLoaderManager = act->GetLoaderManager(mWho, mLoadersStarted, TRUE); *manager = ILoaderManager::Probe(mLoaderManager); REFCOUNT_ADD(*manager); return NOERROR; } ECode Fragment::StartActivity( /* [in] */ IIntent* intent) { VALIDATE_NOT_NULL(intent); StartActivity(intent, NULL); return NOERROR; } ECode Fragment::StartActivity( /* [in] */ IIntent* intent, /* [in] */ IBundle* options) { VALIDATE_NOT_NULL(intent); if (mActivity == NULL) { Slogger::E(TAG, "Fragment not attached to Activity"); return E_ILLEGAL_STATE_EXCEPTION; } if (options != NULL) { mActivity->StartActivityFromFragment(this, intent, -1, options); } else { // Note we want to go through this call for compatibility with // applications that may have overridden the method. mActivity->StartActivityFromFragment(this, intent, -1); } return NOERROR; } ECode Fragment::StartActivityForResult( /* [in] */ IIntent* intent, /* [in] */ Int32 requestCode) { return StartActivityForResult(intent, requestCode, NULL); } ECode Fragment::StartActivityForResult( /* [in] */ IIntent* intent, /* [in] */ Int32 requestCode, /* [in] */ IBundle* options) { if (mActivity == NULL) { Slogger::E(TAG, "Fragment not attached to Activity"); return E_ILLEGAL_STATE_EXCEPTION; } if (options != NULL) { mActivity->StartActivityFromFragment(this, intent, requestCode, options); } else { // Note we want to go through this call for compatibility with // applications that may have overridden the method. mActivity->StartActivityFromFragment(this, intent, requestCode, options); } return NOERROR; } ECode Fragment::OnActivityResult( /* [in] */ Int32 requestCode, /* [in] */ Int32 resultCode, /* [in] */ IIntent* data) { return NOERROR; } ECode Fragment::GetLayoutInflater( /* [in] */ IBundle* savedInstanceState, /* [out] */ ILayoutInflater** inflater) { VALIDATE_NOT_NULL(inflater); // Newer platform versions use the child fragment manager's LayoutInflaterFactory. AutoPtr<IApplicationInfo> ai; IContext::Probe(mActivity)->GetApplicationInfo((IApplicationInfo**)&ai); Int32 skdVer; ai->GetTargetSdkVersion(&skdVer); if (skdVer >= Build::VERSION_CODES::LOLLIPOP) { AutoPtr<ILayoutInflater> li, result; mActivity->GetLayoutInflater((ILayoutInflater**)&li); li->CloneInContext(IContext::Probe(mActivity), (ILayoutInflater**)&result); AutoPtr<IFragmentManager> tmp; GetChildFragmentManager((IFragmentManager**)&tmp); // Init if needed; use raw implementation below. AutoPtr<ILayoutInflaterFactory2> fact; ((FragmentManagerImpl*)mChildFragmentManager.Get())->GetLayoutInflaterFactory((ILayoutInflaterFactory2**)&fact); result->SetPrivateFactory(fact); *inflater = result; REFCOUNT_ADD(*inflater) return NOERROR; } return mActivity->GetLayoutInflater(inflater); } ECode Fragment::OnInflate( /* [in] */ IAttributeSet* attrs, /* [in] */ IBundle* savedInstanceState) { mCalled = TRUE; return NOERROR; } ECode Fragment::OnInflate( /* [in] */ IActivity* activity, /* [in] */ IAttributeSet* attrs, /* [in] */ IBundle* savedInstanceState) { OnInflate(attrs, savedInstanceState); mCalled = TRUE; IContext* ctx = IContext::Probe(activity); AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::Fragment); AutoPtr<ITypedArray> a; ctx->ObtainStyledAttributes(attrs, attrIds, 0, 0, (ITypedArray**)&a); mEnterTransition = LoadTransition(ctx, a, mEnterTransition, NULL, R::styleable::Fragment_fragmentEnterTransition); mReturnTransition = LoadTransition(ctx, a, mReturnTransition, USE_DEFAULT_TRANSITION, R::styleable::Fragment_fragmentReturnTransition); mExitTransition = LoadTransition(ctx, a, mExitTransition, NULL, R::styleable::Fragment_fragmentExitTransition); mReenterTransition = LoadTransition(ctx, a, mReenterTransition, USE_DEFAULT_TRANSITION, R::styleable::Fragment_fragmentReenterTransition); mSharedElementEnterTransition = LoadTransition(ctx, a, mSharedElementEnterTransition, NULL, R::styleable::Fragment_fragmentSharedElementEnterTransition); mSharedElementReturnTransition = LoadTransition(ctx, a, mSharedElementReturnTransition, USE_DEFAULT_TRANSITION, R::styleable::Fragment_fragmentSharedElementReturnTransition); // if (mAllowEnterTransitionOverlap == NULL) { a->GetBoolean( R::styleable::Fragment_fragmentAllowEnterTransitionOverlap, TRUE, &mAllowEnterTransitionOverlap); } // if (mAllowReturnTransitionOverlap == NULL) { a->GetBoolean( R::styleable::Fragment_fragmentAllowReturnTransitionOverlap, TRUE, &mAllowReturnTransitionOverlap); } a->Recycle(); return NOERROR; } ECode Fragment::OnAttach( /* [in] */ IActivity* activity) { #if defined(_DEBUG) if (!mIsConstructed) { Slogger::E(TAG, "Error: Fragment::constructor() is not called by sub classes %s!", TO_CSTR(this)); assert(0 && "Error: Fragment::constructor() is not called by sub classes"); } #endif mCalled = TRUE; return NOERROR; } ECode Fragment::OnCreateAnimator( /* [in] */ Int32 transit, /* [in] */ Boolean enter, /* [in] */ Int32 nextAnim, /* [out] */ IAnimator** animator) { VALIDATE_NOT_NULL(animator); *animator = NULL; return NOERROR; } ECode Fragment::OnCreate( /* [in] */ IBundle* savedInstanceState) { #if defined(_DEBUG) if (!mIsConstructed) { Slogger::E(TAG, "Error: Fragment::constructor() is not called by sub classes %s!", TO_CSTR(this)); assert(0 && "Error: Fragment::constructor() is not called by sub classes"); } #endif mCalled = TRUE; return NOERROR; } ECode Fragment::OnCreateView( /* [in] */ ILayoutInflater* inflater, /* [in] */ IViewGroup* container, /* [in] */ IBundle* savedInstanceState, /* [out] */ IView** view) { VALIDATE_NOT_NULL(view); *view = NULL; return NOERROR; } ECode Fragment::OnViewCreated( /* [in] */ IView* view, /* [in] */ IBundle* savedInstanceState) { return NOERROR; } ECode Fragment::GetView( /* [out] */ IView** view) { VALIDATE_NOT_NULL(view); *view = mView; REFCOUNT_ADD(*view); return NOERROR; } ECode Fragment::OnActivityCreated( /* [in] */ IBundle* savedInstanceState) { mCalled = TRUE; return NOERROR; } ECode Fragment::OnViewStateRestored( /* [in] */ IBundle* savedInstanceState) { mCalled = TRUE; return NOERROR; } ECode Fragment::OnStart() { mCalled = TRUE; if (!mLoadersStarted) { mLoadersStarted = TRUE; if (!mCheckedForLoaderManager) { mCheckedForLoaderManager = TRUE; AutoPtr<Activity> act = (Activity*)mActivity; mLoaderManager = act->GetLoaderManager(mWho, mLoadersStarted, FALSE); } if (mLoaderManager != NULL) { assert(0 && "TODO"); //((LoaderManagerImpl*)mLoaderManager.Get())->DoStart(); } } return NOERROR; } ECode Fragment::OnResume() { mCalled = TRUE; return NOERROR; } ECode Fragment::OnSaveInstanceState( /* [in] */ IBundle* outState) { return NOERROR; } ECode Fragment::OnConfigurationChanged( /* [in] */ IConfiguration* newConfig) { mCalled = TRUE; return NOERROR; } ECode Fragment::OnPause() { mCalled = TRUE; return NOERROR; } ECode Fragment::OnStop() { mCalled = TRUE; return NOERROR; } ECode Fragment::OnLowMemory() { mCalled = TRUE; return NOERROR; } ECode Fragment::OnTrimMemory( /* [in] */ Int32 level) { mCalled = TRUE; return NOERROR; } ECode Fragment::OnDestroyView() { mCalled = TRUE; return NOERROR; } ECode Fragment::OnDestroy() { mCalled = TRUE; //Log.v("foo", "onDestroy: mCheckedForLoaderManager=" + mCheckedForLoaderManager // + " mLoaderManager=" + mLoaderManager); if (!mCheckedForLoaderManager) { mCheckedForLoaderManager = TRUE; AutoPtr<Activity> act = (Activity*)mActivity; mLoaderManager = act->GetLoaderManager(mWho, mLoadersStarted, FALSE); } if (mLoaderManager != NULL) { assert(0 && "TODO"); //((LoaderManagerImpl*)mLoaderManager.Get())->DoStart(); } return NOERROR; } ECode Fragment::InitState() { mIndex = -1; mWho = NULL; mAdded = FALSE; mRemoving = FALSE; mResumed = FALSE; mFromLayout = FALSE; mInLayout = FALSE; mRestored = FALSE; mBackStackNesting = 0; mFragmentManager = NULL; mChildFragmentManager = NULL; mActivity = NULL; mFragmentId = 0; mContainerId = 0; mTag = NULL; mHidden = FALSE; mDetached = FALSE; mRetaining = FALSE; mLoaderManager = NULL; mLoadersStarted = FALSE; mCheckedForLoaderManager = FALSE; return NOERROR; } ECode Fragment::OnDetach() { mCalled = TRUE; return NOERROR; } ECode Fragment::OnCreateOptionsMenu( /* [in] */ IMenu* menu, /* [in] */ IMenuInflater* inflater) { return NOERROR; } ECode Fragment::OnPrepareOptionsMenu( /* [in] */ IMenu* menu) { return NOERROR; } ECode Fragment::OnDestroyOptionsMenu() { return NOERROR; } ECode Fragment::OnOptionsItemSelected( /* [in] */ IMenuItem* item, /* [out] */ Boolean* selected) { VALIDATE_NOT_NULL(selected); *selected = FALSE; return NOERROR; } ECode Fragment::OnOptionsMenuClosed( /* [in] */ IMenu* menu) { return NOERROR; } ECode Fragment::OnCreateContextMenu( /* [in] */ IContextMenu* menu, /* [in] */ IView* v, /* [in] */ IContextMenuInfo* menuInfo) { AutoPtr<IActivity> activity; GetActivity((IActivity**)&activity); activity->OnCreateContextMenu(menu, v, menuInfo); return NOERROR; } ECode Fragment::RegisterForContextMenu( /* [in] */ IView* view) { return view->SetOnCreateContextMenuListener(mViewCreateContextMenuListener); } ECode Fragment::UnregisterForContextMenu( /* [in] */ IView* view) { return view->SetOnCreateContextMenuListener(NULL); } ECode Fragment::OnContextItemSelected( /* [in] */ IMenuItem* item, /* [out] */ Boolean* selected) { VALIDATE_NOT_NULL(selected); *selected = FALSE; return NOERROR; } ECode Fragment::SetEnterSharedElementCallback( /* [in] */ ISharedElementCallback* callback) { mEnterTransitionCallback = callback; if (mEnterTransitionCallback == NULL) { mEnterTransitionCallback = SharedElementCallback::NULL_CALLBACK; } return NOERROR; } ECode Fragment::SetEnterSharedElementTransitionCallback( /* [in] */ ISharedElementCallback* callback) { return SetEnterSharedElementCallback(callback); } ECode Fragment::SetExitSharedElementCallback( /* [in] */ ISharedElementCallback* callback) { mExitTransitionCallback = callback; if (mExitTransitionCallback == NULL) { mExitTransitionCallback = SharedElementCallback::NULL_CALLBACK; } return NOERROR; } ECode Fragment::SetExitSharedElementTransitionCallback( /* [in] */ ISharedElementCallback* callback) { return SetExitSharedElementCallback(callback); } ECode Fragment::SetEnterTransition( /* [in] */ ITransition* transition) { mEnterTransition = transition; return NOERROR; } ECode Fragment::GetEnterTransition( /* [out] */ ITransition** transition) { VALIDATE_NOT_NULL(transition) *transition = mEnterTransition; REFCOUNT_ADD(*transition) return NOERROR; } ECode Fragment::SetReturnTransition( /* [in] */ ITransition* transition) { mReturnTransition = transition; return NOERROR; } ECode Fragment::GetReturnTransition( /* [out] */ ITransition** transition) { VALIDATE_NOT_NULL(transition) if (mReturnTransition == USE_DEFAULT_TRANSITION) { return GetEnterTransition(transition); } else { *transition = mReturnTransition; REFCOUNT_ADD(*transition) } return NOERROR; } ECode Fragment::SetExitTransition( /* [in] */ ITransition* transition) { mExitTransition = transition; return NOERROR; } ECode Fragment::GetExitTransition( /* [out] */ ITransition** transition) { VALIDATE_NOT_NULL(transition) *transition = mExitTransition; REFCOUNT_ADD(*transition) return NOERROR; } ECode Fragment::SetReenterTransition( /* [in] */ ITransition* transition) { mReenterTransition = transition; return NOERROR; } ECode Fragment::GetReenterTransition( /* [out] */ ITransition** transition) { VALIDATE_NOT_NULL(transition) if (mReenterTransition == USE_DEFAULT_TRANSITION) { return GetExitTransition(transition); } else { *transition = mReenterTransition; REFCOUNT_ADD(*transition) } return NOERROR; } ECode Fragment::SetSharedElementEnterTransition( /* [in] */ ITransition* transition) { mSharedElementEnterTransition = transition; return NOERROR; } ECode Fragment::GetSharedElementEnterTransition( /* [out] */ ITransition** transition) { VALIDATE_NOT_NULL(transition) *transition = mSharedElementEnterTransition; REFCOUNT_ADD(*transition) return NOERROR; } ECode Fragment::SetSharedElementReturnTransition( /* [in] */ ITransition* transition) { mSharedElementReturnTransition = transition; return NOERROR; } ECode Fragment::GetSharedElementReturnTransition( /* [out] */ ITransition** transition) { VALIDATE_NOT_NULL(transition) if (mSharedElementReturnTransition == USE_DEFAULT_TRANSITION) { return GetSharedElementEnterTransition(transition); } else { *transition = mSharedElementReturnTransition; REFCOUNT_ADD(*transition) } return NOERROR; } ECode Fragment::SetAllowEnterTransitionOverlap( /* [in] */ Boolean allow) { mAllowEnterTransitionOverlap = allow; return NOERROR; } ECode Fragment::GetAllowEnterTransitionOverlap( /* [out] */ Boolean* allow) { return mAllowEnterTransitionOverlap; } ECode Fragment::SetAllowReturnTransitionOverlap( /* [in] */ Boolean allow) { mAllowReturnTransitionOverlap = allow; return NOERROR; } ECode Fragment::GetAllowReturnTransitionOverlap( /* [out] */ Boolean* allow) { VALIDATE_NOT_NULL(allow) *allow = mAllowReturnTransitionOverlap; return NOERROR; } ECode Fragment::Dump( /* [in] */ const String& prefix, /* [in] */ IFileDescriptor* fd, /* [in] */ IPrintWriter* writer, /* [in] */ ArrayOf<String>* args) { writer->Print(prefix); writer->Print(String("mFragmentId=#")); // writer.print(Integer.toHexString(mFragmentId)); writer->Print(String(" mContainerId=#")); // writer.print(Integer.toHexString(mContainerId)); writer->Print(String(" mTag=")); writer->Println(mTag); writer->Print(prefix); writer->Print(String("mState=")); writer->Print(mState); writer->Print(String(" mIndex=")); writer->Print(mIndex); writer->Print(String(" mWho=")); writer->Print(mWho); writer->Print(String(" mBackStackNesting=")); writer->Println(mBackStackNesting); writer->Print(prefix); writer->Print(String("mAdded=")); writer->Print(mAdded); writer->Print(String(" mRemoving=")); writer->Print(mRemoving); writer->Print(String(" mResumed=")); writer->Print(mResumed); writer->Print(String(" mFromLayout=")); writer->Print(mFromLayout); writer->Print(String(" mInLayout=")); writer->Println(mInLayout); writer->Print(prefix); writer->Print(String("mHidden=")); writer->Print(mHidden); writer->Print(String(" mDetached=")); writer->Print(mDetached); writer->Print(String(" mMenuVisible=")); writer->Print(mMenuVisible); writer->Print(String(" mHasMenu=")); writer->Println(mHasMenu); writer->Print(prefix); writer->Print(String("mRetainInstance=")); writer->Print(mRetainInstance); writer->Print(String(" mRetaining=")); writer->Print(mRetaining); writer->Print(String(" mUserVisibleHint=")); writer->Println(mUserVisibleHint); if (mFragmentManager != NULL) { writer->Print(prefix); writer->Print(String("mFragmentManager=")); writer->Println((IInterface*)mFragmentManager); } if (mActivity != NULL) { writer->Print(prefix); writer->Print(String("mActivity=")); writer->Println(mActivity); } if (mParentFragment != NULL) { writer->Print(prefix); writer->Print(String("mParentFragment=")); writer->Println(mParentFragment); } if (mArguments != NULL) { writer->Print(prefix); writer->Print(String("mArguments=")); writer->Println(mArguments.Get()); } if (mSavedFragmentState != NULL) { writer->Print(prefix); writer->Print(String("mSavedFragmentState=")); writer->Println(mSavedFragmentState.Get()); } if (mSavedViewState != NULL) { writer->Print(prefix); writer->Print(String("mSavedViewState=")); writer->Println(mSavedViewState.Get()); } if (mTarget != NULL) { writer->Print(prefix); writer->Print(String("mTarget=")); writer->Print((IInterface*)mTarget); writer->Print(String(" mTargetRequestCode=")); writer->Println(mTargetRequestCode); } if (mNextAnim != 0) { writer->Print(prefix); writer->Print(String("mNextAnim=")); writer->Println(mNextAnim); } if (mContainer != NULL) { writer->Print(prefix); writer->Print(String("mContainer=")); writer->Println(mContainer.Get()); } if (mView != NULL) { writer->Print(prefix); writer->Print(String("mView=")); writer->Println(mView.Get()); } if (mAnimatingAway != NULL) { writer->Print(prefix); writer->Print(String("mAnimatingAway=")); writer->Println(mAnimatingAway.Get()); writer->Print(prefix); writer->Print(String("mStateAfterAnimating=")); writer->Println(mStateAfterAnimating); } if (mLoaderManager != NULL) { writer->Print(prefix); writer->Println(String("Loader Manager:")); ILoaderManager::Probe(mLoaderManager)->Dump(prefix + " ", fd, writer, args); } if (mChildFragmentManager != NULL) { StringBuilder sb("Child "); sb += mChildFragmentManager; sb += ":"; writer->Print(prefix); writer->Println(sb.ToString()); IFragmentManager::Probe(mChildFragmentManager)->Dump(prefix + " ", fd, writer, args); } return NOERROR; } ECode Fragment::FindFragmentByWho( /* [in] */ const String& who, /* [out] */ IFragment** f) { VALIDATE_NOT_NULL(f); if (who.Equals(mWho)) { *f = this; REFCOUNT_ADD(*f); return NOERROR; } if (mChildFragmentManager != NULL) { AutoPtr<IFragment> fragment; mChildFragmentManager->FindFragmentByWho(who, (IFragment**)&fragment); *f = fragment; REFCOUNT_ADD(*f); return NOERROR; } *f = NULL; return NOERROR; } void Fragment::InstantiateChildFragmentManager() { mChildFragmentManager = new FragmentManagerImpl(); AutoPtr<FragmentContainerLocal> fc = new FragmentContainerLocal(this); mChildFragmentManager->AttachActivity(mActivity, IFragmentContainer::Probe(fc), this); } ECode Fragment::PerformCreate( /* [in] */ IBundle* savedInstanceState) { if (mChildFragmentManager != NULL) { mChildFragmentManager->NoteStateNotSaved(); } mCalled = FALSE; OnCreate(savedInstanceState); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnCreate()"); return E_SUPER_NOT_CALLED_EXCEPTION; } if (savedInstanceState != NULL) { AutoPtr<IParcelable> p; savedInstanceState->GetParcelable(Activity::FRAGMENTS_TAG, (IParcelable**)&p); if (p != NULL) { if (mChildFragmentManager == NULL) { InstantiateChildFragmentManager(); } mChildFragmentManager->RestoreAllState(p, NULL); mChildFragmentManager->DispatchCreate(); } } return NOERROR; } ECode Fragment::PerformCreateView( /* [in] */ ILayoutInflater* inflater, /* [in] */ IViewGroup* container, /* [in] */ IBundle* savedInstanceState, /* [out] */ IView** v) { VALIDATE_NOT_NULL(v); if (mChildFragmentManager != NULL) { mChildFragmentManager->NoteStateNotSaved(); } AutoPtr<IView> view; OnCreateView(inflater, container, savedInstanceState, (IView**)&view); *v = view; REFCOUNT_ADD(*v); return NOERROR; } ECode Fragment::PerformActivityCreated( /* [in] */ IBundle* savedInstanceState) { if (mChildFragmentManager != NULL) { mChildFragmentManager->NoteStateNotSaved(); } mCalled = FALSE; OnActivityCreated(savedInstanceState); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnActivityCreated()"); return E_SUPER_NOT_CALLED_EXCEPTION; } if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchActivityCreated(); } return NOERROR; } ECode Fragment::PerformStart() { if (mChildFragmentManager != NULL) { mChildFragmentManager->NoteStateNotSaved(); Boolean hasexec; mChildFragmentManager->ExecPendingActions(&hasexec); } mCalled = FALSE; OnStart(); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnStart()"); return E_SUPER_NOT_CALLED_EXCEPTION; } if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchStart(); } if (mLoaderManager != NULL) { assert(0 && "TODO"); //((LoaderManagerImpl*)mLoaderManager.Get())->DoReportStart(); } return NOERROR; } ECode Fragment::PerformResume() { if (mChildFragmentManager != NULL) { mChildFragmentManager->NoteStateNotSaved(); Boolean hasexec; mChildFragmentManager->ExecPendingActions(&hasexec); } mCalled = FALSE; OnResume(); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnResume()"); return E_SUPER_NOT_CALLED_EXCEPTION; } if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchResume(); Boolean hasexec; mChildFragmentManager->ExecPendingActions(&hasexec); } return NOERROR; } ECode Fragment::PerformConfigurationChanged( /* [in] */ IConfiguration* newConfig) { OnConfigurationChanged(newConfig); if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchConfigurationChanged(newConfig); } return NOERROR; } ECode Fragment::PerformLowMemory() { OnLowMemory(); if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchLowMemory(); } return NOERROR; } ECode Fragment::PerformTrimMemory( /* [in] */ Int32 level) { OnTrimMemory(level); if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchTrimMemory(level); } return NOERROR; } ECode Fragment::PerformCreateOptionsMenu( /* [in] */ IMenu* menu, /* [in] */ IMenuInflater* inflater, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Boolean show = FALSE; if (!mHidden) { if (mHasMenu && mMenuVisible) { show = TRUE; OnCreateOptionsMenu(menu, inflater); } if (mChildFragmentManager != NULL) { Boolean dispatch; mChildFragmentManager->DispatchCreateOptionsMenu(menu, inflater, &dispatch); show |= dispatch; } } *result = show; return NOERROR; } ECode Fragment::PerformPrepareOptionsMenu( /* [in] */ IMenu* menu, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); Boolean show = FALSE; if (!mHidden) { if (mHasMenu && mMenuVisible) { show = TRUE; OnPrepareOptionsMenu(menu); } if (mChildFragmentManager != NULL) { Boolean dispatch; mChildFragmentManager->DispatchPrepareOptionsMenu(menu, &dispatch); show |= dispatch; } } *result = show; return NOERROR; } ECode Fragment::PerformOptionsItemSelected( /* [in] */ IMenuItem* item, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); if (!mHidden) { if (mHasMenu && mMenuVisible) { Boolean selected; OnOptionsItemSelected(item, &selected); if (selected) { *result = TRUE; return NOERROR; } } if (mChildFragmentManager != NULL) { Boolean itSelected; mChildFragmentManager->DispatchOptionsItemSelected(item, &itSelected); if (itSelected) { *result = TRUE; return NOERROR; } } } *result = FALSE; return NOERROR; } ECode Fragment::PerformContextItemSelected( /* [in] */ IMenuItem* item, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); if (!mHidden) { Boolean selected; OnContextItemSelected(item, &selected); if (selected) { *result = TRUE; return NOERROR; } if (mChildFragmentManager != NULL) { Boolean itSelected; mChildFragmentManager->DispatchContextItemSelected(item, &itSelected); if (itSelected) { *result = TRUE; return NOERROR; } } } *result = FALSE; return NOERROR; } ECode Fragment::PerformOptionsMenuClosed( /* [in] */ IMenu* menu) { if (!mHidden) { if (mHasMenu && mMenuVisible) { OnOptionsMenuClosed(menu); } if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchOptionsMenuClosed(menu); } } return NOERROR; } ECode Fragment::PerformSaveInstanceState( /* [in] */ IBundle* outState) { OnSaveInstanceState(outState); if (mChildFragmentManager != NULL) { AutoPtr<IParcelable> p; mChildFragmentManager->SaveAllState((IParcelable**)&p); if (p != NULL) { outState->PutParcelable(Activity::FRAGMENTS_TAG, p); } } return NOERROR; } ECode Fragment::PerformPause() { if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchPause(); } mCalled = FALSE; OnPause(); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnPause()"); return E_SUPER_NOT_CALLED_EXCEPTION; } return NOERROR; } ECode Fragment::PerformStop() { if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchStop(); } mCalled = FALSE; OnStop(); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnStop()"); return E_SUPER_NOT_CALLED_EXCEPTION; } if (mLoadersStarted) { mLoadersStarted = FALSE; AutoPtr<Activity> act = (Activity*)mActivity; if (!mCheckedForLoaderManager) { mCheckedForLoaderManager = TRUE; mLoaderManager = act->GetLoaderManager(mWho, mLoadersStarted, FALSE); } if (mLoaderManager != NULL) { assert(0 && "TODO"); // if (mActivity == NULL || !act->mChangingConfigurations) { // ILoaderManager::Probe(mLoaderManager)->DoStop(); // } // else { // ILoaderManager::Probe(mLoaderManager)->DoRetain(); // } } } return NOERROR; } ECode Fragment::PerformDestroyView() { if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchDestroyView(); } mCalled = FALSE; OnDestroyView(); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnDestroyView()"); return E_SUPER_NOT_CALLED_EXCEPTION; } if (mLoaderManager != NULL) { assert(0 && "TODO"); // ((LoaderManagerImpl*)mLoaderManager.Get())->DoReportNextStart(); } return NOERROR; } ECode Fragment::PerformDestroy() { if (mChildFragmentManager != NULL) { mChildFragmentManager->DispatchDestroy(); } mCalled = FALSE; OnDestroy(); if (!mCalled) { Slogger::E(TAG, "Fragment did not call through to super::OnDestroy()"); return E_SUPER_NOT_CALLED_EXCEPTION; } return NOERROR; } AutoPtr<ITransition> Fragment::LoadTransition( /* [in] */ IContext* context, /* [in] */ ITypedArray* typedArray, /* [in] */ ITransition* currentValue, /* [in] */ ITransition* defaultValue, /* [in] */ Int32 id) { if (currentValue != defaultValue) { return currentValue; } Int32 transitionId; typedArray->GetResourceId(id, 0, &transitionId); AutoPtr<ITransition> transition = defaultValue; if (transitionId != 0 && transitionId != R::transition::no_transition) { AutoPtr<ITransitionInflater> inflater = TransitionInflater::From(context); transition = NULL; inflater->InflateTransition(transitionId, (ITransition**)&transition); ITransitionSet* ts = ITransitionSet::Probe(transition); if (ts != NULL) { Int32 count; ts->GetTransitionCount(&count); if (count == 0) { transition = NULL; } } } return transition; } } // namespace App } // namespace Droid } // namespace Elastos
25.352601
126
0.637076
jingcao80
875388a1f311e67c9a5dff0dedd1de9be7984990
876
cpp
C++
spec/cpp_stl_98/test_params_pass_array_int.cpp
DarkShadow44/kaitai_struct_tests
4bb13cef82965cca66dda2eb2b77cd64e9f70a12
[ "MIT" ]
11
2018-04-01T03:58:15.000Z
2021-08-14T09:04:55.000Z
spec/cpp_stl_98/test_params_pass_array_int.cpp
DarkShadow44/kaitai_struct_tests
4bb13cef82965cca66dda2eb2b77cd64e9f70a12
[ "MIT" ]
73
2016-07-20T10:27:15.000Z
2020-12-17T18:56:46.000Z
spec/cpp_stl_98/test_params_pass_array_int.cpp
DarkShadow44/kaitai_struct_tests
4bb13cef82965cca66dda2eb2b77cd64e9f70a12
[ "MIT" ]
37
2016-08-15T08:25:56.000Z
2021-08-28T14:48:46.000Z
// Autogenerated from KST: please remove this line if doing any edits by hand! #include <boost/test/unit_test.hpp> #include "params_pass_array_int.h" #include <iostream> #include <fstream> #include <vector> BOOST_AUTO_TEST_CASE(test_params_pass_array_int) { std::ifstream ifs("src/position_to_end.bin", std::ifstream::binary); kaitai::kstream ks(&ifs); params_pass_array_int_t* r = new params_pass_array_int_t(&ks); BOOST_CHECK_EQUAL(r->pass_ints()->nums()->size(), 3); BOOST_CHECK_EQUAL(r->pass_ints()->nums()->at(0), 513); BOOST_CHECK_EQUAL(r->pass_ints()->nums()->at(1), 1027); BOOST_CHECK_EQUAL(r->pass_ints()->nums()->at(2), 1541); BOOST_CHECK_EQUAL(r->pass_ints_calc()->nums()->size(), 2); BOOST_CHECK_EQUAL(r->pass_ints_calc()->nums()->at(0), 27643); BOOST_CHECK_EQUAL(r->pass_ints_calc()->nums()->at(1), 7); delete r; }
36.5
78
0.695205
DarkShadow44
87546f6abfb80b325f8a6b2457886b86016c83a8
918
cpp
C++
aws-cpp-sdk-wellarchitected/source/model/UpgradeLensReviewRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-wellarchitected/source/model/UpgradeLensReviewRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-wellarchitected/source/model/UpgradeLensReviewRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/wellarchitected/model/UpgradeLensReviewRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::WellArchitected::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpgradeLensReviewRequest::UpgradeLensReviewRequest() : m_workloadIdHasBeenSet(false), m_lensAliasHasBeenSet(false), m_milestoneNameHasBeenSet(false), m_clientRequestTokenHasBeenSet(false) { } Aws::String UpgradeLensReviewRequest::SerializePayload() const { JsonValue payload; if(m_milestoneNameHasBeenSet) { payload.WithString("MilestoneName", m_milestoneName); } if(m_clientRequestTokenHasBeenSet) { payload.WithString("ClientRequestToken", m_clientRequestToken); } return payload.View().WriteReadable(); }
20.4
69
0.761438
perfectrecall
8759450edf0914156ea45d95387556e618c96a60
5,320
hpp
C++
src/musicpp/Enums.hpp
Cannedfood/musicpp
e2ba4337f7a434533ad15a2b4ce3c2d2a767c4ee
[ "Zlib" ]
null
null
null
src/musicpp/Enums.hpp
Cannedfood/musicpp
e2ba4337f7a434533ad15a2b4ce3c2d2a767c4ee
[ "Zlib" ]
null
null
null
src/musicpp/Enums.hpp
Cannedfood/musicpp
e2ba4337f7a434533ad15a2b4ce3c2d2a767c4ee
[ "Zlib" ]
null
null
null
// Copyright 2018 Benno Straub, Licensed under the MIT License, a copy can be found at the bottom of this file. #pragma once #include <string_view> #include <array> #include <stdexcept> namespace music { enum Accidental : int8_t { FLAT = -1, NATURAL = 0, SHARP = 1, }; enum Chroma : int8_t { C = 0, Cs = 1, D = 2, Db = Cs, Ds = 3, E = 4, Eb = Ds, F = 5, Fb = E, Fs = 6, Gb = Fs, G = 7, Gs = 8, Ab = Gs, A = 9, As = 10, Bb = As, B = 11, }; namespace detail { constexpr inline int negativeModulo(int a, int b) { int result = a % b; if(result < 0) result += b; return result; } } constexpr inline Chroma operator+ (Chroma v, int interval) noexcept { return Chroma(detail::negativeModulo(int(v) + interval, 12)); } constexpr inline Chroma operator- (Chroma v, int interval) noexcept { return Chroma(detail::negativeModulo(int(v) - interval, 12)); } constexpr inline Chroma operator+=(Chroma& v, int interval) noexcept { return v = v + interval; } constexpr inline Chroma operator-=(Chroma& v, int interval) noexcept { return v = v - interval; } constexpr inline bool not_sharp_or_flat(Chroma note) { switch(note){ case A: case B: case C: case D: case E: case F: case G: return true; default: return false; } } enum Interval : int { prime = 0, min2nd = 1, maj2nd = 2, min3rd = 3, m = 3, maj3rd = 4, M = 4, perf4th = 5, aug4th = 6, dim5th = 6, perf5th = 7, aug5th = 8, min6th = 8, maj6th = 9, min7th = 10, maj7th = 11, octave = 12, min9th = 13, maj9th = 14, min10th = 15, maj10th = 16, perf11th = 17, aug11th = 18, dim12th = 18, pref12th = 19, }; constexpr inline Interval operator- (Chroma a, Chroma b) noexcept { return Interval(detail::negativeModulo(int(a) - int(b), 12)); } constexpr inline std::string_view to_string(Chroma value, Accidental hint = NATURAL) noexcept { if(hint == NATURAL) hint = SHARP; switch(value) { case C: return "C"; case Cs: return hint==SHARP?"C#":"Db"; case D: return "D"; case Ds: return hint==SHARP?"D#":"Eb"; case E: return "E"; case F: return "F"; case Fs: return hint==SHARP?"F#":"Gb"; case G: return "G"; case Gs: return hint==SHARP?"G#":"Ab"; case A: return "A"; case As: return hint==SHARP?"A#":"Bb"; case B: return "B"; } } constexpr inline Chroma from_string(std::string_view s, Accidental alter = NATURAL) { if(s == "C") return Chroma::C + alter; if(s == "C#") return Chroma::Cs + alter; if(s == "Cb") return Chroma::B + alter; if(s == "D") return Chroma::D + alter; if(s == "D#") return Chroma::Db + alter; if(s == "Db") return Chroma::Ds + alter; if(s == "E") return Chroma::E + alter; if(s == "E#") return Chroma::F + alter; if(s == "Eb") return Chroma::Eb + alter; if(s == "F") return Chroma::F + alter; if(s == "F#") return Chroma::Fs + alter; if(s == "Fb") return Chroma::Fb + alter; if(s == "G") return Chroma::G + alter; if(s == "G#") return Chroma::Gs + alter; if(s == "Gb") return Chroma::Gb + alter; if(s == "A") return Chroma::A + alter; if(s == "A#") return Chroma::As + alter; if(s == "Ab") return Chroma::Ab + alter; if(s == "B") return Chroma::B + alter; if(s == "B#") return Chroma::C + alter; if(s == "Bb") return Chroma::Bb + alter; throw std::runtime_error("Failed parsing Chroma"); } constexpr inline std::string_view to_string(Interval ivl, Accidental hint = NATURAL) noexcept { if(hint == NATURAL) hint = SHARP; switch(ivl) { case prime: return "1st"; case min2nd: return "m2nd"; case maj2nd: return "2nd"; case min3rd: return "m3rd"; case maj3rd: return "3rd"; case perf4th: return "4th"; case aug4th: return "aug. 4th"; case perf5th: return "5th"; case aug5th: return "aug. 5th"; case maj6th: return "6th"; case min7th: return "m7th"; case maj7th: return "7th"; case octave: return "octave"; case min9th: return "m9th"; case maj9th: return "9th"; case min10th: return "m10th"; case maj10th: return "10th"; case perf11th: return "11th"; case aug11th: return "aug. 11th"; default: return "?"; } } } // namespace music // The MIT License (MIT) // Copyright (c) 2018 Benno Straub // 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.
29.72067
134
0.641729
Cannedfood
87598f7bc09dea23ca6541153d611f55b7056819
1,209
hpp
C++
Questless/Questless/src/entities/beings/world_view.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
2
2020-07-14T12:50:06.000Z
2020-11-04T02:25:09.000Z
Questless/Questless/src/entities/beings/world_view.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
Questless/Questless/src/entities/beings/world_view.hpp
jonathansharman/questless
bb9ffb2d21cbfde2a71edfecfcbf466479bbbe7d
[ "MIT" ]
null
null
null
//! @file //! @copyright See <a href="LICENSE.txt">LICENSE.txt</a>. #pragma once #include "entities/perception.hpp" #include "world/coordinates.hpp" #include "world/section.hpp" #include <array> #include <optional> #include <variant> #include <vector> namespace ql { struct being; //! Represents everything an agent can perceive about its being's environment. struct world_view { struct tile_view { id id; perception perception; // Position is included here (redundantly) for efficiency because it's required in various places. view::point position; }; struct entity_view { id id; perception perception; // Position is included here (redundantly) for efficiency because it's required in various places. view::point position; }; std::vector<tile_view> tile_views; std::vector<entity_view> entity_views; location center; pace visual_range; //! Constructs the world view of the being with id @p viewer_id. world_view(ql::reg& reg, id viewer_id); world_view(world_view const&) = default; world_view(world_view&&) = default; auto operator=(world_view const&) -> world_view& = default; auto operator=(world_view &&) -> world_view& = default; }; }
23.705882
101
0.71464
jonathansharman
875ab16c3dd7f896c3070d86b35a4716c0a14c78
25,678
cpp
C++
qtimageformats/src/plugins/imageformats/tiff/qtiffhandler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtimageformats/src/plugins/imageformats/tiff/qtiffhandler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtimageformats/src/plugins/imageformats/tiff/qtiffhandler.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtiffhandler_p.h" #include <qvariant.h> #include <qdebug.h> #include <qimage.h> #include <qglobal.h> extern "C" { #include "tiffio.h" } QT_BEGIN_NAMESPACE tsize_t qtiffReadProc(thandle_t fd, tdata_t buf, tsize_t size) { QIODevice *device = static_cast<QIODevice *>(fd); return device->isReadable() ? device->read(static_cast<char *>(buf), size) : -1; } tsize_t qtiffWriteProc(thandle_t fd, tdata_t buf, tsize_t size) { return static_cast<QIODevice *>(fd)->write(static_cast<char *>(buf), size); } toff_t qtiffSeekProc(thandle_t fd, toff_t off, int whence) { QIODevice *device = static_cast<QIODevice *>(fd); switch (whence) { case SEEK_SET: device->seek(off); break; case SEEK_CUR: device->seek(device->pos() + off); break; case SEEK_END: device->seek(device->size() + off); break; } return device->pos(); } int qtiffCloseProc(thandle_t /*fd*/) { return 0; } toff_t qtiffSizeProc(thandle_t fd) { return static_cast<QIODevice *>(fd)->size(); } int qtiffMapProc(thandle_t /*fd*/, tdata_t* /*pbase*/, toff_t* /*psize*/) { return 0; } void qtiffUnmapProc(thandle_t /*fd*/, tdata_t /*base*/, toff_t /*size*/) { } class QTiffHandlerPrivate { public: QTiffHandlerPrivate(); ~QTiffHandlerPrivate(); static bool canRead(QIODevice *device); bool openForRead(QIODevice *device); bool readHeaders(QIODevice *device); void close(); TIFF *tiff; int compression; QImageIOHandler::Transformations transformation; QImage::Format format; QSize size; uint16 photometric; bool grayscale; bool headersRead; }; static QImageIOHandler::Transformations exif2Qt(int exifOrientation) { switch (exifOrientation) { case 1: // normal return QImageIOHandler::TransformationNone; case 2: // mirror horizontal return QImageIOHandler::TransformationMirror; case 3: // rotate 180 return QImageIOHandler::TransformationRotate180; case 4: // mirror vertical return QImageIOHandler::TransformationFlip; case 5: // mirror horizontal and rotate 270 CW return QImageIOHandler::TransformationFlipAndRotate90; case 6: // rotate 90 CW return QImageIOHandler::TransformationRotate90; case 7: // mirror horizontal and rotate 90 CW return QImageIOHandler::TransformationMirrorAndRotate90; case 8: // rotate 270 CW return QImageIOHandler::TransformationRotate270; } qWarning("Invalid EXIF orientation"); return QImageIOHandler::TransformationNone; } static int qt2Exif(QImageIOHandler::Transformations transformation) { switch (transformation) { case QImageIOHandler::TransformationNone: return 1; case QImageIOHandler::TransformationMirror: return 2; case QImageIOHandler::TransformationRotate180: return 3; case QImageIOHandler::TransformationFlip: return 4; case QImageIOHandler::TransformationFlipAndRotate90: return 5; case QImageIOHandler::TransformationRotate90: return 6; case QImageIOHandler::TransformationMirrorAndRotate90: return 7; case QImageIOHandler::TransformationRotate270: return 8; } qWarning("Invalid Qt image transformation"); return 1; } QTiffHandlerPrivate::QTiffHandlerPrivate() : tiff(0) , compression(QTiffHandler::NoCompression) , transformation(QImageIOHandler::TransformationNone) , format(QImage::Format_Invalid) , photometric(false) , grayscale(false) , headersRead(false) { } QTiffHandlerPrivate::~QTiffHandlerPrivate() { close(); } void QTiffHandlerPrivate::close() { if (tiff) TIFFClose(tiff); tiff = 0; } bool QTiffHandlerPrivate::canRead(QIODevice *device) { if (!device) { qWarning("QTiffHandler::canRead() called with no device"); return false; } // current implementation uses TIFFClientOpen which needs to be // able to seek, so sequential devices are not supported QByteArray header = device->peek(4); return header == QByteArray::fromRawData("\x49\x49\x2A\x00", 4) || header == QByteArray::fromRawData("\x4D\x4D\x00\x2A", 4); } bool QTiffHandlerPrivate::openForRead(QIODevice *device) { if (tiff) return true; if (!canRead(device)) return false; tiff = TIFFClientOpen("foo", "r", device, qtiffReadProc, qtiffWriteProc, qtiffSeekProc, qtiffCloseProc, qtiffSizeProc, qtiffMapProc, qtiffUnmapProc); if (!tiff) { return false; } uint32 width; uint32 height; if (!TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width) || !TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height) || !TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric)) { close(); return false; } size = QSize(width, height); uint16 orientationTag; if (TIFFGetField(tiff, TIFFTAG_ORIENTATION, &orientationTag)) transformation = exif2Qt(orientationTag); // BitsPerSample defaults to 1 according to the TIFF spec. uint16 bitPerSample; if (!TIFFGetField(tiff, TIFFTAG_BITSPERSAMPLE, &bitPerSample)) bitPerSample = 1; uint16 samplesPerPixel; // they may be e.g. grayscale with 2 samples per pixel if (!TIFFGetField(tiff, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel)) samplesPerPixel = 1; grayscale = photometric == PHOTOMETRIC_MINISBLACK || photometric == PHOTOMETRIC_MINISWHITE; if (grayscale && bitPerSample == 1 && samplesPerPixel == 1) format = QImage::Format_Mono; else if (photometric == PHOTOMETRIC_MINISBLACK && bitPerSample == 8 && samplesPerPixel == 1) format = QImage::Format_Grayscale8; else if ((grayscale || photometric == PHOTOMETRIC_PALETTE) && bitPerSample == 8 && samplesPerPixel == 1) format = QImage::Format_Indexed8; else if (samplesPerPixel < 4) format = QImage::Format_RGB32; else { uint16 count; uint16 *extrasamples; // If there is any definition of the alpha-channel, libtiff will return premultiplied // data to us. If there is none, libtiff will not touch it and we assume it to be // non-premultiplied, matching behavior of tested image editors, and how older Qt // versions used to save it. bool gotField = TIFFGetField(tiff, TIFFTAG_EXTRASAMPLES, &count, &extrasamples); if (!gotField || !count || extrasamples[0] == EXTRASAMPLE_UNSPECIFIED) format = QImage::Format_ARGB32; else format = QImage::Format_ARGB32_Premultiplied; } headersRead = true; return true; } bool QTiffHandlerPrivate::readHeaders(QIODevice *device) { if (headersRead) return true; return openForRead(device); } QTiffHandler::QTiffHandler() : QImageIOHandler() , d(new QTiffHandlerPrivate) { } bool QTiffHandler::canRead() const { if (d->tiff) return true; if (QTiffHandlerPrivate::canRead(device())) { setFormat("tiff"); return true; } return false; } bool QTiffHandler::canRead(QIODevice *device) { return QTiffHandlerPrivate::canRead(device); } bool QTiffHandler::read(QImage *image) { // Open file and read headers if it hasn't already been done. if (!d->openForRead(device())) return false; QImage::Format format = d->format; if (format == QImage::Format_RGB32 && (image->format() == QImage::Format_ARGB32 || image->format() == QImage::Format_ARGB32_Premultiplied)) format = image->format(); if (image->size() != d->size || image->format() != format) *image = QImage(d->size, format); TIFF *const tiff = d->tiff; const uint32 width = d->size.width(); const uint32 height = d->size.height(); if (format == QImage::Format_Mono) { QVector<QRgb> colortable(2); if (d->photometric == PHOTOMETRIC_MINISBLACK) { colortable[0] = 0xff000000; colortable[1] = 0xffffffff; } else { colortable[0] = 0xffffffff; colortable[1] = 0xff000000; } image->setColorTable(colortable); if (!image->isNull()) { for (uint32 y=0; y<height; ++y) { if (TIFFReadScanline(tiff, image->scanLine(y), y, 0) < 0) { d->close(); return false; } } } } else { if (format == QImage::Format_Indexed8) { if (!image->isNull()) { const uint16 tableSize = 256; QVector<QRgb> qtColorTable(tableSize); if (d->grayscale) { for (int i = 0; i<tableSize; ++i) { const int c = (d->photometric == PHOTOMETRIC_MINISBLACK) ? i : (255 - i); qtColorTable[i] = qRgb(c, c, c); } } else { // create the color table uint16 *redTable = 0; uint16 *greenTable = 0; uint16 *blueTable = 0; if (!TIFFGetField(tiff, TIFFTAG_COLORMAP, &redTable, &greenTable, &blueTable)) { d->close(); return false; } if (!redTable || !greenTable || !blueTable) { d->close(); return false; } for (int i = 0; i<tableSize ;++i) { const int red = redTable[i] / 257; const int green = greenTable[i] / 257; const int blue = blueTable[i] / 257; qtColorTable[i] = qRgb(red, green, blue); } } image->setColorTable(qtColorTable); for (uint32 y=0; y<height; ++y) { if (TIFFReadScanline(tiff, image->scanLine(y), y, 0) < 0) { d->close(); return false; } } // free redTable, greenTable and greenTable done by libtiff } } else if (format == QImage::Format_Grayscale8) { if (!image->isNull()) { for (uint32 y = 0; y < height; ++y) { if (TIFFReadScanline(tiff, image->scanLine(y), y, 0) < 0) { d->close(); return false; } } } } else { if (!image->isNull()) { const int stopOnError = 1; if (TIFFReadRGBAImageOriented(tiff, width, height, reinterpret_cast<uint32 *>(image->bits()), qt2Exif(d->transformation), stopOnError)) { for (uint32 y=0; y<height; ++y) convert32BitOrder(image->scanLine(y), width); } else { d->close(); return false; } } } } if (image->isNull()) { d->close(); return false; } float resX = 0; float resY = 0; uint16 resUnit; if (!TIFFGetField(tiff, TIFFTAG_RESOLUTIONUNIT, &resUnit)) resUnit = RESUNIT_INCH; if (TIFFGetField(tiff, TIFFTAG_XRESOLUTION, &resX) && TIFFGetField(tiff, TIFFTAG_YRESOLUTION, &resY)) { switch(resUnit) { case RESUNIT_CENTIMETER: image->setDotsPerMeterX(qRound(resX * 100)); image->setDotsPerMeterY(qRound(resY * 100)); break; case RESUNIT_INCH: image->setDotsPerMeterX(qRound(resX * (100 / 2.54))); image->setDotsPerMeterY(qRound(resY * (100 / 2.54))); break; default: // do nothing as defaults have already // been set within the QImage class break; } } d->close(); return true; } static bool checkGrayscale(const QVector<QRgb> &colorTable) { if (colorTable.size() != 256) return false; const bool increasing = (colorTable.at(0) == 0xff000000); for (int i = 0; i < 256; ++i) { if ((increasing && colorTable.at(i) != qRgb(i, i, i)) || (!increasing && colorTable.at(i) != qRgb(255 - i, 255 - i, 255 - i))) return false; } return true; } static QVector<QRgb> effectiveColorTable(const QImage &image) { QVector<QRgb> colors; switch (image.format()) { case QImage::Format_Indexed8: colors = image.colorTable(); break; case QImage::Format_Alpha8: colors.resize(256); for (int i = 0; i < 256; ++i) colors[i] = qRgba(0, 0, 0, i); break; case QImage::Format_Grayscale8: colors.resize(256); for (int i = 0; i < 256; ++i) colors[i] = qRgb(i, i, i); break; default: Q_UNREACHABLE(); } return colors; } bool QTiffHandler::write(const QImage &image) { if (!device()->isWritable()) return false; TIFF *const tiff = TIFFClientOpen("foo", "wB", device(), qtiffReadProc, qtiffWriteProc, qtiffSeekProc, qtiffCloseProc, qtiffSizeProc, qtiffMapProc, qtiffUnmapProc); if (!tiff) return false; const int width = image.width(); const int height = image.height(); const int compression = d->compression; if (!TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width) || !TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height) || !TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) { TIFFClose(tiff); return false; } // set the resolution bool resolutionSet = false; const int dotPerMeterX = image.dotsPerMeterX(); const int dotPerMeterY = image.dotsPerMeterY(); if ((dotPerMeterX % 100) == 0 && (dotPerMeterY % 100) == 0) { resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER) && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, dotPerMeterX/100.0) && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, dotPerMeterY/100.0); } else { resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH) && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, static_cast<float>(image.logicalDpiX())) && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, static_cast<float>(image.logicalDpiY())); } if (!resolutionSet) { TIFFClose(tiff); return false; } // set the orienataion bool orientationSet = false; orientationSet = TIFFSetField(tiff, TIFFTAG_ORIENTATION, qt2Exif(d->transformation)); if (!orientationSet) { TIFFClose(tiff); return false; } // configure image depth const QImage::Format format = image.format(); if (format == QImage::Format_Mono || format == QImage::Format_MonoLSB) { uint16 photometric = PHOTOMETRIC_MINISBLACK; if (image.colorTable().at(0) == 0xffffffff) photometric = PHOTOMETRIC_MINISWHITE; if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric) || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_CCITTRLE) || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 1)) { TIFFClose(tiff); return false; } // try to do the conversion in chunks no greater than 16 MB int chunks = (width * height / (1024 * 1024 * 16)) + 1; int chunkHeight = qMax(height / chunks, 1); int y = 0; while (y < height) { QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(QImage::Format_Mono); int chunkStart = y; int chunkEnd = y + chunk.height(); while (y < chunkEnd) { if (TIFFWriteScanline(tiff, reinterpret_cast<uint32 *>(chunk.scanLine(y - chunkStart)), y) != 1) { TIFFClose(tiff); return false; } ++y; } } TIFFClose(tiff); } else if (format == QImage::Format_Indexed8 || format == QImage::Format_Grayscale8 || format == QImage::Format_Alpha8) { QVector<QRgb> colorTable = effectiveColorTable(image); bool isGrayscale = checkGrayscale(colorTable); if (isGrayscale) { uint16 photometric = PHOTOMETRIC_MINISBLACK; if (colorTable.at(0) == 0xffffffff) photometric = PHOTOMETRIC_MINISWHITE; if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric) || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_PACKBITS) || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)) { TIFFClose(tiff); return false; } } else { if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE) || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_PACKBITS) || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)) { TIFFClose(tiff); return false; } //// write the color table // allocate the color tables const int tableSize = colorTable.size(); Q_ASSERT(tableSize <= 256); QVarLengthArray<uint16> redTable(tableSize); QVarLengthArray<uint16> greenTable(tableSize); QVarLengthArray<uint16> blueTable(tableSize); // set the color table for (int i = 0; i<tableSize; ++i) { const QRgb color = colorTable.at(i); redTable[i] = qRed(color) * 257; greenTable[i] = qGreen(color) * 257; blueTable[i] = qBlue(color) * 257; } const bool setColorTableSuccess = TIFFSetField(tiff, TIFFTAG_COLORMAP, redTable.data(), greenTable.data(), blueTable.data()); if (!setColorTableSuccess) { TIFFClose(tiff); return false; } } //// write the data // try to do the conversion in chunks no greater than 16 MB int chunks = (width * height/ (1024 * 1024 * 16)) + 1; int chunkHeight = qMax(height / chunks, 1); int y = 0; while (y < height) { QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)); int chunkStart = y; int chunkEnd = y + chunk.height(); while (y < chunkEnd) { if (TIFFWriteScanline(tiff, reinterpret_cast<uint32 *>(chunk.scanLine(y - chunkStart)), y) != 1) { TIFFClose(tiff); return false; } ++y; } } TIFFClose(tiff); } else if (!image.hasAlphaChannel()) { if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB) || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW) || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 3) || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)) { TIFFClose(tiff); return false; } // try to do the RGB888 conversion in chunks no greater than 16 MB const int chunks = (width * height * 3 / (1024 * 1024 * 16)) + 1; const int chunkHeight = qMax(height / chunks, 1); int y = 0; while (y < height) { const QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(QImage::Format_RGB888); int chunkStart = y; int chunkEnd = y + chunk.height(); while (y < chunkEnd) { if (TIFFWriteScanline(tiff, (void*)chunk.scanLine(y - chunkStart), y) != 1) { TIFFClose(tiff); return false; } ++y; } } TIFFClose(tiff); } else { const bool premultiplied = image.format() != QImage::Format_ARGB32 && image.format() != QImage::Format_RGBA8888; const uint16 extrasamples = premultiplied ? EXTRASAMPLE_ASSOCALPHA : EXTRASAMPLE_UNASSALPHA; if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB) || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW) || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 4) || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8) || !TIFFSetField(tiff, TIFFTAG_EXTRASAMPLES, 1, &extrasamples)) { TIFFClose(tiff); return false; } // try to do the RGBA8888 conversion in chunks no greater than 16 MB const int chunks = (width * height * 4 / (1024 * 1024 * 16)) + 1; const int chunkHeight = qMax(height / chunks, 1); const QImage::Format format = premultiplied ? QImage::Format_RGBA8888_Premultiplied : QImage::Format_RGBA8888; int y = 0; while (y < height) { const QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(format); int chunkStart = y; int chunkEnd = y + chunk.height(); while (y < chunkEnd) { if (TIFFWriteScanline(tiff, (void*)chunk.scanLine(y - chunkStart), y) != 1) { TIFFClose(tiff); return false; } ++y; } } TIFFClose(tiff); } return true; } QByteArray QTiffHandler::name() const { return "tiff"; } QVariant QTiffHandler::option(ImageOption option) const { if (option == Size && canRead()) { if (d->readHeaders(device())) return d->size; } else if (option == CompressionRatio) { return d->compression; } else if (option == ImageFormat) { if (d->readHeaders(device())) return d->format; } else if (option == ImageTransformation) { if (d->readHeaders(device())) return int(d->transformation); } return QVariant(); } void QTiffHandler::setOption(ImageOption option, const QVariant &value) { if (option == CompressionRatio && value.type() == QVariant::Int) d->compression = value.toInt(); if (option == ImageTransformation) { int transformation = value.toInt(); if (transformation > 0 && transformation < 8) d->transformation = QImageIOHandler::Transformations(transformation); } } bool QTiffHandler::supportsOption(ImageOption option) const { return option == CompressionRatio || option == Size || option == ImageFormat || option == ImageTransformation || option == TransformedByDefault; } void QTiffHandler::convert32BitOrder(void *buffer, int width) { uint32 *target = reinterpret_cast<uint32 *>(buffer); for (int32 x=0; x<width; ++x) { uint32 p = target[x]; // convert between ARGB and ABGR target[x] = (p & 0xff000000) | ((p & 0x00ff0000) >> 16) | (p & 0x0000ff00) | ((p & 0x000000ff) << 16); } } QT_END_NAMESPACE
34.283044
153
0.571384
wgnet
87643dc47b33eb0417bee94f127e4e45c81716ff
417
hpp
C++
library/ATF/_force_result_other_zocl.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/_force_result_other_zocl.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/_force_result_other_zocl.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_CHRID.hpp> START_ATF_NAMESPACE struct _force_result_other_zocl { char byRetCode; char byForceIndex; char byForceLv; _CHRID idPerformer; _CHRID idDster; char byAttackSerial; }; END_ATF_NAMESPACE
21.947368
108
0.688249
lemkova
8766ad7e467125ea0d05c0ec58631a7ebe879e6c
10,339
hpp
C++
timer/timer.hpp
Spilleren/mega2560-hal
6531602e77cc94bb225e9df829e2f6d356ad00cf
[ "MIT" ]
null
null
null
timer/timer.hpp
Spilleren/mega2560-hal
6531602e77cc94bb225e9df829e2f6d356ad00cf
[ "MIT" ]
null
null
null
timer/timer.hpp
Spilleren/mega2560-hal
6531602e77cc94bb225e9df829e2f6d356ad00cf
[ "MIT" ]
null
null
null
#pragma once #include "interface_timer.hpp" #include "timer_configs.hpp" #include <stdint.h> namespace MEGA2560 { namespace Timer { template <typename config> class Device : public InterfaceTimer { public: static Device &instance() { static Device instance; return instance; } /* Timer created as a singleton object */ Device(const Device &) = delete; Device(Device &&) = delete; Device &operator=(const Device &) = delete; Device &operator=(Device &&) = delete; /* Initiate timer with default values - fast pwm - input_capture 40000 - prescaler 8 - compare value 1500 - non-inverting compare mode */ void init() { set_waveform_generation_mode(fast_pwm_input_top); set_input_capture(40000); set_prescaler(8); set_compare(1500); set_compare_output_mode(non_inverting); } /* Set compare output for all channels */ void set_compare_output_mode(compare_output_mode mode) { set_compare_output_mode(mode, output_channel::A); set_compare_output_mode(mode, output_channel::B); set_compare_output_mode(mode, output_channel::C); } /* Set compare output for specific channel */ void set_compare_output_mode(compare_output_mode mode, output_channel channel) { if (channel == A) { switch (mode) { case normal_compare: *config::TCCRA |= (0 << COM1A1) | (0 << COM1A0); break; case toggle: *config::TCCRA |= (0 << COM1A1) | (1 << COM1A0); break; case non_inverting: *config::TCCRA |= (1 << COM1A1) | (0 << COM1A0); break; case inverting: *config::TCCRA |= (1 << COM1A1) | (1 << COM1A0); break; default: *config::TCCRA |= (0 << COM1A1) | (0 << COM1A0); break; } } if (channel == B) { switch (mode) { case normal_compare: *config::TCCRA |= (0 << COM1B1) | (0 << COM1B0); break; case toggle: *config::TCCRA |= (0 << COM1B1) | (1 << COM1B0); break; case non_inverting: *config::TCCRA |= (1 << COM1B1) | (0 << COM1B0); break; case inverting: *config::TCCRA |= (1 << COM1B1) | (1 << COM1B0); break; default: *config::TCCRA |= (0 << COM1B1) | (0 << COM1B0); break; } } if (channel == C) { switch (mode) { case normal_compare: *config::TCCRA |= (0 << COM1C1) | (0 << COM1C0); break; case toggle: *config::TCCRA |= (0 << COM1C1) | (1 << COM1C0); break; case non_inverting: *config::TCCRA |= (1 << COM1C1) | (0 << COM1C0); break; case inverting: *config::TCCRA |= (1 << COM1C1) | (1 << COM1C0); break; default: *config::TCCRA |= (0 << COM1C1) | (0 << COM1C0); break; } } } /* Set waveform generation mode */ void set_waveform_generation_mode(waveform_mode mode) { switch (mode) { case normal_waveform: *config::TCCRA |= (0 << WGM11) | (0 << WGM10); *config::TCCRB |= (0 << WGM13) | (0 << WGM12); break; case pwm_phase_correct_8bit: *config::TCCRA |= (0 << WGM11) | (1 << WGM10); *config::TCCRB |= (0 << WGM13) | (0 << WGM12); break; case pwm_phase_correct_9bit: *config::TCCRA |= (1 << WGM11) | (0 << WGM10); *config::TCCRB |= (0 << WGM13) | (0 << WGM12); break; case pwm_phase_correct_10bit: *config::TCCRA |= (1 << WGM11) | (1 << WGM10); *config::TCCRB |= (0 << WGM13) | (0 << WGM12); break; case ctc_compare_top: *config::TCCRA |= (0 << WGM11) | (0 << WGM10); *config::TCCRB |= (0 << WGM13) | (1 << WGM12); break; case fast_pwm_8bit: *config::TCCRA |= (0 << WGM11) | (1 << WGM10); *config::TCCRB |= (0 << WGM13) | (1 << WGM12); break; case fast_pwm_9bit: *config::TCCRA |= (1 << WGM11) | (0 << WGM10); *config::TCCRB |= (0 << WGM13) | (1 << WGM12); break; case fast_pwm_10bit: *config::TCCRA |= (1 << WGM11) | (1 << WGM10); *config::TCCRB |= (0 << WGM13) | (1 << WGM12); break; case pwm_phase_freq_correct_input_top: *config::TCCRA |= (0 << WGM11) | (0 << WGM10); *config::TCCRB |= (1 << WGM13) | (0 << WGM12); break; case pwm_phase_freq_correct_compare_top: *config::TCCRA |= (0 << WGM11) | (1 << WGM10); *config::TCCRB |= (1 << WGM13) | (0 << WGM12); break; case pwm_phase_correct_input_top: *config::TCCRA |= (0 << WGM11) | (1 << WGM10); *config::TCCRB |= (1 << WGM13) | (0 << WGM12); break; case pwm_phase_correct_compare_top: *config::TCCRA |= (1 << WGM11) | (1 << WGM10); *config::TCCRB |= (1 << WGM13) | (0 << WGM12); break; case ctc_input_top: *config::TCCRA |= (0 << WGM11) | (0 << WGM10); *config::TCCRB |= (1 << WGM13) | (1 << WGM12); break; case fast_pwm_input_top: *config::TCCRA |= (1 << WGM11) | (0 << WGM10); *config::TCCRB |= (1 << WGM13) | (1 << WGM12); break; case fast_pwm_compare_top: *config::TCCRA |= (1 << WGM11) | (1 << WGM10); *config::TCCRB |= (1 << WGM13) | (1 << WGM12); break; default: break; } } /* Set prescaler to prefered value Input options are 0, 1, 8, 64, 256 and 1024 */ void set_prescaler(uint16_t prescaler) { switch (prescaler) { case 0: *config::TCCRB |= (0 << CS12) | (0 << CS11) | (0 << CS10); break; case 1: *config::TCCRB |= (0 << CS12) | (0 << CS11) | (1 << CS10); break; case 8: *config::TCCRB |= (0 << CS12) | (1 << CS11) | (0 << CS10); break; case 64: *config::TCCRB |= (0 << CS12) | (1 << CS11) | (1 << CS10); break; case 256: *config::TCCRB |= (1 << CS12) | (0 << CS11) | (0 << CS10); break; case 1024: *config::TCCRB |= (1 << CS12) | (0 << CS11) | (1 << CS10); break; default: *config::TCCRB |= (0 << CS12) | (0 << CS11) | (0 << CS10); break; } } /* Set compare value for specfic channel */ void set_compare(uint16_t value, output_channel output) { switch (output) { case A: *config::OCRA = value; break; case B: *config::OCRB = value; break; case C: *config::OCRC = value; break; default: break; } } /* Set compare value for all channels */ void set_compare(uint16_t value) { set_compare(value, output_channel::A); set_compare(value, output_channel::B); set_compare(value, output_channel::C); } void set_input_capture(uint16_t value) { *config::ICR |= value; } /* Enable interrupt type Input options are - input_capture - output_compare_c - output_compare_b - output_compare_a - timer_overflow */ void interrupt_type_enable(interrupt_type value) { // sei(); switch (value) { case input_capture: *config::TIMSK |= (1 << ICIE1); break; case output_compare_c: *config::TIMSK |= (1 << OCIE1C); break; case output_compare_b: *config::TIMSK |= (1 << OCIE1B); break; case output_compare_a: *config::TIMSK |= (1 << OCIE1A); break; case timer_overflow: *config::TIMSK |= (1 << TOIE1); break; default: break; } } /* Disable interrupt type Input options are - input_capture - output_compare_c - output_compare_b - output_compare_a - timer_overflow */ void interrupt_type_disable(interrupt_type type) { switch (type) { case input_capture: *config::TIMSK |= (0 << ICIE1); break; case output_compare_c: *config::TIMSK |= (0 << OCIE1C); break; case output_compare_b: *config::TIMSK |= (0 << OCIE1B); break; case output_compare_a: *config::TIMSK |= (0 << OCIE1A); break; case timer_overflow: *config::TIMSK |= (0 << TOIE1); break; default: break; } } /* Timer enable pwm channel A, B or C*/ void enable_pwm_pin(output_channel output) { switch (output) { case A: *config::DDR |= config::CHANNEL_A; break; case B: *config::DDR |= config::CHANNEL_B; break; case C: *config::DDR |= config::CHANNEL_C; break; default: break; } } private: Device() {} // no one else can create one ~Device() {} // prevent accidental deletion }; } // namespace Time }// namespace MEGA2560
29.042135
85
0.448303
Spilleren
8768db73f78cc62e57bb67a64c3c724de1ef50dd
3,131
cpp
C++
VideoPlayer/qtavvideowidget.cpp
wangpengcheng/OfflineMapTest
b1a28214fa4882589b3cf399669240b0ec3fc225
[ "Apache-2.0" ]
29
2019-03-30T23:30:36.000Z
2022-02-28T13:35:19.000Z
VideoPlayer/qtavvideowidget.cpp
wangpengcheng/OfflineMapTest
b1a28214fa4882589b3cf399669240b0ec3fc225
[ "Apache-2.0" ]
1
2019-06-30T12:59:06.000Z
2019-12-15T13:30:19.000Z
VideoPlayer/qtavvideowidget.cpp
wangpengcheng/OfflineMapTest
b1a28214fa4882589b3cf399669240b0ec3fc225
[ "Apache-2.0" ]
9
2019-03-24T12:41:09.000Z
2021-12-02T12:43:28.000Z
#include "qtavvideowidget.h" #include "QtAVWidgets/QtAVWidgets.h" #include "QtAV/AudioOutput.h" #include "MapItems/tool.h" QtAVVideoWidget::QtAVVideoWidget(QWidget *parent) : QWidget(parent) { //初始化相关数据 Init(); } QtAVVideoWidget::QtAVVideoWidget(QSharedPointer<QtAV::AVPlayer> new_player, QString new_vid) { av_player_ = new_player; vid = new_vid; Init(); av_player_->addVideoRenderer(this->video_render_); //绑定 } QtAVVideoWidget::QtAVVideoWidget(const QtAVVideoWidget &rhs) { if (this != &rhs) { /// TODO } } QtAVVideoWidget::~QtAVVideoWidget() { DELETE_OBJECT(video_render_); DELETE_QOBJECT(video_layer_out_); } void QtAVVideoWidget::Init() { //选择渲染模式。注意渲染模式一定要在初始化之前更改 QtAV::VideoDecoderId v = QtAV::VideoRendererId_Widget; if (vid == QLatin1String("gl")) { v = QtAV::VideoRendererId_GLWidget2; } else if (vid == QLatin1String("wg")) { v = QtAV::VideoRendererId_Widget; } else if (vid == QLatin1String("d2d")) { v = QtAV::VideoRendererId_Direct2D; } else if (vid == QLatin1String("gdi")) { v = QtAV::VideoRendererId_GDI; } else if (vid == QLatin1String("xv")) { v = QtAV::VideoRendererId_XV; } //创建渲染器 video_render_ = QtAV::VideoRenderer::create(v); video_render_->setRegionOfInterest(0, 0, 0, 0); //设置显示偏移为0; //创建水平布局 video_layer_out_ = new QHBoxLayout(this); video_layer_out_->setMargin(1); //设置边距 video_layer_out_->setSpacing(1); this->setLayout(video_layer_out_); //添加布局 //将显示输出绑定到布局 video_layer_out_->addWidget(video_render_->widget()); } void QtAVVideoWidget::ChangeVideoRender(QtAV::VideoRenderer *new_render) { if (new_render == video_render_) { qDebug() << "Same Render!!!!"; return; } if (av_player_.isNull()) { qDebug() << "Please set Player"; return; } else { QList<QtAV::VideoRenderer *> render_list = av_player_->videoOutputs(); if (render_list.isEmpty()) { //先将旧render从布局删除 video_layer_out_->replaceWidget(video_render_->widget(), new_render->widget()); DELETE_OBJECT(video_render_); this->video_render_ = new_render; av_player_->addVideoRenderer(video_render_); } if (render_list.contains(new_render)) { qDebug() << "this render is already in Playlist"; } else { video_layer_out_->replaceWidget(video_render_->widget(), new_render->widget()); av_player_->removeVideoRenderer(video_render_); DELETE_OBJECT(video_render_); video_render_ = new_render; av_player_->addVideoRenderer(video_render_); } } } //注意一定要先有再改 void QtAVVideoWidget::ChangeAVPlayer(QSharedPointer<QtAV::AVPlayer> new_player) { qDebug() << "start av player change"; if (!av_player_.isNull()) { av_player_->removeVideoRenderer(this->video_render_); } av_player_ = new_player; av_player_->addVideoRenderer(this->video_render_); }
27.464912
92
0.633663
wangpengcheng
876a03d24d6cbaca07ec59f4252627356f92f8fb
2,857
cpp
C++
suffix_array_long.cpp
agaitanis/strings
13688cc3e9007d0dadaf92feca198272e135fe60
[ "MIT" ]
2
2018-10-30T08:13:30.000Z
2019-03-05T22:49:40.000Z
suffix_array_long.cpp
agaitanis/strings
13688cc3e9007d0dadaf92feca198272e135fe60
[ "MIT" ]
null
null
null
suffix_array_long.cpp
agaitanis/strings
13688cc3e9007d0dadaf92feca198272e135fe60
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <string> #include <vector> #include <utility> #include <cassert> using namespace std; #define ALPHABET_SIZE 5 static void print_vec(const char *s, const vector<int> &vec) { cout << s << ": "; for (size_t i = 0; i < vec.size(); i++) { cout << vec[i] << " "; } cout << endl; } static int letter_to_index(char c) { switch (c) { case '$': return 0; case 'A': return 1; case 'C': return 2; case 'G': return 3; case 'T': return 4; default: assert(0); return 0; } } static vector<int> SortCharacters(const string &s) { int n = s.size(); vector<int> order(n); vector<int> cnt(ALPHABET_SIZE, 0); for (int i = 0; i < n; i++) { int c_i = letter_to_index(s[i]); cnt[c_i]++; } for (size_t j = 1; j < cnt.size(); j++) { cnt[j] += cnt[j-1]; } for (int i = n - 1; i >= 0; i--) { char c = letter_to_index(s[i]); cnt[c]--; order[cnt[c]] = i; } return order; } static vector<int> ComputeCharClasses(const string &s, const vector<int> &order) { int n = s.size(); vector<int> my_class(n); my_class[order[0]] = 0; for (size_t i = 1; i < n; i++) { if (s[order[i]] != s[order[i-1]]) { my_class[order[i]] = my_class[order[i-1]] + 1; } else { my_class[order[i]] = my_class[order[i-1]]; } } return my_class; } static vector<int> SortDoubled(const string &s, int L, const vector<int> &order, const vector<int> &my_class) { int n = s.size(); vector<int> cnt(n, 0); vector<int> new_order(n); for (int i = 0; i < n; i++) { cnt[my_class[i]]++; } for (int j = 1; j < n; j++) { cnt[j] += cnt[j-1]; } for (int i = n - 1; i >= 0; i--) { int start = (order[i] - L + n) % n; int cl = my_class[start]; cnt[cl]--; new_order[cnt[cl]] = start; } return new_order; } static vector<int> UpdateClasses(const vector<int> &new_order, const vector<int> &my_class, int L) { int n = new_order.size(); vector<int> new_class(n); new_class[new_order[0]] = 0; for (int i = 1; i < n; i++) { int cur = new_order[i]; int prev = new_order[i-1]; int mid = (cur + L) % n; int mid_prev = (prev + L) % n; if (my_class[cur] != my_class[prev] || my_class[mid] != my_class[mid_prev]) { new_class[cur] = new_class[prev] + 1; } else { new_class[cur] = new_class[prev]; } } return new_class; } static vector<int> BuildSuffixArray(const string &s) { vector<int> order = SortCharacters(s); vector<int> my_class = ComputeCharClasses(s, order); int n = s.size(); int L = 1; while (L < n) { order = SortDoubled(s, L, order, my_class); my_class = UpdateClasses(order, my_class, L); L *= 2; } return order; } int main() { string s; cin >> s; vector<int> suffix_array = BuildSuffixArray(s); for (int i = 0; i < suffix_array.size(); ++i) { cout << suffix_array[i] << ' '; } cout << endl; return 0; }
17.745342
109
0.583479
agaitanis
87722f657ad29345370fa872900120f6f91564da
312
hpp
C++
include/internal/utils.hpp
hrlou/nhentai
83440bd2b61c00d893941349bd7d571cc10cbec1
[ "BSD-3-Clause" ]
2
2020-10-11T15:27:12.000Z
2020-10-14T19:28:09.000Z
include/internal/utils.hpp
hrlou/nhentai_c
83440bd2b61c00d893941349bd7d571cc10cbec1
[ "BSD-3-Clause" ]
null
null
null
include/internal/utils.hpp
hrlou/nhentai_c
83440bd2b61c00d893941349bd7d571cc10cbec1
[ "BSD-3-Clause" ]
1
2021-05-29T07:51:02.000Z
2021-05-29T07:51:02.000Z
#pragma once #include <string> namespace utils { bool is_dir(const std::string& path); bool exist_test(const std::string& name); std::string dirname(const std::string& path); std::string read_file(const std::string& name); bool do_mkdir(const std::string& path); bool mkpath(std::string path); }
22.285714
48
0.705128
hrlou
877583617168c2cda0f2f512daa22c2ed8b9bcc6
129
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:b7a689390058519b2e382a8fd260640bad650f9d9b17ef70106d4d3dd50bf16f size 1082
32.25
75
0.883721
initialz
8776b36d526364173d5fe5484e7c7acbdd4ee015
2,224
cpp
C++
Irrlichtv1/DynamicObject.cpp
UnProgramator/Drone-AI-Training-Framework
bb6fb2b83331d6e0e307c6579184330c448efece
[ "Zlib", "BSD-3-Clause" ]
1
2021-03-16T16:28:11.000Z
2021-03-16T16:28:11.000Z
Irrlichtv1/DynamicObject.cpp
UnProgramator/Licenta_alex
bb6fb2b83331d6e0e307c6579184330c448efece
[ "Zlib", "BSD-3-Clause" ]
null
null
null
Irrlichtv1/DynamicObject.cpp
UnProgramator/Licenta_alex
bb6fb2b83331d6e0e307c6579184330c448efece
[ "Zlib", "BSD-3-Clause" ]
null
null
null
#include "DynamicObject.h" #include <iostream> DynamicObject::DynamicObject(irr::scene::ISceneNode* meshNode, const irr::core::vector3df & position, const irr::core::vector3df& rotation, const irr::core::vector3df& forwardVector, bool bHasCollision, const std::string& name): StaticObject(meshNode, position, rotation, bHasCollision, name), forwardVector{ forwardVector/forwardVector.getLength() }, defaultForwardVector(forwardVector) { } DynamicObject::DynamicObject(const std::string& meshPath, const std::string& texturePath, const irr::core::vector3df& position, const irr::core::vector3df& rotation, const irr::core::vector3df& forwardVector, const irr::core::vector3df& scale, bool bHasCollision, bool bAddToRaycastDetection, const std::string& name): StaticObject(meshPath, texturePath, position, rotation, scale, bHasCollision, bAddToRaycastDetection, name), forwardVector{ forwardVector / forwardVector.getLength() }, defaultForwardVector(forwardVector) { } DynamicObject::~DynamicObject() {} void DynamicObject::setForwardVector(const irr::core::vector3df& newForwardVector) { this->forwardVector = newForwardVector; } const irr::core::vector3df& DynamicObject::getForwardVector() const { return this->forwardVector; } void DynamicObject::addInputVector(const irr::core::vector3df & inputVector) { this->meshNode->setPosition(this->meshNode->getPosition() + inputVector); } void DynamicObject::moveForward(float distance) { setPosition(getPosition() + distance * forwardVector); } void DynamicObject::setRotation(const irr::core::vector3df & newRotation) { StaticObject::setRotation(newRotation); this->forwardVector = this->forwardVector.rotationToDirection(newRotation); } void DynamicObject::rotate(const irr::core::vector3df & angles) { irr::core::vector3df rot = this->meshNode->getRotation(); rot += angles; this->StaticObject::setRotation(rot); this->forwardVector.rotateXYBy(-angles.Z); this->forwardVector.rotateXZBy(-angles.Y); this->forwardVector.rotateYZBy(-angles.X); } void DynamicObject::reset(bool toDefaults) { StaticObject::reset(toDefaults); if (toDefaults) forwardVector = defaultForwardVector; else forwardVector = irr::core::vector3df(0.0, 0.0, 1.0); }
33.69697
318
0.774281
UnProgramator
877923bbe74e410e909c125a899c18d641a3e150
8,094
cpp
C++
usr/ringbuffer.cpp
Itamare4/ROS_stm32f1_rosserial_USB_VCP
5fac421fa991db1ffe6fa469b93c0fb9d4ae2b87
[ "BSD-3-Clause" ]
14
2018-12-06T04:04:16.000Z
2022-03-01T17:45:04.000Z
usr/ringbuffer.cpp
Itamare4/ROS_stm32f1_rosserial_USB_VCP
5fac421fa991db1ffe6fa469b93c0fb9d4ae2b87
[ "BSD-3-Clause" ]
null
null
null
usr/ringbuffer.cpp
Itamare4/ROS_stm32f1_rosserial_USB_VCP
5fac421fa991db1ffe6fa469b93c0fb9d4ae2b87
[ "BSD-3-Clause" ]
7
2018-10-09T12:17:01.000Z
2021-09-14T02:43:13.000Z
/* * File : ringbuffer.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2012, RT-Thread Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Change Logs: * Date Author Notes * 2012-09-30 Bernard first version. * 2013-05-08 Grissiom reimplement */ #include "stm32f1xx_hal.h" #include "ringbuffer.h" #include <string.h> #define ASSERT(EX) \ __inline enum ringbuffer_state ringbuffer_status(struct ringbuffer *rb) { if (rb->read_index == rb->write_index) { if (rb->read_mirror == rb->write_mirror) return RT_RINGBUFFER_EMPTY; else return RT_RINGBUFFER_FULL; } return RT_RINGBUFFER_HALFFULL; } /** return the size of data in rb */ uint16_t ringbuffer_data_len(struct ringbuffer *rb) { switch ( ringbuffer_status(rb)) { case RT_RINGBUFFER_EMPTY: return 0; case RT_RINGBUFFER_FULL: return rb->buffer_size; case RT_RINGBUFFER_HALFFULL: default: if (rb->write_index > rb->read_index) return rb->write_index - rb->read_index; else return rb->buffer_size - (rb->read_index - rb->write_index); }; } /** return the free space size of rb */ uint16_t ringbuffer_free_len(struct ringbuffer *rb) { return rb->buffer_size - ringbuffer_data_len(rb); } /** * put a block of data into ring buffer */ uint32_t ringbuffer_put(struct ringbuffer *rb, const uint8_t *ptr, uint16_t length) { uint16_t size; ASSERT(rb != NULL); /* whether has enough space */ size = ringbuffer_empty_space(rb); /* no space */ if (size == 0) return 0; /* drop some data */ if (size < length) length = size; if (rb->buffer_size - rb->write_index > length) { /* read_index - write_index = empty space */ memcpy(&rb->buffer_ptr[rb->write_index], ptr, length); /* this should not cause overflow because there is enough space for * length of data in current mirror */ rb->write_index += length; return length; } memcpy(&rb->buffer_ptr[rb->write_index], &ptr[0], rb->buffer_size - rb->write_index); memcpy(&rb->buffer_ptr[0], &ptr[rb->buffer_size - rb->write_index], length - (rb->buffer_size - rb->write_index)); /* we are going into the other side of the mirror */ rb->write_mirror = ~rb->write_mirror; rb->write_index = length - (rb->buffer_size - rb->write_index); return length; } /** * put a block of data into ring buffer * * When the buffer is full, it will discard the old data. */ uint32_t ringbuffer_put_force(struct ringbuffer *rb, const uint8_t *ptr, uint16_t length) { enum ringbuffer_state old_state; ASSERT(rb != NULL); old_state = ringbuffer_status(rb); if (length > rb->buffer_size) length = rb->buffer_size; if (rb->buffer_size - rb->write_index > length) { /* read_index - write_index = empty space */ memcpy(&rb->buffer_ptr[rb->write_index], ptr, length); /* this should not cause overflow because there is enough space for * length of data in current mirror */ rb->write_index += length; if (old_state == RT_RINGBUFFER_FULL) rb->read_index = rb->write_index; return length; } memcpy(&rb->buffer_ptr[rb->write_index], &ptr[0], rb->buffer_size - rb->write_index); memcpy(&rb->buffer_ptr[0], &ptr[rb->buffer_size - rb->write_index], length - (rb->buffer_size - rb->write_index)); /* we are going into the other side of the mirror */ rb->write_mirror = ~rb->write_mirror; rb->write_index = length - (rb->buffer_size - rb->write_index); if (old_state == RT_RINGBUFFER_FULL) { rb->read_mirror = ~rb->read_mirror; rb->read_index = rb->write_index; } return length; } /** * get data from ring buffer */ uint32_t ringbuffer_get(struct ringbuffer *rb, uint8_t *ptr, uint16_t length) { uint32_t size; ASSERT(rb != NULL); /* whether has enough data */ size = ringbuffer_data_len(rb); /* no data */ if (size == 0) return 0; /* less data */ if (size < length) length = size; if (rb->buffer_size - rb->read_index > length) { /* copy all of data */ memcpy(ptr, &rb->buffer_ptr[rb->read_index], length); /* this should not cause overflow because there is enough space for * length of data in current mirror */ rb->read_index += length; return length; } memcpy(&ptr[0], &rb->buffer_ptr[rb->read_index], rb->buffer_size - rb->read_index); memcpy(&ptr[rb->buffer_size - rb->read_index], &rb->buffer_ptr[0], length - (rb->buffer_size - rb->read_index)); /* we are going into the other side of the mirror */ rb->read_mirror = ~rb->read_mirror; rb->read_index = length - (rb->buffer_size - rb->read_index); return length; } /** * put a character into ring buffer */ uint32_t ringbuffer_putchar(struct ringbuffer *rb, const uint8_t ch) { ASSERT(rb != NULL); /* whether has enough space */ if (! ringbuffer_empty_space(rb)) return 0; rb->buffer_ptr[rb->write_index] = ch; /* flip mirror */ if (rb->write_index == rb->buffer_size - 1) { rb->write_mirror = ~rb->write_mirror; rb->write_index = 0; } else { rb->write_index++; } return 1; } /** * put a character into ring buffer * * When the buffer is full, it will discard one old data. */ uint32_t ringbuffer_putchar_force(struct ringbuffer *rb, const uint8_t ch) { enum ringbuffer_state old_state; ASSERT(rb != NULL); old_state = ringbuffer_status(rb); rb->buffer_ptr[rb->write_index] = ch; /* flip mirror */ if (rb->write_index == rb->buffer_size-1) { rb->write_mirror = ~rb->write_mirror; rb->write_index = 0; if (old_state == RT_RINGBUFFER_FULL) { rb->read_mirror = ~rb->read_mirror; rb->read_index = rb->write_index; } } else { rb->write_index++; if (old_state == RT_RINGBUFFER_FULL) rb->read_index = rb->write_index; } return 1; } /** * get a character from a ringbuffer */ uint32_t ringbuffer_getchar(struct ringbuffer *rb, uint8_t *ch) { ASSERT(rb != NULL); /* ringbuffer is empty */ if (! ringbuffer_data_len(rb)) return 0; /* put character */ *ch = rb->buffer_ptr[rb->read_index]; if (rb->read_index == rb->buffer_size-1) { rb->read_mirror = ~rb->read_mirror; rb->read_index = 0; } else { rb->read_index++; } return 1; } void ringbuffer_flush(struct ringbuffer *rb) { ASSERT(rb != NULL); /* initialize read and write index */ rb->read_mirror = rb->read_index = 0; rb->write_mirror = rb->write_index = 0; } void ringbuffer_init(struct ringbuffer *rb, uint8_t *pool, int16_t size) { ASSERT(rb != NULL); ASSERT(size > 0); /* initialize read and write index */ rb->read_mirror = rb->read_index = 0; rb->write_mirror = rb->write_index = 0; /* set buffer pool and size */ rb->buffer_ptr = pool; rb->buffer_size = size; //ALIGN_DOWN(size, ALIGN_SIZE); }
25.695238
89
0.618112
Itamare4
877969918d674c75ff14ee8e0bd12f2473d65237
1,643
cpp
C++
src/MemeGraphics/IndexBuffer.cpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
src/MemeGraphics/IndexBuffer.cpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
src/MemeGraphics/IndexBuffer.cpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
#include <MemeGraphics/IndexBuffer.hpp> #include <MemeGraphics/OpenGL.hpp> namespace ml { /* * * * * * * * * * * * * * * * * * * * */ IndexBuffer::IndexBuffer() : IHandle (NULL) , m_data (NULL) , m_count (NULL) , m_usage (GL::StaticDraw) , m_type (GL::UnsignedInt) { } IndexBuffer::IndexBuffer(const IndexBuffer & copy) : IHandle (copy) , m_data (copy.m_data) , m_count (copy.m_count) , m_usage (copy.m_usage) , m_type (copy.m_type) { } IndexBuffer::~IndexBuffer() { clean(); } /* * * * * * * * * * * * * * * * * * * * */ IndexBuffer & IndexBuffer::clean() { if ((*this)) { ML_GL.deleteBuffers(1, (*this)); } return (*this); } IndexBuffer & IndexBuffer::create(GL::Usage usage, GL::Type type) { if (set_handle(ML_GL.genBuffers(1))) { m_usage = usage; m_type = type; } return (*this); } /* * * * * * * * * * * * * * * * * * * * */ const IndexBuffer & IndexBuffer::bind() const { ML_GL.bindBuffer(GL::ElementArrayBuffer, (*this)); return (*this); } const IndexBuffer & IndexBuffer::unbind() const { ML_GL.bindBuffer(GL::ElementArrayBuffer, NULL); return (*this); } /* * * * * * * * * * * * * * * * * * * * */ const IndexBuffer & IndexBuffer::bufferData(const List<uint32_t> & data) const { return bufferData(&data[0], (uint32_t)data.size()); } const IndexBuffer & IndexBuffer::bufferData(const uint32_t * data, uint32_t count) const { m_data = data; m_count = count; ML_GL.bufferData( GL::ElementArrayBuffer, (m_count * sizeof(uint32_t)), m_data, m_usage); return (*this); } /* * * * * * * * * * * * * * * * * * * * */ }
18.670455
89
0.567864
Gurman8r
877db499e700e6495e5846c988e73903eaced9cd
305
cpp
C++
lab4/src/countnegatives.cpp
Sinduja-S/Algorithm-Design-Lab
9bd64ae42c574b91ca733bb108cd845c15fe3baf
[ "MIT" ]
2
2020-04-17T05:26:11.000Z
2020-05-09T12:27:07.000Z
lab4/src/countnegatives.cpp
sindu-sss/Algorithm-Design-Lab
9bd64ae42c574b91ca733bb108cd845c15fe3baf
[ "MIT" ]
null
null
null
lab4/src/countnegatives.cpp
sindu-sss/Algorithm-Design-Lab
9bd64ae42c574b91ca733bb108cd845c15fe3baf
[ "MIT" ]
3
2020-04-02T12:50:10.000Z
2021-03-27T05:01:22.000Z
#include <iostream> using namespace std; int countneg(int *a,int s,int e){ if(e==s){ if(a[e]<0) return(1); return(0); } else{ int z1,z2; cout<<e; cout<<s<<endl; z1=countneg(a,s,(e+s)/2); z2=countneg(a,(s+e)/2+1,e); return(z1+z2); } }
14.52381
33
0.472131
Sinduja-S
877fec58ed7c13622c1759d9146899aa20460ea9
427
cpp
C++
CodeBlocks1908/share/CodeBlocks/templates/wizard/fltk/files/main.cpp
BenjaminRenz/FirmwareTY71M
55cff63f23c8d844341f4dbf58ce145f073567f6
[ "MIT" ]
9
2019-02-04T02:13:38.000Z
2021-06-24T20:31:49.000Z
CodeBlocks1908/share/CodeBlocks/templates/wizard/fltk/files/main.cpp
userx14/FirmwareTY71M
55cff63f23c8d844341f4dbf58ce145f073567f6
[ "MIT" ]
null
null
null
CodeBlocks1908/share/CodeBlocks/templates/wizard/fltk/files/main.cpp
userx14/FirmwareTY71M
55cff63f23c8d844341f4dbf58ce145f073567f6
[ "MIT" ]
1
2021-06-24T20:31:53.000Z
2021-06-24T20:31:53.000Z
#include <FL/Fl.H> #include <FL/Fl_Window.H> #include <FL/Fl_Box.H> int main (int argc, char ** argv) { Fl_Window *window; Fl_Box *box; window = new Fl_Window (300, 180); box = new Fl_Box (20, 40, 260, 100, "Hello World!"); box->box (FL_UP_BOX); box->labelsize (36); box->labelfont (FL_BOLD+FL_ITALIC); box->labeltype (FL_SHADOW_LABEL); window->end (); window->show (argc, argv); return(Fl::run()); }
19.409091
54
0.63466
BenjaminRenz
87836940c2798edb41ccb43175c5019e177b54b6
349
cpp
C++
src/KEngine/src/Common/Color.cpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2019-04-09T13:03:11.000Z
2021-01-27T04:58:29.000Z
src/KEngine/src/Common/Color.cpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
2
2017-02-06T03:48:45.000Z
2020-08-31T01:30:10.000Z
src/KEngine/src/Common/Color.cpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2020-06-28T08:19:53.000Z
2020-06-28T16:30:19.000Z
#include "KEngine/Common/Color.hpp" namespace ke { const Color Color::WHITE { 255, 255, 255, 255}; const Color Color::BLACK { 0, 0, 0, 255 }; const Color Color::RED { 255, 0, 0, 255 }; const Color Color::GREEN { 0, 255, 0, 255 }; const Color Color::BLUE { 0, 0, 255, 255 }; const Color Color::TRANSPARENT { 0, 0, 0, 0 }; }
26.846154
51
0.595989
yxbh
8785b725fffd3c073dd3d559965bc2a746d773f5
6,583
cpp
C++
apps/cloud_inference/server_app/region.cpp
asalmanp/MIVisionX
a964774944331827c8d6e9bb1ffbb2578f335056
[ "MIT" ]
153
2018-12-20T19:33:15.000Z
2022-03-30T03:51:14.000Z
apps/cloud_inference/server_app/region.cpp
asalmanp/MIVisionX
a964774944331827c8d6e9bb1ffbb2578f335056
[ "MIT" ]
484
2019-01-02T23:51:58.000Z
2022-03-31T15:52:43.000Z
apps/cloud_inference/server_app/region.cpp
asalmanp/MIVisionX
a964774944331827c8d6e9bb1ffbb2578f335056
[ "MIT" ]
105
2018-12-21T00:02:38.000Z
2022-03-25T15:44:02.000Z
#include "region.h" #include "common.h" // biases for Nb=5 const std::string classNames20[] = { "aeroplane","bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"}; // helper functions // sort indexes based on comparing values in v template <typename T> void sort_indexes(const std::vector<T> &v, std::vector<size_t> &idx) { sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] > v[i2];}); } // todo:: convert using SSE4 intrinsics // reshape transpose void CYoloRegion::Reshape(float *input, float *output, int numChannels, int n) { int i, j, p; float *tmp = output; for(i = 0; i < n; ++i) { for(j = 0, p = i; j < numChannels; ++j, p += n) { *tmp++ = input[p]; } } } // todo:: optimize float CYoloRegion::Sigmoid(float x) { return 1./(1. + exp(-x)); } void CYoloRegion::SoftmaxRegion(float *input, int classes, float *output) { int i; float sum = 0; float largest = input[0]; for(i = 0; i < classes; i++){ if(input[i] > largest) largest = input[i]; } for(i = 0; i < classes; i++){ float e = exp(input[i] - largest); sum += e; output[i] = e; } for(i = 0; i < classes; i++){ output[i] /= sum; } } inline float rect_overlap(rect &a, rect &b) { float x_overlap = std::max(0.f, (std::min(a.right, b.right) - std::max(a.left, b.left))); float y_overlap = std::max(0.f, (std::min(a.bottom, b.bottom) - std::max(a.top, b.top))); return (x_overlap * y_overlap); } float CYoloRegion::box_iou(box a, box b) { float box_intersection, box_union; rect ra, rb; ra = {a.x-a.w/2, a.y-a.h/2, a.x+a.w/2, a.y+a.h/2}; rb = {b.x-b.w/2, b.y-b.h/2, b.x+b.w/2, b.y+a.h/2}; box_intersection = rect_overlap(ra, rb); box_union = a.w*a.h + b.w*b.h - box_intersection; return box_intersection/box_union; } int CYoloRegion::argmax(float *a, int n) { if(n <= 0) return -1; int i, max_i = 0; float max = a[0]; for(i = 1; i < n; ++i){ if(a[i] > max){ max = a[i]; max_i = i; } } return max_i; } CYoloRegion::CYoloRegion() { initialized = false; outputSize = 0; frameNum = 0; } CYoloRegion::~CYoloRegion() { initialized = false; if (output) delete [] output; outputSize = 0; } void CYoloRegion::Initialize(int c, int h, int w, int classes) { int size = 4 + classes + 1; // x,y,w,h,pc, c1...c20 outputSize = c * h * w; totalObjectsPerClass = Nb * h * w; output = new float[outputSize]; boxes.resize(totalObjectsPerClass); initialized = true; } // Same as doing inference for this layer int CYoloRegion::GetObjectDetections(float* in_data, const float *biases, int c, int h, int w, int classes, int imgw, int imgh, float thresh, float nms_thresh, int blockwd, std::vector<ObjectBB> &objects) { objects.clear(); int size = 4 + classes + 1; Nb = 5;//biases.size(); if(!initialized) { Initialize(c, h, w, classes); } if(!initialized) { fatal("GetObjectDetections: initialization failed"); return -1; } int i,j,k; Reshape(in_data, output, size*Nb, w*h); // reshape output // Initialize box, scale and probability for(i = 0; i < totalObjectsPerClass; ++i) { int index = i * size; //Box int n = i % Nb; int row = (i/Nb) / w; int col = (i/Nb) % w; boxes[i].x = (col + Sigmoid(output[index + 0])) / blockwd; // box x location boxes[i].y = (row + Sigmoid(output[index + 1])) / blockwd; // box y location boxes[i].w = exp(output[index + 2]) * biases[n*2]/ blockwd; //w; boxes[i].h = exp(output[index + 3]) * biases[n*2+1] / blockwd; //h; //Scale output[index + 4] = Sigmoid(output[index + 4]); //Class Probability SoftmaxRegion(&output[index + 5], classes, &output[index + 5]); // remove the ones which has low confidance for(j = 0; j < classes; ++j) { output[index+5+j] *= output[index+4]; if(output[index+5+j] < thresh) output[index+5+j] = 0; } } //non_max_suppression using box_iou (intersection of union) for(k = 0; k < classes; ++k) { std::vector<float> class_prob_vec(totalObjectsPerClass); std::vector<size_t> s_idx(totalObjectsPerClass); for(i = 0; i < totalObjectsPerClass; ++i) { class_prob_vec[i] = output[i*size + k + 5]; s_idx[i] = i; } //std::iota(idx.begin(), idx.end(), 0); // todo::analyse for performance sort_indexes(class_prob_vec, s_idx); // sort indeces based on prob for(i = 0; i < totalObjectsPerClass; ++i){ if(output[s_idx[i] * size + k + 5] == 0) continue; box a = boxes[s_idx[i]]; for(j = i+1; j < totalObjectsPerClass; ++j){ box b = boxes[s_idx[j]]; if (box_iou(a, b) > nms_thresh){ output[s_idx[j] * size + 5 + k] = 0; } } } } // generate objects for(i = 0, j = 5; i < totalObjectsPerClass; ++i, j += size) { int iclass = argmax(&output[j], classes); float prob = output[j+iclass]; if(prob > thresh) { box b = boxes[i]; #if 0 // boundingbox to actual coordinates printf("%f %f %f %f\n", b.x, b.y, b.w, b.h); int left = (b.x-b.w/2.)*imgw; int right = (b.x+b.w/2.)*imgw; int top = (b.y-b.h/2.)*imgh; int bot = (b.y+b.h/2.)*imgh; if(left < 0) left = 0; if(right > imgw-1) right = imgw-1; if(top < 0) top = 0; if(bot > imgh-1) bot = imgh-1; #endif ObjectBB obj; obj.x = b.x; obj.y = b.y; obj.w = b.w; obj.h = b.h; obj.confidence = prob; obj.label = iclass; //std::cout << "BoundingBox(xywh): "<< i << "for frame: "<< frameNum << " (" << b.x << " " << b.y << " "<< b.w << " "<< b.h << ") " << "confidence: " << prob << " lablel: " << iclass << std::endl; objects.push_back(obj); } } frameNum++; return 0; }
28.012766
216
0.510102
asalmanp
8788714b6fe83a50d1222bfa89a660c64e0ddc07
1,989
cpp
C++
datastructure/08/8-6.cpp
Simon-Chenzw/homework
6e0e7f8c498f047b4fea5b050690dec4de5bd5a7
[ "MIT" ]
4
2021-04-05T16:32:06.000Z
2022-03-10T01:28:04.000Z
datastructure/08/8-6.cpp
Simon-Chenzw/homework
6e0e7f8c498f047b4fea5b050690dec4de5bd5a7
[ "MIT" ]
null
null
null
datastructure/08/8-6.cpp
Simon-Chenzw/homework
6e0e7f8c498f047b4fea5b050690dec4de5bd5a7
[ "MIT" ]
null
null
null
#include <cctype> #include <iostream> #include <list> #include <map> #include <set> #include <stack> using namespace std; class Node { public: char name; list<Node*> sub; Node(): name(0) {} Node(char _name): name(_name) {} set<int> findDep(char ch) const { set<int> ret; bfsFind(ch, 1, ret); return ret; } private: void bfsFind(const char& ch, int base, set<int>& ret) const { if (name == ch) ret.insert(base); for (auto& it : sub) it->bfsFind(ch, base + 1, ret); } public: static Node create(const string& s) { stack<Node*> st; map<char, Node*> addr; for (auto& ch : s) { if (ch == ',' || ch == ')') { st.pop(); } else if (isalpha(ch)) { auto it = addr.find(ch); if (it == addr.end()) { it = addr.insert({ch, new Node(ch)}).first; if (!st.empty()) st.top()->sub.push_back(it->second); st.push(it->second); } else { if (!st.empty()) st.top()->sub.push_back(it->second); st.push(new Node); // add empty one } } } while (st.size() > 1) st.pop(); //当没有广义表编号的时候 return *st.top(); } }; ostream& operator<<(ostream& out, const set<int>& s) { bool first = true; for (auto& p : s) { if (first) first = false; else out << ' '; out << p; } return out; } int main() { auto list1 = Node::create("L(A(B(a, b)), C(B(a, b), c), D(c, d, e), E(e))"); // 图 8-1 cout << "a: " << list1.findDep('a') << endl; cout << "c: " << list1.findDep('c') << endl; auto list2 = Node::create("L = A(a, B(c, C(a, b), d), E(e, F(f)))"); // 习题 8-3 cout << "a: " << list2.findDep('a') << endl; cout << "C: " << list2.findDep('C') << endl; }
26.52
92
0.43992
Simon-Chenzw
878db0266024ff8c6088177de583c77696c6ef60
2,482
cpp
C++
CtCI/Chapter1/1.3.cpp
wqw547243068/DS_Algorithm
6d4a9baeb3650a8f93308c7405c9483bac59e98b
[ "RSA-MD" ]
2
2021-12-29T14:42:51.000Z
2021-12-29T14:46:45.000Z
CtCI/Chapter1/1.3.cpp
wqw547243068/DS_Algorithm
6d4a9baeb3650a8f93308c7405c9483bac59e98b
[ "RSA-MD" ]
null
null
null
CtCI/Chapter1/1.3.cpp
wqw547243068/DS_Algorithm
6d4a9baeb3650a8f93308c7405c9483bac59e98b
[ "RSA-MD" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; string removeDuplicate1(string s) { int check = 0; int len = s.length(); if(len < 2) return s; string str = ""; for(int i=0; i<len; ++i) { int v = (int)(s[i]-'a'); if((check & (1<<v)) == 0) { str += s[i]; check |= (1<<v); } } return str; } string removeDuplicate2(string s) { int len = s.length(); if(len < 2) return s; string str = ""; for(int i=0; i<len; ++i) { if(s[i] != '\0') { str += s[i]; for(int j=i+1; j<len; ++j) if(s[j]==s[i]) s[j] = '\0'; } } return str; } void removeDuplicate3(char s[]) { int len = strlen(s); if(len < 2) return; int p = 0; for(int i=0; i<len; ++i) { if(s[i] != '\0') { s[p++] = s[i]; for(int j=i+1; j<len; ++j) if(s[j]==s[i]) s[j] = '\0'; } } s[p] = '\0'; } void removeDuplicate4(char s[]) { int len = strlen(s); if(len < 2) return; bool c[256]; memset(c, 0, sizeof(c)); int p = 0; for(int i=0; i<len; ++i) { if(!c[s[i]]) { s[p++] = s[i]; c[s[i]] = true; } } s[p] = '\0'; } void removeDuplicate5(char s[]) { int len = strlen(s); if(len < 2) return; int check = 0, p = 0; for(int i=0; i<len; ++i) { int v = (int)(s[i]-'a'); if((check & (1<<v))==0) { s[p++] = s[i]; check |= (1<<v); } } s[p] = '\0'; } int main() { string s1 = "abcde"; string s2 = "aaabbb"; string s3 = ""; string s4 = "abababc"; string s5 = "ccccc"; cout<<removeDuplicate1(s1)<<" "<<removeDuplicate2(s1)<<endl; cout<<removeDuplicate1(s2)<<" "<<removeDuplicate2(s2)<<endl; cout<<removeDuplicate1(s3)<<" "<<removeDuplicate2(s3)<<endl; cout<<removeDuplicate1(s4)<<" "<<removeDuplicate2(s4)<<endl; cout<<removeDuplicate1(s5)<<" "<<removeDuplicate2(s5)<<endl; char ss1[] = "abcde"; char ss2[] = "aaabbb"; char ss3[] = ""; char ss4[] = "abababc"; char ss5[] = "ccccc"; removeDuplicate5(ss1); removeDuplicate5(ss2); removeDuplicate5(ss3); removeDuplicate5(ss4); removeDuplicate5(ss5); cout<<ss1<<" "<<ss2<<" "<<ss3<<" "<<ss4<<" "<<ss5<<endl; return 0; }
21.033898
64
0.43755
wqw547243068
878ff952ba31c6ca43afaed0936051ecd81610c8
2,388
hpp
C++
src/models/Mesh.hpp
sophia-x/RayTracing
1092971b08ff17e8642e408e2cb0c518d6591e2b
[ "MIT" ]
1
2016-05-05T10:20:45.000Z
2016-05-05T10:20:45.000Z
src/models/Mesh.hpp
sophia-x/RayTracing
1092971b08ff17e8642e408e2cb0c518d6591e2b
[ "MIT" ]
null
null
null
src/models/Mesh.hpp
sophia-x/RayTracing
1092971b08ff17e8642e408e2cb0c518d6591e2b
[ "MIT" ]
null
null
null
#ifndef MESH #define MESH #include "Model.hpp" #include "Triangle.hpp" #include "../common.hpp" class Mesh : public Model { private: vector<Triangle> __tris; vector<vec3> __vertices; vector<vec3> __model_verticles; vector<vec2> __uvs; public: Mesh(const char *file_name, const Material &material): Model(material) { loadObj(file_name); buildModel(); } Mesh(const vector<vec3> &vertices, const vector<int> &tri_idx, const Material &material): Model(material), __vertices(vertices) { size_t size = tri_idx.size() / 3; __tris.reserve(size); for (size_t i = 0; i < size; i++) { __tris.push_back(Triangle(__vertices[tri_idx[3 * i]], __vertices[tri_idx[3 * i + 1]], __vertices[tri_idx[3 * i + 2]], __hash_code, __material)); } buildModel(); } Mesh(const vector<vec3> &vertices, const vector<vec2> &uvs, const vector<int> &tri_idx, const Material &material): Model(material), __vertices(vertices), __uvs(uvs) { size_t size = tri_idx.size() / 3; __tris.reserve(size); for (size_t i = 0; i < size; i++) { __tris.push_back(Triangle(__vertices[tri_idx[3 * i]], __vertices[tri_idx[3 * i + 1]], __vertices[tri_idx[3 * i + 2]], __uvs[tri_idx[3 * i]], __uvs[tri_idx[3 * i + 1]], __uvs[tri_idx[3 * i + 2]], __hash_code, __material)); } buildModel(); } void transform(const mat4 &transform_matrix) { for (size_t i = 0; i < __vertices.size(); i ++) { __vertices[i] = vec3(transform_matrix * vec4(__model_verticles[i], 1)); } for (auto tri = __tris.begin(); tri != __tris.end(); tri++) tri->update(); } inline void addPrimitives(vector<Primitive *> &primitives) { for (size_t i = 0; i < __tris.size(); i++) primitives.push_back(&(__tris[i])); } private: void loadObj(const char* file_name); void buildModel() { vec3 mean(0), max_p(numeric_limits<float>::min()), min_p(numeric_limits<float>::max()); for (size_t i = 0; i < __vertices.size(); i++) { mean += __vertices[i]; max_p = max(max_p, __vertices[i]); min_p = min(min_p, __vertices[i]); } mean /= float(__vertices.size()); vec3 m = max(abs(max_p - mean), abs(min_p - mean)); __model_verticles.reserve(__vertices.size()); for (size_t i = 0; i < __vertices.size(); i ++) { vec3 p = __vertices[i] - mean; for (int j = 0; j < 3; j ++) { if (m[j] >= EPSILON) { p[j] /= m[j]; } } __model_verticles.push_back(p); } } }; #endif
28.428571
224
0.643216
sophia-x
87926192a988cd4db786867eb9a8df26601c7619
16,021
cc
C++
src/model/mem_sampler.cc
delorean-sim/gem5
0c02c1d7efb781680eb5817730440832af3d5587
[ "BSD-3-Clause" ]
null
null
null
src/model/mem_sampler.cc
delorean-sim/gem5
0c02c1d7efb781680eb5817730440832af3d5587
[ "BSD-3-Clause" ]
null
null
null
src/model/mem_sampler.cc
delorean-sim/gem5
0c02c1d7efb781680eb5817730440832af3d5587
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012-2019 Nikos Nikoleris * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nikos Nikoleris */ #include "model/mem_sampler.hh" #include <fstream> #include <functional> #include <string> #include "arch/utility.hh" #include "base/compiler.hh" #include "base/types.hh" #include "config/the_isa.hh" #include "cpu/simple_thread.hh" #include "cpu/thread_context.hh" #include "debug/MemSampler.hh" #include "debug/MemSamplerDebug.hh" #include "model/statcache.hh" #include "params/MemSampler.hh" #include "sim/system.hh" MemSampler::MemSampler(const MemSamplerParams *p) : SimObject(p), kvmWatchpoints(p->system), blockSize(p->blockSize), vicinityWindowSize(p->windowSize), targetedAccessMinReuseInst(20000), excludeKernel(true) { std::random_device rd; rng.seed(rd()); } void MemSampler::observeLoad(ThreadContext *tc, Addr inst_addr, Addr phys_addr, Addr virt_addr, int size) { if (!TheISA::inUserMode(tc) && excludeKernel) { return; } recordReuse(inst_addr, virt_addr, phys_addr, size); if (nextLoadSample == loadCtr) { sampleAccess(inst_addr, virt_addr, phys_addr, size); if (sampledLoadsInBatch < batchSize) { sampledLoadsInBatch++; nextLoadSample++; } } if (nextLoadSample <= loadCtr) { sampledLoadsInBatch = 0; if (samplingEnabled) { nextLoadSample += nextSample(); } else { nextLoadSample = (uint64_t)-1; } DPRINTF(MemSampler, "Next load sample %d\n", nextLoadSample); } } void MemSampler::observeStore(ThreadContext *tc, Addr inst_addr, Addr phys_addr, Addr virt_addr, int size) { if (!TheISA::inUserMode(tc) && excludeKernel) { return; } recordReuse(inst_addr, virt_addr, phys_addr, size); if (nextStoreSample == storeCtr) { sampleAccess(inst_addr, virt_addr, phys_addr, size); if (sampledStoresInBatch < batchSize) { sampledStoresInBatch++; nextStoreSample++; } } if (nextStoreSample <= storeCtr) { sampledStoresInBatch = 0; if (samplingEnabled) { nextStoreSample += nextSample(); } else { nextStoreSample = (uint64_t)-1; } DPRINTF(MemSampler, "Next store sample %d\n", nextStoreSample); } } void MemSampler::sampleAccess(Addr inst_addr, Addr virt_addr, Addr phys_addr, Addr size) { AccessSample ac; ac.instAddr = inst_addr; ac.effAddr = virt_addr; ac.effPhysAddr = phys_addr; ac.size = size; ac.mtime = memInstCtr; ac.itime = instCtr; ac.weight = samplingPeriod; ac.targeted = false; ac.random = true; DPRINTF(MemSampler, "Sampling access: (%d/%d): access: %#llx " "(+%d) by %#x\n", instCtr, memInstCtr, ac.effPhysAddr, ac.size, ac.instAddr); sampleAccess(ac); } void MemSampler::sampleAccess(const AccessSample ac) { const Addr blk_phys_addr = roundDown(ac.effPhysAddr, blockSize); auto ret = watchpoints.emplace(blk_phys_addr, ac); if (!ret.second) { // there was already a targeted watchpoint and we happened to // randomly sample the same block auto &wp = ret.first; AccessSample &old_ac = wp->second; assert(old_ac.targeted || ac.targeted); old_ac.random = old_ac.targeted = true; } kvmWatchpoints.insert(blk_phys_addr); } void MemSampler::recordReuse(Addr inst_addr, Addr virt_addr, Addr phys_addr, Addr size) { const Addr blk_phys_addr = roundDown(phys_addr, blockSize); auto it = watchpoints.find(blk_phys_addr); if (it == watchpoints.end()) { return; } AccessSample &ac1 = it->second; MemoryReuse reuse; reuse.begin = ac1; AccessSample &ac2 = reuse.end; ac2.instAddr = inst_addr; ac2.effAddr = virt_addr; ac2.effPhysAddr = phys_addr; ac2.size = size; ac2.mtime = memInstCtr; ac2.itime = instCtr; const Tick rdist = memInstCtr - ac1.mtime; // At this point, this could be a targeted access or the reuse of // a randomly choosen instruction or both if (ac1.random) { DPRINTF(MemSampler, "Recording smpl reuse - addr: %#llx " "pc: %#llx inst count: %llu rdist %llu\n", blk_phys_addr, inst_addr, instCtr, rdist); numSampledReuses++; sampledReuses.push_back(reuse); ac1.random = false; } auto wp = targetedAccesses.find(blk_phys_addr); assert(!ac1.targeted || wp != targetedAccesses.end()); if (ac1.targeted) { TargetedAccess &acc = wp->second; numTargetedWatchpointHits++; if (virt_addr == acc.effAddr && phys_addr == acc.effPhysAddr && inst_addr == acc.instAddr && size == acc.size) { // only if there is a match in a couple of properties we // record this const Tick rdist_inst = instCtr - ac1.itime; // if this is the first time, we observed this access or // it reuse is small than we expected, we skip it if (ac1.mtime != -1 && rdist_inst > targetedAccessMinReuseInst) { DPRINTF(MemSampler, "Recording tgt reuse - addr: %#llx " "pc: %#llx inst count: %llu rdist: %llu\n", blk_phys_addr, inst_addr, instCtr, rdist); numTargetedReuses++; targetedReuses.push_back(reuse); acc.count++; acc.itime = instCtr; acc.dist = memInstCtr - ac1.mtime; } } ac1 = ac2; ac1.targeted = true; } else { // if this is not a targeted access, we don't need the // watchpoint any more watchpoints.erase(it); kvmWatchpoints.remove(phys_addr); } } void MemSampler::stage() { assert(stagedTargetedAccesses.empty()); std::swap(targetedAccesses, stagedTargetedAccesses); stagedTime = instCtr; for (const auto &reuse: stagedTargetedAccesses) { TargetedAccess acc = reuse.second; const Addr blk_phys_addr = roundDown(acc.effPhysAddr, blockSize); DPRINTF(MemSampler, "Staging access %#x\n", acc.effPhysAddr); auto it = watchpoints.find(blk_phys_addr); assert(it != watchpoints.end()); AccessSample &as = it->second; assert(as.targeted); as.targeted = false; if (!as.random) { watchpoints.erase(it); kvmWatchpoints.remove(blk_phys_addr); } } assert(targetedAccesses.empty()); for (const auto &wp: watchpoints) { const AccessSample &as = wp.second; assert(!as.targeted); } } void MemSampler::loadAccesses(const char *ifile) { assert(targetedAccesses.empty()); std::fstream input(ifile, std::ios::in | std::ios::binary); panic_if(!input, "File not found: %s\n", ifile); ProtoReuseProfile::Accesses pAccesses; panic_if(!pAccesses.ParseFromIstream(&input), "Failed to parse file: %s\n", ifile); for (unsigned i = 0; i < pAccesses.accesses_size(); i++) { const ProtoReuseProfile::Access &pAccess = pAccesses.accesses(i); TargetedAccess tgt_acc; tgt_acc.instAddr = pAccess.pc(); tgt_acc.effAddr = pAccess.addr(); tgt_acc.effPhysAddr = pAccess.physaddr(); tgt_acc.size = pAccess.size(); tgt_acc.count = 0; tgt_acc.dist = 0; const Addr blk_phys_addr = roundDown(tgt_acc.effPhysAddr, blockSize); auto ret M5_VAR_USED = targetedAccesses.emplace(blk_phys_addr, tgt_acc); assert(ret.second); AccessSample smpl_acc; smpl_acc.instAddr = pAccess.pc(); smpl_acc.effAddr = pAccess.addr(); smpl_acc.effPhysAddr = pAccess.physaddr(); smpl_acc.size = pAccess.size(); smpl_acc.targeted = true; smpl_acc.random = false; smpl_acc.mtime = -1; DPRINTF(MemSampler, "Loading key access: %#llx (+%d) by %#x\n", smpl_acc.effPhysAddr, smpl_acc.size, smpl_acc.instAddr); sampleAccess(smpl_acc); kvmWatchpoints.enable(smpl_acc.effPhysAddr); } numTargetedAccesses += pAccesses.accesses_size(); google::protobuf::ShutdownProtobufLibrary(); } Vicinity MemSampler::populateVicinity(Tick itime) { Vicinity vicinity(vicinityWindowSize); vicinity.reset(); // Traverse recorded reuse samples and populate the vicinity // histogram and a per-instruction bounded buffer with reuse // samples auto rit = sampledReuses.begin(); while (rit != sampledReuses.end()) { const MemoryReuse &reuse = *rit; if (reuse.begin.itime < itime) { Tick rdist = reuse.end.mtime - reuse.begin.mtime; vicinity.addReuse(reuse.begin.mtime, reuse.end.mtime, reuse.begin.weight); DPRINTF(MemSampler, "Adding reuse to vicinity: %llu (w:%llu) - " "from pc: %#llx time: %#llu, to pc: %#llx time: %#llu\n", rdist, reuse.begin.weight, reuse.begin.instAddr, reuse.begin.mtime, reuse.end.instAddr, reuse.end.mtime); rit = sampledReuses.erase(rit); } else { rit++; } } // Add pending watchpoints in the vicinity histogram as infinite // reuses, danglings. auto wit = watchpoints.begin(); while (wit != watchpoints.end()) { const AccessSample as = wit->second; if (as.itime < itime) { assert(!as.targeted); DPRINTF(MemSampler, "Adding dangling to vicinity: inf (w: %%llu) " "- from pc: %#llx time: %#llu\n", as.instAddr, as.mtime); vicinity.addDangling(as.mtime, as.weight); wit = watchpoints.erase(wit); kvmWatchpoints.remove(as.effPhysAddr); } else { wit++; } } return vicinity; } void MemSampler::save(const char *reuse_file, const char *accesses_file) { Vicinity vicinity = populateVicinity(stagedTime); ProtoReuseProfile::ReuseProfile reuseProfile; vicinity.save(reuseProfile); ProtoReuseProfile::Accesses pAccesses; bool dump_key_accesses = false; for (const auto &reuse: stagedTargetedAccesses) { TargetedAccess acc = reuse.second; ProtoReuseProfile::Access *pAccess; if (!acc.count) { dump_key_accesses = true; DPRINTF(MemSampler, "Key access not found (i:%llu): " "%#llx (%#llx) by %#llx\n", acc.itime, acc.effAddr, acc.effPhysAddr, acc.instAddr); pAccess = pAccesses.add_accesses(); } else { DPRINTF(MemSampler, "Saving access (i:%llu): %d " "%#llx (%#llx) by %#llx\n", acc.itime, acc.dist, acc.effAddr, acc.effPhysAddr, acc.instAddr); pAccess = reuseProfile.add_accesses(); pAccess->set_dist(acc.dist); } pAccess->set_pc(acc.instAddr); pAccess->set_addr(acc.effAddr); pAccess->set_physaddr(acc.effPhysAddr); pAccess->set_size(acc.size); } stagedTargetedAccesses.clear(); if (reuse_file) { DPRINTF(MemSampler, "Dumping collected reuses until %d to: %s\n", stagedTime, reuse_file); using namespace std; fstream output(reuse_file, ios::out | ios::trunc | ios::binary); panic_if(!reuseProfile.SerializeToOstream(&output), "Failed to write %s.", reuse_file); } if (accesses_file && dump_key_accesses) { DPRINTF(MemSampler, "Dumping remaining key accesses to: %s\n", accesses_file); using namespace std; fstream output(accesses_file, ios::out | ios::trunc | ios::binary); panic_if(!pAccesses.SerializeToOstream(&output), "Failed to write %s.", accesses_file); } google::protobuf::ShutdownProtobufLibrary(); } void MemSampler::setSamplingPeriod(long period, int size) { DPRINTF(MemSampler, "Changing parameters: period %lld size: %d\n", period, size); if (size == 0) { samplingEnabled = false; return; } samplingPeriod = period; batchSize = size; double lambda = 1. / samplingPeriod; expDistr = std::exponential_distribution<double>(lambda); if (!samplingEnabled) { nextLoadSample = loadCtr + nextSample(); nextStoreSample = storeCtr + nextSample(); samplingEnabled = true; DPRINTF(MemSampler, "Enabling sampling next - load: %d store: %d\n", nextLoadSample, nextStoreSample); } } void MemSampler::regStats() { SimObject::regStats(); using namespace Stats; numRandomSamples .name(name() + ".random_samples") .desc("Number of times a random sample was taken") ; numTargetedAccesses .name(name() + ".targeted_accesses") .desc("Number of accesses that we targeted") ; numSampledReuses .name(name() + ".sampled_reuses") .desc("Number of reuses we sampled") ; numTargetedReuses .name(name() + ".targeted_reuses") .desc("Number of targeted reuses we obtained") ; numTargetedWatchpointHits .name(name() + ".targeted_watchpoint_hits") .desc("Number of time a targeted watchpoint was triggered") ; numMissedSamplesLoad .name(name() + ".missed_samples_load") .desc("Number of missed samples - load") ; numMissedSamplesStore .name(name() + ".missed_samples_store") .desc("Number of missed samples - store") ; kvmWatchpoints.regStats(); } MemSampler* MemSamplerParams::create() { return new MemSampler(this); }
32.629328
78
0.628051
delorean-sim
87947efc4974a50c8e689fb07952009ffe8ef12f
1,925
cpp
C++
foo_cover_resizer/ContextMenuUtils.cpp
marc2k3/fb2k-component
1dcdfd489eefc3a392d2ff4d0fb5133aa6636e73
[ "MIT" ]
7
2021-10-05T02:13:08.000Z
2022-03-29T15:17:37.000Z
foo_cover_resizer/ContextMenuUtils.cpp
marc2k3/fb2k-component
1dcdfd489eefc3a392d2ff4d0fb5133aa6636e73
[ "MIT" ]
2
2022-03-11T04:49:10.000Z
2022-03-17T00:13:04.000Z
foo_cover_resizer/ContextMenuUtils.cpp
marc2k3/fb2k-component
1dcdfd489eefc3a392d2ff4d0fb5133aa6636e73
[ "MIT" ]
null
null
null
#include "stdafx.h" using namespace resizer; static const std::vector<ContextItem> context_items = { { &guid_context_command_convert, "Convert front covers to JPG without resizng" }, { &guid_context_command_remove_all_except_front, "Remove all except front" }, }; class ContextMenuUtils : public contextmenu_item_simple { public: GUID get_item_guid(uint32_t index) override { return *context_items[index].guid; } GUID get_parent() override { return guid_context_group_utils; } bool context_get_display(uint32_t index, metadb_handle_list_cref handles, pfc::string_base& out, uint32_t& displayflags, const GUID& caller) override { get_item_name(index, out); return true; } bool get_item_description(uint32_t index, pfc::string_base& out) override { get_item_name(index, out); return true; } uint32_t get_num_items() override { return context_items.size(); } void context_command(uint32_t index, metadb_handle_list_cref handles, const GUID& caller) override { const HWND hwnd = core_api::get_main_window(); if (index == 0) { if (MessageBoxW(hwnd, L"This option will ignore any images that are already JPG. Continue?", string_wide_from_utf8_fast(group_utils), MB_ICONWARNING | MB_SETFOREGROUND | MB_YESNO) == IDYES) { auto cb = fb2k::service_new<CoverResizer>(handles, true); threaded_process::get()->run_modeless(cb, threaded_process_flags, hwnd, "Converting front covers to JPG..."); } } else if (index == 1) { auto cb = fb2k::service_new<CoverRemover>(handles); threaded_process::get()->run_modeless(cb, threaded_process_flags, hwnd, "Removing covers..."); } } void get_item_name(uint32_t index, pfc::string_base& out) override { out = context_items[index].name; } }; static contextmenu_group_popup_factory g_context_group_utils(guid_context_group_utils, contextmenu_groups::root, group_utils, 1); FB2K_SERVICE_FACTORY(ContextMenuUtils);
28.308824
192
0.753766
marc2k3
8797e5ee50a22e5af0a19ef86a3311b1661a95b3
3,173
cpp
C++
modules/trivia/cmd_achievements.cpp
brainboxdotcc/triviabot
d074256f38a002bfb9d352c4f80bc45f19a71384
[ "Apache-2.0" ]
23
2020-06-28T18:07:03.000Z
2022-03-02T20:12:47.000Z
modules/trivia/cmd_achievements.cpp
brainboxdotcc/triviabot
d074256f38a002bfb9d352c4f80bc45f19a71384
[ "Apache-2.0" ]
4
2020-10-08T13:37:39.000Z
2022-03-26T22:41:19.000Z
modules/trivia/cmd_achievements.cpp
brainboxdotcc/triviabot
d074256f38a002bfb9d352c4f80bc45f19a71384
[ "Apache-2.0" ]
13
2020-10-08T13:32:02.000Z
2021-12-02T00:00:28.000Z
/************************************************************************************ * * TriviaBot, The trivia bot for discord based on Fruitloopy Trivia for ChatSpike IRC * * Copyright 2004 Craig Edwards <support@brainbox.cc> * * Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************************/ #include <dpp/dpp.h> #include <fmt/format.h> #include <sporks/modules.h> #include <sporks/regex.h> #include <string> #include <cstdint> #include <fstream> #include <streambuf> #include <sporks/stringops.h> #include <sporks/statusfield.h> #include <sporks/database.h> #include <dpp/nlohmann/json.hpp> #include "state.h" #include "trivia.h" #include "webrequest.h" #include "commands.h" using json = nlohmann::json; command_achievements_t::command_achievements_t(class TriviaModule* _creator, const std::string &_base_command, bool adm, const std::string& descr, std::vector<dpp::command_option> options) : command_t(_creator, _base_command, adm, descr, options) { } void command_achievements_t::call(const in_cmd &cmd, std::stringstream &tokens, guild_settings_t &settings, const std::string &username, bool is_moderator, dpp::channel* c, dpp::user* user) { dpp::snowflake user_id = 0; tokens >> user_id; if (!user_id) { user_id = cmd.author_id; } uint32_t unlock_count = from_string<uint32_t>(db::query("SELECT COUNT(*) AS unlocked FROM achievements WHERE user_id = ?", {user_id})[0]["unlocked"], std::dec); std::string trophies = fmt::format(_("ACHCOUNT", settings), unlock_count, creator->achievements->size() - unlock_count) + "\n"; std::vector<field_t> fields; for (auto& showoff : *(creator->achievements)) { db::resultset inf = db::query("SELECT *, date_format(unlocked, '%d-%b-%Y') AS unlocked_friendly FROM achievements WHERE user_id = ? AND achievement_id = ?", {user_id, showoff["id"].get<uint32_t>()}); if (inf.size()) { fields.push_back({ "<:" + showoff["image"].get<std::string>() + ":" + showoff["emoji_unlocked"].get<std::string>() + "> - " + _(showoff["name"].get<std::string>(), settings), _(showoff["desc"].get<std::string>(), settings) + " (*" + inf[0]["unlocked_friendly"] + "*)\n<:blank:667278047006949386>", false }); } } creator->EmbedWithFields( cmd.interaction_token, cmd.command_id, settings, _("TROPHYCABINET", settings), fields, cmd.channel_id, "https://triviabot.co.uk/", "", "", "<:blank:667278047006949386>\n" + trophies + "<:blank:667278047006949386>" ); creator->CacheUser(cmd.author_id, cmd.user, cmd.member, cmd.channel_id); }
40.679487
250
0.670974
brainboxdotcc
879a470fc5bf0aebafbd40975363b09fa0725bd3
479
cpp
C++
src/A/A6B84.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/A/A6B84.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/A/A6B84.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long #define ld long double using namespace std; bool prime(int n){ int m=sqrt(n); for(int i=2;i<=m;i++){ if(n%i==0) return false; } return true; } int main(){ ios::sync_with_stdio(false); cin.tie(0); ll n,q=1; while(cin>>n){ if(n==0) return 0; else{ if(n<=3) ; ll i=sqrt(n)*2+10; while(i*(i-3)/2>n) i-=100; if(i<0) i=1; while(i*(i-3)/2<n) i++; cout<<"Case "<<q<<": "<<i<<endl; q++; } } return 0; }
15.451613
35
0.542797
wlhcode
879a8472c0a0fcbd4bdd4f1755fd7604ccb68f4c
427
cpp
C++
src/Generic/common/SymbolConstants.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/common/SymbolConstants.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/common/SymbolConstants.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #include "Generic/common/leak_detection.h" // This must be the first #include #include "Generic/common/SymbolConstants.h" Symbol SymbolConstants::leftParen = Symbol(L"("); Symbol SymbolConstants::rightParen = Symbol(L")"); Symbol SymbolConstants::nullSymbol = Symbol(L":NULL"); Symbol SymbolConstants::unreachableSymbol = Symbol(L"OTHER_SENT");
35.583333
78
0.747073
BBN-E
879bb074afd41eb3c778443b83ee7f18ddd99b5b
770
cc
C++
apose.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
apose.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
apose.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
#include "imgutils.hh" #include "strutils.hh" #include "partrait.hh" #include "parson.hh" #include "catalog.hh" #include "autoposer.hh" using namespace makemore; using namespace std; int main(int argc, char **argv) { assert(argc > 0); Catalog cat(argv[1]); Autoposer ap("fineposer.proj"); for (auto fn : cat.fn) { Partrait par; par.load(fn); Triangle mark; mark.p = Point(192, 240); mark.q = Point(320, 240); mark.r = Point(256, 384); par.set_mark(mark); ap.autopose(&par); ap.autopose(&par); Pose pose = par.get_pose(); par.set_tag("angle", pose.angle); par.set_tag("stretch", pose.stretch); par.set_tag("skew", pose.skew); par.save(fn); fprintf(stderr, "%s\n", fn.c_str()); } return 0; }
19.25
41
0.619481
jdb19937
879cf099e1424416d9da9c5c94647ab57d86a769
5,575
cpp
C++
runtime/tests/test_message_priority.cpp
thejkane/AGM
4d5cfe9522461d207ceaef7d90c1cd10ce9b469c
[ "BSL-1.0" ]
1
2021-09-03T10:22:04.000Z
2021-09-03T10:22:04.000Z
runtime/tests/test_message_priority.cpp
thejkane/AGM
4d5cfe9522461d207ceaef7d90c1cd10ce9b469c
[ "BSL-1.0" ]
null
null
null
runtime/tests/test_message_priority.cpp
thejkane/AGM
4d5cfe9522461d207ceaef7d90c1cd10ce9b469c
[ "BSL-1.0" ]
null
null
null
#include <config.h> #include <boost/config.hpp> #include "am++/am++.hpp" #include <iostream> #include <pthread.h> #include <boost/thread.hpp> #include <boost/thread/barrier.hpp> #include <boost/bind.hpp> #define TRANSPORT_HEADER <am++/BOOST_JOIN(TRANSPORT, _transport).hpp> #include TRANSPORT_HEADER #include <time.h> #include <sys/time.h> #define DISABLE_SELF_SEND_CHECK typedef double time_type; // copies directly from europar_tests inline time_type get_time() { return MPI_Wtime(); #if 0 timeval tp; gettimeofday(&tp, 0); return tp.tv_sec + tp.tv_usec / 1000000.0; #endif } time_type non_priority_time = 0; time_type priority_time = 0; time_type time_at_start = 0; struct message_priority_handler { typedef amplusplus::message_type<int> tm_type; tm_type& tm; amplusplus::transport& trans; message_priority_handler(tm_type& tm, amplusplus::transport& t): tm(tm), trans(t) { std::cerr << "Constructor" << std::endl; } void operator()(int source, const int* buf, int count) const { // std::cout << "My rank is " << trans.rank() << " Messag is from rank " << source << std::endl; for (int i = 0; i < count; ++i) { // std::cout << "The message content - " << buf[i] << std::endl; if (buf[i] % 2 == 0) { non_priority_time = get_time(); // even - non priority message } else { priority_time = get_time(); // odd - priority message } } } }; struct empty_deleter { typedef void result_type; void operator()() const {} template <typename T> void operator()(const T&) const {} }; #define MSG_SIZE 10000 struct msg_send_args { amplusplus::transport& trans; amplusplus::message_type<int>& tm; amplusplus::message_type<int>& priority_tm; bool coalesced; int start; boost::barrier& barier; msg_send_args(amplusplus::transport& t, amplusplus::message_type<int>& mt, amplusplus::message_type<int>& priority_m, bool c, int st, boost::barrier& cur_barier): trans(t), tm(mt), priority_tm(priority_m), coalesced(c), start(st), barier(cur_barier) {} }; void *send_normal_messages(void *arguments) { struct msg_send_args *args = (struct msg_send_args *)arguments; amplusplus::transport& trans = args->trans; amplusplus::message_type<int> tm = args->tm; amplusplus::message_type<int> priority_tm = args->priority_tm; if (!(args->coalesced)) { // wait till both threads reach here args->barier.wait(); // message sending must be within an epoch amplusplus::scoped_epoch epoch(trans); { if (trans.rank() == 0) { // boost::shared_ptr<int> msg = boost::make_shared<int>(0); for(int j=0; j<MSG_SIZE; ++j) { tm.message_being_built(1); priority_tm.message_being_built(1); tm.send(&j, 1, 1, empty_deleter()); // even - non priority ++j; priority_tm.send(&j, 1, 1, empty_deleter()); //odd - priority } } } } else { // TODO } return NULL; } void run_test(amplusplus::environment& env) { std::cout << "Inside run test" << std::endl; amplusplus::transport trans = env.create_transport(); std::cout << "Transport size " << trans.size() << std::endl; BOOST_ASSERT (trans.size() == 2); // sending normal messages amplusplus::message_type<int> tm = trans.create_message_type<int>(); tm.set_max_count(1); tm.set_handler(message_priority_handler(tm, trans)); // sending priority messages amplusplus::message_type<int> ptm = trans.create_message_type<int>(1); ptm.set_max_count(1); ptm.set_handler(message_priority_handler(ptm, trans)); bool coalesced = false; // create the barier for 2 threads boost::barrier bar(2); struct msg_send_args args(trans,tm, ptm, coalesced, 0, bar); // struct msg_send_args pargs(trans,ptm, coalesced, MSG_SIZE); if (trans.rank() == 0) { // set number of threads to 2 trans.set_nthreads(2); // { amplusplus::scoped_epoch epoch(trans); } // create threads pthread_t normal_thread, priority_thread; int ret = 0; // create thread to send priority messages ret = pthread_create(&priority_thread, NULL, send_normal_messages, (void*)&args); if(ret) { std::cerr << "ERROR - Error creating the normal thread. Error code - " << ret << std::endl; return; } // create thread to send non priority messages ret = pthread_create(&normal_thread, NULL, send_normal_messages, (void*)&args); if(ret) { std::cerr << "ERROR - Error creating the normal thread. Error code - " << ret << std::endl; return; } // wait till threads finishes pthread_join(normal_thread, NULL); pthread_join(priority_thread, NULL); trans.set_nthreads(1); std::cout << "Finish sending messages ..." << std::endl; } else { // do nothing, but need epoch for termination detection amplusplus::scoped_epoch epoch(trans); // register handler for the message types } { amplusplus::scoped_epoch epoch(trans); } if (trans.rank() == 1) { non_priority_time = non_priority_time - time_at_start; priority_time = priority_time - time_at_start; std::cout << "The priority time - " << priority_time << " non-priority time - " << non_priority_time << std::endl; // for rank 1 - we should be receiving priority messages before non priority messages std::cout << "The difference - " << non_priority_time - priority_time << " the ratio - " << non_priority_time / priority_time << std::endl; BOOST_ASSERT(priority_time < non_priority_time * 0.99); } } int main(int argc, char** argv) { std::cout << "Main starting ..." << std::endl; amplusplus::environment env = amplusplus::mpi_environment(argc, argv, false, 1, 10000); time_at_start = get_time(); run_test(env); }
28.589744
142
0.686816
thejkane
87a489338e02421b98e439ca06c363be05326079
22
cpp
C++
test/SIM_isystem/models/third_party/Warning.cpp
iamthad/trick
88ac5b5990228e42a653347c9d7a103acea4d137
[ "NASA-1.3" ]
647
2015-05-07T16:08:16.000Z
2022-03-30T02:33:21.000Z
test/SIM_isystem/models/third_party/Warning.cpp
tanglemontree/trick
f182c723495185708434e67789457eb29d52ad58
[ "NASA-1.3" ]
995
2015-04-30T19:44:31.000Z
2022-03-31T20:14:44.000Z
test/SIM_isystem/models/third_party/Warning.cpp
tanglemontree/trick
f182c723495185708434e67789457eb29d52ad58
[ "NASA-1.3" ]
251
2015-05-15T09:24:34.000Z
2022-03-22T20:39:05.000Z
#include <Warning.hh>
11
21
0.727273
iamthad
87a65939b208840ff4e2d1558aa4447830597e51
1,528
cpp
C++
codeforces/4d.mysterious-present/4d.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
3
2018-01-19T14:09:23.000Z
2018-02-01T00:40:55.000Z
codeforces/4d.mysterious-present/4d.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
null
null
null
codeforces/4d.mysterious-present/4d.cpp
KayvanMazaheri/acm
aeb05074bc9b9c92f35b6a741183da09a08af85d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #define X first #define Y second using namespace std; const int MAX_N = 5e3 + 123; typedef pair <int, int> point; typedef pair <point, int> tp; vector <tp> vec; point dp[MAX_N]; vector <int> result; bool CMP(tp a, tp b) { if ((long long) a.X.X * (long long) a.X.Y == (long long) b.X.X * (long long) b.X.Y) return a.X.X < b.X.X; return (long long) a.X.X * (long long) a.X.Y < (long long) b.X.X * (long long) b.X.Y; } int main() { int n, x0, y0; cin >> n >> x0 >> y0; for(int i=0; i<n; i++) { point inp; cin >> inp.X >> inp.Y; if (inp.X > x0 && inp.Y > y0) vec.push_back(make_pair(inp, i)); } sort(vec.begin(), vec.end(), CMP); for(int i=0; i<vec.size(); i++) { dp[vec[i].Y] = make_pair (1, -1); for(int j=0; j<i; j++) { if (vec[j].X.X < vec[i].X.X && vec[j].X.Y < vec[i].X.Y) if (dp[vec[j].Y].X + 1 > dp[vec[i].Y].X) dp[vec[i].Y] = make_pair (dp[vec[j].Y].X + 1, vec[j].Y); } } // cerr << endl << "\t Test data :" << endl; // for(int i=0; i<vec.size(); i++) // cerr << i << ": " << vec[i].Y << " " << vec[i].X.X << " " << vec[i].X.Y << " sz : " << dp[vec[i].Y].X << " par : " << dp[vec[i].Y].Y << endl; int _mx = max_element(dp, dp+MAX_N) - dp; int pos = _mx; while(pos != -1 && dp[_mx].X) { result.push_back(pos + 1); pos = dp[pos].Y; } reverse(result.begin(), result.end()); cout << result.size() << endl; for(int i=0; i<result.size(); i++) cout << result[i] << " "; cout << endl; return 0; }
22.144928
150
0.521597
KayvanMazaheri
87ab3ef53b136b43f93bdec284d6f777eb097868
1,546
cpp
C++
cpp/codeforces/educational/educational_108/C.cpp
nirvanarsc/CompetitiveProgramming
218ae447bbf7455e4953e05220418b7c32ee6b0e
[ "MIT" ]
2
2021-06-02T16:11:46.000Z
2021-12-23T20:37:02.000Z
cpp/codeforces/educational/educational_108/C.cpp
nirvanarsc/CompetitiveProgramming
218ae447bbf7455e4953e05220418b7c32ee6b0e
[ "MIT" ]
null
null
null
cpp/codeforces/educational/educational_108/C.cpp
nirvanarsc/CompetitiveProgramming
218ae447bbf7455e4953e05220418b7c32ee6b0e
[ "MIT" ]
1
2021-05-14T14:19:14.000Z
2021-05-14T14:19:14.000Z
#include <bits/stdc++.h> #define fast_io \ ios::sync_with_stdio(false); \ cin.tie(nullptr); using ll = long long; using namespace std; signed main() { fast_io; int t; cin >> t; for (int test = 0; test < t; test++) { int n; cin >> n; int u[n]; int s[n]; vector<vector<int>> g(n); for (int i = 0; i < n; i++) { cin >> u[i]; u[i]--; } for (int i = 0; i < n; i++) { cin >> s[i]; g[u[i]].push_back(s[i]); } unordered_map<int, vector<ll>> map; unordered_map<int, vector<ll>> pre; for (int i = 0; i < n; i++) { if (g[i].size() > 0) { sort(g[i].begin(), g[i].end()); reverse(g[i].begin(), g[i].end()); if (!map.count(g[i].size())) { map[g[i].size()] = vector<ll>(g[i].size()); } for (int j = 0; j < g[i].size(); j++) { map[g[i].size()][j] += g[i][j]; } } } int maxL = 0; for (auto it = map.begin(); it != map.end(); ++it) { maxL = max(maxL, it->first); pre[it->first] = vector<ll>(it->first + 1); for (int j = 1; j <= it->second.size(); j++) { pre[it->first][j] = pre[it->first][j - 1] + it->second[j - 1]; } } ll* res = (ll*)(calloc(n, sizeof(ll))); for (int L = 1; L <= maxL; L++) { for (auto it = map.begin(); it != map.end(); ++it) { res[L - 1] += pre[it->first][it->first - (it->first % L)]; } } for (int i = 0; i < n; i++) { cout << res[i] << " "; } cout << "\n"; } }
25.766667
70
0.42238
nirvanarsc
87ac94d23f080e504353b154c99c380a4f2dd414
20,108
cpp
C++
bin/.log/data_preprocessor.cpp
GMAP/GMaVis
1950ea3a57e1f359f2de9f07d81023e3d26417b8
[ "MIT" ]
null
null
null
bin/.log/data_preprocessor.cpp
GMAP/GMaVis
1950ea3a57e1f359f2de9f07d81023e3d26417b8
[ "MIT" ]
null
null
null
bin/.log/data_preprocessor.cpp
GMAP/GMaVis
1950ea3a57e1f359f2de9f07d81023e3d26417b8
[ "MIT" ]
null
null
null
/* *************************************************************************** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. * **************************************************************************** * Authors: Cleverson Ledur <cleversonledur@gmail.com> * Copyright: GNU General Public License * Description: This is part of the GMaVis Compiler * File Name: preprocessor.cpp * Version: 1.0 (20/10/2015) **************************************************************************** */ int REQUIRED1 = 3-1; int REQUIRED2 = 4-1; #include "sys/sysinfo.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <chrono> #include <fstream> #include <vector> typedef struct { char ***buffer; unsigned long long **counter; }data_to_parse; typedef struct { unsigned long long *result = NULL; unsigned long long count; }filter_data; using namespace std; bool header_in_file=false; filter_data filter(unsigned long long **counter,char ***data, unsigned long long number_of_fields); std::string print_output(unsigned long long filter_finds,unsigned long long **counter,char ***data, unsigned long long *filter, char delimiter, char endRegistry); std::string return_string(char *buffer, unsigned long long count){ std::string string_to_return=""; if(buffer){ for(unsigned long long i=0;i<count;i++){ if(buffer[i]){ string_to_return += buffer[i]; } } } return string_to_return; } unsigned long long return_registry_number(char *buffer, char endregistry, char delimiter,unsigned long long start, unsigned long long end){ unsigned long long registry_n=0; for(unsigned long long i=start;i<=end;i++){ if(buffer[i]==endregistry){ registry_n++; } } return registry_n; } unsigned long long return_fields_number(char delimiter, char endRegistry, char *buffer,unsigned long long start, unsigned long long end){ unsigned long long fields = 0; unsigned long long i; for(i=start;i<=end;i++){ if(buffer[i]==delimiter) fields++; else if(buffer[i]==endRegistry){ fields++; break; } } if(fields < REQUIRED1) { return -1; } if(fields < REQUIRED2) { return -1; } return fields; } bool string_contains(unsigned long long **counter,char ***data, unsigned long long i, int field, std::string value){ std::string field_data = return_string(data[i][field],counter[i][field]); std::size_t found = field_data.find(value); return found!=std::string::npos ? true : false; } bool string_is_equal(unsigned long long **counter,char ***data, unsigned long long i, int field, std::string value){ std::string field_data = return_string(data[i][field],counter[i][field]); return field_data == value ? true : false; } bool string_is_different(unsigned long long **counter,char ***data, unsigned long long i, int field, std::string value){ std::string field_data = return_string(data[i][field],counter[i][field]); std::size_t found = field_data.find(value); return found!=std::string::npos ? false : true; } bool int_is_equal(unsigned long long **counter,char ***data, unsigned long long i, int field, long long int value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value == atoll(field_data.c_str())){ return true; }else{ return false; } } bool int_is_different(unsigned long long **counter,char ***data, unsigned long long i, int field, long long int value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value != atoll(field_data.c_str())){ return true; }else{ return false; } } bool int_is_greater(unsigned long long **counter,char ***data, unsigned long long i, int field, long long int value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value < atoll(field_data.c_str())){ return true; }else{ return false; } } bool int_is_less(unsigned long long **counter,char ***data, unsigned long long i, int field, long long int value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value > atoll(field_data.c_str())){ return true; }else{ return false; } } bool int_is_between(unsigned long long **counter,char ***data, unsigned long long i, int field, long long int value1, long long int value2 ){ std::string field_data = return_string(data[i][field],counter[i][field]); if((value1 < atoll(field_data.c_str()))&&(value2 > atoll(field_data.c_str()))){ return true; }else{ return false; } } bool float_is_equal(unsigned long long **counter,char ***data, unsigned long long i, int field, double value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value == atof(field_data.c_str())){ return true; }else{ return false; } } bool float_is_different(unsigned long long **counter,char ***data, unsigned long long i, int field, double value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value != atof(field_data.c_str())){ return true; }else{ return false; } } bool float_is_greater(unsigned long long **counter,char ***data, unsigned long long i, int field, double value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value < atof(field_data.c_str())){ return true; }else{ return false; } } bool float_is_less(unsigned long long **counter,char ***data, unsigned long long i, int field, double value){ std::string field_data = return_string(data[i][field],counter[i][field]); if(value > atof(field_data.c_str())){ return true; }else{ return false; } } bool float_is_between(unsigned long long **counter,char ***data, unsigned long long i, int field, double value1, double value2 ){ std::string field_data = return_string(data[i][field],counter[i][field]); if((value1 < atof(field_data.c_str()))&&(value2 > atof(field_data.c_str()))){ return true; }else{ return false; } } /****************************************************************************** -> FILE OPERATIONS ******************************************************************************/ data_to_parse file_parser(char *buffer, char endRegistry, char delimiter, unsigned long long start, unsigned long long end){ unsigned long long **counter; char *** array_data; unsigned long long n=0,l=0; for(unsigned long long i=start;i<=end;i++){ if(buffer[i]==endRegistry){ n++; } } l = return_fields_number(delimiter, endRegistry,buffer,start,end); array_data = new char**[n]; counter = new unsigned long long* [n]; unsigned long long row=0; unsigned long long column=0; unsigned long long field_size = 0; for(unsigned long long i=0;i<n;i++){ counter[i] = new unsigned long long[l]; array_data[i] = new char*[l]; for(unsigned long long j=0;j<l;j++){ counter[i][j] = 0; array_data[i][j] = NULL; } if(!array_data[i]) exit(-1); } for(unsigned long long i=start;i<=end;i++){ if(buffer[i]==delimiter){ array_data[row][column] = &buffer[i-field_size]; counter[row][column] = field_size; field_size = 0; column++; } else if (buffer[i]==endRegistry){ array_data[row][column] = &buffer[i-field_size]; counter[row][column] = field_size; row++; field_size = 0; column=0; }else{ field_size += 1; } } data_to_parse data_to_return; data_to_return.buffer = array_data; data_to_return.counter = counter; return (data_to_return); } void desalocate_3D(char ***data, unsigned long long **counter, unsigned long long n){ for(unsigned long long i=0;i<n;i++) { if(data[i] !=NULL) delete [] data[i]; delete [] counter[i]; } delete [] counter; delete [] data; } std::string process_chunk(char *file, unsigned long long start, unsigned long long end, char delimiter, char endRegistry){ unsigned long long **counter; unsigned long long n=0; for(unsigned long long i=start;i<=end;i++){ if(file[i]==endRegistry){ n++; } } char ***data; unsigned long long del = return_fields_number(delimiter,endRegistry, file,start,end); if(del==-1) return ""; unsigned long long del_aux = 0; unsigned long long line=0; /*for(unsigned long long i=start;i<=end;i++){ if(file[i]=='''){ file[i]=' '; } if(file[i]==delimiter){ del_aux ++; } if(file[i]==endRegistry){ del_aux ++; line++; if(del_aux!=del){ std::cout << "ERROR: Data with problem in line " << line << ": " << del_aux << " != " << del << std::endl; exit(-1); } del_aux = 0; } }*/ data_to_parse parsed_data; parsed_data = file_parser(file,endRegistry,delimiter,start,end); data = parsed_data.buffer; counter = parsed_data.counter; filter_data filtered_data = filter(counter,data,n); unsigned long long *x = filtered_data.result; unsigned long long filtered_data_n = filtered_data.count; std::string output = print_output(filtered_data_n,counter,data, x,delimiter,endRegistry); free(x); desalocate_3D(data,counter, n); return (char*)output.c_str(); } unsigned long long recalculate_start(char* buffer,unsigned long long start, unsigned long long lSize ,char endRegistry,char delimiter){ if(buffer[start]==endRegistry){ start++; } unsigned long long n=start; int lines=0,col1=0,col2=0; while(lines==0){ if(buffer[n]==delimiter){ col1++; } if(buffer[n]==endRegistry){ col1++; lines++; } n++; } while(lines==1){ if(buffer[n]==delimiter){ col2++; } if(buffer[n]==endRegistry) { col2++; lines++; } n++; } if(col1!=col2){ for(unsigned long long i = start;i<lSize;i++){ if(buffer[i]==endRegistry){ start=i+1; break; } } } return start; } unsigned long long recalculate_end(char* buffer, unsigned long long lSize,char endRegistry,char delimiter){ /*int start=0; if(buffer[start]==endRegistry){ start++; }*/ /*unsigned long long n=start; int lines=0,col1=0,col2=0; while(lines==0){ if(buffer[n]==delimiter){ col1++; } if(buffer[n]==endRegistry){ col1++; lines++; } n++; } while(lines==1){ if(buffer[n]==delimiter){ col2++; } if(buffer[n]==endRegistry) { col2++; lines++; } n++; } */ for(unsigned long long i=lSize;i>0;i--){ if(buffer[i]==endRegistry){ lSize=i; break; } } return lSize; } static inline ssize_t getNumProcessors() { ssize_t n = 1; FILE * f; f = popen("cat /proc/cpuinfo |grep processor | wc -l","r"); if(fscanf(f,"%ld",& n) == EOF) { pclose (f); return n; } pclose (f); return n; } static inline ssize_t getfile_lines(std::string file_name) { ssize_t n = 1; FILE * f; std::string command = "wc -l " + file_name + " | awk '{print $1}' "; f = popen(command.c_str(),"r"); if(fscanf(f,"%ld",& n) == EOF) { pclose (f); return n; } pclose (f); return n; } bool date_is_between(unsigned long long **counter,char ***data,unsigned long long i, int field, std::string date2, std::string date3){ std::string date1 = return_string(data[i][field],counter[i][field]); int day1=0, month1=0, year1=0; int day2=0, month2=0, year2=0; int day3=0, month3=0, year3=0; int ok; if(year1 > year2){ ok = 0; //printf("%d is greater than %d\n", year1,year2); }else if((year1 == year2) && (month1 > month2)){ ok = 0; }else if((year1 == year2) && (month1 == month2) && (day1 > day2)){ ok = 0; }else{ return false; } if(year1 < year3){ ok = 0; }else if((year1 == year3) && (month1 < month3)){ ok = 0; }else if((year1 == year3) && (month1 == month3) && (day1 < day3)){ ok = 0; }else{ return false; } //printf("%d %d %d is between %d %d %d and %d %d %d\n", day1,month1,year1,day2,month2,year2,day3,month3,year3); if(ok==0) return true; return true; } bool date_is_less(unsigned long long **counter,char ***data, unsigned long long i, int field, std::string date2){ std::string date1 = return_string(data[i][field],counter[i][field]); int day1=0, month1=0, year1=0; int day2=0, month2=0, year2=0; if(year1 < year2){ return true; }else if((year1==year2)&&(month1<month2)){ return true; }else if((year1==year2)&&(month1 == month2)&&(day1<day2)){ return true; }else{ return false; } } bool date_is_greater(unsigned long long **counter,char ***data,unsigned long long i, int field, std::string date2){ std::string date1 = return_string(data[i][field],counter[i][field]); int day1=0, month1=0, year1=0; int day2=0, month2=0, year2=0; if(year1 > year2){ return true; }else if((year1==year2)&&(month1>month2)){ return true; }else if((year1==year2)&&(month1 == month2)&&(day1>day2)){ return true; }else{ return false; } } bool date_is_equal(unsigned long long **counter,char ***data, unsigned long long i, int field, std::string date2){ std::string date1 = return_string(data[i][field],counter[i][field]); int day1=0, month1=0, year1=0; int day2=0, month2=0, year2=0; if((year1==year2)&&(month1 == month2)&&(day1==day2)){ return true; }else{ return false; } } bool date_is_different(unsigned long long **counter,char ***data, unsigned long long i, int field, std::string date2){ std::string date1 = return_string(data[i][field],counter[i][field]); int day1=0, month1=0, year1=0; int day2=0, month2=0, year2=0; if((year1!=year2)&&(month1 != month2)&&(day1!=day2)){ return true; }else{ return false; } } filter_data filter(unsigned long long **counter,char ***data, unsigned long long number_of_fields){ filter_data filtered_data; unsigned long long *result; unsigned long long count = 0; result = (unsigned long long*)malloc(sizeof(unsigned long long)*number_of_fields); for(unsigned long long i=0;i<number_of_fields;i++){ if((i==0)&&(header_in_file==true)) continue; std::string required_field1 = return_string(data[i][REQUIRED1],counter[i][REQUIRED1]); std::string required_field2 = return_string(data[i][REQUIRED2],counter[i][REQUIRED2]); if( ((strcmp(required_field1.c_str(),(char*)"")!=0) && (strcmp(required_field2.c_str(),(char*)"")!=0)) && (string_is_equal(counter,data,i,13-1,"2016")) ) { result[count]=i; count++; } } filtered_data.result = result; filtered_data.count = count; return filtered_data; } int classification(unsigned long long **counter, char ***data, unsigned long long j,unsigned long long *filter){ unsigned long long i = filter[j]; if(string_is_equal(counter,data,i,11-1,"RS")) return 1; if(string_is_equal(counter,data,i,11-1,"SP")) return 2; if(string_is_equal(counter,data,i,11-1,"RJ")) return 3; if(string_is_equal(counter,data,i,11-1,"MG")) return 4; return 0; } std::string print_output(unsigned long long filter_finds,unsigned long long **counter,char ***data, unsigned long long *filter, char delimiter, char endRegistry){ std::string output_aux; std::string output; for(unsigned long long i=0;i<filter_finds;i++){ int classification_class = classification(counter,data,i,filter); if(classification_class!=0){ output_aux = return_string(data[filter[i]][REQUIRED1],counter[filter[i]][REQUIRED1]) + delimiter + return_string(data[filter[i]][REQUIRED2],counter[filter[i]][REQUIRED2])+delimiter+ std::to_string(classification_class) + endRegistry; output+=output_aux; } } return output; } int threads = 3; int main(){ std::vector < std::string > files; std::vector <bool> files_header_info; files.push_back("examples/datasets/saude_brasil.csv"); files_header_info.push_back(true); [[spar::ToStream(),spar::Input(files,files_header_info)]]while(!files.empty()){ std::cout << "Starting processing of file " << files.back() << "\n"; header_in_file = files_header_info.back(); std::string filename = files.back(); char delimiter = ';'; char endRegistry = '\n'; long long start = 0,end=0; unsigned long long total_processed = 0; unsigned long freeMem = 0; unsigned long long chunk_size = 104857600; //printf("Free Memory: %f\n", ((float)freeMem/1024)/1024); //printf("Chunk size: %f\n", ((float)chunk_size/1024)/1024); unsigned long long last_read = 0; unsigned long long file_size = 0; int num_processors = getNumProcessors(); //Open File FILE *pFile; pFile = fopen((const char*)filename.c_str(),"r"); if(pFile==NULL){ printf("\n\nERROR: Hey! I can not open this file! Verify this file specificaion in your code...\n"); exit(-1); } //printf("Loading file %s to buffer.\n",filename); fseek (pFile , 0 , SEEK_END); file_size = ftell (pFile); auto t_start = std::chrono::high_resolution_clock::now(); while(last_read < file_size){ //std::cout << "Begining new processing...\n"; int chunk_count = 0; rewind (pFile); unsigned long long read_size = 0; if(file_size - last_read < chunk_size){ read_size = file_size - last_read; //std::cout << "Last reading...\n"; if(read_size<100){ //Junk data like \n in the end of file\n break; } }else{ //std::cout << "Middle reading...\n"; read_size = chunk_size; } //std::cout << "\nread_size: " << read_size << std::endl; char * buffer=NULL; buffer = new char[read_size]; if(buffer!=NULL){ fseek(pFile, last_read, SEEK_SET); //std::cout << "\nread_size2: " << read_size << std::endl; if(fread (buffer,1,read_size,pFile) != read_size){ std::cerr << "ERROR: Error when reading file.\n"; exit(-1); } }else{ std::cerr << "ERROR: Error in malloc of buffer when reading file.\n"; } //std::cout << "\nread_size3:\t\t" << read_size << std::endl; start =1; //start = recalculate_start(buffer,end,read_size,endRegistry,delimiter); end = read_size; end = recalculate_end(buffer,end,endRegistry,delimiter); last_read += end; total_processed=end; chunk_count +=1; std::cout << "chunk_size: " << chunk_size << std::endl; std::cout << "file_size: " << file_size << std::endl; std::cout << "last_read: " << last_read << std::endl; std::cout << "total_processed: " << total_processed << std::endl; std::cout << "chunk_count: " << chunk_count << std::endl; std::cout << "end: " << end << std::endl; std::cout << "start: " << start << std::endl; std::string output_chunk; [[spar::Stage(),spar::Input(buffer,output_chunk,start,end,delimiter,endRegistry),spar::Output(output_chunk),spar::Replicate(threads)]]{ output_chunk = process_chunk(buffer,start,end,delimiter,endRegistry); delete [] buffer; } [[spar::Stage(),spar::Input(output_chunk)]]{ std::ofstream out_file; out_file.open ("/home/cleversonledur/SVN_REPOS/GMaVis/compiler/build/bin/.log/output",std::ios::app); if(out_file.fail()){ std::cout << "ERROR to open file\n"; exit(-1); } out_file << output_chunk; out_file.close(); } } auto t_end = std::chrono::high_resolution_clock::now(); std::cout << " " << std::chrono::duration<double>(t_end-t_start).count() << " "; fclose(pFile); files.pop_back(); } return 0; }
26.597884
237
0.656654
GMAP
87ad6e3a9f7518f9cd01c20e872cc5afc9cbf15a
55,227
cpp
C++
build_1/third_party/omr/jitbuilderclient/cpp/IlBuilder.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
build_1/third_party/omr/jitbuilderclient/cpp/IlBuilder.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
build_1/third_party/omr/jitbuilderclient/cpp/IlBuilder.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2019, 2019 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #include "ilgen/BytecodeBuilder.hpp" #include "ilgen/IlBuilder.hpp" #include "ilgen/MethodBuilder.hpp" #include "ilgen/IlType.hpp" #include "ilgen/IlValue.hpp" #include "ilgen/ThunkBuilder.hpp" #include "ilgen/TypeDictionary.hpp" #include "ilgen/VirtualMachineOperandArray.hpp" #include "ilgen/VirtualMachineOperandStack.hpp" #include "ilgen/VirtualMachineRegister.hpp" #include "ilgen/VirtualMachineRegisterInStruct.hpp" #include "ilgen/VirtualMachineState.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/Macros.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/BytecodeBuilder.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/IlBuilder.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/MethodBuilder.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/IlType.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/IlValue.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/ThunkBuilder.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/TypeDictionary.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/VirtualMachineOperandArray.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/VirtualMachineOperandStack.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/VirtualMachineRegister.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/VirtualMachineRegisterInStruct.hpp" #include "/Users/cijiexia/Project/lljb/third_party/omr/jitbuilder/release/cpp/include/VirtualMachineState.hpp" namespace OMR { namespace JitBuilder { extern "C" void * getImpl_JBCase(void * client) { return static_cast<TR::IlBuilder::JBCase *>(static_cast<IlBuilder::JBCase *>(client)->_impl); } IlBuilder::JBCase::JBCase(int32_t caseValue, IlBuilder * caseBuilder, int32_t caseFallsThrough) { auto * impl = ::new TR::IlBuilder::JBCase(caseValue, static_cast<TR::IlBuilder *>(caseBuilder != NULL ? caseBuilder->_impl : NULL), caseFallsThrough); static_cast<TR::IlBuilder::JBCase *>(impl)->setClient(this); initializeFromImpl(static_cast<void *>(impl)); } IlBuilder::JBCase::JBCase(void * impl) { if (impl != NULL) { static_cast<TR::IlBuilder::JBCase *>(impl)->setClient(this); initializeFromImpl(impl); } } void IlBuilder::JBCase::initializeFromImpl(void * impl) { _impl = impl; static_cast<TR::IlBuilder::JBCase *>(_impl)->setGetImpl(&getImpl_JBCase); } IlBuilder::JBCase::~JBCase() {} extern "C" void * allocateIlBuilderJBCase(void * impl) { return new IlBuilder::JBCase(impl); } extern "C" void * getImpl_JBCondition(void * client) { return static_cast<TR::IlBuilder::JBCondition *>(static_cast<IlBuilder::JBCondition *>(client)->_impl); } IlBuilder::JBCondition::JBCondition(IlBuilder * conditionBuilder, IlValue * conditionValue) { auto * impl = ::new TR::IlBuilder::JBCondition(static_cast<TR::IlBuilder *>(conditionBuilder != NULL ? conditionBuilder->_impl : NULL), static_cast<TR::IlValue *>(conditionValue != NULL ? conditionValue->_impl : NULL)); static_cast<TR::IlBuilder::JBCondition *>(impl)->setClient(this); initializeFromImpl(static_cast<void *>(impl)); } IlBuilder::JBCondition::JBCondition(void * impl) { if (impl != NULL) { static_cast<TR::IlBuilder::JBCondition *>(impl)->setClient(this); initializeFromImpl(impl); } } void IlBuilder::JBCondition::initializeFromImpl(void * impl) { _impl = impl; static_cast<TR::IlBuilder::JBCondition *>(_impl)->setGetImpl(&getImpl_JBCondition); } IlBuilder::JBCondition::~JBCondition() {} extern "C" void * allocateIlBuilderJBCondition(void * impl) { return new IlBuilder::JBCondition(impl); } extern "C" bool IlBuilderCallback_buildIL(void * clientObj) { IlBuilder * client = static_cast<IlBuilder *>(clientObj); return client->buildIL(); } extern "C" void * getImpl_IlBuilder(void * client) { return static_cast<TR::IlBuilder *>(static_cast<IlBuilder *>(client)->_impl); } IlBuilder::IlBuilder(void * impl) { if (impl != NULL) { static_cast<TR::IlBuilder *>(impl)->setClient(this); initializeFromImpl(impl); } } void IlBuilder::initializeFromImpl(void * impl) { _impl = impl; GET_CLIENT_OBJECT(clientObj_NoType, IlType, static_cast<TR::IlBuilder *>(_impl)->NoType); NoType = clientObj_NoType; GET_CLIENT_OBJECT(clientObj_Int8, IlType, static_cast<TR::IlBuilder *>(_impl)->Int8); Int8 = clientObj_Int8; GET_CLIENT_OBJECT(clientObj_Int16, IlType, static_cast<TR::IlBuilder *>(_impl)->Int16); Int16 = clientObj_Int16; GET_CLIENT_OBJECT(clientObj_Int32, IlType, static_cast<TR::IlBuilder *>(_impl)->Int32); Int32 = clientObj_Int32; GET_CLIENT_OBJECT(clientObj_Int64, IlType, static_cast<TR::IlBuilder *>(_impl)->Int64); Int64 = clientObj_Int64; GET_CLIENT_OBJECT(clientObj_Float, IlType, static_cast<TR::IlBuilder *>(_impl)->Float); Float = clientObj_Float; GET_CLIENT_OBJECT(clientObj_Double, IlType, static_cast<TR::IlBuilder *>(_impl)->Double); Double = clientObj_Double; GET_CLIENT_OBJECT(clientObj_Address, IlType, static_cast<TR::IlBuilder *>(_impl)->Address); Address = clientObj_Address; GET_CLIENT_OBJECT(clientObj_VectorInt8, IlType, static_cast<TR::IlBuilder *>(_impl)->VectorInt8); VectorInt8 = clientObj_VectorInt8; GET_CLIENT_OBJECT(clientObj_VectorInt16, IlType, static_cast<TR::IlBuilder *>(_impl)->VectorInt16); VectorInt16 = clientObj_VectorInt16; GET_CLIENT_OBJECT(clientObj_VectorInt32, IlType, static_cast<TR::IlBuilder *>(_impl)->VectorInt32); VectorInt32 = clientObj_VectorInt32; GET_CLIENT_OBJECT(clientObj_VectorInt64, IlType, static_cast<TR::IlBuilder *>(_impl)->VectorInt64); VectorInt64 = clientObj_VectorInt64; GET_CLIENT_OBJECT(clientObj_VectorFloat, IlType, static_cast<TR::IlBuilder *>(_impl)->VectorFloat); VectorFloat = clientObj_VectorFloat; GET_CLIENT_OBJECT(clientObj_VectorDouble, IlType, static_cast<TR::IlBuilder *>(_impl)->VectorDouble); VectorDouble = clientObj_VectorDouble; GET_CLIENT_OBJECT(clientObj_Word, IlType, static_cast<TR::IlBuilder *>(_impl)->Word); Word = clientObj_Word; static_cast<TR::IlBuilder *>(_impl)->setClientCallback_buildIL(reinterpret_cast<void*>(&IlBuilderCallback_buildIL)); static_cast<TR::IlBuilder *>(_impl)->setGetImpl(&getImpl_IlBuilder); } IlBuilder::~IlBuilder() {} IlBuilder * IlBuilder::OrphanBuilder() { TR::IlBuilder * implRet = static_cast<TR::IlBuilder *>(_impl)->OrphanBuilder(); GET_CLIENT_OBJECT(clientObj, IlBuilder, implRet); return clientObj; } BytecodeBuilder * IlBuilder::OrphanBytecodeBuilder(int32_t bcIndex, char * name) { TR::BytecodeBuilder * implRet = static_cast<TR::IlBuilder *>(_impl)->OrphanBytecodeBuilder(bcIndex, name); GET_CLIENT_OBJECT(clientObj, BytecodeBuilder, implRet); return clientObj; } IlValue * IlBuilder::Copy(IlValue * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Copy(static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } TypeDictionary * IlBuilder::typeDictionary() { TR::TypeDictionary * implRet = static_cast<TR::IlBuilder *>(_impl)->typeDictionary(); GET_CLIENT_OBJECT(clientObj, TypeDictionary, implRet); return clientObj; } IlValue * IlBuilder::ConstInteger(IlType * type, int64_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstInteger(static_cast<TR::IlType *>(type != NULL ? type->_impl : NULL), value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstAddress(void * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstAddress(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstDouble(double value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstDouble(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstFloat(float value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstFloat(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstInt8(int8_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstInt8(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstInt16(int16_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstInt16(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstInt32(int32_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstInt32(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstInt64(int64_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstInt64(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConstString(char * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConstString(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(void * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(double value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(float value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(int8_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(int16_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(int32_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Const(int64_t value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Const(value); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::NullAddress() { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->NullAddress(); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Add(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Add(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::AddWithOverflow(IlBuilder ** overflowHandler, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, overflowHandlerImpl, overflowHandlerArg, overflowHandler); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->AddWithOverflow(overflowHandlerArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, overflowHandlerImpl, overflowHandler); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::AddWithUnsignedOverflow(IlBuilder ** overflowHandler, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, overflowHandlerImpl, overflowHandlerArg, overflowHandler); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->AddWithUnsignedOverflow(overflowHandlerArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, overflowHandlerImpl, overflowHandler); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::And(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->And(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Div(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Div(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedDiv(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedDiv(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::IndexAt(IlType * dt, IlValue * base, IlValue * index) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->IndexAt(static_cast<TR::IlType *>(dt != NULL ? dt->_impl : NULL), static_cast<TR::IlValue *>(base != NULL ? base->_impl : NULL), static_cast<TR::IlValue *>(index != NULL ? index->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Mul(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Mul(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::MulWithOverflow(IlBuilder ** overflowHandler, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, overflowHandlerImpl, overflowHandlerArg, overflowHandler); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->MulWithOverflow(overflowHandlerArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, overflowHandlerImpl, overflowHandler); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Negate(IlValue * v) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Negate(static_cast<TR::IlValue *>(v != NULL ? v->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Or(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Or(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Rem(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Rem(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedRem(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedRem(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ShiftL(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ShiftL(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ShiftR(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ShiftR(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Sub(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Sub(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::SubWithOverflow(IlBuilder ** overflowHandler, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, overflowHandlerImpl, overflowHandlerArg, overflowHandler); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->SubWithOverflow(overflowHandlerArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, overflowHandlerImpl, overflowHandler); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::SubWithUnsignedOverflow(IlBuilder ** overflowHandler, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, overflowHandlerImpl, overflowHandlerArg, overflowHandler); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->SubWithUnsignedOverflow(overflowHandlerArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, overflowHandlerImpl, overflowHandler); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedShiftR(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedShiftR(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Xor(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Xor(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::EqualTo(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->EqualTo(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::LessOrEqualTo(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->LessOrEqualTo(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::LessThan(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->LessThan(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::GreaterOrEqualTo(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->GreaterOrEqualTo(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::GreaterThan(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->GreaterThan(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::NotEqualTo(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->NotEqualTo(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedLessOrEqualTo(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedLessOrEqualTo(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedLessThan(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedLessThan(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedGreaterOrEqualTo(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedGreaterOrEqualTo(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedGreaterThan(IlValue * left, IlValue * right) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedGreaterThan(static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConvertBitsTo(IlType * type, IlValue * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConvertBitsTo(static_cast<TR::IlType *>(type != NULL ? type->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ConvertTo(IlType * type, IlValue * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ConvertTo(static_cast<TR::IlType *>(type != NULL ? type->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnsignedConvertTo(IlType * type, IlValue * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnsignedConvertTo(static_cast<TR::IlType *>(type != NULL ? type->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::AtomicAdd(IlValue * baseAddress, IlValue * value) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->AtomicAdd(static_cast<TR::IlValue *>(baseAddress != NULL ? baseAddress->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::CreateLocalArray(int32_t numElements, IlType * elementType) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->CreateLocalArray(numElements, static_cast<TR::IlType *>(elementType != NULL ? elementType->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::CreateLocalStruct(IlType * structType) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->CreateLocalStruct(static_cast<TR::IlType *>(structType != NULL ? structType->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Load(const char * name) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Load(name); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::LoadAt(IlType * type, IlValue * address) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->LoadAt(static_cast<TR::IlType *>(type != NULL ? type->_impl : NULL), static_cast<TR::IlValue *>(address != NULL ? address->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::LoadIndirect(const char * type, const char * field, IlValue * object) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->LoadIndirect(type, field, static_cast<TR::IlValue *>(object != NULL ? object->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } void IlBuilder::Store(const char * name, IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->Store(name, static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::StoreAt(IlValue * address, IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->StoreAt(static_cast<TR::IlValue *>(address != NULL ? address->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::StoreIndirect(const char * type, const char * field, IlValue * object, IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->StoreIndirect(type, field, static_cast<TR::IlValue *>(object != NULL ? object->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::StoreOver(IlValue * dest, IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->StoreOver(static_cast<TR::IlValue *>(dest != NULL ? dest->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::Transaction(IlBuilder ** persistentFailureBuilder, IlBuilder ** transientFailureBuilder, IlBuilder ** transactionBuilder) { ARG_SETUP(IlBuilder, persistentFailureBuilderImpl, persistentFailureBuilderArg, persistentFailureBuilder); ARG_SETUP(IlBuilder, transientFailureBuilderImpl, transientFailureBuilderArg, transientFailureBuilder); ARG_SETUP(IlBuilder, transactionBuilderImpl, transactionBuilderArg, transactionBuilder); static_cast<TR::IlBuilder *>(_impl)->Transaction(persistentFailureBuilderArg, transientFailureBuilderArg, transactionBuilderArg); ARG_RETURN(IlBuilder, persistentFailureBuilderImpl, persistentFailureBuilder); ARG_RETURN(IlBuilder, transientFailureBuilderImpl, transientFailureBuilder); ARG_RETURN(IlBuilder, transactionBuilderImpl, transactionBuilder); } void IlBuilder::TransactionAbort() { static_cast<TR::IlBuilder *>(_impl)->TransactionAbort(); } IlValue * IlBuilder::StructFieldInstanceAddress(const char * structName, const char * fieldName, IlValue * obj) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->StructFieldInstanceAddress(structName, fieldName, static_cast<TR::IlValue *>(obj != NULL ? obj->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::UnionFieldInstanceAddress(const char * unionName, const char * fieldName, IlValue * obj) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->UnionFieldInstanceAddress(unionName, fieldName, static_cast<TR::IlValue *>(obj != NULL ? obj->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::VectorLoad(char * name) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->VectorLoad(name); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::VectorLoadAt(IlType * type, IlValue * address) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->VectorLoadAt(static_cast<TR::IlType *>(type != NULL ? type->_impl : NULL), static_cast<TR::IlValue *>(address != NULL ? address->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } void IlBuilder::VectorStore(char * name, IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->VectorStore(name, static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::VectorStoreAt(IlValue * address, IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->VectorStoreAt(static_cast<TR::IlValue *>(address != NULL ? address->_impl : NULL), static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::AppendBuilder(IlBuilder * b) { static_cast<TR::IlBuilder *>(_impl)->AppendBuilder(static_cast<TR::IlBuilder *>(b != NULL ? b->_impl : NULL)); } IlValue * IlBuilder::Call(const char * name, int32_t numArgs, IlValue ** arguments) { ARRAY_ARG_SETUP(IlValue, numArgs, argumentsArg, arguments); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Call(name, numArgs, argumentsArg); ARRAY_ARG_RETURN(IlValue, numArgs, argumentsArg, arguments); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Call(const char * name, int32_t numArgs, ...) { IlValue ** arguments = new IlValue *[numArgs]; va_list vararg; va_start(vararg, numArgs); for (int i = 0; i < numArgs; ++i) { arguments[i] = va_arg(vararg, IlValue *); } va_end(vararg); IlValue * ret = Call(name, numArgs, arguments); delete[] arguments; return ret; } IlValue * IlBuilder::Call(MethodBuilder * name, int32_t numArgs, IlValue ** arguments) { ARRAY_ARG_SETUP(IlValue, numArgs, argumentsArg, arguments); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Call(static_cast<TR::MethodBuilder *>(static_cast<TR::IlBuilder *>(name != NULL ? name->_impl : NULL)), numArgs, argumentsArg); ARRAY_ARG_RETURN(IlValue, numArgs, argumentsArg, arguments); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::Call(MethodBuilder * name, int32_t numArgs, ...) { IlValue ** arguments = new IlValue *[numArgs]; va_list vararg; va_start(vararg, numArgs); for (int i = 0; i < numArgs; ++i) { arguments[i] = va_arg(vararg, IlValue *); } va_end(vararg); IlValue * ret = Call(name, numArgs, arguments); delete[] arguments; return ret; } IlValue * IlBuilder::ComputedCall(char * name, int32_t numArgs, IlValue ** arguments) { ARRAY_ARG_SETUP(IlValue, numArgs, argumentsArg, arguments); TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->ComputedCall(name, numArgs, argumentsArg); ARRAY_ARG_RETURN(IlValue, numArgs, argumentsArg, arguments); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } IlValue * IlBuilder::ComputedCall(char * name, int32_t numArgs, ...) { IlValue ** arguments = new IlValue *[numArgs]; va_list vararg; va_start(vararg, numArgs); for (int i = 0; i < numArgs; ++i) { arguments[i] = va_arg(vararg, IlValue *); } va_end(vararg); IlValue * ret = ComputedCall(name, numArgs, arguments); delete[] arguments; return ret; } void IlBuilder::DoWhileLoop(char * exitCondition, IlBuilder ** body) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); static_cast<TR::IlBuilder *>(_impl)->DoWhileLoop(exitCondition, bodyArg); ARG_RETURN(IlBuilder, bodyImpl, body); } void IlBuilder::DoWhileLoop(char * exitCondition, IlBuilder ** body, IlBuilder ** breakBuilder, IlBuilder ** continueBuilder) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, breakBuilderImpl, breakBuilderArg, breakBuilder); ARG_SETUP(IlBuilder, continueBuilderImpl, continueBuilderArg, continueBuilder); static_cast<TR::IlBuilder *>(_impl)->DoWhileLoop(exitCondition, bodyArg, breakBuilderArg, continueBuilderArg); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, breakBuilderImpl, breakBuilder); ARG_RETURN(IlBuilder, continueBuilderImpl, continueBuilder); } void IlBuilder::DoWhileLoopWithBreak(char * exitCondition, IlBuilder ** body, IlBuilder ** breakBuilder) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, breakBuilderImpl, breakBuilderArg, breakBuilder); static_cast<TR::IlBuilder *>(_impl)->DoWhileLoopWithBreak(exitCondition, bodyArg, breakBuilderArg); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, breakBuilderImpl, breakBuilder); } void IlBuilder::DoWhileLoopWithContinue(char * exitCondition, IlBuilder ** body, IlBuilder ** continueBuilder) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, continueBuilderImpl, continueBuilderArg, continueBuilder); static_cast<TR::IlBuilder *>(_impl)->DoWhileLoopWithContinue(exitCondition, bodyArg, continueBuilderArg); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, continueBuilderImpl, continueBuilder); } void IlBuilder::Goto(IlBuilder * b) { static_cast<TR::IlBuilder *>(_impl)->Goto(static_cast<TR::IlBuilder *>(b != NULL ? b->_impl : NULL)); } void IlBuilder::Goto(IlBuilder ** b) { ARG_SETUP(IlBuilder, bImpl, bArg, b); static_cast<TR::IlBuilder *>(_impl)->Goto(bArg); ARG_RETURN(IlBuilder, bImpl, b); } IlBuilder::JBCondition * IlBuilder::MakeCondition(IlBuilder * conditionBuilder, IlValue * conditionValue) { TR::IlBuilder::JBCondition * implRet = static_cast<TR::IlBuilder *>(_impl)->MakeCondition(static_cast<TR::IlBuilder *>(conditionBuilder != NULL ? conditionBuilder->_impl : NULL), static_cast<TR::IlValue *>(conditionValue != NULL ? conditionValue->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, JBCondition, implRet); return clientObj; } void IlBuilder::IfAnd(IlBuilder ** allTrueBuilder, IlBuilder ** anyFalseBuilder, int32_t numTerms, IlBuilder::JBCondition ** terms) { ARG_SETUP(IlBuilder, allTrueBuilderImpl, allTrueBuilderArg, allTrueBuilder); ARG_SETUP(IlBuilder, anyFalseBuilderImpl, anyFalseBuilderArg, anyFalseBuilder); ARRAY_ARG_SETUP(IlBuilder::JBCondition, numTerms, termsArg, terms); static_cast<TR::IlBuilder *>(_impl)->IfAnd(allTrueBuilderArg, anyFalseBuilderArg, numTerms, termsArg); ARG_RETURN(IlBuilder, allTrueBuilderImpl, allTrueBuilder); ARG_RETURN(IlBuilder, anyFalseBuilderImpl, anyFalseBuilder); ARRAY_ARG_RETURN(IlBuilder::JBCondition, numTerms, termsArg, terms); } void IlBuilder::IfAnd(IlBuilder ** allTrueBuilder, IlBuilder ** anyFalseBuilder, int32_t numTerms, ...) { IlBuilder::JBCondition ** terms = new IlBuilder::JBCondition *[numTerms]; va_list vararg; va_start(vararg, numTerms); for (int i = 0; i < numTerms; ++i) { terms[i] = va_arg(vararg, IlBuilder::JBCondition *); } va_end(vararg); IfAnd(allTrueBuilder, anyFalseBuilder, numTerms, terms); delete[] terms; } void IlBuilder::IfCmpEqual(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpEqual(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpEqual(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpEqual(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpLessOrEqual(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpLessOrEqual(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpLessOrEqual(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpLessOrEqual(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpLessThan(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpLessThan(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpLessThan(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpLessThan(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpGreaterOrEqual(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpGreaterOrEqual(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpGreaterOrEqual(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpGreaterOrEqual(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpGreaterThan(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpGreaterThan(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpGreaterThan(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpGreaterThan(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpNotEqual(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpNotEqual(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpNotEqual(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpNotEqual(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpUnsignedLessOrEqual(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedLessOrEqual(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpUnsignedLessOrEqual(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedLessOrEqual(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpUnsignedLessThan(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedLessThan(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpUnsignedLessThan(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedLessThan(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpUnsignedGreaterOrEqual(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedGreaterOrEqual(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpUnsignedGreaterOrEqual(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedGreaterOrEqual(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpUnsignedGreaterThan(IlBuilder * target, IlValue * left, IlValue * right) { static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedGreaterThan(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); } void IlBuilder::IfCmpUnsignedGreaterThan(IlBuilder ** target, IlValue * left, IlValue * right) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpUnsignedGreaterThan(targetArg, static_cast<TR::IlValue *>(left != NULL ? left->_impl : NULL), static_cast<TR::IlValue *>(right != NULL ? right->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpEqualZero(IlBuilder * target, IlValue * condition) { static_cast<TR::IlBuilder *>(_impl)->IfCmpEqualZero(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL)); } void IlBuilder::IfCmpEqualZero(IlBuilder ** target, IlValue * condition) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpEqualZero(targetArg, static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfCmpNotEqualZero(IlBuilder * target, IlValue * condition) { static_cast<TR::IlBuilder *>(_impl)->IfCmpNotEqualZero(static_cast<TR::IlBuilder *>(target != NULL ? target->_impl : NULL), static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL)); } void IlBuilder::IfCmpNotEqualZero(IlBuilder ** target, IlValue * condition) { ARG_SETUP(IlBuilder, targetImpl, targetArg, target); static_cast<TR::IlBuilder *>(_impl)->IfCmpNotEqualZero(targetArg, static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL)); ARG_RETURN(IlBuilder, targetImpl, target); } void IlBuilder::IfOr(IlBuilder ** anyTrueBuilder, IlBuilder ** allFalseBuilder, int32_t numTerms, IlBuilder::JBCondition ** terms) { ARG_SETUP(IlBuilder, anyTrueBuilderImpl, anyTrueBuilderArg, anyTrueBuilder); ARG_SETUP(IlBuilder, allFalseBuilderImpl, allFalseBuilderArg, allFalseBuilder); ARRAY_ARG_SETUP(IlBuilder::JBCondition, numTerms, termsArg, terms); static_cast<TR::IlBuilder *>(_impl)->IfOr(anyTrueBuilderArg, allFalseBuilderArg, numTerms, termsArg); ARG_RETURN(IlBuilder, anyTrueBuilderImpl, anyTrueBuilder); ARG_RETURN(IlBuilder, allFalseBuilderImpl, allFalseBuilder); ARRAY_ARG_RETURN(IlBuilder::JBCondition, numTerms, termsArg, terms); } void IlBuilder::IfOr(IlBuilder ** anyTrueBuilder, IlBuilder ** allFalseBuilder, int32_t numTerms, ...) { IlBuilder::JBCondition ** terms = new IlBuilder::JBCondition *[numTerms]; va_list vararg; va_start(vararg, numTerms); for (int i = 0; i < numTerms; ++i) { terms[i] = va_arg(vararg, IlBuilder::JBCondition *); } va_end(vararg); IfOr(anyTrueBuilder, allFalseBuilder, numTerms, terms); delete[] terms; } void IlBuilder::IfThen(IlBuilder ** thenPath, IlValue * condition) { ARG_SETUP(IlBuilder, thenPathImpl, thenPathArg, thenPath); static_cast<TR::IlBuilder *>(_impl)->IfThen(thenPathArg, static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL)); ARG_RETURN(IlBuilder, thenPathImpl, thenPath); } void IlBuilder::IfThenElse(IlBuilder ** thenPath, IlBuilder ** elsePath, IlValue * condition) { ARG_SETUP(IlBuilder, thenPathImpl, thenPathArg, thenPath); ARG_SETUP(IlBuilder, elsePathImpl, elsePathArg, elsePath); static_cast<TR::IlBuilder *>(_impl)->IfThenElse(thenPathArg, elsePathArg, static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL)); ARG_RETURN(IlBuilder, thenPathImpl, thenPath); ARG_RETURN(IlBuilder, elsePathImpl, elsePath); } IlValue * IlBuilder::Select(IlValue * condition, IlValue * trueValue, IlValue * falseValue) { TR::IlValue * implRet = static_cast<TR::IlBuilder *>(_impl)->Select(static_cast<TR::IlValue *>(condition != NULL ? condition->_impl : NULL), static_cast<TR::IlValue *>(trueValue != NULL ? trueValue->_impl : NULL), static_cast<TR::IlValue *>(falseValue != NULL ? falseValue->_impl : NULL)); GET_CLIENT_OBJECT(clientObj, IlValue, implRet); return clientObj; } void IlBuilder::ForLoop(bool countsUp, char * indVar, IlBuilder ** body, IlBuilder ** breakBuilder, IlBuilder ** continueBuilder, IlValue * initial, IlValue * iterateWhile, IlValue * increment) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, breakBuilderImpl, breakBuilderArg, breakBuilder); ARG_SETUP(IlBuilder, continueBuilderImpl, continueBuilderArg, continueBuilder); static_cast<TR::IlBuilder *>(_impl)->ForLoop(countsUp, indVar, bodyArg, breakBuilderArg, continueBuilderArg, static_cast<TR::IlValue *>(initial != NULL ? initial->_impl : NULL), static_cast<TR::IlValue *>(iterateWhile != NULL ? iterateWhile->_impl : NULL), static_cast<TR::IlValue *>(increment != NULL ? increment->_impl : NULL)); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, breakBuilderImpl, breakBuilder); ARG_RETURN(IlBuilder, continueBuilderImpl, continueBuilder); } void IlBuilder::ForLoopDown(char * indVar, IlBuilder ** body, IlValue * initial, IlValue * iterateWhile, IlValue * increment) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); static_cast<TR::IlBuilder *>(_impl)->ForLoopDown(indVar, bodyArg, static_cast<TR::IlValue *>(initial != NULL ? initial->_impl : NULL), static_cast<TR::IlValue *>(iterateWhile != NULL ? iterateWhile->_impl : NULL), static_cast<TR::IlValue *>(increment != NULL ? increment->_impl : NULL)); ARG_RETURN(IlBuilder, bodyImpl, body); } void IlBuilder::ForLoopUp(char * indVar, IlBuilder ** body, IlValue * initial, IlValue * iterateWhile, IlValue * increment) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); static_cast<TR::IlBuilder *>(_impl)->ForLoopUp(indVar, bodyArg, static_cast<TR::IlValue *>(initial != NULL ? initial->_impl : NULL), static_cast<TR::IlValue *>(iterateWhile != NULL ? iterateWhile->_impl : NULL), static_cast<TR::IlValue *>(increment != NULL ? increment->_impl : NULL)); ARG_RETURN(IlBuilder, bodyImpl, body); } void IlBuilder::ForLoopWithBreak(bool countsUp, char * indVar, IlBuilder ** body, IlBuilder ** breakBuilder, IlValue * initial, IlValue * iterateWhile, IlValue * increment) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, breakBuilderImpl, breakBuilderArg, breakBuilder); static_cast<TR::IlBuilder *>(_impl)->ForLoopWithBreak(countsUp, indVar, bodyArg, breakBuilderArg, static_cast<TR::IlValue *>(initial != NULL ? initial->_impl : NULL), static_cast<TR::IlValue *>(iterateWhile != NULL ? iterateWhile->_impl : NULL), static_cast<TR::IlValue *>(increment != NULL ? increment->_impl : NULL)); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, breakBuilderImpl, breakBuilder); } void IlBuilder::ForLoopWithContinue(bool countsUp, char * indVar, IlBuilder ** body, IlBuilder ** continueBuilder, IlValue * initial, IlValue * iterateWhile, IlValue * increment) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, continueBuilderImpl, continueBuilderArg, continueBuilder); static_cast<TR::IlBuilder *>(_impl)->ForLoopWithContinue(countsUp, indVar, bodyArg, continueBuilderArg, static_cast<TR::IlValue *>(initial != NULL ? initial->_impl : NULL), static_cast<TR::IlValue *>(iterateWhile != NULL ? iterateWhile->_impl : NULL), static_cast<TR::IlValue *>(increment != NULL ? increment->_impl : NULL)); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, continueBuilderImpl, continueBuilder); } void IlBuilder::Return() { static_cast<TR::IlBuilder *>(_impl)->Return(); } void IlBuilder::Return(IlValue * value) { static_cast<TR::IlBuilder *>(_impl)->Return(static_cast<TR::IlValue *>(value != NULL ? value->_impl : NULL)); } void IlBuilder::Switch(const char * selectionVar, IlBuilder ** defaultBuilder, int32_t numCases, IlBuilder::JBCase ** cases) { ARG_SETUP(IlBuilder, defaultBuilderImpl, defaultBuilderArg, defaultBuilder); ARRAY_ARG_SETUP(IlBuilder::JBCase, numCases, casesArg, cases); static_cast<TR::IlBuilder *>(_impl)->Switch(selectionVar, defaultBuilderArg, numCases, casesArg); ARG_RETURN(IlBuilder, defaultBuilderImpl, defaultBuilder); ARRAY_ARG_RETURN(IlBuilder::JBCase, numCases, casesArg, cases); } void IlBuilder::Switch(const char * selectionVar, IlBuilder ** defaultBuilder, int32_t numCases, ...) { IlBuilder::JBCase ** cases = new IlBuilder::JBCase *[numCases]; va_list vararg; va_start(vararg, numCases); for (int i = 0; i < numCases; ++i) { cases[i] = va_arg(vararg, IlBuilder::JBCase *); } va_end(vararg); Switch(selectionVar, defaultBuilder, numCases, cases); delete[] cases; } void IlBuilder::TableSwitch(const char * selectionVar, IlBuilder ** defaultBuilder, bool generateBoundsCheck, int32_t numCases, IlBuilder::JBCase ** cases) { ARG_SETUP(IlBuilder, defaultBuilderImpl, defaultBuilderArg, defaultBuilder); ARRAY_ARG_SETUP(IlBuilder::JBCase, numCases, casesArg, cases); static_cast<TR::IlBuilder *>(_impl)->TableSwitch(selectionVar, defaultBuilderArg, generateBoundsCheck, numCases, casesArg); ARG_RETURN(IlBuilder, defaultBuilderImpl, defaultBuilder); ARRAY_ARG_RETURN(IlBuilder::JBCase, numCases, casesArg, cases); } void IlBuilder::TableSwitch(const char * selectionVar, IlBuilder ** defaultBuilder, bool generateBoundsCheck, int32_t numCases, ...) { IlBuilder::JBCase ** cases = new IlBuilder::JBCase *[numCases]; va_list vararg; va_start(vararg, numCases); for (int i = 0; i < numCases; ++i) { cases[i] = va_arg(vararg, IlBuilder::JBCase *); } va_end(vararg); TableSwitch(selectionVar, defaultBuilder, generateBoundsCheck, numCases, cases); delete[] cases; } IlBuilder::JBCase * IlBuilder::MakeCase(int32_t value, IlBuilder ** builder, int32_t fallsThrough) { ARG_SETUP(IlBuilder, builderImpl, builderArg, builder); TR::IlBuilder::JBCase * implRet = static_cast<TR::IlBuilder *>(_impl)->MakeCase(value, builderArg, fallsThrough); ARG_RETURN(IlBuilder, builderImpl, builder); GET_CLIENT_OBJECT(clientObj, JBCase, implRet); return clientObj; } void IlBuilder::WhileDoLoop(char * exitCondition, IlBuilder ** body) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); static_cast<TR::IlBuilder *>(_impl)->WhileDoLoop(exitCondition, bodyArg); ARG_RETURN(IlBuilder, bodyImpl, body); } void IlBuilder::WhileDoLoopWithBreak(char * exitCondition, IlBuilder ** body, IlBuilder ** breakBuilder) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, breakBuilderImpl, breakBuilderArg, breakBuilder); static_cast<TR::IlBuilder *>(_impl)->WhileDoLoopWithBreak(exitCondition, bodyArg, breakBuilderArg); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, breakBuilderImpl, breakBuilder); } void IlBuilder::WhileDoLoopWithContinue(char * exitCondition, IlBuilder ** body, IlBuilder ** continueBuilder) { ARG_SETUP(IlBuilder, bodyImpl, bodyArg, body); ARG_SETUP(IlBuilder, continueBuilderImpl, continueBuilderArg, continueBuilder); static_cast<TR::IlBuilder *>(_impl)->WhileDoLoopWithContinue(exitCondition, bodyArg, continueBuilderArg); ARG_RETURN(IlBuilder, bodyImpl, body); ARG_RETURN(IlBuilder, continueBuilderImpl, continueBuilder); } bool IlBuilder::buildIL() { return 0; } extern "C" void * allocateIlBuilder(void * impl) { return new IlBuilder(impl); } } // JitBuilder } // OMR
54.952239
334
0.721948
xiacijie
87b00527361099dbefaf8c7d6af3ef6c27afb5ca
289
cpp
C++
src/PontoPartida.cpp
leohmcs/AVANTStation
f1f635b2f4ec9ffcb010660f4b5c91eb9d5fa190
[ "Apache-2.0" ]
null
null
null
src/PontoPartida.cpp
leohmcs/AVANTStation
f1f635b2f4ec9ffcb010660f4b5c91eb9d5fa190
[ "Apache-2.0" ]
null
null
null
src/PontoPartida.cpp
leohmcs/AVANTStation
f1f635b2f4ec9ffcb010660f4b5c91eb9d5fa190
[ "Apache-2.0" ]
1
2020-12-10T03:39:05.000Z
2020-12-10T03:39:05.000Z
#include "PontoPartida.h" PontoPartida::PontoPartida() { } PontoPartida::PontoPartida(double lat, double lon) { setInitialPoint(Point(lat, lon, 0)); } void PontoPartida::setApproxPoint(double lat, double lon, double h) { setApproxPoint(Point(lat, lon, h)); }
13.761905
68
0.67128
leohmcs
87b6528dc49a975e0d3609eeb77d6f8e237f9f64
2,836
cpp
C++
logdevice/common/test/ConfigSourceLocationParserTest.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
1,831
2018-09-12T15:41:52.000Z
2022-01-05T02:38:03.000Z
logdevice/common/test/ConfigSourceLocationParserTest.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
183
2018-09-12T16:14:59.000Z
2021-12-07T15:49:43.000Z
logdevice/common/test/ConfigSourceLocationParserTest.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
228
2018-09-12T15:41:51.000Z
2022-01-05T08:12:09.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/ConfigSourceLocationParser.h" #include <gtest/gtest.h> #include "logdevice/common/FileConfigSource.h" #include "logdevice/common/configuration/ZookeeperConfigSource.h" using namespace facebook::logdevice; TEST(ConfigSourceLocationParserTest, TestAll) { std::vector<std::unique_ptr<ConfigSource>> sources; sources.push_back(std::make_unique<FileConfigSource>()); sources.push_back(std::make_unique<ZookeeperConfigSource>( std::chrono::milliseconds(100), nullptr)); std::string path; auto it = sources.end(); { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "zk:logdevice/test"); ASSERT_NE(sources.end(), it); EXPECT_EQ("Zookeeper", (*it)->getName()); EXPECT_EQ("logdevice/test", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "zookeeper:logdevice/test"); ASSERT_NE(sources.end(), it); EXPECT_EQ("Zookeeper", (*it)->getName()); EXPECT_EQ("logdevice/test", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "file://logdevice/test"); ASSERT_NE(sources.end(), it); EXPECT_EQ("file", (*it)->getName()); EXPECT_EQ("//logdevice/test", path); } { // File is the default std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "/logdevice/test"); ASSERT_NE(sources.end(), it); EXPECT_EQ("file", (*it)->getName()); EXPECT_EQ("/logdevice/test", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "schema:/logdevice/test"); ASSERT_EQ(sources.end(), it); EXPECT_EQ("", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, ""); ASSERT_NE(sources.end(), it); EXPECT_EQ("file", (*it)->getName()); EXPECT_EQ("", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "zk"); ASSERT_NE(sources.end(), it); EXPECT_EQ("file", (*it)->getName()); EXPECT_EQ("zk", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "zk:"); ASSERT_NE(sources.end(), it); EXPECT_EQ("Zookeeper", (*it)->getName()); EXPECT_EQ("", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "zk:{test: test}"); ASSERT_NE(sources.end(), it); EXPECT_EQ("Zookeeper", (*it)->getName()); EXPECT_EQ("{test: test}", path); } { std::tie(it, path) = ConfigSourceLocationParser::parse(sources, "10.0.0.1:8080"); ASSERT_EQ(sources.end(), it); EXPECT_EQ("", path); } }
27.803922
79
0.642807
majra20
87bd38ac62a9ade0f356e5a2bd38846420462e42
3,524
cpp
C++
getnum/widget.cpp
upcMvc/-BankQueuingSystem
6eaec760f61430cb3a49692453b444982299e45f
[ "MIT" ]
2
2016-07-20T02:23:51.000Z
2017-09-02T09:44:52.000Z
getnum/widget.cpp
upcMvc/bank-queue-system
6eaec760f61430cb3a49692453b444982299e45f
[ "MIT" ]
null
null
null
getnum/widget.cpp
upcMvc/bank-queue-system
6eaec760f61430cb3a49692453b444982299e45f
[ "MIT" ]
null
null
null
#include "widget.h" #include "ui_widget.h" #include "close.h" #include <QLabel> #include <QString> #include <QByteArray> #include <QtNetwork> #include <QDebug> #include <QCloseEvent> #include <QEvent> #include <QPalette> #include <QBrush> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QPalette palette; palette.setBrush(this->backgroundRole(),QBrush(QPixmap("../img/zx.jpg"))); //括号内为图片的相对目录 this->setPalette(palette); sender=new QUdpSocket(this); receiver=new QUdpSocket(this); receiver->bind(45454,QUdpSocket::ShareAddress); connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram())); //时间表 QTimer *timer=new QTimer(this); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(time())); timer->start(500); } Widget::~Widget() { delete ui; } void Widget::on_pushButton_clicked(){ //向服务器发送信息 QByteArray datagram="a"; sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress("172.19.43.206"),45454); } void Widget::on_pushButton_2_clicked(){ //向服务器发送信息 QByteArray datagram="b"; sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress("172.19.43.206"),45454); } void Widget::time(){ QDateTime time = QDateTime::currentDateTime(); QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); ui->label_5->setText(str); } void Widget::processPendingDatagram(){ //等待数据 QByteArray datagram; while(receiver->hasPendingDatagrams()){ datagram.resize(receiver->pendingDatagramSize()); //接受数据,存到datagram中 receiver->readDatagram(datagram.data(),datagram.size()); } //将QByteArray转换成Qstring QString string; QString str0; string = QString(datagram); str0=string.section(",",0,0); if("c"==str0){ QString str1=string.section(',',1,1); QString str2=string.section(',',2,2); ui->label->setText("普通客户您好,您前面有"+str1+"位普通客户,有"+str2+"位VIP用户"); ui->label_2->setText("vip客户您好,您前面有"+str2+"人在排队"); } if("e"==str0){ QString str1=string.section(',',1,1); QString str2=string.section(',',2,2); QString str3=string.section(',',3,3); ui->label->setText("普通客户您好,您前面有"+str2+"位普通客户,有"+str3+"位VIP用户"); ui->label_2->setText("vip客户您好,您前面有"+str3+"人在排队"); ui->lineEdit->setText("取号成功,您的号码是"+str1+"号"); } if("x"==str0){ QString str1=string.section(',',1,1); QString str2=string.section(',',2,2); QString str3=string.section(',',3,3); ui->label->setText("普通客户您好,您前面有"+str2+"位普通客户,有"+str3+"位VIP用户"); ui->label_2->setText("vip客户您好,您前面有"+str3+"人在排队"); ui->lineEdit_2->setText("取号成功,您的号码是"+str1+"号"); } if("h"==str0){ QString str1=string.section(',',1,1); QString str2=string.section(',',2,2); QString str3=string.section(',',3,3); if("0"==str3){ ui->textEdit->moveCursor(QTextCursor::Start); ui->textEdit->insertPlainText("请普通用户"+str1+"号到"+str2+"号柜台办理业务\n"); } else{ ui->textEdit->moveCursor(QTextCursor::Start); ui->textEdit->insertPlainText("请VIP用户"+str1+"号到"+str2+"号柜台办理业务\n"); } } } void Widget::closeEvent(QCloseEvent *event) { Close *close = new Close(this); close->setModal(true); close->exec(); if (close->flag == 1) { event->accept(); } else { event->ignore(); } }
26.103704
95
0.612372
upcMvc
87bd9cb27f59fcdb80ed9a36dd8400999f82c854
1,421
cpp
C++
LeetCode/Weekly_Contest/WC_59/LC732.cpp
AuthurExcalbern/ACM
08429e53fbc9a6919ac7a134693cefa28998b302
[ "MIT" ]
null
null
null
LeetCode/Weekly_Contest/WC_59/LC732.cpp
AuthurExcalbern/ACM
08429e53fbc9a6919ac7a134693cefa28998b302
[ "MIT" ]
null
null
null
LeetCode/Weekly_Contest/WC_59/LC732.cpp
AuthurExcalbern/ACM
08429e53fbc9a6919ac7a134693cefa28998b302
[ "MIT" ]
null
null
null
/* Probelm 732 My Calendar III * 每次都给定一个范围:start <= x < end * 然后设定一个函数,返回重复预订的次数 Example 1: MyCalendarThree(); MyCalendarThree.book(10, 20); // returns 1 MyCalendarThree.book(50, 60); // returns 1 MyCalendarThree.book(10, 40); // returns 2 MyCalendarThree.book(5, 15); // returns 3 MyCalendarThree.book(5, 10); // returns 3 MyCalendarThree.book(25, 55); // returns 3 Explanation: The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking. The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking. The remaining events cause the maximum K-booking to be only a 3-booking. Note that the last event locally causes a 2-booking, but the answer is still 3 because eg. [10, 20), [10, 40), and [5, 15) are still triple booked. Note: The number of calls to MyCalendarThree.book per test case will be at most 400. In calls to MyCalendarThree.book(start, end), start and end are integers in the range [0, 10^9]. */ using PII = pair<int, int>; #define F first #define S second class MyCalendarThree { public: map<PII, int> m; MyCalendarThree() { } int book(int start, int end) { m[{end, -1}]++; m[{start, 1}]++; int s = 0, maxn = 0; for (const auto &it : m) { s += it.S * it.F.S; if (maxn <= s) { maxn = s; } } return maxn; } };
27.326923
96
0.636875
AuthurExcalbern
87c0621d5a6a4dee4187e1f88ea212826847bdf8
4,094
cpp
C++
glfw3_app/common/mdf/surface.cpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
9
2015-09-22T21:36:57.000Z
2021-04-01T09:16:53.000Z
glfw3_app/common/mdf/surface.cpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
null
null
null
glfw3_app/common/mdf/surface.cpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
2
2019-02-21T04:22:13.000Z
2021-03-02T17:24:32.000Z
//=====================================================================// /*! @file @brief サーフェース・クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE */ //=====================================================================// #include "mdf/surface.hpp" namespace mdf { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 球を描画 @param[in] radius 半径 @param[in] lats 分割数 @param[in] longs 分割数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// void draw_sphere(float radius, int lats, int longs) { for(int i = 0; i <= lats; ++i) { float lat0 = vtx::get_pi<float>() * (-0.5f + static_cast<float>(i - 1) / lats); float z0 = radius * std::sin(lat0); float zr0 = radius * std::cos(lat0); float lat1 = vtx::get_pi<float>() * (-0.5f + static_cast<float>(i) / lats); float z1 = radius * std::sin(lat1); float zr1 = radius * std::cos(lat1); glBegin(GL_QUAD_STRIP); for(int j = 0; j <= longs; ++j) { float lng = 2 * vtx::get_pi<float>() * static_cast<float>(j - 1) / longs; float x = std::cos(lng); float y = std::sin(lng); glNormal3f(x * zr1, y * zr1, z1); glVertex3f(x * zr1, y * zr1, z1); glNormal3f(x * zr0, y * zr0, z0); glVertex3f(x * zr0, y * zr0, z0); } glEnd(); } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief シリンダーを描画 @param[in] radius_org 半径(開始) @param[in] radius_end 半径(終点) @param[in] length 長さ @param[in] lats 分割数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// void draw_cylinder(float radius_org, float radius_len, float length, int lats) { int divide = 12; float a = 0.0f; float d = 2.0f * vtx::get_pi<float>() / static_cast<float>(divide); glBegin(GL_TRIANGLE_STRIP); for(int i = 0; i < divide; ++i) { float x = std::sin(a); float y = std::cos(a); a += d; glVertex3f(x * radius_org, 0.0f, y * radius_org); glVertex3f(x * radius_len, length, y * radius_len); } { a = 0.0f; float x = std::sin(a); float y = std::cos(a); glVertex3f(x * radius_org, 0.0f, y * radius_org); glVertex3f(x * radius_len, length, y * radius_len); } glEnd(); } #if 0 void surface::destroy_vertex_() { if(vertex_id_) { glDeleteBuffers(1, &vertex_id_); vertex_id_ = 0; } } void surface::destroy_element_() { if(!elements_.empty()) { glDeleteBuffers(elements_.size(), &elements_[0]); elements_.clear(); } } //-----------------------------------------------------------------// /*! @brief 頂点を開始 @param[in] n 頂点数を指定する場合指定 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool surface::begin_vertex(uint32_t n) { destroy_vertex_(); glGenBuffers(1, &vertex_id_); if(n) { vertexes_.reserve(n); } vertexes_.clear(); return true; } //-----------------------------------------------------------------// /*! @brief 頂点を追加 @param[in] n 数を指定する場合 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool surface::add_vertex(const vertex& v) { vertexes_.push_back(v); return true; } //-----------------------------------------------------------------// /*! @brief 頂点を終了 @return 成功なら「true」 */ //-----------------------------------------------------------------// bool surface::end_vertex() { glBindBuffer(GL_ARRAY_BUFFER, vertex_id_); glBufferData(GL_ARRAY_BUFFER, vertexes_.size() * sizeof(vertex), &vertexes_[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); vertexes tmp; tmp.swap(vertexes_); return true; } //-----------------------------------------------------------------// /*! @brief レンダリング @param[in] h ハンドル(0なら全てをレンダリング) */ //-----------------------------------------------------------------// void surface::render(handle h) { if(h == 0) { } else if((h - 1) < elements_.size()) { } } #endif }
23.94152
82
0.462384
hirakuni45
87c213c8b8aa15ca394141ee41b4e05600b12de6
294
cc
C++
src/effect/mask_filter.cc
RuiwenTang/Skity
2f98d8bda9946a9055d955fae878fef43c4eee57
[ "MIT" ]
65
2021-08-05T09:52:49.000Z
2022-03-29T14:45:20.000Z
src/effect/mask_filter.cc
RuiwenTang/Skity
2f98d8bda9946a9055d955fae878fef43c4eee57
[ "MIT" ]
1
2022-03-24T09:35:06.000Z
2022-03-25T06:38:20.000Z
src/effect/mask_filter.cc
RuiwenTang/Skity
2f98d8bda9946a9055d955fae878fef43c4eee57
[ "MIT" ]
9
2021-08-08T07:30:13.000Z
2022-03-29T14:45:25.000Z
#include <skity/effect/mask_filter.hpp> namespace skity { std::shared_ptr<MaskFilter> MaskFilter::MakeBlur(BlurStyle style, float sigma) { return std::make_shared<MaskFilter>(); } Rect MaskFilter::approximateFilteredBounds(const Rect &src) const { return Rect(); } } // namespace skity
22.615385
80
0.751701
RuiwenTang
87c60c367286d35a99d44dc732aecb69676271e3
216,697
cpp
C++
MMOCoreORB/src/server/zone/managers/sui/SuiManager.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/managers/sui/SuiManager.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/managers/sui/SuiManager.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* Copyright <SWGEmu> See file COPYING for copying conditions. */ #include "SuiManager.h" #include "server/zone/ZoneProcessServer.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/sui/SuiWindowType.h" #include "server/zone/objects/player/sui/banktransferbox/SuiBankTransferBox.h" #include "server/zone/objects/player/sui/characterbuilderbox/SuiCharacterBuilderBox.h" #include "server/zone/objects/player/sui/transferbox/SuiTransferBox.h" #include "server/zone/objects/creature/commands/UnconsentCommand.h" #include "server/zone/managers/skill/SkillManager.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" #include "server/zone/objects/player/sui/inputbox/SuiInputBox.h" #include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h" #include "server/zone/ZoneServer.h" #include "server/zone/managers/minigames/FishingManager.h" #include "server/zone/objects/player/sui/keypadbox/SuiKeypadBox.h" #include "server/zone/objects/player/sui/callbacks/LuaSuiCallback.h" #include "server/zone/objects/tangible/terminal/characterbuilder/CharacterBuilderTerminal.h" #include "templates/params/creature/CreatureAttribute.h" #include "templates/params/creature/CreatureState.h" #include "server/zone/objects/tangible/deed/eventperk/EventPerkDeed.h" #include "server/zone/objects/tangible/eventperk/Jukebox.h" #include "server/zone/objects/tangible/eventperk/ShuttleBeacon.h" #include "server/zone/objects/player/sui/SuiBoxPage.h" #include "server/zone/managers/loot/LootManager.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/managers/skill/SkillManager.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/packets/player/PlayMusicMessage.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/ZoneServer.h" #include "server/chat/ChatManager.h" #include "server/zone/objects/tangible/components/vendor/VendorDataComponent.h" #include "server/zone/managers/stringid/StringIdManager.h" #include "server/zone/managers/auction/AuctionManager.h" #include "server/zone/managers/auction/AuctionsMap.h" #include "server/zone/managers/statistics/StatisticsManager.h" #include "server/zone/objects/mission/MissionTypes.h" SuiManager::SuiManager() : Logger("SuiManager") { server = nullptr; setGlobalLogging(true); setLogging(false); } void SuiManager::handleSuiEventNotification(uint32 boxID, CreatureObject* player, uint32 eventIndex, Vector<UnicodeString>* args) { uint16 windowType = (uint16) boxID; Locker _lock(player); ManagedReference<PlayerObject*> ghost = player->getPlayerObject(); if (ghost == nullptr) return; ManagedReference<SuiBox*> suiBox = ghost->getSuiBox(boxID); if (suiBox == nullptr) return; //Remove the box from the player, callback can readd it to the player if needed. ghost->removeSuiBox(boxID); suiBox->clearOptions(); //TODO: Eventually SuiBox needs to be cleaned up to not need this. Reference<SuiCallback*> callback = suiBox->getCallback(); if (callback != nullptr) { Reference<LuaSuiCallback*> luaCallback = cast<LuaSuiCallback*>(callback.get()); if (luaCallback != nullptr && suiBox->isSuiBoxPage()) { Reference<SuiBoxPage*> boxPage = cast<SuiBoxPage*>(suiBox.get()); if (boxPage != nullptr) { Reference<SuiPageData*> pageData = boxPage->getSuiPageData(); if (pageData != nullptr) { try { Reference<SuiCommand*> suiCommand = pageData->getCommand(eventIndex); if (suiCommand != nullptr && suiCommand->getCommandType() == SuiCommand::SCT_subscribeToEvent) { StringTokenizer callbackString(suiCommand->getNarrowParameter(2)); callbackString.setDelimeter(":"); String luaPlay = ""; String luaCall = ""; callbackString.getStringToken(luaPlay); callbackString.getStringToken(luaCall); callback = new LuaSuiCallback(player->getZoneServer(), luaPlay, luaCall); } } catch(Exception& e) { error(e.getMessage()); } } } } callback->run(player, suiBox, eventIndex, args); return; } StringBuffer msg; msg << "Unknown message callback with SuiWindowType: " << hex << windowType << ". Falling back on old handler system."; //info(msg, true); switch (windowType) { case SuiWindowType::DANCING_START: handleStartDancing(player, suiBox, eventIndex, args); break; case SuiWindowType::DANCING_CHANGE: handleStartDancing(player, suiBox, eventIndex, args); break; case SuiWindowType::MUSIC_START: handleStartMusic(player, suiBox, eventIndex, args); break; case SuiWindowType::MUSIC_CHANGE: handleStartMusic(player, suiBox, eventIndex, args); break; case SuiWindowType::BAND_START: handleStartMusic(player, suiBox, eventIndex, args); break; case SuiWindowType::BAND_CHANGE: handleStartMusic(player, suiBox, eventIndex, args); break; case SuiWindowType::BANK_TRANSFER: handleBankTransfer(player, suiBox, eventIndex, args); break; case SuiWindowType::FISHING: handleFishingAction(player, suiBox, eventIndex, args); break; case SuiWindowType::CHARACTER_BUILDER_LIST: handleCharacterBuilderSelectItem(player, suiBox, eventIndex, args); break; case SuiWindowType::OBJECT_NAME: handleSetObjectName(player, suiBox, eventIndex, args); break; } } void SuiManager::handleSetObjectName(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) { if (!suiBox->isInputBox() || cancel != 0) return; ManagedReference<SceneObject*> object = suiBox->getUsingObject().get(); if (object == nullptr) return; if (args->size() < 1) return; UnicodeString objectName = args->get(0); object->setCustomObjectName(objectName, true); if (object->isSignObject()) { StringIdChatParameter params("@player_structure:prose_sign_name_updated"); //Sign name successfully updated to '%TO'. params.setTO(objectName); player->sendSystemMessage(params); } } void SuiManager::handleStartDancing(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) { if (!suiBox->isListBox() || cancel != 0) return; if (args->size() < 2) return; int index = Integer::valueOf(args->get(0).toString()); uint32 id = suiBox->getBoxID(); bool change = (uint16)id == SuiWindowType::DANCING_CHANGE; SuiListBox* listBox = cast<SuiListBox*>( suiBox); if (index == -1) return; String dance = listBox->getMenuItemName(index); if (!change) player->executeObjectControllerAction(STRING_HASHCODE("startdance"), 0, dance); else player->executeObjectControllerAction(STRING_HASHCODE("changedance"), 0, dance); } void SuiManager::handleStartMusic(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) { if (!suiBox->isListBox() || cancel != 0) return; if (args->size() < 2) return; int index = Integer::valueOf(args->get(0).toString()); uint32 id = suiBox->getBoxID(); SuiListBox* listBox = cast<SuiListBox*>( suiBox); if (index == -1) return; String dance = listBox->getMenuItemName(index); switch ((uint16)id) { case SuiWindowType::MUSIC_START: player->executeObjectControllerAction(STRING_HASHCODE("startmusic"), player->getTargetID(), dance); break; case SuiWindowType::MUSIC_CHANGE: player->executeObjectControllerAction(STRING_HASHCODE("changemusic"), player->getTargetID(), dance); break; case SuiWindowType::BAND_CHANGE: player->executeObjectControllerAction(STRING_HASHCODE("changebandmusic"), player->getTargetID(), dance); break; case SuiWindowType::BAND_START: player->executeObjectControllerAction(STRING_HASHCODE("startband"), player->getTargetID(), dance); break; } } void SuiManager::handleBankTransfer(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) { if (!suiBox->isBankTransferBox() || cancel != 0) return; if (args->size() < 2) return; int cash = Integer::valueOf(args->get(0).toString()); int bank = Integer::valueOf(args->get(1).toString()); SuiBankTransferBox* suiBank = cast<SuiBankTransferBox*>( suiBox); ManagedReference<SceneObject*> bankObject = suiBank->getBank(); if (bankObject == nullptr) return; if (!player->isInRange(bankObject, 5)) return; uint32 currentCash = player->getCashCredits(); uint32 currentBank = player->getBankCredits(); if ((currentCash + currentBank) == ((uint32) cash + (uint32) bank)) { player->setCashCredits(cash); player->setBankCredits(bank); } } void SuiManager::handleFishingAction(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) { if (cancel != 0) return; if (args->size() < 1) return; int index = Integer::valueOf(args->get(0).toString()); FishingManager* manager = server->getFishingManager(); manager->setNextAction(player, index + 1); uint32 newBoxID = 0; switch (index + 1) { case FishingManager::TUGUP: newBoxID = manager->createWindow(player, suiBox->getBoxID()); break; case FishingManager::TUGRIGHT: newBoxID = manager->createWindow(player, suiBox->getBoxID()); break; case FishingManager::TUGLEFT: newBoxID = manager->createWindow(player, suiBox->getBoxID()); break; case FishingManager::REEL: newBoxID = manager->createWindow(player, suiBox->getBoxID()); break; case FishingManager::STOPFISHING: player->sendSystemMessage("@fishing:stop_fishing"); //You reel-in your line and stop fishing... manager->stopFishing(player, suiBox->getBoxID(), true); return; break; default: newBoxID = manager->createWindow(player, suiBox->getBoxID()); break; } manager->setFishBoxID(player, suiBox->getBoxID()); } void SuiManager::handleCharacterBuilderSelectItem(CreatureObject* player, SuiBox* suiBox, uint32 cancel, Vector<UnicodeString>* args) { if (!ConfigManager::instance()->getCharacterBuilderEnabled()) return; ZoneServer* zserv = player->getZoneServer(); if (args->size() < 1) return; bool otherPressed = false; int index = 0; if(args->size() > 1) { otherPressed = Bool::valueOf(args->get(0).toString()); index = Integer::valueOf(args->get(1).toString()); } else { index = Integer::valueOf(args->get(0).toString()); } if (!suiBox->isCharacterBuilderBox()) return; ManagedReference<SuiCharacterBuilderBox*> cbSui = cast<SuiCharacterBuilderBox*>( suiBox); CharacterBuilderMenuNode* currentNode = cbSui->getCurrentNode(); PlayerObject* ghost = player->getPlayerObject(); //If cancel was pressed then we kill the box/menu. if (cancel != 0 || ghost == nullptr) return; //Back was pressed. Send the node above it. if (otherPressed) { CharacterBuilderMenuNode* parentNode = currentNode->getParentNode(); if(parentNode == nullptr) return; cbSui->setCurrentNode(parentNode); ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); return; } CharacterBuilderMenuNode* node = currentNode->getChildNodeAt(index); //Node doesn't exist or the index was out of bounds. Should probably resend the menu here. if (node == nullptr) { ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); return; } if (node->hasChildNodes()) { //If it has child nodes, display them. cbSui->setCurrentNode(node); ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); } else { ManagedReference<SceneObject*> scob = cbSui->getUsingObject().get(); if (scob == nullptr) return; CharacterBuilderTerminal* bluefrog = scob.castTo<CharacterBuilderTerminal*>(); if (bluefrog == nullptr) return; String templatePath = node->getTemplatePath(); if (templatePath.indexOf(".iff") < 0) { // Non-item selections if (templatePath == "unlearn_all_skills") { SkillManager::instance()->surrenderAllSkills(player, true, false); player->sendSystemMessage("All skills unlearned."); } else if (templatePath == "cleanse_character") { if (!player->isInCombat()) { player->sendSystemMessage("You have been cleansed from the signs of previous battles."); for (int i = 0; i < 9; ++i) { player->setWounds(i, 0); } player->setShockWounds(0); } else { player->sendSystemMessage("Not within combat."); return; } } else if (templatePath == "fill_force_bar") { if (ghost->isJedi()) { if (!player->isInCombat()) { player->sendSystemMessage("You force bar has been filled."); ghost->setForcePower(ghost->getForcePowerMax(), true); } else { player->sendSystemMessage("Not within combat."); } } } else if (templatePath == "reset_buffs") { if (!player->isInCombat()) { player->sendSystemMessage("Your buffs have been reset."); player->clearBuffs(true, false); ghost->setFoodFilling(0); ghost->setDrinkFilling(0); } else { player->sendSystemMessage("Not within combat."); return; } } else if (templatePath.beginsWith("crafting_apron_")) { //"object/tangible/wearables/apron/apron_chef_s01.iff" //"object/tangible/wearables/ithorian/apron_chef_jacket_s01_ith.iff" ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (inventory == nullptr) { return; } uint32 itemCrc = ( player->getSpecies() != CreatureObject::ITHORIAN ) ? 0x5DDC4E5D : 0x6C191FBB; ManagedReference<WearableObject*> apron = zserv->createObject(itemCrc, 2).castTo<WearableObject*>(); if (apron == nullptr) { player->sendSystemMessage("There was an error creating the requested item. Please report this issue."); ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); error("could not create frog crafting apron"); return; } Locker locker(apron); apron->createChildObjects(); if (apron->isWearableObject()) { apron->addMagicBit(false); UnicodeString modName = "(General)"; apron->addSkillMod(SkillModManager::WEARABLE, "general_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "general_experimentation", 25); if(templatePath == "crafting_apron_armorsmith") { modName = "(Armorsmith)"; apron->addSkillMod(SkillModManager::WEARABLE, "armor_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "armor_experimentation", 25); apron->addSkillMod(SkillModManager::WEARABLE, "armor_repair", 25); } else if(templatePath == "crafting_apron_weaponsmith") { modName = "(Weaponsmith)"; apron->addSkillMod(SkillModManager::WEARABLE, "weapon_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "weapon_experimentation", 25); apron->addSkillMod(SkillModManager::WEARABLE, "weapon_repair", 25); apron->addSkillMod(SkillModManager::WEARABLE, "grenade_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "grenade_experimentation", 25); } else if(templatePath == "crafting_apron_tailor") { modName = "(Tailor)"; apron->addSkillMod(SkillModManager::WEARABLE, "clothing_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "clothing_experimentation", 25); apron->addSkillMod(SkillModManager::WEARABLE, "clothing_repair", 25); } else if(templatePath == "crafting_apron_chef") { modName = "(Chef)"; apron->addSkillMod(SkillModManager::WEARABLE, "food_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "food_experimentation", 25); } else if(templatePath == "crafting_apron_architect") { modName = "(Architect)"; apron->addSkillMod(SkillModManager::WEARABLE, "structure_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "structure_experimentation", 25); apron->addSkillMod(SkillModManager::WEARABLE, "structure_complexity", 25); } else if(templatePath == "crafting_apron_droid_engineer") { modName = "(Droid Engineer)"; apron->addSkillMod(SkillModManager::WEARABLE, "droid_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "droid_experimentation", 25); apron->addSkillMod(SkillModManager::WEARABLE, "droid_complexity", 25); } else if(templatePath == "crafting_apron_doctor") { modName = "(Doctor)"; apron->addSkillMod(SkillModManager::WEARABLE, "medicine_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "medicine_experimentation", 25); } else if(templatePath == "crafting_apron_combat_medic") { modName = "(Combat Medic)"; apron->addSkillMod(SkillModManager::WEARABLE, "combat_medicine_assembly", 25); apron->addSkillMod(SkillModManager::WEARABLE, "combat_medicine_experimentation", 25); } UnicodeString apronName = "Crafting Apron " + modName; apron->setCustomObjectName(apronName, false); } if (inventory->transferObject(apron, -1, true)) { apron->sendTo(player, true); } else { apron->destroyObjectFromDatabase(true); return; } StringIdChatParameter stringId; stringId.setStringId("@faction_perk:bonus_base_name"); //You received a: %TO. stringId.setTO(apron->getObjectID()); player->sendSystemMessage(stringId); } else if (templatePath == "enhance_character") { bluefrog->enhanceCharacter(player); } else if (templatePath == "credits") { player->addCashCredits(50000, true); player->sendSystemMessage("You have received 50.000 Credits"); } else if (templatePath == "faction_rebel") { ghost->increaseFactionStanding("rebel", 100000); } else if (templatePath == "faction_imperial") { ghost->increaseFactionStanding("imperial", 100000); } else if (templatePath == "language") { bluefrog->giveLanguages(player); } else if (templatePath == "apply_all_dots") { player->addDotState(player, CreatureState::POISONED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0); player->addDotState(player, CreatureState::BLEEDING, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0); player->addDotState(player, CreatureState::DISEASED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0); player->addDotState(player, CreatureState::ONFIRE, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0, 20); } else if (templatePath == "apply_poison_dot") { player->addDotState(player, CreatureState::POISONED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0); } else if (templatePath == "apply_bleed_dot") { player->addDotState(player, CreatureState::BLEEDING, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0); } else if (templatePath == "apply_disease_dot") { player->addDotState(player, CreatureState::DISEASED, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0); } else if (templatePath == "apply_fire_dot") { player->addDotState(player, CreatureState::ONFIRE, scob->getObjectID(), 100, CreatureAttribute::UNKNOWN, 60, -1, 0, 20); } else if (templatePath == "clear_dots") { player->clearDots(); } else if (templatePath == "frs_light_side") { if (ghost->getJediState() < 4) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("FRS Light Jedi"); box->setPromptText("FRS Light Jedi Requires (Light Jedi Rank"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (ghost->getJediState() == 4) { PlayerManager* pman = zserv->getPlayerManager(); pman->unlockFRSForTesting(player, 1); } } else if (templatePath == "frs_dark_side") { if (ghost->getJediState() < 8) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("FRS Dark Jedi"); box->setPromptText("FRS Dark Jedi Requires (Dark Jedi Rank"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (ghost->getJediState() == 8) { PlayerManager* pman = zserv->getPlayerManager(); pman->unlockFRSForTesting(player, 2); } } else if (templatePath == "color_crystals" || templatePath == "krayt_pearls") { ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (inventory == nullptr) return; LootManager* lootManager = zserv->getLootManager(); lootManager->createLoot(inventory, templatePath, 300, true); } else if (templatePath == "max_xp") { ghost->maximizeExperience(); player->sendSystemMessage("You have maximized all xp types."); //Gray Jedi Unlock Checks } else if (templatePath == "jedi_Lives") { if (ghost->getJediState() < 2) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Gray Jedi Unlock"); box->setPromptText("Gray Jedi Requires (Force Sensative)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (ghost->getJediState() >= 2 && player->getScreenPlayState("jedi_Lives") == 0) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); player->sendSystemMessage("You Have Unlocked Gray Jedi"); int livesLeft = player->getScreenPlayState("jediLives") + 3; player->setScreenPlayState("jediLives", livesLeft); int jediVis1 = ghost->getVisibility(); box->setPromptTitle("Gray Jedi Progress"); StringBuffer promptText; String playerName = player->getFirstName(); promptText << "\\#00ff00 " << playerName << " Has " << "\\#000000 " << "(" << "\\#ffffff " << player->getScreenPlayState("jediLives") << "\\#000000 " << ")" << "\\#00ff00 " << " Gray Jedi Lives" << endl; promptText << "\\#ffffff " << playerName << "\\#00ff00 Your Visibility is at: " << jediVis1; box->setPromptText(promptText.toString()); ghost->addSuiBox(box); player->sendMessage(box->generateMessage()); SkillManager* skillManager = server->getSkillManager(); SkillManager::instance()->awardSkill("combat_jedi_novice", player, true, true, true); box->setForceCloseDistance(5.f); } //Player Stats } else if (templatePath == "player_stats") { PlayerObject* ghost = player->getPlayerObject(); StringBuffer msg; msg << "---PvP Statistics---\n" << "PvP Rating: " << ghost->getPvpRating() << "\n" << "Total PvP Kills: " << ghost->getPvpKills() << "\n" << "Total PvP Deaths: " << ghost->getPvpDeaths() << "\n" << "Total Bounty Kills: " << ghost->getBountyKills() << "\n\n" << "---PvE Statistics---\n" << "Total PvE Kills: " << ghost->getPveKills() << "\n" << "Total PvE Deaths: " << ghost->getPveDeaths() << "\n" << "Total Boss Kills: " << ghost->getworldbossKills() << "\n\n" << "---Mission Statistics---\n" << "Total Missions Completed: " << ghost->getMissionsCompleted() << "\n\n" << "---Misc Statistics---\n" << "Event Attendance: " << ghost->geteventplayerCrate(); ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::NONE); box->setPromptTitle(player->getFirstName() + "'s" + " Character Statistics"); box->setPromptText(msg.toString()); ghost->addSuiBox(box); player->sendMessage(box->generateMessage()); //Community Online Status } else if (templatePath == "community_status") { ManagedReference<PlayerObject*> ghost = player->getPlayerObject(); PlayerManager* playerManager = server->getZoneServer()->getPlayerManager(); StringBuffer body; Time timestamp; timestamp.updateToCurrentTime(); body << "-- Flurry Server --" << endl << endl; body << "Connections Online: " << String::valueOf(player->getZoneServer()->getConnectionCount()) << endl; body << "Most Concurrent (since last reset): " << String::valueOf(player->getZoneServer()->getMaxPlayers()) << endl; body << "Server Cap: " << String::valueOf(player->getZoneServer()->getServerCap()) << endl << endl << endl; body << "Deleted Characters (since last reset): " << String::valueOf(player->getZoneServer()->getDeletedPlayers()) << endl; body << "Total Connections (since last reset): " << String::valueOf(player->getZoneServer()->getTotalPlayers()) << endl; body << endl;endl; body << "Missions info (since last reset): " << endl; body << StatisticsManager::instance()->getStatistics() << endl; ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::NONE); box->setPromptTitle("Flurry Community Status"); box->setPromptText(body.toString()); ghost->addSuiBox(box); player->sendMessage(box->generateMessage()); //JediQuest Remove Screen Play Tester } else if (templatePath == "jedi_quest_remove") { if (!player->isInCombat() && player->getBankCredits() < 999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Jedi Quest"); box->setPromptText("Jedi Quest Requires 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); player->sendSystemMessage("Thank you for your credits."); int questLeft = player->getScreenPlayState("jediQuest") - 1; player->setScreenPlayState("jediQuest", questLeft); int jediVis1 = ghost->getVisibility(); box->setPromptTitle("Jedi Quest Progress"); StringBuffer promptText; String playerName = player->getFirstName(); promptText << "\\#00ff00 " << playerName << " Has " << "\\#000000 " << "(" << "\\#ffffff " << player->getScreenPlayState("jediQuest") << "\\#000000 " << ")" << "\\#00ff00 " << " Jedi Quest Progress" << endl; promptText << "\\#ffffff " << playerName << "\\#00ff00 Your Visibility is at: " << jediVis1; box->setPromptText(promptText.toString()); ghost->addSuiBox(box); player->sendMessage(box->generateMessage()); player->subtractBankCredits(1000); box->setForceCloseDistance(5.f); } //BOSS TELEPORT ROOM } else if (templatePath == "teleportroom") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Boss Instance Teleport Room"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dungeon2", -33.6957, 0.77033, 24.5291, 14200816); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //GALACTIC TRAVEL SYSTEM City Politician Skill } else if (templatePath == "citypolitician") { if (!player->isInCombat() && player->getBankCredits() < 999999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Master Politician"); box->setPromptText("Master Politician Requires 1,000,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 999999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); player->sendSystemMessage("Thank you for your credits."); SkillManager::instance()->awardSkill("social_politician_master", player, true, true, true); player->subtractBankCredits(1000000); box->setForceCloseDistance(5.f); } //GALACTIC TRAVEL SYSTEM Recalculate's Jedi's Force Pool } else if (templatePath == "recalculateforce") { if (!player->checkCooldownRecovery("force_recalculate_cooldown")) { StringIdChatParameter stringId; Time* cdTime = player->getCooldownTime("force_recalculate_cooldown"); int timeLeft = floor((float)cdTime->miliDifference() / 1000) *-1; stringId.setStringId("@innate:equil_wait"); // You are still recovering from your last Command available in %DI seconds. stringId.setDI(timeLeft); player->sendSystemMessage(stringId); error("Cooldown In Effect You May Not Recalculate Force: " + player->getFirstName()); return; } if (!player->isInCombat()) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); String playerName = player->getFirstName(); StringBuffer zBroadcast; zBroadcast << "\\#00E604" << playerName << " \\#63C8F9 Has Recalculated Their Force Pool."; SkillManager* skillManager = SkillManager::instance(); skillManager->awardForceFromSkills(player); player->sendSystemMessage("Recalculated Max force and Regen"); player->playEffect("clienteffect/mus_relay_activate.cef", ""); player->addCooldown("force_recalculate_cooldown", 86400 * 1000);// 24 hour cooldown player->getZoneServer()->getChatManager()->broadcastGalaxy(nullptr, zBroadcast.toString()); } //GALACTIC TRAVEL SYSTEM Recalculate's Players Skills } else if (templatePath == "recalculateskills") { if (!player->checkCooldownRecovery("skill_recalculate_cooldown")) { StringIdChatParameter stringId; Time* cdTime = player->getCooldownTime("skill_recalculate_cooldown"); int timeLeft = floor((float)cdTime->miliDifference() / 1000) *-1; stringId.setStringId("@innate:equil_wait"); // You are still recovering from your last Command available in %DI seconds. stringId.setDI(timeLeft); player->sendSystemMessage(stringId); error("Cooldown In Effect You May Not Recalculate Skills: " + player->getFirstName()); return; } if (!player->isInCombat()) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); String playerName = player->getFirstName(); StringBuffer zBroadcast; zBroadcast << "\\#00E604" << playerName << " \\#63C8F9 Has Recalculated Their Skills."; SkillManager* skillManager = SkillManager::instance(); skillManager->awardResetSkills(player); player->sendSystemMessage("Recalculated Skills"); player->playEffect("clienteffect/mus_relay_activate.cef", ""); player->addCooldown("skill_recalculate_cooldown", 86400 * 1000);// 24 hour cooldown player->getZoneServer()->getChatManager()->broadcastGalaxy(nullptr, zBroadcast.toString()); } //GALACTIC TRAVEL SYSTEM //Corellia Travel } else if (templatePath == "corellia_bela_vistal_a_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Bela Vistal Shuttleport A"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 6644.269, 330, -5922.5225); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "corellia_bela_vistal_b_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Bela Vistal Shuttleport B"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 6930.8042, 330, -5534.8936); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "corellia_coronet_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Coronet Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -66.760902, 28, -4711.3281); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "corellia_coronet_a_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Coronet Shuttle A"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -25.671804, 28, -4409.7847); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "corellia_coronet_b_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Coronet Shuttle B"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -329.76605, 28, -4641.23); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "doaba_guerfel_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Doaba Guerfel Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 3085.4963, 280, 4993.0098); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "doaba_guerfel_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Doaba Guerfel Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 3349.8933, 308, 5598.1362); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "kor_vella_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Kor Vella Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -3775.2546, 31, 3234.2202); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "kor_vella_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Kor Vella Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -3157.2834, 31, 2876.2029); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "tyrena_a_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Tyrena Shuttle A"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -5005.354, 21, -2386.9819); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "tyrena_b_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Tyrena Shuttle B"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -5600.6367, 21, -2790.7429); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "tyrena_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Tyrena Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -5003.0649, 21, -2228.3665); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "vreni_island_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Vreni Island Shuttle"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -5551.9473, 15.890146, -6059.9673); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "argilat_swamp_badge") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("POI Argilat Swamp Badge"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 1387, 30, 3749); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "bela_vistal_fountain_badge") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("POI Bela Vistal Fountain Badge"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 6767, 30, -5617); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "rebel_hideout_badge") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("POI Rebel Hideout"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -6530, 30, 5967); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "rogue_corsec_base_badge") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("POI Rogue Corsec Base Badge"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", 5291, 30, 1494); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "tyrena_theater_badge") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("POI Tyrena Theater Badge"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -5418, 30, -6248); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Dantooine Travels } else if (templatePath == "dantooine_agro_outpost_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dantooine Agro Outpost Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", 1569.66, 4, -6415.7598); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "dantooine_imperial_outpost_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dantooine Imperial Outpost Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", -4208.6602, 3, -2350.24); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "dantooine_mining_outpost_startport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dantooine Mining Outpost Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", -635.96887, 3, 2507.0115); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Dathomir Travels } else if (templatePath == "dathomir_trade_outpost_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dathomir Trade Outpost Starport "); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", 618.89258, 6.039608, 3092.0142); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "dathomir_science_outpost_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dathomir Science Outpost Starport "); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", -49.021923, 18, -1584.7278); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "dathomir_village_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dathomir Village Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", 5271.4, 0, -4119.53); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Lok Travels } else if (templatePath == "nyms_stronghold_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Nym's Stronghold Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("lok", 478.92676, 9, 5511.9565); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Hoth Travels } else if (templatePath == "scavenger_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Scavenger Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("hoth", 0, 0, -2000); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Yavin IV Travels } else if (templatePath == "yavin_iv_imperial_outpost_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Yavin IV Imperial Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("yavin4", 4054.1, 37, -6216.9); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "yavin_iv_labor_outpost_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Yavin IV Labor Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("yavin4", -6921.6733, 73, -5726.5161); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "yavin_iv_mining_outpost_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Yavin IV Mining Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("yavin4", -269, 35, 4893); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Tatooine Travels } else if (templatePath == "anchorhead_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Tatooine Anchorhead Shuttle"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 47.565128, 52, -5338.9072); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "bestine_shuttle_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Bestine Shuttle"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -1098.4836, 12, -3563.5342); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "bestine_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Bestine Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -1361.1917, 12, -3600.0254); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_eisley_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Eisley Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 3416.6914, 5, -4648.1411); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_entha_shuttle_a_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Entha Shuttle A"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 1730.8828, 7, 3184.6135); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_entha_shuttle_b_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Entha Shuttle B"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 1395.447, 7, 3467.0117); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_entha_spaceport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Entha Spaceport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 1266.0996, 7, 3065.1392); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_espa_shuttleport_east_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Espa Shuttle Port East"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -2803.511, 5, 2182.9648); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_espa_shuttleport_south_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Espa Shuttle Port South"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -2897.0933, 5, 1933.4144); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_espa_shuttleport_west_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Espa Shuttle Port West"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -3112.1296, 5, 2176.9607); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_espa_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Espa Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -2833.1609, 5, 2107.3787); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_eisley_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Eisley Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 3594, 5, -4778); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Talus Travels } else if (templatePath == "talus_dearic_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Talus Dearic Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 699.297, 6, -3041.4199); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "talus_dearic_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Talus Dearic Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 263.58401, 6, -2952.1284); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "talus_nashal_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Talus Nashal Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 4334.5786, 9.8999996, 5431.0415); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "talus_imperial_outpost_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Talus Imprial Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", -2226, 20, 2319); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "talus_nashal_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Talus Imprial Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 4455, 2, 5356); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Naboo Travels } else if (templatePath == "deeja_peak_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dee'ja Peak ShuttlePort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 5331.9375, 327.02765, -1576.6733); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "kaadar_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Kaadara ShuttlePort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 5123.3857, -192, 6616.0264); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "kaadara_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Kaadara StarPort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 5280.2002, -192, 6688.0498); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "keren_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Keren ShuttlePort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 2021.0026, 19, 2525.679); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "keren_shuttleport_south_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Karen ShuttlePort South"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 1567.5193, 25, 2837.8777); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "keren_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Keren Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 1371.5938, 13, 2747.9043); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "moenia_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Moenia StarPort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 4731.1743, 4.1700001, -4677.5439); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "the_lake_retreat_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("The Lake Retreat ShuttlePort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -5494.4224, -150, -21.837162); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "theed_shuttleport_a_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Theed ShuttlePort A"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -5856.1055, 6, 4172.1606); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "theed_shuttleport_b_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Theed ShuttlePort B"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -5005, 6, 4072); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "theed_shuttleport_c_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Theed ShuttlePort C"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -5411.0171, 6, 4322.3315); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "theed_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Theed Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -4858.834, 5.9483199, 4164.0679); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_kessel_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City - Kessel"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 7405, -196, 6200); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "moenia_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Moenia StarPort"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 4961, 3, -4898); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Rori Travels } else if (templatePath == "narmel_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Narmle Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", -5255.4116, 80.664185, -2161.6274); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "narmel_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Narmle Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", -5374.0718, 80, -2188.6143); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "rebel_outpost_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Rebel Outpost Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", 3691.9023, 96, -6403.4404); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "restuss_shuttleport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Restuss Shuttleport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", 5210, 78, 5794); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "restuss_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Restuss Starport"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", 5340, 80, 5734); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Endor Travels } else if (templatePath == "smuggler_outpost_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Endor Smuggler Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("endor", -950.59241, 73, 1553.4125); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "research_outpost_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Endor Research Outpost"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("endor", 3201.6599, 24, -3499.76); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Chandrila Travels } else if (templatePath == "nayli_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Nayli Starpot"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("chandrila", -5271, 18, 265); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "hanna_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Hanna City Starpot"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("chandrila", 253, 6, -2937); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Hutta Travels } else if (templatePath == "bilbousa_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Bilbousa Starpot"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("hutta", -765, 80, 1703); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Geonosis Travels } else if (templatePath == "geonosis_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Geonosis Starpot"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("geonosis", 86, 5, -11); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } // Mandalore Travels } else if (templatePath == "keldabe_starport_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Keldabe Starport"); box->setPromptText("Travel Cost 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("mandalore", 1568, 4, -6415); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Light Jedi Enclave } else if (templatePath == "light_enclave_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Light Jedi Enclave"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("yavin4", -5575, 87, 4901); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Dark Jedi Enclave } else if (templatePath == "dark_enclave_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Dark Jedi Enclave"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("yavin4", 5080, 79, 306); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Rori Restuss PVP Zone } else if (templatePath == "restuss_pvp_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Restuss PvP Zone"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", 5297, 78, 6115); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //Player City Travels } else if (templatePath == "pc_korrivan_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Korrivan"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -1644, 0, -5277); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_intas_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Intas Minor"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -2577, -196, 6027); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_caladan_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Caladan"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 6049, 6, -1218); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_hilltop_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Hill Top"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", -2859, 77, -5211); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_sundari_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Sundari"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("endor", -3947, 10, 3794); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_shadowfalls_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Shadow Falls"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -1474, 3, -3220); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_jantatown_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Janta Town"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", 6533, 1, -4294); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_serendipity_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Serendipity"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", -7116, 0, -3726); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_riverside_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Riverside"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("kashyyyk", 3300, 0, 2244); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_maka_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Make America Krayt Again"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", 6093, 52, 4307); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_darkness_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Darkness Falls"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", 3136, 77, -5953); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_bmh_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Bad Mutta Hutta"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("hutta", 2876, 108, 3923); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_indestine_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Indestine"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("hoth", -1847, 36, 3788); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_cyberdyne_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Cyberdyne"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", -5060, 78, -5015); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_lafayette_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Lafayette"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -6955, -196, 5360); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_skynet_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Skynet"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -4791, 22, 6402); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_crimson_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Crimson Throne"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("lok", -2996, 11, 6867); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_freedom_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("New Freedom"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("mandalore", 5733, 0, 876); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_malice_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Malice"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", 3480, 5, 3300); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_annamnesis_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Annamnesis" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("yavin4", -2253, 18, 6958); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_avalon_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Avalon Prime" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", -7004, 11, -3785); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_sanctus_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Sactus" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", -4556, 83, -4669); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_unrest_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Unrest" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", -5350, 90, -3587); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_oldwest_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("The Old West" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("mandalore", -7155, 3, -787); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_nerfherder_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Nerf Herder Central" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("taanab", 5129, 49, -4794); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_virdomus_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Vir Domus" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", -179, 20, -4180); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_littlechina_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Little China" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("tatooine", -377, 0, 3777); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "frs_floor") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("FRS Selection Floor" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dungeon2", 5994, 39, 0, 14200833); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "mos_potatoes") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Mos Potatoes" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("endor", -46, 207, 4767); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_binary_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Binary" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("lok", 1245, 0, 6603); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_asgard_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Asgard" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("geonosis", -28, 7, 1937); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_sparta_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Sparta" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", -3417, 122, 2684); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_purgatory_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Purgatory" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("endor", -3593, 200, 5764); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_sincity_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Sin city" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("taanab", -2225, 58, -501); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_nofate_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("No Fate" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", 6159, 75, 1625); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_serenity_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Serenity" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("lok", 3260, 12, -3912); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_banir_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Banir" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", 3179, 1, 5309); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_setec_astronomy_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Setec Astronomy" ); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("mandalore", -2022, 1, 2603); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_limes inferior_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Limes Inferior"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dathomir", 1985, 0, -4320); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_lowca island_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Lowca Island"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("corellia", -2019 , 8, -4392); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_solace_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Solace"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", -5499, 40, -4139); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_stewjon_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Stewjon"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("rori", 4241, 79, 5983); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_valinor_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Valinor"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("taanab", 6028, 10, 3724); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_flurrys haven_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Flurrys Haven"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 1995, -197, 6198); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_lost city_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Lost City"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("geonosis", -3476, 7, 1948); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_rebs_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Rebs of Hoth"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("hoth", -2654, 12, 4883); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_portrielig_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Port Rielig"); box->setPromptText("Travel Coast 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", 1950, 10, -6910); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_somov city_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Somov'Rit"); box->setPromptText("Travel Cost 5,000 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("geonosis", 600, 9, -1512); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity != nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_crymorenoobs_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Cry More Noobs"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 6397, 9, 2809); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_sanitarium_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Sanitarium"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("naboo", 4374, 7, 1528); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_newjustice_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City New Justice"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("lok", -6671, 11, -3516); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_laconia_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Laconia"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 315, 41, 330); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_phobos_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Phobos"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("geonosis", 5388, 6, -3956); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_infinite_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Infinite"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("dantooine", -529, 3, -2933); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } } else if (templatePath == "pc_tombstone_travel") { if (!player->isInCombat() && player->getBankCredits() < 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Player City Tombstone"); box->setPromptText("Travel Cost 5,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 4999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); ManagedReference<CityRegion*> currentCity = player->getCityRegion().get(); player->sendSystemMessage("Thank you for your travels."); player->switchZone("talus", 3900, 71, -2279); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); if(currentCity !=nullptr && !currentCity->isClientRegion()) { Locker clocker(currentCity, player); currentCity->addToCityTreasury(1000); } } //GRAY JEDI HOLOCRON QUEST END CHAPTER } else if (templatePath == "switch_normal_loadout") { if (!player->isInCombat() && player->getBankCredits() < 99) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Normal Player Loadout"); box->setPromptText("Costume Coast 100 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 99) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); player->sendSystemMessage("You are now swtiching back to your normal loadout , soft logging your character will fully cloth you again , you can also unequipt and reqequipt your items if you do not want to soft log.."); player->setAlternateAppearance("", true); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); } } else if (templatePath == "royal_guard_appearance") { if (!player->isInCombat() && player->getBankCredits() < 99) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Royal Guard"); box->setPromptText("Costume Coast 100 credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 99) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); player->sendSystemMessage("Thank you for purchasing a costume."); player->setAlternateAppearance("object/mobile/shared_royal_guard.iff", true); player->subtractBankCredits(5000); box->setForceCloseDistance(5.f); } } else if (templatePath == "become_glowy") { bluefrog->grantGlowyBadges(player); } else if (templatePath == "unlock_jedi_initiate") { if (!player->isInCombat() && player->getBankCredits() < 9999999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); box->setPromptTitle("Unlocking Jedi"); box->setPromptText("Unlocking Jedi Cost 10,000,000 Credits. (Bank)"); box->setOkButton(true, "@cancel"); box->setUsingObject(player); player->getPlayerObject()->addSuiBox(box); player->sendMessage(box->generateMessage()); } if (!player->isInCombat() && player->getBankCredits() > 9999999) { ManagedReference<SuiMessageBox*> box = new SuiMessageBox(player, SuiWindowType::CITY_ADMIN_CONFIRM_UPDATE_TYPE); player->sendSystemMessage("Thank you for purchasing a Jedi Unlock."); bluefrog->grantGlowyBadges(player); bluefrog->grantJediInitiate(player); player->subtractBankCredits(10000000); box->setForceCloseDistance(5.f); } } else { if (templatePath.length() > 0) { SkillManager::instance()->awardSkill(templatePath, player, true, true, true); if (player->hasSkill(templatePath)) player->sendSystemMessage("You have learned a skill."); } else { player->sendSystemMessage("Unknown selection."); return; } } ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); } else { // Items ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (inventory == nullptr) { return; } if (templatePath.contains("event_perk")) { if (!ghost->hasGodMode() && ghost->getEventPerkCount() >= 5) { player->sendSystemMessage("@event_perk:pro_too_many_perks"); // You cannot rent any more items right now. ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); return; } } ManagedReference<SceneObject*> item = zserv->createObject(node->getTemplateCRC(), 1); if (item == nullptr) { player->sendSystemMessage("There was an error creating the requested item. Please report this issue."); ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); error("could not create frog item: " + node->getDisplayName()); return; } Locker locker(item); item->createChildObjects(); if (item->isEventPerkDeed()) { EventPerkDeed* deed = item.castTo<EventPerkDeed*>(); deed->setOwner(player); ghost->addEventPerk(deed); } if (item->isEventPerkItem()) { if (item->getServerObjectCRC() == 0x46BD798B) { // Jukebox Jukebox* jbox = item.castTo<Jukebox*>(); if (jbox != nullptr) jbox->setOwner(player); } else if (item->getServerObjectCRC() == 0x255F612C) { // Shuttle Beacon ShuttleBeacon* beacon = item.castTo<ShuttleBeacon*>(); if (beacon != nullptr) beacon->setOwner(player); } ghost->addEventPerk(item); } if (inventory->transferObject(item, -1, true)) { item->sendTo(player, true); StringIdChatParameter stringId; stringId.setStringId("@faction_perk:bonus_base_name"); //You received a: %TO. stringId.setTO(item->getObjectID()); player->sendSystemMessage(stringId); } else { item->destroyObjectFromDatabase(true); player->sendSystemMessage("Error putting item in inventory."); return; } ghost->addSuiBox(cbSui); player->sendMessage(cbSui->generateMessage()); } player->info("[CharacterBuilder] gave player " + templatePath, true); } } void SuiManager::sendKeypadSui(SceneObject* keypad, SceneObject* creatureSceneObject, const String& play, const String& callback) { if (keypad == nullptr) return; if (creatureSceneObject == nullptr || !creatureSceneObject->isCreatureObject()) return; CreatureObject* creature = cast<CreatureObject*>(creatureSceneObject); PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiKeypadBox*> keypadSui = new SuiKeypadBox(creature, 0x00); keypadSui->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback)); keypadSui->setUsingObject(keypad); keypadSui->setForceCloseDisabled(); creature->sendMessage(keypadSui->generateMessage()); playerObject->addSuiBox(keypadSui); } } void SuiManager::sendConfirmSui(SceneObject* terminal, SceneObject* player, const String& play, const String& callback, const String& prompt, const String& button) { if (terminal == nullptr) return; if (player == nullptr || !player->isCreatureObject()) return; CreatureObject* creature = cast<CreatureObject*>(player); PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiMessageBox*> confirmSui = new SuiMessageBox(creature, 0x00); confirmSui->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback)); confirmSui->setUsingObject(terminal); confirmSui->setPromptText(prompt); confirmSui->setOkButton(true, button); confirmSui->setOtherButton(false, ""); confirmSui->setCancelButton(false, ""); confirmSui->setForceCloseDistance(32); creature->sendMessage(confirmSui->generateMessage()); playerObject->addSuiBox(confirmSui); } } void SuiManager::sendInputBox(SceneObject* terminal, SceneObject* player, const String& play, const String& callback, const String& prompt, const String& button) { if (terminal == nullptr) return; if (player == nullptr || !player->isCreatureObject()) return; CreatureObject* creature = cast<CreatureObject*>(player); PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiInputBox*> confirmSui = new SuiInputBox(creature, 0x00); confirmSui->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback)); confirmSui->setUsingObject(terminal); confirmSui->setPromptText(prompt); confirmSui->setOkButton(true, button); confirmSui->setOtherButton(false, ""); confirmSui->setCancelButton(false, ""); confirmSui->setForceCloseDistance(32); creature->sendMessage(confirmSui->generateMessage()); playerObject->addSuiBox(confirmSui); } } void SuiManager::sendMessageBox(SceneObject* usingObject, SceneObject* player, const String& title, const String& text, const String& okButton, const String& screenplay, const String& callback, unsigned int windowType ) { if (usingObject == nullptr) return; if (player == nullptr || !player->isCreatureObject()) return; CreatureObject* creature = cast<CreatureObject*>(player); PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiMessageBox*> messageBox = new SuiMessageBox(creature, windowType); messageBox->setCallback(new LuaSuiCallback(creature->getZoneServer(), screenplay, callback)); messageBox->setPromptTitle(title); messageBox->setPromptText(text); messageBox->setUsingObject(usingObject); messageBox->setOkButton(true, okButton); messageBox->setCancelButton(true, "@cancel"); messageBox->setForceCloseDistance(32.f); creature->sendMessage(messageBox->generateMessage()); playerObject->addSuiBox(messageBox); } } void SuiManager::sendListBox(SceneObject* usingObject, SceneObject* player, const String& title, const String& text, const uint8& numOfButtons, const String& cancelButton, const String& otherButton, const String& okButton, LuaObject& options, const String& screenplay, const String& callback, const float& forceCloseDist) { if (usingObject == nullptr) return; if (player == nullptr || !player->isCreatureObject()) return; CreatureObject* creature = cast<CreatureObject*>(player); PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiListBox*> box = nullptr; switch (numOfButtons) { case 1: box = new SuiListBox(creature, 0x00, SuiListBox::HANDLESINGLEBUTTON); box->setCancelButton(false, ""); box->setOtherButton(false, ""); box->setOkButton(true, okButton); break; case 2: box = new SuiListBox(creature, 0x00, SuiListBox::HANDLETWOBUTTON); box->setCancelButton(true, cancelButton); box->setOtherButton(false, ""); box->setOkButton(true, okButton); break; case 3: box = new SuiListBox(creature, 0x00, SuiListBox::HANDLETHREEBUTTON); box->setCancelButton(true, cancelButton); box->setOtherButton(true, otherButton); box->setOkButton(true, okButton); break; default: return; break; } if (options.isValidTable()) { for (int i = 1; i <= options.getTableSize(); ++i) { LuaObject table = options.getObjectAt(i); box->addMenuItem(table.getStringAt(1), table.getLongAt(2)); table.pop(); } options.pop(); } box->setCallback(new LuaSuiCallback(creature->getZoneServer(), screenplay, callback)); box->setPromptTitle(title); box->setPromptText(text); box->setUsingObject(usingObject); box->setForceCloseDistance(forceCloseDist); creature->sendMessage(box->generateMessage()); playerObject->addSuiBox(box); } } void SuiManager::sendTransferBox(SceneObject* usingObject, SceneObject* player, const String& title, const String& text, LuaObject& optionsAddFrom, LuaObject& optionsAddTo, const String& screenplay, const String& callback) { if (usingObject == nullptr) return; if (player == nullptr || !player->isCreatureObject()) return; CreatureObject* creature = cast<CreatureObject*>(player); PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiTransferBox*> box = nullptr; box = new SuiTransferBox(creature, 0x00); if(optionsAddFrom.isValidTable()){ String optionAddFromTextString = optionsAddFrom.getStringAt(1); String optionAddFromStartingString = optionsAddFrom.getStringAt(2); String optionAddFromRatioString = optionsAddFrom.getStringAt(3); box->addFrom(optionAddFromTextString, optionAddFromStartingString, optionAddFromStartingString, optionAddFromRatioString); optionsAddFrom.pop(); } if(optionsAddTo.isValidTable()){ String optionAddToTextString = optionsAddTo.getStringAt(1); String optionAddToStartingString = optionsAddTo.getStringAt(2); String optionAddToRatioString = optionsAddTo.getStringAt(3); box->addTo(optionAddToTextString, optionAddToStartingString, optionAddToStartingString, optionAddToRatioString); optionsAddTo.pop(); } box->setCallback(new LuaSuiCallback(creature->getZoneServer(), screenplay, callback)); box->setPromptTitle(title); box->setPromptText(text); box->setUsingObject(usingObject); box->setForceCloseDistance(32.f); creature->sendMessage(box->generateMessage()); playerObject->addSuiBox(box); } } int32 SuiManager::sendSuiPage(CreatureObject* creature, SuiPageData* pageData, const String& play, const String& callback, unsigned int windowType) { if (pageData == nullptr) return 0; if (creature == nullptr || !creature->isPlayerCreature()) return 0; PlayerObject* playerObject = creature->getPlayerObject(); if (playerObject != nullptr) { ManagedReference<SuiBoxPage*> boxPage = new SuiBoxPage(creature, pageData, windowType); boxPage->setCallback(new LuaSuiCallback(creature->getZoneServer(), play, callback)); creature->sendMessage(boxPage->generateMessage()); playerObject->addSuiBox(boxPage); return boxPage->getBoxID(); } return 0; }
53.505432
323
0.636271
V-Fib
87c7c386c1dab80254c8d90765c3dbb0dfa73342
1,654
cpp
C++
cplusplus/RCF/src/RCF/CurrentSerializationProtocol.cpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
cplusplus/RCF/src/RCF/CurrentSerializationProtocol.cpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
cplusplus/RCF/src/RCF/CurrentSerializationProtocol.cpp
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
//****************************************************************************** // RCF - Remote Call Framework // // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved. // http://www.deltavsoft.com // // RCF is distributed under dual licenses - closed source or GPL. // Consult your particular license for conditions of use. // // If you have not purchased a commercial license, you are using RCF // under GPL terms. // // Version: 2.0 // Contact: support <at> deltavsoft.com // //****************************************************************************** #include <RCF/CurrentSerializationProtocol.hpp> #include <RCF/ClientStub.hpp> #include <RCF/RcfSession.hpp> #include <RCF/ThreadLocalData.hpp> namespace RCF { SerializationProtocolIn *getCurrentSerializationProtocolIn() { ClientStub * pClientStub = RCF::getTlsClientStubPtr(); RcfSession * pRcfSession = RCF::getTlsRcfSessionPtr(); if (pClientStub) { return &pClientStub->getSpIn(); } else if (pRcfSession) { return &pRcfSession->getSpIn(); } else { return NULL; } } SerializationProtocolOut *getCurrentSerializationProtocolOut() { ClientStub * pClientStub = RCF::getTlsClientStubPtr(); RcfSession * pRcfSession = RCF::getTlsRcfSessionPtr(); if (pClientStub) { return &pClientStub->getSpOut(); } else if (pRcfSession) { return &pRcfSession->getSpOut(); } else { return NULL; } } } // namespace RCF
25.84375
80
0.545345
ASMlover
87c9666cbb690c2e1adede8d9ece41a4fd3f59de
15,614
cpp
C++
src/Library/DetectorSpheres/DetectorSphere.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
1
2018-12-20T19:31:02.000Z
2018-12-20T19:31:02.000Z
src/Library/DetectorSpheres/DetectorSphere.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
src/Library/DetectorSpheres/DetectorSphere.cpp
aravindkrishnaswamy/rise
297d0339a7f7acd1418e322a30a21f44c7dbbb1d
[ "BSD-2-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////// // // DetectorSphere.cpp - Implements a detector sphere // // Author: Aravind Krishnaswamy // Date of Birth: April 11, 2002 // Tabs: 4 // Comments: // // License Information: Please see the attached LICENSE.TXT file // ////////////////////////////////////////////////////////////////////// #include "pch.h" #include <fstream> #include "DetectorSphere.h" #include "../Geometry/SphereGeometry.h" #include "../Utilities/RandomNumbers.h" #include "../Utilities/RTime.h" #include "../Interfaces/ILog.h" #include <algorithm> using namespace RISE; using namespace RISE::Implementation; DetectorSphere::DetectorSphere( ) : m_pTopPatches( 0 ), m_pBottomPatches( 0 ), m_numThetaPatches( 0 ), m_numPhiPatches( 0 ), m_dRadius( 0 ), m_discretization( eEqualPSA ) { } DetectorSphere::~DetectorSphere( ) { if( m_pTopPatches ) { GlobalLog()->PrintDelete( m_pTopPatches, __FILE__, __LINE__ ); delete [] m_pTopPatches; m_pTopPatches = 0; } if( m_pBottomPatches ) { GlobalLog()->PrintDelete( m_pBottomPatches, __FILE__, __LINE__ ); delete [] m_pBottomPatches; m_pBottomPatches = 0; } } void DetectorSphere::ComputePatchAreas( const Scalar radius ) { // Scalar sqrRadius = radius * radius; for( unsigned int i=0; i<m_numThetaPatches/2; i++ ) { for( unsigned int j=0; j<m_numPhiPatches; j++ ) { const PATCH& p = m_pTopPatches[ i * m_numPhiPatches + j ]; Scalar patch_area = GeometricUtilities::SphericalPatchArea( PI_OV_TWO-p.dThetaEnd, PI_OV_TWO-p.dThetaBegin, p.dPhiBegin, p.dPhiEnd, radius ); // approx. of theta_r // Cos(Theta) is approximated by averaging theta // Scalar ctr = fabs( cos( (p.dThetaEnd-p.dThetaBegin)/2.0 + p.dThetaBegin ) ); // Cos(Theta) is approximated by averaging the Cos(thetas) Scalar ctr = (fabs( cos( p.dThetaBegin ) ) + fabs( cos( p.dThetaEnd ) )) / 2.0; { PATCH& p = m_pTopPatches[ i * m_numPhiPatches + j ]; p.dArea = patch_area; p.dCosT = ctr; p.dAreaCos = p.dArea*p.dCosT; // p.dSolidProjectedAngle = p.dAreaCos / sqrRadius; // Alternate method of computing the projected solid angle p.dSolidProjectedAngle = 0.5 * (p.dPhiEnd-p.dPhiBegin) * (cos(p.dThetaBegin)*cos(p.dThetaBegin) - cos(p.dThetaEnd)*cos(p.dThetaEnd) ); } } } } void DetectorSphere::InitPatches( const unsigned int num_theta_patches, const unsigned int num_phi_patches, const Scalar radius, const PatchDiscretization discretization ) { if( m_pTopPatches ) { GlobalLog()->PrintDelete( m_pTopPatches, __FILE__, __LINE__ ); delete m_pTopPatches; m_pTopPatches = 0; } m_dRadius = radius; m_discretization = discretization; // Allocate the memory for the patches m_pTopPatches = new PATCH[num_theta_patches*num_phi_patches/2]; GlobalLog()->PrintNew( m_pTopPatches, __FILE__, __LINE__, "top patches" ); memset( m_pTopPatches, 0, sizeof( PATCH ) * num_theta_patches*num_phi_patches/2 ); m_numThetaPatches = num_theta_patches; m_numPhiPatches = num_phi_patches; const Scalar delta_phi = 2.0 * PI/Scalar(num_phi_patches); const Scalar delta_the = PI_OV_TWO/Scalar(num_theta_patches/2); // adjusted to sphere const Scalar h = radius / Scalar(num_theta_patches/2); //Scalar delta_costheta = 1.0 / Scalar(num_theta_patches/2); // Setup the top hemisphere of patches int unsigned i=0, j=0; Scalar last_te = 0.0; const Scalar psa_per_patch = PI / Scalar(num_theta_patches/2); // Hemisphere const Scalar OV_Num_Theta = 1.0 / Scalar(num_theta_patches/2); for( i=0; i<num_theta_patches/2; i++ ) { Scalar tb=0, te=0; if( m_discretization == eEqualAngles ) { // This keeps the angle the same for each of the patches tb = i*delta_the; te = tb + delta_the; } else if( m_discretization == eEqualAreas ) { // This keeps the area the same for each of the patches tb = asin( h*Scalar(i) / radius ); te = asin( h*Scalar(i+1) / radius ); // This also keeps the area the same for each of the patches, equal intervals in CosT space // tb = acos( delta_costheta * Scalar(i+1) ); // te = acos( delta_costheta * Scalar(i) ); } else if( m_discretization == eExponentiallyIncreasingSolidAngles ) { // Right from the paper tb = acos( h*Scalar(i+1) / radius ); te = acos( h*Scalar(i) / radius ); } else if( m_discretization == eEqualPSA ) { // Keeps the PSA the same, but assumes that the coses are embedded in the integration tb = last_te; te = acos( sqrt( fabs( OV_Num_Theta - cos(last_te)*cos(last_te) ) ) ); last_te = te; } for( j=0; j<num_phi_patches; j++ ) { PATCH& patch = m_pTopPatches[ i*num_phi_patches + j ]; patch.dThetaBegin = tb; patch.dThetaEnd = te; patch.dPhiBegin = j*delta_phi; patch.dPhiEnd = patch.dPhiBegin + delta_phi; if( m_discretization == eEqualPSA ) { patch.dArea = GeometricUtilities::SphericalPatchArea( patch.dThetaBegin, patch.dThetaEnd, patch.dPhiBegin, patch.dPhiEnd, radius ); patch.dSolidProjectedAngle = psa_per_patch / Scalar(num_phi_patches); } patch.dKnownValue = INV_PI; patch.dRatio = 0; } } if( m_discretization != eEqualPSA ) { ComputePatchAreas( m_dRadius ); } // Now setup the bottom hemisphere of patches, the bottom hemisphere can be a direct copy of // the top, except that the theta's just need to be adjusted to add PI_OV_TWO if( m_pBottomPatches ) { GlobalLog()->PrintDelete( m_pBottomPatches, __FILE__, __LINE__ ); delete [] m_pBottomPatches; m_pBottomPatches = 0; } // Allocate the memory for the patches m_pBottomPatches = new PATCH[num_theta_patches*num_phi_patches/2]; GlobalLog()->PrintNew( m_pBottomPatches, __FILE__, __LINE__, "bottom patches" ); memcpy( m_pBottomPatches, m_pTopPatches, sizeof( PATCH ) * num_theta_patches*num_phi_patches/2 ); // Now go through and adjust the thetas for( i=0; i<num_theta_patches/2; i++ ) { for( j=0; j<num_phi_patches; j++ ) { PATCH& patch = m_pBottomPatches[ i*num_phi_patches + j ]; patch.dThetaBegin = PI - patch.dThetaBegin; patch.dThetaEnd = PI - patch.dThetaEnd; } } } void DetectorSphere::DumpToCSVFileForExcel( const char * szFile, const Scalar phi_begin, const Scalar phi_end, const Scalar theta_begin, const Scalar theta_end ) const { int i, e; // We write our results to a CSV file so that it can be loaded in excel and nice graphs can be // made from it... std::ofstream f( szFile ); f << "Top hemisphere" << std::endl; f << "Theta begin, Theta end, Phi begin, Phi end, Patch area, Cos T, Solid Proj. Angle, Ratio\n";; for( i=0, e = numPatches()/2; i<e; i++ ) { f << m_pTopPatches[i].dThetaBegin * RAD_TO_DEG << ", " << m_pTopPatches[i].dThetaEnd * RAD_TO_DEG << ", " << m_pTopPatches[i].dPhiBegin * RAD_TO_DEG << ", " << m_pTopPatches[i].dPhiEnd * RAD_TO_DEG << ", " << m_pTopPatches[i].dArea << ", " << m_pTopPatches[i].dCosT << ", " << m_pTopPatches[i].dSolidProjectedAngle << ", " << m_pTopPatches[i].dRatio << "\n"; } f << std::endl << std::endl; f << "Bottom hemisphere" << std::endl; f << "Theta begin, Theta end, Phi begin, Phi end, Patch area, Cos T, Solid Proj. Angle, Ratio\n";; for( i=0, e = numPatches()/2; i<e; i++ ) { f << m_pBottomPatches[i].dThetaBegin * RAD_TO_DEG << ", " << m_pBottomPatches[i].dThetaEnd * RAD_TO_DEG << ", " << m_pBottomPatches[i].dPhiBegin * RAD_TO_DEG << ", " << m_pBottomPatches[i].dPhiEnd * RAD_TO_DEG << ", " << m_pBottomPatches[i].dArea << ", " << m_pBottomPatches[i].dCosT << ", " << m_pBottomPatches[i].dSolidProjectedAngle << ", " << m_pBottomPatches[i].dRatio << "\n"; } } void DetectorSphere::DumpForMatlab( const char* szFile, const Scalar phi_begin, const Scalar phi_end, const Scalar theta_begin, const Scalar theta_end ) const { std::ofstream f( szFile ); unsigned int i, j; for( i=0; i<m_numThetaPatches/2; i++ ) { for( j=0; j<m_numPhiPatches; j++ ) { f << m_pTopPatches[i*m_numPhiPatches+j].dRatio << " "; } f << std::endl; } for( i=0; i<m_numThetaPatches/2; i++ ) { for( j=0; j<m_numPhiPatches; j++ ) { f << m_pBottomPatches[i*m_numPhiPatches+j].dRatio << " "; } f << std::endl; } } DetectorSphere::PATCH* DetectorSphere::PatchFromAngles( const Scalar& theta, const Scalar phi ) const { // Optimization: Finding out which phi is trivial, its which theta that is tricky... // This says its the nth phi patch on the mth theta ring const unsigned int phi_num = int( (phi / TWO_PI) * Scalar(m_numPhiPatches)); // Find out which side first if( theta <= PI_OV_TWO ) { // Top patches for( unsigned int i=0; i<m_numThetaPatches/2; i++ ) { const unsigned int iPatchIdx = i*m_numPhiPatches+phi_num; const PATCH& p = m_pTopPatches[iPatchIdx]; if( theta >= p.dThetaBegin && theta <= p.dThetaEnd ) { // This is the right ring... return &m_pTopPatches[iPatchIdx]; } } } if( theta >= PI_OV_TWO ) { // Bottom patches for( unsigned int i=0; i<m_numThetaPatches/2; i++ ) { const unsigned int iPatchIdx = i*m_numPhiPatches+phi_num; const PATCH& p = m_pBottomPatches[iPatchIdx]; if( theta >= p.dThetaEnd && theta <= p.dThetaBegin ) { // This is the right ring... return &m_pBottomPatches[iPatchIdx]; } } } return 0; } void DetectorSphere::PerformMeasurement( const ISampleGeometry& pEmmitter, ///< [in] Sample geometry of the emmitter const ISampleGeometry& pSpecimenGeom, ///< [in] Sample geometry of the specimen const Scalar& radiant_power, const IMaterial& pSample, const unsigned int num_samples, const unsigned int samples_base, IProgressCallback* pProgressFunc, int progress_rate ) { // Clear the current results { for( int i=0, e=numPatches()/2; i<e; i++ ) { m_pTopPatches[i].dRatio = 0; m_pBottomPatches[i].dRatio = 0; } } srand( GetMilliseconds() ); // The detector geometry itself, which is a sphere SphereGeometry* pDetector = new SphereGeometry( m_dRadius ); GlobalLog()->PrintNew( pDetector, __FILE__, __LINE__, "Detector sphere geometry" ); //Scalar theta_size = Scalar(m_numThetaPatches) * INV_PI; //Scalar phi_size = 0.5 * Scalar(m_numPhiPatches) * INV_PI; Scalar power_each_sample = radiant_power / (Scalar(num_samples) * Scalar(samples_base)); // See below, this is power distributed to every patch in the ring at the top of the detector Scalar specialCaseDistributedEnergy = power_each_sample / Scalar(m_numPhiPatches); unsigned int i = 0; ISPF* pSPF = pSample.GetSPF(); if( !pSPF ) { return; } for( ; i<num_samples; i++ ) { for( unsigned int j = 0; j<samples_base; j++ ) { Point3 pointOnEmmitter = pEmmitter.GetSamplePoint(); Point3 pointOnSpecimen = pSpecimenGeom.GetSamplePoint(); // The emmitter ray starts at where the emmitter is, and heads towards the world origin Ray emmitter_ray( pointOnEmmitter, Vector3Ops::Normalize(Vector3Ops::mkVector3(pointOnSpecimen,pointOnEmmitter)) ); RayIntersectionGeometric ri( emmitter_ray, nullRasterizerState ); ri.ptIntersection = Point3(0,0,0); // ri.onb.CreateFromW( Vector3( 1, 0, 0 ) ); // For each sample, fire it down to the surface, the fire the reflected ray to see // which detector it hits ScatteredRayContainer scattered; pSPF->Scatter( ri, random, scattered, 0 ); ScatteredRay* pScat = scattered.RandomlySelect( random.CanonicalRandom(), false ); if( pScat ) { // If the ray wasn't absorbed, then fire it at the detector patches RayIntersectionGeometric ri( pScat->ray, nullRasterizerState ); Vector3Ops::NormalizeMag(ri.ray.dir); // Ignore the front faces, just hit the back faces! pDetector->IntersectRay( ri, false, true, false ); if( ri.bHit ) { // Compute the deposited power on this detector // // To do this we just follow the instructions as laid out in // Baranoski and Rokne's Eurographics tutorial // "Simulation Of Light Interaction With Plants" // // This is the ratio between the radiant power reaching the detector // and the incident radiant power (which is multiplied by the projected solid angle) // Note that rather than accruing the power reaching the detector, we could simply // count the number of rays that hit the detector and use that as the ratio (still multiplying) // by the projected solid angle of course... either way is fine, neither is more or less // beneficial... though I could see an application of this method to ensure materials // maintain energy conservation. // // Here we just store the incident power, which is simple enough to do Scalar phi=0, theta=0; if( Point3Ops::AreEqual(ri.ptIntersection, Point3( 0, 0, 1 ), NEARZERO ) ) { // Special case: // The ray is reflected completely straight up, at precisely the point // where all the patches of one ring meet. This was causing accuracy problems with // certain BRDFs, so instead, the power is equally distributed to all the patches // that particular ring for( unsigned int k=(m_numThetaPatches-2)*m_numPhiPatches/2; k<m_numPhiPatches*m_numThetaPatches/2; k++ ) { m_pTopPatches[ k ].dRatio += specialCaseDistributedEnergy; } } else if( Point3Ops::AreEqual(ri.ptIntersection, Point3( 0, 0, -1 ), NEARZERO ) ) { for( unsigned int k=(m_numThetaPatches-2)*m_numThetaPatches/2; k<m_numPhiPatches*m_numThetaPatches/2; k++ ) { m_pBottomPatches[ k ].dRatio += specialCaseDistributedEnergy; } } else { if( GeometricUtilities::GetSphericalFromPoint3( ri.ptIntersection, phi, theta ) ) { #if 1 if( theta < PI_OV_TWO ) { theta = PI_OV_TWO - theta; } else { theta = PI_OV_TWO + PI - theta; } if( phi < PI ) { phi = PI + phi; } else { phi = phi - PI; } #endif PATCH* patch = PatchFromAngles( theta, phi ); if( !patch ) { GlobalLog()->PrintEx( eLog_Warning, "DetectorSphere::PerformMeasurement, Couldn't find patch, phi: %f, theta: %f", phi, theta ); } else { patch->dRatio += power_each_sample*ColorMath::MaxValue(pScat->kray); } } } } } } if( (i % progress_rate == 0) && pProgressFunc ) { if( !pProgressFunc->Progress( static_cast<double>(i), static_cast<double>(num_samples) ) ) { break; // abort } } } safe_release( pDetector ); if( pProgressFunc ) { pProgressFunc->Progress( 1.0, 1.0 ); } // Scalar sqrRadius = (m_dRadius*m_dRadius); unsigned int e = m_numThetaPatches*m_numPhiPatches/2; for( i=0; i<e; i++ ) { // // Now we compute the ratio, // which is the power reaching the detector, divided by // the total incident power times the solid projected angle m_pTopPatches[i].dRatio /= radiant_power * m_pTopPatches[i].dSolidProjectedAngle; m_pBottomPatches[i].dRatio /= radiant_power * m_pBottomPatches[i].dSolidProjectedAngle; } } Scalar DetectorSphere::ComputeOverallRMSErrorIfPerfectlyDiffuse( ) const { // // Given the known value for each of the patches, it computes the overall error for // the entire detector // // // RMS error = sqrt( 1/M sum_i sum_j e^2(i,j) where e(i,j) = abs( f(i,j) - fr(i,j) ) // where f(i,j) is the estimated value for the patch // and fr(i,j) is the actual value for the patch // Scalar accruedSum=0; for( unsigned int i=0; i<numPatches(); i++ ) { Scalar eij = m_pTopPatches[i].dRatio - m_pTopPatches[i].dKnownValue; accruedSum += eij*eij; } return sqrt(accruedSum / Scalar(numPatches()) ); }
33.363248
385
0.671128
aravindkrishnaswamy
d7b54eb5eefebc6c56e7906c584d96697fcebb3a
736
cpp
C++
input/pointer2.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/pointer2.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
input/pointer2.cpp
xdevkartik/cpp_basics
a6d5a6aca5cdd5b9634c300cfaf2e2914a57aa55
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; main() { string str = {}; int i = 0; string wordfinal; for (string word; i < 3; i++) { cout << "Please enter any word " << i + 1 << ": "; //cin.ignore(); // I have to use it to clear apce of previous cout. getline(cin, word); //cout << word; //cin >> word; // cin only take char as a input, means only 1 character. // So i have to use getline() function wordfinal = "\"" + word + "\", "; //str.append(wordfinal); str[i] = wordfinal; cout << str << "\n"; } cout << "Now printing array backward.\n"; // Printing last entered word first and so on... cout << str[2]; return 0; }
28.307692
80
0.516304
xdevkartik
d7b6b229f4cb939fec3e0ed86681ef0ec637faf9
7,563
cpp
C++
B2G/external/skia/samplecode/SamplePicture.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/external/skia/samplecode/SamplePicture.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/external/skia/samplecode/SamplePicture.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
#include "SampleCode.h" #include "SkDumpCanvas.h" #include "SkView.h" #include "SkCanvas.h" #include "Sk64.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkImageDecoder.h" #include "SkPath.h" #include "SkPicture.h" #include "SkRandom.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkShape.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "SkStream.h" #include "SkXMLParser.h" class SignalShape : public SkShape { public: SignalShape() : fSignal(0) {} SkShape* setSignal(int n) { fSignal = n; return this; } protected: virtual void onDraw(SkCanvas* canvas) { // SkDebugf("---- sc %d\n", canvas->getSaveCount() - 1); } private: int fSignal; }; static SkPMColor SignalProc(SkPMColor src, SkPMColor dst) { return dst; } /* Picture playback will skip blocks of draw calls that follow a clip() call that returns empty, and jump down to the corresponding restore() call. This is a great preformance win for drawing very large/tall pictures with a small visible window (think scrolling a long document). These tests make sure that (a) we are performing the culling, and (b) we don't get confused by nested save() calls, nor by calls to restoreToCount(). */ static void test_saveRestoreCulling() { SkPaint signalPaint; SignalShape signalShape; SkPicture pic; SkRect r = SkRect::MakeWH(0, 0); int n; SkCanvas* canvas = pic.beginRecording(100, 100); int startN = canvas->getSaveCount(); SkDebugf("---- start sc %d\n", startN); canvas->drawShape(signalShape.setSignal(1)); canvas->save(); canvas->drawShape(signalShape.setSignal(2)); n = canvas->save(); canvas->drawShape(signalShape.setSignal(3)); canvas->save(); canvas->clipRect(r); canvas->drawShape(signalShape.setSignal(4)); canvas->restoreToCount(n); canvas->drawShape(signalShape.setSignal(5)); canvas->restore(); canvas->drawShape(signalShape.setSignal(6)); SkASSERT(canvas->getSaveCount() == startN); SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, 100, 100); bm.allocPixels(); SkCanvas c(bm); c.drawPicture(pic); } /////////////////////////////////////////////////////////////////////////////// #include "SkImageRef_GlobalPool.h" static SkBitmap load_bitmap() { SkStream* stream = new SkFILEStream("/skimages/sesame_street_ensemble-hp.jpg"); SkAutoUnref aur(stream); SkBitmap bm; if (SkImageDecoder::DecodeStream(stream, &bm, SkBitmap::kNo_Config, SkImageDecoder::kDecodeBounds_Mode)) { SkPixelRef* pr = new SkImageRef_GlobalPool(stream, bm.config(), 1); bm.setPixelRef(pr)->unref(); } return bm; } static void drawCircle(SkCanvas* canvas, int r, SkColor color) { SkPaint paint; paint.setAntiAlias(true); paint.setColor(color); canvas->drawCircle(SkIntToScalar(r), SkIntToScalar(r), SkIntToScalar(r), paint); } class PictureView : public SampleView { SkBitmap fBitmap; public: PictureView() { SkImageRef_GlobalPool::SetRAMBudget(16 * 1024); fBitmap = load_bitmap(); fPicture = new SkPicture; SkCanvas* canvas = fPicture->beginRecording(100, 100); SkPaint paint; paint.setAntiAlias(true); canvas->drawBitmap(fBitmap, 0, 0, NULL); drawCircle(canvas, 50, SK_ColorBLACK); fSubPicture = new SkPicture; canvas->drawPicture(*fSubPicture); canvas->translate(SkIntToScalar(50), 0); canvas->drawPicture(*fSubPicture); canvas->translate(0, SkIntToScalar(50)); canvas->drawPicture(*fSubPicture); canvas->translate(SkIntToScalar(-50), 0); canvas->drawPicture(*fSubPicture); // fPicture now has (4) references to us. We can release ours, and just // unref fPicture in our destructor, and it will in turn take care of // the other references to fSubPicture fSubPicture->unref(); test_saveRestoreCulling(); } virtual ~PictureView() { fPicture->unref(); } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "Picture"); return true; } return this->INHERITED::onQuery(evt); } void drawSomething(SkCanvas* canvas) { SkPaint paint; canvas->save(); canvas->scale(0.5f, 0.5f); canvas->drawBitmap(fBitmap, 0, 0, NULL); canvas->restore(); const char beforeStr[] = "before circle"; const char afterStr[] = "after circle"; paint.setAntiAlias(true); paint.setColor(SK_ColorRED); canvas->drawData(beforeStr, sizeof(beforeStr)); canvas->drawCircle(SkIntToScalar(50), SkIntToScalar(50), SkIntToScalar(40), paint); canvas->drawData(afterStr, sizeof(afterStr)); paint.setColor(SK_ColorBLACK); paint.setTextSize(SkIntToScalar(40)); canvas->drawText("Picture", 7, SkIntToScalar(50), SkIntToScalar(62), paint); } virtual void onDrawContent(SkCanvas* canvas) { drawSomething(canvas); SkPicture* pict = new SkPicture; SkAutoUnref aur(pict); drawSomething(pict->beginRecording(100, 100)); pict->endRecording(); canvas->save(); canvas->translate(SkIntToScalar(300), SkIntToScalar(50)); canvas->scale(-SK_Scalar1, -SK_Scalar1); canvas->translate(-SkIntToScalar(100), -SkIntToScalar(50)); canvas->drawPicture(*pict); canvas->restore(); canvas->save(); canvas->translate(SkIntToScalar(200), SkIntToScalar(150)); canvas->scale(SK_Scalar1, -SK_Scalar1); canvas->translate(0, -SkIntToScalar(50)); canvas->drawPicture(*pict); canvas->restore(); canvas->save(); canvas->translate(SkIntToScalar(100), SkIntToScalar(100)); canvas->scale(-SK_Scalar1, SK_Scalar1); canvas->translate(-SkIntToScalar(100), 0); canvas->drawPicture(*pict); canvas->restore(); if (false) { SkDebugfDumper dumper; SkDumpCanvas dumpCanvas(&dumper); dumpCanvas.drawPicture(*pict); } // test that we can re-record a subpicture, and see the results SkRandom rand(SampleCode::GetAnimTime()); canvas->translate(SkIntToScalar(10), SkIntToScalar(250)); drawCircle(fSubPicture->beginRecording(50, 50), 25, rand.nextU() | 0xFF000000); canvas->drawPicture(*fPicture); delayInval(500); } private: #define INVAL_ALL_TYPE "inval-all" void delayInval(SkMSec delay) { (new SkEvent(INVAL_ALL_TYPE))->post(this->getSinkID(), delay); } virtual bool onEvent(const SkEvent& evt) { if (evt.isType(INVAL_ALL_TYPE)) { this->inval(NULL); return true; } return this->INHERITED::onEvent(evt); } SkPicture* fPicture; SkPicture* fSubPicture; typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new PictureView; } static SkViewRegister reg(MyFactory);
29.658824
83
0.615232
wilebeast
d7b789f0fddc21ac674103af32f37b76dc5f8c83
198
hpp
C++
src/waygate.hpp
ohowland/waygate
926100c101b30827b52ba9262f3b7dfdbb6f50ad
[ "MIT" ]
null
null
null
src/waygate.hpp
ohowland/waygate
926100c101b30827b52ba9262f3b7dfdbb6f50ad
[ "MIT" ]
null
null
null
src/waygate.hpp
ohowland/waygate
926100c101b30827b52ba9262f3b7dfdbb6f50ad
[ "MIT" ]
null
null
null
#define WAYGATE_VERSION_MAJOR @WAYGATE_VERSION_MAJOR@ #define WAYGATE_VERSION_MINOR @WAYGATE_VERSION_MINOR@ #define PROJECT_CONFIG_DIR @PROJECT_CONFIG_DIR@ #include "bus.hpp" #include "signals.hpp"
33
53
0.848485
ohowland
d7b9a861bee0cc94b025451683fc0115352bf679
1,103
cpp
C++
ver1/answers/lp-14-37.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
ver1/answers/lp-14-37.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
ver1/answers/lp-14-37.cpp
aafulei/cppp5e
f8d254073866e3025c3a08b919d9bbe3965b6918
[ "MIT" ]
null
null
null
// 18/03/14 = Wed // Exercise 14.37: Write a class that tests whether two values are equal. Use that object and the library algorithms to write a program to replace all instances of a given value in a sequence. #include <algorithm> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <vector> using namespace std; template<typename T> class Equal { T v; public: Equal(const T & v) : v(v) {} bool operator()(T u) const { return u == v; } }; template<typename C> void print(const C & c) { for (const auto & e : c) cout << e << endl; } string process(const string & line) { istringstream iss(line); ostringstream oss; istream_iterator<string> isit(iss), isend; ostream_iterator<string> osit(oss, " "); string word, with; cout << "Enter the word you want to replace: "; cin >> word; cout << "with what? "; cin >> with; Equal<string> eq(word); replace_copy_if(isit, isend, osit, eq, with); return oss.str(); } int main() { const string line = "how now now now brown cow cow"; cout << line << endl; cout << process(line) << endl; return 0; }
20.054545
192
0.671804
aafulei
d7c03bfdeaed888635cc39cd09c2bce3aef4f95e
299
cc
C++
src/abc195/a.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc195/a.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc195/a.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#ifdef _debug #define _GLIBCXX_DEBUG #endif #include <bits/stdc++.h> typedef long long ll; using namespace std; string solve(int m, int h) { return h % m == 0 ? "Yes" : "No"; } #ifndef _debug int main() { int m, h; cin >> m >> h; cout << solve(m, h) << endl; return 0; } #endif
15.736842
37
0.585284
nryotaro
d7c41c9f13f27f9cec743aeb265bb560a063488d
18,285
cpp
C++
src/csapex_core/src/model/graph_facade_impl.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
21
2016-09-02T15:33:25.000Z
2021-06-10T06:34:39.000Z
src/csapex_core/src/model/graph_facade_impl.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
src/csapex_core/src/model/graph_facade_impl.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
10
2016-10-12T00:55:17.000Z
2020-04-24T19:59:02.000Z
/// HEADER #include <csapex/model/graph_facade_impl.h> /// PROJECT #include <csapex/model/node_facade_impl.h> #include <csapex/model/graph_facade_impl.h> #include <csapex/model/graph/graph_impl.h> #include <csapex/model/graph/vertex.h> #include <csapex/model/subgraph_node.h> #include <csapex/model/node_state.h> #include <csapex/model/node_runner.h> #include <csapex/model/node_handle.h> #include <csapex/scheduling/thread_pool.h> #include <csapex/msg/direct_connection.h> #include <csapex/model/connectable.h> #include <csapex/msg/input.h> #include <csapex/msg/output.h> #include <csapex/signal/event.h> #include <csapex/signal/slot.h> using namespace csapex; GraphFacadeImplementation::GraphFacadeImplementation(ThreadPool& executor, GraphImplementationPtr graph, SubgraphNodePtr graph_node, NodeFacadeImplementationPtr nh, GraphFacadeImplementation* parent) : absolute_uuid_(graph_node->getUUID()), parent_(parent), graph_handle_(nh), executor_(executor), graph_(graph), graph_node_(graph_node) { observe(graph->vertex_added, this, &GraphFacadeImplementation::nodeAddedHandler); observe(graph->vertex_removed, this, &GraphFacadeImplementation::nodeRemovedHandler); observe(graph->notification, notification); observe(graph->connection_added, [this](const ConnectionDescription& ci) { connection_added(ci); }); observe(graph->connection_removed, [this](const ConnectionDescription& ci) { connection_removed(ci); }); observe(graph->state_changed, state_changed); observe(graph_node_->forwarding_connector_added, forwarding_connector_added); observe(graph_node_->forwarding_connector_removed, forwarding_connector_removed); if (parent_) { // TODO: refactor! apex_assert_hard(graph_handle_); AUUID parent_auuid = parent_->getAbsoluteUUID(); if (!parent_auuid.empty()) { absolute_uuid_ = AUUID(UUIDProvider::makeDerivedUUID_forced(parent_auuid, absolute_uuid_.getFullName())); } } } NodeFacadePtr GraphFacadeImplementation::getNodeFacade() const { return graph_handle_; } AUUID GraphFacadeImplementation::getAbsoluteUUID() const { return absolute_uuid_; } UUID GraphFacadeImplementation::generateUUID(const std::string& prefix) { return graph_->generateUUID(prefix); } GraphFacade* GraphFacadeImplementation::getParent() const { return parent_; } GraphFacadePtr GraphFacadeImplementation::getSubGraph(const UUID& uuid) { if (uuid.empty()) { throw std::logic_error("cannot get subgraph for empty UUID"); } if (uuid.composite()) { GraphFacadePtr facade = children_[uuid.rootUUID()]; return facade->getSubGraph(uuid.nestedUUID()); } else { GraphFacadePtr facade = children_[uuid]; return facade; } } GraphFacadeImplementationPtr GraphFacadeImplementation::getLocalSubGraph(const UUID& uuid) { if (uuid.empty()) { throw std::logic_error("cannot get subgraph for empty UUID"); } if (uuid.composite()) { GraphFacadeImplementationPtr facade = children_.at(uuid.rootUUID()); return facade->getLocalSubGraph(uuid.nestedUUID()); } else { return children_.at(uuid); } } SubgraphNodePtr GraphFacadeImplementation::getSubgraphNode() { return std::dynamic_pointer_cast<SubgraphNode>(graph_node_); } NodeFacadePtr GraphFacadeImplementation::findNodeFacade(const UUID& uuid) const { return graph_->findNodeFacade(uuid); } NodeFacadePtr GraphFacadeImplementation::findNodeFacadeNoThrow(const UUID& uuid) const noexcept { return graph_->findNodeFacadeNoThrow(uuid); } NodeFacadePtr GraphFacadeImplementation::findNodeFacadeForConnector(const UUID& uuid) const { return graph_->findNodeFacadeForConnector(uuid); } NodeFacadePtr GraphFacadeImplementation::findNodeFacadeForConnectorNoThrow(const UUID& uuid) const noexcept { return graph_->findNodeFacadeForConnectorNoThrow(uuid); } NodeFacadePtr GraphFacadeImplementation::findNodeFacadeWithLabel(const std::string& label) const { return graph_->findNodeFacadeWithLabel(label); } ConnectorPtr GraphFacadeImplementation::findConnector(const UUID& uuid) { return graph_->findConnector(uuid); } ConnectorPtr GraphFacadeImplementation::findConnectorNoThrow(const UUID& uuid) noexcept { return graph_->findConnectorNoThrow(uuid); } bool GraphFacadeImplementation::isConnected(const UUID& from, const UUID& to) const { return graph_->getConnection(from, to) != nullptr; } ConnectionDescription GraphFacadeImplementation::getConnection(const UUID& from, const UUID& to) const { ConnectionPtr c = graph_->getConnection(from, to); if (!c) { throw std::runtime_error("unknown connection requested"); } return c->getDescription(); } ConnectionDescription GraphFacadeImplementation::getConnectionWithId(int id) const { ConnectionPtr c = graph_->getConnectionWithId(id); if (!c) { throw std::runtime_error("Cannot get connection with id " + std::to_string(id)); } return c->getDescription(); } std::size_t GraphFacadeImplementation::countNodes() const { return graph_->countNodes(); } int GraphFacadeImplementation::getComponent(const UUID& node_uuid) const { return graph_->getComponent(node_uuid); } int GraphFacadeImplementation::getDepth(const UUID& node_uuid) const { return graph_->getDepth(node_uuid); } GraphImplementationPtr GraphFacadeImplementation::getLocalGraph() const { return graph_; } GraphFacadeImplementation* GraphFacadeImplementation::getLocalParent() const { return parent_; } NodeFacadeImplementationPtr GraphFacadeImplementation::getLocalNodeFacade() const { return graph_handle_; } ThreadPool* GraphFacadeImplementation::getThreadPool() { return &executor_; } TaskGenerator* GraphFacadeImplementation::getTaskGenerator(const UUID& uuid) { return generators_.at(uuid).get(); } void GraphFacadeImplementation::addNode(NodeFacadeImplementationPtr nh) { graph_->addNode(nh); } void GraphFacadeImplementation::clear() { stop(); graph_->clear(); generators_.clear(); } void GraphFacadeImplementation::stop() { for (NodeHandle* nh : graph_->getAllNodeHandles()) { nh->stop(); } executor_.stop(); stopped(); } ConnectionPtr GraphFacadeImplementation::connect(OutputPtr output, InputPtr input) { auto c = DirectConnection::connect(output, input); graph_->addConnection(c); return c; } ConnectionPtr GraphFacadeImplementation::connect(NodeHandlePtr output, int output_id, NodeHandlePtr input, int input_id) { return connect(output.get(), output_id, input.get(), input_id); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, NodeHandlePtr input, int input_id) { OutputPtr o = getOutput(output_id); InputPtr i = getInput(getInputUUID(input.get(), input_id)); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeHandlePtr output, int output_id, const UUID& input_id) { OutputPtr o = getOutput(getOutputUUID(output.get(), output_id)); InputPtr i = getInput(input_id); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, NodeHandlePtr input, const std::string& input_id) { return connect(output_id, input.get(), input_id); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, NodeHandle* input, const std::string& input_id) { OutputPtr o = getOutput(output_id); InputPtr i = getInput(getInputUUID(input, input_id)); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeHandlePtr output, const std::string& output_id, const UUID& input_id) { return connect(output.get(), output_id, input_id); } ConnectionPtr GraphFacadeImplementation::connect(NodeHandle* output, const std::string& output_id, const UUID& input_id) { OutputPtr o = getOutput(getOutputUUID(output, output_id)); InputPtr i = getInput(input_id); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeHandle* output, int output_id, NodeHandle* input, int input_id) { OutputPtr o = getOutput(getOutputUUID(output, output_id)); InputPtr i = getInput(getInputUUID(input, input_id)); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeHandlePtr output, const std::string& output_id, NodeHandlePtr input, const std::string& input_id) { return connect(output.get(), output_id, input.get(), input_id); } ConnectionPtr GraphFacadeImplementation::connect(NodeHandle* output, const std::string& output_name, NodeHandle* input, const std::string& input_name) { OutputPtr o = getOutput(getOutputUUID(output, output_name)); InputPtr i = getInput(getInputUUID(input, input_name)); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, const UUID& input_id) { OutputPtr o = getOutput(output_id); InputPtr i = getInput(input_id); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, NodeFacade* input, const std::string& input_name) { UUID i = getInputUUID(input, input_name); return connect(output_id, i); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, NodeFacadePtr input, const std::string& input_name) { return connect(output_id, input.get(), input_name); } ConnectionPtr GraphFacadeImplementation::connect(const UUID& output_id, NodeFacadePtr input, int input_id) { UUID i = getInputUUID(input.get(), input_id); return connect(output_id, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacade* output, const std::string& output_name, NodeFacade* input, const std::string& input_name) { UUID o = getOutputUUID(output, output_name); UUID i = getInputUUID(input, input_name); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacadePtr output, const std::string& output_name, NodeFacadePtr input, const std::string& input_name) { return connect(output.get(), output_name, input.get(), input_name); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacade* output, const std::string& output_name, const UUID& input_id) { UUID o = getOutputUUID(output, output_name); return connect(o, input_id); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacadePtr output, const std::string& output_name, const UUID& input_id) { return connect(output.get(), output_name, input_id); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacadePtr output, int output_id, const UUID& input_id) { UUID o = getOutputUUID(output.get(), output_id); return connect(o, input_id); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacade* output, int output_id, NodeFacade* input, int input_id) { UUID o = getOutputUUID(output, output_id); UUID i = getInputUUID(input, input_id); return connect(o, i); } ConnectionPtr GraphFacadeImplementation::connect(NodeFacadePtr output, int output_id, NodeFacadePtr input, int input_id) { UUID o = getOutputUUID(output.get(), output_id); UUID i = getInputUUID(input.get(), input_id); return connect(o, i); } OutputPtr GraphFacadeImplementation::getOutput(const UUID& uuid) { OutputPtr o = std::dynamic_pointer_cast<Output>(getConnectable(uuid)); apex_assert_hard(o); return o; } InputPtr GraphFacadeImplementation::getInput(const UUID& uuid) { InputPtr i = std::dynamic_pointer_cast<Input>(getConnectable(uuid)); apex_assert_hard(i); return i; } ConnectablePtr GraphFacadeImplementation::getConnectable(const UUID& uuid) { NodeHandle* node = graph_->findNodeHandleForConnector(uuid); apex_assert_hard(node); return node->getConnector(uuid); } UUID GraphFacadeImplementation::getOutputUUID(NodeFacade* node, const std::string& label) { for (const ConnectorDescription& out : node->getExternalOutputs()) { if (out.label == label) { return out.id; } } for (const ConnectorDescription& event : node->getEvents()) { if (event.label == label) { return event.id; } } throw std::logic_error(node->getUUID().getFullName() + " does not have an output with the label " + label); } UUID GraphFacadeImplementation::getInputUUID(NodeFacade* node, const std::string& label) { for (const ConnectorDescription& in : node->getExternalInputs()) { if (in.label == label) { return in.id; } } for (const ConnectorDescription& slot : node->getSlots()) { if (slot.label == label) { return slot.id; } } throw std::logic_error(node->getUUID().getFullName() + " does not have an input with the label " + label); } UUID GraphFacadeImplementation::getOutputUUID(NodeHandle* node, const std::string& label) { for (const OutputPtr& out : node->getExternalOutputs()) { if (out->getLabel() == label) { return out->getUUID(); } } for (const EventPtr& event : node->getEvents()) { if (event->getLabel() == label) { return event->getUUID(); } } throw std::logic_error(node->getUUID().getFullName() + " does not have an output with the label " + label); } UUID GraphFacadeImplementation::getInputUUID(NodeHandle* node, const std::string& label) { for (const InputPtr& in : node->getExternalInputs()) { if (in->getLabel() == label) { return in->getUUID(); } } for (const SlotPtr& slot : node->getSlots()) { if (slot->getLabel() == label) { return slot->getUUID(); } } throw std::logic_error(node->getUUID().getFullName() + " does not have an input with the label " + label); } template <class Container> UUID GraphFacadeImplementation::getOutputUUID(Container* node, int id) { return graph_->makeTypedUUID_forced(node->getUUID(), "out", id); } template <class Container> UUID GraphFacadeImplementation::getInputUUID(Container* node, int id) { return graph_->makeTypedUUID_forced(node->getUUID(), "in", id); } void GraphFacadeImplementation::nodeAddedHandler(graph::VertexPtr vertex) { NodeFacadeImplementationPtr facade = std::dynamic_pointer_cast<NodeFacadeImplementation>(vertex->getNodeFacade()); apex_assert_hard(facade); if (facade->isGraph()) { createSubgraphFacade(facade); } node_facades_[facade->getUUID()] = facade; if (!facade->getNodeHandle()->isIsolated()) { NodeRunnerPtr runner = facade->getNodeRunner(); apex_assert_hard(runner); generators_[facade->getUUID()] = runner; int thread_id = facade->getNodeState()->getThreadId(); if (thread_id >= 0) { executor_.addToGroup(runner.get(), thread_id); } else { executor_.add(runner.get()); } facade->getNode()->finishSetup(); } vertex->getNodeFacade()->notification.connect(notification); node_facade_added(facade); } void GraphFacadeImplementation::nodeRemovedHandler(graph::VertexPtr vertex) { NodeFacadeImplementationPtr facade = std::dynamic_pointer_cast<NodeFacadeImplementation>(vertex->getNodeFacade()); auto pos = generators_.find(facade->getUUID()); if (pos != generators_.end()) { TaskGeneratorPtr runner = pos->second; generators_.erase(facade->getUUID()); executor_.remove(runner.get()); } NodeFacadePtr facade_ptr = node_facades_[facade->getUUID()]; node_facade_removed(facade_ptr); node_facades_.erase(facade_ptr->getUUID()); if (facade->isGraph()) { auto pos = children_.find(facade->getUUID()); apex_assert_hard(pos != children_.end()); child_removed(pos->second); children_.erase(pos); } } void GraphFacadeImplementation::createSubgraphFacade(NodeFacadePtr nf) { NodeFacadeImplementationPtr local_facade = std::dynamic_pointer_cast<NodeFacadeImplementation>(nf); apex_assert_hard(local_facade); NodePtr node = local_facade->getNode(); apex_assert_hard(node); SubgraphNodePtr sub_graph = std::dynamic_pointer_cast<SubgraphNode>(node); apex_assert_hard(sub_graph); NodeHandle* subnh = graph_->findNodeHandle(local_facade->getUUID()); apex_assert_hard(subnh == local_facade->getNodeHandle().get()); GraphImplementationPtr graph_local = sub_graph->getLocalGraph(); GraphFacadeImplementationPtr sub_graph_facade = std::make_shared<GraphFacadeImplementation>(executor_, graph_local, sub_graph, local_facade, this); children_[local_facade->getUUID()] = sub_graph_facade; observe(sub_graph_facade->notification, notification); observe(sub_graph_facade->node_facade_added, child_node_facade_added); observe(sub_graph_facade->node_facade_removed, child_node_facade_removed); observe(sub_graph_facade->child_node_facade_added, child_node_facade_added); observe(sub_graph_facade->child_node_facade_removed, child_node_facade_removed); child_added(sub_graph_facade); } void GraphFacadeImplementation::clearBlock() { executor_.clear(); } void GraphFacadeImplementation::resetActivity() { bool pause = isPaused(); pauseRequest(true); graph_->resetActivity(); for (auto pair : children_) { GraphFacadePtr child = pair.second; child->resetActivity(); } if (!parent_) { graph_node_->activation(); } pauseRequest(pause); } bool GraphFacadeImplementation::isPaused() const { return executor_.isPaused(); } void GraphFacadeImplementation::pauseRequest(bool pause) { if (executor_.isPaused() == pause) { return; } executor_.setPause(pause); paused(pause); } std::string GraphFacadeImplementation::makeStatusString() const { return graph_node_->makeStatusString(); } std::vector<UUID> GraphFacadeImplementation::enumerateAllNodes() const { return graph_->getAllNodeUUIDs(); } std::vector<ConnectionDescription> GraphFacadeImplementation::enumerateAllConnections() const { std::vector<ConnectionDescription> result; auto connections = graph_->getConnections(); result.reserve(connections.size()); for (const ConnectionPtr& c : connections) { result.push_back(c->getDescription()); } return result; }
31.525862
199
0.728138
ICRA-2018
d7c5469fb3b0a151a1a37df3fd5ecfbd460ac47f
9,264
cpp
C++
Arduino/libraries/PMIC_SGM41512/src/SGM41512.cpp
rdpoor/tinyml_low_power
65fe34cc1f156e5bc9687cc8cc690ea71baa56de
[ "MIT" ]
null
null
null
Arduino/libraries/PMIC_SGM41512/src/SGM41512.cpp
rdpoor/tinyml_low_power
65fe34cc1f156e5bc9687cc8cc690ea71baa56de
[ "MIT" ]
null
null
null
Arduino/libraries/PMIC_SGM41512/src/SGM41512.cpp
rdpoor/tinyml_low_power
65fe34cc1f156e5bc9687cc8cc690ea71baa56de
[ "MIT" ]
null
null
null
/* * Copyright (c) 2021 Syntiant Corp. All rights reserved. * Contact at http://www.syntiant.com * * This software is available to you under a choice of one of two licenses. * You may choose to be licensed under the terms of the GNU General Public * License (GPL) Version 2, available from the file LICENSE in the main * directory of this source tree, or the OpenIB.org BSD license below. Any * code involving Linux software will require selection of the GNU General * Public License (GPL) Version 2. * * OPENIB.ORG BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "SGM41512.h" //Default PMIC (SGM41512) I2C address #define PMIC_ADDRESS 0x6B // Register address definitions (only the ones used here) #define PMIC_POWERON_CONFIG_REG 0x01 #define PMIC_CHARGE_VOLTAGE_CONTROL_REG 0x04 #define PMIC_CHARGE_TIMER_CONTROL_REG 0x05 #define PMIC_MISC_CONTROL_REG 0x07 #define PMIC_SYSTEM_STATUS_REG 0x08 #define PMIC_RESET_AND_VERSION_REG 0x0B PMICClass::PMICClass(TwoWire &wire) : _wire(&wire) { } /******************************************************************************* * Function Name : begin * Description : Initializes the I2C for the PMIC module * Input : NONE * Return : 0 on Error, 1 on Success *******************************************************************************/ bool PMICClass::begin() { _wire->begin(); #ifdef ARDUINO_ARCH_SAMD pinMode(PIN_USB_HOST_ENABLE - 3, OUTPUT); //digitalWrite(PIN_USB_HOST_ENABLE, LOW); digitalWrite(PIN_USB_HOST_ENABLE - 3, HIGH); #if defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) pinMode(PMIC_IRQ_PIN, INPUT_PULLUP); #endif #endif //check PMIC version --- ignoring the last two-bit field, DEV_REV[1:0] if ((readRegister(PMIC_RESET_AND_VERSION_REG) | 0x03) != 0x2F) { return 0; } else { return 1; } } /******************************************************************************* * Function Name : end * Description : Deinitializes the I2C for the PMIC module * Input : NONE * Return : NONE *******************************************************************************/ void PMICClass::end() { #ifdef ARDUINO_ARCH_SAMD //pinMode(PIN_USB_HOST_ENABLE, INPUT); pinMode(PIN_USB_HOST_ENABLE - 3, INPUT); #if defined(ARDUINO_SAMD_MKRGSM1400) || defined(ARDUINO_SAMD_MKRNB1500) pinMode(PMIC_IRQ_PIN, INPUT); #endif #endif _wire->end(); } /******************************************************************************* * Function Name : enableCharge * Description : Enables PMIC charge mode * Input : NONE * Return : 0 on Error, 1 on Success *******************************************************************************/ bool PMICClass::enableCharge() { #ifdef ARDUINO_ARCH_SAMD //digitalWrite(PIN_USB_HOST_ENABLE, LOW); digitalWrite(PIN_USB_HOST_ENABLE - 3, HIGH); #endif int DATA = readRegister(PMIC_POWERON_CONFIG_REG); if (DATA == -1) { return 0; } byte mask = DATA & 0xCF; // Enable PMIC battery charging mode if (!writeRegister(PMIC_POWERON_CONFIG_REG, mask | 0x10)) { return 0; } DATA = readRegister(PMIC_CHARGE_TIMER_CONTROL_REG); if (DATA == -1) { return 0; } mask = DATA & 0x7F; // Enable charge termination feature if (!writeRegister(PMIC_CHARGE_TIMER_CONTROL_REG, mask | 0x80)) { return 0; } DATA = readRegister(PMIC_CHARGE_VOLTAGE_CONTROL_REG); if (DATA == -1) { return 0; } // Enable Top-off timer if (!writeRegister(PMIC_CHARGE_VOLTAGE_CONTROL_REG, DATA | 0x03)) { return 0; } return enableBATFET(); } /******************************************************************************* * Function Name : enableBoostMode * Description : Enables PMIC boost mode, allow to generate 5V from battery * Input : NONE * Return : 0 on Error, 1 on Success *******************************************************************************/ bool PMICClass::enableBoostMode() { int DATA = readRegister(PMIC_POWERON_CONFIG_REG); if (DATA == -1) { return 0; } byte mask = DATA & 0xCF; // Enable PMIC boost mode if (!writeRegister(PMIC_POWERON_CONFIG_REG, mask | 0x20)) { return 0; } #ifdef ARDUINO_ARCH_SAMD //digitalWrite(PIN_USB_HOST_ENABLE, LOW); digitalWrite(PIN_USB_HOST_ENABLE - 3, HIGH); #endif // Disable charge termination feature DATA = readRegister(PMIC_CHARGE_TIMER_CONTROL_REG); if (DATA == -1) { return 0; } mask = DATA & 0x7F; // remove "enable termination" bit if (!writeRegister(PMIC_CHARGE_TIMER_CONTROL_REG, mask)) { return 0; } // wait for enable boost mode delay(500); return 1; } /******************************************************************************* * Function Name : enableBATFET * Description : turn on BATFET * Input : NONE * Return : 0 on Error, 1 on Success *******************************************************************************/ bool PMICClass::enableBATFET(void) { int DATA = readRegister(PMIC_MISC_CONTROL_REG); if (DATA == -1) { return 0; } return writeRegister(PMIC_MISC_CONTROL_REG, (DATA & 0b11011111)); } /******************************************************************************* * Function Name : chargeStatus * Description : Query the PMIC and returns the Charging status * Input : NONE * Return : -1 on Error, Charging status on Success *******************************************************************************/ int PMICClass::chargeStatus() { int DATA = readRegister(PMIC_SYSTEM_STATUS_REG); if (DATA == -1) { return DATA; } byte charge_staus = (DATA & 0x18)>>3; return charge_staus; } /******************************************************************************* * Function Name : getOperationMode * Description : Query the PMIC and returns the mode of operation * Input : NONE * Return : -1 on Error, 0 on Charge mode, 1 on Boost mode *******************************************************************************/ int PMICClass::getOperationMode() { int DATA = readRegister(PMIC_POWERON_CONFIG_REG); if (DATA == -1) { return DATA; } byte mode_staus = (DATA & 0x20)>>5; return mode_staus; } /******************************************************************************* * Function Name : disableWatchdog * Description : Disable Watchdog timer * Input : NONE * Return : 0 on Error, 1 on Success *******************************************************************************/ bool PMICClass::disableWatchdog(void) { int DATA = readRegister(PMIC_CHARGE_TIMER_CONTROL_REG); if (DATA == -1) { return 0; } return writeRegister(PMIC_CHARGE_TIMER_CONTROL_REG, (DATA & 0b11001111)); } /******************************************************************************* * Function Name : readRegister * Description : read the register with the given address in the PMIC * Input : register address * Return : 0 on Error, 1 on Success *******************************************************************************/ int PMICClass::readRegister(byte address) { _wire->beginTransmission(PMIC_ADDRESS); _wire->write(address); if (_wire->endTransmission(true) != 0) { return -1; } if (_wire->requestFrom(PMIC_ADDRESS, 1, true) != 1) { return -1; } return _wire->read(); } /******************************************************************************* * Function Name : writeRegister * Description : write a value in the register with the given address in the PMIC * Input : register address, value * Return : 0 on Error, 1 on Success *******************************************************************************/ int PMICClass::writeRegister(byte address, byte val) { _wire->beginTransmission(PMIC_ADDRESS); _wire->write(address); _wire->write(val); if (_wire->endTransmission(true) != 0) { return 0; } return 1; } PMICClass PMIC(Wire);
30.574257
85
0.554512
rdpoor
d7cac9e4a9cc3fd29c53b9ab50d1c8a9ef0aa9c5
658
hpp
C++
source/Senses/View/ResizeUITab.hpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
8
2015-01-23T05:41:46.000Z
2019-11-20T05:10:27.000Z
source/Senses/View/ResizeUITab.hpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
null
null
null
source/Senses/View/ResizeUITab.hpp
fstudio/Phoenix
28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d
[ "MIT" ]
4
2015-05-05T05:15:43.000Z
2020-03-07T11:10:56.000Z
/********************************************************************************************************* * UIWindow.cpp * Note: ResizeUITab.cpp * Date: @2015.04 * E-mail:<forcemz@outlook.com> * Copyright (C) 2015 The ForceStudio All Rights Reserved. **********************************************************************************************************/ #ifndef PHOENXI_RESIZEUITAB_HPP #define PHOENXI_RESIZEUITAB_HPP class ResizeUITab{ private: RECT m_place; public: ResizeUITab(); bool Create(); LRESULT Initialize(); LRESULT Resize(); LRESULT Move(); LRESULT Draw(); LRESULT Close(); LRESULT Click(); }; #endif
25.307692
107
0.465046
fstudio
d7d09a740cfbd23b9debf34ea601735536edaf16
805
cpp
C++
potato/spud/tests/test_delegate_ref.cpp
seanmiddleditch/grimm
9f47fc5d7aa0af19a3a7c82a38b7f7c59b83fbf5
[ "MIT" ]
38
2019-05-25T17:32:26.000Z
2022-02-27T22:25:05.000Z
potato/spud/tests/test_delegate_ref.cpp
seanmiddleditch/grimm
9f47fc5d7aa0af19a3a7c82a38b7f7c59b83fbf5
[ "MIT" ]
35
2019-05-26T17:52:39.000Z
2022-02-12T19:54:14.000Z
potato/spud/tests/test_delegate_ref.cpp
seanmiddleditch/grimm
9f47fc5d7aa0af19a3a7c82a38b7f7c59b83fbf5
[ "MIT" ]
2
2019-06-09T16:06:27.000Z
2019-08-16T14:17:20.000Z
#include "potato/spud/delegate_ref.h" #include <catch2/catch.hpp> TEST_CASE("potato.spud.delegate_ref", "[potato][spud]") { using namespace up; SECTION("lambda delegate_ref") { int (*f)(int) = [](int i) { return i * 2; }; delegate_ref d = f; CHECK(d(0) == 0); CHECK(d(-1) == -2); CHECK(d(10) == 20); } SECTION("delegate_ref reassignment") { int i1 = 2; auto f1 = [&i1](int i) { return i1 += i; }; static_assert(is_invocable_v<decltype(f1), int>); int i2 = 2; auto f2 = [&i2](int i) { return i2 *= i; }; delegate_ref<int(int)> d(f1); d(2); CHECK(i1 == 4); d = f2; d(4); CHECK(i2 == 8); } }
20.125
57
0.448447
seanmiddleditch
d7d1e3215854e380e81622caaeee52b61611a464
3,807
cpp
C++
project/OFEC_sc2/instance/problem/continuous/multi_modal/metrics_mmop.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/problem/continuous/multi_modal/metrics_mmop.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/problem/continuous/multi_modal/metrics_mmop.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "../../../../core/algorithm/solution.h" #include "../../../../core/problem/continuous/continuous.h" #include "metrics_mmop.h" #include <algorithm> namespace OFEC { void MetricsMMOP::updateCandidates(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates) const { updateOnlyByObj(sol, candidates); } size_t MetricsMMOP::numOptimaFound(const std::list<std::unique_ptr<SolBase>> &candidates) const { return numOptimaOnlyByObj(candidates); } void MetricsMMOP::updateOnlyByObj(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates) const { if (sol.objectiveDistance(m_optima.objective(0)) < m_objective_accuracy) { for (auto &c : candidates) { if (c->variableDistance(sol, m_id_pro) < m_variable_niche_radius) return; } candidates.emplace_back(new Solution<>(dynamic_cast<const Solution<>&>(sol))); } } void MetricsMMOP::updateByObjAndVar(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates) const { std::vector<bool> is_opt_fnd(m_optima.numberObjectives(), false); Real dis_obj, dis_var; for (auto &c : candidates) { for (size_t i = 0; i < m_optima.numberVariables(); i++) { if (is_opt_fnd[i]) continue; dis_obj = c->objectiveDistance(m_optima.objective(i)); dis_var = c->variableDistance(m_optima.variable(i), m_id_pro); if (dis_obj < m_objective_accuracy && dis_var < m_variable_niche_radius) is_opt_fnd[i] = true; } } for (size_t i = 0; i < m_optima.numberObjectives(); i++) { if (!is_opt_fnd[i]) { dis_obj = sol.objectiveDistance(m_optima.objective(i)); dis_var = sol.variableDistance(m_optima.variable(i), m_id_pro); if (dis_obj < m_objective_accuracy && dis_var < m_variable_niche_radius) { candidates.emplace_back(new Solution<>(dynamic_cast<const Solution<>&>(sol))); break; } } } } void MetricsMMOP::updateBestFixedNumSols(const SolBase &sol, std::list<std::unique_ptr<SolBase>> &candidates, size_t num_sols) const { bool flag_add = true; for (auto iter = candidates.begin(); iter != candidates.end();) { if (sol.variableDistance(**iter, m_id_pro) < m_variable_niche_radius) { if (sol.dominate(**iter, m_id_pro)) iter = candidates.erase(iter); else { flag_add = false; break; } } else iter++; } if (flag_add) { if (candidates.size() < num_sols) candidates.emplace_back(new Solution<>(dynamic_cast<const Solution<>&>(sol))); else { auto iter_worst = std::min_element( candidates.begin(), candidates.end(), [this](const std::unique_ptr<SolBase> &rhs1, const std::unique_ptr<SolBase> &rhs2) { return rhs1->dominate(*rhs2, this->m_id_pro); }); (*iter_worst).reset(new Solution<>(dynamic_cast<const Solution<>&>(sol))); } } } size_t MetricsMMOP::numOptimaOnlyByObj(const std::list<std::unique_ptr<SolBase>> &candidates) const { std::list<SolBase*> opts_fnd; for (auto &c : candidates) { if (c->objectiveDistance(m_optima.objective(0)) < m_objective_accuracy) { bool is_new_opt = true; for (auto of : opts_fnd) { if (of->variableDistance(*c, m_id_pro) < m_variable_niche_radius) { is_new_opt = false; break; } } if (is_new_opt) opts_fnd.push_back(c.get()); } } return opts_fnd.size(); } size_t MetricsMMOP::numOptimaByObjAndVar(const std::list<std::unique_ptr<SolBase>> &candidates) const { size_t count = 0; Real dis_obj, dis_var; for (size_t i = 0; i < m_optima.numberObjectives(); i++) { for (auto &c : candidates) { dis_obj = c->objectiveDistance(m_optima.objective(i)); dis_var = c->variableDistance(m_optima.variable(i), m_id_pro); if (dis_obj < m_objective_accuracy && dis_var < m_variable_niche_radius) { count++; break; } } } return count; } }
34.926606
139
0.679275
BaiChunhui-9803
d7d64647ebace47c95299ab67c845921d10ded46
681
cpp
C++
Cpp_primer_5th/code_part7/prog7_1.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part7/prog7_1.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part7/prog7_1.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; struct Sales_data{ string bookNo; double revenue = 0.0; int usold= 0; }; int main(){ Sales_data total; if(cin >> total.bookNo >> total.usold >> total.revenue){ Sales_data trans; while(cin >> trans.bookNo >> trans.usold >> trans.revenue){ if(total.bookNo == trans.bookNo){ total.usold += trans.usold; total.revenue += trans.revenue; } else{ cout << total.bookNo << " " << total.usold << " " << total.revenue << endl; total = trans; } } cout << total.bookNo << " " << total.usold << " " << total.revenue << endl; }d else{ cerr << "No data?!" << endl; return -1; } return 0; }
20.636364
79
0.582966
Links789
d7d8aa0ddd64e09f166a357010d294268b355fad
3,872
cpp
C++
src/Profiling.cpp
jrayzero/TylerDistHalide
bbe117161a7c5539a9b89b7f38aac91b99ae4be6
[ "MIT" ]
2
2020-09-24T17:03:37.000Z
2022-02-03T10:48:14.000Z
src/Profiling.cpp
jrayzero/TylerDistHalide
bbe117161a7c5539a9b89b7f38aac91b99ae4be6
[ "MIT" ]
8
2015-07-21T10:06:12.000Z
2015-08-03T19:09:52.000Z
src/Profiling.cpp
jrayzero/TylerDistHalide
bbe117161a7c5539a9b89b7f38aac91b99ae4be6
[ "MIT" ]
1
2020-10-01T17:27:17.000Z
2020-10-01T17:27:17.000Z
#include <algorithm> #include <map> #include <string> #include <limits> #include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: map<string, int> indices; // maps from func name -> index in buffer. vector<int> stack; // What produce nodes are we currently inside of. InjectProfiling() { indices["overhead"] = 0; stack.push_back(0); } private: using IRMutator::visit; void visit(const ProducerConsumer *op) { int idx; map<string, int>::iterator iter = indices.find(op->name); if (iter == indices.end()) { idx = (int)indices.size(); indices[op->name] = idx; } else { idx = iter->second; } stack.push_back(idx); Stmt produce = mutate(op->produce); Stmt update = op->update.defined() ? mutate(op->update) : Stmt(); stack.pop_back(); Stmt consume = mutate(op->consume); Expr profiler_token = Variable::make(Int(32), "profiler_token"); Expr profiler_state = Variable::make(Handle(), "profiler_state"); // This call gets inlined and becomes a single store instruction. Expr set_task = Call::make(Int(32), "halide_profiler_set_current_func", {profiler_state, profiler_token, idx}, Call::Extern); // At the beginning of the consume step, set the current task // back to the outer one. Expr set_outer_task = Call::make(Int(32), "halide_profiler_set_current_func", {profiler_state, profiler_token, stack.back()}, Call::Extern); produce = Block::make(Evaluate::make(set_task), produce); consume = Block::make(Evaluate::make(set_outer_task), consume); stmt = ProducerConsumer::make(op->name, produce, update, consume); } void visit(const For *op) { // We profile by storing a token to global memory, so don't enter GPU loops if (op->device_api == DeviceAPI::Parent || op->device_api == DeviceAPI::Host) { IRMutator::visit(op); } else { stmt = op; } } }; Stmt inject_profiling(Stmt s, string pipeline_name) { InjectProfiling profiling; s = profiling.mutate(s); int num_funcs = (int)(profiling.indices.size()); Expr func_names_buf = Load::make(Handle(), "profiling_func_names", 0, Buffer(), Parameter()); func_names_buf = Call::make(Handle(), Call::address_of, {func_names_buf}, Call::Intrinsic); Expr start_profiler = Call::make(Int(32), "halide_profiler_pipeline_start", {pipeline_name, num_funcs, func_names_buf}, Call::Extern); Expr get_state = Call::make(Handle(), "halide_profiler_get_state", {}, Call::Extern); Expr profiler_token = Variable::make(Int(32), "profiler_token"); Expr stop_profiler = Call::make(Int(32), Call::register_destructor, {Expr("halide_profiler_pipeline_end"), get_state}, Call::Intrinsic); s = LetStmt::make("profiler_state", get_state, s); // If there was a problem starting the profiler, it will call an // appropriate halide error function and then return the // (negative) error code as the token. s = Block::make(AssertStmt::make(profiler_token >= 0, profiler_token), s); s = LetStmt::make("profiler_token", start_profiler, s); for (std::pair<string, int> p : profiling.indices) { s = Block::make(Store::make("profiling_func_names", p.first, p.second), s); } s = Allocate::make("profiling_func_names", Handle(), {num_funcs}, const_true(), s); s = Block::make(Evaluate::make(stop_profiler), s); return s; } } }
33.37931
104
0.621126
jrayzero
d7d8e6203585b78e5a2e850c83112151697b7868
495
cpp
C++
WaveformGenerator/waveformgenerator.cpp
VioletGiraffe/AudioGenerator
bea5118a55ffd3f246f87aea7e22880741d4e669
[ "Apache-2.0" ]
null
null
null
WaveformGenerator/waveformgenerator.cpp
VioletGiraffe/AudioGenerator
bea5118a55ffd3f246f87aea7e22880741d4e669
[ "Apache-2.0" ]
null
null
null
WaveformGenerator/waveformgenerator.cpp
VioletGiraffe/AudioGenerator
bea5118a55ffd3f246f87aea7e22880741d4e669
[ "Apache-2.0" ]
null
null
null
#include "waveformgenerator.h" WaveformGenerator::~WaveformGenerator() { } float WaveformGenerator::extraParameter() const { return _extraParameter; } bool WaveformGenerator::hasExtraParameter() const { return false; } const WaveformGenerator::ExtraParameterProperties WaveformGenerator::extraParameterProperties() { return ExtraParameterProperties{std::string(), 0.0f, 0.0f, 0.0f}; } void WaveformGenerator::setExtraParameter(float p) { _extraParameter = p; }
19.038462
96
0.747475
VioletGiraffe
d7df21b6414e312c796e0fedab119443608b9032
3,084
cpp
C++
Nesis/Instruments/src/XMLGaugeRoundAltitude.cpp
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
3
2015-11-08T07:17:46.000Z
2019-04-05T17:08:05.000Z
Nesis/Instruments/src/XMLGaugeRoundAltitude.cpp
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
null
null
null
Nesis/Instruments/src/XMLGaugeRoundAltitude.cpp
jpoirier/x-gauges
8261b19a9678ad27db44eb8c354f5e66bd061693
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * * * Copyright (C) 2007 by Kanardia d.o.o. [see www.kanardia.eu] * * Writen by: * * Ales Krajnc [ales.krajnc@kanardia.eu] * * * * Status: Open Source * * * * License: GPL - GNU General Public License * * See 'COPYING.html' for more details about the license. * * * ***************************************************************************/ #include <QDebug> #include "Unit/Manager.h" #include "XMLTags.h" #include "XMLGaugeRoundAltitude.h" namespace instrument { // ------------------------------------------------------------------------- XMLGaugeRoundAltitude::XMLGaugeRoundAltitude( const QDomElement& e, QWidget *pParent ) : XMLGaugeRound(e, pParent) { Q_ASSERT(m_vpScale.count() == 1); Q_ASSERT(m_vpScale[0]->GetParameter()->GetName()==TAG_ALTITUDE); unit::Manager* pM = unit::Manager::GetInstance(); m_vpScale[0]->EnableBoundScale(false); m_bThreeNeedles = false; bool bThird = (e.attribute(TAG_THIRD_NEEDLE)==TAG_YES); if(bThird) { int iUserKey = m_vpScale[0]->GetParameter()->GetUnitKeyUser(); if(iUserKey >= 0) { if(pM->GetUnit(iUserKey)->GetSignature()=="feet") m_bThreeNeedles = true; } } // At this time we know if we have QNH frame. // Set number of decimals ... for(int i=0; i<m_vpFrame.count(); i++) { if(m_vpFrame[i]->GetParameter()->GetName()==TAG_QNH) { // Check units int iUserKey = m_vpFrame[i]->GetParameter()->GetUnitKeyUser(); if(iUserKey >= 0) { if(pM->GetUnit(iUserKey)->GetSignature()=="inHg") { m_vpFrame[i]->SetDecimals(1); } } break; } } m_vpScale[0]->GetNeedle().SetType(Needle::tPointed); m_needle3.SetType(Needle::tFatShort); m_needle4.SetType(Needle::t10000); } // ------------------------------------------------------------------------- void XMLGaugeRoundAltitude::DrawForeground(QPainter& P) { XMLGaugeRound::DrawForeground(P); float fU = m_vpScale[0]->GetParameter()->GetValueUser(); m_needle3.Draw(P, 90.0f - 36*fU/1000); if(m_bThreeNeedles) m_needle4.Draw(P, 90.0f - 36*fU/10000); } // ------------------------------------------------------------------------- void XMLGaugeRoundAltitude::ResizeBackground() { XMLGaugeRound::ResizeBackground(); const int iW = width(); const int iOff = 7*iW/100; m_vpScale[0]->GetNeedle().SetSize(QSize(40*iW/100, 5), iOff); m_needle3.SetSize(QSize(28*iW/100, 5*iW/100), iOff); m_needle4.SetSize(QSize(46*iW/100, 7*iW/100), iOff); } // ------------------------------------------------------------------------- } // namespace
31.793814
77
0.467899
jpoirier
d7e4286d7ff4c1c5b13e9232815f4f983858b873
23,423
cpp
C++
LithiumGD/Cheats/Creator.cpp
ALEHACKsp/LithiumGD
7f1e2c7da98e879830fbf9657c2618625c6daa5b
[ "MIT" ]
null
null
null
LithiumGD/Cheats/Creator.cpp
ALEHACKsp/LithiumGD
7f1e2c7da98e879830fbf9657c2618625c6daa5b
[ "MIT" ]
null
null
null
LithiumGD/Cheats/Creator.cpp
ALEHACKsp/LithiumGD
7f1e2c7da98e879830fbf9657c2618625c6daa5b
[ "MIT" ]
1
2021-09-19T17:35:28.000Z
2021-09-19T17:35:28.000Z
#include <Windows.h> #include "Cheats.h" #include "../Game/Game.h" #include "../Game/Offsets.h" void cCheats::CopyHack() { static const char Patch1[] = { 0x90, 0x90 }; static const char Patch2[] = { 0x8B, 0xCA, 0x90 }; static const char Patch3[] = { 0xB0, 0x01, 0x90 }; static const char OriginalAddress1[] = { 0x75, 0x0E }; static const char OriginalAddress2[] = { 0x0F, 0x44, 0xCA }; static const char OriginalAddress3[] = { 0x0F, 0x95, 0xC0 }; if (Configuration.CopyHack) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address2), &Patch2, sizeof(Patch2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address3), &Patch3, sizeof(Patch3), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.CopyHack.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0); } } void cCheats::NoCopyMark() { static const char Patch1[] = { 0x2B, 0x87, 0xCC, 0x02, 0x00, 0x00 }; static const char Patch2[] = { 0xEB, 0x26 }; static const char OriginalAddress1[] = { 0x2B, 0x87, 0xD0, 0x02, 0x00, 0x00 }; static const char OriginalAddress2[] = { 0x74, 0x26 }; if (Configuration.NoCopyMark) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address2), &Patch2, sizeof(Patch2), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoCopyMark.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); } } void cCheats::UnlimitedObjects() { static const char Patch[] = { 0xFF, 0xFF, 0xFF, 0x7F }; static const char OriginalAddresses[] = { 0x80, 0x38, 0x01, 0x00 }; if (Configuration.UnlimitedObjects) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address1), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address2), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address3), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address4), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address5), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address6), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address7), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address1), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address2), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address3), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address4), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address5), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address6), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedObjects.Address7), &OriginalAddresses, sizeof(OriginalAddresses), 0); } } void cCheats::UnlimitedCustomObjects() { static const char Patch1[] = { 0xEB }; static const char Patch2[] = { 0xEB }; static const char Patch3[] = { 0x90, 0x90 }; static const char OriginalAddress1[] = { 0x72 }; static const char OriginalAddress2[] = { 0x76 }; static const char OriginalAddress3[] = { 0x77, 0x3A }; if (Configuration.UnlimitedCustomObjects) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address2), &Patch2, sizeof(Patch2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address3), &Patch3, sizeof(Patch3), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedCustomObjects.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0); } } void cCheats::UnlimitedZoom() { static const char Patch[] = { 0x90, 0x90, 0x90 }; static const char OriginalAddress1[] = { 0x0F, 0x2F, 0xC8 }; static const char OriginalAddress2[] = { 0x0F, 0x28, 0xC8 }; static const char OriginalAddress3[] = { 0x0F, 0x2F, 0xC8 }; static const char OriginalAddress4[] = { 0x0F, 0x28, 0xC8 }; if (Configuration.UnlimitedZoom) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address1), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address2), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address3), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address4), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZoom.Address4), &OriginalAddress4, sizeof(OriginalAddress4), 0); } } void cCheats::UnlimitedToolboxButtons() { static const char Patch1[] = { 0x83, 0xF9, 0x01 }; static const char Patch2[] = { 0xB8, 0x01, 0x00, 0x00, 0x00 }; static const char Patch3[] = { 0x83, 0xF9, 0x7F }; static const char Patch4[] = { 0xB9, 0x7F, 0x00, 0x00, 0x00 }; static const char OriginalAddress1[] = { 0x83, 0xF9, 0x06 }; static const char OriginalAddress2[] = { 0xB8, 0x06, 0x00, 0x00, 0x00 }; static const char OriginalAddress3[] = { 0x83, 0xF9, 0x0C }; static const char OriginalAddress4[] = { 0xB9, 0x0C, 0x00, 0x00, 0x00 }; static const char OriginalAddress5[] = { 0x83, 0xF9, 0x02 }; static const char OriginalAddress6[] = { 0xB8, 0x02, 0x00, 0x00, 0x00 }; static const char OriginalAddress7[] = { 0x83, 0xF9, 0x03 }; static const char OriginalAddress8[] = { 0xB9, 0x03, 0x00, 0x00, 0x00 }; if (Configuration.UnlimitedToolboxButtons) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address2), &Patch2, sizeof(Patch2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address3), &Patch3, sizeof(Patch3), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address4), &Patch4, sizeof(Patch4), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address5), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address6), &Patch2, sizeof(Patch2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address7), &Patch3, sizeof(Patch3), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address8), &Patch4, sizeof(Patch4), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address4), &OriginalAddress4, sizeof(OriginalAddress4), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address5), &OriginalAddress5, sizeof(OriginalAddress5), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address6), &OriginalAddress6, sizeof(OriginalAddress6), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address7), &OriginalAddress7, sizeof(OriginalAddress7), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedToolboxButtons.Address8), &OriginalAddress8, sizeof(OriginalAddress8), 0); } } void cCheats::VerifyHack() { static const char Patch[] = { 0xEB }; static const char OriginalAddress1[] = { 0x74 }; if (Configuration.VerifyHack) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.VerifyHack.Address1), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.VerifyHack.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); } } void cCheats::HiddenSongs() { static const char Patch1[] = { 0x90, 0x90 }; static const char Patch2[] = { 0x90, 0x90, 0x90 }; static const char OriginalAddress1[] = { 0x74, 0x2F }; static const char OriginalAddress2[] = { 0x0F, 0x4F, 0xC6 }; if (Configuration.HiddenSongs) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address2), &Patch2, sizeof(Patch2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address3), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address4), &Patch2, sizeof(Patch2), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address3), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.HiddenSongs.Address4), &OriginalAddress2, sizeof(OriginalAddress2), 0); } } void cCheats::EditorLength() { static const char Patch1[] = { 0x00, 0x60, 0xEA, 0x4B }; static const char Patch2[] = { 0x0F, 0x60, 0xEA, 0x4B }; static const char OriginalAddress1[] = { 0x00, 0x60, 0x6A, 0x48 }; static const char OriginalAddress2[] = { 0x80, 0x67, 0x6A, 0x48 }; if (Configuration.EditorLength) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address2), &Patch2, sizeof(Patch2), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.EditorLength.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); } } void cCheats::PlaceOver() { static const char Patch1[] = { 0x8B, 0xC1, 0x90 }; static const char Patch2[] = { 0xE9, 0x23, 0x02, 0x00, 0x00, 0x90 }; static const char OriginalAddress1[] = { 0x0F, 0x48, 0xC1 }; static const char OriginalAddress2[] = { 0x0F, 0x8F, 0x22, 0x02, 0x00, 0x00 }; if (Configuration.PlaceOver) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address1), &Patch1, sizeof(Patch1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address2), &Patch2, sizeof(Patch2), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.PlaceOver.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); } } void cCheats::AntiTestmode() { static const char Patch[] = { 0xE9, 0xB7, 0x00, 0x00, 0x00, 0x90 }; static const char OriginalAddress1[] = { 0x0F, 0x84, 0xB6, 0x00, 0x00, 0x00 }; if (Configuration.AntiTestmode) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AntiTestmode.Address1), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AntiTestmode.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); } } void cCheats::RotationHack() { static const char Patch[] = { 0xB8, 0x01, 0x00, 0x00, 0x00, 0x90 }; static const char OriginalAddress1[] = { 0x8B, 0x80, 0x00, 0x03, 0x00, 0x00 }; static const char OriginalAddress2[] = { 0x8B, 0x80, 0x00, 0x03, 0x00, 0x00 }; static const char OriginalAddress3[] = { 0x8B, 0x80, 0x00, 0x03, 0x00, 0x00 }; static const char OriginalAddress4[] = { 0x8B, 0x87, 0x00, 0x03, 0x00, 0x00 }; static const char OriginalAddress5[] = { 0x8B, 0x86, 0x00, 0x03, 0x00, 0x00 }; static const char OriginalAddress6[] = { 0x8B, 0x83, 0x00, 0x03, 0x00, 0x00 }; if (Configuration.RotationHack) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address1), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address2), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address3), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address4), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address5), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address6), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address3), &OriginalAddress3, sizeof(OriginalAddress3), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address4), &OriginalAddress4, sizeof(OriginalAddress4), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address5), &OriginalAddress5, sizeof(OriginalAddress5), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.RotationHack.Address6), &OriginalAddress6, sizeof(OriginalAddress6), 0); } } void cCheats::FreeScroll() { static const char Patch[] = { 0xEB }; static const char OriginalAddresses[] = { 0x77 }; if (Configuration.FreeScroll) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address1), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address2), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address3), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address4), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address1), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address2), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address3), &OriginalAddresses, sizeof(OriginalAddresses), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.FreeScroll.Address4), &OriginalAddresses, sizeof(OriginalAddresses), 0); } } void cCheats::NoEditorUI() { static const char Patch[] = { 0xB3, 0x00, 0x90 }; static const char OriginalAddress1[] = { 0x0F, 0x44, 0xD9 }; if (Configuration.NoEditorUI) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoEditorUI.Address1), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoEditorUI.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); } } void cCheats::UnlimitedZOrder() { static const char Patch[] = { 0x90, 0x90, 0x90 }; static const char OriginalAddress1[] = { 0x0F, 0x4C, 0xC1 }; static const char OriginalAddress2[] = { 0x0F, 0x4F, 0xC1 }; if (Configuration.UnlimitedZOrder) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address1), &Patch, sizeof(Patch), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address2), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.UnlimitedZOrder.Address2), &OriginalAddress2, sizeof(OriginalAddress2), 0); } } void cCheats::AbsoluteScaling() { static const char Patch[] = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 }; static const char OriginalAddress1[] = { 0x56, 0xE8, 0xB1, 0xEA, 0xFF, 0xFF }; if (Configuration.AbsoluteScaling) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsoluteScaling.Address1), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsoluteScaling.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); } } void cCheats::AbsolutePosition() { static const char Patch[] = { 0x90, 0x8B, 0xCE, 0x90, 0x90, 0x90 }; static const char OriginalAddress1[] = { 0x51, 0x8B, 0xCE, 0xFF, 0x50, 0x5C }; if (Configuration.AbsolutePosition) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsolutePosition.Address1), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.AbsolutePosition.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); } } void cCheats::NoScaleSnap() { static const char Patch[] = { 0xEB }; static const char OriginalAddress1[] = { 0x76 }; if (Configuration.NoScaleSnap) { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoScaleSnap.Address1), &Patch, sizeof(Patch), 0); } else { WriteProcessMemory(Game->GetProcessHandle(), (LPVOID)(Game->GetGeometryDashModule() + Offsets.NoScaleSnap.Address1), &OriginalAddress1, sizeof(OriginalAddress1), 0); } }
68.090116
180
0.745165
ALEHACKsp
d7e6e7c3da957da091e1315a75b44d07aab9edb2
190
cpp
C++
myblog/Cplusplus/004_pointer/demo3.cpp
WangBaobaoLOVE/WangBaobaoLOVE.github.io
e8e53475874193a929bbda247dd6a77da8950856
[ "CC-BY-3.0" ]
null
null
null
myblog/Cplusplus/004_pointer/demo3.cpp
WangBaobaoLOVE/WangBaobaoLOVE.github.io
e8e53475874193a929bbda247dd6a77da8950856
[ "CC-BY-3.0" ]
null
null
null
myblog/Cplusplus/004_pointer/demo3.cpp
WangBaobaoLOVE/WangBaobaoLOVE.github.io
e8e53475874193a929bbda247dd6a77da8950856
[ "CC-BY-3.0" ]
null
null
null
#include <iostream> using namespace std; int main () { int *ptr = NULL; cout << "ptr 的值是 " << ptr ; if(ptr) cout << false; if(!ptr) cout << true; return 0; }
11.176471
30
0.505263
WangBaobaoLOVE
d7e97b217df8db666c383e0f903c2082b90a17bc
1,063
cpp
C++
src/test/currenttime/main.cpp
xsjqqq123/treefrog-framework
da7cc2c4b277e4858ee7a6e5e7be7ce707642e00
[ "BSD-3-Clause" ]
1
2019-01-08T12:37:11.000Z
2019-01-08T12:37:11.000Z
src/test/currenttime/main.cpp
dragondjf/treefrog-framework
b85df01fffab5a9bab94679376ec057ebc2293f5
[ "BSD-3-Clause" ]
null
null
null
src/test/currenttime/main.cpp
dragondjf/treefrog-framework
b85df01fffab5a9bab94679376ec057ebc2293f5
[ "BSD-3-Clause" ]
2
2018-09-14T12:35:36.000Z
2020-05-09T16:52:20.000Z
#include <QTest> #include <QtCore> #include <tglobal.h> class TestDateTime : public QObject { Q_OBJECT private slots: void compare(); void benchQtCurrentDateTime(); void benchTfCurrentDateTime(); }; void TestDateTime::compare() { for (int i = 0; i < 3; ++i) { QDateTime qt = QDateTime::currentDateTime(); QDateTime tf = Tf::currentDateTimeSec(); QCOMPARE(qt.date().year(), tf.date().year()); QCOMPARE(qt.date().month(), tf.date().month()); QCOMPARE(qt.date().day(), tf.date().day()); QCOMPARE(qt.time().hour(), tf.time().hour()); QCOMPARE(qt.time().minute(), tf.time().minute()); QCOMPARE(qt.time().second(), tf.time().second()); Tf::msleep(1500); } } void TestDateTime::benchQtCurrentDateTime() { QBENCHMARK { QDateTime dt = QDateTime::currentDateTime(); } } void TestDateTime::benchTfCurrentDateTime() { QBENCHMARK { QDateTime dt = Tf::currentDateTimeSec(); } } QTEST_APPLESS_MAIN(TestDateTime) #include "main.moc"
21.26
57
0.608655
xsjqqq123
d7ebe3bb2f48c3bcca53fa9a86d38d65abbf85c6
2,011
hpp
C++
modules/memory/include/shard/memory/allocators/heap_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/memory/include/shard/memory/allocators/heap_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/memory/include/shard/memory/allocators/heap_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Miklos Molnar. All rights reserved. #ifndef SHARD_MEMORY_HEAP_ALLOCATOR_HPP #define SHARD_MEMORY_HEAP_ALLOCATOR_HPP #include "shard/memory/allocator.hpp" #include "shard/memory/utils.hpp" #include <cstdio> #include <cstdlib> #include <cstring> #include <limits> namespace shard { namespace memory { class heap_allocator : public allocator { public: heap_allocator() : allocator(0) {} void* allocate(std::size_t size, std::size_t align) override { assert(size != 0); auto total_size = size + header_size; auto ptr = std::malloc(total_size); // check if allocation was successful if (!ptr) { return nullptr; } // clear the bytes in the allocated memory block std::memset(ptr, '\0', total_size); // padding includes the size of the allocation header, hence it is // subtracted from the aligned address auto header = reinterpret_cast<allocation_header*>(ptr); header->size = total_size; auto aligned_address = add(ptr, header_size); // check that the alignments are ok (should always be the case) assert(is_aligned(header)); assert(is_aligned(aligned_address, align)); m_used_memory += total_size; ++m_allocation_count; return aligned_address; } void deallocate(void* ptr) override { assert(ptr); // get the header at the start of the allocated memory auto header = reinterpret_cast<allocation_header*>(sub(ptr, header_size)); m_used_memory -= header->size; --m_allocation_count; // return the memory std::free(header); } private: struct allocation_header { std::size_t size; }; private: static constexpr auto header_size = sizeof(allocation_header); }; } // namespace memory // bring symbols into parent namespace using memory::heap_allocator; } // namespace shard #endif // SHARD_MEMORY_HEAP_ALLOCATOR_HPP
24.228916
82
0.660368
ikimol
d7ef285c805d115f3739bf9c295f6c1f37a00f1e
954
cpp
C++
src/binary/socket-server/test/MainTest.cpp
heaven-chp/base-server-cpp
87213259c61c93a791d087f4b284f79f0f05574c
[ "Apache-2.0" ]
null
null
null
src/binary/socket-server/test/MainTest.cpp
heaven-chp/base-server-cpp
87213259c61c93a791d087f4b284f79f0f05574c
[ "Apache-2.0" ]
1
2021-12-19T13:36:19.000Z
2021-12-19T14:07:14.000Z
src/binary/socket-server/test/MainTest.cpp
heaven-chp/base-server-cpp
87213259c61c93a791d087f4b284f79f0f05574c
[ "Apache-2.0" ]
null
null
null
#include "test.h" #include "../Main.h" #include "gtest/gtest.h" #include "Singleton.h" #include "EnvironmentVariable.h" static void test(int iArgc, char *pcArgv[]) { const int iPid = fork(); ASSERT_NE(iPid, -1); extern int optind; optind = 1; if(iPid == 0) { EXPECT_TRUE(Main().Run(iArgc, pcArgv)); exit(testing::Test::HasFailure()); } this_thread::sleep_for(chrono::seconds(2)); EXPECT_FALSE(Main().Run(iArgc, pcArgv)); EXPECT_STREQ(send_command("stop", true).c_str(), "200 ok\r\n"); this_thread::sleep_for(chrono::seconds(2)); } TEST(MainTest, Run) { EXPECT_FALSE(Main().Run(0, nullptr)); } TEST(MainTest, StandAlone) { int iArgc = 4; char *pcArgv[] = {(char *)"./MainTest", (char *)"-c", (char *)GstrConfigPath.c_str(), (char *)"-s"}; test(iArgc, pcArgv); } TEST(MainTest, NonStandAlone) { int iArgc = 3; char *pcArgv[] = {(char *)"./MainTest", (char *)"-c", (char *)GstrConfigPath.c_str()}; test(iArgc, pcArgv); }
18.346154
101
0.644654
heaven-chp
d7f002903117701f16c8e4bd4c26b09523c853a8
1,882
cpp
C++
src/views/oscilloscope/LCurve.cpp
lotusczp/Lobster
ceb5ec720fdbbd5eddba5eeccc2f875a62d4332e
[ "Apache-2.0", "MIT" ]
6
2021-01-30T00:06:22.000Z
2022-02-16T08:20:09.000Z
src/views/oscilloscope/LCurve.cpp
lotusczp/Lobster
ceb5ec720fdbbd5eddba5eeccc2f875a62d4332e
[ "Apache-2.0", "MIT" ]
null
null
null
src/views/oscilloscope/LCurve.cpp
lotusczp/Lobster
ceb5ec720fdbbd5eddba5eeccc2f875a62d4332e
[ "Apache-2.0", "MIT" ]
1
2021-08-11T05:19:11.000Z
2021-08-11T05:19:11.000Z
#include "LCurve.h" LCurve::LCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) { m_pLine = new QCPGraph(keyAxis, valueAxis); connect(m_pLine, SIGNAL(selectionChanged(bool)), this, SLOT(receiveCurveSelected(bool))); } LCurve::~LCurve() { //! \note No need to delete m_pLine, its ownership belongs to QCustomPlot instance } void LCurve::setName(const QString &a_rName) { m_pLine->setName(a_rName); } QString LCurve::getName() const { return m_pLine->name(); } void LCurve::addPoint(const QPointF &a_rPoint) { m_pLine->addData(a_rPoint.x(), a_rPoint.y()); } void LCurve::clear() { m_pLine->setData(QVector<double>(), QVector<double>()); } void LCurve::setColor(const QColor& a_rColor) { QPen pen = m_pLine->pen(); pen.setColor(a_rColor); m_pLine->setPen(pen); #if 0 pen = m_pLine->keyAxis()->basePen(); pen.setColor(a_rColor); m_pLine->valueAxis()->setBasePen(pen); pen = m_pLine->keyAxis()->tickPen(); pen.setColor(a_rColor); m_pLine->valueAxis()->setTickPen(pen); pen = m_pLine->keyAxis()->subTickPen(); pen.setColor(a_rColor); m_pLine->valueAxis()->setSubTickPen(pen); #endif } void LCurve::setPenStyle(const Qt::PenStyle &a_rPenStyle) { QPen pen = m_pLine->pen(); if(pen.style() != a_rPenStyle) { pen.setStyle(a_rPenStyle); m_pLine->setPen(pen); } } void LCurve::setSelected(bool a_bSelected) { if(a_bSelected) { QCPDataRange range; // Select the last 2 points if(m_pLine->data()->size() >= 2) { range.setEnd(m_pLine->data()->size()-1); range.setBegin(m_pLine->data()->size()-2); } m_pLine->setSelection(QCPDataSelection(range)); } else { m_pLine->setSelection(QCPDataSelection()); } } void LCurve::receiveCurveSelected(bool a_bSelected) { emit sendCurveSelected(a_bSelected); }
23.234568
93
0.648778
lotusczp
d7f1175d285cbcdd2f16afacb3d11608ff254ee0
784
cpp
C++
Codeforces/711A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/711A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/711A.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; string s[1010][2]; int n; bool flag = false; int main(){ cin >> n; for ( int i = 0 ; i < n ; i++){ string x ; cin >> x; string s1 =""; s1 += x[0]; s1 += x[1]; s[i][0] = s1; s1 = ""; s1 += x[3];s1+=x[4]; s[i][1] = s1; } for ( int i = 0 ; i < n ; i++){ if ( s[i][0] == "OO"){ s[i][0] = "++"; flag = true; break; } else if ( s[i][1] == "OO"){ s[i][1] ="++"; flag = true; break; } } if (!flag) return cout <<"NO\n" , 0; cout << "YES\n"; for ( int i = 0 ; i < n ; i++) cout << s[i][0] << '|' << s[i][1] << '\n'; return 0; }
21.189189
50
0.317602
Alipashaimani
d7f1dee1657f8b89b7415600ec6bdde58e6b9d3e
1,285
cpp
C++
backup/2/codewars/c++/spanish-conjugator.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/codewars/c++/spanish-conjugator.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/codewars/c++/spanish-conjugator.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/codewars/spanish-conjugator.html . using namespace std; using V = std::vector<std::string>; using R = std::unordered_map<std::string, V>; R conjugate(const std::string &verb) { const static R suffix = {{"ar", {"o", "as", "a", "amos", "áis", "an"}}, {"er", {"o", "es", "e", "emos", "éis", "en"}}, {"ir", {"o", "es", "e", "imos", "ís", "en"}}}; int S = verb.size() >= 2 ? verb.size() - 2 : 0; std::string base = verb.substr(0, S), infinitiveSuffix = verb.substr(S); auto it = suffix.find(infinitiveSuffix); R r; if (it != suffix.end()) { for (const auto &i : it->second) { r[verb].push_back(base + i); } } return r; }
42.833333
345
0.607004
yangyanzhan
d7f2c24c55d79b5d81a31bfcf47e661548680f1b
986
hpp
C++
osx-main/src/key_window.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
osx-main/src/key_window.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
osx-main/src/key_window.hpp
m4c0/m4c0-stl
5e47439528faee466270706534143c87b4af8cbb
[ "MIT" ]
null
null
null
#pragma once #include "m4c0/objc/geometry.hpp" #include "m4c0/objc/ns_window.hpp" #include "metal_view.hpp" namespace m4c0::osx::details { class window : public objc::ns_window { view m_view {}; public: explicit window(const char * title) : ns_window() { using namespace m4c0::objc; constexpr const auto window_width = 800; constexpr const auto window_height = 600; set_content_view(m_view); set_accepts_mouse_moved_events(true); set_title(title); set_style_mask( ns_window_style_mask::titled | ns_window_style_mask::closable | ns_window_style_mask::miniaturizable | ns_window_style_mask::resizable); set_collection_behavior(ns_window_collection_behavior::full_screen_primary); set_frame(cg_rect { {}, { window_width, window_height } }, true); center(); make_key_and_order_front(); } [[nodiscard]] constexpr const auto * content_view() { return &m_view; } }; }
27.388889
110
0.685598
m4c0
d7f2ede87d36e0c112ec2812f082072eb07dde89
12,511
cpp
C++
test/catch/scheduler-test.cpp
malachi-iot/embr-netbuf
501c0ceb251f880d85e112d6eb4e20738791085a
[ "MIT" ]
1
2019-11-17T11:13:05.000Z
2019-11-17T11:13:05.000Z
test/catch/scheduler-test.cpp
malachi-iot/embr
9790f4745dd9ac4a3e927a5167cc49f8947acd92
[ "MIT" ]
null
null
null
test/catch/scheduler-test.cpp
malachi-iot/embr
9790f4745dd9ac4a3e927a5167cc49f8947acd92
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <bitset> #include <embr/scheduler.h> // Not available because we test against C++11 //using namespace std::literals::chrono_literals; struct Item { int event_due; int* counter; }; struct ItemTraits { typedef Item value_type; typedef int time_point; static time_point get_time_point(const Item& item) { return item.event_due; } static bool process(Item& item, time_point) { if(item.counter != nullptr) ++(*item.counter); return false; } }; struct Item2Traits { typedef unsigned time_point; // NOTE: It's preferred to keep app state such as counter off in a pointed to struct // somewhere, since value_type here is copied around a lot during heap sorts. That said, // it's not any kind of specific violation to keep app data in here struct value_type { int counter = 0; time_point wakeup; // DEBT: needed because vector doesn't currently know how to do unassigned by itself // that said, it is partially spec behavior of vector: // https://stackoverflow.com/questions/29920394/vector-of-class-without-default-constructor // however ours deviates because we out of necessity pre allocate value_type() = default; value_type(time_point wakeup) : wakeup{wakeup} {} value_type(const value_type&) = default; /* although enabling all the following works, it hits me we prefer to lean heavily towards * copy-only because move operations imply greater short term overhead and we want this struct * as lightweight as possible value_type(value_type&&) = default; value_type& operator=(const value_type&) = default; value_type& operator=(value_type&&) = default; */ }; static time_point get_time_point(const value_type& v) { return v.wakeup; } static bool process(value_type& v, time_point) { v.wakeup += 10; ++v.counter; return true; } }; struct Item3Traits { typedef estd::chrono::steady_clock::time_point time_point; struct control_structure { typedef Item3Traits::time_point time_point; time_point t; virtual bool process(time_point current_time) = 0; }; typedef control_structure* value_type; static time_point get_time_point(value_type v) { return v->t; } static bool process(value_type v, time_point t) { return v->process(t); } }; struct Item3ControlStructure1 : Item3Traits::control_structure { int counter = 0; virtual bool process(time_point current_time) { ++counter; // DEBT: Looks like estd::chrono doesn't have these overloads sorted yet t += std::chrono::seconds(10); return true; } }; struct Item3ControlStructure2 : Item3Traits::control_structure { int counter = 0; virtual bool process(time_point current_time) { ++counter; //t += std::chrono::seconds(5); return false; } }; struct TraditionalTraitsBase { typedef unsigned long time_point; struct control_structure { typedef bool (*handler_type)(control_structure* c, time_point current_time); time_point wake_time; handler_type handler; void* data; }; }; template <bool is_inline> struct TraditionalTraits; template <> struct TraditionalTraits<true> : TraditionalTraitsBase { typedef control_structure value_type; static time_point get_time_point(const value_type& v) { return v.wake_time; } static bool process(value_type& v, time_point current_time) { return v.handler(&v, current_time); } }; template <> struct TraditionalTraits<false> : TraditionalTraitsBase { typedef control_structure* value_type; static time_point get_time_point(value_type v) { return v->wake_time; } static bool process(value_type v, time_point current_time) { return v->handler(v, current_time); } }; bool traditional_handler( TraditionalTraitsBase::control_structure* c, unsigned long current_time) { ++(*(int*)c->data); return false; } using FunctorTraits = embr::internal::experimental::FunctorTraits<unsigned>; struct StatefulFunctorTraits : FunctorTraits { time_point now_ = 0; time_point now() { return now_++; } }; TEST_CASE("scheduler test", "[scheduler]") { SECTION("impl operations") { SECTION("copy") { FunctorTraits::control_structure s1, s2(s1); FunctorTraits::control_structure s3, *ps3 = &s3, *ps1 = &s1; *ps3 = std::move(*ps1); } } SECTION("one-shot") { // doesn't have 'accessor', and maybe array isn't a good fit for priority_queue anyway //typedef estd::array<int, 4> container_type; typedef estd::layer1::vector<Item, 20> container_type; embr::internal::Scheduler<container_type, ItemTraits> scheduler; int counter = 0; scheduler.schedule(Item{5, &counter}); scheduler.schedule(Item{6, &counter}); scheduler.schedule(Item{10, &counter}); scheduler.schedule(Item{11, &counter}); auto top = scheduler.top(); const Item& value = top.clock(); REQUIRE(value.event_due == 5); top.cunlock(); scheduler.process(10); REQUIRE(counter == 3); REQUIRE(scheduler.size() == 1); } SECTION("repeating") { embr::internal::layer1::Scheduler<Item2Traits, 5> scheduler; scheduler.schedule(5); scheduler.schedule(99); // should never reach this one for(Item2Traits::time_point i = 0; i < 50; i++) { scheduler.process(i); } // being that we continually reschedule, we'll always be at the top auto& v = scheduler.top().clock(); // Should wake up 5 times at 5, 15, 25, 35 and 45 REQUIRE(v.counter == 5); } SECTION("events (aux)") { int counter = 0; int _counter = 0; typedef estd::layer1::vector<Item, 20> container_type; auto o1 = embr::experimental::make_delegate_observer([&counter]( const embr::internal::events::Scheduled<ItemTraits>& scheduled) { ++counter; }); auto o2 = embr::experimental::make_delegate_observer([&counter]( const embr::internal::events::Removed<ItemTraits>& removed) { --counter; }); // NOTE: May be wanting a ref evaporator not a struct evaporator for scheduler auto s = embr::layer1::make_subject(o1, o2); typedef decltype(s) subject_type; embr::internal::Scheduler<container_type, ItemTraits, subject_type> scheduler(std::move(s)); scheduler.schedule(Item{5}); REQUIRE(counter == 1); scheduler.schedule(Item{7}); REQUIRE(counter == 2); scheduler.process(6); // process removes one, so that will bump down our counter REQUIRE(counter == 1); } SECTION("virtual") { embr::internal::layer1::Scheduler<Item3Traits, 5> scheduler; Item3ControlStructure1 schedule1; Item3ControlStructure2 schedule2; scheduler.schedule(&schedule1); scheduler.schedule(&schedule2); estd::chrono::steady_clock::time_point now; estd::chrono::steady_clock::time_point end = now + std::chrono::seconds(60); for(; now < end; now += std::chrono::seconds(2)) { scheduler.process(now); } REQUIRE(schedule1.counter == 6); REQUIRE(schedule2.counter == 1); } SECTION("traditional") { SECTION("inline") { typedef TraditionalTraits<true> traits_type; typedef traits_type::value_type value_type; int counter = 0; embr::internal::layer1::Scheduler<traits_type, 5> scheduler; scheduler.schedule(value_type{10, traditional_handler, &counter}); scheduler.schedule(value_type{20, traditional_handler, &counter}); scheduler.process(5); scheduler.process(10); scheduler.process(19); scheduler.process(21); REQUIRE(counter == 2); } SECTION("user allocated") { typedef TraditionalTraits<false> traits_type; typedef traits_type::value_type value_type; int counter = 0; embr::internal::layer1::Scheduler<traits_type, 5> scheduler; traits_type::control_structure scheduled1{10, traditional_handler, &counter}, scheduled2{20, traditional_handler, &counter}; scheduler.schedule(&scheduled1); scheduler.schedule(&scheduled2); scheduler.process(5); scheduler.process(10); scheduler.process(19); scheduler.process(21); REQUIRE(counter == 2); } } SECTION("experimental") { // Works well, but overly verbose on account of estd::experimental::function // indeed being in progress and experimental SECTION("estd::function style") { std::bitset<32> arrived; embr::internal::layer1::Scheduler<FunctorTraits, 5> scheduler; SECTION("trivial scheduling") { auto f_set_only = FunctorTraits::make_function([&arrived](unsigned* wake, unsigned current_time) { arrived.set(*wake); }); auto f_set_and_repeat = FunctorTraits::make_function([&arrived](unsigned* wake, unsigned current_time) { arrived.set(*wake); *wake += 2; }); scheduler.schedule(11, f_set_and_repeat); scheduler.schedule(3, f_set_only); scheduler.schedule(9, f_set_only); scheduler.process(0); scheduler.process(4); scheduler.process(9); scheduler.process(11); scheduler.process(20); REQUIRE(!arrived[0]); REQUIRE(arrived[3]); REQUIRE(!arrived[4]); REQUIRE(arrived[9]); REQUIRE(arrived[11]); REQUIRE(!arrived[12]); REQUIRE(arrived[13]); REQUIRE(arrived[15]); REQUIRE(arrived[17]); REQUIRE(!arrived[18]); REQUIRE(arrived[19]); } SECTION("overly smart scheduling") { auto _f = estd::experimental::function<void(unsigned*, unsigned)>::make_inline( [&arrived](unsigned* wake, unsigned current_time) { arrived.set(*wake); if (*wake < 11 || *wake > 20) { } else { *wake = *wake + 2; } }); estd::experimental::function_base<void(unsigned*, unsigned)> f(&_f); scheduler.schedule(11, f); scheduler.schedule(3, f); scheduler.schedule(9, f); scheduler.process(0); REQUIRE(!arrived[0]); scheduler.process(4); REQUIRE(arrived[3]); REQUIRE(!arrived[9]); scheduler.process(9); REQUIRE(arrived[9]); scheduler.process(11); REQUIRE(arrived[11]); scheduler.process(20); REQUIRE(!arrived[12]); REQUIRE(arrived[13]); REQUIRE(!arrived[14]); REQUIRE(arrived[15]); REQUIRE(!arrived[16]); } } SECTION("stateful") { std::bitset<32> arrived; embr::internal::layer1::Scheduler<StatefulFunctorTraits, 5> scheduler; auto f = StatefulFunctorTraits::make_function( [&](unsigned* wake, unsigned current) { arrived.set(*wake); }); scheduler.schedule_now(f); scheduler.process(10); REQUIRE(arrived.count() == 1); REQUIRE(arrived[0]); } } }
28.369615
118
0.572456
malachi-iot
d7f6efbcc3d448023580562a5e6dcf136e6894b4
9,265
cpp
C++
src/Structure/BranchingPoint.cpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/Structure/BranchingPoint.cpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/Structure/BranchingPoint.cpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
//------------------------------------------------------------------ // **MEDYAN** - Simulation Package for the Mechanochemical // Dynamics of Active Networks, v4.0 // // Copyright (2015-2018) Papoian Lab, University of Maryland // // ALL RIGHTS RESERVED // // See the MEDYAN web page for more information: // http://www.medyan.org //------------------------------------------------------------------ #include "BranchingPoint.h" #include "SubSystem.h" #include "Bead.h" #include "Cylinder.h" #include "Filament.h" #include "ChemRNode.h" #include "CompartmentGrid.h" #include "GController.h" #include "SysParams.h" #include "MathFunctions.h" #include "Rand.h" using namespace mathfunc; void BranchingPoint::updateCoordinate() { coordinate = midPointCoordinate(_c1->getFirstBead()->vcoordinate(), _c1->getSecondBead()->vcoordinate(), _c1->adjustedrelativeposition(_position)); } BranchingPoint::BranchingPoint(Cylinder* c1, Cylinder* c2, short branchType, floatingpoint position) : Trackable(true,true), _c1(c1), _c2(c2), _position(position), _branchType(branchType), _birthTime(tau()) { //Find compartment updateCoordinate(); try {_compartment = GController::getCompartment(coordinate);} catch (exception& e) { cout << e.what(); printSelf(); exit(EXIT_FAILURE); } int pos = int(position * SysParams::Geometry().cylinderNumMon[c1->getType()]); #ifdef CHEMISTRY _cBranchingPoint = unique_ptr<CBranchingPoint>( new CBranchingPoint(branchType, _compartment, c1->getCCylinder(), c2->getCCylinder(), pos)); _cBranchingPoint->setBranchingPoint(this); #endif #ifdef MECHANICS _mBranchingPoint = unique_ptr<MBranchingPoint>(new MBranchingPoint(branchType)); _mBranchingPoint->setBranchingPoint(this); #endif //set the branching cylinder _c1->setBranchingCylinder(_c2); } BranchingPoint::~BranchingPoint() noexcept { #ifdef MECHANICS //offset the branching cylinder's bead by a little for safety auto msize = SysParams::Geometry().monomerSize[_c1->getType()]; vector<floatingpoint> offsetCoord = {(Rand::randInteger(0,1) ? -1 : +1) * Rand::randfloatingpoint(msize, 2 * msize), (Rand::randInteger(0,1) ? -1 : +1) * Rand::randfloatingpoint(msize, 2 * msize), (Rand::randInteger(0,1) ? -1 : +1) * Rand::randfloatingpoint(msize, 2 * msize)}; auto b = _c2->getFirstBead(); b->coordinate()[0] += offsetCoord[0]; b->coordinate()[1] += offsetCoord[1]; b->coordinate()[2] += offsetCoord[2]; #endif #ifdef CHEMISTRY //mark the correct species on the minus end of the branched //filament. If this is a filament species, change it to its //corresponding minus end. If a plus end, release a diffusing //or bulk species, depending on the initial reaction. CMonomer* m = _c2->getCCylinder()->getCMonomer(0); short speciesFilament = m->activeSpeciesFilament(); //there is a filament species, mark its corresponding minus end if(speciesFilament != -1) { m->speciesMinusEnd(speciesFilament)->up(); //unmark the filament and bound species m->speciesFilament(speciesFilament)->down(); m->speciesBound(SysParams::Chemistry().brancherBoundIndex[_c1->getType()])->down(); } //mark the free species instead else { //find the free species string speciesName2 = _cBranchingPoint->getdiffusingactinspeciesname(); string speciesName = diffusingactinspeciesname; cout<<speciesName<<" "<<speciesName2<<endl; Species* freeMonomer = _compartment->findSpeciesByName(speciesName); //Commented out on Dec 11, 2019. Found an alternate way that is more robust. /*Species* speciesFilament = m->speciesFilament(m->activeSpeciesPlusEnd()); string speciesName = SpeciesNamesDB::removeUniqueFilName(speciesFilament->getName()); string speciesFirstChar = speciesName.substr(0,1); //find the free monomer, either bulk or diffusing Species* freeMonomer = nullptr; auto grid = _subSystem->getCompartmentGrid(); Species* dMonomer = _compartment->findSpeciesByName(speciesName); Species* dfMonomer = _compartment->findSpeciesByName(speciesFirstChar); Species* bMonomer = grid->findSpeciesBulkByName(speciesName); Species* bfMonomer = grid->findSpeciesBulkByName(speciesFirstChar); //try diffusing if(dMonomer != nullptr) freeMonomer = dMonomer; // try bulk else if(bMonomer != nullptr) freeMonomer = bMonomer; //diffusing, remove all but first char else if(dfMonomer != nullptr) freeMonomer = dfMonomer; //bulk, remove all but first char else if(bfMonomer != nullptr) freeMonomer = bfMonomer;*/ //could not find. exit ungracefully if(freeMonomer == nullptr) { cout << "In unbranching reaction, could not find corresponding " << "diffusing species of filament species " << speciesName << ". Exiting." << endl; exit(EXIT_FAILURE); } //remove the filament from the system Filament *bf = (Filament*)(_c2->getParent()); _subSystem->removeTrackable<Filament>(bf); delete bf; //mark species, update reactions freeMonomer->up(); freeMonomer->updateReactantPropensities(); } #endif //reset branching cylinder _c1->setBranchingCylinder(nullptr); } void BranchingPoint::updatePosition() { #ifdef CHEMISTRY //update ccylinders _cBranchingPoint->setFirstCCylinder(_c1->getCCylinder()); _cBranchingPoint->setSecondCCylinder(_c2->getCCylinder()); #endif //Find compartment updateCoordinate(); Compartment* c; try {c = GController::getCompartment(coordinate);} catch (exception& e) { cout << e.what(); printSelf(); exit(EXIT_FAILURE); } if(c != _compartment) { _compartment = c; #ifdef CHEMISTRY SpeciesBound* firstSpecies = _cBranchingPoint->getFirstSpecies(); CBranchingPoint* clone = _cBranchingPoint->clone(c); setCBranchingPoint(clone); _cBranchingPoint->setFirstSpecies(firstSpecies); #endif } } void BranchingPoint::updateReactionRates() { //if no rate changers were defined, skip if(_unbindingChangers.empty()) return; //current force on branching point, use the total force floatingpoint fbranch = sqrt(_mBranchingPoint->branchForce[0]*_mBranchingPoint->branchForce[0] + _mBranchingPoint->branchForce[1]*_mBranchingPoint->branchForce[1] + _mBranchingPoint->branchForce[2]*_mBranchingPoint->branchForce[2]); floatingpoint force = max<floatingpoint>((floatingpoint)0.0, fbranch); //get the unbinding reaction ReactionBase* offRxn = _cBranchingPoint->getOffReaction(); //change the rate if (SysParams::RUNSTATE == false) offRxn->setRateMulFactor(0.0f, ReactionBase::RESTARTPHASESWITCH); else offRxn->setRateMulFactor(1.0f, ReactionBase::RESTARTPHASESWITCH); if(_unbindingChangers.size() > 0) { float factor = _unbindingChangers[_branchType]->getRateChangeFactor(force); offRxn->setRateMulFactor(factor, ReactionBase::MECHANOCHEMICALFACTOR); offRxn->updatePropensity(); } } void BranchingPoint::printSelf()const { cout << endl; cout << "BranchingPoint: ptr = " << this << endl; cout << "Branching type = " << _branchType << ", Branch ID = " << getId() << endl; cout << "Coordinates = " << coordinate[0] << ", " << coordinate[1] << ", " << coordinate[2] << endl; cout << "Position on mother cylinder (floatingpoint) = " << _position << endl; cout << "Birth time = " << _birthTime << endl; cout << endl; #ifdef CHEMISTRY cout << "Associated species = " << _cBranchingPoint->getFirstSpecies()->getName() << " , copy number = " << _cBranchingPoint->getFirstSpecies()->getN() << " , position on mother cylinder (int) = " << _cBranchingPoint->getFirstPosition() << endl; #endif cout << endl; cout << "Associated cylinders (mother and branching): " << endl; _c1->printSelf(); _c2->printSelf(); cout << endl; } species_copy_t BranchingPoint::countSpecies(const string& name) { species_copy_t copyNum = 0; for(auto b : getElements()) { auto s = b->getCBranchingPoint()->getFirstSpecies(); string sname = SpeciesNamesDB::removeUniqueFilName(s->getName()); if(sname == name) copyNum += s->getN(); } return copyNum; } vector<BranchRateChanger*> BranchingPoint::_unbindingChangers;
34.314815
104
0.615542
allen-cell-animated
d7f75dc0369d6bbc3a178f4a337f49cc3b02b2c0
621
cpp
C++
Harte_Kugeln/src/bsp_collision_update.cpp
oerpli/ComputationalPhysics
5081c46c01d078fe7b86601919a3447294304d8d
[ "Apache-2.0" ]
null
null
null
Harte_Kugeln/src/bsp_collision_update.cpp
oerpli/ComputationalPhysics
5081c46c01d078fe7b86601919a3447294304d8d
[ "Apache-2.0" ]
null
null
null
Harte_Kugeln/src/bsp_collision_update.cpp
oerpli/ComputationalPhysics
5081c46c01d078fe7b86601919a3447294304d8d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <typeinfo> #include "MatVec.h" #include "Box.h" using namespace std; int main () { const unsigned dim{3}; MatVec<lengthT,dim> pos{8, 0, 0}; MatVec<velocityT,dim> vel {1, 0, 0}; Box<3> box{MatVec<lengthT,dim>{10}, 2, Kugel<dim>{4, 1}}; timeT coll_time{}; box[0].position(pos); box[1].velocity(vel); box.initiate(); cout << box; coll_time = box.collide(); cout << coll_time << '\n'; cout << box; coll_time = box.collide(); cout << coll_time << '\n'; cout << box; coll_time = box.collide(); cout << coll_time << '\n'; cout << box; }
18.818182
58
0.626409
oerpli
d7f7da4d6bf36bdecda0dd769511a7464f8e58db
968
cpp
C++
marsyas-vamp/marsyas/src/tests/unit_tests/ChromaFilter_runner.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/tests/unit_tests/ChromaFilter_runner.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/tests/unit_tests/ChromaFilter_runner.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
/* Generated file, do not edit */ #ifndef CXXTEST_RUNNING #define CXXTEST_RUNNING #endif #define _CXXTEST_HAVE_STD #include <cxxtest/TestListener.h> #include <cxxtest/TestTracker.h> #include <cxxtest/TestRunner.h> #include <cxxtest/RealDescriptions.h> #include <cxxtest/ErrorPrinter.h> int main() { return CxxTest::ErrorPrinter().run(); } #include "TestChromaFilter.h" static Sum_runner suite_Sum_runner; static CxxTest::List Tests_Sum_runner = { 0, 0 }; CxxTest::StaticSuiteDescription suiteDescription_Sum_runner( "TestChromaFilter.h", 23, "Sum_runner", suite_Sum_runner, Tests_Sum_runner ); static class TestDescription_Sum_runner_test_chroma : public CxxTest::RealTestDescription { public: TestDescription_Sum_runner_test_chroma() : CxxTest::RealTestDescription( Tests_Sum_runner, suiteDescription_Sum_runner, 27, "test_chroma" ) {} void runTest() { suite_Sum_runner.test_chroma(); } } testDescription_Sum_runner_test_chroma; #include <cxxtest/Root.cpp>
31.225806
143
0.80062
jaouahbi
d7f9365a88328554992d812629a1e659be898815
559
hpp
C++
include/ttl/nn/bits/ops/impl/col2im1d.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
3
2018-10-23T18:46:39.000Z
2019-06-24T00:46:10.000Z
include/ttl/nn/bits/ops/impl/col2im1d.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
27
2018-11-10T14:19:16.000Z
2020-03-08T23:33:01.000Z
include/ttl/nn/bits/ops/impl/col2im1d.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
1
2018-11-05T06:17:12.000Z
2018-11-05T06:17:12.000Z
#pragma once #include <ttl/algorithm> #include <ttl/nn/bits/ops/col2im1d.hpp> namespace ttl::nn::ops { template <typename R> void col2im1d::operator()(const ttl::tensor_ref<R, 1> &y, const ttl::tensor_view<R, 2> &x) const { const auto [n] = y.shape().dims(); ttl::fill(y, static_cast<R>(0)); for (auto j : ttl::range<0>(x)) { for (auto k : ttl::range<1>(x)) { const int i = (*this)(j, k); if (inside(i, n)) { y.at(unpad(i)) += x.at(j, k); } } } } } // namespace ttl::nn::ops
26.619048
64
0.525939
stdml
d7fa3e643ddf645883fe5592ebbb6f292da88668
2,882
cpp
C++
src/general/BitmapListItem.cpp
louisdem/LibWalter
a6c88387697e5e7e9012cd5396591487afea8130
[ "MIT" ]
2
2021-01-12T21:19:19.000Z
2022-03-27T10:10:30.000Z
src/general/BitmapListItem.cpp
louisdem/LibWalter
a6c88387697e5e7e9012cd5396591487afea8130
[ "MIT" ]
6
2018-11-04T14:52:16.000Z
2020-01-01T18:40:40.000Z
src/general/BitmapListItem.cpp
louisdem/LibWalter
a6c88387697e5e7e9012cd5396591487afea8130
[ "MIT" ]
4
2016-10-08T11:01:56.000Z
2020-10-26T06:11:15.000Z
/* BitmapListItem.cpp: A BListView item with an optional picture Written by DarkWyrm <darkwyrm@earthlink.net>, Copyright 2007 Released under the MIT license. Certain code portions courtesy of the Haiku project */ #include "BitmapListItem.h" #include <View.h> #include <String.h> #include <Font.h> #include <Message.h> BitmapListItem::BitmapListItem(BBitmap *bitmap, const char *text, uint32 level, bool expanded) : BStringItem(text,level,expanded), fBitmap(bitmap) { font_height fontHeight; be_plain_font->GetHeight(&fontHeight); fBaselineOffset = fontHeight.descent; } BitmapListItem::BitmapListItem(BMessage *data) : BStringItem(data) { fBitmap = (BBitmap*)BBitmap::Instantiate(data); } BitmapListItem::~BitmapListItem(void) { delete fBitmap; } status_t BitmapListItem::Archive(BMessage *data, bool deep) const { status_t status = BStringItem::Archive(data,deep); if (status == B_OK && fBitmap) status = fBitmap->Archive(data,deep); if (status == B_OK) status = data->AddString("class","BitmapListItem"); return status; } void BitmapListItem::SetBitmap(BBitmap *bitmap) { delete fBitmap; fBitmap = bitmap; } BBitmap * BitmapListItem::Bitmap(void) const { return fBitmap; } void BitmapListItem::DrawItem(BView *owner, BRect rect, bool all) { // All of this code has been swiped from Haiku's BStringItem::DrawItem and // from ResEdit if (!Text() && fBitmap) return; rgb_color highColor = owner->HighColor(); rgb_color lowColor = owner->LowColor(); if (IsSelected() || all) { if (IsSelected()) { owner->SetHighColor(tint_color(lowColor, B_DARKEN_2_TINT)); owner->SetLowColor(owner->HighColor()); } else owner->SetHighColor(lowColor); owner->FillRect(rect); } BRect drawrect(0,0,0,0); if (fBitmap) { // Scale the fBitmap down to completely fit within the field's height drawrect = fBitmap->Bounds().OffsetToCopy(rect.LeftTop()); if (drawrect.Height() > rect.Height()) { drawrect = rect; drawrect.right = drawrect.left + (fBitmap->Bounds().Width() * (rect.Height() / fBitmap->Bounds().Height())); } owner->SetDrawingMode(B_OP_ALPHA); owner->DrawBitmap(fBitmap, fBitmap->Bounds(), drawrect); if (!IsEnabled()) { owner->SetDrawingMode(B_OP_OVER); owner->SetHighColor(255,255,255); owner->FillRect(drawrect); } owner->SetDrawingMode(B_OP_COPY); } rgb_color black = {0, 0, 0, 255}; if (!IsEnabled()) owner->SetHighColor(tint_color(black, B_LIGHTEN_2_TINT)); else owner->SetHighColor(black); BRect stringrect = rect; stringrect.right -= 5; stringrect.left = drawrect.right + 5; stringrect.bottom -= fBaselineOffset; BString out(Text()); owner->TruncateString(&out, B_TRUNCATE_END, stringrect.Width()); owner->DrawString(out.String(), stringrect.LeftBottom()); owner->SetHighColor(highColor); owner->SetLowColor(lowColor); }
21.669173
79
0.707148
louisdem
d7fedf29e51f5ba677481dfd2f24543cea21b721
1,614
cpp
C++
C++/introduction/variable_sized_arrays.cpp
beebus/hacker_rank_practice
a532655dab0b933f0a27721bca8919a0922f7394
[ "MIT" ]
null
null
null
C++/introduction/variable_sized_arrays.cpp
beebus/hacker_rank_practice
a532655dab0b933f0a27721bca8919a0922f7394
[ "MIT" ]
null
null
null
C++/introduction/variable_sized_arrays.cpp
beebus/hacker_rank_practice
a532655dab0b933f0a27721bca8919a0922f7394
[ "MIT" ]
null
null
null
/* https://www.hackerrank.com/challenges/variable-sized-arrays/ Input Format ------------ The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries). Each line i of the n subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i]. Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query. Output Format ------------- For each pair of i and j values (i.e., for each query), print a single integer denoting the element located at index j of the array referenced by a[i]. There should be a total of q lines of output. */ #include <vector> #include <iostream> using namespace std; int main() { int n,q; // First line of input cin >> n; // the number of variable-length arrays cin >> q; // the number of queries // create vector of vectors vector<vector<int>> a(n); // fill each 2D vector i with k_i values for (int i = 0; i < n; i++) { // get the length k of the vector at a[i] int k; cin >> k; // fill the vector with k values a[i].resize(k); for (int j = 0; j < k; j++) { cin >> a[i][j]; } } // run queries on a for (int q_num = 0; q_num < q; q_num++) { // get i, j as the 'query' to get a value from a int i, j; cin >> i >> j; cout << a[i][j] << endl; } return 0; }
31.038462
197
0.625155
beebus
d7ff438f53ef27cab355e5da3acf6517a8f99b6a
1,141
cpp
C++
crack-data-structures-and-algorithms/leetcode/search_in_rotated_sorted_array_II_q81.cpp
Watch-Later/Eureka
3065e76d5bf8b37d5de4f9ee75b2714a42dd4c35
[ "MIT" ]
20
2016-05-16T11:09:04.000Z
2021-12-08T09:30:33.000Z
crack-data-structures-and-algorithms/leetcode/search_in_rotated_sorted_array_II_q81.cpp
Watch-Later/Eureka
3065e76d5bf8b37d5de4f9ee75b2714a42dd4c35
[ "MIT" ]
1
2018-12-30T09:55:31.000Z
2018-12-30T14:08:30.000Z
crack-data-structures-and-algorithms/leetcode/search_in_rotated_sorted_array_II_q81.cpp
Watch-Later/Eureka
3065e76d5bf8b37d5de4f9ee75b2714a42dd4c35
[ "MIT" ]
11
2016-05-02T09:17:12.000Z
2021-12-08T09:30:35.000Z
#include <vector> using namespace std; // 核心思路 // 这题数组可能包含重复元素,因此虽然大体框架一致,处理细节上有区别 // 1) 之前用 nums[l] 和 nuns[m] 的大小来判断旋转图像,确定单调连续的一端出现在哪个位置 // 这里因为元素重复可能会导致 nums[l] == nums[m],无法决断 // 这种情况放弃一次减半的目的,改为 ++l 只缩减一个元素,并且这样缩减不改变数组的性质 class Solution { public: bool search(vector<int>& nums, int target) { int l = 0, r = nums.size(); while (l < r) { auto m = l + (r - l) / 2; if (nums[m] == target) { return true; } if (nums[l] < nums[m]) { // left part is monotonic if (nums[l] <= target && target < nums[m]) { r = m; } else { l = m + 1; } } else if (nums[l] > nums[m]) { // right part is monotonic if (nums[m] < target && target < nums[l]) { l = m + 1; } else { r = m; } } else { // nums[l] == nums[m], can't decide; threfore shrink l by one ++l; } } return false; } };
27.166667
77
0.404908
Watch-Later
cc0096c9c2da939173d886e91a4447129ce0a14f
11,599
cpp
C++
libtr101290/src/Demux.cpp
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
libtr101290/src/Demux.cpp
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
libtr101290/src/Demux.cpp
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2009-2019 easyice Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Demux.h" #include "global.h" #include "TrCore.h" #include "csysclock.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "EiLog.h" using namespace tr101290; using namespace std; CDemux::CDemux(CTrCore* pParent) { m_pParent = pParent; m_pPsiCk = new CPsiCheck(pParent); m_h_dvbpsi_pat = dvbpsi_AttachPAT(DumpPAT, this); m_bDemuxFinish = false; m_nUsedPcrPid = -1; m_pOldOccurTime = new long long[8192]; m_pKnownPid = new bool[8192]; for (int i = 0; i < 8192; i++) { m_pOldOccurTime[i] = -1; if (i <=0x1F) m_pKnownPid[i] = true; else m_pKnownPid[i] = false; } m_pKnownPid[0x1FFF] = true; m_llFirstPcr = -1; } CDemux::~CDemux() { delete m_pPsiCk; delete [] m_pOldOccurTime; delete [] m_pKnownPid; vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { delete it->pCalcPcrN1; } dvbpsi_DetachPAT(m_h_dvbpsi_pat); map<int,PMTINFO>::iterator itmap = m_mapPmtmInfo.begin(); for (; itmap != m_mapPmtmInfo.end(); ++itmap) { dvbpsi_DetachPMT(itmap->second.handle); } } void CDemux::Demux(uint8_t* pPacket) { uint16_t i_pid = ((uint16_t)(pPacket[1] & 0x1f) << 8) + pPacket[2]; if (m_mapPmtmInfo.empty()) { if(i_pid == 0x0) { dvbpsi_PushPacket(m_h_dvbpsi_pat, pPacket); } return; } else // pmt { map<int,PMTINFO>::iterator it = m_mapPmtmInfo.begin(); for (; it != m_mapPmtmInfo.end(); ++it) { if (it->second.pmt_pid == i_pid) { dvbpsi_PushPacket (it->second.handle,pPacket); } } } //判断是否解析完毕 map<int,PMTINFO>::iterator it = m_mapPmtmInfo.begin(); for (; it != m_mapPmtmInfo.end(); ++it) { if (!it->second.parsed) { //m_vecDemuxInfoBuf.clear(); return; } } m_bDemuxFinish = true; } /***************************************************************************** * DumpPAT *****************************************************************************/ void CDemux::DumpPAT(void* p_zero, dvbpsi_pat_t* p_pat) { CDemux * lpthis = (CDemux*) p_zero; dvbpsi_pat_program_t* p_program = p_pat->p_first_program; int count = 0; while(p_program) { count++; if (p_program->i_number != 0) // 0 is nit { PMTINFO pmtinfo; pmtinfo.pmt_pid = p_program->i_pid; pmtinfo.handle = dvbpsi_AttachPMT(p_program->i_number, DumpPMT, p_zero); lpthis->m_mapPmtmInfo[p_program->i_number] = pmtinfo; lpthis->m_pPsiCk->AddPmtPid(p_program->i_pid,p_program->i_number); } //else if (m_pCrcCkHds[p_program->i_pid] != NULL), newHadle.... lpthis->m_pKnownPid[p_program->i_pid] = true; lpthis->m_mapUnReferPid.erase(p_program->i_pid); p_program = p_program->p_next; } ei_log(LV_DEBUG,"libtr101290", "PAT decode finish,program count:%d",count); dvbpsi_DeletePAT(p_pat); } /***************************************************************************** * DumpPMT *****************************************************************************/ void CDemux::DumpPMT(void* p_zero, dvbpsi_pmt_t* p_pmt) { CDemux * lpthis = (CDemux*) p_zero; dvbpsi_pmt_es_t* p_es = p_pmt->p_first_es; ei_log(LV_DEBUG,"libtr101290","PMT decode info: program_number=0x%02x (%d) ",p_pmt->i_program_number,p_pmt->i_program_number); ei_log( LV_DEBUG,"libtr101290", "PCR_PID=0x%x (%d)",p_pmt->i_pcr_pid, p_pmt->i_pcr_pid); map<int,PMTINFO>::iterator it = lpthis->m_mapPmtmInfo.find(p_pmt->i_program_number); if (it == lpthis->m_mapPmtmInfo.end()) return; lpthis->m_pKnownPid[p_pmt->i_pcr_pid] = true; lpthis->m_mapUnReferPid.erase(p_pmt->i_pcr_pid); PROGRAM_INFO prog_info; while(p_es != NULL) { ei_log(LV_DEBUG,"libtr101290","es_pid=0x%02x (%d) stream_type=0x%x",p_es->i_pid, p_es->i_pid,p_es->i_type); ES_INFO es_info; es_info.pid = p_es->i_pid; es_info.stream_type = p_es->i_type; prog_info.vecPayloadPid.push_back(es_info); lpthis->m_pKnownPid[p_es->i_pid] = true; lpthis->m_mapUnReferPid.erase(p_es->i_pid); p_es = p_es->p_next; } it->second.pcr_pid = p_pmt->i_pcr_pid; prog_info.nPcrPid = p_pmt->i_pcr_pid; prog_info.nPmtPid = it->second.pmt_pid; prog_info.pCalcPcrN1 = new CCalcPcrN1(); it->second.parsed = true; lpthis->m_vecDemuxInfoBuf.push_back(prog_info); dvbpsi_DeletePMT(p_pmt); } void CDemux::AddPacket(uint8_t* pPacket) { //demux if (!m_bDemuxFinish) { Demux(pPacket); } UpdateClock(pPacket); ProcessPacket(pPacket); } void CDemux::UpdateClock(uint8_t* pPacket) { CTsPacket tsPacket; tsPacket.SetPacket(pPacket); int pid = tsPacket.Get_PID(); //find first eff pcr if (m_nUsedPcrPid < 0) { vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { if (pid == it->nPcrPid && tsPacket.Get_PCR_flag()) { m_nUsedPcrPid = pid; } } } if (m_nUsedPcrPid < 0) { return; } if (pid == m_nUsedPcrPid && tsPacket.Get_PCR_flag()) { //检测PCR跳变 long long calcPCr = m_pParent->m_pSysClock->GetPcr(); long long curPcr = tsPacket.Get_PCR(); if ( calcPCr >= 0 && llabs( diff_pcr(calcPCr,curPcr)) > 270000 ) { m_pParent->m_pSysClock->Reset(); //10ms认为跳变 } m_pParent->m_pSysClock->AddPcrPacket(curPcr); if (m_llFirstPcr < 0) { m_llFirstPcr = curPcr; } } else { m_pParent->m_pSysClock->AddPayloadPacket(); } } inline bool CDemux::IsPmtPid(int pid) { vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { if (pid == it->nPmtPid) { return true; } } return false; } inline long long CDemux::CheckOccTime(int pid,long long llCurTime) { if (m_pOldOccurTime[pid] == -1 || llCurTime == -1) { return -1; } long long interval = diff_pcr(llCurTime, m_pOldOccurTime[pid]) /*/ 27000*/; return interval; } bool CDemux::CheckEsPid(int pid,long long llCurTime,CTsPacket& tsPacket) { bool bEsPid = false; vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { vector<ES_INFO>::iterator ites = it->vecPayloadPid.begin(); for (; ites != it->vecPayloadPid.end(); ++ites) { if (m_pOldOccurTime[ites->pid] != -2) { //check timeout if (m_pOldOccurTime[ites->pid] != -1) //pid dis aper { long long interval = diff_pcr(llCurTime, m_pOldOccurTime[ites->pid]) / 27000; if (interval > 5000) { m_pOldOccurTime[ites->pid] = -2;//for never report agein m_pParent->Report(1,LV1_PID_ERROR,ites->pid,-1,-1); } } else //pid never occur { long long interval = diff_pcr(llCurTime, m_llFirstPcr ) / 27000; if (interval > 5000) { m_pOldOccurTime[ites->pid] = -2;//for never report agein m_pParent->Report(1,LV1_PID_ERROR,ites->pid,-1,-1); } } } if (ites->pid == pid) { bEsPid = true; //check pts long long pts; long long calcPCr = m_pParent->m_pSysClock->GetPcr(); if (tsPacket.Get_PTS(pts) && ites->llPrevPts_occ >= 0) { m_pParent->Report(2,LV2_PTS_ERROR,pid,diff_pcr(calcPCr, ites->llPrevPts_occ),-1); //Report(2,LV2_PTS_ERROR,pid,pts-ites->llPrevPts,-1); ites->llPrevPts = pts; ites->llPrevPts_occ = calcPCr; } } } //!for ites } //!for it return bEsPid; } void CDemux::CheckPCR(int pid,CTsPacket& tsPacket) { vector<PROGRAM_INFO>::iterator it = m_vecDemuxInfoBuf.begin(); for (;it != m_vecDemuxInfoBuf.end(); ++it) { if (pid == it->nPcrPid && tsPacket.Get_PCR_flag()) { long long pcr = tsPacket.Get_PCR(); BYTE afLen; BYTE* pAf = tsPacket.Get_adaptation_field(afLen); int discontinuity_indicator = 0; if (pAf != NULL) { if (tsPacket.Get_discontinuity_indicator(pAf)) discontinuity_indicator = 1; } //check pcr it long long pcr_prev = it->pCalcPcrN1->GetPcrPrev(); if (pcr_prev != -1) { m_pParent->Report(2,LV2_PCR_REPETITION_ERROR,pid, pcr - pcr_prev,discontinuity_indicator); } //check pcr ac long long pcr_calc = it->pCalcPcrN1->GetPcr(); if (pcr_calc != -1) { m_pParent->Report(2,LV2_PCR_ACCURACY_ERROR,pid, pcr - pcr_calc,-1); } it->pCalcPcrN1->AddPcrPacket(pcr); } else { it->pCalcPcrN1->AddPayloadPacket(); } } } void CDemux::CheckUnreferPid(int pid,long long llCurTime) { long long interval = 0; //添加一种新的PID if (!m_pKnownPid[pid]) { m_pKnownPid[pid] = true; m_mapUnReferPid[pid] = llCurTime; return; } //检测超时 map<int,long long>::iterator it = m_mapUnReferPid.begin(); for (;it != m_mapUnReferPid.end();++it) { if (it->second != -1) { interval = diff_pcr(llCurTime, it->second) / 27000; if (interval > 500) { //error here m_pParent->Report(3,LV3_UNREFERENCED_PID,pid,-1,-1); m_pKnownPid[pid] = true; m_mapUnReferPid.erase(it); return; } } else { it->second = llCurTime; } } } void CDemux::ProcessPacket(uint8_t* pPacket) { CTsPacket tsPacket; tsPacket.SetPacket(pPacket); int pid = tsPacket.Get_PID(); long long llCurTime = m_pParent->m_pSysClock->GetPcr(); long long interval; bool bPsi = false; //pat err if (pid == 0) { //check occ if ((interval=CheckOccTime(0,llCurTime)) > 0) { m_pParent->Report(1,LV1_PAT_ERROR_OCC,0,interval,-1); } //check tid CPrivate_Section cs; if (cs.SetPacket(tsPacket)) { if (cs.Get_table_id() != 0) { m_pParent->Report(1,LV1_PAT_ERROR_TID,0,-1,-1); } } //check scf if (tsPacket.Get_transport_scrambling_control() != 0) { m_pParent->Report(1,LV1_PAT_ERROR_SCF,0,-1,-1); } bPsi = true; } //pmt err if (IsPmtPid(pid)) { //check occ if ((interval = CheckOccTime(pid,llCurTime)) > 0) { m_pParent->Report(1,LV1_PMT_ERROR_OCC,pid,interval,-1); } //check scf if (tsPacket.Get_transport_scrambling_control() != 0) { m_pParent->Report(1,LV1_PMT_ERROR_SCF,pid,-1,-1); } bPsi = true; } //cat err if (pid == 1) { //check tid CPrivate_Section cs; if (cs.SetPacket(tsPacket)) { if (cs.Get_table_id() != 1) { m_pParent->Report(2,LV2_CAT_ERROR_TID,1,-1,-1); } } bPsi = true; } bool bEsPid = false; //pid err and pts err if (llCurTime > 0) { bEsPid = CheckEsPid(pid,llCurTime,tsPacket); } m_pPsiCk->AddPacket(pPacket,bEsPid,pid); //check pcr error CheckPCR(pid,tsPacket); if (!bPsi) { CheckUnreferPid(pid,llCurTime); } if (llCurTime < 0) { //当没有计算到时去码流中遇到的第一个PCR。 //当收到第二个PCR包的时候,N1 PCR 已经计算成功了 m_pOldOccurTime[pid] = m_llFirstPcr; } else { m_pOldOccurTime[pid] = llCurTime; } } bool CDemux::IsDemuxFinish() { return m_bDemuxFinish; }
21.802632
460
0.654625
codetalks-new
cc03e057746f6f15aa203928d8b54e0dab9b3046
1,841
cpp
C++
Section15/CopyConstructorAssignmentOperator/main.cpp
Himanshu40/Learn-Cpp
f0854f7c88bf31857c0c6216af80245666ca9b54
[ "CC-BY-4.0" ]
2
2021-07-18T18:12:10.000Z
2021-07-19T15:40:25.000Z
Section15/CopyConstructorAssignmentOperator/main.cpp
Himanshu40/Learn-Cpp
f0854f7c88bf31857c0c6216af80245666ca9b54
[ "CC-BY-4.0" ]
null
null
null
Section15/CopyConstructorAssignmentOperator/main.cpp
Himanshu40/Learn-Cpp
f0854f7c88bf31857c0c6216af80245666ca9b54
[ "CC-BY-4.0" ]
null
null
null
#include <iostream> using namespace std; class Base { private: int value; public: Base() : Base {0} { cout << "Base No-args constructor" << endl; } Base(int x) : value {x} { cout << "Base int constructor" << endl; } Base(const Base &other) : Base {other.value} { cout << "Base copy constructor" << endl; } Base &operator=(const Base &rhs) { cout << "Base operator=" << endl; if (this != &rhs) { value = rhs.value; } return *this; } ~Base() { cout << "Base destructor" << endl; } }; class Derived : public Base { private: int doubleValue; public: Derived() : Base(), doubleValue {0} { cout << "Derived No-args constructor" << endl; } Derived(int x) : Base(x), doubleValue {x * 2} { cout << "Derived int constructor" << endl; } Derived(const Derived &other) : Base(other), doubleValue {other.doubleValue} { cout << "Derived copy constructor" << endl; } Derived &operator=(const Derived &rhs) { cout << "Derived operator=" << endl; if (this != &rhs) { Base::operator=(rhs); doubleValue = rhs.doubleValue; } return *this; } ~Derived() { cout << "Derived destructor" << endl; } }; int main() { Base b {100}; // Overloaded constructor Base b1 {b}; // Copy constructor b = b1; // Copy assignment Derived d {100}; // Overloaded constructor Derived d1 {d}; // Copy constructor d = d1; // Copy assignment Derived d2; // No-args constructor return 0; }
23.0125
86
0.477458
Himanshu40
cc0450c7063ad045812f9d9183e3788b462ab683
9,673
cpp
C++
Source/Core/LibJob/Job.cpp
dzik143/tegenaria
a6c138633ab14232a2229d7498875d9d869d25a9
[ "MIT" ]
3
2020-12-28T06:18:47.000Z
2021-08-01T06:18:12.000Z
Source/Core/LibJob/Job.cpp
dzik143/tegenaria
a6c138633ab14232a2229d7498875d9d869d25a9
[ "MIT" ]
null
null
null
Source/Core/LibJob/Job.cpp
dzik143/tegenaria
a6c138633ab14232a2229d7498875d9d869d25a9
[ "MIT" ]
null
null
null
/******************************************************************************/ /* */ /* Copyright (c) 2010, 2014 Sylwester Wysocki <sw143@wp.pl> */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining a */ /* copy of this software and associated documentation files (the "Software"), */ /* to deal in the Software without restriction, including without limitation */ /* the rights to use, copy, modify, merge, publish, distribute, sublicense, */ /* and/or sell copies of the Software, and to permit persons to whom the */ /* Software is furnished to do so, subject to the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be included in */ /* all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */ /* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */ /* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL */ /* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */ /* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */ /* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER */ /* DEALINGS IN THE SOFTWARE. */ /* */ /******************************************************************************/ #include <cmath> #include <Tegenaria/Debug.h> #include "Job.h" namespace Tegenaria { // // Create job object. // // title - job's title (IN/OPT). // notifyCallback - callback called when job changed state or progress meter (IN/OPT). // notifyCallbackCtx - caller context passed to notifyCallback() directly (IN/OPT). // workerCallback - callback function performing real job work (IN). // workerCallbackCtx - caller context passed to workerCallback() directly (IN/OPT). // Job::Job(const char *title, JobNotifyCallbackProto notifyCallback, void *notifyCallbackCtx, JobWorkerCallbackProto workerCallback, void *workerCallbackCtx) { DBG_ENTER3("Job::Job"); // // Set job title. // if (title) { title_ = title; } else { char title[64]; snprintf(title, sizeof(title) - 1, "Anonymous job %p.\n", this); title_ = title; } // // Add object to debug set. // DBG_SET_ADD("Job", this, "%s", getTitle()); // // Set notify callback. // notifyCallback_ = notifyCallback; notifyCallbackCtx_ = notifyCallbackCtx; // // Set worker function. // workerCallback_ = workerCallback; workerCallbackCtx_ = workerCallbackCtx; // // Zero refference counter. // refCount_ = 1; // // Set state to initializing. // setState(JOB_STATE_INITIALIZING); // // Create worker thread performing real job. // workerThread_ = ThreadCreate(workerLoop, this); // // Zero statistics. // percentCompleted_ = 0.0; errorCode_ = 0; DBG_SET_RENAME("thread", workerThread_, getTitle()); DBG_LEAVE3("Job::Job"); } // // Call underlying notify callback set in constructor. // // code - one of JOB_NOTIFY_XXX codes (IN). // void Job::triggerNotifyCallback(int code) { if (notifyCallback_) { notifyCallback_(code, this, notifyCallbackCtx_); } } // // Increase refference counter. // // WARNING! Every call to addRef() MUSTS be followed by one release() call. // // TIP #1: Object will not be destroyed until refference counter is greater // than 0. // // TIP #2: Don't call destructor directly, use release() instead. If // refference counter achieve 0, object will be destroyed // automatically. // void Job::addRef() { refCountMutex_.lock(); refCount_ ++; DEBUG2("Increased refference counter to %d for job '%s'.\n", refCount_, getTitle()); refCountMutex_.unlock(); } // // Decrease refference counter increased by addRef() before. // void Job::release() { int deleteNeeded = 0; // // Decrease refference counter by 1. // refCountMutex_.lock(); refCount_ --; DEBUG2("Decreased refference counter to %d for job '%s'.\n", refCount_, getTitle()); if (refCount_ == 0) { deleteNeeded = 1; } refCountMutex_.unlock(); // // Delete object if refference counter goes down to 0. // if (deleteNeeded) { delete this; } } // // Worker loop performing real job in background thread. // This function calls underlying doTheJob() function implemented in child class. // // jobPtr - pointer to related Job object (this pointer) (IN/OUT). // int Job::workerLoop(void *jobPtr) { Job *this_ = (Job *) jobPtr; this_ -> addRef(); this_ -> setState(JOB_STATE_PENDING); if (this_ -> workerCallback_) { this_ -> workerCallback_(this_, this_ -> workerCallbackCtx_); } else { Error("ERROR: Worker callback is NULL for '%s'.\n", this_ -> getTitle()); } this_ -> release(); return 0; } // // Change current state. See JOB_STATE_XXX defines in Job.h. // // state - new state to set (IN). // void Job::setState(int state) { state_ = state; DEBUG2("%s: changed state to [%s].\n", getTitle(), getStateString()); switch(state) { case JOB_STATE_ERROR: DBG_INFO("%s : finished with error.\n", getTitle()); break; case JOB_STATE_INITIALIZING: DEBUG2("%s : initializing.\n", getTitle()); break; case JOB_STATE_PENDING: DEBUG2("%s : pending.\n", getTitle()); break; case JOB_STATE_FINISHED: DBG_INFO("%s : finished with success.\n", getTitle()); break; case JOB_STATE_STOPPED: DBG_INFO("%s : stopped.\n", getTitle()); break; } // // Call notify callback if set. // triggerNotifyCallback(JOB_NOTIFY_STATE_CHANGED); } // // Get current state code. See JOB_STATE_XXX defines in Job.h. // // RETURNS: Current state code. // int Job::getState() { return state_; } // // Get current state as human readable string. // // RETURNS: Name of current job's state. // const char *Job::getStateString() { switch(state_) { case JOB_STATE_ERROR: return "Error"; case JOB_STATE_INITIALIZING: return "Initializing"; case JOB_STATE_PENDING: return "Pending"; case JOB_STATE_FINISHED: return "Finished"; case JOB_STATE_STOPPED: return "Stopped"; }; return "Unknown"; } // // Wait until job finished or stopped with error. // // timeout - maximum time to wait in ms. Set to -1 for infinite (IN). // // RETURNS: 0 if OK (job finished/stopped on exit), // -1 otherwise (job still active on exit). int Job::wait(int timeout) { DBG_ENTER2("Job::wait"); int exitCode = -1; int timeLeft = timeout; while(state_ == JOB_STATE_INITIALIZING || state_ == JOB_STATE_PENDING) { ThreadSleepMs(50); if (timeout > 0) { timeLeft -= 50; if (timeLeft <= 0) { Error("ERROR: Timeout while waiting for job '%s'.\n", this -> getTitle()); goto fail; } } } // // Error handler. // exitCode = 0; fail: DBG_LEAVE2("SftpJob::wait"); return exitCode; } // // Send stop signal for pending job object. // After that related thread should stop working and state // should change to JOB_STATE_STOPPED. // // WARNING#1: Job object MUSTS be still released with release() method. // // TIP#1: To stop and release resources related with job use below code: // // job -> cancel(); // job -> release(); // void Job::cancel() { this -> setState(JOB_STATE_STOPPED); } // // Retrieve job's title set in constructor before. // const char *Job::getTitle() { return title_.c_str(); } Job::~Job() { ThreadWait(workerThread_); ThreadClose(workerThread_); DBG_SET_DEL("Job", this); } // // Get current job's progress in percentages (0-100%). // double Job::getPercentCompleted() { return percentCompleted_; } // // Get error code related with object. // This function should be used when job finished with error state. // int Job::getErrorCode() { return errorCode_; } // // Set current error code related with job. // This function should be used to inform caller why job object // finished with error state. // void Job::setErrorCode(int code) { errorCode_ = code; } // // Set current job's progress in percentages (0-100%). // void Job::setPercentCompleted(double percentCompleted) { int notifyNeeded = 0; if (fabs(percentCompleted_ - percentCompleted) > 0.01) { notifyNeeded = 1; } percentCompleted_ = percentCompleted; if (notifyNeeded) { triggerNotifyCallback(JOB_NOTIFY_PROGRESS); } } } /* namespace Tegenaria */
23.708333
96
0.572005
dzik143
cc05eb814f2b793eec7079778810c61bacb14f7b
6,502
cpp
C++
DeviceCode/Drivers/BatteryModel/IML200425_2/IML200425_2_config.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
DeviceCode/Drivers/BatteryModel/IML200425_2/IML200425_2_config.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
DeviceCode/Drivers/BatteryModel/IML200425_2/IML200425_2_config.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <tinyhal.h> //--// // some curve fits of this battery discharge vs. voltage/temp // X is range as (MilliVolts - MinVoltage) / VoltageToX, and below MinVoltage, 0% state of charge // the upper limit is then X=Max // this allows the coefficients to fit into the poly evaluator const STATE_OF_CHARGE_SINGLE_CURVE_FIT g_IML200425_2_DATA[] = { // -10C // y = - 2.921848049979300000E-02 // + 8.782307948443700000E-03x // - 2.333808204045830000E-04x2 // + 3.856237912002600000E-06x3 // - 2.214094332551320000E-08x4 // + 4.117594055691850000E-11x5 { -100, // INT16 Temperature; 6, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3105, // UINT16 MinVoltage; 210, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; -2105413406259200LL, 632831980865024LL, -16816860412952LL, 277871225976LL, -1595423106LL, 2967039LL, 0LL, 0LL, 0LL, 0LL, } }, // 0C // y = + 2.047522162115460000E-02 // - 4.275968405409000000E-03x // + 3.272098642863600000E-04x2 // - 6.454859570126370000E-06x3 // + 6.073919354325840000E-08x4 // - 2.543781333968020000E-10x5 // + 3.846397268909590000E-13x6 { 0, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3101, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 1475395207413760LL, -308115995475968LL, 23577955565952LL, -465121650476LL, 4376720150LL, -18329877LL, 27716LL, 0LL, 0LL, 0LL, } }, // 10C // y = + 2.411092941110840000E-02 // - 4.693360087401290000E-03x // + 2.525245543836260000E-04x2 // - 4.017030204306330000E-06x3 // + 3.082229605788980000E-08x4 // - 1.006704638813020000E-10x5 // + 1.071946769614940000E-13x6 { 100, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3094, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 1737375563382790LL, -338192235851776LL, 18196311824384LL, -289457531700LL, 2220980496LL, -7254072LL, 7724LL, 0LL, 0LL, 0LL, } }, // 20C // y = + 3.337666242396150000E-02 // - 6.122761342908230000E-03x // + 2.778481003815610000E-04x2 // - 3.921589108946130000E-06x3 // + 2.666577843908270000E-08x4 // - 7.656661606751900000E-11x5 // + 6.677988717433050000E-14x6 { 200, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3095, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 2405041991286780LL, -441191451238400LL, 20021065621504LL, -282580275996LL, 1921471837LL, -5517207LL, 4811LL, 0LL, 0LL, 0LL, } }, // 30C // y = + 2.283453822883530000E-02 // - 3.790126855165000000E-03x // + 1.648931592157510000E-04x2 // - 1.697413976042840000E-06x3 // + 5.926739318935780000E-09x4 // + 1.259643704311840000E-11x5 // - 7.520650690460260000E-14x6 { 300, // INT16 Temperature; 7, // INT8 NumCoefficients; 56, // INT8 CoefficientsScalerBits; 3095, // UINT16 MinVoltage; 209, // UINT16 MaxX; 5, // UINT16 VoltageToX; { // INT64 Coefficients[10]; 1645401885736960LL, -273107422281728LL, 11881804326400LL, -122311567200LL, 427066575LL, 907668LL, -5420LL, 0LL, 0LL, 0LL, } } }; STATE_OF_CHARGE_CURVE_FIT g_BATTERY_MEASUREMENT_CurveFit = { { TRUE }, // HAL_DRIVER_CONFIG_HEADER Header; //--// ARRAYSIZE(g_IML200425_2_DATA), g_IML200425_2_DATA, };
37.802326
201
0.375884
PervasiveDigital
cc088855eecd363b32f02609132bab024347bf22
1,029
cpp
C++
src/main.cpp
arccos0/Strip-Packing-Algorithm
d7093db2ef1dee6a06c5299b3512bca47a83e1ec
[ "MIT" ]
7
2021-09-25T07:35:11.000Z
2021-12-24T12:50:55.000Z
src/main.cpp
arccos0/Strip-Packing-Algorithm
d7093db2ef1dee6a06c5299b3512bca47a83e1ec
[ "MIT" ]
1
2021-11-04T11:45:50.000Z
2021-12-21T06:42:56.000Z
src/main.cpp
arccos0/Strip-Packing-Algorithm
d7093db2ef1dee6a06c5299b3512bca47a83e1ec
[ "MIT" ]
9
2021-09-25T04:56:43.000Z
2021-11-26T03:09:18.000Z
#include <experimental/filesystem> #include <iostream> #include <map> #include <string> #include "BLEU.h" #include "datareader.h" #include "heuristic.h" #include "spp.h" int main() { const std::string instancesFolder = "./2sp/"; for (int i = 0; i < 1; ++i) { for (const auto& entry : std::experimental::filesystem::directory_iterator(instancesFolder)) { std::string filePath = entry.path().relative_path().string(); std::cout << filePath; std::vector<const StripPacking::item*> allItems; StripPacking::Heuristic hrs; int W = readData(filePath, allItems); std::vector<const StripPacking::item*> copyItems(allItems.begin(), allItems.end()); int totalArea = 0; StripPacking::BLEU alg(allItems, W, 20, 1000); auto status = alg.evaluate(); std::cout << "The status is " << status << "\n"; for (auto it = allItems.begin(); it != allItems.end(); ++it) delete (*it); } } system("pause"); }
33.193548
80
0.594752
arccos0
cc098edc2353ea7587be178498d1d10575db91af
85,164
cpp
C++
InterfaceManager.cpp
cjcoimbra/ChessterOSX
89c6cbdfb295b3d929faa0bf036440b96a0007c6
[ "AML" ]
null
null
null
InterfaceManager.cpp
cjcoimbra/ChessterOSX
89c6cbdfb295b3d929faa0bf036440b96a0007c6
[ "AML" ]
null
null
null
InterfaceManager.cpp
cjcoimbra/ChessterOSX
89c6cbdfb295b3d929faa0bf036440b96a0007c6
[ "AML" ]
null
null
null
#include "StdAfx.h" #include "InterfaceManager.h" InterfaceManager::InterfaceManager(sf::RenderWindow * rw, ResourceManager * rm, float factor, float max_tile_size) { //ctor wptr = rw; resource_manager = rm; isIncreasingScore = false; isDecreasingScore = false; currentScore = 0; //title_screen_spt.SetImage(resource_manager->GetImageResource(11)); next_treasure_banner.SetImage(resource_manager->GetImageResource(72)); next_treasure_banner.Resize((float)(358 * wptr->GetWidth())/1920, (float)(110 * wptr->GetHeight())/1080); next_treasure_banner.SetPosition((float)(wptr->GetWidth() * 1508) / 1920, (float)(wptr->GetHeight() * 156) / 1080); moves_spt.SetImage(resource_manager->GetImageResource(17)); info_frame_spt.SetImage(resource_manager->GetImageResource(18)); turns_spt.SetImage(resource_manager->GetImageResource(19)); moves_bluecrest_spt.SetImage(resource_manager->GetImageResource(43)); turns_bluecrest_spt.SetImage(resource_manager->GetImageResource(43)); moves_spt.Resize((float)(263 * wptr->GetWidth())/1920, (float)(86 * wptr->GetHeight())/1080); turns_spt.Resize((float)(262 * wptr->GetWidth())/1920, (float)(85 * wptr->GetHeight())/1080); //info_frame_spt.Resize((411 * wptr->GetWidth())/1920, (714 * wptr->GetHeight())/1080); info_frame_spt.Resize((float)(391 * wptr->GetWidth())/1920, (float)(703 * wptr->GetHeight())/1080); std::cout << "Panel size: [" << info_frame_spt.GetSize().x << "," << info_frame_spt.GetSize().y << "]\n"; moves_bluecrest_spt.Resize((float)(135 * wptr->GetWidth())/1920, (float)(135 * wptr->GetHeight())/1080); turns_bluecrest_spt.Resize((float)(135 * wptr->GetWidth())/1920, (float)(135 * wptr->GetHeight())/1080); int right_panel = (float)(wptr->GetWidth()/2 + 4 * factor * max_tile_size); //1480x330 - position of the panel in the mockup moves_spt.SetPosition((float)(wptr->GetWidth() * 31) / 1920, (float)(wptr->GetHeight() * 66) / 1080); turns_spt.SetPosition((float)(wptr->GetWidth() * 196) / 1920, (float)(wptr->GetHeight() * 170) / 1080); //info_frame_spt.SetPosition((wptr->GetWidth() * 1478) / 1920, (wptr->GetHeight() * 207) / 1080); info_frame_spt.SetPosition((float)(wptr->GetWidth() * 1490) / 1920, (float)(wptr->GetHeight() * 340) / 1080); moves_bluecrest_spt.SetPosition((float)(wptr->GetWidth() * 94) / 1920, (float)(wptr->GetHeight() * 95) / 1080); turns_bluecrest_spt.SetPosition((float)(wptr->GetWidth() * 256) / 1920, (float)(wptr->GetHeight() * 195) / 1080); //Font for growing score and combo size this->original_font_size = 48; chesster_font.LoadFromFile("GFX/Font/Deutsch.ttf"); temp_new_game.SetFont(chesster_font); temp_new_game.SetText("[R]esume game"); temp_new_game.SetSize(42); temp_new_game.SetColor(sf::Color(200,0,0)); temp_new_game.SetPosition((float)wptr->GetWidth()/2 - temp_new_game.GetRect().GetWidth()/2, (float)wptr->GetHeight()/2 - temp_new_game.GetRect().GetHeight() - 20); temp_resume_game.SetFont(chesster_font); temp_resume_game.SetText("[N]ew game"); temp_resume_game.SetSize(42); temp_resume_game.SetColor(sf::Color(200,0,0)); temp_resume_game.SetPosition((float)wptr->GetWidth()/2 - temp_resume_game.GetRect().GetWidth()/2, (float)temp_new_game.GetPosition().y + temp_new_game.GetRect().GetHeight() + 20); temp_cancel.SetFont(chesster_font); temp_cancel.SetText("[C]ancel"); temp_cancel.SetSize(42); temp_cancel.SetColor(sf::Color(200,0,0)); temp_cancel.SetPosition((float)wptr->GetWidth()/2 - temp_cancel.GetRect().GetWidth()/2,(float) temp_resume_game.GetPosition().y + temp_resume_game.GetRect().GetHeight() + 20); deselect_info.SetFont(chesster_font); deselect_info.SetText("'right button' to deselect current piece" ); deselect_info.SetSize(24); deselect_info.SetColor(sf::Color(200,0,0)); deselect_info.SetPosition((float)wptr->GetWidth()/2 - deselect_info.GetRect().GetWidth()/2, (float)wptr->GetHeight() - deselect_info.GetRect().GetHeight() - 10); temp_info.SetFont(chesster_font); temp_info.SetText("Chesster - OSX v0.931 Demo (C) 2013 - Team Checkmate" ); temp_info.SetSize(22); temp_info.SetColor(sf::Color(255,255,255)); temp_info.SetPosition((float)wptr->GetWidth() - temp_info.GetRect().GetWidth() - 5 , (float)wptr->GetHeight() - temp_info.GetRect().GetHeight() - 10); loading_info.SetFont(chesster_font); loading_info.SetText("loading..." ); loading_info.SetSize(24); loading_info.SetColor(sf::Color(255,255,255)); loading_info.SetPosition((float)wptr->GetWidth()/2 - loading_info.GetRect().GetWidth()/2,(float) wptr->GetHeight()/2 - loading_info.GetRect().GetHeight()/2); turn_label.SetFont(chesster_font); turn_label.SetText("turn"); turn_label.SetSize(32); turn_label.SetColor(sf::Color(197,198,141)); turn_label.SetPosition(80, (float)wptr->GetHeight()/2 - 300); turn_info.SetFont(chesster_font); turn_info.SetText(""); turn_info.SetSize(42); turn_info.SetColor(sf::Color(255,255,255)); turn_info.SetPosition((float)(wptr->GetWidth() * 304) / 1920,(float) (wptr->GetHeight() * 235) / 1080); moves_label.SetFont(chesster_font); moves_label.SetText("moves"); moves_label.SetSize(32); moves_label.SetColor(sf::Color(197,198,141)); //moves_label.SetPosition(wptr->GetWidth() - 200, wptr->GetHeight()/2 - 300); //moves_label.SetPosition(moves_spt.GetPosition().x + moves_spt.GetSize().x/2 - 5, moves_spt.GetPosition().y + moves_spt.GetSize().y + 100); moves_info.SetFont(chesster_font); moves_info.SetText(""); moves_info.SetSize(42); moves_info.SetColor(sf::Color(255,255,255)); moves_info.SetPosition((float)(wptr->GetWidth() * 148) / 1920, (float)(wptr->GetHeight() * 142) / 1080); //moves_info.SetPosition(moves_spt.GetPosition().x + moves_spt.GetSize().x/2 - 10, moves_spt.GetPosition().y + moves_spt.GetSize().y - 15); turn_points_label.SetFont(chesster_font); turn_points_label.SetText("turn points"); turn_points_label.SetSize(32); turn_points_label.SetColor(sf::Color(197,198,141)); turn_points_label.SetPosition((float)wptr->GetWidth() - 200,(float) wptr->GetHeight()/2 - 150); turn_points_info.SetFont(chesster_font); turn_points_info.SetText(""); turn_points_info.SetSize(42); turn_points_info.SetColor(sf::Color(255,255,255)); turn_points_info.SetPosition((float)(wptr->GetWidth() * 1670) / 1920, (float)(wptr->GetHeight() * 508) / 1080); //turn_points_info.SetPosition(info_frame_spt.GetPosition().x + 65, info_frame_spt.GetPosition().y + 90); //520 demand_label.SetFont(chesster_font); demand_label.SetText("demand" ); demand_label.SetSize(32); demand_label.SetColor(sf::Color(197,198,141)); demand_label.SetPosition((float)wptr->GetWidth() - 200 + 12,(float) wptr->GetHeight()/2 + 133); //((wptr->GetWidth() * x) / 1920) //((wptr->GetHeight() * y) / 1080) demand_info.SetFont(chesster_font); demand_info.SetText(""); demand_info.SetSize(42); demand_info.SetColor(sf::Color(255,255,255)); demand_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - demand_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 688) / 1080); //demand_info.SetPosition(info_frame_spt.GetPosition().x + 65, info_frame_spt.GetPosition().y + 185); //706 total_points_label.SetFont(chesster_font); total_points_label.SetText("total"); total_points_label.SetSize(32); total_points_label.SetColor(sf::Color(197,198,141)); total_points_label.SetPosition((float)wptr->GetWidth() - 200,(float) wptr->GetHeight()/2 + 150); total_points_info.SetFont(chesster_font); total_points_info.SetText(""); total_points_info.SetSize(42); total_points_info.SetColor(sf::Color(255,255,255)); total_points_info.SetPosition((float)(wptr->GetWidth() * 1670) / 1920,(float) (wptr->GetHeight() * 896) / 1080); //total_points_info.SetPosition(info_frame_spt.GetPosition().x + 65, info_frame_spt.GetPosition().y + 300); //908 match_label.SetFont(chesster_font); match_label.SetText(""); match_label.SetSize(62); match_label.SetColor(sf::Color(255,255,255)); match_label.SetPosition(50,(float) wptr->GetHeight()/2 - 100); x_label.SetFont(chesster_font); x_label.SetText(""); x_label.SetSize(48); x_label.SetColor(sf::Color(255,255,255)); x_label.SetPosition((float)(wptr->GetWidth() * 200) / 1920, (float)(wptr->GetHeight() * 590) / 1080); match_points_info.SetFont(chesster_font); match_points_info.SetText(""); match_points_info.SetSize((float)this->original_font_size); match_points_info.SetColor(sf::Color(255,255,255)); //match_points_info.SetPosition((wptr->GetWidth() * 180) / 1920, (wptr->GetHeight() * 680) / 1080); match_points_info.SetPosition((float)(wptr->GetWidth() * 200) / 1920,(float) (wptr->GetHeight() * 590) / 1080); multiply_spt.SetImage(resource_manager->GetImageResource(71)); multiply_spt.Resize((float)(83 * wptr->GetWidth())/1920, (float)(90 * wptr->GetHeight())/1080); //multiply_spt.SetPosition((wptr->GetWidth() * 200) / 1920, (wptr->GetHeight() * 590) / 1080); multiply_spt.SetPosition((float)(wptr->GetWidth() * 200) / 1920,(float) match_points_info.GetPosition().y + match_points_info.GetRect().GetHeight() + 110); match_amount_info.SetFont(chesster_font); match_amount_info.SetText(""); match_amount_info.SetSize((float)this->original_font_size); match_amount_info.SetColor(sf::Color(255,255,255)); //match_amount_info.SetPosition((wptr->GetWidth() * 290) / 1920,(wptr->GetHeight() * 590) / 1080); match_amount_info.SetPosition((float)multiply_spt.GetPosition().x + multiply_spt.GetSize().x + 20, (float)multiply_spt.GetPosition().y); play_button_normal.SetImage(resource_manager->GetImageResource(21)); play_button_focus.SetImage(resource_manager->GetImageResource(22)); play_button_normal.Resize((float)(307 * wptr->GetWidth())/1920,(float) (113 * wptr->GetHeight())/1080); play_button_focus.Resize((float)(307 * wptr->GetWidth())/1920,(float) (113 * wptr->GetHeight())/1080); play_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - play_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 465) / 1080); play_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - play_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 465) / 1080); tutorial_button_normal.SetImage(resource_manager->GetImageResource(23)); tutorial_button_focus.SetImage(resource_manager->GetImageResource(24)); tutorial_button_normal.Resize((float)(419 * wptr->GetWidth())/1920, (float)(106 * wptr->GetHeight())/1080); tutorial_button_focus.Resize((float)(419 * wptr->GetWidth())/1920, (float)(106 * wptr->GetHeight())/1080); tutorial_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - tutorial_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 575) / 1080); tutorial_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - tutorial_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 575) / 1080); // Version with Puzzle puzzle_button_normal.SetImage(resource_manager->GetImageResource(25)); puzzle_button_focus.SetImage(resource_manager->GetImageResource(26)); puzzle_button_normal.Resize((float)(396 * wptr->GetWidth())/1920, (float)(91 * wptr->GetHeight())/1080); puzzle_button_focus.Resize((float)(396 * wptr->GetWidth())/1920,(float) (91 * wptr->GetHeight())/1080); puzzle_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - puzzle_button_normal.GetSize().x/2, (float)(wptr->GetHeight() * 690) / 1080); puzzle_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - puzzle_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 690) / 1080); scores_button_normal.SetImage(resource_manager->GetImageResource(27)); scores_button_focus.SetImage(resource_manager->GetImageResource(28)); scores_button_normal.Resize((float)(385 * wptr->GetWidth())/1920,(float) (90 * wptr->GetHeight())/1080); scores_button_focus.Resize((float)(385 * wptr->GetWidth())/1920, (float)(90 * wptr->GetHeight())/1080); scores_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - scores_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 805) / 1080); scores_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - scores_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 805) / 1080); credits_button_normal.SetImage(resource_manager->GetImageResource(29)); credits_button_focus.SetImage(resource_manager->GetImageResource(30)); credits_button_normal.Resize((float)(402 * wptr->GetWidth())/1920,(float) (90 * wptr->GetHeight())/1080); credits_button_focus.Resize((float)(402 * wptr->GetWidth())/1920, (float)(90 * wptr->GetHeight())/1080); credits_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - credits_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 920) / 1080); credits_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - credits_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 920) / 1080); //Version without Puzzle /* scores_button_normal.SetImage(resource_manager->GetImageResource(27)); scores_button_focus.SetImage(resource_manager->GetImageResource(28)); scores_button_normal.Resize((385 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); scores_button_focus.Resize((385 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); scores_button_normal.SetPosition(this->wptr->GetWidth()/2 - scores_button_normal.GetSize().x/2, (wptr->GetHeight() * 690) / 1080); scores_button_focus.SetPosition(this->wptr->GetWidth()/2 - scores_button_focus.GetSize().x/2, (wptr->GetHeight() * 690) / 1080); credits_button_normal.SetImage(resource_manager->GetImageResource(29)); credits_button_focus.SetImage(resource_manager->GetImageResource(30)); credits_button_normal.Resize((402 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); credits_button_focus.Resize((402 * wptr->GetWidth())/1920, (90 * wptr->GetHeight())/1080); credits_button_normal.SetPosition(this->wptr->GetWidth()/2 - credits_button_normal.GetSize().x/2, (wptr->GetHeight() * 805) / 1080); credits_button_focus.SetPosition(this->wptr->GetWidth()/2 - credits_button_focus.GetSize().x/2, (wptr->GetHeight() * 805) / 1080); */ quit_button_normal.SetImage(resource_manager->GetImageResource(69)); quit_button_focus.SetImage(resource_manager->GetImageResource(70)); quit_button_normal.Resize((float)(140 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); quit_button_focus.Resize((float)(140 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); quit_button_normal.SetPosition(20, (float)wptr->GetHeight() - quit_button_focus.GetSize().y - 20); quit_button_focus.SetPosition(20,(float) wptr->GetHeight() - quit_button_focus.GetSize().y - 20); new_button_normal.SetImage(resource_manager->GetImageResource(76)); new_button_focus.SetImage(resource_manager->GetImageResource(77)); new_button_normal.Resize((float)(145 * wptr->GetWidth())/1920, (float)(80 * wptr->GetHeight())/1080); new_button_focus.Resize((float)(145 * wptr->GetWidth())/1920, (float)(80 * wptr->GetHeight())/1080); new_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - new_button_normal.GetSize().x/2,(float) (wptr->GetHeight() * 465) / 1080); new_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - new_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 465) / 1080); resume_button_normal.SetImage(resource_manager->GetImageResource(78)); resume_button_focus.SetImage(resource_manager->GetImageResource(79)); resume_button_normal.Resize((float)(254 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); resume_button_focus.Resize((float)(254 * wptr->GetWidth())/1920,(float) (80 * wptr->GetHeight())/1080); resume_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - resume_button_normal.GetSize().x/2, (float)(wptr->GetHeight() * 575) / 1080); resume_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - resume_button_focus.GetSize().x/2,(float) (wptr->GetHeight() * 575) / 1080); back_button_normal.SetImage(resource_manager->GetImageResource(80)); back_button_focus.SetImage(resource_manager->GetImageResource(81)); back_button_normal.Resize((float)(170 * wptr->GetWidth())/1920, (float)(84 * wptr->GetHeight())/1080); back_button_focus.Resize((float)(170 * wptr->GetWidth())/1920,(float) (84 * wptr->GetHeight())/1080); back_button_normal.SetPosition((float)this->wptr->GetWidth()/2 - back_button_normal.GetSize().x/2, (float)(wptr->GetHeight() * 690) / 1080); back_button_focus.SetPosition((float)this->wptr->GetWidth()/2 - back_button_focus.GetSize().x/2, (float)(wptr->GetHeight() * 690) / 1080); combos_button_focus.SetImage(resource_manager->GetImageResource(33)); combos_button_focus.Resize((float)(146 * wptr->GetWidth())/1920,(float) (146 * wptr->GetHeight())/1080); combos_button_focus.SetPosition((float)(wptr->GetWidth() * 301) / 1920,(float) (wptr->GetHeight() * 886) / 1080); //combos_button_focus.SetPosition((wptr->GetWidth() * 22) / 1920, (wptr->GetHeight() * 26) / 1080); combos_button_off.SetImage(resource_manager->GetImageResource(31)); combos_button_off.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); combos_button_off.SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 886) / 1080); //combos_button_off.SetPosition((wptr->GetWidth() * 153) / 1920, (wptr->GetHeight() * 26) / 1080); combos_button_on.SetImage(resource_manager->GetImageResource(32)); combos_button_on.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); combos_button_on.SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 886) / 1080); combos_button_state = "off"; movement_button_focus.SetImage(resource_manager->GetImageResource(36)); movement_button_focus.Resize((float)(146 * wptr->GetWidth())/1920,(float) (146 * wptr->GetHeight())/1080); movement_button_focus.SetPosition((float)(wptr->GetWidth() * 42) / 1920, (float)(wptr->GetHeight() * 886) / 1080); movement_button_off.SetImage(resource_manager->GetImageResource(34)); movement_button_off.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); movement_button_off.SetPosition((float)(wptr->GetWidth() * 42) / 1920,(float) (wptr->GetHeight() * 886) / 1080); movement_button_on.SetImage(resource_manager->GetImageResource(35)); movement_button_on.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); movement_button_on.SetPosition((float)(wptr->GetWidth() * 42) / 1920,(float) (wptr->GetHeight() * 886) / 1080); movement_button_state = "off"; treasure_button_focus.SetImage(resource_manager->GetImageResource(39)); treasure_button_focus.Resize((float)(146 * wptr->GetWidth())/1920,(float) (147 * wptr->GetHeight())/1080); treasure_button_focus.SetPosition((float)(wptr->GetWidth() * 174) / 1920, (float)(wptr->GetHeight() * 886) / 1080); treasure_button_off.SetImage(resource_manager->GetImageResource(37)); treasure_button_off.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); treasure_button_off.SetPosition((float)(wptr->GetWidth() * 174) / 1920, (float)(wptr->GetHeight() * 886) / 1080); treasure_button_on.SetImage(resource_manager->GetImageResource(38)); treasure_button_on.Resize((float)(146 * wptr->GetWidth())/1920, (float)(146 * wptr->GetHeight())/1080); treasure_button_on.SetPosition((float)(wptr->GetWidth() * 174) / 1920,(float) (wptr->GetHeight() * 886) / 1080); treasure_button_state = "off"; combos_board.SetImage(resource_manager->GetImageResource(40)); combos_board.Resize((float)(483 * wptr->GetWidth())/1920,(float) (809 * wptr->GetHeight())/1080); //combos_board.SetPosition((wptr->GetWidth() * 44) / 1920, (wptr->GetHeight() * 80) / 1080); combos_board.SetPosition((float)0 - combos_board.GetSize().x - 20,(float) (wptr->GetHeight() * 80) / 1080); combosboard_x = combos_board.GetPosition().x; combos_board_state = "off"; movement_board.SetImage(resource_manager->GetImageResource(41)); movement_board.Resize((float)(483 * wptr->GetWidth())/1920,(float) (809 * wptr->GetHeight())/1080); //movement_board.SetPosition((wptr->GetWidth() * 44) / 1920, (wptr->GetHeight() * 80) / 1080); movement_board.SetPosition((float)0 - combos_board.GetSize().x - 20,(float) (wptr->GetHeight() * 80) / 1080); movesboard_x = movement_board.GetPosition().x; movement_board_state = "off"; treasure_board.SetImage(resource_manager->GetImageResource(42)); treasure_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); //treasure_board.SetPosition((wptr->GetWidth() * 44) / 1920, (wptr->GetHeight() * 80) / 1080); treasure_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); treasuresboard_x = treasure_board.GetPosition().x; treasure_board_state = "off"; is_sliding_out = false; textboard_to_show = "null"; textboard_to_hide = "null"; slide_speed = 2000; next_treasure_info[0].SetFont(chesster_font); next_treasure_info[0].SetText("200pts"); next_treasure_info[0].SetSize(48); next_treasure_info[0].SetColor(sf::Color(0,0,0)); next_treasure_info[0].SetPosition((float)(wptr->GetWidth() * 1600) / 1920,(float) (wptr->GetHeight() * 238) / 1080); next_treasure_info[1].SetFont(chesster_font); next_treasure_info[1].SetText("300pts"); next_treasure_info[1].SetSize(48); next_treasure_info[1].SetColor(sf::Color(0,0,0)); next_treasure_info[1].SetPosition((float)(wptr->GetWidth() * 1600) / 1920,(float) (wptr->GetHeight() * 238) / 1080); next_treasure_info[2].SetFont(chesster_font); next_treasure_info[2].SetText("400pts"); next_treasure_info[2].SetSize(48); next_treasure_info[2].SetColor(sf::Color(0,0,0)); next_treasure_info[2].SetPosition((float)(wptr->GetWidth() * 1600) / 1920, (float)(wptr->GetHeight() * 238) / 1080); next_treasure_info[3].SetFont(chesster_font); next_treasure_info[3].SetText("500pts"); next_treasure_info[3].SetSize(48); next_treasure_info[3].SetColor(sf::Color(0,0,0)); next_treasure_info[3].SetPosition((float)(wptr->GetWidth() * 1600) / 1920, (float)(wptr->GetHeight() * 238) / 1080); demand_animation[0].SetImage(resource_manager->LoadDemandAnimation(0)); demand_animation[0].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[0].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[1].SetImage(resource_manager->LoadDemandAnimation(1)); demand_animation[1].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[1].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[2].SetImage(resource_manager->LoadDemandAnimation(2)); demand_animation[2].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[2].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[3].SetImage(resource_manager->LoadDemandAnimation(3)); demand_animation[3].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[3].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[4].SetImage(resource_manager->LoadDemandAnimation(0)); demand_animation[4].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[4].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[5].SetImage(resource_manager->LoadDemandAnimation(5)); demand_animation[5].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[5].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[6].SetImage(resource_manager->LoadDemandAnimation(6)); demand_animation[6].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[6].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[7].SetImage(resource_manager->LoadDemandAnimation(7)); demand_animation[7].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[7].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[8].SetImage(resource_manager->LoadDemandAnimation(8)); demand_animation[8].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[8].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[9].SetImage(resource_manager->LoadDemandAnimation(9)); demand_animation[9].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[9].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[10].SetImage(resource_manager->LoadDemandAnimation(10)); demand_animation[10].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[10].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[11].SetImage(resource_manager->LoadDemandAnimation(11)); demand_animation[11].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[11].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[12].SetImage(resource_manager->LoadDemandAnimation(12)); demand_animation[12].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[12].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[13].SetImage(resource_manager->LoadDemandAnimation(13)); demand_animation[13].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[13].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[14].SetImage(resource_manager->LoadDemandAnimation(14)); demand_animation[14].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[14].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[15].SetImage(resource_manager->LoadDemandAnimation(15)); demand_animation[15].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[15].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[16].SetImage(resource_manager->LoadDemandAnimation(16)); demand_animation[16].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[16].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[17].SetImage(resource_manager->LoadDemandAnimation(17)); demand_animation[17].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[17].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[18].SetImage(resource_manager->LoadDemandAnimation(18)); demand_animation[18].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[18].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[19].SetImage(resource_manager->LoadDemandAnimation(19)); demand_animation[19].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[19].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[20].SetImage(resource_manager->LoadDemandAnimation(20)); demand_animation[20].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[20].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[21].SetImage(resource_manager->LoadDemandAnimation(21)); demand_animation[21].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[21].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); demand_animation[22].SetImage(resource_manager->LoadDemandAnimation(22)); demand_animation[22].Resize((float)(600 * wptr->GetWidth())/1920, (float)(600 * wptr->GetHeight())/1080); demand_animation[22].SetPosition((float)(wptr->GetWidth() * 1372) / 1920, (float)(wptr->GetHeight() * 232) / 1080); positive_score_animation[0].SetImage(resource_manager->LoadPositiveScoreAnimation(0)); positive_score_animation[0].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[0].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[1].SetImage(resource_manager->LoadPositiveScoreAnimation(1)); positive_score_animation[1].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[1].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[2].SetImage(resource_manager->LoadPositiveScoreAnimation(2)); positive_score_animation[2].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[2].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[3].SetImage(resource_manager->LoadPositiveScoreAnimation(3)); positive_score_animation[3].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[3].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[4].SetImage(resource_manager->LoadPositiveScoreAnimation(4)); positive_score_animation[4].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[4].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[5].SetImage(resource_manager->LoadPositiveScoreAnimation(5)); positive_score_animation[5].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[5].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[6].SetImage(resource_manager->LoadPositiveScoreAnimation(6)); positive_score_animation[6].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[6].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[7].SetImage(resource_manager->LoadPositiveScoreAnimation(7)); positive_score_animation[7].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[7].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[8].SetImage(resource_manager->LoadPositiveScoreAnimation(8)); positive_score_animation[8].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[8].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[9].SetImage(resource_manager->LoadPositiveScoreAnimation(9)); positive_score_animation[9].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[9].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[10].SetImage(resource_manager->LoadPositiveScoreAnimation(10)); positive_score_animation[10].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[10].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[11].SetImage(resource_manager->LoadPositiveScoreAnimation(11)); positive_score_animation[11].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[11].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[12].SetImage(resource_manager->LoadPositiveScoreAnimation(12)); positive_score_animation[12].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[12].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[13].SetImage(resource_manager->LoadPositiveScoreAnimation(13)); positive_score_animation[13].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[13].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[14].SetImage(resource_manager->LoadPositiveScoreAnimation(14)); positive_score_animation[14].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[14].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[15].SetImage(resource_manager->LoadPositiveScoreAnimation(15)); positive_score_animation[15].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[15].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[16].SetImage(resource_manager->LoadPositiveScoreAnimation(16)); positive_score_animation[16].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[16].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[17].SetImage(resource_manager->LoadPositiveScoreAnimation(17)); positive_score_animation[17].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[17].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[18].SetImage(resource_manager->LoadPositiveScoreAnimation(18)); positive_score_animation[18].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[18].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[19].SetImage(resource_manager->LoadPositiveScoreAnimation(19)); positive_score_animation[19].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[19].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[20].SetImage(resource_manager->LoadPositiveScoreAnimation(20)); positive_score_animation[20].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[20].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[21].SetImage(resource_manager->LoadPositiveScoreAnimation(21)); positive_score_animation[21].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[21].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[22].SetImage(resource_manager->LoadPositiveScoreAnimation(22)); positive_score_animation[22].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[22].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[23].SetImage(resource_manager->LoadPositiveScoreAnimation(23)); positive_score_animation[23].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[23].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_score_animation[24].SetImage(resource_manager->LoadPositiveScoreAnimation(24)); positive_score_animation[24].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_score_animation[24].SetPosition((float)(wptr->GetWidth() * 1440) / 1920, (float)(wptr->GetHeight() * 260) / 1080); positive_total_score_animation[0].SetImage(resource_manager->LoadPositiveScoreAnimation(0)); positive_total_score_animation[0].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[0].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[1].SetImage(resource_manager->LoadPositiveScoreAnimation(1)); positive_total_score_animation[1].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[1].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[2].SetImage(resource_manager->LoadPositiveScoreAnimation(2)); positive_total_score_animation[2].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[2].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[3].SetImage(resource_manager->LoadPositiveScoreAnimation(3)); positive_total_score_animation[3].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[3].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[4].SetImage(resource_manager->LoadPositiveScoreAnimation(4)); positive_total_score_animation[4].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[4].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[5].SetImage(resource_manager->LoadPositiveScoreAnimation(5)); positive_total_score_animation[5].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[5].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[6].SetImage(resource_manager->LoadPositiveScoreAnimation(6)); positive_total_score_animation[6].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[6].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[7].SetImage(resource_manager->LoadPositiveScoreAnimation(7)); positive_total_score_animation[7].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[7].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[8].SetImage(resource_manager->LoadPositiveScoreAnimation(8)); positive_total_score_animation[8].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[8].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[9].SetImage(resource_manager->LoadPositiveScoreAnimation(9)); positive_total_score_animation[9].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[9].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[10].SetImage(resource_manager->LoadPositiveScoreAnimation(10)); positive_total_score_animation[10].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[10].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[11].SetImage(resource_manager->LoadPositiveScoreAnimation(11)); positive_total_score_animation[11].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[11].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[12].SetImage(resource_manager->LoadPositiveScoreAnimation(12)); positive_total_score_animation[12].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[12].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[13].SetImage(resource_manager->LoadPositiveScoreAnimation(13)); positive_total_score_animation[13].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[13].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[14].SetImage(resource_manager->LoadPositiveScoreAnimation(14)); positive_total_score_animation[14].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[14].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[15].SetImage(resource_manager->LoadPositiveScoreAnimation(15)); positive_total_score_animation[15].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[15].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[16].SetImage(resource_manager->LoadPositiveScoreAnimation(16)); positive_total_score_animation[16].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[16].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[17].SetImage(resource_manager->LoadPositiveScoreAnimation(17)); positive_total_score_animation[17].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[17].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[18].SetImage(resource_manager->LoadPositiveScoreAnimation(18)); positive_total_score_animation[18].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[18].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[19].SetImage(resource_manager->LoadPositiveScoreAnimation(19)); positive_total_score_animation[19].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[19].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[20].SetImage(resource_manager->LoadPositiveScoreAnimation(20)); positive_total_score_animation[20].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[20].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[21].SetImage(resource_manager->LoadPositiveScoreAnimation(21)); positive_total_score_animation[21].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[21].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[22].SetImage(resource_manager->LoadPositiveScoreAnimation(22)); positive_total_score_animation[22].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[22].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[23].SetImage(resource_manager->LoadPositiveScoreAnimation(23)); positive_total_score_animation[23].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[23].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); positive_total_score_animation[24].SetImage(resource_manager->LoadPositiveScoreAnimation(24)); positive_total_score_animation[24].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); positive_total_score_animation[24].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[0].SetImage(resource_manager->LoadNegativeScoreAnimation(0)); negative_total_score_animation[0].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[0].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[1].SetImage(resource_manager->LoadNegativeScoreAnimation(1)); negative_total_score_animation[1].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[1].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[2].SetImage(resource_manager->LoadNegativeScoreAnimation(2)); negative_total_score_animation[2].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[2].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[3].SetImage(resource_manager->LoadNegativeScoreAnimation(3)); negative_total_score_animation[3].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[3].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[4].SetImage(resource_manager->LoadNegativeScoreAnimation(4)); negative_total_score_animation[4].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[4].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[5].SetImage(resource_manager->LoadNegativeScoreAnimation(5)); negative_total_score_animation[5].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[5].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[6].SetImage(resource_manager->LoadNegativeScoreAnimation(6)); negative_total_score_animation[6].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[6].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[7].SetImage(resource_manager->LoadNegativeScoreAnimation(7)); negative_total_score_animation[7].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[7].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[8].SetImage(resource_manager->LoadNegativeScoreAnimation(8)); negative_total_score_animation[8].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[8].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[9].SetImage(resource_manager->LoadNegativeScoreAnimation(9)); negative_total_score_animation[9].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[9].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[10].SetImage(resource_manager->LoadNegativeScoreAnimation(10)); negative_total_score_animation[10].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[10].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[11].SetImage(resource_manager->LoadNegativeScoreAnimation(11)); negative_total_score_animation[11].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[11].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[12].SetImage(resource_manager->LoadNegativeScoreAnimation(12)); negative_total_score_animation[12].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[12].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[13].SetImage(resource_manager->LoadNegativeScoreAnimation(13)); negative_total_score_animation[13].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[13].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[14].SetImage(resource_manager->LoadNegativeScoreAnimation(14)); negative_total_score_animation[14].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[14].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[15].SetImage(resource_manager->LoadNegativeScoreAnimation(15)); negative_total_score_animation[15].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[15].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[16].SetImage(resource_manager->LoadNegativeScoreAnimation(16)); negative_total_score_animation[16].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[16].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[17].SetImage(resource_manager->LoadNegativeScoreAnimation(17)); negative_total_score_animation[17].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[17].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[18].SetImage(resource_manager->LoadNegativeScoreAnimation(18)); negative_total_score_animation[18].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[18].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[19].SetImage(resource_manager->LoadNegativeScoreAnimation(19)); negative_total_score_animation[19].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[19].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); negative_total_score_animation[20].SetImage(resource_manager->LoadNegativeScoreAnimation(20)); negative_total_score_animation[20].Resize((float)(430 * wptr->GetWidth())/1920, (float)(430 * wptr->GetHeight())/1080); negative_total_score_animation[20].SetPosition((float)(wptr->GetWidth() * 1464) / 1920, (float)(wptr->GetHeight() * 652) / 1080); } void InterfaceManager::SetupTreasureImagesForNewLevel() { treasure[0].SetImage(resource_manager->OnDemandLoadTreasures(0)); treasure[0].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[0].SetPosition((float)(wptr->GetWidth() * 133) / 1920, (float)(wptr->GetHeight() * 327) / 1080); unlocked_treasures[0] = false; treasure_shadow[0].SetImage(resource_manager->OnDemandLoadTreasures(4)); treasure_shadow[0].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure_shadow[0].SetPosition((float)(wptr->GetWidth() * 133) / 1920, (float)(wptr->GetHeight() * 327) / 1080); next_treasure[0].SetImage(resource_manager->OnDemandLoadTreasures(0)); next_treasure[0].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[0].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); treasure[1].SetImage(resource_manager->OnDemandLoadTreasures(1)); treasure[1].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[1].SetPosition((float)(wptr->GetWidth() * 294) / 1920, (float)(wptr->GetHeight() * 326) / 1080); unlocked_treasures[1] = false; treasure_shadow[1].SetImage(resource_manager->OnDemandLoadTreasures(5)); treasure_shadow[1].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure_shadow[1].SetPosition((float)(wptr->GetWidth() * 294) / 1920, (float)(wptr->GetHeight() * 326) / 1080); next_treasure[1].SetImage(resource_manager->OnDemandLoadTreasures(1)); next_treasure[1].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[1].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); treasure[2].SetImage(resource_manager->OnDemandLoadTreasures(2)); treasure[2].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[2].SetPosition((float)(wptr->GetWidth() * 141) / 1920, (float)(wptr->GetHeight() * 554) / 1080); unlocked_treasures[2] = false; treasure_shadow[2].SetImage(resource_manager->OnDemandLoadTreasures(6)); treasure_shadow[2].Resize((float)(120 * wptr->GetWidth())/1920,(float) (120 * wptr->GetHeight())/1080); treasure_shadow[2].SetPosition((float)(wptr->GetWidth() * 141) / 1920, (float)(wptr->GetHeight() * 554) / 1080); next_treasure[2].SetImage(resource_manager->OnDemandLoadTreasures(2)); next_treasure[2].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[2].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); treasure[3].SetImage(resource_manager->OnDemandLoadTreasures(3)); treasure[3].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure[3].SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 538) / 1080); unlocked_treasures[3] = false; treasure_shadow[3].SetImage(resource_manager->OnDemandLoadTreasures(7)); treasure_shadow[3].Resize((float)(120 * wptr->GetWidth())/1920, (float)(120 * wptr->GetHeight())/1080); treasure_shadow[3].SetPosition((float)(wptr->GetWidth() * 301) / 1920, (float)(wptr->GetHeight() * 538) / 1080); next_treasure[3].SetImage(resource_manager->OnDemandLoadTreasures(3)); next_treasure[3].Resize((float)(160 * wptr->GetWidth())/1920, (float)(160 * wptr->GetHeight())/1080); next_treasure[3].SetPosition((float)(wptr->GetWidth() * 1598) / 1920, (float)(wptr->GetHeight() * 51) / 1080); } void InterfaceManager::PerformTextboardSlide() { if (is_sliding_out) { if (textboard_to_hide == "treasure") { if (treasuresboard_x > moving_textboard_target_x) { treasuresboard_x -= slide_speed * wptr->GetFrameTime(); treasure_board.SetPosition(treasuresboard_x, (wptr->GetHeight() * 80) / 1080); } else { textboard_to_hide = "null"; treasure_board_state = "off"; if (textboard_to_show == "moves") { movement_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (textboard_to_show == "combos") { combos_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } is_sliding_out = false; } } else if (textboard_to_hide == "moves") { if (movesboard_x > moving_textboard_target_x) { movesboard_x -= slide_speed * wptr->GetFrameTime(); movement_board.SetPosition((float)movesboard_x, (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_hide = "null"; movement_board_state = "off"; if (textboard_to_show == "treasure") { treasure_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (textboard_to_show == "combos") { combos_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } is_sliding_out = false; } } else if (textboard_to_hide == "combos") { if (combosboard_x > moving_textboard_target_x) { combosboard_x -= slide_speed * wptr->GetFrameTime(); combos_board.SetPosition((float)combosboard_x , (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_hide = "null"; combos_board_state = "off"; if (textboard_to_show == "moves") { movement_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (textboard_to_show == "treasure") { treasure_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } is_sliding_out = false; } } } else // Slide in { if (textboard_to_show == "treasure") { if (treasuresboard_x < moving_textboard_target_x) { treasuresboard_x += slide_speed * wptr->GetFrameTime(); treasure_board.SetPosition((float)treasuresboard_x, (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_show = "null"; } } else if (textboard_to_show == "moves") { if (movesboard_x < moving_textboard_target_x) { movesboard_x += slide_speed * wptr->GetFrameTime(); movement_board.SetPosition((float)movesboard_x, (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_show = "null"; } } else if (textboard_to_show == "combos") { if (combosboard_x < moving_textboard_target_x) { combosboard_x += slide_speed * wptr->GetFrameTime(); combos_board.SetPosition((float)combosboard_x , (float)(wptr->GetHeight() * 80) / 1080); } else { textboard_to_show = "null"; } } } } void InterfaceManager::SetupTextboardTransition(std::string in, std::string out) { //one going out and another going in if (in != "null" && out != "null") { //std::cout <<"ONE IN ANOTHER OUT \n\n"; if (out == "combos") { textboard_to_hide = "combos"; moving_textboard_target_x = 0 - combos_board.GetSize().x - 20; } else if (out == "moves") { textboard_to_hide = "moves"; moving_textboard_target_x = 0 - movement_board.GetSize().x - 20; } else if (out == "treasure") { textboard_to_hide = "treasure"; moving_textboard_target_x = 0 - treasure_board.GetSize().x - 20; } textboard_to_show = in; is_sliding_out = true; } //just one going out else if (in == "null" && out != "null") { //std::cout <<"JUST ONE OUT \n\n"; if (out == "combos") { textboard_to_hide = "combos"; moving_textboard_target_x = 0 - combos_board.GetSize().x - 20; } else if (out == "moves") { textboard_to_hide = "moves"; moving_textboard_target_x = 0 - movement_board.GetSize().x - 20; } else if (out == "treasure") { textboard_to_hide = "treasure"; moving_textboard_target_x = 0 - treasure_board.GetSize().x - 20; } textboard_to_show = "null"; is_sliding_out = true; } //just one going in else if (in != "null" && out == "null") { //std::cout <<"JUST ONE IN \n\n"; if (in == "combos") { textboard_to_show = "combos"; combos_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (in == "moves") { textboard_to_show = "moves"; movement_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } else if (in == "treasure") { textboard_to_show = "treasure"; treasure_board_state = "on"; moving_textboard_target_x = (float)(wptr->GetWidth() * 44) / 1920; } textboard_to_hide = "null"; is_sliding_out = false; } } void InterfaceManager::ShowNextTreasure() { if (!this->unlocked_treasures[3] && !this->unlocked_treasures[2] && !this->unlocked_treasures[1] && !this->unlocked_treasures[0]) { //show first treasure this->wptr->Draw(this->next_treasure[0]); this->wptr->Draw(this->next_treasure_info[0]); this->wptr->Draw(this->next_treasure_banner); } else if (!this->unlocked_treasures[3] && !this->unlocked_treasures[2] && !this->unlocked_treasures[1] && this->unlocked_treasures[0]) { //show second treasure this->wptr->Draw(this->next_treasure[1]); this->wptr->Draw(this->next_treasure_info[1]); this->wptr->Draw(this->next_treasure_banner); } else if (!this->unlocked_treasures[3] && !this->unlocked_treasures[2] && this->unlocked_treasures[1] && this->unlocked_treasures[0]) { //show third treasure this->wptr->Draw(this->next_treasure[2]); this->wptr->Draw(this->next_treasure_info[2]); this->wptr->Draw(this->next_treasure_banner); } else if (!this->unlocked_treasures[3] && this->unlocked_treasures[2] && this->unlocked_treasures[1] && this->unlocked_treasures[0]) { //show fourth treasure this->wptr->Draw(this->next_treasure[3]); this->wptr->Draw(this->next_treasure_info[3]); this->wptr->Draw(this->next_treasure_banner); } } void InterfaceManager::RetifyTextPositions() { demand_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - demand_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 688) / 1080); turn_points_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - turn_points_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 508) / 1080); total_points_info.SetPosition((float)((wptr->GetWidth() * 1670) / 1920) - total_points_info.GetRect().GetWidth()/2, (float)(wptr->GetHeight() * 896) / 1080); } void InterfaceManager::ResetFontSize() { this->match_amount_info.SetSize((float)this->original_font_size); this->match_points_info.SetSize((float)this->original_font_size); } void InterfaceManager::IncreaseFontSize() { if (this->match_amount_info.GetSize() < 68) { this->match_amount_info.SetSize((float)this->match_amount_info.GetSize() + 4); this->match_points_info.SetSize((float)this->match_points_info.GetSize() + 4); } } void InterfaceManager::UnlockTreasure(int id) { this->unlocked_treasures[id] = true; } void InterfaceManager::ResetSlidingConditions() { is_sliding_out = false; textboard_to_show = "null"; textboard_to_hide = "null"; combos_board_state = "off"; movement_board_state = "off"; treasure_board_state = "off"; combos_button_state = "off"; movement_button_state = "off"; treasure_button_state = "off"; treasure_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); treasuresboard_x = treasure_board.GetPosition().x; combos_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); combosboard_x = combos_board.GetPosition().x; movement_board.SetPosition((float)0 - combos_board.GetSize().x - 20, (float)(wptr->GetHeight() * 80) / 1080); movesboard_x = movement_board.GetPosition().x; } std::string InterfaceManager::ButtonInput(int game_state, int x, int y) { std::string response; if (game_state == 0) { if (x > play_button_normal.GetPosition().x && x < play_button_normal.GetPosition().x + play_button_normal.GetSize().x && y > play_button_normal.GetPosition().y && y < play_button_normal.GetPosition().y + play_button_normal.GetSize().y) response = "Play"; if (x > tutorial_button_normal.GetPosition().x && x < tutorial_button_normal.GetPosition().x + tutorial_button_normal.GetSize().x && y > tutorial_button_normal.GetPosition().y && y < tutorial_button_normal.GetPosition().y + tutorial_button_normal.GetSize().y) response = "Tutorial"; if (x > puzzle_button_normal.GetPosition().x && x < puzzle_button_normal.GetPosition().x + puzzle_button_normal.GetSize().x && y > puzzle_button_normal.GetPosition().y && y < puzzle_button_normal.GetPosition().y + puzzle_button_normal.GetSize().y) response = "Puzzle"; if (x > scores_button_normal.GetPosition().x && x < scores_button_normal.GetPosition().x + scores_button_normal.GetSize().x && y > scores_button_normal.GetPosition().y && y < scores_button_normal.GetPosition().y + scores_button_normal.GetSize().y) response = "Scores"; if (x > credits_button_normal.GetPosition().x && x < credits_button_normal.GetPosition().x + credits_button_normal.GetSize().x && y > credits_button_normal.GetPosition().y && y < credits_button_normal.GetPosition().y + credits_button_normal.GetSize().y) response = "Credits"; if (x > quit_button_normal.GetPosition().x && x < quit_button_normal.GetPosition().x + quit_button_normal.GetSize().x && y > quit_button_normal.GetPosition().y && y < quit_button_normal.GetPosition().y + quit_button_normal.GetSize().y) response = "Quit"; return response; } else if (game_state == 30) { if (x > new_button_normal.GetPosition().x && x < new_button_normal.GetPosition().x + new_button_normal.GetSize().x && y > new_button_normal.GetPosition().y && y < new_button_normal.GetPosition().y + new_button_normal.GetSize().y) response = "New"; if (x > resume_button_normal.GetPosition().x && x < resume_button_normal.GetPosition().x + resume_button_normal.GetSize().x && y > resume_button_normal.GetPosition().y && y < resume_button_normal.GetPosition().y + resume_button_normal.GetSize().y) response = "Resume"; if (x > back_button_normal.GetPosition().x && x < back_button_normal.GetPosition().x + back_button_normal.GetSize().x && y > back_button_normal.GetPosition().y && y < back_button_normal.GetPosition().y + back_button_normal.GetSize().y) response = "Back"; return response; } else if (game_state == 1) { if (x > combos_button_off.GetPosition().x && x < combos_button_off.GetPosition().x + combos_button_off.GetSize().x && y > combos_button_off.GetPosition().y && y < combos_button_off.GetPosition().y + combos_button_off.GetSize().y) { if (combos_button_state == "focused") { //ReloadBoard(1); //std::cout << "Combos button was clicked\n\n"; if (movement_board_state == "on") { //std::cout << "Movement textboard is on\n\n"; SetupTextboardTransition("combos", "moves"); } else if (treasure_board_state == "on") { //std::cout << "Treasure textboard is on\n\n"; SetupTextboardTransition("combos", "treasure"); } else if (combos_board_state == "off" && movement_board_state == "off" && treasure_board_state == "off") { //std::cout << "All textboards are off\n\n"; SetupTextboardTransition("combos", "null"); } //combos_board_state = "on"; combos_button_state = "on"; //movement_board_state = "off"; movement_button_state = "off"; //treasure_board_state = "off"; treasure_button_state = "off"; } else if (combos_button_state == "on") { combos_button_state = "off"; //combos_board_state = "off"; SetupTextboardTransition("null", "combos"); } } else if (x > movement_button_off.GetPosition().x && x < movement_button_off.GetPosition().x + movement_button_off.GetSize().x && y > movement_button_off.GetPosition().y && y < movement_button_off.GetPosition().y + movement_button_off.GetSize().y) { if (movement_button_state == "focused") { //ReloadBoard(0); //std::cout << "Movement button was clicked\n\n"; if (combos_board_state == "on") { //std::cout << "Combos textboard is on\n\n"; SetupTextboardTransition("moves", "combos"); } else if (treasure_board_state == "on") { //std::cout << "Treasure textboard is on\n\n"; SetupTextboardTransition("moves", "treasure"); } else if (movement_board_state == "off" && combos_board_state == "off" && treasure_board_state == "off") { //std::cout << "All textboards are off\n\n"; SetupTextboardTransition("moves", "null"); } movement_button_state = "on"; //movement_board_state = "on"; //combos_board_state = "off"; combos_button_state = "off"; //treasure_board_state = "off"; treasure_button_state = "off"; } else if (movement_button_state == "on") { movement_button_state = "off"; //movement_board_state = "off"; SetupTextboardTransition("null", "moves"); } } else if (x > treasure_button_off.GetPosition().x && x < treasure_button_off.GetPosition().x + treasure_button_off.GetSize().x && y > treasure_button_off.GetPosition().y && y < treasure_button_off.GetPosition().y + treasure_button_off.GetSize().y) { if (treasure_button_state == "focused") { //ReloadBoard(2); if (combos_board_state == "on") { SetupTextboardTransition("treasure", "combos"); } else if (movement_board_state == "on") { SetupTextboardTransition("treasure", "moves"); } else if (treasure_board_state == "off" && combos_board_state == "off" && movement_board_state == "off") { SetupTextboardTransition("treasure", "null"); } treasure_button_state = "on"; //treasure_board_state = "on"; movement_button_state = "off"; //movement_board_state = "off"; //combos_board_state = "off"; combos_button_state = "off"; } else if (treasure_button_state == "on") { treasure_button_state = "off"; //treasure_board_state = "off"; SetupTextboardTransition("null", "treasure"); } } return "Null"; } } void InterfaceManager::ResetTreasures() { for (int i = 0; i < 4; i++) { this->unlocked_treasures[i] = false; } this->SetupTreasureImagesForNewLevel(); } void InterfaceManager::LoadSavedTreasures(int t1, int t2, int t3, int t4) { if (t1 == 1) this->unlocked_treasures[0] = true; if (t2 == 1) this->unlocked_treasures[1] = true; if (t3 == 1) this->unlocked_treasures[2] = true; if (t4 == 1) this->unlocked_treasures[3] = true; } void InterfaceManager::ReloadBoard(int brd) { if (brd == 2) { treasure_board.SetImage(resource_manager->OnDemandLoadForBoards(2)); treasure_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); treasure_board.SetPosition((float)(wptr->GetWidth() * 44) / 1920, (float)(wptr->GetHeight() * 80) / 1080); } else if (brd == 0) { movement_board.SetImage(resource_manager->OnDemandLoadForBoards(0)); movement_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); movement_board.SetPosition((float)(wptr->GetWidth() * 44) / 1920, (float)(wptr->GetHeight() * 80) / 1080); } else if (brd == 1) { combos_board.SetImage(resource_manager->OnDemandLoadForBoards(1)); combos_board.Resize((float)(483 * wptr->GetWidth())/1920, (float)(809 * wptr->GetHeight())/1080); combos_board.SetPosition((float)(wptr->GetWidth() * 44) / 1920, (float)(wptr->GetHeight() * 80) / 1080); } } void InterfaceManager::HandleGameButtons(int game_state) { int x = wptr->GetInput().GetMouseX(); int y = wptr->GetInput().GetMouseY(); if (combos_button_state == "off") this->wptr->Draw(combos_button_off); else if (combos_button_state == "on") this->wptr->Draw(combos_button_on); else if (combos_button_state == "focused") this->wptr->Draw(combos_button_focus); if (movement_button_state == "off") this->wptr->Draw(movement_button_off); else if (movement_button_state == "on") this->wptr->Draw(movement_button_on); else if (movement_button_state == "focused") this->wptr->Draw(movement_button_focus); if (treasure_button_state == "off") this->wptr->Draw(treasure_button_off); else if (treasure_button_state == "on") this->wptr->Draw(treasure_button_on); else if (treasure_button_state == "focused") this->wptr->Draw(treasure_button_focus); if (game_state == 1) //show textboards only when the player has control over the board { if (combos_board_state == "on") this->wptr->Draw(combos_board); if (movement_board_state == "on") this->wptr->Draw(movement_board); if (treasure_board_state == "on") { this->wptr->Draw(treasure_board); if (!is_sliding_out && treasure_board.GetPosition().x >= moving_textboard_target_x) { for (int i = 0; i < 4; i++) { if (this->unlocked_treasures[i]) this->wptr->Draw(this->treasure[i]); else this->wptr->Draw(this->treasure_shadow[i]); } } } } if (x > combos_button_off.GetPosition().x && x < combos_button_off.GetPosition().x + combos_button_off.GetSize().x && y > combos_button_off.GetPosition().y && y < combos_button_off.GetPosition().y + combos_button_off.GetSize().y) { if (combos_button_state == "off") combos_button_state = "focused"; } else { if (combos_button_state == "focused") combos_button_state = "off"; } if (x > movement_button_off.GetPosition().x && x < movement_button_off.GetPosition().x + movement_button_off.GetSize().x && y > movement_button_off.GetPosition().y && y < movement_button_off.GetPosition().y + movement_button_off.GetSize().y) { if (movement_button_state == "off") movement_button_state = "focused"; } else { if (movement_button_state == "focused") movement_button_state = "off"; } if (x > treasure_button_off.GetPosition().x && x < treasure_button_off.GetPosition().x + treasure_button_off.GetSize().x && y > treasure_button_off.GetPosition().y && y < treasure_button_off.GetPosition().y + treasure_button_off.GetSize().y) { if (treasure_button_state == "off") treasure_button_state = "focused"; } else { if (treasure_button_state == "focused") treasure_button_state = "off"; } this->PerformTextboardSlide(); } void InterfaceManager::HandleMainMenuButtons(int screenId) { int x = wptr->GetInput().GetMouseX(); int y = wptr->GetInput().GetMouseY(); if (screenId == 0) // Main Menu { if (x > play_button_normal.GetPosition().x && x < play_button_normal.GetPosition().x + play_button_normal.GetSize().x && y > play_button_normal.GetPosition().y && y < play_button_normal.GetPosition().y + play_button_normal.GetSize().y) wptr->Draw(play_button_focus); else wptr->Draw(play_button_normal); if (x > tutorial_button_normal.GetPosition().x && x < tutorial_button_normal.GetPosition().x + tutorial_button_normal.GetSize().x && y > tutorial_button_normal.GetPosition().y && y < tutorial_button_normal.GetPosition().y + tutorial_button_normal.GetSize().y) wptr->Draw(tutorial_button_focus); else wptr->Draw(tutorial_button_normal); if (x > puzzle_button_normal.GetPosition().x && x < puzzle_button_normal.GetPosition().x + puzzle_button_normal.GetSize().x && y > puzzle_button_normal.GetPosition().y && y < puzzle_button_normal.GetPosition().y + puzzle_button_normal.GetSize().y) wptr->Draw(puzzle_button_focus); else wptr->Draw(puzzle_button_normal); if (x > scores_button_normal.GetPosition().x && x < scores_button_normal.GetPosition().x + scores_button_normal.GetSize().x && y > scores_button_normal.GetPosition().y && y < scores_button_normal.GetPosition().y + scores_button_normal.GetSize().y) wptr->Draw(scores_button_focus); else wptr->Draw(scores_button_normal); if (x > credits_button_normal.GetPosition().x && x < credits_button_normal.GetPosition().x + credits_button_normal.GetSize().x && y > credits_button_normal.GetPosition().y && y < credits_button_normal.GetPosition().y + credits_button_normal.GetSize().y) wptr->Draw(credits_button_focus); else wptr->Draw(credits_button_normal); if (x > quit_button_normal.GetPosition().x && x < quit_button_normal.GetPosition().x + quit_button_normal.GetSize().x && y > quit_button_normal.GetPosition().y && y < quit_button_normal.GetPosition().y + quit_button_normal.GetSize().y) wptr->Draw(quit_button_focus); else wptr->Draw(quit_button_normal); } else if (screenId == 1) //New or Resume selection submenu { if (x > new_button_normal.GetPosition().x && x < new_button_normal.GetPosition().x + new_button_normal.GetSize().x && y > new_button_normal.GetPosition().y && y < new_button_normal.GetPosition().y + new_button_normal.GetSize().y) wptr->Draw(new_button_focus); else wptr->Draw(new_button_normal); if (x > resume_button_normal.GetPosition().x && x < resume_button_normal.GetPosition().x + resume_button_normal.GetSize().x && y > resume_button_normal.GetPosition().y && y < resume_button_normal.GetPosition().y + resume_button_normal.GetSize().y) wptr->Draw(resume_button_focus); else wptr->Draw(resume_button_normal); if (x > back_button_normal.GetPosition().x && x < back_button_normal.GetPosition().x + back_button_normal.GetSize().x && y > back_button_normal.GetPosition().y && y < back_button_normal.GetPosition().y + back_button_normal.GetSize().y) wptr->Draw(back_button_focus); else wptr->Draw(back_button_normal); } } void InterfaceManager::SetupScoreUpdate(int tScore, int mode, bool remainder) { if (mode == 0) //Add turn points { targetScore = tScore + currentScore; isIncreasingScore = true; isDecreasingScore = false; isAnimating = true; positive_score_animation_frame = 0; positive_score_animation_timer.Reset(); } else if (mode == 1) //Decrease demand { targetScore = currentScore - 100; isIncreasingScore = false; isDecreasingScore = false; isAnimating = true; demand_animation_timer.Reset(); demand_animation_frame = 0; hasEndTimerStarted = false; } else if (mode == 2) { isIncreasingScore = false; isDecreasingScore = true; targetScore = 0; isAnimating = true; positive_score_animation_frame = 0; positive_score_animation_timer.Reset(); hasPositiveRemainder = remainder; } scoreUpdateTimer.Reset(); } void InterfaceManager::UpdateScore(int mode) { if (mode == 0) //Add turn points { if (scoreUpdateTimer.GetElapsedTime() >= 0.0001f && isIncreasingScore) { currentScore++; std::stringstream out; out << currentScore; this->turn_points_info.SetText(out.str()); if (currentScore >= targetScore) { isIncreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } currentScore++; std::stringstream out2; out2 << currentScore; this->turn_points_info.SetText(out2.str()); if (currentScore >= targetScore) { isIncreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } if (isAnimating) { if (positive_score_animation_timer.GetElapsedTime() >= 0.04f) { if (positive_score_animation_frame < 24) { positive_score_animation_frame++; positive_score_animation_timer.Reset(); } else { isAnimating = false; } } } } else if (mode == 1) //Decrease demand { if (scoreUpdateTimer.GetElapsedTime() >= 0.01f && isDecreasingScore) { currentScore--; std::stringstream out; out << currentScore; this->turn_points_info.SetText(out.str()); if (currentScore <= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } if (isAnimating) { if (demand_animation_timer.GetElapsedTime() >= 0.04f) { if (demand_animation_frame < 22) { demand_animation_frame++; demand_animation_timer.Reset(); if (demand_animation_frame >= 10 && isDecreasingScore == false) isDecreasingScore = true; } else { isAnimating = false; } } } } else if (mode == 2) //Total calculation { if (scoreUpdateTimer.GetElapsedTime() >= 0.01f && isDecreasingScore) { if (hasPositiveRemainder) { currentScore--; std::stringstream out; out << currentScore; this->turn_points_info.SetText(out.str()); currentTotalScore++; std::stringstream out2; out2 << currentTotalScore; this->total_points_info.SetText(out2.str()); if (currentScore <= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } currentScore--; std::stringstream out3; out3 << currentScore; this->turn_points_info.SetText(out3.str()); currentTotalScore++; std::stringstream out4; out4 << currentTotalScore; this->total_points_info.SetText(out4.str()); if (currentScore <= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } else { if(currentScore != 0) { currentScore++; std::stringstream out5; out5 << currentScore; this->turn_points_info.SetText(out5.str()); currentTotalScore--; std::stringstream out6; out6 << currentTotalScore; this->total_points_info.SetText(out6.str()); } if (currentScore >= targetScore) { isDecreasingScore = false; return; } else { scoreUpdateTimer.Reset(); } } } if (isAnimating) { if (hasPositiveRemainder) { if (positive_score_animation_timer.GetElapsedTime() >= 0.04f) { if (positive_score_animation_frame < 24) { positive_score_animation_frame++; positive_score_animation_timer.Reset(); } else { isAnimating = false; } } } else { if (positive_score_animation_timer.GetElapsedTime() >= 0.04f) { if (positive_score_animation_frame < 20) { positive_score_animation_frame++; positive_score_animation_timer.Reset(); } else { isAnimating = false; } } } } } }
49.861827
181
0.699439
cjcoimbra
cc13b6f40f01be7581c398fa6c6a3e5ee89f7824
20,483
cpp
C++
pin/contech_fe.cpp
Ridhii/SyncdSim
4cd120e9f7d4db348d405db4608ef9c6f9499d01
[ "BSD-3-Clause" ]
50
2015-10-21T23:16:35.000Z
2021-09-27T12:52:04.000Z
pin/contech_fe.cpp
Ridhii/SyncdSim
4cd120e9f7d4db348d405db4608ef9c6f9499d01
[ "BSD-3-Clause" ]
187
2015-01-08T22:24:54.000Z
2020-04-17T17:23:50.000Z
pin/contech_fe.cpp
Ridhii/SyncdSim
4cd120e9f7d4db348d405db4608ef9c6f9499d01
[ "BSD-3-Clause" ]
25
2015-11-02T17:54:49.000Z
2020-06-16T07:28:11.000Z
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation 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 INTEL OR ITS 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. END_LEGAL */ /* * Sample buffering tool * * This tool collects an address trace of instructions that access memory * by filling a buffer. When the buffer overflows,the callback writes all * of the collected records to a file. * */ #include <iostream> #include <fstream> #include <stdlib.h> #include <stddef.h> #include <map> #include <vector> #include <sys/timeb.h> #include <sys/sysinfo.h> #include "pin.H" #include "portability.H" using namespace std; /* * Name of the output file */ KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "buffer.out", "output file"); /* * The ID of the buffer */ BUFFER_ID bufId; REG scratch_reg0; /* * Number of OS pages for the buffer */ #define NUM_BUF_PAGES 1024 struct BASICBLOCK { UINT32 id; }; struct MEMREF { ADDRINT ea; UINT32 size; BOOL read; }; struct MEMMGMT { UINT32 type; UINT32 size; }; struct TASK { UINT32 type; UINT32 data; }; enum event_type { ct_event_basic_block = 0, ct_event_memory_op, ct_event_memory, ct_event_task }; struct EVENT { //UINT32 type; union { BASICBLOCK bb; ADDRINT mem; MEMMGMT mgmt; TASK task; }; }; // Compressed form for serialization // Borrowed from contech struct memOp { union { struct { uint64_t is_write : 1; uint64_t pow_size : 3; // the size of the op is 2^pow_size uint64_t addr : 58; }; uint64_t data; char data8[8]; }; }; UINT32 nextBBId = 0; map<UINT32, vector<MEMREF> > blockMap; struct ThreadBufferWrapper { VOID* buf; THREADID tid; UINT64 elemCount; ThreadBufferWrapper* next; }; PIN_MUTEX QueueBufferLock; PIN_MUTEX ThreadIDLock; PIN_SEMAPHORE BufferQueueSignal; ThreadBufferWrapper* BufferHead = NULL; ThreadBufferWrapper* BufferTail = NULL; UINT32 runningThreadCount = 0; UINT32 exitThreadCount = 0; UINT32 ticketNumber = 0; struct timeb starttp; struct timeb endtp; static void InternalThreadMain(void* v); #if defined(TARGET_MAC) #define MALLOC "_malloc" #define FREE "_free" #else #define MALLOC "malloc" #define FREE "free" #define SYNC "pthread_mutex_lock" #define CREATE "pthread_create" #define JOIN "pthread_join" #endif /************************************************************************** * * Instrumentation routines * **************************************************************************/ /* * Insert code to write data to a thread-specific buffer for instructions * that access memory. */ VOID Trace(TRACE trace, VOID *v) { for(BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl=BBL_Next(bbl)) { INS iPoint = BBL_InsHead(bbl); vector<MEMREF> bbMemOps; UINT32 bbId = ~0x0; for(INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins=INS_Next(ins)) { string fnName = RTN_FindNameByAddress(BBL_Address(bbl)); if (fnName == MALLOC) {continue;} if (fnName == FREE) {continue;} // Insert BBL buffer fill before first instruction if (ins == BBL_InsHead(bbl)) { iPoint = ins; // BBL_Address is not unique //bbId = (UINT32) BBL_Address(bbl); bbId = nextBBId++; map<UINT32, vector<MEMREF> >::iterator it = blockMap.find(bbId); if (it != blockMap.end()) { // bbId is already a basic block do { bbId += 0x0100000000; cerr << "BBID now " << bbId << endl; return; } while ((it = blockMap.find(bbId)) != blockMap.end()); } INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, //IARG_UINT32, ct_event_basic_block, offsetof(EVENT, type), IARG_UINT32, bbId, offsetof(EVENT, bb.id), IARG_END); } UINT32 memoryOperands = INS_MemoryOperandCount(ins); for (UINT32 memOp = 0; memOp < memoryOperands; memOp++) { UINT32 refSize = INS_MemoryOperandSize(ins, memOp); MEMREF currMemOp; // // Add record for bbId that it has memoryOperands, each of the following properties // // Note that if the operand is both read and written we log it once // for each. if (INS_MemoryOperandIsRead(ins, memOp)) { INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, //IARG_UINT32, ct_event_memory_op, offsetof(EVENT, type), IARG_MEMORYOP_EA, memOp, offsetof(EVENT, mem), //IARG_UINT32, refSize, offsetof(EVENT, mem.size), //IARG_BOOL, TRUE, offsetof(EVENT, mem.read), IARG_END); currMemOp.size = refSize; currMemOp.read = TRUE; } if (INS_MemoryOperandIsWritten(ins, memOp)) { INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, //IARG_UINT32, ct_event_memory_op, offsetof(EVENT, type), IARG_MEMORYOP_EA, memOp, offsetof(EVENT, mem), //mem.ea //IARG_UINT32, refSize, offsetof(EVENT, mem.size), //IARG_BOOL, FALSE, offsetof(EVENT, mem.read), IARG_END); currMemOp.size = refSize; currMemOp.read = FALSE; } bbMemOps.push_back(currMemOp); } } if (bbId != (~ (UINT32)0x0)) blockMap[bbId] = bbMemOps; } } VOID MallocBefore(CHAR * name, ADDRINT size) { } VOID MallocAfter(ADDRINT ret) { } UINT32 GetTicketNumber() { return __sync_fetch_and_add( &ticketNumber, 1); } VOID Image(IMG img, VOID *v) { // Instrument the malloc() and free() functions. Print the input argument // of each malloc() or free(), and the return value of malloc(). // // Find the malloc() function. RTN mallocRtn = RTN_FindByName(img, MALLOC); if (RTN_Valid(mallocRtn)) { RTN_Open(mallocRtn); INS ins = RTN_InsHeadOnly(mallocRtn); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_memory, offsetof(EVENT, mgmt.type), IARG_FUNCARG_ENTRYPOINT_VALUE, 0, offsetof(EVENT, mgmt.size), IARG_END); // Instrument malloc() to print the input argument value and the return value. RTN_InsertCall(mallocRtn, IPOINT_BEFORE, (AFUNPTR)MallocBefore, IARG_ADDRINT, MALLOC, IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END); RTN_InsertCall(mallocRtn, IPOINT_AFTER, (AFUNPTR)MallocAfter, IARG_FUNCRET_EXITPOINT_VALUE, IARG_END); RTN_Close(mallocRtn); } // Find the free() function. RTN freeRtn = RTN_FindByName(img, FREE); if (RTN_Valid(freeRtn)) { RTN_Open(freeRtn); // Instrument free() to print the input argument value. INS ins = RTN_InsHeadOnly(freeRtn); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_memory, offsetof(EVENT, mgmt.type), IARG_FUNCARG_ENTRYPOINT_VALUE, 0, offsetof(EVENT, mgmt.size), // hmm IARG_END); RTN_InsertCall(freeRtn, IPOINT_BEFORE, (AFUNPTR)MallocBefore, IARG_ADDRINT, FREE, IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END); RTN_InsertCall(freeRtn, IPOINT_AFTER, (AFUNPTR)MallocAfter, IARG_FUNCRET_EXITPOINT_VALUE, IARG_END); RTN_Close(freeRtn); } RTN syncRtn = RTN_FindByName(img, SYNC); if (RTN_Valid(syncRtn)) { RTN_Open(syncRtn); INS ins = RTN_InsHeadOnly(syncRtn); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_task, offsetof(EVENT, task.type), IARG_THREAD_ID, offsetof(EVENT, task.data), IARG_END); //scratch_reg0 INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)GetTicketNumber, IARG_RETURN_REGS, scratch_reg0, IARG_END); // Overload an event with additional data on the sync INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_REG_VALUE, scratch_reg0, offsetof(EVENT, task.type), IARG_TSC, offsetof(EVENT, mgmt.size), IARG_END); RTN_Close(syncRtn); } RTN createRtn = RTN_FindByName(img, CREATE); if (RTN_Valid(createRtn)) { RTN_Open(createRtn); INS ins = RTN_InsHeadOnly(createRtn); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_task, offsetof(EVENT, task.type), IARG_THREAD_ID, offsetof(EVENT, task.data), IARG_END); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_task, offsetof(EVENT, task.type), IARG_TSC, offsetof(EVENT, mgmt.size), IARG_END); RTN_Close(createRtn); } RTN joinRtn = RTN_FindByName(img, JOIN); if (RTN_Valid(joinRtn)) { RTN_Open(joinRtn); INS ins = RTN_InsHeadOnly(joinRtn); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_task, offsetof(EVENT, task.type), IARG_THREAD_ID, offsetof(EVENT, task.data), IARG_END); INS_InsertFillBuffer(ins, IPOINT_BEFORE, bufId, IARG_UINT32, ct_event_task, offsetof(EVENT, task.type), IARG_TSC, offsetof(EVENT, mgmt.size), IARG_END); RTN_Close(joinRtn); } } /************************************************************************** * * Callback Routines * **************************************************************************/ /*! * Called when a buffer fills up, or the thread exits, so we can process it or pass it off * as we see fit. * @param[in] id buffer handle * @param[in] tid id of owning thread * @param[in] ctxt application context * @param[in] buf actual pointer to buffer * @param[in] numElements number of records * @param[in] v callback value * @return A pointer to the buffer to resume filling. */ VOID * BufferFull(BUFFER_ID id, THREADID tid, const CONTEXT *ctxt, VOID *buf, UINT64 numElements, VOID *v) { VOID* r = NULL; ThreadBufferWrapper* tbw = (ThreadBufferWrapper*) malloc(sizeof(ThreadBufferWrapper)); tbw->tid = tid; tbw->elemCount = numElements; tbw->buf = buf; tbw->next = NULL; // cerr << "Thread " << tid << ": Dumping " << numElements << " memops" << endl; PIN_MutexLock(&QueueBufferLock); //cerr << buf << ", " << numElements << endl; if (BufferHead == NULL) { BufferHead = tbw; BufferTail = tbw; PIN_SemaphoreSet(&BufferQueueSignal); } else { BufferTail->next = tbw; BufferTail = tbw; //cerr << "Head next - " << BufferHead->next->buf << endl; } PIN_MutexUnlock(&QueueBufferLock); do { r = PIN_AllocateBuffer(bufId); } while (r == NULL); return r; } VOID ThreadStart(THREADID tid, CONTEXT *ctxt, INT32 flags, VOID *v) { PIN_MutexLock(&ThreadIDLock); runningThreadCount++; PIN_MutexUnlock(&ThreadIDLock); } VOID ThreadFini(THREADID tid, const CONTEXT *ctxt, INT32 code, VOID *v) { struct timeb tp; { ftime(&tp); //cerr << tp.time << "." << tp.millitm << "\n"; LOG("PIN_END: " + decstr((unsigned int)tp.time) + "." + decstr(tp.millitm) + "\n"); } PIN_MutexLock(&ThreadIDLock); exitThreadCount++; endtp = tp; // memcpy, implicitly PIN_MutexUnlock(&ThreadIDLock); } /* ===================================================================== */ /* Print Help Message */ /* ===================================================================== */ INT32 Usage() { cerr << "Experimental Pin Frontend for the Contech framework." << endl; cerr << endl << KNOB_BASE::StringKnobSummary() << endl; return -1; } void InternalThreadMain(void* v) { char* fname = getenv("CONTECH_FE_FILE"); FILE* ofile; UINT64 totalBytes = 0; UINT32 rdBytes = 1024; if (fname == NULL) { ofile = fopen("/tmp/contech.trace", "w"); } else { ofile = fopen(fname, "w"); } if ( ! ofile ) { cerr << "Error: could not open output file." << endl; exit(1); } // ThreadIDLock is carried over in the while condition PIN_MutexLock(&ThreadIDLock); do { PIN_MutexUnlock(&ThreadIDLock); // While there are no queued buffers, wait PIN_MutexLock(&QueueBufferLock); while (BufferHead == NULL) { PIN_MutexUnlock(&QueueBufferLock); PIN_SemaphoreWait(&BufferQueueSignal); PIN_MutexLock(&QueueBufferLock); } // tbw is the wrapper for the current head of the queue ThreadBufferWrapper* tbw = BufferHead; PIN_MutexUnlock(&QueueBufferLock); while (tbw != NULL) { UINT32 chksum = 0; UINT32* b = (UINT32*) tbw->buf; UINT32 numBytes = sizeof(EVENT) * tbw->elemCount ; totalBytes += (UINT64) numBytes; //cerr << ", " << tbw->buf << ", " << tbw->elemCount << "\n"; // WRITE DATA TO FILE HERE // Even computing a checksum results in a buffer backlog and termination if (numBytes > rdBytes) numBytes = rdBytes; for (UINT32 i = 0; i < numBytes; i += 4) { chksum = chksum ^ *b; b++; } rdBytes = rdBytes >> 1; fwrite(&chksum, sizeof(chksum), 1, ofile); // We could use the more complex Contech buffer management, which // maintains a list of pre-allocated buffers; // However, the savings should be minimal // Contech uses ~5% time to manage buffers, since buffer creation is // much higher than deletion, Deallocate probably models this more // accurately when there is no delay writing data to disk PIN_DeallocateBuffer(bufId, tbw->buf); PIN_MutexLock(&QueueBufferLock); ThreadBufferWrapper* tNext = tbw->next; BufferHead = tNext; if (BufferHead == NULL) {BufferTail = NULL;} PIN_MutexUnlock(&QueueBufferLock); free(tbw); tbw = tNext; } PIN_MutexLock(&ThreadIDLock); // Contech switches exit() to pthread_exit() // This may result in a Contech instrumented program executing longer than pin } while (runningThreadCount != exitThreadCount); // Test for threads exiting { cerr << "CT_END: " << endtp.time << "." << endtp.millitm << "\n"; if (endtp.millitm < starttp.millitm) { endtp.millitm += 1000; endtp.time -= 1; } cerr << "CT_DELTA: " << (endtp.time - starttp.time) << "." << (endtp.millitm - starttp.millitm) << "\n"; cerr << "CT_DATA: " << totalBytes << "\n"; } { struct timeb tp; ftime(&tp); cerr << "CT_FLUSH: " << tp.time << "." << tp.millitm << "\n"; } fclose(ofile); } /* ===================================================================== */ /* Main */ /* ===================================================================== */ /*! * The main procedure of the tool. * This function is called when the application image is loaded but not yet started. * @param[in] argc total number of elements in the argv array * @param[in] argv array of command line arguments, * including pin -t <toolname> -- ... */ int main(int argc, char *argv[]) { // Initialize PIN library. Print help message if -h(elp) is specified // in the command line or the command line is invalid if( PIN_Init(argc,argv) ) { return Usage(); } // Initialize the memory reference buffer; // set up the callback to process the buffer. // bufId = PIN_DefineTraceBuffer(sizeof(EVENT), NUM_BUF_PAGES, BufferFull, 0); if(bufId == BUFFER_ID_INVALID) { cerr << "Error: could not allocate initial buffer" << endl; return 1; } // add an instrumentation function TRACE_AddInstrumentFunction(Trace, 0); //IMG_AddInstrumentFunction(Image, 0); // add callbacks PIN_AddThreadStartFunction(ThreadStart, 0); PIN_AddThreadFiniFunction(ThreadFini, 0); PIN_MutexInit(&QueueBufferLock); PIN_MutexInit(&ThreadIDLock); PIN_SemaphoreInit(&BufferQueueSignal); if (PIN_SpawnInternalThread(InternalThreadMain, NULL, 0, NULL) == INVALID_THREADID) { fprintf(stderr, "TOOL: <%d> Unable to spawn internal thread. Killing the test!\n", PIN_GetTid()); fflush(stderr); PIN_ExitProcess(101); } { struct timeb tp; ftime(&tp); starttp = tp; cerr << "CT_START: " << tp.time << "." << tp.millitm << "\n"; } // Start the program, never returns PIN_StartProgram(); return 0; }
32.307571
112
0.542694
Ridhii
cc152ed8c9aee502fdebf84cfb612afa33c1e52a
945
hh
C++
gazebo/physics/roki/RokiFixedJoint.hh
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/physics/roki/RokiFixedJoint.hh
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/physics/roki/RokiFixedJoint.hh
nyxrobotics/gazebo
4a9b733a8af9a13cd7f3b23d5414d322a3666a55
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#ifndef _ROKIFIXEDJOINT_HH_ #define _ROKIFIXEDJOINT_HH_ #include "ignition/math/Angle.hh" #include "ignition/math/Vector3.hh" #include "gazebo/util/system.hh" #include "gazebo/physics/FixedJoint.hh" #include "gazebo/physics/roki/RokiJoint.hh" namespace gazebo { namespace physics { class GZ_PHYSICS_VISIBLE RokiFixedJoint : public FixedJoint<RokiJoint> { public: explicit RokiFixedJoint(BasePtr _parent); public: virtual ~RokiFixedJoint(); public: virtual void Load(sdf::ElementPtr _sdf); public: virtual void Init(); public: virtual double PositionImpl(const unsigned int _index) const; public: virtual void SetVelocity(unsigned int _index, double _vel); public: virtual double GetVelocity(unsigned int _index) const; protected: virtual void SetForceImpl(unsigned int _index, double _effort); protected: virtual double GetForceImpl(unsigned int _index); }; } } #endif
30.483871
80
0.740741
nyxrobotics
cc166ece701763a5e7c27fc9148c3d08a7771ced
618
cpp
C++
src/util/timestamp.cpp
CGCL-codes/FJoin
cd3ace4bfbb66686535963415bfaa3792f7de822
[ "MIT" ]
3
2021-10-31T12:38:22.000Z
2021-12-20T08:56:25.000Z
src/util/timestamp.cpp
chenhanhua/FJoin
cd3ace4bfbb66686535963415bfaa3792f7de822
[ "MIT" ]
null
null
null
src/util/timestamp.cpp
chenhanhua/FJoin
cd3ace4bfbb66686535963415bfaa3792f7de822
[ "MIT" ]
1
2021-11-25T10:02:15.000Z
2021-11-25T10:02:15.000Z
#ifndef __TIMER__ #define __TIMER__ #include"../head.hpp" std::string get_date_ts() { struct tm *timeinfo; time_t rawtime; char *time_buf; time(&rawtime); timeinfo = localtime(&rawtime); time_buf = asctime(timeinfo); std::string ret(time_buf); if (!ret.empty() && ret[ret.length() - 1] == '\n') { ret.erase(ret.length()-1); } return (ret); } long long get_ts() { time_t t= time(NULL); struct timeval tv; gettimeofday(&tv,NULL); return ((long long)(t * 1000) + (long long)(tv.tv_usec >> 10));//返回近似毫秒时间戳 } #endif
19.935484
79
0.563107
CGCL-codes
cc1d8404cce1393b8064f3f064102a54d8cdc892
844
hpp
C++
ltl2fsm/base/exception/Invalid_Vertex_Name.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
2
2016-11-23T14:31:55.000Z
2018-05-10T01:11:54.000Z
ltl2fsm/base/exception/Invalid_Vertex_Name.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
ltl2fsm/base/exception/Invalid_Vertex_Name.hpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
/** * @file ltl2fsm/base/exception/Invalid_Vertex_Name.hpp * * $Id$ * * @author Oliver Arafat * * @brief @ref * * @note DOCUMENTED * * @test * * @todo */ #ifndef LTL2FSM__BASE__EXCEPTION__INVALID_VERTEX_NAME__HPP #define LTL2FSM__BASE__EXCEPTION__INVALID_VERTEX_NAME__HPP #include<ltl2fsm/base/exception/Exception.hpp> LTL2FSM__BEGIN__NAMESPACE__LTL2FSM; class Invalid_Vertex_Name : public Exception { //////////////////////////////////////////////////////////////////////////////// /** * @name Construction / Destruction * @{ */ public: Invalid_Vertex_Name(Source_Location const & source_location, ::std::string const & what); virtual ~Invalid_Vertex_Name() throw(); // @} public: virtual char const * class_name() const; }; LTL2FSM__END__NAMESPACE__LTL2FSM; #endif
16.88
84
0.627962
arafato
cc1fbd9849223de739927cfa2f2d8b36cebd54ff
5,367
cpp
C++
src/dispatcher.cpp
ornl-epics/epicsipmi
788bf6a815e2c0c3a17df219a5becf7f9a376d65
[ "BSD-3-Clause" ]
1
2019-11-15T08:21:52.000Z
2019-11-15T08:21:52.000Z
src/dispatcher.cpp
ornl-epics/epicsipmi
788bf6a815e2c0c3a17df219a5becf7f9a376d65
[ "BSD-3-Clause" ]
1
2020-11-09T17:48:19.000Z
2020-11-11T17:41:09.000Z
src/dispatcher.cpp
klemenv/epicsipmi
05daec62f5bb003361836708a348e13cea0b9474
[ "BSD-3-Clause" ]
null
null
null
/* dispatcher.cpp * * Copyright (c) 2018 Oak Ridge National Laboratory. * All rights reserved. * See file LICENSE that is included with this distribution. * * @author Klemen Vodopivec * @date Oct 2018 */ #include "common.h" #include "freeipmiprovider.h" #include "print.h" #include "dispatcher.h" #include <cstring> #include <map> #include <string> // EPICS records that we support #include <aiRecord.h> #include <stringinRecord.h> namespace dispatcher { static std::map<std::string, std::shared_ptr<FreeIpmiProvider>> g_connections; //!< Global map of connections. static epicsMutex g_mutex; //!< Global mutex to protect g_connections. static std::pair<std::string, std::string> _parseLink(const std::string& link) { auto tokens = common::split(link, ' ', 2); if (tokens.size() < 3 || tokens[0] != "ipmi") return std::make_pair(std::string(""), std::string("")); return std::make_pair(tokens[1], tokens[2]); } static std::string _createLink(const std::string& conn_id, const std::string& addr) { return "@ipmi " + conn_id + " " + addr; } static std::shared_ptr<FreeIpmiProvider> _getConnection(const std::string& conn_id) { common::ScopedLock lock(g_mutex); auto it = g_connections.find(conn_id); if (it != g_connections.end()) return it->second; return nullptr; } bool connect(const std::string& conn_id, const std::string& hostname, const std::string& username, const std::string& password, const std::string& authtype, const std::string& protocol, const std::string& privlevel) { common::ScopedLock lock(g_mutex); if (g_connections.find(conn_id) != g_connections.end()) return false; std::shared_ptr<FreeIpmiProvider> conn; try { conn.reset(new FreeIpmiProvider(conn_id, hostname, username, password, authtype, protocol, privlevel)); } catch (std::bad_alloc& e) { LOG_ERROR("can't allocate FreeIPMI provider\n"); return false; } catch (std::runtime_error& e) { if (username.empty()) LOG_ERROR("can't connect to %s - %s", hostname.c_str(), e.what()); else LOG_ERROR("can't connect to %s as user %s - %s", hostname.c_str(), username.c_str(), e.what()); return false; } g_connections[conn_id] = conn; return true; } void scan(const std::string& conn_id, const std::vector<EntityType>& types) { g_mutex.lock(); auto it = g_connections.find(conn_id); bool found = (it != g_connections.end()); g_mutex.unlock(); if (!found) { LOG_ERROR("no such connection " + conn_id); return; } auto conn = it->second; for (auto& type: types) { try { std::vector<Provider::Entity> entities; std::string header; if (type == EntityType::SENSOR) { entities = conn->getSensors(); header = "Sensors:"; } else if (type == EntityType::FRU) { entities = conn->getFrus(); header = "FRUs:"; } else if (type == EntityType::PICMG_LED) { entities = conn->getPicmgLeds(); header = "PICMG LEDs:"; } print::printScanReport(header, entities); } catch (std::runtime_error& e) { LOG_ERROR(e.what()); } } } void printDb(const std::string& conn_id, const std::string& path, const std::string& pv_prefix) { g_mutex.lock(); auto it = g_connections.find(conn_id); bool found = (it != g_connections.end()); g_mutex.unlock(); if (!found) { LOG_ERROR("no such connection " + conn_id); return; } auto conn = it->second; FILE *dbfile = fopen(path.c_str(), "w+"); if (dbfile == nullptr) LOG_ERROR("Failed to open output database file - %s", strerror(errno)); try { auto sensors = conn->getSensors(); for (auto& sensor: sensors) { auto inp = sensor.getField<std::string>("INP", ""); if (!inp.empty()) { sensor["INP"] = _createLink(conn_id, inp); print::printRecord(dbfile, pv_prefix, sensor); } } auto frus = conn->getFrus(); for (auto& fru: frus) { auto inp = fru.getField<std::string>("INP", ""); if (!inp.empty()) { fru["INP"] = _createLink(conn_id, inp); print::printRecord(dbfile, pv_prefix, fru); } } auto leds = conn->getPicmgLeds(); for (auto& led: leds) { auto inp = led.getField<std::string>("INP", ""); if (!inp.empty()) { led["INP"] = _createLink(conn_id, inp); print::printRecord(dbfile, pv_prefix, led); } } } catch (...) { // TODO: do we need to log } fclose(dbfile); } bool checkLink(const std::string& address) { auto conn = _getConnection( _parseLink(address).first ); return (!!conn); } bool scheduleGet(const std::string& address, const std::function<void()>& cb, Provider::Entity& entity) { auto addr = _parseLink(address); auto conn = _getConnection(addr.first); if (!conn) return false; return conn->schedule( Provider::Task(std::move(addr.second), cb, entity) ); } }; // namespace dispatcher
29.327869
111
0.584312
ornl-epics
cc21bd341dfcc4eef1dedead8ca7829864d99e46
665
cpp
C++
xiosim/ZCOMPS-bpred/bpred-perfect.cpp
s-kanev/XIOSim
9673bbd15ba72c9cce15243a462bffb5d9ded9ae
[ "BSD-3-Clause" ]
55
2015-05-29T19:59:33.000Z
2022-02-08T03:08:15.000Z
xiosim/ZCOMPS-bpred/bpred-perfect.cpp
s-kanev/XIOSim
9673bbd15ba72c9cce15243a462bffb5d9ded9ae
[ "BSD-3-Clause" ]
1
2015-04-03T04:40:26.000Z
2015-04-03T04:40:26.000Z
xiosim/ZCOMPS-bpred/bpred-perfect.cpp
s-kanev/XIOSim
9673bbd15ba72c9cce15243a462bffb5d9ded9ae
[ "BSD-3-Clause" ]
7
2015-04-03T00:28:32.000Z
2018-09-01T20:53:58.000Z
/* bpred-perfect.cpp: Oracle/perfect predictor NOTE: for branch direction only (not target) */ /* * __COPYRIGHT__ GT */ #define COMPONENT_NAME "perfect" #ifdef BPRED_PARSE_ARGS if(!strcasecmp(COMPONENT_NAME,type)) { return std::make_unique<bpred_perfect_t>(core); } #else class bpred_perfect_t:public bpred_dir_t { public: bpred_perfect_t(const core_t * core) : bpred_dir_t(core) { init(); name = COMPONENT_NAME; type = "perfect/oracle"; bits = 0; } /* LOOKUP */ BPRED_LOOKUP_HEADER { BPRED_STAT(lookups++;) scvp->updated = false; return outcome; } }; #endif /* BPRED_PARSE_ARGS */ #undef COMPONENT_NAME
15.833333
58
0.678195
s-kanev
cc28c047389fce15b68825d7a3ffbdcc87521611
2,903
cpp
C++
simulation&control/pid_tuning_and_fuzzy_adaptive/6/GYJPID_ws/src/pid_identification/src/slros_busmsg_conversion.cpp
L-Net-1992/guyueclass
a6dd06529dfbe500a52ae89aa5156eca7d305c28
[ "Apache-2.0" ]
null
null
null
simulation&control/pid_tuning_and_fuzzy_adaptive/6/GYJPID_ws/src/pid_identification/src/slros_busmsg_conversion.cpp
L-Net-1992/guyueclass
a6dd06529dfbe500a52ae89aa5156eca7d305c28
[ "Apache-2.0" ]
null
null
null
simulation&control/pid_tuning_and_fuzzy_adaptive/6/GYJPID_ws/src/pid_identification/src/slros_busmsg_conversion.cpp
L-Net-1992/guyueclass
a6dd06529dfbe500a52ae89aa5156eca7d305c28
[ "Apache-2.0" ]
null
null
null
#include "slros_busmsg_conversion.h" // Conversions between SL_Bus_PID_identification_ros_time_Time and ros::Time void convertFromBus(ros::Time* msgPtr, SL_Bus_PID_identification_ros_time_Time const* busPtr) { const std::string rosMessageType("ros_time/Time"); msgPtr->nsec = busPtr->Nsec; msgPtr->sec = busPtr->Sec; } void convertToBus(SL_Bus_PID_identification_ros_time_Time* busPtr, ros::Time const* msgPtr) { const std::string rosMessageType("ros_time/Time"); busPtr->Nsec = msgPtr->nsec; busPtr->Sec = msgPtr->sec; } // Conversions between SL_Bus_PID_identification_sensor_msgs_Joy and sensor_msgs::Joy void convertFromBus(sensor_msgs::Joy* msgPtr, SL_Bus_PID_identification_sensor_msgs_Joy const* busPtr) { const std::string rosMessageType("sensor_msgs/Joy"); convertFromBusVariablePrimitiveArray(msgPtr->axes, busPtr->Axes, busPtr->Axes_SL_Info); convertFromBusVariablePrimitiveArray(msgPtr->buttons, busPtr->Buttons, busPtr->Buttons_SL_Info); convertFromBus(&msgPtr->header, &busPtr->Header); } void convertToBus(SL_Bus_PID_identification_sensor_msgs_Joy* busPtr, sensor_msgs::Joy const* msgPtr) { const std::string rosMessageType("sensor_msgs/Joy"); convertToBusVariablePrimitiveArray(busPtr->Axes, busPtr->Axes_SL_Info, msgPtr->axes, slros::EnabledWarning(rosMessageType, "axes")); convertToBusVariablePrimitiveArray(busPtr->Buttons, busPtr->Buttons_SL_Info, msgPtr->buttons, slros::EnabledWarning(rosMessageType, "buttons")); convertToBus(&busPtr->Header, &msgPtr->header); } // Conversions between SL_Bus_PID_identification_std_msgs_Header and std_msgs::Header void convertFromBus(std_msgs::Header* msgPtr, SL_Bus_PID_identification_std_msgs_Header const* busPtr) { const std::string rosMessageType("std_msgs/Header"); convertFromBusVariablePrimitiveArray(msgPtr->frame_id, busPtr->FrameId, busPtr->FrameId_SL_Info); msgPtr->seq = busPtr->Seq; convertFromBus(&msgPtr->stamp, &busPtr->Stamp); } void convertToBus(SL_Bus_PID_identification_std_msgs_Header* busPtr, std_msgs::Header const* msgPtr) { const std::string rosMessageType("std_msgs/Header"); convertToBusVariablePrimitiveArray(busPtr->FrameId, busPtr->FrameId_SL_Info, msgPtr->frame_id, slros::EnabledWarning(rosMessageType, "frame_id")); busPtr->Seq = msgPtr->seq; convertToBus(&busPtr->Stamp, &msgPtr->stamp); } // Conversions between SL_Bus_PID_identification_std_msgs_Int16 and std_msgs::Int16 void convertFromBus(std_msgs::Int16* msgPtr, SL_Bus_PID_identification_std_msgs_Int16 const* busPtr) { const std::string rosMessageType("std_msgs/Int16"); msgPtr->data = busPtr->Data; } void convertToBus(SL_Bus_PID_identification_std_msgs_Int16* busPtr, std_msgs::Int16 const* msgPtr) { const std::string rosMessageType("std_msgs/Int16"); busPtr->Data = msgPtr->data; }
35.839506
149
0.769549
L-Net-1992
cc2c6ae1741f548f9af84a1a90051803f8d8c629
1,534
hpp
C++
extras/sixense/sixense_utils/mouse_pointer.hpp
adminicg/opentracker
fa8c542c3b2f3495d74d0e2b1670449da94d9a0c
[ "BSD-3-Clause" ]
1
2021-06-24T09:55:20.000Z
2021-06-24T09:55:20.000Z
extras/sixense/sixense_utils/mouse_pointer.hpp
adminicg/opentracker
fa8c542c3b2f3495d74d0e2b1670449da94d9a0c
[ "BSD-3-Clause" ]
null
null
null
extras/sixense/sixense_utils/mouse_pointer.hpp
adminicg/opentracker
fa8c542c3b2f3495d74d0e2b1670449da94d9a0c
[ "BSD-3-Clause" ]
null
null
null
/* * * SIXENSE CONFIDENTIAL * * Copyright (C) 2011 Sixense Entertainment Inc. * All Rights Reserved * */ #ifndef SIXENSE_UTILS_MOUSE_POINTER_HPP #define SIXENSE_UTILS_MOUSE_POINTER_HPP #pragma warning(push) #pragma warning( disable:4251 ) #include "sixense_utils/export.hpp" #include <sixense.h> #include <sixense_math.hpp> using sixenseMath::Vector2; using sixenseMath::Vector3; using sixenseMath::Matrix3; namespace sixenseUtils { // LaserPointer computes a ray that shoots from the controller and intersects with the screen. class SIXENSE_UTILS_EXPORT MousePointer { public: MousePointer(); sixenseMath::Vector2 update( sixenseControllerData *cd ); void setSensitivity( float sensitivity ); void setAcceleration( float acceleration ); void setSlideEnabled( bool slide_enabled ); void setAspectRatio( float aspect_ratio ); float getRollAngle(); void setCenter(); private: bool _slide_enabled; float _aspect_ratio; float _sensitivity; float _screen_width_in_mm; // velocity params float _min_vel, _max_vel; float _acceleration; // This offset is the position of the center of the virtual screen relative to the base Vector2 mouse_offset; // Keep track of the previous mouse pos so we can compute velocity Vector2 _last_mouse_pos; // Keep track of the last accel so we can filter it float _last_accel; float _roll_angle; bool _center_mouse_requested; }; } #pragma warning(pop) #endif
21.605634
97
0.72425
adminicg
cc2d80af346a576a7ad097c9f3e4ed58e0e24533
19,936
cpp
C++
OpenDriveMap.cpp
chacha95/libOpendrive
69400a60bd7e4de331396f92c7d20d1a795f4ca9
[ "Apache-2.0" ]
1
2021-12-06T02:03:09.000Z
2021-12-06T02:03:09.000Z
OpenDriveMap.cpp
chacha95/libOpendrive
69400a60bd7e4de331396f92c7d20d1a795f4ca9
[ "Apache-2.0" ]
null
null
null
OpenDriveMap.cpp
chacha95/libOpendrive
69400a60bd7e4de331396f92c7d20d1a795f4ca9
[ "Apache-2.0" ]
1
2021-12-06T02:03:46.000Z
2021-12-06T02:03:46.000Z
#include "OpenDriveMap.h" #include "Geometries/Arc.h" #include "Geometries/CubicSpline.h" #include "Geometries/Line.h" #include "Geometries/ParamPoly3.h" #include "Geometries/Spiral.h" #include "LaneSection.h" #include "Lanes.h" #include "RefLine.h" #include "Road.h" #include "pugixml/pugixml.hpp" #include <iostream> #include <string> #include <utility> namespace odr { OpenDriveMap::OpenDriveMap(std::string xodr_file, bool with_lateralProfile, bool with_laneHeight, bool center_map) : xodr_file(xodr_file) { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(xodr_file.c_str()); if (!result) printf("%s\n", result.description()); pugi::xml_node odr_node = doc.child("OpenDRIVE"); if (auto geoReference_node = odr_node.child("header").child("geoReference")) this->proj4 = geoReference_node.text().as_string(); size_t cnt = 1; if (center_map) { for (pugi::xml_node road_node : odr_node.children("road")) { for (pugi::xml_node geometry_hdr_node : road_node.child("planView").children("geometry")) { const double x0 = geometry_hdr_node.attribute("x").as_double(); this->x_offs = this->x_offs + ((x0 - this->x_offs) / cnt); const double y0 = geometry_hdr_node.attribute("y").as_double(); this->y_offs = this->y_offs + ((y0 - this->y_offs) / cnt); cnt++; } } } for (pugi::xml_node road_node : odr_node.children("road")) { /* make road */ std::shared_ptr<Road> road = std::make_shared<Road>(); road->length = road_node.attribute("length").as_double(); road->id = road_node.attribute("id").as_string(); road->junction = road_node.attribute("junction").as_string(); road->name = road_node.attribute("name").as_string(); this->roads[road->id] = road; /* parse road links */ for (bool is_predecessor : {true, false}) { pugi::xml_node road_link_node = is_predecessor ? road_node.child("link").child("predecessor") : road_node.child("link").child("successor"); if (road_link_node) { RoadLink& link = is_predecessor ? road->predecessor : road->successor; link.elementId = road_link_node.child("elementId").text().as_string(); link.elementType = road_link_node.child("elementType").text().as_string(); link.contactPoint = road_link_node.child("contactPoint").text().as_string(); } } /* parse road neighbors */ for (pugi::xml_node road_neighbor_node : road_node.child("link").children("neighbor")) { RoadNeighbor road_neighbor; road_neighbor.elementId = road_neighbor_node.attribute("elementId").as_string(); road_neighbor.side = road_neighbor_node.attribute("side").as_string(); road_neighbor.direction = road_neighbor_node.attribute("direction").as_string(); road->neighbors.push_back(road_neighbor); } /* parse road type and speed */ for (pugi::xml_node road_type_node : road_node.children("type")) { double s = road_type_node.attribute("s").as_double(); std::string type = road_type_node.attribute("type").as_string(); road->s_to_type[s] = type; if (pugi::xml_node node = road_type_node.child("speed")) { SpeedRecord speed_record; speed_record.max = node.attribute("max").as_string(); speed_record.unit = node.attribute("unit").as_string(); road->s_to_speed[s] = speed_record; } } /* make ref_line - parse road geometries */ road->ref_line = std::make_shared<RefLine>(road->length); for (pugi::xml_node geometry_hdr_node : road_node.child("planView").children("geometry")) { double s0 = geometry_hdr_node.attribute("s").as_double(); double x0 = geometry_hdr_node.attribute("x").as_double() - this->x_offs; double y0 = geometry_hdr_node.attribute("y").as_double() - this->y_offs; double hdg0 = geometry_hdr_node.attribute("hdg").as_double(); double length = geometry_hdr_node.attribute("length").as_double(); pugi::xml_node geometry_node = geometry_hdr_node.first_child(); std::string geometry_type = geometry_node.name(); if (geometry_type == "line") { road->ref_line->s0_to_geometry[s0] = std::make_shared<Line>(s0, x0, y0, hdg0, length); } else if (geometry_type == "spiral") { double curv_start = geometry_node.attribute("curvStart").as_double(); double curv_end = geometry_node.attribute("curvEnd").as_double(); road->ref_line->s0_to_geometry[s0] = std::make_shared<Spiral>(s0, x0, y0, hdg0, length, curv_start, curv_end); } else if (geometry_type == "arc") { double curvature = geometry_node.attribute("curvature").as_double(); road->ref_line->s0_to_geometry[s0] = std::make_shared<Arc>(s0, x0, y0, hdg0, length, curvature); } else if (geometry_type == "paramPoly3") { double aU = geometry_node.attribute("aU").as_double(); double bU = geometry_node.attribute("bU").as_double(); double cU = geometry_node.attribute("cU").as_double(); double dU = geometry_node.attribute("dU").as_double(); double aV = geometry_node.attribute("aV").as_double(); double bV = geometry_node.attribute("bV").as_double(); double cV = geometry_node.attribute("cV").as_double(); double dV = geometry_node.attribute("dV").as_double(); bool pRange_normalized = true; if (geometry_node.attribute("pRange")) { std::string pRange_str = geometry_node.attribute("pRange").as_string(); std::transform(pRange_str.begin(), pRange_str.end(), pRange_str.begin(), [](unsigned char c) { return std::tolower(c); }); if (pRange_str == "arclength") pRange_normalized = false; } road->ref_line->s0_to_geometry[s0] = std::make_shared<ParamPoly3>(s0, x0, y0, hdg0, length, aU, bU, cU, dU, aV, bV, cV, dV, pRange_normalized); } else { printf("Could not parse %s\n", geometry_type.c_str()); } } std::map<std::string /*x path query*/, CubicSpline&> cubic_spline_fields{ {".//elevationProfile//elevation", road->ref_line->elevation_profile}, {".//lanes//laneOffset", road->lane_offset}}; if (with_lateralProfile) cubic_spline_fields.insert({".//lateralProfile//superelevation", road->superelevation}); /* parse elevation profiles, lane offsets, superelevation */ for (auto entry : cubic_spline_fields) { pugi::xpath_node_set nodes = road_node.select_nodes(entry.first.c_str()); for (pugi::xpath_node node : nodes) { double s0 = node.node().attribute("s").as_double(); double a = node.node().attribute("a").as_double(); double b = node.node().attribute("b").as_double(); double c = node.node().attribute("c").as_double(); double d = node.node().attribute("d").as_double(); entry.second.s0_to_poly[s0] = Poly3(s0, a, b, c, d); } } /* parse crossfall - has extra attribute side */ if (with_lateralProfile) { for (pugi::xml_node crossfall_node : road_node.child("lateralProfile").children("crossfall")) { double s0 = crossfall_node.attribute("s").as_double(); double a = crossfall_node.attribute("a").as_double(); double b = crossfall_node.attribute("b").as_double(); double c = crossfall_node.attribute("c").as_double(); double d = crossfall_node.attribute("d").as_double(); Poly3 crossfall_poly(s0, a, b, c, d); road->crossfall.s0_to_poly[s0] = crossfall_poly; if (pugi::xml_attribute side = crossfall_node.attribute("side")) { std::string side_str = side.as_string(); std::transform(side_str.begin(), side_str.end(), side_str.begin(), [](unsigned char c) { return std::tolower(c); }); if (side_str == "left") road->crossfall.sides[s0] = Crossfall::Side::Left; else if (side_str == "right") road->crossfall.sides[s0] = Crossfall::Side::Right; else road->crossfall.sides[s0] = Crossfall::Side::Both; } } /* check for lateralProfile shape - not implemented yet */ for (auto road_shape_node : road_node.child("lateralProfile").children("shape")) printf("Lateral Profile Shape not supported\n"); } /* parse road lane sections and lanes */ for (pugi::xml_node lane_section_node : road_node.child("lanes").children("laneSection")) { double s0 = lane_section_node.attribute("s").as_double(); std::shared_ptr<LaneSection> lane_section = std::make_shared<LaneSection>(s0); lane_section->road = road; road->s_to_lanesection[lane_section->s0] = lane_section; for (pugi::xpath_node lane_node : lane_section_node.select_nodes(".//lane")) { int lane_id = lane_node.node().attribute("id").as_int(); std::string lane_type = lane_node.node().attribute("type").as_string(); bool level = lane_node.node().attribute("level").as_bool(); std::shared_ptr<Lane> lane = std::make_shared<Lane>(lane_id, level, lane_type); lane->road = road; lane_section->id_to_lane[lane->id] = lane; for (pugi::xml_node lane_width_node : lane_node.node().children("width")) { double sOffs = lane_width_node.attribute("sOffset").as_double(); double a = lane_width_node.attribute("a").as_double(); double b = lane_width_node.attribute("b").as_double(); double c = lane_width_node.attribute("c").as_double(); double d = lane_width_node.attribute("d").as_double(); lane->lane_width.s0_to_poly[s0 + sOffs] = Poly3(s0 + sOffs, a, b, c, d); } if (with_laneHeight) { for (pugi::xml_node lane_height_node : lane_node.node().children("height")) { double s_offset = lane_height_node.attribute("sOffset").as_double(); double inner = lane_height_node.attribute("inner").as_double(); double outer = lane_height_node.attribute("outer").as_double(); lane->s_to_height_offset[s0 + s_offset] = HeightOffset{inner, outer}; } } for (pugi::xml_node roadmark_node : lane_node.node().children("roadMark")) { double sOffsetRoadMark = roadmark_node.attribute("sOffset").as_double(0); double width = roadmark_node.attribute("width").as_double(-1); double height = roadmark_node.attribute("height").as_double(0); std::string type = roadmark_node.attribute("type").as_string("none"); std::string weight = roadmark_node.attribute("weight").as_string("standard"); std::string color = roadmark_node.attribute("color").as_string("standard"); std::string material = roadmark_node.attribute("material").as_string("standard"); std::string laneChange = roadmark_node.attribute("laneChange").as_string("both"); RoadMarkGroup roadmark_group{width, height, sOffsetRoadMark, type, weight, color, material, laneChange}; if (pugi::xml_node roadmark_type_node = roadmark_node.child("type")) { std::string name = roadmark_type_node.attribute("name").as_string(""); double line_width_1 = roadmark_type_node.attribute("width").as_double(-1); for (pugi::xml_node roadmarks_line_node : roadmark_type_node.children("line")) { double length = roadmarks_line_node.attribute("length").as_double(0); double space = roadmarks_line_node.attribute("space").as_double(0); double tOffset = roadmarks_line_node.attribute("tOffset").as_double(0); double sOffsetRoadMarksLine = roadmarks_line_node.attribute("sOffset").as_double(0); double line_width_0 = roadmarks_line_node.attribute("width").as_double(-1); double line_width = line_width_0 < 0 ? line_width_1 : line_width_0; std::string rule = roadmarks_line_node.attribute("rule").as_string("none"); RoadMarksLine roadmarks_line{line_width, length, space, tOffset, sOffsetRoadMarksLine, name, rule}; roadmark_group.s_to_roadmarks_line[s0 + sOffsetRoadMark + sOffsetRoadMarksLine] = roadmarks_line; } } lane->s_to_roadmark_group[s0 + sOffsetRoadMark] = roadmark_group; } if (pugi::xml_node node = lane_node.node().child("link").child("predecessor")) lane->predecessor = node.attribute("id").as_int(); if (pugi::xml_node node = lane_node.node().child("link").child("successor")) lane->successor = node.attribute("id").as_int(); } /* derive lane borders from lane widths */ auto id_lane_iter0 = lane_section->id_to_lane.find(0); if (id_lane_iter0 == lane_section->id_to_lane.end()) throw std::runtime_error("lane section does not have lane #0"); /* iterate from id #0 towards +inf */ auto id_lane_iter1 = std::next(id_lane_iter0); for (auto iter = id_lane_iter1; iter != lane_section->id_to_lane.end(); iter++) { if (iter == id_lane_iter0) { iter->second->outer_border = iter->second->lane_width; } else { iter->second->inner_border = std::prev(iter)->second->outer_border; iter->second->outer_border = std::prev(iter)->second->outer_border.add(iter->second->lane_width); } } /* iterate from id #0 towards -inf */ std::map<int, std::shared_ptr<Lane>>::const_reverse_iterator r_id_lane_iter_1(id_lane_iter0); for (auto r_iter = r_id_lane_iter_1; r_iter != lane_section->id_to_lane.rend(); r_iter++) { if (r_iter == r_id_lane_iter_1) { r_iter->second->outer_border = r_iter->second->lane_width.negate(); } else { r_iter->second->inner_border = std::prev(r_iter)->second->outer_border; r_iter->second->outer_border = std::prev(r_iter)->second->outer_border.add(r_iter->second->lane_width.negate()); } } for (auto& id_lane : lane_section->id_to_lane) { id_lane.second->inner_border = id_lane.second->inner_border.add(road->lane_offset); id_lane.second->outer_border = id_lane.second->outer_border.add(road->lane_offset); } } } } ConstRoadSet OpenDriveMap::get_roads() const { ConstRoadSet roads; for (const auto& id_road : this->roads) roads.insert(id_road.second); return roads; } RoadSet OpenDriveMap::get_roads() { RoadSet roads; for (const auto& id_road : this->roads) roads.insert(id_road.second); return roads; } Mesh3D OpenDriveMap::get_refline_lines(double eps) const { /* indices are pairs of vertices representing line segments */ Mesh3D reflines; for (std::shared_ptr<const Road> road : this->get_roads()) { const size_t idx_offset = reflines.vertices.size(); const Line3D refl_pts = road->ref_line->get_line(0.0, road->length, eps); reflines.vertices.insert(reflines.vertices.end(), refl_pts.begin(), refl_pts.end()); for (size_t idx = idx_offset; idx < (idx_offset + refl_pts.size() - 1); idx++) { reflines.indices.push_back(idx); reflines.indices.push_back(idx + 1); } } return reflines; } RoadNetworkMesh OpenDriveMap::get_mesh(double eps) const { RoadNetworkMesh out_mesh; LaneMeshUnion& lanes_union = out_mesh.lane_mesh_union; RoadmarkMeshUnion& roadmarks_union = out_mesh.roadmark_mesh_union; for (std::shared_ptr<const Road> road : this->get_roads()) { lanes_union.road_start_indices[lanes_union.vertices.size()] = road->id; roadmarks_union.road_start_indices[roadmarks_union.vertices.size()] = road->id; for (std::shared_ptr<const LaneSection> lanesec : road->get_lanesections()) { lanes_union.lanesec_start_indices[lanes_union.vertices.size()] = lanesec->s0; roadmarks_union.lanesec_start_indices[roadmarks_union.vertices.size()] = lanesec->s0; for (std::shared_ptr<const Lane> lane : lanesec->get_lanes()) { size_t idx_offset = lanes_union.vertices.size(); lanes_union.lane_start_indices[idx_offset] = lane->id; Mesh3D lane_mesh = lane->get_mesh(lanesec->s0, lanesec->get_end(), eps); lanes_union.st_coordinates.insert(lanes_union.st_coordinates.end(), lane_mesh.st_coordinates.begin(), lane_mesh.st_coordinates.end()); lanes_union.vertices.insert(lanes_union.vertices.end(), lane_mesh.vertices.begin(), lane_mesh.vertices.end()); for (const size_t& idx : lane_mesh.indices) lanes_union.indices.push_back(idx + idx_offset); idx_offset = roadmarks_union.vertices.size(); roadmarks_union.lane_start_indices[idx_offset] = lane->id; const std::vector<RoadMark> roadmarks = lane->get_roadmarks(lanesec->s0, lanesec->get_end()); for (const RoadMark& roadmark : roadmarks) { idx_offset = roadmarks_union.vertices.size(); const Mesh3D roadmark_mesh = lane->get_roadmark_mesh(roadmark, eps); roadmarks_union.vertices.insert(roadmarks_union.vertices.end(), roadmark_mesh.vertices.begin(), roadmark_mesh.vertices.end()); for (const size_t& idx : roadmark_mesh.indices) roadmarks_union.indices.push_back(idx + idx_offset); roadmarks_union.roadmark_type_start_indices[idx_offset] = roadmark.type; } } } } return out_mesh; } } // namespace odr
48.743276
150
0.575492
chacha95
cc3009926544a974144c920dcdc5e96803c64a14
4,590
cc
C++
graphics/sphere.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
graphics/sphere.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
graphics/sphere.cc
Tibonium/genecis
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
[ "BSD-2-Clause" ]
null
null
null
#include <genecis/graphics/sphere.h> #include <ctime> #include <cstring> using namespace genecis::graphics ; /** * Constructor */ Sphere::Sphere(integral_type radius, size_type rings, size_type sectors) : _vertices(rings * sectors * 3, 0), _normals(rings * sectors * 3, 0), _texcoords(rings * sectors * 2, 0), _colors(rings * sectors * 3, 0), _position(3, 0), _velocity(3, 0), _acceleration(3,0), _indices(rings * sectors * 4, 0), _red(0), _green(0), _blue(0), _id(0) { integral_type const R = 1./(integral_type)(rings-1) ; integral_type const S = 1./(integral_type)(sectors-1) ; container_type::iterator v = _vertices.begin() ; container_type::iterator n = _normals.begin() ; container_type::iterator t = _texcoords.begin() ; for(size_type r=0; r<rings; ++r) { for(size_type s=0; s<sectors; ++s) { integral_type const y = std::sin(-M_PI_2 + M_PI * r * R) ; integral_type const x = std::cos(2*M_PI * s * S) * std::sin(M_PI * r * R) ; integral_type const z = std::sin(2*M_PI * s * S) * std::sin(M_PI * r * R) ; *t++ = s * S ; *t++ = r * R ; *v++ = x * radius ; *v++ = y * radius ; *v++ = z * radius ; *n++ = x ; *n++ = y ; *n++ = z ; } } container::array<GLushort>::iterator i = _indices.begin() ; for(size_type r=0; r<(rings - 1); ++r) { for(size_type s=0; s<(sectors - 1); ++s) { *i++ = r * sectors + s ; *i++ = r * sectors + (s + 1) ; *i++ = (r + 1) * sectors + (s + 1) ; *i++ = (r + 1) * sectors + s ; } } _rotation = new GLfloat[rings * sectors * 3] ; std::fill_n( _rotation, rings*sectors*3, 0) ; } /** * Destructor */ Sphere::~Sphere() { if( _rotation ) { delete _rotation ; _rotation = NULL ; } } void Sphere::draw(container::array<double> center, double dt) { draw(center(0), center(1), center(2), dt) ; } /** * Draws the sphere centered at (x,y,z) */ void Sphere::draw(GLfloat x, GLfloat y, GLfloat z, double dt) { glMatrixMode( GL_MODELVIEW ) ; glPushMatrix() ; glRotatef( _velocity(1)*dt, 0.0, 1.0, 0.0 ) ; glRotatef( _velocity(2)*dt, 0.0, 0.0, 1.0 ) ; glMultMatrixf( _rotation ) ; glGetFloatv( GL_MODELVIEW_MATRIX, _rotation ) ; glTranslatef( x, y, z ) ; glEnableClientState( GL_VERTEX_ARRAY ) ; glEnableClientState( GL_NORMAL_ARRAY ) ; glEnableClientState( GL_TEXTURE_COORD_ARRAY ) ; glEnableClientState( GL_COLOR_ARRAY ) ; glVertexPointer( 3, GL_FLOAT, 0, _vertices.begin() ) ; glNormalPointer( GL_FLOAT, 0, _normals.begin() ) ; glTexCoordPointer( 2, GL_FLOAT, 0, _texcoords.begin() ) ; glColorPointer( 3, GL_FLOAT, 0, _colors.begin() ) ; glDrawElements( GL_QUADS, _indices.size(), GL_UNSIGNED_SHORT, _indices.begin() ) ; glPopMatrix() ; // glGenBuffers( 1, &_id ) ; // glBindBuffer( GL_ARRAY_BUFFER, _id ) ; // glBufferData( GL_ARRAY_BUFFER, sizeof(GL_FLOAT)*_vertices.size(), _vertices.begin(), GL_DYNAMIC_DRAW ) ; // glEnableVertexAttribArray( 0 ) ; // glVertexAttribPointer( _id, 4, GL_FLOAT, GL_FALSE, 0, 0 ) ; // // glGenBuffers( 1, &_id ) ; // glBindBuffer( GL_ARRAY_BUFFER, _id ) ; // glBufferData( GL_ARRAY_BUFFER, sizeof(GL_FLOAT)*_indices.size(), _indices.begin(), GL_DYNAMIC_DRAW ) ; // glEnableVertexAttribArray( 0 ) ; // glVertexAttribPointer( _id, 4, GL_FLOAT, GL_FALSE, 0, 0 ) ; // glBufferData( GL_ARRAY_BUFFER, sizeof(_vertices) + sizeof(_indices), 0, GL_STATIC_DRAW ) ; // glBufferSubData( GL_ARRAY_BUFFER, 0, _vertices.size(), _vertices.begin() ) ; // glBufferSubData( GL_ARRAY_BUFFER, _vertices.size(), _indices.size(), _indices.begin() ) ; // glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _indices.begin() ) ; // glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, 0, _indices.size(), _indicies.begin() ) ; // glDrawArrays( GL_QUADS, 0, _vertices.size() ) ; // glDisableVertexAttribArray( _id ) ; // glDrawElements( GL_QUADS, _indices.size(), GL_UNSIGNED_SHORT, _indices.begin() ) ; } /** * Sets the color of the sphere */ void Sphere::color(GLfloat r, GLfloat g, GLfloat b) { std::srand(0) ; //_red = r ; //_green = g ; //_blue = b ; int N = _colors.size() ; double res = 1.0 / N ; for(int i=0; i<N; i+=3) { _colors[i] = std::fmod((r + i*res), 1.0) ; _colors[i+1] = std::fmod((g + i*res), 1.0) ; _colors[i+2] = std::fmod((b + i*res), 1.0) ; } }
32.323944
110
0.586928
Tibonium
cc311d45d444f0d9532b9acba940f32b958936d2
94
cpp
C++
src/Graphics/UI/Font.cpp
noche-x/Stardust-Engine
1b6f295650c7b6b7faced0577b04557d5dc23d9b
[ "MIT" ]
null
null
null
src/Graphics/UI/Font.cpp
noche-x/Stardust-Engine
1b6f295650c7b6b7faced0577b04557d5dc23d9b
[ "MIT" ]
null
null
null
src/Graphics/UI/Font.cpp
noche-x/Stardust-Engine
1b6f295650c7b6b7faced0577b04557d5dc23d9b
[ "MIT" ]
null
null
null
#include <Graphics/UI/Font.h> namespace Stardust::Graphics::UI { intraFont* g_DefaultFont; }
18.8
34
0.755319
noche-x
cc3cdda7f2949416f9ab8a752fd735675b92beab
1,763
cpp
C++
SPOJ/SPOJ - BITMAP/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
SPOJ/SPOJ - BITMAP/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
SPOJ/SPOJ - BITMAP/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2018-03-15 23:37:16 * solution_verdict: Accepted language: C++ * run_time (ms): 640 memory_used (MB): 15.4 * problem: https://vjudge.net/problem/SPOJ-BITMAP ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int inf=1e9; int t,n,m,mat[202][202],dis[202][202]; string s; vector<pair<int,int> >v; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; void bfs(int r,int c) { queue<pair<int,int> >q; pair<int,int>x; dis[r][c]=0; q.push({r,c}); while(q.size()) { x=q.front(); q.pop(); int rw=x.first; int cl=x.second; for(int i=0;i<4;i++) { int xx=rw+dx[i]; int yy=cl+dy[i]; if(xx<1||xx>n||yy<1||yy>m)continue; if(dis[rw][cl]+1<dis[xx][yy]) { q.push({xx,yy}); dis[xx][yy]=dis[rw][cl]+1; } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>t; while(t--) { cin>>n>>m; v.clear(); for(int i=1;i<=n;i++) { cin>>s; for(int j=1;j<=m;j++) { mat[i][j]=s[j-1]; if(mat[i][j]=='1')v.push_back({i,j}); } } for(int i=0;i<=200;i++) { for(int j=0;j<=200;j++)dis[i][j]=inf; } for(auto x:v)bfs(x.first,x.second); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { cout<<dis[i][j]<<" "; } cout<<endl; } } return 0; }
23.197368
111
0.384005
kzvd4729
cc40322bb13f5677d154982adda25a83dfbf220a
3,442
hxx
C++
ds/adsi/winnt/cprinter.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/winnt/cprinter.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/winnt/cprinter.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1995 Microsoft Corporation Module Name: cprinter.hxx Abstract: Contains definitions for CWinNTFSPrintQueueGeneralInfo, CWinNTFSPrintQueueOperation and CWinNTPrintQueue Author: Ram Viswanathan (ramv) 11-18-95 Revision History: --*/ class CWinNTFSPrintQueueGeneralInfo; class CWinNTFSPrintQueueOperation; class CPropertyCache; class CWinNTPrintQueue:INHERIT_TRACKING, public ISupportErrorInfo, public IADsPrintQueue, public IADsPrintQueueOperations, public IADsPropertyList, public CCoreADsObject, public INonDelegatingUnknown, public IADsExtension { public: /* IUnknown methods */ STDMETHOD(QueryInterface)(THIS_ REFIID riid, LPVOID FAR* ppvObj); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); // INonDelegatingUnknown methods STDMETHOD(NonDelegatingQueryInterface)(THIS_ const IID&, void ** ); DECLARE_NON_DELEGATING_REFCOUNTING DECLARE_IDispatch_METHODS; DECLARE_ISupportErrorInfo_METHODS; DECLARE_IADs_METHODS; DECLARE_IADsPrintQueue_METHODS; DECLARE_IADsPrintQueueOperations_METHODS; DECLARE_IADsPropertyList_METHODS; DECLARE_IADsExtension_METHODS // // constructor and destructor // CWinNTPrintQueue(); ~CWinNTPrintQueue(); static HRESULT CreatePrintQueue(LPTSTR lpszADsParent, DWORD dwParentId, LPTSTR pszDomainName, LPTSTR pszServerName, LPTSTR pszPrinterName, DWORD dwObjectState, REFIID riid, CWinNTCredentials& Credentials, LPVOID * ppvoid ); static HRESULT CWinNTPrintQueue::AllocatePrintQueueObject(LPTSTR pszServerName, LPTSTR pszPrinterName, CWinNTPrintQueue ** ppPrintQueue ); HRESULT CWinNTPrintQueue::MarshallAndSet(LPPRINTER_INFO_2 lpPrinterInfo2 ); HRESULT CWinNTPrintQueue::UnMarshall(LPPRINTER_INFO_2 lpPrinterInfo2, BOOL fExplicit ); #if (!defined(BUILD_FOR_NT40)) HRESULT CWinNTPrintQueue::MarshallAndSet(LPPRINTER_INFO_7 lpPrinterInfo7 ); HRESULT CWinNTPrintQueue::UnMarshall7(LPPRINTER_INFO_7 lpPrinterInfo7, BOOL fExplicit ); #endif STDMETHOD(ImplicitGetInfo)(void); protected: STDMETHOD(GetInfo)(THIS_ DWORD dwApiLevel, BOOL fExplicit) ; HRESULT WinNTAddPrinter(); CWinNTFSPrintQueueGeneralInfo *_pGenInfoPS; CWinNTFSPrintQueueOperation *_pOperationPS; CAggregatorDispMgr * _pDispMgr; CADsExtMgr FAR * _pExtMgr; LPWSTR _pszPrinterName; // Caches UNC name CPropertyCache * _pPropertyCache; CWinNTCredentials _Credentials; }; typedef CWinNTPrintQueue *PCWinNTPrintQueue;
23.575342
80
0.578443
npocmaka
cc4094ca11987a4f409b60e790653e1b7e6d0d36
3,212
cpp
C++
triangle.cpp
artem-bondar/triangles-intersection-finder
26376af03f16527be9337fd0b3893fb8f3f6ebab
[ "Unlicense" ]
null
null
null
triangle.cpp
artem-bondar/triangles-intersection-finder
26376af03f16527be9337fd0b3893fb8f3f6ebab
[ "Unlicense" ]
null
null
null
triangle.cpp
artem-bondar/triangles-intersection-finder
26376af03f16527be9337fd0b3893fb8f3f6ebab
[ "Unlicense" ]
null
null
null
#include "triangle.h" #include "text.h" #include <iostream> Triangle::Triangle() { isExist = false; } Triangle::Triangle(Dot a, Dot b, Dot c) { if (checkTriangleInequality(getSquareNormBetweenTwoDots(a,b), getSquareNormBetweenTwoDots(b,c), getSquareNormBetweenTwoDots(a,c))) { isExist = true; AB = Segment(a, b); BC = Segment(b, c); AC = Segment(a, c); A = a; B = b; C = c; } else isExist = false; } std::ostream& operator <<(std::ostream& ostream, const Triangle &triangle) { if (triangle.isExist) ostream << text.geometry[8] << triangle.A << text.geometry[7] << triangle.B << text.geometry[7] << triangle.C << text.geometry[9]; else ostream << text.geometry[0] << text.geometry[4]; return ostream; } bool Triangle::checkExistence() const { return isExist; } bool Triangle::checkTriangleInequality(const double a, const double b, const double c) const { return a < (b + c) && b < (a + c) && c < (a + b); } bool Triangle::checkSegmentsIntersectionWith(const Triangle &anotherTriangle) const { return AB.isCrossedBy(anotherTriangle.AB) || AB.isCrossedBy(anotherTriangle.BC) || AB.isCrossedBy(anotherTriangle.AC) || BC.isCrossedBy(anotherTriangle.AB) || BC.isCrossedBy(anotherTriangle.BC) || BC.isCrossedBy(anotherTriangle.AC) || AC.isCrossedBy(anotherTriangle.AB) || AC.isCrossedBy(anotherTriangle.BC) || AC.isCrossedBy(anotherTriangle.AC); } bool Triangle::checkIfOneOfSegmentsIsStretchedIn(const Triangle &anotherTriangle) const { Segment segments[3] = { AB, BC, AC }; Segment anotherTriangleSegments[3] = { anotherTriangle.AB, anotherTriangle.BC, anotherTriangle.AC }; Dot anotherTriangleDots[3] = { anotherTriangle.A, anotherTriangle.B, anotherTriangle.C }; for (Segment i : segments) { int end = 0, start = 0; for (int j = 0; j < 3; j++) { if (anotherTriangleSegments[j].isDotOnSegment(i.getStart())) start = j++; if (anotherTriangleSegments[j].isDotOnSegment(i.getEnd())) end = j++; if (end && start && end == start) end = start = 0; } if (end && start) return true; } return false; } bool Triangle::checkIfIn(const Triangle &anotherTriangle) const { Dot triangleDots[3] = { A, B, C }; Dot anotherTriangleDots[3] = { anotherTriangle.A, anotherTriangle.B, anotherTriangle.C }; Segment anotherTriangleSegments[3] = { anotherTriangle.AB, anotherTriangle.BC, anotherTriangle.AC }; for (Dot i : triangleDots) { for (Dot j : anotherTriangleDots) { if (i == j) break; Segment segment(i, j); for (Segment k : anotherTriangleSegments) { Dot dot = segment.getCrossingWith(k); if ((!segment.isIn(anotherTriangle.AB) && !segment.isIn(anotherTriangle.BC) && !segment.isIn(anotherTriangle.AC)) && (!anotherTriangle.AB.isDotOnSegment(dot) && !anotherTriangle.BC.isDotOnSegment(dot) && !anotherTriangle.AC.isDotOnSegment(dot))) return false; } } } return true; } bool Triangle::checkIntersectionWith(const Triangle &anotherTriangle) const { return checkSegmentsIntersectionWith(anotherTriangle) || checkIfIn(anotherTriangle) || anotherTriangle.checkIfIn(*this) || checkIfOneOfSegmentsIsStretchedIn(anotherTriangle) || anotherTriangle.checkIfOneOfSegmentsIsStretchedIn(*this); }
34.537634
136
0.705791
artem-bondar
cc4321d1811a4f615623f91d4739193c6797c760
118
hpp
C++
test/TestHeaders.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
1,783
2018-02-28T16:28:42.000Z
2022-03-31T18:45:01.000Z
test/TestHeaders.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
337
2018-02-27T06:38:39.000Z
2022-03-22T02:50:58.000Z
test/TestHeaders.hpp
coderkd10/EternalTerminal
d15bb726d987bd147480125d694de44a2ea6ce83
[ "Apache-2.0" ]
135
2018-04-30T14:48:36.000Z
2022-03-21T16:51:09.000Z
#ifndef __TEST_HEADERS_HPP__ #define __TEST_HEADERS_HPP__ #include "Headers.hpp" #include "catch2/catch.hpp" #endif
14.75
28
0.805085
coderkd10
cc469bfeceb6669e7dd9f6168709d5d4c7ed85fe
3,038
cpp
C++
CursEn/ConsoleApplicationCourse12/ConsoleApplicationCourse12/Source.cpp
catalinboja/cpp_examples_2016
784741ea12fd3dd2ebc659b431f7daaf17898956
[ "Apache-2.0" ]
null
null
null
CursEn/ConsoleApplicationCourse12/ConsoleApplicationCourse12/Source.cpp
catalinboja/cpp_examples_2016
784741ea12fd3dd2ebc659b431f7daaf17898956
[ "Apache-2.0" ]
null
null
null
CursEn/ConsoleApplicationCourse12/ConsoleApplicationCourse12/Source.cpp
catalinboja/cpp_examples_2016
784741ea12fd3dd2ebc659b431f7daaf17898956
[ "Apache-2.0" ]
4
2016-12-21T15:31:37.000Z
2018-08-04T10:36:34.000Z
#include <iostream> using namespace std; class Product { protected: int code; char name[50]; float price; //const int id; public: Product() { cout << endl << "Default product"; code = 0; price = 0.0; strcpy(name, ""); } Product(int Code, float Price, char* Name, int Id) { cout << endl << "Known product"; code = Code; price = Price; strcpy(name, Name); } char* getName() { return name; } float getPrice() { return price; } int getCode() { return code; } virtual void print() { cout << endl << "The product " << name << " (" << code << ")" << " has a price of " << price << " RON"; } ~Product() { cout << endl << "Product destroyed"; } virtual void doSomething() = 0; //pure method }; //inheritance //is a relation class PromotionalProduct :public Product { float discount; public: PromotionalProduct() :Product(1000, 0, "Default promotional product", 0) { cout << endl << "Default promotional product"; //this->code = 1000; //this->price = 0; //strcpy(name, "Default promotional product"); discount = 0.1; //default set to 10% } PromotionalProduct(int Code, char* Name, float Price, float Discount, int ID) :Product(Code, Price, Name, ID) { //this->code = Code; //this->price = Price; //strcpy(name, Name); discount = Discount; //default set to 10% } ~PromotionalProduct() { } //overriding the base class version of print void print() { cout << endl << "The product " << name << " (" << code << ")" << " has a price of " << price << " RON" << " and it has a discount of " << discount * 100 << "%"; } void printNew() { cout << endl << "The product " << name << " (" << code << ")" << " has a price of " << price << " RON" << " and it has a discount of " << discount * 100 << "%"; } void DoSomething() { } void doSomething() { } }; void main() { //Product p1; Product p2(1, 2.5, "Still water", 1); //p1.print(); p2.print(); cout << endl << "Working with extended classes"; PromotionalProduct pp1; pp1.print(); PromotionalProduct pp2(2, "Toy", 100, 0.3, 1); cout << endl << "Test print after overriding it"; pp2.print(); pp2.printNew(); //Product listP[5]; //PromotionalProduct listPP[5]; //pp2 = p2; p2 = pp2; p2.print(); cout << endl << "Working with arrays"; Product list[5]; list[0] = Product(1, 2.5, "Pepsi", 1); list[1] = PromotionalProduct(2, "Drone", 400, 0.25, 1); list[2] = Product(1, 2.5, "Coca-Cola", 1); list[3] = PromotionalProduct(2, "Bike", 400, 0.25, 1); list[4] = Product(1, 2.5, "Still water", 1); for (int i = 0; i < 5; i++) { list[i].print(); } Product* list2[5]; list2[0] = new Product(1, 2.5, "Pepsi", 1); list2[1] = new PromotionalProduct(2, "Drone", 400, 0.25, 1); list2[2] = new Product(1, 2.5, "Coca-Cola", 1); list2[3] = new PromotionalProduct(2, "Bike", 400, 0.25, 1); list2[4] = new Product(1, 2.5, "Still water", 1); cout << endl << "Working with pointers"; for (int i = 0; i < 5; i++) { list2[i]->print(); } }
19.986842
55
0.579658
catalinboja