blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
bd49fc54bd80b2bd88046c5e0fb9c031d7711945
bb6ebff7a7f6140903d37905c350954ff6599091
/third_party/WebKit/Source/web/win/WebFontRendering.cpp
f5a02fd4c0748cf414c60ba942c82813671bd17f
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
PDi-Communication-Systems-Inc/lollipop_external_chromium_org
faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f
ccadf4e63dd34be157281f53fe213d09a8c66d2c
refs/heads/master
2022-12-23T18:07:04.568931
2016-04-11T16:03:36
2016-04-11T16:03:36
53,677,925
0
1
BSD-3-Clause
2022-12-09T23:46:46
2016-03-11T15:49:07
C++
UTF-8
C++
false
false
907
cpp
WebFontRendering.cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "public/web/win/WebFontRendering.h" #include "platform/fonts/FontCache.h" namespace blink { // static void WebFontRendering::setUseDirectWrite(bool useDirectWrite) { WebCore::FontCache::setUseDirectWrite(useDirectWrite); } // static void WebFontRendering::setDirectWriteFactory(IDWriteFactory* factory) { WebCore::FontCache::setDirectWriteFactory(factory); } // static void WebFontRendering::setUseSubpixelPositioning(bool useSubpixelPositioning) { WebCore::FontCache::setUseSubpixelPositioning(useSubpixelPositioning); } // static void WebFontRendering::addSideloadedFontForTesting(SkTypeface* typeface) { WebCore::FontCache::addSideloadedFontForTesting(typeface); } } // namespace blink
29167360a94751d494610c77dee3f9b7de3d50e9
f8517de40106c2fc190f0a8c46128e8b67f7c169
/AllJoyn/Samples/MyLivingRoom/Models/org.alljoyn.Control.Volume/VolumeServiceEventArgs.cpp
9da491951e2c48b2fb2c2e7942ba067427fd53a6
[ "MIT" ]
permissive
ferreiramarcelo/samples
eb77df10fe39567b7ebf72b75dc8800e2470108a
4691f529dae5c440a5df71deda40c57976ee4928
refs/heads/develop
2023-06-21T00:31:52.939554
2021-01-23T16:26:59
2021-01-23T16:26:59
66,746,116
0
0
MIT
2023-06-19T20:52:43
2016-08-28T02:48:20
C
UTF-8
C++
false
false
21,157
cpp
VolumeServiceEventArgs.cpp
//----------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // // Tool: AllJoynCodeGenerator.exe // // This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn // Visual Studio Extension in the Visual Studio Gallery. // // The generated code should be packaged in a Windows 10 C++/CX Runtime // Component which can be consumed in any UWP-supported language using // APIs that are available in Windows.Devices.AllJoyn. // // Using AllJoynCodeGenerator - Invoke the following command with a valid // Introspection XML file and a writable output directory: // AllJoynCodeGenerator -i <INPUT XML FILE> -o <OUTPUT DIRECTORY> // </auto-generated> //----------------------------------------------------------------------------- #include "pch.h" using namespace concurrency; using namespace Microsoft::WRL; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Devices::AllJoyn; using namespace org::alljoyn::Control::Volume; namespace org { namespace alljoyn { namespace Control { namespace Volume { // Methods VolumeAdjustVolumeCalledEventArgs::VolumeAdjustVolumeCalledEventArgs( _In_ AllJoynMessageInfo^ info, _In_ int16 interfaceMemberDelta) : m_raised(false), m_completionsRequired(0), m_messageInfo(info), m_interfaceMemberDelta(interfaceMemberDelta) { m_result = VolumeAdjustVolumeResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeAdjustVolumeCalledEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeAdjustVolumeCalledEventArgs::Complete); return ref new Deferral(handler); } void VolumeAdjustVolumeCalledEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeAdjustVolumeCalledEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeAdjustVolumeCalledEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for AdjustVolumeCalled."); } else { m_tce.set(m_result); } } VolumeAdjustVolumePercentCalledEventArgs::VolumeAdjustVolumePercentCalledEventArgs( _In_ AllJoynMessageInfo^ info, _In_ double interfaceMemberChange) : m_raised(false), m_completionsRequired(0), m_messageInfo(info), m_interfaceMemberChange(interfaceMemberChange) { m_result = VolumeAdjustVolumePercentResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeAdjustVolumePercentCalledEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeAdjustVolumePercentCalledEventArgs::Complete); return ref new Deferral(handler); } void VolumeAdjustVolumePercentCalledEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeAdjustVolumePercentCalledEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeAdjustVolumePercentCalledEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for AdjustVolumePercentCalled."); } else { m_tce.set(m_result); } } // Readable Properties VolumeGetEnabledRequestedEventArgs::VolumeGetEnabledRequestedEventArgs( _In_ AllJoynMessageInfo^ info) : m_raised(false), m_completionsRequired(0), m_messageInfo(info) { m_result = VolumeGetEnabledResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeGetEnabledRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeGetEnabledRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeGetEnabledRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetEnabledRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetEnabledRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetEnabledRequested."); } else { m_tce.set(m_result); } } VolumeGetMuteRequestedEventArgs::VolumeGetMuteRequestedEventArgs( _In_ AllJoynMessageInfo^ info) : m_raised(false), m_completionsRequired(0), m_messageInfo(info) { m_result = VolumeGetMuteResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeGetMuteRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeGetMuteRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeGetMuteRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetMuteRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetMuteRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetMuteRequested."); } else { m_tce.set(m_result); } } VolumeGetVersionRequestedEventArgs::VolumeGetVersionRequestedEventArgs( _In_ AllJoynMessageInfo^ info) : m_raised(false), m_completionsRequired(0), m_messageInfo(info) { m_result = VolumeGetVersionResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeGetVersionRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeGetVersionRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeGetVersionRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetVersionRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetVersionRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetVersionRequested."); } else { m_tce.set(m_result); } } VolumeGetVolumeRequestedEventArgs::VolumeGetVolumeRequestedEventArgs( _In_ AllJoynMessageInfo^ info) : m_raised(false), m_completionsRequired(0), m_messageInfo(info) { m_result = VolumeGetVolumeResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeGetVolumeRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeGetVolumeRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeGetVolumeRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetVolumeRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetVolumeRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetVolumeRequested."); } else { m_tce.set(m_result); } } VolumeGetVolumeRangeRequestedEventArgs::VolumeGetVolumeRangeRequestedEventArgs( _In_ AllJoynMessageInfo^ info) : m_raised(false), m_completionsRequired(0), m_messageInfo(info) { m_result = VolumeGetVolumeRangeResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeGetVolumeRangeRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeGetVolumeRangeRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeGetVolumeRangeRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetVolumeRangeRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeGetVolumeRangeRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetVolumeRangeRequested."); } else { m_tce.set(m_result); } } // Writable Properties VolumeSetMuteRequestedEventArgs::VolumeSetMuteRequestedEventArgs( _In_ AllJoynMessageInfo^ info, _In_ bool value) : m_raised(false), m_completionsRequired(0), m_messageInfo(info), m_value(value) { m_result = VolumeSetMuteResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeSetMuteRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeSetMuteRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeSetMuteRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeSetMuteRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeSetMuteRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for SetMuteRequested."); } else { m_tce.set(m_result); } } VolumeSetVolumeRequestedEventArgs::VolumeSetVolumeRequestedEventArgs( _In_ AllJoynMessageInfo^ info, _In_ int16 value) : m_raised(false), m_completionsRequired(0), m_messageInfo(info), m_value(value) { m_result = VolumeSetVolumeResult::CreateFailureResult(ER_NOT_IMPLEMENTED); } Deferral^ VolumeSetVolumeRequestedEventArgs::GetDeferral() { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_raised) { // Cannot ask for a deferral after the event handler has returned. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired++; auto handler = ref new DeferralCompletedHandler(this, &VolumeSetVolumeRequestedEventArgs::Complete); return ref new Deferral(handler); } void VolumeSetVolumeRequestedEventArgs::InvokeAllFinished() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); m_raised = true; invokeNeeded = (m_completionsRequired == 0); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeSetVolumeRequestedEventArgs::Complete() { bool invokeNeeded; // We need to hold a lock while modifying private state, but release it before invoking a completion handler. { std::lock_guard<std::mutex> lockGuard(m_lock); if (m_completionsRequired == 0) { // This should never happen since Complete() should only be called by Windows.Foundation.Deferral // which will only invoke our completion handler once. throw Exception::CreateException(E_ILLEGAL_METHOD_CALL); } m_completionsRequired--; invokeNeeded = (m_raised && (m_completionsRequired == 0)); } if (invokeNeeded) { InvokeCompleteHandler(); } } void VolumeSetVolumeRequestedEventArgs::InvokeCompleteHandler() { if (m_result->Status == ER_NOT_IMPLEMENTED) { throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for SetVolumeRequested."); } else { m_tce.set(m_result); } } } } } }
a011e7a0fdb53511d142de1178c4f2208479d384
7fea4ad59786056397a0cf6b872dd77366d436bc
/lap.cpp
d87f6d36866dfb570f595dd475e257caaf201daf
[]
no_license
anmolp14/summer17_codes
6dadc636904a958cdc5f425bb31beadeae70336e
ac098b5598ba793c3a60a53fbc9c31d89e9eb835
refs/heads/master
2021-01-20T13:45:20.775469
2017-11-06T19:40:54
2017-11-06T19:40:54
90,524,744
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
lap.cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(;t>0;t--) { int n,a; cin >> n; vector <int> c(101,0); for( int i=0;i<n;i++) { cin >> a; c[a]++; } //for( int i=1; i<101;i++) //cout << c[i] << ' ' ; a = c[1]; int j=1; while( a != 1 ) { j++; a = c[j]; } cout << j << endl; } return 0; }
325f0cefcc0a2830af63eef30413b970e83b0bcd
603abbd229e8751ca39b54de2bd7aed470987035
/BOJ/ForCodingTest-CPP/Mathematics1/NumberOfCombination0.cpp
aa0ca4c99a499dd7ecf82fcdf2cbba6a5105b05d
[]
no_license
SeonJongYoo/Algorithm
869661f5e0c23eedb40b1e8f017bba5501b0519a
e672287c5d6b6c19c146bb59cf73064bda9b4fe2
refs/heads/main
2023-08-11T02:33:25.679790
2021-09-20T15:00:25
2021-09-20T15:00:25
310,283,160
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
cpp
NumberOfCombination0.cpp
// 조합 0의 개수 #include <iostream> using namespace std; pair<long long, long long> ZeroInFac(int N) { pair<long long, long long> p; long long two = 0, five = 0; long long n2 = 2, n5 = 5; // 이 부분이 핵심!! // N을 n2로 나눈 몫이 의미하는 바 - 1 ~ N까지 n2를 인수로 가지는 숫자의 개수 -> N!을 소인수분해 했을 때 2의 개수! while (n2 <= N) { two += N / n2; n2 *= 2; } // N을 n5로 나눈 몫이 의미하는 바 - N!을 소인수분해 했을 때 5의 개수! while (n5 <= N) { five += N / n5; n5 *= 5; } p.first = two; p.second = five; return p; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); pair<long long, long long> ja; pair<long long, long long> mo1; pair<long long, long long> mo2; int n, m; cin >> n >> m; ja = ZeroInFac(n); mo1 = ZeroInFac(n-m); mo2 = ZeroInFac(m); long long r1 = 0, r2 = 0; r1 = ja.first - (mo1.first + mo2.first); r2 = ja.second - (mo1.second + mo2.second); if (r1 >= r2) cout << r2; else cout << r1; return 0; }
700fca6b208c5f0c9713a34a83b4db4b92a8b55d
635c344550534c100e0a86ab318905734c95390d
/wpilibc/src/main/native/include/frc/event/BooleanEvent.h
745a53c09596b03e7d2eef0cf4aa42f42ae79821
[ "BSD-3-Clause" ]
permissive
wpilibsuite/allwpilib
2435cd2f5c16fb5431afe158a5b8fd84da62da24
8f3d6a1d4b1713693abc888ded06023cab3cab3a
refs/heads/main
2023-08-23T21:04:26.896972
2023-08-23T17:47:32
2023-08-23T17:47:32
24,655,143
986
769
NOASSERTION
2023-09-14T03:51:22
2014-09-30T20:51:33
C++
UTF-8
C++
false
false
3,989
h
BooleanEvent.h
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include <frc/filter/Debouncer.h> #include <functional> #include <memory> #include <units/time.h> #include <wpi/FunctionExtras.h> #include "EventLoop.h" namespace frc { /** * This class provides an easy way to link actions to inputs. Each object * represents a boolean condition to which callback actions can be bound using * {@link #IfHigh(std::function<void()>)}. * * <p>These events can easily be composed using factories such as {@link * #operator!}, * {@link #operator||}, {@link #operator&&} etc. * * <p>To get an event that activates only when this one changes, see {@link * #Falling()} and {@link #Rising()}. */ class BooleanEvent { public: /** * Creates a new event with the given condition determining whether it is * active. * * @param loop the loop that polls this event * @param condition returns whether or not the event should be active */ BooleanEvent(EventLoop* loop, std::function<bool()> condition); /** * Check whether this event is active or not. * * @return true if active. */ bool GetAsBoolean() const; /** * Bind an action to this event. * * @param action the action to run if this event is active. */ void IfHigh(std::function<void()> action); operator std::function<bool()>(); // NOLINT /** * A method to "downcast" a BooleanEvent instance to a subclass (for example, * to a command-based version of this class). * * @param ctor a method reference to the constructor of the subclass that * accepts the loop as the first parameter and the condition/signal as the * second. * @return an instance of the subclass. */ template <class T> T CastTo(std::function<T(EventLoop*, std::function<bool()>)> ctor = [](EventLoop* loop, std::function<bool()> condition) { return T(loop, condition); }) { return ctor(m_loop, m_condition); } /** * Creates a new event that is active when this event is inactive, i.e. that * acts as the negation of this event. * * @return the negated event */ BooleanEvent operator!(); /** * Composes this event with another event, returning a new event that is * active when both events are active. * * <p>The new event will use this event's polling loop. * * @param rhs the event to compose with * @return the event that is active when both events are active */ BooleanEvent operator&&(std::function<bool()> rhs); /** * Composes this event with another event, returning a new event that is * active when either event is active. * * <p>The new event will use this event's polling loop. * * @param rhs the event to compose with * @return the event that is active when either event is active */ BooleanEvent operator||(std::function<bool()> rhs); /** * Get a new event that events only when this one newly changes to true. * * @return a new event representing when this one newly changes to true. */ BooleanEvent Rising(); /** * Get a new event that triggers only when this one newly changes to false. * * @return a new event representing when this one newly changes to false. */ BooleanEvent Falling(); /** * Creates a new debounced event from this event - it will become active when * this event has been active for longer than the specified period. * * @param debounceTime The debounce period. * @param type The debounce type. * @return The debounced event. */ BooleanEvent Debounce(units::second_t debounceTime, frc::Debouncer::DebounceType type = frc::Debouncer::DebounceType::kRising); private: EventLoop* m_loop; std::function<bool()> m_condition; }; } // namespace frc
8ed995f0ff584a4e0f408879cfd3a433f44914ac
ca6a0c4eb6fabc5a3b778c60759e476beb3614e8
/Common/math/src/Types.cpp
be5627e666868261fbc9c6368e4993c0f0d5337e
[]
no_license
vansten/Renderers
75e5f06eb473e824c6bbac2bb2468190ac1eccfb
5409a3785a307440c2c30b3aaea52f9f37cd862d
refs/heads/master
2021-01-11T04:10:12.389414
2016-11-22T17:17:10
2016-11-22T17:17:10
71,240,165
0
0
null
null
null
null
UTF-8
C++
false
false
1,484
cpp
Types.cpp
#include "../include/Types.h" uint32 make(uint8 r, uint8 g, uint8 b, uint8 a) { return (a << 24) | (r << 16) | (g << 8) | (b); } void getRGBA(uint32 color, uint8& r, uint8& g, uint8& b, uint8& a) { b = (color & 0x000000ff); g = (color & 0x0000ff00) >> 8; r = (color & 0x00ff0000) >> 16; a = (color & 0xff000000) >> 24; } float clamp(const float & value, const float min, const float max) { return fmax(fmin(value, max), min); } Color24 operator*(const float s, const Color24 & c) { return c * s; } const Color32 Color32::Black = Color32(0x00, 0x00, 0x00, 0x00); const Color32 Color32::Red = Color32(0xFF, 0x00, 0x00, 0xFF); const Color32 Color32::Green = Color32(0x00, 0xFF, 0x00, 0xFF); const Color32 Color32::Blue = Color32(0x00, 0x00, 0xFF, 0xFF); const Color32 Color32::Yellow = Color32(0xFF, 0xFF, 0x00, 0xFF); const Color32 Color32::Magenta = Color32(0xFF, 0x00, 0xFF, 0xFF); const Color32 Color32::Cyan = Color32(0x00, 0xFF, 0xFF, 0xFF); const Color32 Color32::White = Color32(0xFF, 0xFF, 0xFF, 0xFF); const Color24 Color24::Black = Color24(0.0f, 0.0f, 0.0f); const Color24 Color24::Red = Color24(1.0f, 0.0f, 0.0f); const Color24 Color24::Green = Color24(0.0f, 1.0f, 0.0f); const Color24 Color24::Blue = Color24(0.0f, 0.0f, 1.0f); const Color24 Color24::Yellow = Color24(1.0f, 1.0f, 0.0f); const Color24 Color24::Magenta = Color24(1.0f, 0.0f, 1.0f); const Color24 Color24::Cyan = Color24(0.0f, 1.0f, 1.0f); const Color24 Color24::White = Color24(1.0f, 1.0f, 1.0f);
7a8dbf625cd49860046ee27d6471cf6b13e57396
d84852c821600c3836952b78108df724f90e1096
/exams/2558/02204111/1/final/2_2_715_5820502914.cpp
5cda87315e536a7e21d642d539cd99dde53eb6dc
[ "MIT" ]
permissive
btcup/sb-admin
4a16b380bbccd03f51f6cc5751f33acda2a36b43
c2c71dce1cd683f8eff8e3c557f9b5c9cc5e168f
refs/heads/master
2020-03-08T05:17:16.343572
2018-05-07T17:21:22
2018-05-07T17:21:22
127,944,367
0
1
null
null
null
null
UTF-8
C++
false
false
82
cpp
2_2_715_5820502914.cpp
#include<iostream> using namespace std; char CountThe(char a,char b) { char
da875dab0c5fa5864b82bc9f51e9eccbbd776e4c
44eeb51b4b7a58c2c6fb2332457a1fb04674569b
/src/work_queue.cc
494cd0b4d9dfdf683727dbe5a6bc579ad71f2bc3
[ "BSD-2-Clause" ]
permissive
robertu94/libdistributed
bb44cf6858c4e670dae9c2b61f592c7f1e117033
de64a76bb153e3517d0afa920cd66b9d01db239d
refs/heads/master
2023-08-29T00:35:01.997408
2023-08-10T15:22:54
2023-08-10T15:22:54
234,158,547
3
0
null
null
null
null
UTF-8
C++
false
false
192
cc
work_queue.cc
#include <libdistributed_comm.h> distributed::comm::serializer::type_registry& distributed::comm::serializer::get_type_registry() { static type_registry registery; return registery; }
925938cf2f97c0ec65aa22f8606f54e9b866a82e
5cbd4644c2ce895d54954ff6184ac13b1a07332e
/Application/Parsing/AST.h
3648bb6aad53abc42a82ec2bdb7610ca9434e342
[]
no_license
nayaknishant/Nome3
bd727a969074f916da4ae748850fc37404680a0c
854a1a7de6bcf4b910d4925d06d2e1dcf4ac2a07
refs/heads/master
2020-09-01T20:59:22.968667
2019-10-31T22:28:00
2019-10-31T22:28:00
219,055,747
0
0
null
2019-11-01T20:12:35
2019-11-01T20:12:35
null
UTF-8
C++
false
false
6,840
h
AST.h
#pragma once #include "ASTContext.h" #include "SourceManager.h" #include <map> #include <type_traits> #include <vector> namespace Nome { enum class EClassId { Expr, Keyword, Ident, Number, UnaryOp, BinaryOp, Transform, ExprList, CommandArgument, Command }; class AExpr { public: inline static EClassId StaticId() { return EClassId::Expr; } static AExpr* Create(CASTContext& ctx, CSourceLocation beginLoc, CSourceLocation endLoc); EClassId ClassId; CSourceLocation BeginLoc; CSourceLocation EndLoc; protected: AExpr(); AExpr(CSourceLocation beginLoc, CSourceLocation endLoc); }; class AIdent : public AExpr { AIdent(const std::string& ident, CSourceLocation beginLoc, CSourceLocation endLoc); public: inline static EClassId StaticId() { return EClassId::Ident; } static AIdent* Create(CASTContext& ctx, const std::string& id, CSourceLocation beginLoc, CSourceLocation endLoc); std::string Identifier; }; class ANumber : public AExpr { ANumber(const std::string& stringVal, CSourceLocation beginLoc, CSourceLocation endLoc); public: inline static EClassId StaticId() { return EClassId::Number; } static ANumber* Create(CASTContext& ctx, const std::string& stringVal, CSourceLocation beginLoc, CSourceLocation endLoc); double GetValue() const { return Value; } private: double Value; std::string String; }; class AUnaryOp : public AExpr { public: enum EOperator { UOP_NEG, // Trig UOP_SIN, UOP_COS, UOP_TAN, UOP_COT, UOP_SEC, UOP_CSC, UOP_ARCSIN, UOP_ARCCOS, UOP_ARCTAN, UOP_ARCCOT, UOP_ARCSEC, UOP_ARCCSC, }; EOperator Type; AExpr* Operand; inline static EClassId StaticId() { return EClassId::UnaryOp; } static AUnaryOp* Create(CASTContext& ctx, EOperator type, AExpr* operand, AIdent* operatorToken); private: AUnaryOp(EOperator type, AExpr* operand, AIdent* operatorToken); }; class ABinaryOp : public AExpr { public: enum EOperator { BOP_ADD, BOP_SUB, BOP_MUL, BOP_DIV, BOP_EXP }; EOperator Type; AExpr* Left; AExpr* Right; inline static EClassId StaticId() { return EClassId::BinaryOp; } // No need for location, auto derive from left and right operands static ABinaryOp* Create(CASTContext& ctx, EOperator type, AExpr* left, AExpr* right, AIdent* operatorToken = nullptr); private: ABinaryOp(EOperator type, AExpr* left, AExpr* right, AIdent* operatorToken); }; class ATransform : public AExpr { public: enum ETransformType { TF_ROTATE, TF_SCALE, TF_TRANSLATE } Type; AExpr* AxisX; AExpr* AxisY; AExpr* AxisZ; AExpr* Deg; // Only valid for rotation inline static EClassId StaticId() { return EClassId::Transform; } static ATransform* Create(CASTContext& ctx); }; class AExprList : public AExpr { public: inline static EClassId StaticId() { return EClassId::ExprList; } static AExprList* Create(CASTContext& ctx); void AddExpr(AExpr* expr); const std::vector<AExpr*>& GetExpressions() const; std::vector<AIdent*> ConvertToIdents() const; private: std::vector<AExpr*> Expressions; }; // Corresponds to command_arg_list in the parser class ACommandArgument { friend class ACommand; public: EClassId ClassId = EClassId::CommandArgument; inline static EClassId StaticId() { return EClassId::CommandArgument; } static ACommandArgument* Create(CASTContext& ctx, AIdent* param, AExpr* value, ACommandArgument* next = nullptr); ACommand* GetParent() const { return Parent; } ACommandArgument* GetPrev() const { return Prev; } ACommandArgument* GetNext() const { return Next; } AIdent* GetParameter() const { return Parameter; } AExpr* GetValue() const { return Value; } private: ACommand* Parent = nullptr; ACommandArgument* Prev = nullptr; ACommandArgument* Next = nullptr; AIdent* Parameter; AExpr* Value; }; class ACommand { public: EClassId ClassId = EClassId::Command; inline static EClassId StaticId() { return EClassId::Command; } static ACommand* Create(CASTContext& ctx, AIdent* name, AIdent* beginKeyword, AIdent* endKeyword, ACommandArgument* args = nullptr, ACommand* subcommands = nullptr); AIdent* GetBeginKeyword() const { return BeginKeyword; } AIdent* GetEndKeyword() const { return EndKeyword; } AIdent* GetName() const { return Name; } void SetNext(ACommand* next) { this->Next = next; if (next) next->Prev = this; } AExpr* FindNamedArg(const std::string& name) const; ACommandArgument* GetArguments() const { return Arguments; } void SetArguments(ACommandArgument* args) { Arguments = args; Arguments->Parent = this; } ACommandArgument* AddArgument(AIdent* param, AExpr* value); void AppendChild(ACommand* cmd); std::vector<ACommand*> GatherSubcommands() const; private: ACommand(CASTContext& ctx) : Context(ctx) { } CASTContext& Context; ACommand* Parent = nullptr; ACommand* Prev = nullptr; ACommand* Next = nullptr; ACommand* FirstChild = nullptr; // Subcommands // Only BeginKeyword is required AIdent* BeginKeyword = nullptr; // Can be nullptr, e.g., `set` AIdent* EndKeyword = nullptr; // Can be nullptr if the command has no name like `delete` or `set` AIdent* Name = nullptr; ACommandArgument* Arguments = nullptr; }; template <typename TTo, typename TFrom, typename TToPlain = typename std::remove_pointer<TTo>::type> TTo ast_as(TFrom* node) { if (!node) return nullptr; if (node->ClassId == TToPlain::StaticId()) return static_cast<TTo>(node); // TODO: also consider up/down cast return nullptr; } class CSemanticError : public std::exception { public: CSemanticError(const char* message, AExpr* expr) { Message = std::string(message) + " " + expr->BeginLoc.ToString() + "-" + expr->EndLoc.ToString(); } CSemanticError(const std::string& message, AExpr* expr) { Message = message + " " + expr->BeginLoc.ToString() + "-" + expr->EndLoc.ToString(); } CSemanticError(const std::string& message, ACommand* cmd) { Message = message + " " + cmd->GetBeginKeyword()->BeginLoc.ToString(); } [[nodiscard]] char const* what() const noexcept override { return Message.c_str(); } private: std::string Message; }; }
024630d542d853314db7687ae99eff160fe7f178
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_3852.cpp
a67768f6770ee2cbc7a4de3b221dd63d180f423f
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
49
cpp
Kitware_CMake_repos_basic_block_block_3852.cpp
f(!hoststr) { free(buf); return NULL; }
466c614b18c8f9c0fb83b2908e9f98868d2aac8e
127f913b2f7e31b562d4aadebde89e1987424ead
/include/ignition/physics/SphereShape.hh
ee57847f5e79dd1ae46742bd148f9f0976e086c0
[ "Apache-2.0" ]
permissive
Tobias-Fischer/ign-physics
6f43d66cf52dd9adbd0a72dce2449cf2555721d1
42d232088f719d4a65d8f443f5df56dd837367a2
refs/heads/main
2023-08-22T07:15:53.120269
2021-09-21T17:02:42
2021-09-21T17:02:42
414,787,410
0
0
NOASSERTION
2021-10-07T23:37:34
2021-10-07T23:37:34
null
UTF-8
C++
false
false
4,448
hh
SphereShape.hh
/* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef IGNITION_PHYSICS_SPHERESHAPE_HH_ #define IGNITION_PHYSICS_SPHERESHAPE_HH_ #include <string> #include <ignition/physics/DeclareShapeType.hh> #include <ignition/physics/Geometry.hh> namespace ignition { namespace physics { IGN_PHYSICS_DECLARE_SHAPE_TYPE(SphereShape) ///////////////////////////////////////////////// class IGNITION_PHYSICS_VISIBLE GetSphereShapeProperties : public virtual FeatureWithRequirements<SphereShapeCast> { public: template <typename PolicyT, typename FeaturesT> class SphereShape : public virtual Entity<PolicyT, FeaturesT> { public: using Scalar = typename PolicyT::Scalar; /// \brief Get the radius of this SphereShape /// \return the radius of this SphereShape public: Scalar GetRadius() const; }; public: template <typename PolicyT> class Implementation : public virtual Feature::Implementation<PolicyT> { public: using Scalar = typename PolicyT::Scalar; public: virtual Scalar GetSphereShapeRadius( const Identity &_sphereID) const = 0; }; }; ///////////////////////////////////////////////// class IGNITION_PHYSICS_VISIBLE SetSphereShapeProperties : public virtual FeatureWithRequirements<SphereShapeCast> { public: template <typename PolicyT, typename FeaturesT> class SphereShape : public virtual Entity<PolicyT, FeaturesT> { public: using Scalar = typename PolicyT::Scalar; /// \brief Set the radius of this SphereShape /// \param[in] _value /// The desired radius of this SphereShape public: void SetRadius(Scalar _radius); }; public: template <typename PolicyT> class Implementation : public virtual Feature::Implementation<PolicyT> { public: using Scalar = typename PolicyT::Scalar; public: virtual void SetSphereShapeRadius( const Identity &_sphereID, Scalar _radius) = 0; }; }; ///////////////////////////////////////////////// /// \brief This feature constructs a new sphere shape and attaches the /// desired pose in the link frame. The pose is defined as the /// sphere center point in actual implementation. class IGNITION_PHYSICS_VISIBLE AttachSphereShapeFeature : public virtual FeatureWithRequirements<SphereShapeCast> { public: template <typename PolicyT, typename FeaturesT> class Link : public virtual Feature::Link<PolicyT, FeaturesT> { public: using Scalar = typename PolicyT::Scalar; public: using PoseType = typename FromPolicy<PolicyT>::template Use<Pose>; public: using ShapePtrType = SphereShapePtr<PolicyT, FeaturesT>; /// \brief Rigidly attach a SphereShape to this link. /// \param[in] _radius /// The radius of the sphere. /// \param[in] _pose /// The desired pose of the SphereShape relative to the Link frame. /// \returns a ShapePtrType to the newly constructed SphereShape public: ShapePtrType AttachSphereShape( const std::string &_name, Scalar _radius = 1.0, const PoseType &_pose = PoseType::Identity()); }; public: template <typename PolicyT> class Implementation : public virtual Feature::Implementation<PolicyT> { public: using Scalar = typename PolicyT::Scalar; public: using PoseType = typename FromPolicy<PolicyT>::template Use<Pose>; public: virtual Identity AttachSphereShape( const Identity &_linkID, const std::string &_name, Scalar _radius, const PoseType &_pose) = 0; }; }; } } #include <ignition/physics/detail/SphereShape.hh> #endif
26ea81a30955aed0e23105c17361f0ea3688e576
cd419581c4712024f85e1cc30d4b0299284ea506
/GameState.h
8ff1ab8934339da9fc7bad9060a34c425ac70bde
[]
no_license
log4me/SDLFlappyBird
d09343ff9363f5882a87d9a3c2e43390794a15fc
87db9b123f899e001617eb58258fdd3ce27789de
refs/heads/master
2021-01-11T14:39:00.016707
2017-01-27T06:51:50
2017-01-27T06:51:50
80,186,996
1
0
null
null
null
null
UTF-8
C++
false
false
463
h
GameState.h
//GameState.h #ifndef GAMESTATE_H #define GAMESTATE_H #include "WorldState.h" class GameState : public WorldState{ public: virtual ~GameState(); virtual void update(); virtual void render(); virtual bool onEnter(); virtual bool onExit(); virtual string getStateID() const{return s_GameID; } private: bool m_loadingComplete; bool m_exiting; vector<string> m_textureIDList; vector<WorldObject*> m_worldObjects; static const string s_GameID; }; #endif
e71496ad26ec225f6e8bb61721b90f8dfcbe8a0a
d82fb53af96a06408d777d008bc1da95574c1274
/WindowLayout/main.cpp
8f9633f589748e3f78722e2fff3ab43dd778a786
[ "MIT" ]
permissive
blacknaml/Qt-Work-Experiments
49da1d0afbd70ddddcf900bd81057582f25d6466
6d02726e6ea57a60f5b98b049b5c90c4ad52a4fc
refs/heads/master
2020-12-02T16:00:14.909713
2016-08-23T15:52:01
2016-08-23T15:52:01
66,380,468
0
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
main.cpp
#include "widget.h" #include <QApplication> #include <QLabel> #include <QLineEdit> #include <QHBoxLayout> int main(int argc, char *argv[]) { QApplication app(argc, argv); Widget window; QLabel *label = new QLabel(QApplication::translate("windowlayout", "Name:")); QLineEdit *lineedit = new QLineEdit(); QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(label); layout->addWidget(lineedit); window.setLayout(layout); window.setWindowTitle(QApplication::translate("windowlayout", "Window Layout")); window.show(); return app.exec(); }
f5202f8cfe68e0c7ffc3e1c04209d8aaa5dc9e7f
55fa93532e1377d3dc7b77833fb024e6d1bda62e
/libs/ossia/include/ossia/editor/curve/curve_segment/linear.hpp
be7b0254852f2c24b450d485f949b6cf12a8ef95
[]
no_license
avilleret/ofxOSSIA
14293f0d762748b77fc646d9807874b807719a31
86474907447004ba0db98ff04c527215378cf50a
refs/heads/master
2021-01-18T11:20:03.269109
2016-08-17T19:41:25
2016-08-17T19:41:30
67,735,146
0
0
null
2016-09-08T19:47:37
2016-09-08T19:47:37
null
UTF-8
C++
false
false
190
hpp
linear.hpp
#pragma once namespace ossia { template <typename Y> struct curve_segment_linear { Y operator()(double ratio, Y start, Y end) const { return start + ratio * (end - start); } }; }
55c84b25e86d1453244287450c3b92ab709166eb
58b5ca0ad9d0db45bc4c47ea0c62e6424b779ba2
/project_week_4/tests/image_geometry_test.cpp
88c409669fa46f78d72eb3588b0807aa8704642a
[]
no_license
green-fox-academy/znemeth
b72f48f4621c9434b1ae114c5b1c368cc21f87c1
eda20c847143812f77d3e5d44614be49cc6dcbbc
refs/heads/master
2020-04-16T18:51:54.696643
2019-07-25T14:27:37
2019-07-25T14:27:37
165,837,872
0
2
null
null
null
null
UTF-8
C++
false
false
1,386
cpp
image_geometry_test.cpp
#include "gtest/gtest.h" #include "../opencv/image_geometry.cpp" class TestGeometryImage : public testing::Test { protected: cv::Mat originalImage; virtual void SetUp() { originalImage = cv::imread("../../../img/speed_sign.jpg"); } }; TEST_F(TestGeometryImage, fileRead) { cv::Mat resultImage = resizerotateImage(originalImage, 1, 0); EXPECT_FALSE(resultImage.empty()); } TEST_F(TestGeometryImage, sizeOfOriginalAndOutputFileResize1) { cv::Mat resultImage = resizerotateImage(originalImage, 1, 0); EXPECT_TRUE(resultImage.size == originalImage.size); } TEST_F(TestGeometryImage, sizeOfOriginalAndOutputFileResize2) { cv::Mat resultImage = resizerotateImage(originalImage, 2, 0); EXPECT_FALSE(resultImage.size == originalImage.size); } TEST_F(TestGeometryImage, sizeOfOriginalAndOutputFileRotate) { cv::Mat resultImage = resizerotateImage(originalImage, 1, 30); EXPECT_TRUE(resultImage.size == originalImage.size); } TEST_F(TestGeometryImage, ratioOfOriginalAndOutputFileResize) { cv::Mat resultImage = resizerotateImage(originalImage, 2, 0); EXPECT_TRUE(resultImage.cols / resultImage.rows == originalImage.cols / originalImage.rows); } TEST_F(TestGeometryImage, ratioOfOriginalAndOutputFileRotate) { cv::Mat resultImage = resizerotateImage(originalImage, 1, 40); EXPECT_TRUE(resultImage.cols / resultImage.rows == originalImage.cols / originalImage.rows); }
e915945d53f093fd8886db1b9d4f79ae43dfcc92
2f0bf6328564b46399b90bad96f5415df8024fd9
/Banking_Project/Banking.cpp
a5e79378dfd6b988a95252280ddeaf9aa9530cfd
[]
no_license
Tejesh-Raut/Banking-Application
8b17d8ee775a430840ad9d21ded62e72b5959997
cd284ddc098e9d1c53794eca48a7d6bcc7e4f14f
refs/heads/master
2021-01-10T15:11:44.653675
2016-01-11T21:40:01
2016-01-11T21:40:01
49,455,085
0
0
null
null
null
null
UTF-8
C++
false
false
31,199
cpp
Banking.cpp
//______________________________________________________________________________________________________ //______________________________________________________________________________________________________ //Header files used in our project //______________________________________________________________________________________________________ #include<iostream> #include<cstdio> #include <fstream> #include<stdlib.h> #include<simplecpp> #include<cmath> //______________________________________________________________________________________________________ //open variables //______________________________________________________________________________________________________ using namespace std; int count; FILE * fp;//declaring a pointer to a file //______________________________________________________________________________________________________ //______________________________________________________________________________________________________ //Structure used in our project //______________________________________________________________________________________________________ struct customer { int Account_num; int PIN; float Balance; char Name[50]; char DOB[11];//dd/mm/yyyy char Address[70];//Maximum 70 characters void create_account() { cout<<"Please fill the following form:"<<endl;//storing information filled by customer in a temporary object c cout<<"Enter your name(Upto maximum 50 characters): "<<endl; cin.clear(); cin.sync(); cin.getline(Name,50); TryAgain19: cout<<"Enter date of birth(dd/mm/yyyy format): "<<endl; cin.clear(); cin.sync(); cin.getline(DOB,11); if((DOB[2]!='/')||(DOB[5]!='/')) { cout<<"You have not entered date of birth in the given format"<<endl; cout<<"Please re-enter it in the given format "<<endl; system("pause"); system("cls"); goto TryAgain19; } cout<<"Enter complete residential address(Upto maximum 70 characters in a single line): "; cin.clear(); cin.sync(); cin.getline(Address,70); TryAgain3://label cout<<"Enter a new PIN(4 digits) for your account"<<endl; cin>>PIN; if((PIN>9999)||(PIN<1000))//Invalid input { system("cls"); cout<<"Invalid input"<<endl; goto TryAgain3;//Re-enter a new PIN } system("cls"); cout<<"Re-Enter PIN:"<<endl; int p; cin>>p; if(p!=PIN)//Invalid re-entering { system("cls"); cout<<"The two PINs entered by you don't match"<<endl; cout<<"Please try again "<<endl; goto TryAgain3;//Try entering new PIN again } TryAgain12: cout<<"Enter Initial balance in the account: "<<endl; cin>>Balance; if(Balance<1000) { cout<<"Any Account must have a minimum balance of 1000"<<endl; system("pause"); system("cls"); goto TryAgain12; } Account_num=count+1000; system("cls"); cout<<"Account created successfully "<<endl; Text t(175,200," Your account number is "); Text t1(175,290,Account_num); Rectangle button(175,400,150,50); Text t2(175,400," OK "); button.setFill(true); button.setColor(COLOR(255,255,153)); TryAgain30: int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; if((cx>=100)&&(cx<=250)&&(cy>=375)&&(cy<=425)) { button.setFill(true); button.setColor(COLOR("red")); wait(0.25); button.setColor(COLOR(255,255,153)); wait(0.25); system("cls"); return; } else { goto TryAgain30; } }//end of create_account void deposit_account() { float amount; system("cls"); cout<<"Enter the amount to be deposited"<<endl; cin>>amount; Balance=Balance+amount; }//end of deposit_account() void withdrawal_account() { float amount; TryAgain13: system("cls"); cout<<"Enter the amount to withdraw"<<endl; cin>>amount; if((Balance-amount)<1000) { cout<<"Any Account must have a minimum balance of 1000"<<endl; system("pause"); system("cls"); goto TryAgain13; } Balance=Balance-amount; }//end of withdrawal_account() void view_account() { cout<<"Name\t:\t"<<Name<<endl; cout<<"Date of birth\t:\t"<<DOB<<endl; cout<<"Residential address\t:\t"<<Address<<endl; cout<<"Current balance\t:\t"<<Balance<<endl<<endl<<endl; }//end of view_account() void modify_account() { TryAgain8 : system("cls"); Rectangle button(175,81,150,70); Text t(175,81," Name "); button.setFill(true); button.setColor(COLOR(255,255,153)); Rectangle button1(175,187,150,70); Text t1(175,187," Date of birth "); button1.setFill(true); button1.setColor(COLOR(255,255,153)); Rectangle button2(175,293,150,70); Text t2(175,293," Residential Address "); button2.setFill(true); button2.setColor(COLOR(255,255,153)); Rectangle button3(175,399,150,70); Text t3(175,399," PIN "); button3.setFill(true); button3.setColor(COLOR(255,255,153)); int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; if((cx>=100)&&(cx<=250)&&(cy>=46)&&(cy<=106)) { button.setFill(true); button.setColor(COLOR("red")); wait(0.25); button.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); cout<<"Enter your new name(Upto maximum 50 characters): "<<endl; cin.clear(); cin.sync(); cin.getline(Name,50); return; } if((cx>=100)&&(cx<=250)&&(cy>=152)&&(cy<=222)) { button1.setFill(true); button1.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); TryAgain20: cout<<"Enter new date of birth(dd/mm/yyyy format): "<<endl; cin.clear(); cin.sync(); cin.getline(DOB,11); if((DOB[2]!='/')||(DOB[5]!='/')) { cout<<"You have not entered date of birth in the given format"<<endl; cout<<"Please re-enter it in the given format "<<endl; system("pause"); system("cls"); goto TryAgain20; } return; } if((cx>=100)&&(cx<=250)&&(cy>=258)&&(cy<=328)) { button2.setFill(true); button2.setColor(COLOR("red")); wait(0.25); button2.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); cout<<"Enter new complete residential address(Upto maximum 70 characters in a single line): "; cin.clear(); cin.sync(); cin.getline(Address,70); return; } if((cx>=100)&&(cx<=250)&&(cy>=364)&&(cy<=434)) { button3.setFill(true); button3.setColor(COLOR("red")); wait(0.25); button3.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); TryAgain6 : int pin; cout<<"Enter current PIN : "<<endl; cin>>pin; if(PIN!=pin) { cout<<"You have entered incorrect PIN"<<endl; cout<<"Please try again"<<endl; system("pause"); system("cls"); goto TryAgain6; } TryAgain7://label system("cls"); cout<<"Enter a new PIN(4 digits) for your account"<<endl; cin>>PIN; if((PIN>9999)||(PIN<1000))//Invalid input { system("cls"); cout<<"Invalid input"<<endl; goto TryAgain7;//Re-enter a new PIN } system("cls"); cout<<"Re-Enter PIN:"<<endl; int p; cin>>p; if(p!=PIN)//Invalid re-entering { system("cls"); cout<<"The two PINs entered by you don't match"<<endl; cout<<"Please try again "<<endl; goto TryAgain7;//Try entering new PIN again } return; } else { goto TryAgain8; } }//End of modify_account() void delete_account() { Text t(175,81," Name "); Name[0]='-';Name[1]='\0'; DOB[0]='-';DOB[1]='\0'; Address[0]='-';Address[1]='\0'; PIN =0; Balance=0; }//end of delete_account() void loan_account() { int year;float principal,amount; cout<<"Enter the amount to be taken as loan "<<endl; cin>>principal; cout<<"Enter the time in years to take the loan "<<endl; cout<<"(You can take only for integral number of years"<<endl; cout<<"Our interest rate is only 10% per annum )"<<endl; cin>>year; amount=principal*(pow(1.1,year)); system("cls"); Text t(175,55," You will have to repay "); Text t3(75,115,amount); Text t4(150,115," after "); Text t5(225,115,year); Text t6(300,115," years "); Text t7(175,225," Confirm ? "); Rectangle button1(175,315,150,70); Text t1(175,315," Yes "); button1.setFill(true); button1.setColor(COLOR(255,255,153)); Rectangle button2(175,425,150,70); Text t2(175,425," No "); button2.setFill(true); button2.setColor(COLOR(255,255,153)); TryAgain31: int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; if((cx>=100)&&(cx<=250)&&(cy>=280)&&(cy<=350))//yes { button1.setFill(true); button1.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); Balance=Balance+principal; system("cls"); cout<<"Loan received successfully "<<endl; return; } if((cx>=100)&&(cx<=250)&&(cy>=390)&&(cy<=460))//no { button2.setFill(true); button2.setColor(COLOR("red")); wait(0.25); button2.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); return; } else { goto TryAgain31; } }//end of loan_account() void fixeddeposit_account() { int year;float principal,amount; TryAgain18: cout<<"Enter the amount to be given as fixed deposit "<<endl; cin>>principal; cout<<"Enter the time in years to keep fixed deposit "<<endl; cout<<"(You can take only for integral number of years"<<endl; cout<<"You will get profit of 8% per annum )"<<endl; cin>>year; amount=principal*(pow(1.08,year)); system("cls"); Text t(175,55," You will get "); Text t3(75,115,amount); Text t4(150,115," after "); Text t5(225,115,year); Text t6(300,115," years "); Text t7(175,225," Confirm ? "); Rectangle button1(175,315,150,70); Text t1(175,315," Yes "); button1.setFill(true); button1.setColor(COLOR(255,255,153)); Rectangle button2(175,425,150,70); Text t2(175,425," No "); button2.setFill(true); button2.setColor(COLOR(255,255,153)); TryAgain32: int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; if((cx>=100)&&(cx<=250)&&(cy>=280)&&(cy<=350))//yes { button1.setFill(true); button1.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); if((Balance-principal)<1000) { cout<<"Any Account must have a minimum balance of 1000"<<endl; system("pause"); system("cls"); goto TryAgain18; } Balance=Balance-principal; system("cls"); cout<<"Fixed deposit created successfully "<<endl; return; } if((cx>=100)&&(cx<=250)&&(cy>=390)&&(cy<=460))//no { button2.setFill(true); button2.setColor(COLOR("red")); wait(0.25); button2.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); return; } else { goto TryAgain32; } cout<<amount<<"will be deposited in your account after "<<year<<" years "<<endl; cout<<"Enter Y/y to proceed or enter N/n to go back "<<endl; char w; cin>>w; if((w=='Y')||(w=='y')) { if((Balance-principal)<1000) { cout<<"Any Account must have a minimum balance of 1000"<<endl; system("pause"); system("cls"); goto TryAgain18; } Balance=Balance-principal; system("cls"); cout<<"Fixed deposit created successfully "<<endl; } else { return; } }//end of fixeddeposit_account() };//end of structure customer //______________________________________________________________________________________________________ //______________________________________________________________________________________________________ //Open functions and some more variables //______________________________________________________________________________________________________ customer c; int rec_size=sizeof(struct customer);//getting size of above structure void create_acc() { fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if long POS;//to denote position in the current file fseek ( fp , 0 , SEEK_END );//Set cursor to the end of the file POS=ftell(fp); count=POS/rec_size; c.create_account(); fseek ( fp , 0 , SEEK_END ); fwrite(&c,rec_size,1,fp); fclose(fp); return; }//end of create_acc void deposit_acc(long POS) { fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.deposit_account(); fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record system("cls"); cout<<"Your account was credited successfully."<<endl; fclose(fp); }//end of deposit_acc void withdrawal_acc(long POS) { fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.withdrawal_account(); fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record system("cls"); cout<<"Your account was debited successfully."<<endl; fclose(fp); }//end of withdrawal_acc() void view_acc(long POS) { fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.view_account(); fclose(fp); }//end of view_acc void modify_acc(long POS) { fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.modify_account(); fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record system("cls"); cout<<"Your account was modified successfully."<<endl; fclose(fp); }//end of modify_acc() void delete_acc(long POS) { fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.delete_account(); fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record system("cls"); cout<<"Your account was deleted successfully."<<endl; fclose(fp); }//end of delete_acc() void transfer_acc(long POS) { long pos; fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c int amount,acc_no1; TryAgain21: system("cls"); cout<<"Enter the account number of the account to which money is to be transferred"<<endl; cin>>acc_no1; if(acc_no1==(1000+POS/rec_size)) { cout<<"You cant enter your own account number for transfer "<<endl; cout<<"Please enter correct information "<<endl; system("pause"); goto TryAgain21; } fseek ( fp , 0 , SEEK_END );//Set cursor to the end of the file pos=ftell(fp); count=pos/rec_size; if((acc_no1>(count+1000))||(acc_no1<1000)) { cout<<"You have entered incorrect account number"<<endl; cout<<"Please try again"<<endl; system("pause"); goto TryAgain21; } TryAgain15: cout<<"Enter the amount to be transferred :"<<endl; cin>>amount; if((c.Balance-amount)<1000) { cout<<"Any Account must have a minimum balance of 1000"<<endl; system("pause"); system("cls"); goto TryAgain15; } c.Balance=c.Balance-amount; fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record customer c1; long POS1;//to store position of the record of account to which transfer is being done POS1=(acc_no1-1000)*rec_size; fseek(fp,POS1,SEEK_SET); fread(&c1,rec_size,1,fp);//reading record into c1 c1.Balance=c1.Balance+amount; fseek(fp,POS1,SEEK_SET); fwrite(&c1,rec_size,1,fp); system("cls"); cout<<"Your transfer was done successfully."<<endl; fclose(fp); }//end of transfer_acc() void loan_acc(long POS) { system("cls"); fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.loan_account(); fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record fclose(fp); }//end of loan_acc() void fixeddeposit_acc(long POS) { system("cls"); fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return; }//end of if fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp);//reading record into c c.fixeddeposit_account(); fseek(fp,POS,SEEK_SET);//taking back to same position for update of record fwrite(&c,rec_size,1,fp);//updating record fclose(fp); }//end of fixeddeposit_acc() //______________________________________________________________________________________________________ //______________________________________________________________________________________________________ //main function of our program //______________________________________________________________________________________________________ main_program { initCanvas("Controller",350,510); Rectangle Erase1(175,255,350,510); Erase1.setFill(true); Erase1.setColor(COLOR(255,255,153)); Text t7(175,175,"WELCOME"); Text t8(175,250,"TO THE"); Text t9(175,325,"BANK MANAGEMENT SYSTEM"); wait(3); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); TryAgain10: Rectangle button(175,125,150,50); Text t(175,125," Log In "); button.setFill(true); button.setColor(COLOR(255,255,153)); Rectangle button1(175,275,150,50); Text t1(175,275," Create New Account "); button1.setFill(true); button1.setColor(COLOR(255,255,153)); Rectangle button2(175,425,150,50); Text t2(175,425," View all accounts "); button2.setFill(true); button2.setColor(COLOR(255,255,153)); int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; system("cls"); if((cx>=100)&&(cx<=250)&&(cy>=100)&&(cy<=150))//log in { button.setFill(true); button.setColor(COLOR("red")); wait(0.25); button.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); int acc_no,pin; TryAgain4: system("cls"); cout<<"Enter account no. :"<<endl; cin.clear(); cin.sync(); cin>>acc_no; cout<<"Enter PIN :"<<endl; cin.clear(); cin.sync(); cin>>pin; fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return -1; }//end of if struct customer c; int n; long POS;//to denote position in the current file POS=(acc_no-1000)*rec_size; fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp); if (c.PIN!=pin) { cout<<"You have provided a wrong information"<<endl; cout<<"Please try again"<<endl; system("pause"); system("cls"); goto TryAgain4; } //log in successfull system("cls"); TryAgain11: Rectangle button(100,65,100,70); Text t(100,65," Deposit "); button.setFill(true); button.setColor(COLOR(255,255,153)); Rectangle button1(100,165,100,70); Text t1(100,165," Withdrawal "); button1.setFill(true); button1.setColor(COLOR(255,255,153)); Rectangle button2(100,265,100,70); Text t2(100,265," Transfer "); button2.setFill(true); button2.setColor(COLOR(255,255,153)); Rectangle button3(100,365,100,70); Text t3(100,365," View "); button3.setFill(true); button3.setColor(COLOR(255,255,153)); Rectangle button4(250,265,100,70); Text t4(250,265," Modify "); button4.setFill(true); button4.setColor(COLOR(255,255,153)); Rectangle button5(250,365,100,70); Text t5(250,365," Delete "); button5.setFill(true); button5.setColor(COLOR(255,255,153)); Rectangle button6(175,460,150,60); Text t6(175,460," Log Out "); button6.setFill(true); button6.setColor(COLOR(255,255,153)); Rectangle button10(250,65,100,70); Text t10(250,65," Loan "); button10.setFill(true); button10.setColor(COLOR(255,255,153)); Rectangle button11(250,165,100,70); Text t11(250,165," Fixed Deposit "); button11.setFill(true); button11.setColor(COLOR(255,255,153)); int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; if((cx>=50)&&(cx<=150)&&(cy>=30)&&(cy<=100))//deposit { button.setFill(true); button.setColor(COLOR("red")); wait(0.25); button.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); deposit_acc(POS); goto TryAgain11; } if((cx>=50)&&(cx<=150)&&(cy>=130)&&(cy<=200))//withdrawal { button1.setFill(true); button1.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); withdrawal_acc(POS); goto TryAgain11; } if((cx>=50)&&(cx<=150)&&(cy>=230)&&(cy<=300))//Transfer { button2.setFill(true); button2.setColor(COLOR("red")); wait(0.25); button2.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); transfer_acc(POS); goto TryAgain11; } if((cx>=50)&&(cx<=150)&&(cy>=330)&&(cy<=400))//View { button3.setFill(true); button3.setColor(COLOR("red")); wait(0.25); button3.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); view_acc(POS); goto TryAgain11; } if((cx>=200)&&(cx<=300)&&(cy>=230)&&(cy<=300))//Modify { button4.setFill(true); button4.setColor(COLOR("red")); wait(0.25); button4.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); modify_acc(POS); goto TryAgain11; } if((cx>=200)&&(cx<=300)&&(cy>=30)&&(cy<=100))//Loan { button10.setFill(true); button10.setColor(COLOR("red")); wait(0.25); button10.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); loan_acc(POS); goto TryAgain11; } if((cx>=200)&&(cx<=300)&&(cy>=130)&&(cy<=200))//FD { button11.setFill(true); button11.setColor(COLOR("red")); wait(0.25); button11.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); fixeddeposit_acc(POS); goto TryAgain11; } if((cx>=200)&&(cx<=300)&&(cy>=330)&&(cy<=400))//Delete { button5.setFill(true); button5.setColor(COLOR("red")); wait(0.25); button5.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); TryAgain16: system("cls"); Text t(175,150," Confirm deletion "); Rectangle button1(175,285,150,70); Text t1(175,285," Yes "); button1.setFill(true); button1.setColor(COLOR(255,255,153)); Rectangle button2(175,415,150,70); Text t2(175,415," No "); button2.setFill(true); button2.setColor(COLOR(255,255,153)); int clickpos = getClick(); int cx = clickpos/65536; int cy = clickpos%65536; if((cx>=100)&&(cx<=250)&&(cy>=250)&&(cy<=320))//yes { button1.setFill(true); button1.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); delete_acc(POS); goto TryAgain10; } if((cx>=100)&&(cx<=250)&&(cy>=380)&&(cy<=450))//no { button2.setFill(true); button2.setColor(COLOR("red")); wait(0.25); button2.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); goto TryAgain11; } else { goto TryAgain16; } }//end of delete if((cx>=100)&&(cx<=250)&&(cy>=430)&&(cy<=490))//Logout { button6.setFill(true); button6.setColor(COLOR("red")); wait(0.25); button6.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); system("cls"); goto TryAgain10; } else { goto TryAgain11; } }//end of log in button if((cx>=100)&&(cx<=250)&&(cy>=250)&&(cy<=300))//create new account button pressed { button1.setFill(true); button1.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); create_acc(); system("cls"); goto TryAgain10; }//end of button create new account if((cx>=100)&&(cx<=250)&&(cy>=400)&&(cy<=450))//view all accounts { button2.setFill(true); button2.setColor(COLOR("red")); wait(0.25); button1.setColor(COLOR(255,255,153)); wait(0.25); Rectangle Erase(175,255,350,510); Erase.setFill(true); Erase.setColor(COLOR(255,178,102)); fp=fopen("customers_data.txt","rb+"); if(fp==NULL)//Unable to open the file { cout<<"Could not open database file"<<endl; return 0; }//end of if long POS;//to denote position in the current file fseek ( fp , 0 , SEEK_END );//Set cursor to the end of the file POS=ftell(fp); count=POS/rec_size; int i; for(i=0;i<count;i++) { POS=i*rec_size; fseek(fp,POS,SEEK_SET); fread(&c,rec_size,1,fp); cout<<endl<<endl<<"Account number : "<<(1000+i)<<endl; view_acc(POS); } goto TryAgain10; }//end of view all accounts else { goto TryAgain10; } }//end of main
030b55354290bb2fbca42f0a0341a552d9522122
fa31838af133b6ed23355cdf6f10f64b7e2874de
/include/operator.hh
bc4daeefd38f1b5c17977a68949293f4eef775da
[]
no_license
grasingerm/calgebra
d128ef9ebc9cf580e8e5687011440c73d99c53e9
8f70643909b048bb3c4f2c271216cb9fcc1c6db3
refs/heads/master
2021-05-03T11:21:31.791023
2016-11-23T07:46:36
2016-11-23T07:46:36
65,251,982
0
0
null
null
null
null
UTF-8
C++
false
false
4,454
hh
operator.hh
#ifndef __OPERATOR_HH #define __OPERATOR_HH #include "token.hh" #include <stdexcept> #include <iostream> #include <memory> namespace scalc { enum class Associativity { LEFT, RIGHT }; class AbstractOperator : public AbstractToken { private: int precedence; Associativity associativity; virtual void _parse(TokenQueue&, TokenStack&) const; virtual void _eval(TokenQueue&, TokenStack&) const=0; virtual void _pushToTokenStack(TokenStack&) const=0; public: AbstractOperator(const int precedence, const Associativity associativity) : precedence(precedence), associativity(associativity) {} virtual ~AbstractOperator() {} virtual std::string toString() const=0; virtual TokenHandler getInverse() const=0; inline auto getPrecedence() const noexcept { return precedence; } inline auto getAssociativity() const noexcept { return associativity; } }; inline bool isTokenOperator(const AbstractToken* ptoken) { return (dynamic_cast<const AbstractOperator*>(ptoken) != nullptr); } int getTokenPrecedence(const AbstractToken* ptoken); class Carrot : public AbstractOperator { public: Carrot() : AbstractOperator(5, Associativity::RIGHT) {} virtual TokenHandler getInverse() const { throw std::logic_error("Cannot solve equations with '^' operator"); return TokenHandler(nullptr); } virtual ~Carrot() {} virtual std::string toString() const { return std::string(1, '^'); } private: virtual void _eval(TokenQueue&, TokenStack&) const; inline virtual void _pushToTokenStack(TokenStack& ts) const { ts.emplace(new Carrot()); } friend std::ostream& operator<<(std::ostream& os, const Carrot&) { os << '^'; return os; } }; class Negation : public AbstractOperator { public: Negation() : AbstractOperator(4, Associativity::RIGHT) {} virtual ~Negation() {} virtual TokenHandler getInverse() const { return TokenHandler(new Negation()); } virtual std::string toString() const { return std::string(1, '-'); } private: virtual void _eval(TokenQueue&, TokenStack&) const; inline virtual void _pushToTokenStack(TokenStack& ts) const { ts.emplace(new Negation()); } friend std::ostream& operator<<(std::ostream& os, const Negation&) { os << '-'; return os; } }; class Multiplication : public AbstractOperator { public: Multiplication() : AbstractOperator(3, Associativity::LEFT) {} virtual ~Multiplication() {} virtual TokenHandler getInverse() const; virtual std::string toString() const { return std::string(1, '*'); } private: virtual void _eval(TokenQueue&, TokenStack&) const; inline virtual void _pushToTokenStack(TokenStack& ts) const { ts.emplace(new Multiplication()); } friend std::ostream& operator<<(std::ostream& os, const Multiplication&) { os << '*'; return os; } }; class Division : public AbstractOperator { public: Division() : AbstractOperator(3, Associativity::LEFT) {} virtual ~Division() {} virtual TokenHandler getInverse() const; virtual std::string toString() const { return std::string(1, '/'); } private: virtual void _eval(TokenQueue&, TokenStack&) const; inline virtual void _pushToTokenStack(TokenStack& ts) const { ts.emplace(new Division()); } friend std::ostream& operator<<(std::ostream& os, const Division&) { os << '/'; return os; } }; class Addition : public AbstractOperator { public: Addition() : AbstractOperator(2, Associativity::LEFT) {} virtual ~Addition() {} virtual TokenHandler getInverse() const; virtual std::string toString() const { return std::string(1, '+'); } private: virtual void _eval(TokenQueue&, TokenStack&) const; inline virtual void _pushToTokenStack(TokenStack& ts) const { ts.emplace(new Addition()); } friend std::ostream& operator<<(std::ostream& os, const Addition&) { os << '+'; return os; } }; class Subtraction : public AbstractOperator { public: Subtraction() : AbstractOperator(2, Associativity::LEFT) {} virtual ~Subtraction() {} virtual TokenHandler getInverse() const; virtual std::string toString() const { return std::string(1, '-'); } private: virtual void _eval(TokenQueue&, TokenStack&) const; inline virtual void _pushToTokenStack(TokenStack& ts) const { ts.emplace(new Subtraction()); } friend std::ostream& operator<<(std::ostream& os, const Subtraction&) { os << '-'; return os; } }; } // namespace scalc #endif // __OPERATOR_HH
5061250fa134cb1a8b1ed0055a0128ce4bf93557
e2f8e283f9d4ff283cc066c22913b50acd93302d
/CodeChef/Dynamic Programming/Flash vs QuickSilver.cpp
d96b0e3b1a36eea5b71af4b8ca1137e472c0f5ac
[]
no_license
kenneth-kho/cp
e57771b1c3f967946011b4f356299a00ab92ad97
6639d15bc5b658862b6c95c66a714a3875fb887b
refs/heads/master
2020-09-02T19:51:04.061805
2020-01-09T02:41:41
2020-01-09T02:41:41
219,286,602
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
Flash vs QuickSilver.cpp
//https://www.codechef.com/problems/FLAASH //Calculate and memoize the minimum time between going down 1 step, down to n/2, or down to n/3 (when possible) #include<iostream> using namespace std; long long dp[1000002]={0,0}; int main(){ for(int i=2;i<1000001;i++){ if(i%6==0)dp[i]=min(min(dp[i/2],dp[i/3]),dp[i-1])+1; else if(i%3==0)dp[i]=min(dp[i/3],dp[i-1])+1; else if(i%2==0)dp[i]=min(dp[i/2],dp[i-1])+1; else dp[i]=dp[i-1]+1; }int t;cin>>t; while(t--){ int n;cin>>n; cout<<dp[n]<<'\n'; } }
581a5042c00631b48570f7ba46d7f1e7bb301fa8
624f1e7153cfdce4433af562d86b4821d27762a7
/klondike/src/Option.h
2c30e4c6fd5f76f18dcbff28ad3da1504a5e7bfb
[]
no_license
sarroutbi/pexpupm
284c6a8417efa778c322572286fa30f234e2aa48
5259a4184868770c07ed79a9f87b17679746e804
refs/heads/master
2020-06-06T08:30:19.312664
2019-02-13T15:31:17
2019-02-13T15:31:17
34,008,495
0
0
null
null
null
null
UTF-8
C++
false
false
236
h
Option.h
#ifndef OPTION_H #define OPTION_H #include <string> #include "GameAction.h" class Option { public: Option() {}; virtual ~Option() {}; virtual void Display() = 0; virtual GameAction* GetGameAction() = 0; }; #endif // OPTION_H
e65ac4e924e4a2fcc4b536204c32ec5dc1108f44
b09de87297dde13c874d24db2541817d788b2594
/directX/manager.h
13c5b2a1c2ed71205287a69cc2b7d9bb7ce84bd1
[]
no_license
tnbmi/TGS_20150327
f28e84aa846594c5753f249147376b350e916011
5e4f4ab119648207b6fe05c5819102f4a907845e
refs/heads/master
2020-03-31T02:13:59.268880
2015-03-29T15:38:51
2015-03-29T15:38:51
31,594,249
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,450
h
manager.h
//***************************************************************************** // // CManagerクラス [manager.h] // Author :MAI TANABE // //***************************************************************************** #ifndef _MY_MANAGER_H #define _MY_MANAGER_H //============================================================================= //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // インクルードファイル //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #include "main.h" //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // クラス定義 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ class CRenderer; class CDebugproc; class CImport; class CPhase; class CInputKeyboard; class CManager { public: CManager(); ~CManager(){}; static CManager* Create(HINSTANCE instance, HWND wnd, bool window); HRESULT Init(HINSTANCE instance, HWND wnd, bool window); void Uninit(void); void Update(void); void Draw(void); void CalculateFPS(DWORD frameCnt, DWORD curTime, DWORD FPSLastTime); static void SetNextPhase(CPhase* phase){m_phaseNext = phase;} private: CRenderer* m_renderer; CDebugproc* m_debugproc; CImport* m_import; CPhase* m_phase; static CPhase* m_phaseNext; CInputKeyboard* m_keyboard; }; //============================================================================= #endif
cba2c03802b71c6fa11b308353894eacb8eedc98
4b2a43128f60c39aecfd54b4b2df75dd8fdb3f33
/include/xcspp/core/xcsr/xcsr_repr.hpp
9a8209bdfa46ce7a86e9be4a7a91176a28011e97
[ "MIT" ]
permissive
m4saka/xcspp
3348f7dfbcd4c6a018373dad540bbb4076183ccf
a383170c1dece7d233e91ca64fd8a62968b967f9
refs/heads/master
2023-07-08T07:20:53.040917
2021-08-11T13:22:40
2021-08-11T13:22:40
290,694,867
3
2
null
null
null
null
UTF-8
C++
false
false
973
hpp
xcsr_repr.hpp
#pragma once #include <cmath> #include "xcspp/util/random.hpp" namespace xcspp::xcsr { // XCSR representation enum class XCSRRepr { kCSR, // Center-Spread Representation [ c - s , c + s ) kOBR, // Ordered-Bound Representation [ l , u ) kUBR, // Unordered-Bound Representation [ min(p,q) , max(p,q) ) }; // Forward declarations for function arguments class Symbol; struct XCSRParams; // --- Functions that depends on the representation --- double GetLowerBound(const Symbol & s, XCSRRepr repr); double GetUpperBound(const Symbol & s, XCSRRepr repr); double ClampSymbolValue1(double v1, XCSRRepr repr, double minValue, double maxValue, bool doRangeRestriction); double ClampSymbolValue2(double v2, XCSRRepr repr, double minValue, double maxValue, bool doRangeRestriction); Symbol MakeCoveringSymbol(double inputValue, const XCSRParams *pParams, Random & random); }
8032d371f762e6f44e54a6e78511e38a95864cb5
dec18c88baf887f176afb8b9597d21d1c1d56e52
/mainwindow.cpp
ffb0ef352ec15cec704839f03327327c4af3f1f5
[ "MIT" ]
permissive
plenarius/cleanmodels-qt
04fb6b7487e5e661f4fdbe3631a937a8ddeb0496
22de0b75fbc50b2eb57f98b75506ea13b06c131b
refs/heads/main
2023-02-15T15:45:03.573142
2021-01-09T07:28:18
2021-01-09T07:28:18
321,256,290
2
1
null
null
null
null
UTF-8
C++
false
false
48,902
cpp
mainwindow.cpp
#include "fsmodel.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include <QApplication> #include <QClipboard> #include <QCompleter> #include <QDebug> #include <QFile> #include <QFileDialog> #include <QFileInfo> #include <QMessageBox> #include <QProgressBar> #include <QScreen> #include <QScrollBar> #include <QSettings> #include <QStandardPaths> #include <QStringBuilder> #include <QTableWidgetItem> #include <QTextStream> #include <QWhatsThis> #include <QWindow> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->debugTextBrowser->insertHtml(tr("Welcome to Clean Models:EE QT!<br>")); #ifdef Q_OS_WIN m_sBinaryName = "cleanmodels-cli.exe"; #else m_sBinaryName = "cleanmodels-cli"; #endif bool cliFound = true; auto cliInPath = QStandardPaths::findExecutable(m_sBinaryName); if (cliInPath.isEmpty()) { QStringList cliPaths = {QDir::currentPath(), QApplication::applicationDirPath()}; cliInPath = QStandardPaths::findExecutable(m_sBinaryName, cliPaths); if (cliInPath.isEmpty()) cliFound = false; } if (cliFound) { m_sBinaryPath = cliInPath; QString foundMsg = "Clean Models Command Line Interface found at " % m_sBinaryPath; ui->debugTextBrowser->insertHtml(tr(foundMsg.toStdString().c_str())); auto sb = ui->debugTextBrowser->verticalScrollBar(); sb->setValue(sb->maximum()); } else { QString errorMsg = "Could not find the " % m_sBinaryName % " executable in the current directory or in your path!"; QMessageBox::critical(nullptr, "No cleanmodels-cli", tr(errorMsg.toStdString().c_str())); ui->debugTextBrowser->insertHtml(tr(errorMsg.toStdString().c_str())); auto sb = ui->debugTextBrowser->verticalScrollBar(); sb->setValue(sb->maximum()); } m_pCleanProcess = new QProcess(this); m_bCleanRunning = false; m_sLastDirsPath = QCoreApplication::applicationDirPath() % "/last_dirs.pl"; bool fileExists = QFileInfo::exists(m_sLastDirsPath) && QFileInfo(m_sLastDirsPath).isFile(); if (!fileExists) { QFile fromResource(":/last_dirs.pl"); fromResource.copy(m_sLastDirsPath); QFile out(m_sLastDirsPath); out.setPermissions(QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther | QFileDevice::WriteOwner | QFileDevice::WriteGroup); } auto* sStatusLabel = new QLabel( QString( tr("Status:") ) ); m_pCleanStatus = new QLabel( QString( tr("Idle") ) ); m_pStatusProgress = new QProgressBar(); m_pStatusProgress->setRange(0, 0); m_pStatusProgress->setTextVisible(false); m_pStatusProgress->setVisible(false); m_pStatusProgress->setMaximumHeight(12); m_pStatusProgress->setMaximumWidth(100); statusBar()->addPermanentWidget( m_pStatusProgress ); statusBar()->addPermanentWidget( sStatusLabel ); statusBar()->addPermanentWidget( m_pCleanStatus ); m_pDirCompleter = new QCompleter(this); m_pDirCompleter->setMaxVisibleItems(4); m_pFileSystemModel = new FileSystemModel(m_pDirCompleter); m_pFileSystemModel->setFilter(QDir::Dirs|QDir::Drives|QDir::NoDotAndDotDot|QDir::AllDirs); m_pDirCompleter->setModel(m_pFileSystemModel); ui->inDirectory->setCompleter(m_pDirCompleter); ui->outDirectory->setCompleter(m_pDirCompleter); ui->filesTable->setColumnCount(5); ui->filesTable->setColumnWidth(1, 100); ui->filesTable->setColumnWidth(2, 140); ui->filesTable->setColumnWidth(3, 70); ui->filesTable->setColumnWidth(4, 100); ui->filesTable->setHorizontalHeaderLabels({"File", "Size", "Status", "Fixes", "Time"}); ui->filesTable->setAlternatingRowColors(true); ui->filesTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->filesTable->horizontalHeader()->setVisible(true); ui->filesTable->verticalHeader()->setDefaultSectionSize(20); ui->filesTable->verticalHeader()->setVisible(false); ui->filesTable->setContextMenuPolicy(Qt::CustomContextMenu); ui->filesTable->setSelectionMode(QAbstractItemView::SingleSelection); ui->filesTable->setSelectionBehavior(QAbstractItemView::SelectRows); m_iconReadingMDL = QIcon(":icons/reading-mdl"); m_iconDecompilingMDL = QIcon(":icons/decompiling-mdl"); m_iconCleaningMDL = QIcon(":icons/cleaning-mdl"); m_iconCleanSuccess = QIcon(":icons/clean-success"); m_iconCleanError = QIcon(":icons/clean-error"); m_iconCleanButton = QIcon(":icons/clean-button"); m_iconASCIIMdl = QIcon(":icons/mdl-ascii"); m_iconBinaryMdl = QIcon(":icons/mdl-binary"); m_iconAbortButton = QIcon(":icons/abort-button"); m_iconDecompileButton = QIcon(":icons/decompile-button"); m_iconLockRescaleBtn = QIcon(":icons/lock-rescale"); m_iconUnlockRescaleBtn = QIcon(":icons/unlock-rescale"); ui->actionLoadPreset->setIcon(QIcon(":icons/load-preset")); ui->actionSavePreset->setIcon(QIcon(":icons/save-preset")); ui->actionHelp->setIcon(QIcon(":icons/whats-this")); ui->indirButton->setIcon(QIcon(":icons/indir")); ui->outdirButton->setIcon(QIcon(":icons/outdir")); ui->cleanButton->setIcon(m_iconCleanButton); m_dirWatcherTimer = new QTimer(this); m_dirWatcherTimer->setInterval(500); connect(m_dirWatcherTimer, &QTimer::timeout, this, QOverload<>::of(&MainWindow::handleDirWatcherTimer)); m_bUpdateFilesAfterClean = false; readInLastDirs(m_sLastDirsPath); QObject::connect(m_pCleanProcess, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, &MainWindow::onCleanFinished); QObject::connect(ui->actionHelp, SIGNAL(triggered()), this, SLOT(onHelpTriggered())); QObject::connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(onAboutTriggered())); QObject::connect(ui->actionSavePreset, SIGNAL(triggered()), this, SLOT(onSaveConfigTriggered())); QObject::connect(ui->actionLoadPreset, SIGNAL(triggered()), this, SLOT(onLoadConfigTriggered())); QObject::connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(onQuitTriggered())); QObject::connect(&m_fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(onDirectoryContentsChanged())); readSettings(); } MainWindow::~MainWindow() { delete ui; m_pCleanProcess->close(); delete m_pCleanProcess; } // Window Position/Geometry void MainWindow::readSettings() { QScreen *screen = QGuiApplication::primaryScreen(); if (const QWindow *window = windowHandle()) screen = window->screen(); if (!screen) return; QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName()); const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray(); if (geometry.isEmpty()) { const QRect availableGeometry = screen->availableGeometry(); resize(availableGeometry.width() / 3, availableGeometry.height() / 2); move((availableGeometry.width() - width()) / 2, (availableGeometry.height() - height()) / 2); } else { restoreGeometry(geometry); } } void MainWindow::writeSettings() { QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName()); settings.setValue("geometry", saveGeometry()); } void MainWindow::closeEvent(QCloseEvent*) { writeSettings(); } // Main last_dirs parsing and writing functions void MainWindow::readInLastDirs(const QString& fileLoc) { QFile inputFile(fileLoc); if (inputFile.open(QIODevice::ReadOnly)) { QTextStream in(&inputFile); while (!in.atEnd()) { QString line = in.readLine(); QString str = R"(^:-asserta\((.*)\((.*)[,]?(\w+|\[.*\])?\)\)\.$)"; QRegularExpression re(str, QRegularExpression::InvertedGreedinessOption | QRegularExpression::MultilineOption); QRegularExpressionMatchIterator i = re.globalMatch(line); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString captured = match.captured(1); QString capturedTwo = match.captured(2).isEmpty() ? match.captured(3) : match.captured(2); if (captured.isEmpty() || capturedTwo.isEmpty()) break; if (capturedTwo.startsWith("'")) capturedTwo.remove(0,1); if (capturedTwo.endsWith("'")) capturedTwo.chop(1); if (captured == "g_indir") { onUpdateInDir(capturedTwo); QDir absDir; m_pFileSystemModel->setRootPath(absDir.absoluteFilePath(capturedTwo)); } else if (captured == "g_outdir") { m_sOutDir = capturedTwo; ui->outDirectory->setText(m_sOutDir); QDir absDir; m_pFileSystemModel->setRootPath(absDir.absoluteFilePath(m_sOutDir)); } else if (captured == "g_pattern") { ui->filePattern->setText(capturedTwo); } else if (captured == "g_logfile") { ui->logFileName->setText(capturedTwo); } else if (captured == "g_small_log") { ui->summaryLogFileName->setText(capturedTwo); } else if (captured == "g_user_option") { QString value = match.captured(3); if (capturedTwo == "classification") { if (value == "character") ui->modelClassCombo->setCurrentIndex(1); else if (value == "door") ui->modelClassCombo->setCurrentIndex(2); else if (value == "effect") ui->modelClassCombo->setCurrentIndex(3); else if (value == "item") ui->modelClassCombo->setCurrentIndex(4); else if (value == "tile") ui->modelClassCombo->setCurrentIndex(5); else ui->modelClassCombo->setCurrentIndex(0); } else if (capturedTwo == "snap") { if (value == "binary") ui->snapCombo->setCurrentIndex(1); else if (value == "decimal") ui->snapCombo->setCurrentIndex(2); else if (value == "fine") ui->snapCombo->setCurrentIndex(3); else ui->snapCombo->setCurrentIndex(0); } else if (capturedTwo == "tvert_snap") { if (value == "256") ui->snapTVertsCombo->setCurrentIndex(1); else if (value == "512") ui->snapTVertsCombo->setCurrentIndex(2); else if (value == "1024") ui->snapTVertsCombo->setCurrentIndex(3); else ui->snapTVertsCombo->setCurrentIndex(0); } else if (capturedTwo == "use_Smoothed") { if (value == "ignore") ui->smoothingGroupsCombo->setCurrentIndex(1); else if (value == "protect") ui->smoothingGroupsCombo->setCurrentIndex(2); else ui->smoothingGroupsCombo->setCurrentIndex(0); } else if (capturedTwo == "fix_overhangs") { if (value == "yes") ui->repairAABBCombo->setCurrentIndex(1); else if (value == "interior_only") ui->repairAABBCombo->setCurrentIndex(2); else ui->repairAABBCombo->setCurrentIndex(0); } else if (capturedTwo == "dynamic_water") { if (value == "no") ui->dynamicWaterCombo->setCurrentIndex(1); else if (value == "wavy") ui->dynamicWaterCombo->setCurrentIndex(2); else ui->dynamicWaterCombo->setCurrentIndex(0); } else if (capturedTwo == "rotate_water") { if (value == "1") ui->waterRotateTextureCombo->setCurrentIndex(1); else if (value == "0") ui->waterRotateTextureCombo->setCurrentIndex(2); else ui->waterRotateTextureCombo->setCurrentIndex(0); } else if (capturedTwo == "tile_water") { if (value == "1") ui->retileWaterCombo->setCurrentIndex(1); else if (value == "2") ui->retileWaterCombo->setCurrentIndex(2); else if (value == "3") ui->retileWaterCombo->setCurrentIndex(3); else ui->retileWaterCombo->setCurrentIndex(0); } else if (capturedTwo == "tile_raise") { if (value == "raise") ui->raiseLowerCombo->setCurrentIndex(1); else if (value == "lower") ui->raiseLowerCombo->setCurrentIndex(2); else ui->raiseLowerCombo->setCurrentIndex(0); } else if (capturedTwo == "slice") { if (value == "no") ui->sliceForTileFadeCombo->setCurrentIndex(1); else if (value == "undo") ui->sliceForTileFadeCombo->setCurrentIndex(2); else ui->sliceForTileFadeCombo->setCurrentIndex(0); } else if (capturedTwo == "tile_raise_amount") { ui->raiseLowerAmountSpin->setValue(value.toDouble()); } else if (capturedTwo == "render") { if (value == "all") ui->renderTrimeshCombo->setCurrentIndex(1); else if (value == "none") ui->renderTrimeshCombo->setCurrentIndex(2); else ui->renderTrimeshCombo->setCurrentIndex(0); } else if (capturedTwo == "shadow") { if (value == "all") ui->renderShadowsCombo->setCurrentIndex(1); else if (value == "none") ui->renderShadowsCombo->setCurrentIndex(2); else ui->renderShadowsCombo->setCurrentIndex(0); } else if (capturedTwo == "repivot") { if (value == "all") ui->repivotCombo->setCurrentIndex(1); else if (value == "none") ui->repivotCombo->setCurrentIndex(2); else ui->repivotCombo->setCurrentIndex(0); } else if (capturedTwo == "pivots_below_z=0") { if (value == "allow") ui->pivotsBelowZeroZCombo->setCurrentIndex(1); else if (value == "slice") ui->pivotsBelowZeroZCombo->setCurrentIndex(2); else ui->pivotsBelowZeroZCombo->setCurrentIndex(0); } else if (capturedTwo == "move_bad_pivots") { if (value == "top") ui->moveBadPivotsCombo->setCurrentIndex(1); else if (value == "middle") ui->moveBadPivotsCombo->setCurrentIndex(2); else if (value == "bottom") ui->moveBadPivotsCombo->setCurrentIndex(3); else ui->moveBadPivotsCombo->setCurrentIndex(0); } else if (capturedTwo == "foliage") { if (value == "tilefade") ui->foliageCombo->setCurrentIndex(1); else if (value == "animate") ui->foliageCombo->setCurrentIndex(2); else if (value == "de-animate") ui->foliageCombo->setCurrentIndex(3); else if (value == "ignore") ui->foliageCombo->setCurrentIndex(4); else ui->foliageCombo->setCurrentIndex(0); } else if (capturedTwo == "rotate_ground") { if (value == "1") ui->groundRotateTextureCombo->setCurrentIndex(1); else if (value == "0") ui->groundRotateTextureCombo->setCurrentIndex(2); else ui->groundRotateTextureCombo->setCurrentIndex(0); } else if (capturedTwo == "chamfer") { if (value == "add") ui->tileEdgeChamfersCombo->setCurrentIndex(1); else if (value == "delete") ui->tileEdgeChamfersCombo->setCurrentIndex(2); else ui->tileEdgeChamfersCombo->setCurrentIndex(0); } else if (capturedTwo == "tile_ground") { if (value == "1") ui->retileGroundPlanesCombo->setCurrentIndex(1); else if (value == "2") ui->retileGroundPlanesCombo->setCurrentIndex(2); else if (value == "3") ui->retileGroundPlanesCombo->setCurrentIndex(3); else ui->retileGroundPlanesCombo->setCurrentIndex(0); } else if (capturedTwo == "invisible_mesh_cull") { ui->cullInvisibleCheck->setChecked(value == "yes"); } else if (capturedTwo == "map_aabb_material") { ui->changeWokMatCheck->setChecked(value == "yes"); ui->changeWokMatGroupBox->setEnabled(value == "yes"); } else if (capturedTwo == "allow_split") { ui->allowSplittingCheck->setChecked(value == "yes"); } else if (capturedTwo == "do_water") { ui->waterFixupsCheck->setChecked(value == "yes"); ui->waterFrame->setEnabled(value == "yes"); } else if (capturedTwo == "water_key") { ui->waterBitmapKeys->setText(value); } else if (capturedTwo == "ground_key") { ui->groundBitmapKeys->setText(value); } else if (capturedTwo == "splotch_key") { ui->splotchBitmapKeys->setText(value); } else if (capturedTwo == "foliage_key") { ui->foliageBitmapKeys->setText(value); } else if (capturedTwo == "min_Size") { ui->subObjectSpin->setValue(value.toInt()); } else if (capturedTwo == "merge_by_bitmap") { ui->meshMergeCheck->setChecked(value == "yes"); } else if (capturedTwo == "placeable_with_transparency") { ui->placeableWithTransparencyCheck->setChecked(value == "yes"); ui->transBitmapKeyFrame->setEnabled(value == "yes"); } else if (capturedTwo == "splotch") { ui->animateSplotchesCheck->setChecked(value == "animate"); ui->splotchBitmapKeysLabel->setEnabled(value == "animate"); ui->splotchBitmapKeys->setEnabled(value == "animate"); } else if (capturedTwo == "force_white") { ui->forceWhiteCheck->setChecked(value == "yes"); } else if (capturedTwo == "split_Priority") { ui->forceWhiteCheck->setChecked(value == "concave"); } else if (capturedTwo == "transparency_key") { ui->transparentBitmapKeys->setText(value); } else if (capturedTwo == "wave_height") { ui->waveHeightSpin->setValue(value.toDouble()); } else if (capturedTwo == "map_aabb_from") { ui->changeWokMatFromSpin->setValue(value.toInt()); } else if (capturedTwo == "map_aabb_to") { ui->changeWokMatToSpin->setValue(value.toInt()); } else if (capturedTwo == "rescaleXYZ") { double X = 1.0; double Y = 1.0; double Z = 1.0; if (value != "no") { auto scales = value.mid(1,value.length() - 2).split(","); X = scales[0].toDouble(nullptr); Y = scales[1].toDouble(nullptr); Z = scales[2].toDouble(nullptr); } ui->rescaleXSpin->setValue(X); ui->rescaleYSpin->setValue(Y); ui->rescaleZSpin->setValue(Z); } } } } inputFile.close(); } } void MainWindow::replaceUserOption(const QString& key, const QString& value, bool coreVal) { QString str, rpl; if (!coreVal) { str = "^:-asserta\\(g_user_option\\(" % key % R"(,(.*)\)\)\.$)"; rpl = ":-asserta(g_user_option(" % key % "," % value % "))."; } else { str = "^:-asserta\\(" % key % R"((.*)\)\)\.$)"; rpl = ":-asserta(" % key % "('" % value % "'))."; } QFile file(m_sLastDirsPath); if(!file.open(QIODevice::Text | QIODevice::ReadWrite)) { QMessageBox::critical(nullptr, "exception", tr("Could not open last_dirs for saving!")); return; } QString dataText = file.readAll(); file.close(); QRegularExpression re(str, QRegularExpression::InvertedGreedinessOption | QRegularExpression::MultilineOption); dataText.replace(re, rpl); if(file.open(QFile::WriteOnly | QFile::Truncate)) { QTextStream out(&file); out << dataText; } file.close(); } // SLOTS/SIGNALS void MainWindow::onLoadConfigTriggered() { QFileDialog fileDialog; fileDialog.setAcceptMode(QFileDialog::AcceptMode::AcceptOpen); QStringList nameFilters; nameFilters.append("Clean Models Config (*.cm)"); fileDialog.setNameFilters(nameFilters); fileDialog.setDirectory(QDir::currentPath()); if (fileDialog.exec()) { QString fileName = fileDialog.selectedFiles()[0]; QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::information(this, tr("Unable to open file"), file.errorString()); return; } else file.close(); if (QFile::exists(m_sLastDirsPath)) { QFile::remove(m_sLastDirsPath); } if (!file.copy(m_sLastDirsPath)) { QMessageBox::information(this, tr("Unable to load file"), file.errorString()); return; } else readInLastDirs(m_sLastDirsPath); } } void MainWindow::onSaveConfigTriggered() { QFileDialog fileDialog; fileDialog.setAcceptMode(QFileDialog::AcceptMode::AcceptSave); fileDialog.setFileMode(QFileDialog::AnyFile); fileDialog.setDefaultSuffix("cm"); QStringList nameFilters; nameFilters.append("Clean Models Config (*.cm)"); fileDialog.setNameFilters(nameFilters); fileDialog.setDirectory(QDir::currentPath()); if (fileDialog.exec()) { QString fileName = fileDialog.selectedFiles()[0]; QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("Unable to open file"), file.errorString()); return; } if (QFile::exists(fileName)) { QFile::remove(fileName); } QFile fromResource(m_sLastDirsPath); if (fromResource.copy(fileName)) { QFile out(fileName); out.setPermissions(QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther | QFileDevice::WriteOwner | QFileDevice::WriteGroup); file.close(); } else { QMessageBox::information(this, tr("Unable to save file"),fromResource.errorString()); return; } } } void MainWindow::onAboutTriggered() { QMessageBox::about(this, tr("About Clean Models:EE QT"), tr("A front end to Clean Models, a utility to tidy up 3d models\n" "for usage in Neverwinter Nights: Enhanced Edition.")); } void MainWindow::onHelpTriggered() { QWhatsThis::enterWhatsThisMode(); } void MainWindow::onQuitTriggered() { if (m_bCleanRunning) m_pCleanProcess->kill(); QApplication::quit(); } void MainWindow::copyToClipboard() { auto *selectedFile = ui->filesTable->selectedItems()[0]; QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(m_sInDir % "/" % selectedFile->text()); } void MainWindow::on_cleanButton_released() { doClean(); } void MainWindow::on_decompileCheck_stateChanged(int arg1) { if (arg1 == Qt::Unchecked) { ui->cleanButton->setText(tr("Clean")); ui->cleanButton->setIcon(m_iconCleanButton); ui->mdlsCleanedLabel->setText(tr("Files Cleaned: 0")); ui->classSnapBox->setDisabled(false); ui->tilesTab->setDisabled(false); ui->coreFixesBox->setDisabled(false); ui->pivotFrame->setDisabled(false); ui->rescaleFrame->setDisabled(false); } else { ui->cleanButton->setText(tr("Decompile")); ui->cleanButton->setIcon(m_iconDecompileButton); ui->mdlsCleanedLabel->setText(tr("Files Decompiled: 0")); ui->classSnapBox->setDisabled(true); ui->tilesTab->setDisabled(true); ui->coreFixesBox->setDisabled(true); ui->pivotFrame->setDisabled(true); ui->rescaleFrame->setDisabled(true); } } void MainWindow::onDirectoryContentsChanged() { m_dirWatcherTimer->stop(); m_bFilesHaveChanged = true; m_dirWatcherTimer->start(); } void MainWindow::handleDirWatcherTimer() { if (m_bFilesHaveChanged) { m_bFilesHaveChanged = false; if (m_bCleanRunning) { m_bUpdateFilesAfterClean = true; } else updateFileListing(); } } void MainWindow::updateFileListing() { ui->filesTable->setRowCount(0); auto pattern = ui->filePattern->text(); QDir dir(ui->inDirectory->text()); dir.setNameFilters((QStringList(pattern))); dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable | QDir::CaseSensitive); QStringList totalfiles = dir.entryList(); ui->mdlsDetectedLabel->setText(tr("Files detected: ") % QString::number(totalfiles.count())); if (!ui->decompileCheck->isChecked()) ui->mdlsCleanedLabel->setText(tr("Files Cleaned: 0")); else ui->mdlsCleanedLabel->setText(tr("Files Decompiled: 0")); ui->mdlsFailedLabel->setText(tr("Failures: 0")); for (const QString &filePath : totalfiles) { QFile inputFile(ui->inDirectory->text() % "/" % filePath); QTextStream stream(&inputFile); inputFile.open(QIODevice::ReadOnly); if (!inputFile.isOpen()) continue; auto line = stream.readLine().trimmed().toStdString(); inputFile.close(); auto isASCII = std::all_of(line.begin(), line.end(), ::isprint); auto *fileNameItem = new QTableWidgetItem(filePath); fileNameItem->setIcon(isASCII ? m_iconASCIIMdl : m_iconBinaryMdl); fileNameItem->setToolTip(isASCII ? tr("ASCII MDL") : tr("Binary MDL")); auto *fileSizeItem = new QTableWidgetItem(); fileSizeItem->setText(QString::number(inputFile.size())); auto *fixesItem = new QTableWidgetItem("0"); fixesItem->setTextAlignment(Qt::AlignCenter); auto *timerItem = new QTableWidgetItem("00:00.000"); timerItem->setTextAlignment(Qt::AlignCenter); int row = ui->filesTable->rowCount(); ui->filesTable->insertRow(row); ui->filesTable->setItem(row, 0, fileNameItem); ui->filesTable->setItem(row, 1, fileSizeItem); ui->filesTable->setItem(row, 3, fixesItem); ui->filesTable->setItem(row, 4, timerItem); } } void MainWindow::onUpdateInDir(const QString& newInDir) { m_dirWatcherTimer->stop(); if (!m_sInDir.isEmpty()) m_fsWatcher.removePath(m_sInDir); m_bFilesHaveChanged = false; m_fsWatcher.addPath(newInDir); ui->inDirectory->setText(newInDir); replaceUserOption("g_indir", newInDir, true); m_sInDir = newInDir; updateFileListing(); m_dirWatcherTimer->start(); } void MainWindow::on_indirButton_released() { QFileDialog dialog(this); QStringList inDirectory; dialog.setFileMode(QFileDialog::Directory); dialog.setOption(QFileDialog::ShowDirsOnly,true); dialog.setDirectory(m_sInDir); dialog.setLabelText(QFileDialog::Accept, tr("Set")); if ( dialog.exec() ) { inDirectory = dialog.selectedFiles(); onUpdateInDir(inDirectory.at(0)); } } void MainWindow::on_inDirectory_textChanged(const QString &arg1) { const QFileInfo inputDir(arg1); QDir dir(QDir::currentPath()); QString s, f; s = dir.relativeFilePath(arg1); f = dir.absoluteFilePath(arg1); if ((!inputDir.exists()) || (!inputDir.isDir()) || (!inputDir.isWritable())) { if (QFile(s).exists()) { ui->inDirectory->setStatusTip(tr("Input folder resolved as ") %f); ui->inDirectory->setStyleSheet(""); } else ui->inDirectory->setStyleSheet("color: #FF0000"); } else { ui->inDirectory->setStatusTip(tr("Input folder resolved as ") %f); ui->inDirectory->setStyleSheet(""); } } void MainWindow::on_inDirectory_editingFinished() { const QFileInfo outputDir(ui->inDirectory->text()); if ((!outputDir.exists()) || (!outputDir.isDir()) || (!outputDir.isWritable())) { ui->inDirectory->setStyleSheet("color: #FF0000"); ui->cleanButton->setEnabled(false); ui->cleanButton->setToolTip(tr("Action disabled until valid input directory set.")); } else { ui->inDirectory->setStyleSheet(""); ui->cleanButton->setEnabled(true); ui->cleanButton->setToolTip(tr("Perform action.")); onUpdateInDir(ui->inDirectory->text()); } } void MainWindow::on_outdirButton_released() { QFileDialog dialog(this); QStringList outDirectory; dialog.setFileMode(QFileDialog::Directory); dialog.setOption(QFileDialog::ShowDirsOnly,true); dialog.setDirectory(m_sOutDir); dialog.setLabelText(QFileDialog::Accept, tr("Set")); if ( dialog.exec() ) { outDirectory = dialog.selectedFiles(); ui->outDirectory->setText(outDirectory.at(0)); m_sOutDir = ui->outDirectory->text(); replaceUserOption("g_outdir", m_sOutDir, true); } } void MainWindow::on_outDirectory_textChanged(const QString &arg1) { const QFileInfo outputDir(arg1); QDir dir(QDir::currentPath()); ui->outDirectory->setStatusTip(tr("Output folder resolved as ") % dir.absoluteFilePath(arg1)); } void MainWindow::on_outDirectory_editingFinished() { m_sOutDir = ui->outDirectory->text(); const QFileInfo outputDir(m_sOutDir); QDir dir(QDir::currentPath()); QString f = dir.absoluteFilePath(m_sOutDir); replaceUserOption("g_outdir", m_sOutDir, true); ui->outDirectory->setStatusTip(tr("Output folder resolved as ") % f); } void MainWindow::on_filePattern_textChanged(const QString &pattern) { m_dirWatcherTimer->stop(); m_bFilesHaveChanged = false; replaceUserOption("g_pattern", pattern, true); updateFileListing(); m_dirWatcherTimer->start(); } void MainWindow::on_modelClassCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("classification","character"); break; case 2: replaceUserOption("classification","door"); break; case 3: replaceUserOption("classification","effect"); break; case 4: replaceUserOption("classification","item"); break; case 5: replaceUserOption("classification","tile"); break; case 0: default: replaceUserOption("classification","automatic"); break; } if (!index || index == 5) { if (ui->mainTabs->count() == 1) ui->mainTabs->addTab(ui->tilesTab, "Tiles"); } else { if (ui->mainTabs->count() == 2) ui->mainTabs->removeTab(1); } ui->rescaleFrame->setEnabled(index != 5); ui->placeableWithTransparencyCheck->setEnabled(index <= 1); if (index <= 1 && ui->placeableWithTransparencyCheck->isChecked()) ui->transparentBitmapKeys->setEnabled(true); } void MainWindow::on_snapCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("snap","binary"); break; case 2: replaceUserOption("snap","decimal"); break; case 3: replaceUserOption("snap","fine"); break; case 0: default: replaceUserOption("snap","none"); break; } } void MainWindow::on_snapTVertsCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("tvert_snap","256"); break; case 2: replaceUserOption("tvert_snap","512"); break; case 3: replaceUserOption("tvert_snap","1024"); break; case 0: default: replaceUserOption("tvert_snap","no"); break; } } void MainWindow::on_renderShadowsCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("shadow","all"); break; case 2: replaceUserOption("shadow","none"); break; case 0: default: replaceUserOption("shadow","default"); break; } } void MainWindow::on_repivotCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("repivot","all"); break; case 2: replaceUserOption("repivot","none"); break; case 0: default: replaceUserOption("repivot","if_needed"); break; } ui->repivotBox->setEnabled(index <= 1); } void MainWindow::on_allowSplittingCheck_toggled(bool checked) { replaceUserOption("allow_split", checked ? "yes" : "no"); ui->allowSplittingFrame->setEnabled(checked); } void MainWindow::on_subObjectSpin_editingFinished() { auto val = ui->subObjectSpin->cleanText(); replaceUserOption("min_Size", val); } void MainWindow::on_smoothingGroupsCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("use_Smoothed","ignore"); break; case 2: replaceUserOption("use_Smoothed","protect"); break; case 0: default: replaceUserOption("use_Smoothed","use"); break; } } void MainWindow::on_splitFirstCombo_currentIndexChanged(int index) { replaceUserOption("split_Priority", index ? "concave" : "convex"); } void MainWindow::on_pivotsBelowZeroZCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("'pivots_below_z=0'","allow"); break; case 2: replaceUserOption("'pivots_below_z=0'","slice"); break; case 0: default: replaceUserOption("'pivots_below_z=0'","disallow"); break; } } void MainWindow::on_moveBadPivotsCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("move_bad_pivots","top"); break; case 2: replaceUserOption("move_bad_pivots","middle"); break; case 3: replaceUserOption("move_bad_pivots","bottom"); break; case 0: default: replaceUserOption("move_bad_pivots","no"); break; } } void MainWindow::on_forceWhiteCheck_toggled(bool checked) { replaceUserOption("force_white", checked ? "yes" : "no"); } void MainWindow::on_repairAABBCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("fix_overhangs","no"); break; case 2: replaceUserOption("fix_overhangs","interior_only"); break; case 0: default: replaceUserOption("fix_overhangs","yes"); break; } } void MainWindow::on_changeWokMatCheck_toggled(bool checked) { replaceUserOption("map_aabb_material", checked ? "yes" : "no"); ui->changeWokMatGroupBox->setEnabled(checked); } void MainWindow::on_raiseLowerCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("tile_raise","raise"); break; case 2: replaceUserOption("tile_raise","lower"); break; case 0: default: replaceUserOption("tile_raise","no"); break; } ui->raiseLowerAmountSpin->setEnabled(index >= 1); } void MainWindow::on_raiseLowerAmountSpin_editingFinished() { auto val = ui->raiseLowerAmountSpin->cleanText(); replaceUserOption("tile_raise_amount", val); } void MainWindow::on_sliceForTileFadeCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("slice","no"); break; case 2: replaceUserOption("slice","undo"); break; case 0: default: replaceUserOption("slice","yes"); break; } ui->sliceHeightFrame->setEnabled(index == 0); } void MainWindow::on_foliageCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("foliage","tilefade"); break; case 2: replaceUserOption("foliage","animate"); break; case 3: replaceUserOption("foliage","de-animate"); break; case 4: replaceUserOption("foliage","ignore"); break; case 0: default: replaceUserOption("foliage","no_change"); break; } ui->foliageBitmapKeys->setEnabled(index != 4); ui->foliageBitmapKeysLabel->setEnabled(index != 4); } void MainWindow::on_groundRotateTextureCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("rotate_ground","1"); break; case 2: replaceUserOption("rotate_ground","0"); break; case 0: default: replaceUserOption("rotate_ground","no_change"); break; } bool showGroundTextEdit = ui->groundRotateTextureCombo->currentIndex() || ui->retileGroundPlanesCombo->currentIndex() || ui->tileEdgeChamfersCombo->currentIndex(); ui->groundBitmapKeys->setEnabled(showGroundTextEdit); ui->groundBitmapKeysLabel->setEnabled(showGroundTextEdit); } void MainWindow::on_tileEdgeChamfersCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("chamfer","add"); break; case 2: replaceUserOption("chamfer","delete"); break; case 0: default: replaceUserOption("chamfer","no_change"); break; } bool showGroundTextEdit = ui->groundRotateTextureCombo->currentIndex() || ui->retileGroundPlanesCombo->currentIndex() || ui->tileEdgeChamfersCombo->currentIndex(); ui->groundBitmapKeys->setEnabled(showGroundTextEdit); ui->groundBitmapKeysLabel->setEnabled(showGroundTextEdit); } void MainWindow::on_retileGroundPlanesCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("tile_ground","1"); break; case 2: replaceUserOption("tile_ground","2"); break; case 3: replaceUserOption("tile_ground","3"); break; case 0: default: replaceUserOption("tile_ground","no_change"); break; } bool showGroundTextEdit = ui->groundRotateTextureCombo->currentIndex() || ui->retileGroundPlanesCombo->currentIndex() || ui->tileEdgeChamfersCombo->currentIndex(); ui->groundBitmapKeys->setEnabled(showGroundTextEdit); ui->groundBitmapKeysLabel->setEnabled(showGroundTextEdit); } void MainWindow::on_meshMergeCheck_toggled(bool checked) { replaceUserOption("merge_by_bitmap", checked ? "yes" : "no"); } void MainWindow::on_placeableWithTransparencyCheck_toggled(bool checked) { if (checked) { replaceUserOption("placeable_with_transparency","yes"); if (ui->modelClassCombo->currentIndex() <= 1) ui->transBitmapKeyFrame->setEnabled(true); } else { replaceUserOption("placeable_with_transparency","no"); ui->transBitmapKeyFrame->setEnabled(false); } } void MainWindow::on_animateSplotchesCheck_toggled(bool checked) { if (checked) { replaceUserOption("splotch","animate"); ui->splotchBitmapKeysLabel->setEnabled(true); ui->splotchBitmapKeys->setEnabled(true); } else { replaceUserOption("splotch","ignore"); ui->splotchBitmapKeysLabel->setEnabled(false); ui->splotchBitmapKeys->setEnabled(false); } } void MainWindow::on_transparentBitmapKeys_editingFinished() { replaceUserOption("transparency_key",ui->transparentBitmapKeys->text().toStdString().c_str()); } void MainWindow::on_cullInvisibleCheck_toggled(bool checked) { replaceUserOption("invisible_mesh_cull", checked ? "yes" : "no"); } void MainWindow::on_renderTrimeshCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("render","all"); break; case 2: replaceUserOption("render","none"); break; case 0: default: replaceUserOption("render","default"); break; } } void MainWindow::on_changeWokMatFromSpin_editingFinished() { auto val = ui->changeWokMatFromSpin->cleanText(); replaceUserOption("map_aabb_from", val); } void MainWindow::on_changeWokMatToSpin_editingFinished() { auto val = ui->changeWokMatToSpin->cleanText(); replaceUserOption("map_aabb_to", val); } void MainWindow::on_waterFixupsCheck_toggled(bool checked) { ui->waterFrame->setEnabled(checked); } void MainWindow::on_waterBitmapKeys_editingFinished() { replaceUserOption("water_key", ui->waterBitmapKeys->text()); } void MainWindow::on_foliageBitmapKeys_editingFinished() { replaceUserOption("foliage_key", ui->foliageBitmapKeys->text()); } void MainWindow::on_splotchBitmapKeys_editingFinished() { replaceUserOption("splotch_key", ui->splotchBitmapKeys->text()); } void MainWindow::on_groundBitmapKeys_editingFinished() { replaceUserOption("ground_key", ui->groundBitmapKeys->text()); } void MainWindow::on_dynamicWaterCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("dynamic_water","no"); break; case 2: replaceUserOption("dynamic_water","wavy"); break; case 0: default: replaceUserOption("dynamic_water","yes"); break; } ui->waveHeightFrame->setEnabled(index == 2); ui->retileWaterCombo->setEnabled(index != 2); ui->retileWaterLabel->setEnabled(index != 2); } void MainWindow::on_waveHeightSpin_editingFinished() { auto val = ui->waveHeightSpin->cleanText(); replaceUserOption("wave_height", val); } void MainWindow::on_waterRotateTextureCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("rotate_water","1"); break; case 2: replaceUserOption("rotate_water","0"); break; case 0: default: replaceUserOption("rotate_water","no_change"); break; } } void MainWindow::on_retileWaterCombo_currentIndexChanged(int index) { switch(index) { case 1: replaceUserOption("tile_water","1"); break; case 2: replaceUserOption("tile_water","2"); break; case 3: replaceUserOption("tile_water","3"); break; case 0: default: replaceUserOption("tile_water","no_change"); break; } } void MainWindow::on_filesTable_customContextMenuRequested(const QPoint &pos) { // Handle global position QPoint globalPos = ui->filesTable->mapToGlobal(pos); // Create menu and insert some actions QMenu myMenu; myMenu.addAction(tr("Copy path to clipboard"), this, SLOT(copyToClipboard())); myMenu.exec(globalPos); } void MainWindow::on_filesTable_doubleClicked(const QModelIndex &index) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)) QString cellText = index.siblingAtColumn(0).data().toString(); ui->debugTextBrowser->moveCursor(QTextCursor::Start); if (!ui->debugTextBrowser->find(cellText)) ui->debugTextBrowser->moveCursor(QTextCursor::End); #endif } void MainWindow::setRescaleOption() { QString rescaleXYZ = "no"; if (ui->rescaleXSpin->value() != 1 || ui->rescaleYSpin->value() != 1 || ui->rescaleZSpin->value() != 1) { rescaleXYZ = "[" % QString::number(ui->rescaleXSpin->value(),'g',4) % "," % QString::number(ui->rescaleYSpin->value(),'g',4) % "," % QString::number(ui->rescaleZSpin->value(),'g',4) % "]"; } replaceUserOption("rescaleXYZ",rescaleXYZ); } void MainWindow::on_rescaleLockBtn_clicked(bool checked) { if (checked) { ui->rescaleLockBtn->setIcon(m_iconLockRescaleBtn); } else ui->rescaleLockBtn->setIcon(m_iconUnlockRescaleBtn); ui->rescaleYSpin->setValue(ui->rescaleXSpin->value()); ui->rescaleZSpin->setValue(ui->rescaleXSpin->value()); ui->rescaleYSpin->setEnabled(!checked); ui->rescaleZSpin->setEnabled(!checked); } void MainWindow::on_rescaleXSpin_valueChanged(double arg1) { if (ui->rescaleLockBtn->isChecked()) { QSignalBlocker blockY(ui->rescaleYSpin); QSignalBlocker blockZ(ui->rescaleZSpin); ui->rescaleYSpin->setValue(arg1); ui->rescaleZSpin->setValue(arg1); } setRescaleOption(); } void MainWindow::on_rescaleYSpin_valueChanged(double) { setRescaleOption(); } void MainWindow::on_rescaleZSpin_valueChanged(double) { setRescaleOption(); }
fb139df85ab9b8a0fc1e1ab62ef9b5af32eba50c
dd8143ea97146890ed3c2383f2c671843a134823
/attack_test.cpp
a8e4b7333f9f2e3368e179b1b070fe77e4fe8232
[]
no_license
benjaminshu2001/TextBasedRPG
2d67770feafd16cf6e3e94c20b6cb32435b6a107
5585de074438627d0aca5809d000d0d40a003650
refs/heads/master
2023-01-27T22:42:15.026245
2020-12-10T21:01:05
2020-12-10T21:01:05
320,450,134
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
attack_test.cpp
#include "player.h" #include "item.h" #include "inventory.cpp" #include "iterator.h" #include <iostream> #include <string> #include "armor.h" #include "weapon.h" #include "equip.h" #include "bubble_sort.cpp" class Iterator; using std::cout; using std::cin; int main() { string name = "Test Name"; int h = 10; int d = 2; int m; int atkdmg; int monster_def; cout << "(TEST) enter atkdmg: "; cin >> atkdmg; cout << endl << "(TEST) enter monster_def: "; cin >> monster_def; cout << endl << "(TEST) enter mana: "; cin >> m; cout << endl; Player* p = new Player(name, h, m, d, atkdmg); cout << p->AttackClient(monster_def) << endl; return 0; }
dd5c9158fb1edaa33c40f8dbead613a6816e2922
59b9c701c25a384d48e65835bdaf1180680f64d2
/problems/667.II beautiful-arrangement-ii.cpp
08964dcc1a0f5fed4c28beb1445ae3a73ca0358a
[ "MIT" ]
permissive
bigfishi/leetcode
4d5b661baf7f2845051c85a080a2dbfc894b20e3
3e512f2822a742349384a0bdd7954696f5867683
refs/heads/master
2020-07-23T21:25:01.121104
2019-10-10T10:31:54
2019-10-10T10:31:54
207,710,508
0
0
null
null
null
null
UTF-8
C++
false
false
653
cpp
667.II beautiful-arrangement-ii.cpp
// 刚开始想参考全排列的实现,发现做不出来 // 改为直接参考 // 这题可以理解为数学题,脑洞题。通过例子得出规律,[1]是1,[2]是[1]+k,[3]是[2]-(k-1),[4]是[3]+(k-2),以此类推,k为0时,[k]是k class Solution { public: vector<int> constructArray(int n, int k) { vector<int> list; list.push_back(1); bool flag = true; int size = 1; while (size<n) { if (k == 0) { list.push_back(size + 1); } else { if (flag) list.push_back(list[size - 1] + k); else list.push_back(list[size - 1] - k); k--; flag = !flag; } size++; } return list; } };
b0f66adb2e4498c201b3fa36e71c7d1b6712e35e
ff443629c167f318d071f62886581167c51690c4
/src/index/base.h
9b2a41dc92b13f143fbf63acdced89f3f41cf368
[ "MIT" ]
permissive
bitcoin/bitcoin
a618b2555d9fe5a2b613e5fec0f4b1eca3b4d86f
6f03c45f6bb5a6edaa3051968b6a1ca4f84d2ccb
refs/heads/master
2023-09-05T00:16:48.295861
2023-09-02T17:43:00
2023-09-02T17:46:33
1,181,927
77,104
33,708
MIT
2023-09-14T20:47:31
2010-12-19T15:16:43
C++
UTF-8
C++
false
false
6,286
h
base.h
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INDEX_BASE_H #define BITCOIN_INDEX_BASE_H #include <dbwrapper.h> #include <interfaces/chain.h> #include <util/threadinterrupt.h> #include <validationinterface.h> #include <string> class CBlock; class CBlockIndex; class Chainstate; namespace interfaces { class Chain; } // namespace interfaces struct IndexSummary { std::string name; bool synced{false}; int best_block_height{0}; uint256 best_block_hash; }; /** * Base class for indices of blockchain data. This implements * CValidationInterface and ensures blocks are indexed sequentially according * to their position in the active chain. */ class BaseIndex : public CValidationInterface { protected: /** * The database stores a block locator of the chain the database is synced to * so that the index can efficiently determine the point it last stopped at. * A locator is used instead of a simple hash of the chain tip because blocks * and block index entries may not be flushed to disk until after this database * is updated. */ class DB : public CDBWrapper { public: DB(const fs::path& path, size_t n_cache_size, bool f_memory = false, bool f_wipe = false, bool f_obfuscate = false); /// Read block locator of the chain that the index is in sync with. bool ReadBestBlock(CBlockLocator& locator) const; /// Write block locator of the chain that the index is in sync with. void WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator); }; private: /// Whether the index has been initialized or not. std::atomic<bool> m_init{false}; /// Whether the index is in sync with the main chain. The flag is flipped /// from false to true once, after which point this starts processing /// ValidationInterface notifications to stay in sync. /// /// Note that this will latch to true *immediately* upon startup if /// `m_chainstate->m_chain` is empty, which will be the case upon startup /// with an empty datadir if, e.g., `-txindex=1` is specified. std::atomic<bool> m_synced{false}; /// The last block in the chain that the index is in sync with. std::atomic<const CBlockIndex*> m_best_block_index{nullptr}; std::thread m_thread_sync; CThreadInterrupt m_interrupt; /// Sync the index with the block index starting from the current best block. /// Intended to be run in its own thread, m_thread_sync, and can be /// interrupted with m_interrupt. Once the index gets in sync, the m_synced /// flag is set and the BlockConnected ValidationInterface callback takes /// over and the sync thread exits. void ThreadSync(); /// Write the current index state (eg. chain block locator and subclass-specific items) to disk. /// /// Recommendations for error handling: /// If called on a successor of the previous committed best block in the index, the index can /// continue processing without risk of corruption, though the index state will need to catch up /// from further behind on reboot. If the new state is not a successor of the previous state (due /// to a chain reorganization), the index must halt until Commit succeeds or else it could end up /// getting corrupted. bool Commit(); /// Loop over disconnected blocks and call CustomRewind. bool Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip); virtual bool AllowPrune() const = 0; template <typename... Args> void FatalErrorf(const char* fmt, const Args&... args); protected: std::unique_ptr<interfaces::Chain> m_chain; Chainstate* m_chainstate{nullptr}; const std::string m_name; void BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override; void ChainStateFlushed(const CBlockLocator& locator) override; /// Initialize internal state from the database and block index. [[nodiscard]] virtual bool CustomInit(const std::optional<interfaces::BlockKey>& block) { return true; } /// Write update index entries for a newly connected block. [[nodiscard]] virtual bool CustomAppend(const interfaces::BlockInfo& block) { return true; } /// Virtual method called internally by Commit that can be overridden to atomically /// commit more index state. virtual bool CustomCommit(CDBBatch& batch) { return true; } /// Rewind index to an earlier chain tip during a chain reorg. The tip must /// be an ancestor of the current best block. [[nodiscard]] virtual bool CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) { return true; } virtual DB& GetDB() const = 0; /// Get the name of the index for display in logs. const std::string& GetName() const LIFETIMEBOUND { return m_name; } /// Update the internal best block index as well as the prune lock. void SetBestBlockIndex(const CBlockIndex* block); public: BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name); /// Destructor interrupts sync thread if running and blocks until it exits. virtual ~BaseIndex(); /// Blocks the current thread until the index is caught up to the current /// state of the block chain. This only blocks if the index has gotten in /// sync once and only needs to process blocks in the ValidationInterface /// queue. If the index is catching up from far behind, this method does /// not block and immediately returns false. bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main); void Interrupt(); /// Initializes the sync state and registers the instance to the /// validation interface so that it stays in sync with blockchain updates. [[nodiscard]] bool Init(); /// Starts the initial sync process. [[nodiscard]] bool StartBackgroundSync(); /// Stops the instance from staying in sync with blockchain updates. void Stop(); /// Get a summary of the index and its state. IndexSummary GetSummary() const; }; #endif // BITCOIN_INDEX_BASE_H
ab6fc1f1e41f129e55681ae9a898e1e9e28494de
f2339e85157027dada17fadd67c163ecb8627909
/Server/EffectServer/Src/EffectContinuePositionAddBuff.h
6e4eb24f3f2137996ff9e7747bf1428c0ba8f00e
[]
no_license
fynbntl/Titan
7ed8869377676b4c5b96df953570d9b4c4b9b102
b069b7a2d90f4d67c072e7c96fe341a18fedcfe7
refs/heads/master
2021-09-01T22:52:37.516407
2017-12-29T01:59:29
2017-12-29T01:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,174
h
EffectContinuePositionAddBuff.h
/******************************************************************* ** 文件名: EffectContinuePositionAddBuff.h ** 版 权: (C) 深圳冰川网络技术有限公司 2008 - All Rights Reserved ** 创建人: 彭政林 ** 日 期: 2/24/2016 ** 版 本: 1.0 ** 描 述: 效果-持续位置增加Buff http://172.16.0.120/redmine/issues/1651 http://172.16.0.120/redmine/issues/1652 ********************************************************************/ #pragma once #include "IEffect.h" #include "EffectDef.h" using namespace EFFECT_SERVER; class CEffectContinuePositionAddBuff : public IEffectEx, public rkt::TimerHandler { public: typedef EffectServer_ContinuePositionAddBuff SCHEME_DATA; CEffectContinuePositionAddBuff( SCHEME_DATA & data ) : m_data(data),m_pEntity(NULL),m_vTargetTile(0,0,0),m_uidTarget(0),m_nSpellID(0) { } // 获取效果ID virtual int GetID() { return m_data.nID; } // 效果启用 virtual bool Start( EFFECT_CONTEXT * context,CONDITION_CONTEXT *pConditionContext ) { if ( context==0 || context->pEntity==0 ) return false; m_pEntity = context->pEntity; m_nSpellID = context->nID; switch (m_data.nType) { case USE_SPELL_POS_TILE: { m_vTargetTile = context->ptTargetTile; } break; case USE_SPELL_POS_SELF: { m_vTargetTile = m_pEntity->getLocation(); m_uidTarget = m_pEntity->getUID(); } break; case USE_SPELL_POS_TARGET: { UID uidTarget = context->uidTarget; if (isInvalidUID(uidTarget)) { return false; } m_vTargetTile = getLocation(uidTarget); m_uidTarget = uidTarget; } break; default: { ErrorLn("CEffectContinuePositionAddBuff error nType="<<m_data.nType); return false; } break; } if(m_data.nCount >= 1) { g_EHelper.SetTimer(0, m_data.nInterval, this, m_data.nCount, "CEffectContinuedSetProperty"); } else { g_EHelper.SetTimer(0, m_data.nInterval, this, INFINITY_CALL, "CEffectContinuedSetProperty"); } return true; } // 效果停止 virtual void Stop() { if (m_pEntity != NULL) { g_EHelper.KillTimer(0, this); m_pEntity = NULL; } } // 克隆一个新效果 virtual IEffect * Clone() { return new CEffectContinuePositionAddBuff(m_data); } // 释放 virtual void Release() { Stop(); delete this; } virtual void OnTimer( unsigned long dwTimerID ) { if (m_pEntity == NULL) { return; } UID uidSelf = m_pEntity->getUID(); // 不是技能点,取目标实时位置 if (m_data.nType != USE_SPELL_POS_TILE) { m_vTargetTile = getLocation(m_uidTarget); } /** 取得实体 */ int nSceneID = UID_2_SCENE(uidSelf); SceneServiceHelper sceneHelper(nSceneID); if ( sceneHelper.m_ptr==0 ) { return; } AOI_PROXY_PTR pProxyArray[MAX_INTEREST_OBJECT]; int num = sceneHelper.m_ptr->k_nearest(m_vTargetTile, m_data.fDistance, pProxyArray, MAX_INTEREST_OBJECT, LAYER_ALL, true); if ( num<=0 ) { return; } SBuffContext BuffContext; BuffContext.nID = m_nSpellID; // 增加BUFF数量 int nAddBuffCount = 0; int nMaxAddBuffCount = m_data.nAddBuffCount == 0 ? EFFECT_CHOOSE_TARGET_COUNT : m_data.nAddBuffCount; UID uidMonsterAddBuff[MAX_INTEREST_OBJECT] = {0}; DWORD dwMonsterCount = 0; for ( int i=0; i<num; ++i ) { // 目标UID UID uidTarget = pProxyArray[i]->m_uid; if (isInvalidUID(uidTarget)) { continue; } if (nAddBuffCount >= nMaxAddBuffCount) { break; } // 检测目标 if (!g_EHelper.chooseTarget(m_pEntity, m_data.nTargetFilter, uidTarget)) { continue; } if (isMonster(uidTarget)) { uidMonsterAddBuff[dwMonsterCount++] = uidTarget; } else { // 给目标增加buff AddBuff(uidTarget, m_data.nBuffID, m_data.nBuffLevel, uidSelf, 0, &BuffContext, sizeof(BuffContext)); } ++nAddBuffCount; } if (dwMonsterCount > 0) { g_EHelper.BatchAddBuff(uidMonsterAddBuff, dwMonsterCount, m_data.nBuffID, m_data.nBuffLevel, uidSelf, 0, &BuffContext, sizeof(BuffContext)); } } private: SCHEME_DATA m_data; __IEntity *m_pEntity; Vector3 m_vTargetTile; UID m_uidTarget; int m_nSpellID; };
7a0a8d23488a5f348649a43b0119aadf6830cf69
297497957c531d81ba286bc91253fbbb78b4d8be
/security/sandbox/chromium/base/memory/unsafe_shared_memory_region.h
36ad96dfccef1ec46a2fdb58e76cbc418b1e1ef0
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
1,909
h
unsafe_shared_memory_region.h
#ifndef BASE_MEMORY_UNSAFE_SHARED_MEMORY_REGION_H_ #define BASE_MEMORY_UNSAFE_SHARED_MEMORY_REGION_H_ #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/platform_shared_memory_region.h" #include "base/memory/shared_memory_mapping.h" namespace base { class BASE_EXPORT UnsafeSharedMemoryRegion { public: using MappingType = WritableSharedMemoryMapping; static UnsafeSharedMemoryRegion Create(size_t size); using CreateFunction = decltype(Create); static UnsafeSharedMemoryRegion Deserialize( subtle::PlatformSharedMemoryRegion handle); static subtle::PlatformSharedMemoryRegion TakeHandleForSerialization( UnsafeSharedMemoryRegion region); UnsafeSharedMemoryRegion(); UnsafeSharedMemoryRegion(UnsafeSharedMemoryRegion&&); UnsafeSharedMemoryRegion& operator=(UnsafeSharedMemoryRegion&&); ~UnsafeSharedMemoryRegion(); UnsafeSharedMemoryRegion Duplicate() const; WritableSharedMemoryMapping Map() const; WritableSharedMemoryMapping MapAt(off_t offset, size_t size) const; bool IsValid() const; size_t GetSize() const { DCHECK(IsValid()); return handle_.GetSize(); } const UnguessableToken& GetGUID() const { DCHECK(IsValid()); return handle_.GetGUID(); } subtle::PlatformSharedMemoryRegion::PlatformHandle GetPlatformHandle() const { DCHECK(IsValid()); return handle_.GetPlatformHandle(); } private: friend class SharedMemoryHooks; explicit UnsafeSharedMemoryRegion(subtle::PlatformSharedMemoryRegion handle); static void set_create_hook(CreateFunction* hook) { create_hook_ = hook; } static CreateFunction* create_hook_; subtle::PlatformSharedMemoryRegion handle_; DISALLOW_COPY_AND_ASSIGN(UnsafeSharedMemoryRegion); }; } #endif
fa49949007bc2517d83fa9347dffa81b1fb40cab
ea2737d56bd2016edd3761f1bdc71449008cea10
/src/TeensyQuadcopter.cpp
16ba4581a10a4e0f236904c833a6bdbd56da3e08
[]
no_license
michaellangford99/STM32Quadcopter
285db516245ad15e51e98b357bc56fb054e0cc64
5e188198f1f47db57f1ac6d43376d30d81fddf14
refs/heads/master
2020-04-13T06:49:33.894296
2020-01-11T20:57:03
2020-01-11T20:57:03
163,031,815
1
0
null
null
null
null
UTF-8
C++
false
false
7,963
cpp
TeensyQuadcopter.cpp
/* Name: TeensyQuadcopter.cpp Created: 5/3/2017 9:52:41 PM Author: Michael Langford */ /* prop1 prop2 | | [][] front [][] [][] | [][] \ | / {[[[]]}-----microcontroller {[[[]]} / \ [][] [][] [][] [][] | | prop3 prop4 */ #include "MPU9250.h" #include "RadioReciever.h" #include "PID.h" #include "Motors.h" #include "Debug.h" #include "wiring.h" #include "wprogram.h" #include "unit_tests.h" #ifdef TEENSYQUADCOPTER #define THROTTLE_THRESHOLD 1.5f #define THROTTLE_UNLOCK -90.0f #define YAW_UNLOCK 90.0f #define PITCH_UNLOCK -90.0f #define ROLL_UNLOCK -90.0f #define GEAR_SET 90.0f #define SAFE 0 #define ARMED 1 //PID loops PIDClass YawPID; PIDClass PitchPID; PIDClass RollPID; //PID outputs float yaw_out, pitch_out, roll_out, throttle_out; //motor outputs float motor_output[4]; //debug values int loop_time = 0; int l_loop_time = 0; int count = 0; //SAFEing value int safety = SAFE; /*//Kalman filters Kalman pitch_kalman; Kalman roll_kalman;*/ //main angles float yaw_angle = 0.0f; float main_pitch = 0.0f; float main_roll = 0.0f; void arm(); // the setup function runs once when you press reset or power the board void setup() { Serial.begin(9600); Serial.clear(); //init debug helper init_Debug(); init_MPU9250(); init_RadioReciever(); init_motors(); //init pid loops YawPID.init_PID(); PitchPID.init_PID(); RollPID.init_PID(); YawPID.Set_Constants (0.70f, 0.0f, 1200.0f); PitchPID.Set_Constants(0.59f, 0.0f, 1200.0f); RollPID.Set_Constants (0.59f, 0.0f, 1200.0f); /*//init kalman filters pitch_kalman.init_Kalman(); roll_kalman.init_Kalman();*/ // //calibrate and load initial values // ClearAngles(0.0f, 0.0f, 0.0f); yaw_angle = 0.0f; main_pitch = 0.0f; main_roll = 0.0f; /*pitch_kalman.init_Kalman(); roll_kalman.init_Kalman();*/ ClearAngles(0.0f, 0.0f, 0.0f); update_MPU9250(); ClearAngles(0.0f, 0.0f, 0.0f); } int angle_reset_count = 0; int resets = 0; void loop() { //update sensors and radio //update_LIS3DH(); update_MPU9250(); update_RadioReciever(); /*//Kalman Filter main_pitch = pitch_kalman.Filter(Get_Acc_Pitch(), GetPitchRate() * GetGyroElapsedTime()); main_roll = roll_kalman.Filter(Get_Acc_Roll(), GetRollRate() * GetGyroElapsedTime()); */ main_pitch = ((double)(main_pitch + GetPitchRate()*getGyroTime()) * 0.9999) + (double)GetPitchAcc()*0.0001; main_roll = ((double)(main_roll + GetRollRate()*getGyroTime()) * 0.9999) + (double)GetRollAcc() * 0.0001; //main_pitch = GetPitch();// (main_pitch + GetPitchRate()*egyrotime);// +Get_Acc_Pitch()*0.000f; //main_roll = GetRoll();// (main_roll + GetRollRate()*egyrotime);// +Get_Acc_Roll()*0.0001f; /*angle_reset_count++; if (angle_reset_count > 30) { angle_reset_count = 0; if (abs(GetPitchRate()) < 3.7f && abs(GetRollRate()) < 3.7f) { if (abs(Get_Acc_Pitch()) < 10.0f && abs(Get_Acc_Roll()) < 10.0f) { resets++; main_pitch = Get_Acc_Pitch(); main_roll = Get_Acc_Roll(); ClearAngles(GetYaw(), Get_Acc_Pitch(), Get_Acc_Roll()); debug_flash(); } } }*/ /*if (abs(GetPitchRate()*GetGyroElapsedTime()) < 5.0f && abs(GetRollRate()*GetGyroElapsedTime()) < 5.0f) { if (abs(Get_Acc_Pitch()) < 2.0f && abs(Get_Acc_Roll()) < 2.0f) { angle_reset_count++; } else { angle_reset_count = 0; } } else { angle_reset_count = 0; } if (angle_reset_count > 8) { angle_reset_count = 0; resets++; main_pitch = Get_Acc_Pitch(); main_roll = Get_Acc_Roll(); ClearAngles(GetYaw(), Get_Acc_Pitch(), Get_Acc_Roll()); debug_flash(); }*/ if (safety == SAFE) { //update debug helper update_Debug_SAFE(); //zero motors update_motors(0.0f, 0.0f, 0.0f, 0.0f); //check ARM arm(); } else if (safety == ARMED) { //update debug helper update_Debug_ARMED(); //update PID loops yaw_angle += GetChannel(RUD_YAW) / 1000.0f; yaw_out = YawPID.update_PID(GetYaw(), yaw_angle); pitch_out = PitchPID.update_PID(main_pitch, -GetChannel(ELEV_PITCH) / 4.0f); roll_out = RollPID.update_PID(main_roll, GetChannel(AIL_ROLL) / 4.0f); //update motor values throttle_out = GetChannel(THROTTLE); throttle_out = (throttle_out + 100.0f) / 2.0f; //check safety value if (GetChannel(GEAR) < GEAR_SET && throttle_out < THROTTLE_THRESHOLD) { safety = SAFE; return; } motor_output[0] = throttle_out; motor_output[1] = throttle_out; motor_output[2] = throttle_out; motor_output[3] = throttle_out; motor_output[0] += yaw_out; motor_output[1] += -yaw_out; motor_output[2] += -yaw_out; motor_output[3] += yaw_out; motor_output[0] += pitch_out; motor_output[1] += pitch_out; motor_output[2] += -pitch_out; motor_output[3] += -pitch_out; motor_output[0] += -roll_out; motor_output[1] += roll_out; motor_output[2] += -roll_out; motor_output[3] += roll_out; //clamp motor values motor_output[0] = max(0.0f, motor_output[0]); motor_output[1] = max(0.0f, motor_output[1]); motor_output[2] = max(0.0f, motor_output[2]); motor_output[3] = max(0.0f, motor_output[3]); motor_output[0] = min(100.0f, motor_output[0]); motor_output[1] = min(100.0f, motor_output[1]); motor_output[2] = min(100.0f, motor_output[2]); motor_output[3] = min(100.0f, motor_output[3]); if (throttle_out < THROTTLE_THRESHOLD) { motor_output[0] = 0.0f; motor_output[1] = 0.0f; motor_output[2] = 0.0f; motor_output[3] = 0.0f; } //send motor values to driver update_motors(motor_output[0], motor_output[1], motor_output[2], motor_output[3]); //update_motors(0.0f, 0.0f, 0.0f, 0.0f); } else { update_Debug_ARMED(); } ////// /////// ////// display /////// ////// /////// //count++; if (count > 100) { count = 0; //Serial.printf("%f, %f, %f, %f, ", motor_output[0], motor_output[1], motor_output[2], motor_output[3]); //Serial.printf("%f, ", 1.0f / ((loop_time - l_loop_time) / 1000000.0f)); //Serial.printf("%f, %f, %f, ", GetXAcc(), GetYAcc(), GetZAcc()); //Serial.printf("%f, %f, ", GetPitchAcc(), GetRollAcc()); //Serial.printf("%f, %f, %f\n", GetYaw(), GetPitch(), GetRoll()); //Serial.printf("%f, %f, %f\n", GetYaw(), main_pitch, main_roll); Serial.printf("%f, %f, ", GetPitchAcc(), GetRollAcc()); Serial.printf("%f, %f, ", GetPitch(), GetRoll()); Serial.printf("%f, %f\n", main_pitch, main_roll); //Serial.printf("%f, %f, %f, 00, %f, %f, %f, 00, %d, %d, %d\n", GetYaw(), GetPitch(), GetRoll(), get_cal_x(), get_cal_y(), get_cal_z(), getX(), getY(), getZ()); //Serial.printf("%f, %f, ", Get_Acc_Pitch(), Get_Acc_Roll()); //Serial.printf("%f, %f, %f, %f, ", GetChannel(THROTTLE), GetChannel(RUD_YAW), GetChannel(AIL_ROLL), GetChannel(ELEV_PITCH)); //Serial.printf("%f, %f\n", GetRoll(), GetPitch()); } l_loop_time = loop_time; loop_time = micros(); } void arm() { if (GetChannel(THROTTLE) < THROTTLE_UNLOCK) { if (GetChannel(RUD_YAW) > YAW_UNLOCK) { if (GetChannel(AIL_ROLL) < ROLL_UNLOCK) { if (GetChannel(ELEV_PITCH) < PITCH_UNLOCK) { if (GetChannel(GEAR) > GEAR_SET) { calibrate_Accelerometer(); calibrate_Gyro(); ClearAngles(0.0f, 0.0f, 0.0f); //delay(100); yaw_angle = 0.0f; main_pitch = 0.0f; main_roll = 0.0f; /*pitch_kalman.init_Kalman(); roll_kalman.init_Kalman();*/ ClearAngles(0.0f, 0.0f, 0.0f); update_MPU9250(); ClearAngles(0.0f, 0.0f, 0.0f); safety = ARMED; } } } } } } #endif
efdfbfd16d938b933629497397c6e6f462720414
f248a1f0c1a1c798b89605471cd32f82e8305ecc
/NewYear 2/NewYear.ino
44f16ec9dda3be40949ac3aec7fb09881974ddb0
[]
no_license
AlexPaskal/My-Arduino
9f99a1137bba690af490e097d8d0f124fe157f26
2fbeccbcccf3cd9a242832a5155da2c78343e6f3
refs/heads/master
2020-04-02T04:44:25.857985
2016-06-12T14:59:20
2016-06-12T14:59:20
60,867,024
0
0
null
null
null
null
UTF-8
C++
false
false
898
ino
NewYear.ino
int rL = 13; int yL = 12; int gL = 8; int bL = 7; int pV = 2; void setup(){ Serial.begin(9600); pinMode(rL, OUTPUT); pinMode(yL, OUTPUT); pinMode(gL, OUTPUT); pinMode(bL, OUTPUT); } void loop(){ int val = analogRead(pV); if (val<200) //1 { digitalWrite(rL, HIGH); digitalWrite(yL, LOW); digitalWrite(gL, LOW); digitalWrite(bL, LOW); } if (val>200 && val<400) //2 { digitalWrite(yL, HIGH); digitalWrite(rL, LOW); digitalWrite(gL, LOW); digitalWrite(bL, LOW); } if (val>400 && val<600) //3 { digitalWrite(gL, HIGH); digitalWrite(rL, LOW); digitalWrite(yL, LOW); digitalWrite(bL, LOW); } if (val>800) //4 { digitalWrite(bL, HIGH); digitalWrite(rL, LOW); digitalWrite(yL, LOW); digitalWrite(gL, LOW); } /*else { digitalWrite(rL, LOW); digitalWrite(yL, LOW); digitalWrite(gL, LOW); digitalWrite(bL, LOW); } */ }
f667a82124e59132a6e0f3900e52c0c824742566
2433aee9c9c66fca796900c86146354ffacfbc68
/Tutorial/episode1.hpp
ac179ec7e3404b0e87b703fdce5bc4ecd758e6e2
[]
no_license
adamandreas565/SDL2onXcode
d5a3d0950abc175cd7841f374bf8c21f0790b5a0
2025194a407c9d954962574d610bde2a5839c1e0
refs/heads/main
2023-02-22T13:04:28.632651
2021-01-24T01:13:37
2021-01-24T01:13:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
271
hpp
episode1.hpp
// // episode1.hpp // SDL_Tutorial // // Created by Rongqing Ye on 4/25/20. // Copyright © 2020 Rongqing Ye. All rights reserved. // #ifndef episode1_hpp #define episode1_hpp #include "engine.hpp" class Episode1: public GameEngine { }; #endif /* episode1_hpp */
54cadc102b6757f9d07b830e4c08beea514c1085
21a880dcdf84fd0c812f8506763a689fde297ba7
/src/cme/market/status_manager.h
81e5556c85b341f3f47ac743eac17650bfd1d38c
[]
no_license
chenlucan/fix_handler
91df9037eeb675b0c7ea6f22d541da74b220092f
765462ff1a85567f43f63e04c29dbc9546a6c2e1
refs/heads/master
2021-03-22T02:07:39.016551
2017-08-01T02:02:20
2017-08-01T02:02:20
84,138,943
2
2
null
null
null
null
UTF-8
C++
false
false
1,547
h
status_manager.h
#ifndef __FH_CME_MARKET_STATUS_MANAGER_H__ #define __FH_CME_MARKET_STATUS_MANAGER_H__ #include "core/global.h" #include "cme/market/message/mdp_message.h" #include "cme/market/message/message_parser_f.h" #include "core/market/marketlisteneri.h" #include "cme/market/definition_manager.h" namespace fh { namespace cme { namespace market { class StatusManager { public: StatusManager(fh::core::market::MarketListenerI *sender, fh::cme::market::DefinitionManager *definition_manager); virtual ~StatusManager(); public: // 接受到产品状态消息(tag 35-MsgType=f)后发送出去 void On_new_status(const fh::cme::market::message::MdpMessage &message); static void Send(fh::core::market::MarketListenerI *sender, const std::string &contract, mktdata::SecurityTradingStatus::Value status); private: // 将 SecurityTradingStatus 转换为: 1(Auctioning) 2(Trading) 3(NoTrading) 4(Other) static std::uint8_t Convert_status(mktdata::SecurityTradingStatus::Value status); private: fh::cme::market::message::MessageParserF m_parser_f; fh::core::market::MarketListenerI *m_sender; fh::cme::market::DefinitionManager *m_definition_manager; private: DISALLOW_COPY_AND_ASSIGN(StatusManager); }; } // namespace market } // namespace cme } // namespace fh #endif // __FH_CME_MARKET_STATUS_MANAGER_H__
cc3ee1c519d42f09e6f73634ca76d2a71ad7218d
6400ecfbff42fd8d717a34f14f1b8e80ec9b070f
/log.cpp
f5b3bc4bd01dd126008459f26f4db0c9955c3ba5
[]
no_license
skyitachi/kv_engine
a4ccc347f808e8754e8b7eb3cbbf618d0bb08a61
6b78dc0da6ad62870f6184df05be303b1523db7d
refs/heads/master
2020-04-08T15:46:27.265633
2018-12-22T13:40:56
2018-12-22T13:40:56
159,491,222
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
log.cpp
// // Created by skyitachi on 2018/11/29. // #include "log.h" #include "util.h" namespace polar_race { RetCode Log::AddRecord(const PolarString &key, const PolarString &v) { char buf[32]; auto keyLen = key.size(); auto valueLen = v.size(); // TODO: 尽量一次调用 WriteUnsignedLong(keyLen, buf); write(fd_, buf, sizeof(size_t)); FileAppend(fd_, key.ToString()); WriteUnsignedLong(valueLen, buf); write(fd_, buf, sizeof(size_t)); FileAppend(fd_, v.ToString()); return kSucc; } }
88826852152a96f08ce8562070e1e6e8402a65fa
da1237f75c380da2bd06b15976206d02b1883c5e
/cgv-develop/build/vs14/cg_icons/open32.png.cxx
974f363953403665abbe1b359bdc6b37053a7393
[]
no_license
Cgironalas/cgv-hdp-cr
7b5e989c4fd0e0695ad179aa30f15fe8434b1f15
f858119674e551ac6777fa9a5072c615a5225670
refs/heads/master
2021-09-24T03:44:29.568892
2018-10-02T16:44:45
2018-10-02T16:44:45
109,702,116
0
0
null
null
null
null
UTF-8
C++
false
false
4,805
cxx
open32.png.cxx
#include <cgv/base/register.h> //D:\Users\CGiron\Documents\Project\cgv-develop\plugins\cg_icons\open32.png ==> open32.png static char resource_file[] = { 10,111,112,101,110,51,50,46,112,110,103, -1,-1,-1,-1, -85,4,0,0, -119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32, 0,0,0,32,8,2,0,0,0,-4,24,-19,-93,0,0,0,9,112,72,89, 115,0,0,18,116,0,0,18,116,1,-34,102,31,120,0,0,4,93,73,68, 65,84,120,-38,-75,-106,-55,-114,28,69,16,-122,-1,-56,-83,-86,-85,-70,-89,123, 22,47,-40,-78,-115,-115,-116,108,89,-100,16,2,9,-28,27,72,112,-29,101,56, 113,-32,9,120,8,-124,-60,35,-16,30,6,35,4,-40,120,108,-49,-30,-79,61, -43,91,-83,-71,4,-121,-102,-34,-122,-15,50,96,-57,-79,58,59,-66,-52,63,34, -1,12,98,102,-68,-51,16,120,-53,-95,0,12,-121,-121,-35,52,126,-77,121,109, -45,116,-46,-63,17,-32,-47,-61,-19,56,22,-41,-33,-65,-15,-90,-78,123,-17,118, 119,-73,-33,-69,62,3,0,-40,-37,-37,-35,-36,60,-109,-90,-35,55,2,-104,76, -122,-50,-71,-123,68,109,76,39,-39,100,-100,117,-69,-23,-1,-52,-34,52,-115,-108, 114,-91,6,11,-31,-84,-11,-34,-65,50,69,-37,120,68,116,-30,-81,33,-16,82, -2,85,-64,-117,34,-19,-116,97,-17,114,-16,51,0,0,16,41,43,62,-82,27, 38,-94,23,-63,94,27,16,-66,67,-8,3,-104,-35,-104,54,27,117,-77,-22,-37, -58,93,87,74,43,37,-1,59,32,-91,123,-80,127,34,-82,16,45,125,117,64, -34,-60,-31,-82,-77,83,-93,58,18,10,68,32,9,-22,6,14,66,-86,66,119, 66,8,68,-12,106,0,-29,47,-64,34,6,-52,-46,87,13,-28,-36,-119,126,-20, 68,109,-22,-93,67,-127,82,104,2,81,65,95,-43,-11,45,-83,-75,2,64,-124, -120,-58,42,60,11,-63,10,87,46,-101,71,-96,-60,-120,-33,3,57,113,108,39, 4,-12,0,-82,-26,-69,64,-45,74,56,2,3,30,-49,-78,67,-12,38,105,-102, 42,0,-87,-50,110,-90,-33,-56,113,5,102,84,43,-27,10,-30,108,30,-99,-81, 34,-114,44,41,-123,69,123,16,-48,57,38,-27,-68,79,-127,33,-74,119,-41,41, 125,46,-91,84,0,74,-37,-13,-127,37,101,-72,4,44,87,43,64,-20,101,-15, -12,-63,52,-113,125,32,17,47,41,-86,68,43,11,17,113,-92,-126,22,66,64, -76,-58,102,-47,52,-47,-10,-29,-50,-39,-117,-123,115,78,1,-16,-84,118,-22,47, -82,38,63,-128,-128,-115,-43,125,25,-24,-57,-11,-70,-81,-111,3,-7,-4,-66,-84, -86,37,-60,-31,-71,45,-99,-88,56,38,-83,33,44,14,-57,3,-25,61,51,11, 49,-109,-10,-48,127,120,-107,126,66,102,-79,-75,10,88,3,110,0,-31,120,-35, -25,29,-117,12,-40,9,-109,-57,-59,52,78,-74,-74,68,-65,39,98,75,-5,-49, -49,17,-111,-42,90,41,117,4,-104,-14,-69,86,-36,-44,-7,29,-72,127,-75,-82, 120,-87,-87,15,-128,61,-12,-21,-22,-73,-121,-58,90,41,3,41,-48,-10,-34,101, -83,-75,49,70,107,125,-12,87,34,76,-11,-105,8,-64,-16,-108,-42,19,1,9, -6,-58,-37,-62,-113,70,97,60,12,117,-51,-93,-23,-122,86,42,-114,99,41,-27, 98,111,-91,-71,-51,-44,-59,-13,-45,-37,-37,6,36,-15,-123,-44,-26,57,-25,-93, -112,-115,-30,73,-79,102,-116,49,-58,-84,0,-84,-68,80,-30,3,-108,64,115,74, -64,26,32,112,-83,-33,84,21,-25,19,126,-76,-65,37,-124,-48,90,25,99,-124, 16,11,0,17,70,-14,115,4,32,59,37,-64,0,9,-42,99,47,93,-88,10, 126,-14,-84,71,68,109,1,-120,104,-91,124,-91,-2,-116,-59,-6,-87,1,0,54, 33,-119,47,36,54,-49,-7,-63,78,31,-52,66,74,-91,-44,113,64,-112,3,23, 125,-126,10,40,-128,0,-124,-91,118,124,121,-12,0,-127,107,-125,102,-102,-121,-99, 39,-58,121,-81,-92,104,109,-4,-72,-39,-107,-55,-41,-70,-4,25,-9,1,61,-77, -124,19,-3,80,-49,76,91,-52,22,104,108,36,-66,-52,101,54,12,-105,-84,11, -127,-123,16,39,1,-52,-89,-66,-9,125,61,-71,51,122,58,-54,-78,97,93,30, -54,48,102,-10,-110,-72,-97,52,74,4,-94,16,105,-97,24,75,96,0,73,-46, -112,-104,-71,35,-109,-49,-49,-124,-64,-50,123,34,48,51,51,31,7,16,-119,-70, 115,-69,-78,87,-57,-45,-125,-125,-22,-63,-50,-2,65,-106,-115,-32,11,37,-84,-111, 85,123,-115,25,112,-50,55,-42,91,27,2,-13,-36,125,-119,104,84,111,-11,-42, 122,-35,110,58,111,-97,19,-50,-81,-88,73,-93,58,-22,103,3,-27,46,110,118, -118,82,88,-69,-74,-16,112,-115,64,-20,92,-88,42,91,55,-42,-69,48,47,19, -43,84,-72,-115,-126,46,-65,115,-2,92,-110,36,45,-29,4,64,16,125,-87,-69, 81,39,81,125,-109,-110,119,-50,-5,-64,-117,106,11,-128,-40,-5,-48,88,107,109, 123,0,110,93,-102,75,81,-40,-83,-102,-49,12,54,-50,49,66,-37,69,106,105, 86,0,51,63,57,120,10,-64,112,105,60,113,71,-77,-106,96,4,94,-15,-16, 118,-71,-108,44,-60,66,31,16,-100,-48,-90,-20,109,-12,-41,77,-78,86,-106,101, 59,9,-88,-39,-64,-30,-18,-35,-1,123,-66,90,83,-95,-39,33,122,-15,-101,-51, -13,119,103,-10,64,-43,104,-68,108,106,63,46,-10,-45,62,6,-3,-75,-123,68, 117,83,-1,-14,-21,-35,-7,44,6,32,-110,-75,-110,-10,-88,83,95,39,24,112, 40,-83,-14,65,10,34,-26,-5,87,-82,92,-71,121,-21,35,0,116,-14,-8,-50, 21,16,64,-89,1,48,60,71,68,-76,108,63,0,-2,1,-51,-86,37,-97,-64, 10,-121,-112,0,0,0,0,73,69,78,68,-82,66,96,-126 }; cgv::base::resource_file_registration resource_file_open32_png(resource_file);
83df7ce62a537296c3c636776068a4f2a1681a3d
e790af34145ed2b5483fd548352f82aaf59f0e86
/src/array/two_sum_ii_input_array_is_sorted.cpp
cd8d34efb21663c52a1638d36c296b75009e8c73
[ "MIT" ]
permissive
dankondr/leetcode-solutions
8d160bb3f912d584884109f987f4c6ece530f02b
9d8424710ed35afd371edeafa1fb89653654fb64
refs/heads/main
2023-03-09T02:34:35.919645
2021-02-18T17:18:40
2021-02-18T17:18:40
339,167,199
0
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
two_sum_ii_input_array_is_sorted.cpp
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int i = 0, j = numbers.size() - 1; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum == target) { return {i + 1, j + 1}; } sum < target ? ++i : --j; } return {}; } string repr(vector<int> answer) { return to_string(answer[0]) + " " + to_string(answer[1]); } }; int main() { /* Input: nums = [2,7,11,15], target = 9 Output: [1,2] */ auto solution = Solution(); vector<int> nums = {2,7,11,15}; int target = 9; cout << solution.repr(solution.twoSum(nums, target)) << endl; return 0; }
8fb05a90c25205d8e455584ff59deffe623f3c35
c47f85f33897c32b41dfd79eb9ecc34fcc0fe2c6
/Modules/SlicerWelcome/.svn/text-base/vtkMRMLSlicerWelcomeNode.cxx.svn-base
9c5f18b60b212dd8d663185f631846ceaef17c92
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-3dslicer-1.0", "BSD-3-Clause" ]
permissive
pieper/ModelDraw
1193b716209fdac6a38d48d42a8b9ffcf067a43c
2ec77974b2c1a8f666704957be854877238e0f0c
refs/heads/master
2020-05-21T00:19:35.884629
2015-06-25T08:42:14
2015-06-25T08:42:14
2,093,941
3
1
null
null
null
null
UTF-8
C++
false
false
3,229
vtkMRMLSlicerWelcomeNode.cxx.svn-base
#include <string> #include <iostream> #include <sstream> #include <fstream> #include "vtkObjectFactory.h" #include "vtkMRMLSlicerWelcomeNode.h" //------------------------------------------------------------------------------ vtkMRMLSlicerWelcomeNode* vtkMRMLSlicerWelcomeNode::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMRMLSlicerWelcomeNode"); if(ret) { return (vtkMRMLSlicerWelcomeNode*)ret; } // If the factory was unable to create the object, then create it here. return new vtkMRMLSlicerWelcomeNode; } //---------------------------------------------------------------------------- vtkMRMLNode* vtkMRMLSlicerWelcomeNode::CreateNodeInstance() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMRMLSlicerWelcomeNode"); if(ret) { return (vtkMRMLSlicerWelcomeNode*)ret; } // If the factory was unable to create the object, then create it here. return new vtkMRMLSlicerWelcomeNode; } //---------------------------------------------------------------------------- vtkMRMLSlicerWelcomeNode::vtkMRMLSlicerWelcomeNode() { this->GUIWidth = 0; this->WelcomeGUIWidth = 0; } //---------------------------------------------------------------------------- vtkMRMLSlicerWelcomeNode::~vtkMRMLSlicerWelcomeNode() { } //---------------------------------------------------------------------------- void vtkMRMLSlicerWelcomeNode::WriteXML(ostream& of, int nIndent) { Superclass::WriteXML(of, nIndent); // Write all MRML node attributes into output stream vtkIndent indent(nIndent); of << indent << " LastGUIWidth =\"" << this->GetGUIWidth() << "\""; of << indent << " WelcomeGUIWidth =\"" << this->GetWelcomeGUIWidth() << "\""; } //---------------------------------------------------------------------------- void vtkMRMLSlicerWelcomeNode::ReadXMLAttributes(const char** atts) { vtkMRMLNode::ReadXMLAttributes(atts); // Read all MRML node attributes from two arrays of names and values const char* attName; const char* attValue; while (*atts != NULL) { attName = *(atts++); attValue = *(atts++); if (!strcmp(attName, "LastGUIWidth")) { this->SetGUIWidth( atoi (attValue )); } else if (!strcmp(attName, "WelcomeGUIWidth")) { this->SetWelcomeGUIWidth( atoi (attValue )); } } } //---------------------------------------------------------------------------- // Copy the node's attributes to this object. // Does NOT copy: ID, FilePrefix, Name, VolumeID void vtkMRMLSlicerWelcomeNode::Copy(vtkMRMLNode *anode) { Superclass::Copy(anode); vtkMRMLSlicerWelcomeNode *node = (vtkMRMLSlicerWelcomeNode *) anode; this->SetGUIWidth ( node->GetGUIWidth() ); this->SetGUIWidth ( node->GetWelcomeGUIWidth() ); } //---------------------------------------------------------------------------- void vtkMRMLSlicerWelcomeNode::PrintSelf(ostream& os, vtkIndent indent) { vtkMRMLNode::PrintSelf(os,indent); os << indent << "GUIWidth: " << this->GetGUIWidth() << "\n"; os << indent << "WelcomeGUIWidth: " << this->GetWelcomeGUIWidth() << "\n"; }
da8e94c222542a861fd2814c00f3692ccbb58849
6693c202f4aa960b05d7dfd0ac8e19a0d1199a16
/COJ/eliogovea-cojAC/eliogovea-p2840-Accepted-s615523.cpp
38fbedf7be4dc16e087de0911486de4a2177aebb
[]
no_license
eliogovea/solutions_cp
001cf73566ee819990065ea054e5f110d3187777
088e45dc48bfb4d06be8a03f4b38e9211a5039df
refs/heads/master
2020-09-11T11:13:47.691359
2019-11-17T19:30:57
2019-11-17T19:30:57
222,045,090
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
eliogovea-p2840-Accepted-s615523.cpp
#include <cstdio> int n, dp[1000]; int main() { scanf("%d", &n); int sum = n * (n + 1) / 2; if (sum & 1) printf("0\n"); else { dp[0] = 1; for (int i = 1; i <= n; i++) for (int j = sum; j >= i; j--) dp[j] += dp[j -i]; printf("%d\n", dp[sum / 2] / 2); } }
34d45efb0ee6419882922c9271cc104179dcabe0
1c08bf5f5188daef7d19010de248f4506bb87987
/NewIterator.hpp
720b322c9bc1a0c4c9c912612251db27441712f5
[]
no_license
PolyubinAI/oop_exercise_6
b8047c95e4ed4ddc48e2552296eb945d7fe6b3d5
ab823e88df1b24079f0e023c302df67f4845df79
refs/heads/main
2023-02-05T17:49:10.715111
2020-12-25T06:52:38
2020-12-25T06:52:38
324,305,915
0
0
null
null
null
null
UTF-8
C++
false
false
1,361
hpp
NewIterator.hpp
// // Created by Ars Polybin on 20.11.2020. // #ifndef LAB5_NEWITERATOR_HPP #define LAB5_NEWITERATOR_HPP #include <cstddef> #include <cstdio> #include <iterator> //Структура итерарора для последовательного контейнера template <typename T> struct iterator {//iteraor traits using iterator_category = std::forward_iterator_tag; using value_type = T; using reference = T&; using difference_type = int; using pointer = T*; T* ptr; iterator (T* ptr_ = nullptr) : ptr(ptr_) {} T& operator*() { return *ptr; } T* operator--() { return --ptr; } T* operator->() { return ptr; } T* operator++() { return ++ptr; } bool operator==(iterator const& other) const { return ptr == other.ptr; } bool operator!=(iterator const& other) const { return !(*this == other); } }; template <typename T> bool operator<(iterator<T> const& lhs, iterator<T> const& rhs) { return lhs.ptr < rhs.ptr; } template <typename T> bool operator>(iterator<T> const& lhs, iterator<T> const& rhs) { return rhs.ptr < lhs.ptr; } template <typename T> bool operator<=(iterator<T> const& lhs, iterator<T> const& rhs) { return !(rhs.ptr < lhs.ptr); } template <typename T> bool operator>=(iterator<T> const& lhs, iterator<T> const& rhs) { return !(lhs.ptr < rhs.ptr); } #endif //LAB5_NEWITERATOR_HPP
928df64ef7f4b55bdb9bb2aefb37d8e07c19e84f
537de3cced1db446036ab97b7bfddcbd8a700446
/Sketches/SlotControl/src/VB_Stucts.h
0aa3bbfa27fa18d0fd4a5643ee8862ab1363b15a
[]
no_license
nicoleyimessier/VolumeControlFun
c893d7114ff6cec4b1f8d56898bffadf85393d69
61aa6570260eddbabaa5a595718e092aaca87395
refs/heads/master
2021-01-24T02:47:50.879369
2018-02-25T22:40:51
2018-02-25T22:40:51
122,863,085
0
0
null
null
null
null
UTF-8
C++
false
false
129
h
VB_Stucts.h
// // VB_Stucts.h // SlotControl // // Created by Nicole Messier on 2/25/18. // // #include "ofMain.h" namespace VB{ }
4336836e5db5adf466653984518b72d2705b2ee6
5f6c9b9a98270440de605bdc75e0bdb706937c0e
/btap lap 7/bai4_lap7_timchuoisoduongcotonglonnhat.cpp
a3f47ea2189ed12118a5cd43f5e9c32332c8f316
[]
no_license
hoa2405/btap-t1911e
e6777ade04a7106fa4da704ab2b306c61c78f248
677b0ce3b8d66d3e29e0fe667cbf6de93e443621
refs/heads/master
2020-09-22T00:37:12.773573
2020-03-27T11:43:21
2020-03-27T11:43:21
224,988,515
0
0
null
null
null
null
UTF-8
C++
false
false
376
cpp
bai4_lap7_timchuoisoduongcotonglonnhat.cpp
#include <stdio.h> int main (){ int n; printf ("nhap n= \n"); scanf ("%d",&n); printf ("nhap cac phan tu cua n: \n"); int ary[n],count = 0,max_count=0; for (int i = 0; i < n; ++i){ scanf ("%d",&ary[i]); if(ary[i]>0){ count+=ary[i]; if(count > max_count){ max_count = count; } }else{ count =0; } } printf("max: %d\n",max_count); return 0; }
b9c45ac84754329c06ad1da58e27129764dbffe8
9c960db52f0e4867157aec7661406712b49d2e1c
/vegtelen3.cpp
01d30439346e59cdf3ce74fe98ba9018beea448b
[]
no_license
Mizumikara/Prog1
53e97830cb3c639a575d134ffdd4be4cb2a5e4db
4d6b6fa615d166e99e6afde665f0d943a4e83822
refs/heads/master
2020-04-28T01:49:49.590338
2019-04-03T08:56:08
2019-04-03T08:56:08
174,874,035
0
0
null
null
null
null
UTF-8
C++
false
false
118
cpp
vegtelen3.cpp
#include <stdio.h> #include <omp.h> int main() { #pragma omp parallel //minden cpu 100% while(1) { } return 0; }
c8b416b794099bd0b7e032eae7172402ff295f40
668b27adf2037d4589b386f67234c6bbb13957f1
/open_procress/open_procress/open_procress.cpp
bdc3184862c88388868aad0f59ee6ccac0cdb958
[ "MIT" ]
permissive
15608447849/cppCode
cda7f3569e8a795ba184878784f16a5df793449d
e94956968ac0e620320114407f7893480e0676b8
refs/heads/master
2021-07-22T08:00:55.894110
2017-11-01T08:09:33
2017-11-01T08:09:33
109,070,078
0
0
null
null
null
null
GB18030
C++
false
false
1,866
cpp
open_procress.cpp
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"") //设置入口地址 - 不显示控制台 #include "stdafx.h" #include <windows.h> #include <iostream> #include <string.h> #include <direct.h> #include <io.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> using namespace std; //文件路径处理 string& filePathHandle(string& path) { //cout << path.c_str() << endl; string::size_type pos = 0; pos = 0; while ((pos = path.find_first_of("/", pos)) != string::npos) { path.replace(pos, 1, "\\");//替换 pos++; } pos = 0; path.erase(0, path.find_first_not_of(" ")); path.erase(path.find_last_not_of(" ") + 1); while ((pos = path.find_first_of(" ", pos)) != string::npos) { path.replace(pos, 1, "\040"); pos = pos++; } return path; } //打开一个程序 void openProcress(const char* path,const char* type) { //cout << path <<" "<<type<<endl; int flag = 0;//表示默认的参数,默认的参数,表示进程如何创建:可以是窗口出现,可以是隐藏的出现 if (strcmp(type, "console") == 0) { flag = CREATE_NEW_CONSOLE; } else if (strcmp(type,"server") == 0) { flag = CREATE_NO_WINDOW; } DWORD dwCreationFlags = flag; string filePath = path; filePathHandle(filePath); TCHAR file[100]; MultiByteToWideChar(CP_ACP, 0, filePath.c_str(), -1, file, 100); STARTUPINFO si = { sizeof(si) }; PROCESS_INFORMATION pi; bool bRet = CreateProcess( file, NULL, NULL, NULL, FALSE, dwCreationFlags,//CREATE_NEW_CONSOLE,//CREATE_NO_WINDOW, NULL, NULL, &si, &pi); if (bRet) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } } int main(int argc, char *argv[]) { for (int i = 0; i < argc;i< i++) { cout << argv[i] << endl; if (strcmp(argv[i],"open")==0) { openProcress(argv[i+1], argv[i+2]); break; } } return 0; }
0cb40f815414f1a76f919b23fc1f5678d942c7c5
4ad2ec9e00f59c0e47d0de95110775a8a987cec2
/_Codeforces/Round 199/E/main.cpp
5048f2726660567c914f3b20174bd8348b5749b1
[]
no_license
atatomir/work
2f13cfd328e00275672e077bba1e84328fccf42f
e8444d2e48325476cfbf0d4cfe5a5aa1efbedce9
refs/heads/master
2021-01-23T10:03:44.821372
2021-01-17T18:07:15
2021-01-17T18:07:15
33,084,680
2
1
null
2015-08-02T20:16:02
2015-03-29T18:54:24
C++
UTF-8
C++
false
false
2,816
cpp
main.cpp
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <cmath> using namespace std; #define mp make_pair #define pb push_back #define ll long long #define maxN 100011 #define inf 1000000000; int n, m, i, x, y, op; vector<int> list[maxN]; int cnt[maxN]; int R; vector<int> adj[maxN]; bool dead[maxN]; vector< pair<int, int> > dist[maxN]; vector<int> way; int lvl[maxN]; int ans[maxN]; int dad[maxN]; void clean(vector<int>& v) { for (int i = 0; i < v.size(); i++) { if (dead[v[i]]) { v[i] = v.back(); v.pop_back(); i--; continue; } } } void dfs(int node, int root) { cnt[node] = 1; clean(list[node]); for (auto to : list[node]) { if (to == root || dead[to]) continue; dfs(to, node); cnt[node] += cnt[to]; } } int dfs2(int node, int root, int target) { bool ok = true; for (auto to : list[node]) { if (to == root || dead[to]) continue; int ans = dfs2(to, node, target); if (ans) return ans; if (cnt[to] > target / 2) ok = false; } if (target - cnt[node] > target / 2) ok = false; if (ok) return node; return 0; } void dfs_dist(int node, int root) { way.pb(node); dist[node].pb(mp(way.size() - 1, way[0])); for (auto to : list[node]) if (to != root && dead[to] == false) dfs_dist(to, node); way.pop_back(); } int get_centroid(int node, int act_lvl) { int R; dfs(node, 0); R = dfs2(node, 0, cnt[node]); dfs_dist(R, 0); lvl[R] = act_lvl; dead[R] = true; for (auto to : list[R]) { if (!dead[to]) { int aux = get_centroid(to, act_lvl + 1); adj[R].pb(aux); dad[aux] = R; } } /*sort(dist[R].begin(), dist[R].end(), [](const pair<int, int>& a, const pair<int, int>& b)->bool const { return lvl[ a.second ] < lvl[ b.second ]; });*/ return R; } int main() { //freopen("test.in","r",stdin); scanf("%d%d", &n, &m); for (i = 1; i < n; i++) { scanf("%d%d", &x, &y); list[x].pb(y); list[y].pb(x); } R = get_centroid(1, 0); for (i = 1; i <= n; i++) ans[i] = inf; for (i = 0; i <= m; i++) { if (i > 0) scanf("%d%d", &op, &x); else op = 1, x = 1; if (op == 1) { for (int lca = x; lca != 0; lca = dad[lca]) ans[lca] = min(ans[lca], dist[x][ lvl[lca] ].first); } if (op == 2) { int sol = inf; for (int lca = x; lca != 0; lca = dad[lca]) sol = min(sol, dist[x][ lvl[lca] ].first + ans[lca]); printf("%d\n", sol); } } return 0; }
45f07d45b2610d55c06f209a817ac7821f245eb3
bfe1b0a690083adbef4b3569d06b93a7f24bb380
/uva 332 - Rational Numbers from Repeating Fractions/main.cpp
00c0b22e8f75fecffff115183f3c68b9e8322aa5
[]
no_license
tajimiitju/UVA_solves_by_tajim
e5a080b6167dee605bc57de8461b707c95a0864a
e9513c6fe7c68567eea489133bb8a990d1582448
refs/heads/master
2021-05-13T12:25:47.384402
2017-12-03T20:48:44
2017-12-03T20:48:44
116,672,900
0
1
null
null
null
null
UTF-8
C++
false
false
980
cpp
main.cpp
//accepted :) #include <iostream> #include <sstream> #include <string> #include <stdio.h> #include <cmath> #include <algorithm> #include<bits/stdc++.h> #define ll long long using namespace std; char s[100000005]; ll GCD(ll a, ll b) { if(b==0) return a; return GCD(b, a%b); } int main() { ll c,j; c=0; while(cin>>j) { c++; unsigned ll g,x,y,q,p,lob,hor; if(j == -1) break; scanf(" %s",s); x=q=0; y=p=1; for(int i=2; i<strlen(s); i++) { x=x*10+s[i]-'0',y*=10; } for(int i=2; i<strlen(s)-j; i++) { q=q*10+s[i]-'0',p*=10; } if(j>0) { lob=x-q; hor=y-p; } else { lob=x; hor=y; } g = 0; g=GCD(lob, hor); //g=__gcd(lob,hor); printf("Case %lld: %lld/%lld\n", c, lob/g , hor/g ); } return 0; }
bb34cdb5fe4d16fa717b877527946dafd220b0a4
51e80c2a9300281777982cf6d4f9eec3014cec05
/Lab_1_Simple_objects/CoffeMachine/CoffeMachine/coffe_machine.cpp
89aff314e9323ae317dd110bff2d28a41ef5bab5
[]
no_license
VladyslavShch/OOP
ef4602ec1b5bc1c09c6be3f9ab5ae75c93d0cf9d
c8da3d535d055143e4e13b3fbce2007ae8aa3ebe
refs/heads/master
2020-07-29T09:06:55.954409
2017-02-20T22:40:39
2017-02-20T22:40:39
73,677,276
0
0
null
null
null
null
UTF-8
C++
false
false
10,365
cpp
coffe_machine.cpp
#include "coffe_machine.hpp" #include <cassert> //Out of information about state of our Coffe Machine //in next format: count of seeds, count of water, count of portions std::ostream & operator << ( std::ostream& _o, const CoffeMachine & _cm) { _o << _cm.SeedsInfo() << ' ' << _cm.WaterInfo() << ' ' << _cm.PortionsInfo() << std::endl; return _o; } CoffeMachine::CoffeMachine ( int _max_coffe, int _max_water, int _max_portion ) { m_Machine[Max_seeds] = _max_coffe; m_Machine[Max_water] = _max_water; m_Machine[Max_portion] = _max_portion; m_Machine[Current_seeds] = 0; m_Machine[Current_rubbish] = 0; m_Machine[Current_water] = 0; } int CoffeMachine::FillSeeds() { //We return a count of seeds which put into Coffe Machine int temp = m_Machine[Max_seeds] - m_Machine[Current_seeds]; m_Machine[Current_seeds] = m_Machine[Max_seeds]; return temp; } int CoffeMachine::FillWater() { //We return a count of water which put into Coffe Machine int temp = m_Machine[Max_water] - m_Machine[Current_water]; m_Machine[Current_water] = m_Machine[Max_water]; return temp; } bool CoffeMachine::MakeCoffe( int _type, int _power ) { assert ( _type == Espresso || _type == Americano); assert ( _power >= Light && _power <= Strong ); //condition when we can't make coffe if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] == 0 || m_Machine[Current_water] == 0 ) return false; else if ( _type == Espresso && _power == Light ) { //condition when we can't make Light Espresso if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 4 || m_Machine[Current_water] < 120 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 4; m_Machine[Current_water] = m_Machine[Current_water] - 120; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 1; return true; } } else if ( _type == Espresso && _power == Middle ) { if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 120 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 8; m_Machine[Current_water] = m_Machine[Current_water] - 120; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 1; return true; } } else if ( _type == Espresso && _power == Strong ) { if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 12 || m_Machine[Current_water] < 120 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 12; m_Machine[Current_water] = m_Machine[Current_water] - 120; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 1; return true; } } else if ( _type == Americano && _power == Light ) { if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 4 || m_Machine[Current_water] < 200 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 4; m_Machine[Current_water] = m_Machine[Current_water] - 200; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 1; return true; } } else if ( _type == Americano && _power == Middle ) { if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 200 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 8; m_Machine[Current_water] = m_Machine[Current_water] - 200; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 1; return true; } } else if ( _type == Americano && _power == Strong ) { if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 12 || m_Machine[Current_water] < 200 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 12; m_Machine[Current_water] = m_Machine[Current_water] - 200; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 1; return true; } } } bool CoffeMachine::MakeDoubleCoffe( int _type, int _power ) { assert ( _type == Espresso || _type == Americano); assert ( _power >= Light && _power <= Strong ); if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] == 0 || m_Machine[Current_water] == 0 ) return false; else if ( _type == Espresso && _power == Light ) { if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion]-1 || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 240 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 8; m_Machine[Current_water] = m_Machine[Current_water] - 240; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 2; return true; } } else if ( _type == Espresso && _power == Middle ) { if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion]-1 || m_Machine[Current_seeds] < 16 || m_Machine[Current_water] < 240 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 16; m_Machine[Current_water] = m_Machine[Current_water] - 240; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 2; return true; } } else if ( _type == Espresso && _power == Strong ) { if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion]-1 || m_Machine[Current_seeds] < 24 || m_Machine[Current_water] < 240 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 24; m_Machine[Current_water] = m_Machine[Current_water] - 240; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 2; return true; } } else if ( _type == Americano && _power == Light ) { if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion]-1 || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 400 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 8; m_Machine[Current_water] = m_Machine[Current_water] - 400; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 2; return true; } } else if ( _type == Americano && _power == Middle ) { if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion]-1 || m_Machine[Current_seeds] < 16 || m_Machine[Current_water] < 400 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 12; m_Machine[Current_water] = m_Machine[Current_water] - 400; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 2; return true; } } else if ( _type == Americano && _power == Strong ) { if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion]-1 || m_Machine[Current_seeds] < 24 || m_Machine[Current_water] < 400 ) return false; else { m_Machine[Current_seeds] = m_Machine[Current_seeds] - 24; m_Machine[Current_water] = m_Machine[Current_water] - 400; m_Machine[Current_rubbish] = m_Machine[Current_rubbish] + 2; return true; } } } void CoffeMachine::CleanMachine() { //500 ml of water - full clean if ( m_Machine[Current_water] >= 500 ) { m_Machine[Current_rubbish] = 0; m_Machine[Current_water] = m_Machine[Current_water] - 500; } //if water is less then 500 ml, we will clean machine not fully else { m_Machine[Current_rubbish] = m_Machine[Current_rubbish] - m_Machine[Current_rubbish] * m_Machine[Current_water] / 500; m_Machine[Current_water] = 0; } } //Function, which is show, that we can make on eportion of choosen coffe bool CoffeMachine::NumberOfPortion( int _type, int _power ) { if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] == 0 || m_Machine[Current_water] == 0 ) return false; else switch( _type ) { case Espresso: switch( _power ) { case Light: if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 4 || m_Machine[Current_water] < 120 ) return false; else return true; break; case Middle: if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 120 ) return false; else return true; break; case Strong: if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 12 || m_Machine[Current_water] < 120 ) return false; else return true; break; } break; case Americano: switch( _power ) { case Light: if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 4 || m_Machine[Current_water] < 200 ) return false; else return true; break; case Middle: if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 200 ) return false; else return true; break; case Strong: if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] < 12 || m_Machine[Current_water] < 200 ) return false; else return true; break; } } } bool CoffeMachine::NumberOfPortion( int _type, int _power, int _double ) { assert ( _double == Double ); if ( m_Machine[Current_rubbish] == m_Machine[Max_portion] || m_Machine[Current_seeds] == 0 || m_Machine[Current_water] == 0 ) return false; else switch( _type ) { case Espresso: switch( _power ) { case Light: if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion] - 1 || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 240 ) return false; else return true; break; case Middle: if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion] - 1 || m_Machine[Current_seeds] < 16 || m_Machine[Current_water] < 240 ) return false; else return true; break; case Strong: if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion] - 1 || m_Machine[Current_seeds] < 24 || m_Machine[Current_water] < 240 ) return false; else return true; break; } break; case Americano: switch( _power ) { case Light: if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion] - 1 || m_Machine[Current_seeds] < 8 || m_Machine[Current_water] < 400 ) return false; else return true; break; case Middle: if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion] - 1 || m_Machine[Current_seeds] < 16 || m_Machine[Current_water] < 400 ) return false; else return true; break; case Strong: if ( m_Machine[Current_rubbish] >= m_Machine[Max_portion] - 1 || m_Machine[Current_seeds] < 24 || m_Machine[Current_water] < 400 ) return false; else return true; break; } } }
137ed46033e556adbd11743161b7a2fcb8c2e1df
42ab733e143d02091d13424fb4df16379d5bba0d
/third_party/libassimp/code/X/XFileImporter.h
7d12b6fdf6dd2d9e34aaa05c9e7073ec89173bfa
[ "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-or-later" ]
permissive
google/filament
11cd37ac68790fcf8b33416b7d8d8870e48181f0
0aa0efe1599798d887fa6e33c412c09e81bea1bf
refs/heads/main
2023-08-29T17:58:22.496956
2023-08-28T17:27:38
2023-08-28T17:27:38
143,455,116
16,631
1,961
Apache-2.0
2023-09-14T16:23:39
2018-08-03T17:26:00
C++
UTF-8
C++
false
false
5,590
h
XFileImporter.h
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2019, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /** @file XFileImporter.h * @brief Definition of the XFile importer class. */ #ifndef AI_XFILEIMPORTER_H_INC #define AI_XFILEIMPORTER_H_INC #include <map> #include "XFileHelper.h" #include <assimp/BaseImporter.h> #include <assimp/types.h> struct aiNode; namespace Assimp { namespace XFile { struct Scene; struct Node; } // --------------------------------------------------------------------------- /** The XFileImporter is a worker class capable of importing a scene from a * DirectX file .x */ class XFileImporter : public BaseImporter { public: XFileImporter(); ~XFileImporter(); // ------------------------------------------------------------------- /** Returns whether the class can handle the format of the given file. * See BaseImporter::CanRead() for details. */ bool CanRead( const std::string& pFile, IOSystem* pIOHandler, bool CheckSig) const; protected: // ------------------------------------------------------------------- /** Return importer meta information. * See #BaseImporter::GetInfo for the details */ const aiImporterDesc* GetInfo () const; // ------------------------------------------------------------------- /** Imports the given file into the given scene structure. * See BaseImporter::InternReadFile() for details */ void InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler); // ------------------------------------------------------------------- /** Constructs the return data structure out of the imported data. * @param pScene The scene to construct the return data in. * @param pData The imported data in the internal temporary * representation. */ void CreateDataRepresentationFromImport( aiScene* pScene, XFile::Scene* pData); // ------------------------------------------------------------------- /** Recursively creates scene nodes from the imported hierarchy. * The meshes and materials of the nodes will be extracted on the way. * @param pScene The scene to construct the return data in. * @param pParent The parent node where to create new child nodes * @param pNode The temporary node to copy. * @return The created node */ aiNode* CreateNodes( aiScene* pScene, aiNode* pParent, const XFile::Node* pNode); // ------------------------------------------------------------------- /** Converts all meshes in the given mesh array. Each mesh is split * up per material, the indices of the generated meshes are stored in * the node structure. * @param pScene The scene to construct the return data in. * @param pNode The target node structure that references the * constructed meshes. * @param pMeshes The array of meshes to convert */ void CreateMeshes( aiScene* pScene, aiNode* pNode, const std::vector<XFile::Mesh*>& pMeshes); // ------------------------------------------------------------------- /** Converts the animations from the given imported data and creates * them in the scene. * @param pScene The scene to hold to converted animations * @param pData The data to read the animations from */ void CreateAnimations( aiScene* pScene, const XFile::Scene* pData); // ------------------------------------------------------------------- /** Converts all materials in the given array and stores them in the * scene's material list. * @param pScene The scene to hold the converted materials. * @param pMaterials The material array to convert. */ void ConvertMaterials( aiScene* pScene, std::vector<XFile::Material>& pMaterials); protected: /** Buffer to hold the loaded file */ std::vector<char> mBuffer; }; } // end of namespace Assimp #endif // AI_BASEIMPORTER_H_INC
b0d02de47b2b491200fc5f4af3290f03fe992750
07dc7eef0569fc05e47461d35f452f2b1693b0ed
/1.print_palindrome/1.print_palindrome.cpp
ec5e7b24cc466b772cce0982a60c7503c54364b3
[]
no_license
ZaitsevaPOLINA/Homework
33d2c7d02460fd79dd33f4f7a11b9469f6ed5cd6
8c26d8e6d529020a7f7730382e29b9cf4146060b
refs/heads/master
2021-01-17T17:37:05.808475
2017-12-10T17:41:57
2017-12-10T17:41:57
70,506,726
0
0
null
2017-01-15T19:42:39
2016-10-10T16:25:23
C++
UTF-8
C++
false
false
557
cpp
1.print_palindrome.cpp
#include <iostream> #include <cmath> using namespace std; void povorot(int k) { while (k>0) { cout << k % 10; k = k / 10; } } void print_palindrom(int n) { cin >> n; if (n % 2 == 0) { int k = pow(10, n / 2 - 1); k=k-k%9+9; while (true) { k+=9; if (k> pow(10,n/2)-1) break; cout << k; povorot(k); cout << " "; } } else { int k=pow(10,n/2); while (true) { k+=9; if (k> pow(10,n/2)-1) break; cout << k; povorot(k); cout << " "; } } int main() { int n; print_palindrom(n); return 0; }
1d4f67d053868ae4008ac61dc1bfbd1652e321d9
a0f8610bcb61463ef9982007dfb877408c3b1a78
/STRJOIN/STRJOIN/main.cpp
e98f2a7d28277799136c4211f53892f6bf195c00
[]
no_license
kiswiss777/Algorithm-SourceCode
75669371f5e9a9a6895543c398bf4a9bfe76c99d
08f01aa3bb1a524e687677a2c8723f1682516dd5
refs/heads/master
2020-04-30T20:50:29.569344
2019-06-14T07:11:15
2019-06-14T07:11:15
177,079,486
0
0
null
null
null
null
UTF-8
C++
false
false
532
cpp
main.cpp
#include<vector> #include<iostream> #include<algorithm> using namespace std; vector<int> str; int get_answer() { int answer = 0; while (str.size() != 1) { sort(str.begin(), str.end()); answer += str[0] + str[1]; str[0] = str[0] + str[1]; str.erase(str.begin() + 1); } return answer; } int main() { int testcase, str_l, input; cin >> testcase; while (testcase--) { cin >> str_l; for (int i = 0; i < str_l; i++) { cin >> input; str.push_back(input); } cout << get_answer() << endl; str.clear(); } }
57330505796fe246f8efb22bfaf4ec8dd0c8280b
b12c8bedabab93fd03df9dd300f66ce85d269ad2
/Source/Vect2.cpp
501270f078f1998d62abffb5c5c5909513b9db50
[]
no_license
olegp/v3d
114de0dbc4702f4ca7e388d648ab32bef135d6f6
a09df4398e402d19405fddc7ebfc52bbf13e8aca
refs/heads/master
2020-12-24T16:50:12.760019
2010-07-14T12:48:35
2010-07-14T12:48:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
935
cpp
Vect2.cpp
// by Oleg Podsechin #include "Vect2.h" void Vect2::operator *= (float scaler) { x *= scaler; y *= scaler; } void Vect2::operator += (const Vect2 &p) { x += p.x; y += p.y; } void Vect2::operator -= (const Vect2 &p) { x -= p.x; y -= p.y; } void Vect2::Zero() { x = y = 0.f; } Vect2 operator -(const Vect2 &p) { return Vect2(-p.x, -p.y); } Vect2 operator +(const Vect2 &a, const Vect2 &b) { return Vect2(a.x + b.x, a.y + b.y); } Vect2 operator -(const Vect2 &a, const Vect2 &b) { return Vect2(a.x - b.x, a.y - b.y); } Vect2 operator *(const Vect2 &p, const Mat3 &m) { return Vect2( m._11*p.x + m._21*p.y + m._31, m._12*p.x + m._22*p.y + m._32 ); } Vect2 operator *(const Vect2 &p, const Mat2 &m) { return Vect2( m._11*p.x + m._21*p.y, m._12*p.x + m._22*p.y ); } bool Vect2::operator == (const Vect2& v) { return (x == v.x && y == v.y); }
a39b9e6dd8807696acee6e08bfbbdbd38c7ebe5a
a548e33c7c894423aecb92277eebdb62fd18a7d6
/adapter/include/BaseShared.h
7b28be388c8ff0c3d015fb25e1e601dd071ebefa
[]
no_license
underbek/Common
0204aca1d5bf80a1484bd8d35535f61c44d4f638
ddddc48f5cbae3c9fa95b457d6962f5dd45aeda6
refs/heads/master
2022-07-19T15:01:07.784817
2019-03-11T11:58:55
2019-03-11T11:58:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
403
h
BaseShared.h
// // Created by Andrey on 2019-01-02. // #ifndef ADAPTER_BASESHARED_H #define ADAPTER_BASESHARED_H #include <memory> template<typename T> struct BaseShared { protected: template<typename F, typename ... V> auto call(F f, V && ... v) { return f(*shared_, std::forward<V>(v)...); } private: std::shared_ptr<T> shared_ = std::make_shared<T>(); }; #endif //ADAPTER_BASESHARED_H
15dadb35241f44213fe0b1c89111fae63a7369d8
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/shell/services/hdsrv/shhwdtct/regnotif.cpp
5f5a13110750c671d075650d105a3d079153a00d
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
35,104
cpp
regnotif.cpp
#include "regnotif.h" #include "svcsync.h" #include "mtpts.h" #include "vol.h" #include "namellst.h" #include "users.h" #include "sfstr.h" #include "tfids.h" #include "dbg.h" #include <shpriv.h> #include <strsafe.h> #define ARRAYSIZE(a) (sizeof((a))/sizeof((a)[0])) #define MAGICTOKENOFFSET ((DWORD)0x57EF57EF) LONG CHardwareDevicesImpl::_lAdviseToken = MAGICTOKENOFFSET; DWORD CHardwareDevicesImpl::_chwdevcb = 0; #define MAX_ADVISETOKEN 11 STDMETHODIMP CHardwareDevicesImpl::EnumVolumes( DWORD dwFlags, IHardwareDevicesVolumesEnum** ppenum) { HRESULT hr; *ppenum = NULL; if ((HWDEV_GETCUSTOMPROPERTIES == dwFlags) || (0 == dwFlags)) { CHardwareDevicesVolumesEnum* phwdve = new CHardwareDevicesVolumesEnum(NULL); if (phwdve) { hr = phwdve->_Init(dwFlags); if (SUCCEEDED(hr)) { *ppenum = phwdve; } else { phwdve->Release(); } } else { hr = E_OUTOFMEMORY; } } else { hr = E_INVALIDARG; } ASSERT((*ppenum && SUCCEEDED(hr)) || (!*ppenum && FAILED(hr))); return hr; } STDMETHODIMP CHardwareDevicesImpl::EnumMountPoints( IHardwareDevicesMountPointsEnum** ppenum) { HRESULT hr; CHardwareDevicesMountPointsEnum* phwdmtpte = new CHardwareDevicesMountPointsEnum(NULL); *ppenum = NULL; if (phwdmtpte) { hr = phwdmtpte->_Init(); if (SUCCEEDED(hr)) { *ppenum = phwdmtpte; } else { phwdmtpte->Release(); } } else { hr = E_OUTOFMEMORY; } ASSERT((*ppenum && SUCCEEDED(hr)) || (!*ppenum && FAILED(hr))); return hr; } STDMETHODIMP CHardwareDevicesImpl::EnumDevices(IHardwareDevicesEnum** /*ppenum*/) { return E_NOTIMPL; } HRESULT _GetStringAdviseToken(LONG lAdviseToken, LPWSTR szAdviseToken, DWORD cchAdviseToken) { HRESULT hr; if (cchAdviseToken >= MAX_ADVISETOKEN) { // 0x12345678 hr = StringCchPrintf(szAdviseToken, cchAdviseToken, TEXT("0x%08X"), lAdviseToken); ASSERT(SUCCEEDED(hr)); } else { hr = E_FAIL; } return hr; } STDMETHODIMP CHardwareDevicesImpl::Advise(DWORD dwProcessID, ULONG_PTR hThread, ULONG_PTR pfctCallback, DWORD* pdwToken) { HRESULT hr; TRACE(TF_ADVISE, TEXT(">>>Called ") TEXT(__FUNCTION__) TEXT(", 0x%08X, 0x%08X, 0x%08X"), dwProcessID, hThread, pfctCallback); if (dwProcessID && hThread && pfctCallback && pdwToken) { LONG lAdviseToken = InterlockedIncrement(&_lAdviseToken); WCHAR szAdviseToken[MAX_ADVISETOKEN]; hr = _GetStringAdviseToken(lAdviseToken, szAdviseToken, ARRAYSIZE(szAdviseToken)); if (SUCCEEDED(hr)) { CNamedElemList* pnel; hr = CHWEventDetectorHelper::GetList(HWEDLIST_ADVISECLIENT, &pnel); if (S_OK == hr) { CNamedElem* pelem; hr = pnel->GetOrAdd(szAdviseToken, &pelem); if (SUCCEEDED(hr)) { CAdviseClient* pac = (CAdviseClient*)pelem; hr = pac->_Init(dwProcessID, hThread, pfctCallback); if (SUCCEEDED(hr)) { *pdwToken = lAdviseToken; } else { pnel->Remove(szAdviseToken); } pelem->RCRelease(); } pnel->RCRelease(); } } if (SUCCEEDED(hr)) { TRACE(TF_ADVISE, TEXT(">>>Advise SUCCEEDED, token = 0x%08X"), lAdviseToken); } } else { hr = E_INVALIDARG; } if (FAILED(hr)) { TRACE(TF_ADVISE, TEXT(">>>Advise FAILED")); } return hr; } STDMETHODIMP CHardwareDevicesImpl::Unadvise(DWORD dwToken) { HRESULT hr; if (dwToken >= (MAGICTOKENOFFSET)) { WCHAR szAdviseToken[MAX_ADVISETOKEN]; hr = _GetStringAdviseToken(dwToken, szAdviseToken, ARRAYSIZE(szAdviseToken)); if (SUCCEEDED(hr)) { CNamedElemList* pnel; hr = CHWEventDetectorHelper::GetList(HWEDLIST_ADVISECLIENT, &pnel); if (S_OK == hr) { pnel->Remove(szAdviseToken); pnel->RCRelease(); } } } else { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { TRACE(TF_ADVISE, TEXT(">>>UNAdvise SUCCEEDED, token = 0x%08X"), dwToken); } else { TRACE(TF_ADVISE, TEXT(">>>UNAdvise FAILED, token = 0x%08X"), dwToken); } return hr; } /////////////////////////////////////////////////////////////////////////////// // class CThreadTaskBroadcastEvent : public CThreadTask { public: CThreadTaskBroadcastEvent() : _pshhe(NULL) {} virtual ~CThreadTaskBroadcastEvent() { if (_pshhe) { _FreeMemoryChunk<SHHARDWAREEVENT*>(_pshhe); } } protected: HRESULT _Broadcast() { CNamedElemList* pnel; HRESULT hr = CHWEventDetectorHelper::GetList(HWEDLIST_ADVISECLIENT, &pnel); if (S_OK == hr) { CNamedElemEnum* penum; hr = pnel->GetEnum(&penum); if (SUCCEEDED(hr) && (S_FALSE != hr)) { CNamedElem* pelem; while (SUCCEEDED(hr) && SUCCEEDED(hr = penum->Next(&pelem)) && (S_FALSE != hr)) { CAdviseClient* pac = (CAdviseClient*)pelem; void* pv; HRESULT hrTmp = pac->WriteMemoryChunkInOtherProcess(_pshhe, _pshhe->cbSize, &pv); if (SUCCEEDED(hrTmp)) { hrTmp = pac->QueueUserAPC(pv); } if (FAILED(hrTmp)) { WCHAR szAdviseToken[MAX_ADVISETOKEN]; DWORD cchReq; TRACE(TF_ADVISE, TEXT(__FUNCTION__) TEXT(": Trying to removed token because failed CB, hr = 0x%08X"), hrTmp); if (SUCCEEDED(pelem->GetName(szAdviseToken, ARRAYSIZE(szAdviseToken), &cchReq))) { TRACE(TF_ADVISE, TEXT(" ") TEXT(__FUNCTION__) TEXT(": Token = %s"), szAdviseToken); pnel->Remove(szAdviseToken); } } pelem->RCRelease(); } penum->RCRelease(); } pnel->RCRelease(); } return hr; } protected: SHHARDWAREEVENT* _pshhe; }; class CThreadTaskMountPointEvent : public CThreadTaskBroadcastEvent { public: HRESULT InitAdded(LPCWSTR pszMtPt, LPCWSTR pszDeviceIDVolume) { ASSERT(!_pshhe); DWORD cbSize = sizeof(SHHARDWAREEVENT) + sizeof(MTPTADDED); HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { MTPTADDED* pmtptadded = (MTPTADDED*)_pshhe->rgbPayLoad; _pshhe->cbSize = cbSize; _pshhe->dwEvent = SHHARDWAREEVENT_MOUNTPOINTARRIVED; hr = SafeStrCpyN(pmtptadded->szMountPoint, pszMtPt, ARRAYSIZE(pmtptadded->szMountPoint)); if (SUCCEEDED(hr)) { hr = SafeStrCpyN(pmtptadded->szDeviceIDVolume, pszDeviceIDVolume, ARRAYSIZE(pmtptadded->szDeviceIDVolume)); if (SUCCEEDED(hr)) { // We give the Shell AllowSetForegroundWindow privilege _GiveAllowForegroundToConsoleShell(); } } } return hr; } HRESULT InitRemoved(LPCWSTR pszMtPt) { ASSERT(!_pshhe); DWORD cbSize = sizeof(SHHARDWAREEVENT) + MAX_PATH * sizeof(WCHAR); HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { _pshhe->cbSize = cbSize; _pshhe->dwEvent = SHHARDWAREEVENT_MOUNTPOINTREMOVED; hr = SafeStrCpyN((LPWSTR)_pshhe->rgbPayLoad, pszMtPt, MAX_PATH); } return hr; } HRESULT _DoStuff() { return _Broadcast(); } }; class CThreadTaskCheckClients : public CThreadTask { public: HRESULT _DoStuff() { CNamedElemList* pnel; // // Get the list of notify clients. // HRESULT hres = CHWEventDetectorHelper::GetList(HWEDLIST_ADVISECLIENT, &pnel); if (S_OK == hres) { CNamedElemEnum* penum; hres = pnel->GetEnum(&penum); if (SUCCEEDED(hres)) { CNamedElem* pelem; // // Enumerate the advised clients. // while (SUCCEEDED(hres = penum->Next(&pelem)) && (S_FALSE != hres)) { CAdviseClient* pac = (CAdviseClient*)pelem; // // Is the process still alive? // HRESULT hrTmp = pac->IsProcessStillAlive( ); if (S_OK != hrTmp) { WCHAR szAdviseToken[MAX_ADVISETOKEN]; DWORD cchReq; // // Nope (or there is some problem with it)... so remove it from the list. // TRACE(TF_ADVISE, TEXT(__FUNCTION__) TEXT(": Trying to removed token because process died, pac = %p"), pac); hrTmp = pelem->GetName(szAdviseToken, ARRAYSIZE(szAdviseToken), &cchReq); if (SUCCEEDED(hrTmp)) { TRACE(TF_ADVISE, TEXT(" ") TEXT(__FUNCTION__) TEXT(": Token = %s"), szAdviseToken); pnel->Remove(szAdviseToken); } } pelem->RCRelease(); } // // Reset the HRESULT if it is the expected exit condition. // if ( S_FALSE == hres ) { hres = S_OK; } penum->RCRelease(); } pnel->RCRelease(); } return hres; } }; class CThreadTaskVolumeEvent : public CThreadTaskBroadcastEvent { public: HRESULT InitAdded(VOLUMEINFO2* pvolinfo2, LPCWSTR pszMtPts, DWORD cchMtPts) { ASSERT(!_pshhe); DWORD cbSize = sizeof(SHHARDWAREEVENT) + pvolinfo2->cbSize; HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { _pshhe->cbSize = cbSize; _pshhe->dwEvent = SHHARDWAREEVENT_VOLUMEARRIVED; CopyMemory(_pshhe->rgbPayLoad, pvolinfo2, pvolinfo2->cbSize); _pszDeviceIDVolume = ((VOLUMEINFO2*)_pshhe->rgbPayLoad)->szDeviceIDVolume; if (SUCCEEDED(hr) && pszMtPts) { hr = _DupMemoryChunk<LPCWSTR>(pszMtPts, cchMtPts * sizeof(WCHAR), &_pszMtPts); } } return hr; } HRESULT InitUpdated(VOLUMEINFO2* pvolinfo2) { ASSERT(!_pshhe); DWORD cbSize = sizeof(SHHARDWAREEVENT) + pvolinfo2->cbSize; HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { _pshhe->cbSize = cbSize; _pshhe->dwEvent = SHHARDWAREEVENT_VOLUMEUPDATED; CopyMemory(_pshhe->rgbPayLoad, pvolinfo2, pvolinfo2->cbSize); _pszDeviceIDVolume = ((VOLUMEINFO2*)_pshhe->rgbPayLoad)->szDeviceIDVolume; // We give the Shell AllowSetForegroundWindow privilege _GiveAllowForegroundToConsoleShell(); } return hr; } HRESULT InitRemoved(LPCWSTR pszDeviceIDVolume, LPCWSTR pszMtPts, DWORD cchMtPts) { ASSERT(!_pshhe); DWORD cbSize = sizeof(SHHARDWAREEVENT) + MAX_DEVICEID * sizeof(WCHAR); HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { _pshhe->cbSize = cbSize; _pshhe->dwEvent = SHHARDWAREEVENT_VOLUMEREMOVED; _pszDeviceIDVolume = ((VOLUMEINFO2*)_pshhe->rgbPayLoad)->szDeviceIDVolume; hr = SafeStrCpyN((LPWSTR)_pshhe->rgbPayLoad, pszDeviceIDVolume, MAX_DEVICEID); if (SUCCEEDED(hr) && pszMtPts) { hr = _DupMemoryChunk<LPCWSTR>(pszMtPts, cchMtPts * sizeof(WCHAR), &_pszMtPts); } } return hr; } HRESULT _DoStuff() { HRESULT hr; switch (_pshhe->dwEvent) { case SHHARDWAREEVENT_VOLUMEARRIVED: case SHHARDWAREEVENT_VOLUMEUPDATED: { hr = _SendVolumeInfo(); if (SUCCEEDED(hr) && (SHHARDWAREEVENT_VOLUMEARRIVED == _pshhe->dwEvent)) { // We need to enum the mountpoints too. We were not // registered to get the notif since this volume was not there hr = _SendMtPtsInfo(); } break; } case SHHARDWAREEVENT_VOLUMEREMOVED: { hr = _SendMtPtsInfo(); if (SUCCEEDED(hr)) { hr = _SendVolumeInfo(); } break; } default: { TRACE(TF_ADVISE, TEXT("DoStuff with unknown SHHARDWAREEVENT_* value")); hr = E_FAIL; break; } } return hr; } private: HRESULT _SendMtPtsInfo() { if (_pszMtPts) { for (LPCWSTR psz = _pszMtPts; *psz; psz += (lstrlen(psz) + 1)) { CThreadTaskMountPointEvent task; HRESULT hr; if (SHHARDWAREEVENT_VOLUMEREMOVED == _pshhe->dwEvent) { hr = task.InitRemoved(psz); } else { hr = task.InitAdded(psz, _pszDeviceIDVolume); } if (SUCCEEDED(hr)) { task.RunSynchronously(); } } } return S_OK; } HRESULT _SendVolumeInfo() { return _Broadcast(); } public: CThreadTaskVolumeEvent() : _pszMtPts(NULL) {} ~CThreadTaskVolumeEvent() { if (_pszMtPts) { _FreeMemoryChunk<LPCWSTR>(_pszMtPts); } } private: LPCWSTR _pszMtPts; LPCWSTR _pszDeviceIDVolume; }; class CThreadTaskGenericEvent : public CThreadTaskBroadcastEvent { public: HRESULT Init(LPCWSTR pszPayload, DWORD dwEvent) { ASSERT(!_pshhe); // maybe use lstrlen()? DWORD cbSize = (DWORD)(sizeof(SHHARDWAREEVENT) + (pszPayload ? MAX_DEVICEID * sizeof(WCHAR) : 0)); HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { LPWSTR pszPayloadLocal = (LPWSTR)_pshhe->rgbPayLoad; _pshhe->cbSize = cbSize; _pshhe->dwEvent = dwEvent; if (pszPayload) { hr = SafeStrCpyN(pszPayloadLocal, pszPayload, MAX_DEVICEID); } } return hr; } HRESULT _DoStuff() { return _Broadcast(); } }; class CThreadTaskDeviceEvent : public CThreadTaskBroadcastEvent { public: HRESULT Init(LPCWSTR pszDeviceIntfID, GUID* pguidInterface, DWORD dwDeviceFlags, DWORD dwEvent) { ASSERT(!_pshhe); DWORD cbSize = (DWORD)(sizeof(SHHARDWAREEVENT) + (sizeof(HWDEVICEINFO))); HRESULT hr = _AllocMemoryChunk<SHHARDWAREEVENT*>(cbSize, &_pshhe); if (SUCCEEDED(hr)) { HWDEVICEINFO* phwdevinfo = (HWDEVICEINFO*)_pshhe->rgbPayLoad; _pshhe->cbSize = cbSize; _pshhe->dwEvent = dwEvent; hr = SafeStrCpyN(phwdevinfo->szDeviceIntfID, pszDeviceIntfID, ARRAYSIZE(phwdevinfo->szDeviceIntfID)); if (SUCCEEDED(hr)) { phwdevinfo->cbSize = sizeof(*phwdevinfo); phwdevinfo->guidInterface = *pguidInterface; phwdevinfo->dwDeviceFlags = dwDeviceFlags; } } return hr; } HRESULT _DoStuff() { return _Broadcast(); } }; HRESULT CHardwareDevicesImpl::_AdviseDeviceArrivedOrRemoved( LPCWSTR pszDeviceIntfID, GUID* pguidInterface, DWORD dwDeviceFlags, LPCWSTR pszEventType) { HRESULT hr; CThreadTaskDeviceEvent* pTask = new CThreadTaskDeviceEvent(); if (pTask) { DWORD dwEvent; if (!lstrcmpi(pszEventType, TEXT("DeviceArrival"))) { dwEvent = SHHARDWAREEVENT_DEVICEARRIVED; } else { dwEvent = SHHARDWAREEVENT_DEVICEREMOVED; } hr = pTask->Init(pszDeviceIntfID, pguidInterface, dwDeviceFlags, dwEvent); if (SUCCEEDED(hr)) { hr = pTask->Run(); } if (FAILED(hr)) { delete pTask; } } else { hr = E_OUTOFMEMORY; } return hr; } //static HRESULT CHardwareDevicesImpl::_AdviseVolumeArrivedOrUpdated( VOLUMEINFO2* pvolinfo2, LPCWSTR pszMtPts, DWORD cchMtPts, BOOL fAdded) { HRESULT hr; TRACE(TF_ADVISE, TEXT(">>>_AdviseVolumeArrivedOrUpdated: fAdded = %d"), fAdded); CThreadTaskVolumeEvent* pTask = new CThreadTaskVolumeEvent(); if (pTask) { if (fAdded) { hr = pTask->InitAdded(pvolinfo2, pszMtPts, cchMtPts); } else { hr = pTask->InitUpdated(pvolinfo2); } if (SUCCEEDED(hr)) { hr = pTask->Run(); } if (FAILED(hr)) { delete pTask; } } else { hr = E_OUTOFMEMORY; } return hr; } // static HRESULT CHardwareDevicesImpl::_AdviseVolumeRemoved(LPCWSTR pszDeviceIDVolume, LPCWSTR pszMtPts, DWORD cchMtPts) { HRESULT hr; TRACE(TF_ADVISE, TEXT(">>>_AdviseVolumeRemoved")); CThreadTaskVolumeEvent* pTask = new CThreadTaskVolumeEvent(); if (pTask) { hr = pTask->InitRemoved(pszDeviceIDVolume, pszMtPts, cchMtPts); if (SUCCEEDED(hr)) { hr = pTask->Run(); } if (FAILED(hr)) { delete pTask; } } else { hr = E_OUTOFMEMORY; } return hr; } //static HRESULT CHardwareDevicesImpl::_AdviseVolumeMountingEvent( LPCWSTR pszDeviceIDVolume, DWORD dwEvent) { TRACE(TF_ADVISE, TEXT(">>>_AdviseVolumeMountingEvent: %s, dwEvent = 0x%08X"), pszDeviceIDVolume, dwEvent); HRESULT hr; CThreadTaskGenericEvent* pTask = new CThreadTaskGenericEvent(); if (pTask) { hr = pTask->Init(pszDeviceIDVolume, dwEvent); if (SUCCEEDED(hr)) { hr = pTask->Run(); } if (FAILED(hr)) { delete pTask; } } else { hr = E_OUTOFMEMORY; } return hr; } //static HRESULT CHardwareDevicesImpl::_AdviseMountPointHelper(LPCWSTR pszMtPt, LPCWSTR pszDeviceIDVolume, BOOL fAdded) { TRACE(TF_ADVISE, TEXT(">>>_AdviseMountPointHelper: %s, fAdded = %d"), pszMtPt, fAdded); HRESULT hr; CThreadTaskMountPointEvent* pTask = new CThreadTaskMountPointEvent(); if (pTask) { if (fAdded) { hr = pTask->InitAdded(pszMtPt, pszDeviceIDVolume); } else { hr = pTask->InitRemoved(pszMtPt); } if (SUCCEEDED(hr)) { hr = pTask->Run(); } if (FAILED(hr)) { delete pTask; } } else { hr = E_OUTOFMEMORY; } return hr; } //static HRESULT CHardwareDevicesImpl::_AdviseCheckClients(void) { HRESULT hr; CThreadTaskCheckClients* pTask = new CThreadTaskCheckClients(); if (pTask) { hr = pTask->Run(); if (FAILED(hr)) { delete pTask; } } else { hr = E_OUTOFMEMORY; } return hr; } /////////////////////////////////////////////////////////////////////////////// // Impl CHardwareDevicesImpl::CHardwareDevicesImpl() { _CompleteShellHWDetectionInitialization(); } CHardwareDevicesImpl::~CHardwareDevicesImpl() {} /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // STDMETHODIMP CHardwareDevicesEnumImpl::Next( LPWSTR* /*ppszDeviceID*/, GUID* /*pguidDeviceID*/) { return E_NOTIMPL; } CHardwareDevicesEnumImpl::CHardwareDevicesEnumImpl() {} CHardwareDevicesEnumImpl::~CHardwareDevicesEnumImpl() {} /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // HRESULT CHardwareDevicesVolumesEnumImpl::_Init(DWORD dwFlags) { CNamedElemList* pnel; HRESULT hr = CHWEventDetectorHelper::GetList(HWEDLIST_VOLUME, &pnel); _dwFlags = dwFlags; if (S_OK == hr) { hr = pnel->GetEnum(&_penum); pnel->RCRelease(); } return hr; } STDMETHODIMP CHardwareDevicesVolumesEnumImpl::Next(VOLUMEINFO* pvolinfo) { HRESULT hr; if (pvolinfo) { if (_penum) { CNamedElem* pelem; hr = _penum->Next(&pelem); if (SUCCEEDED(hr) && (S_FALSE != hr)) { // Const Info WCHAR szVolName[MAX_DEVICEID]; WCHAR szVolGUID[50]; WCHAR szLabel[MAX_LABEL]; WCHAR szFileSystem[MAX_FILESYSNAME]; WCHAR szAutorunIconLocation[MAX_ICONLOCATION]; WCHAR szAutorunLabel[MAX_LABEL]; WCHAR szIconLocationFromService[MAX_ICONLOCATION]; WCHAR szNoMediaIconLocationFromService[MAX_ICONLOCATION]; // We can now have a @%SystemRoot%\system32\shell32.dll,-1785 for MUI stuff WCHAR szLabelFromService[MAX_ICONLOCATION]; CVolume* pvol = (CVolume*)pelem; // Misc DWORD cchReq; ZeroMemory(pvolinfo, sizeof(VOLUMEINFO)); hr = pvol->GetName(szVolName, ARRAYSIZE(szVolName), &cchReq); if (SUCCEEDED(hr)) { hr = pvol->GetVolumeConstInfo(szVolGUID, ARRAYSIZE(szVolGUID), &(pvolinfo->dwVolumeFlags), &(pvolinfo->dwDriveType), &(pvolinfo->dwDriveCapability)); } if (SUCCEEDED(hr)) { hr = pvol->GetVolumeMediaInfo(szLabel, ARRAYSIZE(szLabel), szFileSystem, ARRAYSIZE(szFileSystem), &(pvolinfo->dwFileSystemFlags), &(pvolinfo->dwMaxFileNameLen), &(pvolinfo->dwRootAttributes), &(pvolinfo->dwSerialNumber), &(pvolinfo->dwDriveState), &(pvolinfo->dwMediaState), &(pvolinfo->dwMediaCap)); } if (SUCCEEDED(hr)) { if (HWDEV_GETCUSTOMPROPERTIES & _dwFlags) { szAutorunIconLocation[0] = 0; szAutorunLabel[0] = 0; szIconLocationFromService[0] = 0; szNoMediaIconLocationFromService[0] = 0; szLabelFromService[0] = 0; hr = pvol->GetIconAndLabelInfo(szAutorunIconLocation, ARRAYSIZE(szAutorunIconLocation), szAutorunLabel, ARRAYSIZE(szAutorunLabel), szIconLocationFromService, ARRAYSIZE(szIconLocationFromService), szNoMediaIconLocationFromService, ARRAYSIZE(szNoMediaIconLocationFromService), szLabelFromService, ARRAYSIZE(szLabelFromService)); if (SUCCEEDED(hr)) { if (*szAutorunIconLocation) { hr = _CoTaskMemCopy(szAutorunIconLocation, &(pvolinfo->pszAutorunIconLocation)); } if (SUCCEEDED(hr) && *szAutorunLabel) { hr = _CoTaskMemCopy(szAutorunLabel, &(pvolinfo->pszAutorunLabel)); } if (SUCCEEDED(hr) && *szIconLocationFromService) { hr = _CoTaskMemCopy(szIconLocationFromService, &(pvolinfo->pszIconLocationFromService)); } if (SUCCEEDED(hr) && *szNoMediaIconLocationFromService) { hr = _CoTaskMemCopy(szNoMediaIconLocationFromService, &(pvolinfo->pszNoMediaIconLocationFromService)); } if (SUCCEEDED(hr) && *szLabelFromService) { hr = _CoTaskMemCopy(szLabelFromService, &(pvolinfo->pszLabelFromService)); } } } } if (SUCCEEDED(hr)) { hr = _CoTaskMemCopy(szVolName, &(pvolinfo->pszDeviceIDVolume)); if (SUCCEEDED(hr)) { hr = _CoTaskMemCopy(szVolGUID, &(pvolinfo->pszVolumeGUID)); } if (SUCCEEDED(hr)) { hr = _CoTaskMemCopy(szLabel, &(pvolinfo->pszLabel)); } if (SUCCEEDED(hr)) { hr = _CoTaskMemCopy(szFileSystem, &(pvolinfo->pszFileSystem)); } } if (FAILED(hr)) { _CoTaskMemFree(pvolinfo->pszDeviceIDVolume); _CoTaskMemFree(pvolinfo->pszVolumeGUID); _CoTaskMemFree(pvolinfo->pszLabel); _CoTaskMemFree(pvolinfo->pszFileSystem); _CoTaskMemFree(pvolinfo->pszAutorunIconLocation); _CoTaskMemFree(pvolinfo->pszAutorunLabel); _CoTaskMemFree(pvolinfo->pszIconLocationFromService); _CoTaskMemFree(pvolinfo->pszNoMediaIconLocationFromService); _CoTaskMemFree(pvolinfo->pszLabelFromService); ZeroMemory(pvolinfo, sizeof(VOLUMEINFO)); } pelem->RCRelease(); } } else { hr = S_FALSE; } } else { hr = E_INVALIDARG; } return hr; } CHardwareDevicesVolumesEnumImpl::CHardwareDevicesVolumesEnumImpl() : _penum(NULL) {} CHardwareDevicesVolumesEnumImpl::~CHardwareDevicesVolumesEnumImpl() { if (_penum) { _penum->RCRelease(); } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // HRESULT CHardwareDevicesMountPointsEnumImpl::_Init() { CNamedElemList* pnel; HRESULT hr = CHWEventDetectorHelper::GetList(HWEDLIST_MTPT, &pnel); if (S_OK == hr) { hr = pnel->GetEnum(&_penum); pnel->RCRelease(); } return hr; } STDMETHODIMP CHardwareDevicesMountPointsEnumImpl::Next( LPWSTR* ppszMountPoint, // "c:\", or "d:\MountFolder\" LPWSTR* ppszDeviceIDVolume) // \\?\STORAGE#Volume#...{...GUID...} { HRESULT hr; *ppszMountPoint = NULL; *ppszDeviceIDVolume = NULL; if (_penum) { CNamedElem* pelem; hr = _penum->Next(&pelem); if (SUCCEEDED(hr) && (S_FALSE != hr)) { // Const Info WCHAR szMtPtName[MAX_PATH]; WCHAR szVolName[MAX_DEVICEID]; CMtPt* pmtpt = (CMtPt*)pelem; // Misc DWORD cchReq; hr = pmtpt->GetName(szMtPtName, ARRAYSIZE(szMtPtName), &cchReq); if (SUCCEEDED(hr)) { hr = pmtpt->GetVolumeName(szVolName, ARRAYSIZE(szVolName)); } if (SUCCEEDED(hr)) { hr = _CoTaskMemCopy(szMtPtName, ppszMountPoint); if (SUCCEEDED(hr)) { hr = _CoTaskMemCopy(szVolName, ppszDeviceIDVolume); } else { CoTaskMemFree(*ppszMountPoint); *ppszMountPoint = NULL; } } pelem->RCRelease(); } } else { hr = S_FALSE; } return hr; } CHardwareDevicesMountPointsEnumImpl::CHardwareDevicesMountPointsEnumImpl() : _penum(NULL) {} CHardwareDevicesMountPointsEnumImpl::~CHardwareDevicesMountPointsEnumImpl() { if (_penum) { _penum->RCRelease(); } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// HRESULT CAdviseClient::Init(LPCWSTR pszElemName) { ASSERT(pszElemName); return _SetName(pszElemName); } HRESULT CAdviseClient::_Cleanup() { if (_hProcess) { CloseHandle(_hProcess); _hProcess = NULL; } if (_hThread) { CloseHandle(_hThread); _hThread = NULL; } return S_OK; } HRESULT CAdviseClient::_Init(DWORD dwProcessID, ULONG_PTR hThread, ULONG_PTR pfctCallback) { HRESULT hr = E_FAIL; _Cleanup(); _pfct = (PAPCFUNC)pfctCallback; // rename hProcess! _hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | SYNCHRONIZE | PROCESS_DUP_HANDLE, FALSE, dwProcessID); if (_hProcess) { if (DuplicateHandle(_hProcess, (HANDLE)hThread, GetCurrentProcess(), &_hThread, THREAD_ALL_ACCESS, FALSE, 0)) { hr = S_OK; } } return hr; } HRESULT CAdviseClient::WriteMemoryChunkInOtherProcess(SHHARDWAREEVENT* pshhe, DWORD cbSize, void** ppv) { HRESULT hr = E_FAIL; void* pv = VirtualAllocEx(_hProcess, NULL, cbSize, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE); *ppv = NULL; if (pv) { SIZE_T cbWritten; if (WriteProcessMemory(_hProcess, pv, pshhe, cbSize, &cbWritten) && (cbWritten == cbSize)) { *ppv = pv; hr = S_OK; } else { VirtualFreeEx(_hProcess, pv, 0, MEM_RELEASE); } } else { // Out of mem, but in the other process... hr = E_OUTOFMEMORY; } return hr; } HRESULT CAdviseClient::QueueUserAPC(void* pv) { HRESULT hr; if (::QueueUserAPC(_pfct, _hThread, (ULONG_PTR)pv)) { hr = S_OK; } else { hr = E_FAIL; } return hr; } HRESULT CAdviseClient::IsProcessStillAlive(void) { HRESULT hr; DWORD dwResult = WaitForSingleObject( _hProcess, 0 ); switch (dwResult) { case WAIT_OBJECT_0: hr = S_FALSE; // process has died. break; case WAIT_TIMEOUT: hr = S_OK; // process is still alive break; default: { // problem with handle DWORD dwErr = GetLastError( ); hr = HRESULT_FROM_WIN32( dwErr ); } break; } return hr; } CAdviseClient::CAdviseClient() : _hProcess(NULL), _hThread(NULL), _pfct(NULL) {} CAdviseClient::~CAdviseClient() { _Cleanup(); } // static HRESULT CAdviseClient::Create(CNamedElem** ppelem) { HRESULT hr = S_OK; *ppelem = new CAdviseClient(); if (!(*ppelem)) { hr = E_OUTOFMEMORY; } return hr; }
f2ed5a203df31ad91dd08bd49f12650408dece15
0916323d0197c6032f5971b86b5a24d3bc13678f
/VE3OOI_AD9850_Controller_v1.0/AD9850_v1.cpp
558c040ecc629f82ddcfbf5e27215a1bdbbde866
[ "Apache-2.0" ]
permissive
drajnauth/AD9850_Jack-Knife
e6dbc211274d1968ffccf55f9c1350006dc12087
2512d5566117b5223afbb55dea92825e1e6422f0
refs/heads/master
2017-12-06T11:26:38.992636
2017-11-27T04:35:11
2017-11-27T04:35:11
112,143,998
0
1
null
null
null
null
UTF-8
C++
false
false
7,811
cpp
AD9850_v1.cpp
/* These routines are used to configure and control the AD9850 Module which includes a crystal clock that drives the DDS The AD9850 datasheet describes how to communicate with the AD9850 DDS chip. The module does not change this information. The following pins are used to control/configure the AD9850 chip (regardless of module) FQ_UD: Frequency Update. On the rising edge of this clock, the DDS updates to the frequency (or phase) loaded in the data input register; it then resets the pointer to Word 0ncy/phase/control words. W_CLK: Word Load Clock. This clock is used to load the parallel or serial frequency/phase/control words. DATA (on module) or D7 (chip) D7 (Pin 25) is part of parallel data load or serves as the input data pin for serial communications RESET: This is the master reset function; when set high, it clears all registers (except the input register), and the DAC output goes to cosine 0 after additional clock cycles The AD9850 expects a 40 bin frame which is made of a 32 bit frequency tuning word and 8 bit control word. Bits W0 to W31 Tuning Word (W0 LSB, W31 MSB) Bits W32 to W39 Control Tuning_Word = Fout x 2^32 / CLOCK Conrol Word W32 - Reserved must be 0 W33 - Reserved must be 0 W34 - Power up/Power down, 0=Power Up, 1=Power down W35 - Phase LSB W36 - Phase W37 - Phase W38 - Phase W39 - Phase MSB e.g. Power Down control word i.e. 00100000 = 0x20 Here are the steps to configure the AD9850. 1) Reset the chip by pulsing the RESET line (i.e. pulse is rising and falling edge of pin). For 125 Mhz module no delay requried between rising edge and falling edge 2) Set the chip in serial communicaiton mode. Drop the DATA to 0 then Pulse W_CLK and then pulse FQ_UD. No delay required 3) Calculate the frequecy tuning word using the above formula 4) Shift out 32 bits of the tuning work using LSB first. This means set DATA base on value of the bit being transmitted then pulse the W_CLK line to indicated a bit is present 5) Shift out 8 bits of the control word. For normal operation this should be 0. Note the high order 2 bits MUST be 0. */ #include "Arduino.h" #include <stdint.h> #include <avr/eeprom.h> // Needed for storeing calibration to Arduino EEPROM #include "UART.h" // VE3OOI Serial Interface Routines (TTY Commands) #include "AD9850_v1.h" // VE3OOI AD9850 Routines #include "AD9850_Controller.h" // Defines for this program AD9850_def ad9850params; void DDS60Setup (void) { pinMode (_DATA, OUTPUT); // sets pin 10 as OUPUT pinMode (_W_CLK, OUTPUT); // sets pin 9 as OUTPUT pinMode (_FQ_UD, OUTPUT); // sets pin 8 as OUTPUT pinMode (_RESET, OUTPUT); pinMode (LED, OUTPUT); } void ADInit ( void ) { // Drop All Lines to 0 digitalWrite(_RESET, LOW); digitalWrite(_W_CLK, LOW); digitalWrite(_FQ_UD, LOW); digitalWrite(_DATA, LOW); // Pulse RESET for 5 CLKIN (Cycles i.e. 5x 1/125Mhz ~ 40ns) PulseAD9850Pin(_RESET); // Set to serial mode. Need rising edge of _W_CLK followed by rising edge of _FQ_UD PulseAD9850Pin(_W_CLK); // Pulse _W_CLK PulseAD9850Pin(_FQ_UD); // Pulse _FQ_UD } void SetFrequency(unsigned long frequency) { unsigned long ulongword; double temp; temp = (frequency * 0x100000000); temp /= ad9850params.CorrectedClock; ulongword = (unsigned long) temp; SendDataFrame (ulongword, 0); } void SetFrequencyPhase(unsigned long frequency, unsigned char phase) { /* case %00000 PHASE_WORD = " 0" case %00001 PHASE_WORD = " 11.25" case %00010 PHASE_WORD = " 22.5" case %00011 PHASE_WORD = " 33.75" case %00100 PHASE_WORD = " 45" case %00101 PHASE_WORD = " 56.25" case %00110 PHASE_WORD = " 67.5" case %00111 PHASE_WORD = " 78.75" case %01000 PHASE_WORD = " 90" case %01001 PHASE_WORD = "101.25" case %01010 PHASE_WORD = " 112.5" case %01011 PHASE_WORD = "123.75" case %01100 PHASE_WORD = " 135" case %01101 PHASE_WORD = "146.25" case %01110 PHASE_WORD = " 157.5" case %01111 PHASE_WORD = "168.75" case %10000 PHASE_WORD = " 180" case %10001 PHASE_WORD = "191.25" case %10010 PHASE_WORD = " 202.5" case %10011 PHASE_WORD = "213.75" case %10100 PHASE_WORD = " 225" case %10101 PHASE_WORD = "236.25" case %10110 PHASE_WORD = " 247.5" case %10111 PHASE_WORD = "258.75" case %11000 PHASE_WORD = " 270" case %11001 PHASE_WORD = "281.25" case %11010 PHASE_WORD = " 292.5" case %11011 PHASE_WORD = "303.75" case %11100 PHASE_WORD = " 315" case %11101 PHASE_WORD = "326.25" case %11110 PHASE_WORD = " 337.5" case %11111 PHASE_WORD = "348.75" */ unsigned long ulongword; double temp; temp = (frequency * 0x100000000); temp /= ad9850params.CorrectedClock; ulongword = (unsigned long) temp; // Pulse RESET for 5 CLKIN (Cycles i.e. 5x 1/125Mhz ~ 40ns) SendDataFrame (ulongword, phase); } /* The device also provides five bits of digitally controlled phase modulation, which enables phase shifting of its output in increments of 180°, 90°, 45°, 22.5°, 11.25° 0x01 180° 0x02 90° 0x04 45° 0x14 60° 0x1A 120° */ unsigned char SwapPhaseBits (unsigned char phasein) // This routines swaps bits in phase word so that LSB becomes MSB { unsigned int i; unsigned char phaseout; phaseout = phasein; phaseout &= 0xE0; for (i=0; i<5 ; i++) { if (phasein & 0x1) { phaseout |= 1<<(4-i); } phasein >>= 1; } return phaseout; } void SendDataFrame (unsigned long tword, unsigned char cword) { // Shift out tuning word LSB first ShiftOut ( (unsigned char)(tword & 0xFF)); tword >>= 8; ShiftOut ( (unsigned char)(tword & 0xFF)); tword >>= 8; ShiftOut ( (unsigned char)(tword & 0xFF)); tword >>= 8; ShiftOut ( (unsigned char)(tword & 0xFF)); // Send Control Word MSB first, ie left shift // But need to swap bits of phase because Phase bits shifted LSB first cword = SwapPhaseBits (cword); ShiftOutMSB ( cword ); // Normally this is zero, for power up and phase 0 // Tell AD9850 to Load 40 bits just transferred by pulsing FQ_UD digitalWrite(_DATA, LOW); PulseAD9850Pin(_FQ_UD); } void ShiftOut ( unsigned char value ) // Shift LSB out first (right shift) { unsigned char i; for (i=0; i<8; i++) { if (value & 0x1) { digitalWrite(_DATA, HIGH); } else { digitalWrite(_DATA, LOW); } PulseAD9850Pin(_W_CLK); // Indicate bin ready on Data pin to read value >>= 1; } } void ShiftOutMSB ( unsigned char value ) // Shift MSB out first (left shift) { unsigned char i; for (i=0; i<8; i++) { if (value & 0x80) { digitalWrite(_DATA, HIGH); } else { digitalWrite(_DATA, LOW); } PulseAD9850Pin(_W_CLK); // Indicate bin ready on Data pin to read value <<= 1; } } void PulseAD9850Pin (unsigned char ppin) // Generate a rising and falling edge for a pin { digitalWrite(ppin, LOW); digitalWrite(ppin, HIGH); digitalWrite(ppin, LOW); } void PowerDown (void) // This routine does a power down on the module { // Setup for serial Load digitalWrite(_DATA, LOW); // Set to serial mode. Need rising edge of _W_CLK followed by rising edge of _FQ_UD PulseAD9850Pin(_W_CLK); // Pulse _W_CLK PulseAD9850Pin(_FQ_UD); // Pulse _FQ_UD // don't need to send frequency tuning work...powering down ShiftOut ( 0 ); ShiftOut ( 0 ); ShiftOut ( 0 ); ShiftOut ( 0 ); // Send Control Word // Power Down control word is 00100000 = 0x20 ShiftOut ( POWERDOWN_CONTROL_WORD ); // Send power down control work digitalWrite(_DATA, LOW); PulseAD9850Pin(_FQ_UD); }
6027a7eb8c59bb29c0e2f982c26860f9ada6dd2a
2c97fc62eab1f78c4a5d1a83826a75209ebb6d39
/1比赛题目/edu codeforces round 51/B.cpp
19946d2af7e35b7424903c8b38314c96f46301ff
[]
no_license
GaisaiYuno/My-OI-Code-1
f32932f1004e593ffee0b0e97cffd25d9e2851bf
c57ec4e2aaa1d770ee9490a42710d1cf71a153f2
refs/heads/master
2020-12-31T23:13:46.913582
2020-02-08T01:09:46
2020-02-08T01:09:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
B.cpp
#include<iostream> #include<cstdio> #define maxn 300005 using namespace std; long long l,r; long long a[maxn]; int main(){ scanf("%I64d %I64d",&l,&r); for(long long i=l;i<=r;i++){ a[i-l+1]=i; } printf("YES\n"); for(int i=1;i<=r-l+1;i+=2){ printf("%I64d %I64d\n",a[i],a[i+1]); } }
6fc9688c786127acc207e5e63e207116690d4e76
b20408e6f916aa08785b7cd331e3fc7bff24369b
/src/InverseMouseArea.h
0d19e0f1b7b07ee0fc855558a72a4048301681d4
[ "MIT" ]
permissive
ethereum/mix
305c981fa0cda867ba875a35ac2a131baec407f7
b2f4994d63015ad3386281d51e36771492c5aca5
refs/heads/develop
2023-08-31T10:57:24.332834
2016-08-11T15:26:37
2016-08-11T15:26:37
40,892,643
214
255
null
2016-08-11T15:26:37
2015-08-17T12:24:30
JavaScript
UTF-8
C++
false
false
1,427
h
InverseMouseArea.h
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file InverseMouseArea.h * @author Yann yann@ethdev.com * @date 2015 * Ethereum IDE client. */ #pragma once #include <QQuickWindow> #include <QQuickItem> namespace dev { namespace mix { class InverseMouseArea: public QQuickItem { Q_OBJECT Q_PROPERTY(bool active MEMBER m_active WRITE setActive) public: InverseMouseArea(QQuickItem* _parent = 0): QQuickItem(_parent) {} ~InverseMouseArea() { if (window()) { window()->removeEventFilter(this); } } void setActive(bool _v); protected: void itemChange(ItemChange _c, const ItemChangeData& _v) override; bool eventFilter(QObject* _obj, QEvent *_ev) override; bool contains(const QPointF& _point) const override; private: bool m_active; signals: void clickedOutside(QPointF _point); }; } }
1cfeefa4f1549ee5759a5987bad4056d75e4a019
3b0e3159e3327ffe1e025febe149ee67648cdcef
/2.cpp
a3f3a2c83407905a8ef65f4eccb0335dd5646e81
[]
no_license
LeezhiWen/NETEASE_ProgrammingTest-2017-autumn
16d65dd3530ab99aa43dc4ddb508d4eb554cc97c
c9ad929ad52c1673bf7d7315a0b147564bdb112a
refs/heads/master
2021-01-18T13:16:38.801022
2017-08-15T14:15:04
2017-08-15T14:15:04
100,373,682
1
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
2.cpp
#include<iostream> #include<string.h> using namespace std; int main() { char s[50]; cin >> s; int len = strlen(s), j = 0; int maxnum = 0, num = 0, block[50] = { 0 }; if (len == 1) maxnum = 1; else { for (int i = 0; i<len-1; i++) { if ( s[i] != s[i+1]) num++; else { if (num != 0) { block[j++] = num+1; num = 0; } } } maxnum = num+1; for (int k = 0; k<50; k++) { if (block[k]>maxnum) maxnum = block[k]; } } cout << maxnum; return 0; }
e5cb990a19ab040090c5f65bf9ad1bd118787cb4
fdbfbcf4d6a0ef6f3c1b600e7b8037eed0f03f9e
/systems/primitives/test/vector_log_test.cc
aa68de58f447c36ed598b66706eb22f7d7f39746
[ "BSD-3-Clause" ]
permissive
RobotLocomotion/drake
4529c397f8424145623dd70665531b5e246749a0
3905758e8e99b0f2332461b1cb630907245e0572
refs/heads/master
2023-08-30T21:45:12.782437
2023-08-30T15:59:07
2023-08-30T15:59:07
16,256,144
2,904
1,270
NOASSERTION
2023-09-14T20:51:30
2014-01-26T16:11:05
C++
UTF-8
C++
false
false
1,842
cc
vector_log_test.cc
#include "drake/systems/primitives/vector_log.h" #include <gtest/gtest.h> #include "drake/common/default_scalars.h" namespace drake { namespace systems { namespace { template <typename T> class VectorLogFixture : public testing::Test { protected: static constexpr int64_t kDefaultCapacity = VectorLog<T>::kDefaultCapacity; VectorLog<T> log_{3}; VectorX<T> record_{Vector3<T>{1.1, 2.2, 3.3}}; }; using ScalarTypes = ::testing::Types<double, AutoDiffXd, symbolic::Expression>; TYPED_TEST_SUITE(VectorLogFixture, ScalarTypes); TYPED_TEST(VectorLogFixture, Basics) { auto& log = this->log_; auto& record = this->record_; EXPECT_EQ(log.get_input_size(), 3); EXPECT_EQ(log.num_samples(), 0); log.AddData(0.001, record); EXPECT_EQ(log.num_samples(), 1); EXPECT_EQ(log.sample_times()[0], 0.001); EXPECT_EQ(log.data()(0, 0), 1.1); EXPECT_EQ(log.data()(1, 0), 2.2); EXPECT_EQ(log.data()(2, 0), 3.3); log.Clear(); EXPECT_EQ(log.num_samples(), 0); } TYPED_TEST(VectorLogFixture, Move) { auto& log = this->log_; auto& record = this->record_; log.AddData(0.001, record); EXPECT_EQ(log.num_samples(), 1); auto other_log = std::move(log); EXPECT_EQ(other_log.num_samples(), 1); // The moved-from log becomes empty. EXPECT_EQ(log.num_samples(), 0); } TYPED_TEST(VectorLogFixture, GrowLog) { auto& log = this->log_; auto& record = this->record_; auto goal_size = 1 + this->kDefaultCapacity; for (int k = 0; k < goal_size; k++) { log.AddData(0.001 + k, record); } EXPECT_EQ(log.num_samples(), goal_size); EXPECT_EQ(log.sample_times()[goal_size - 1], 0.001 + goal_size - 1); EXPECT_EQ(log.data()(0, goal_size - 1), 1.1); EXPECT_EQ(log.data()(1, goal_size - 1), 2.2); EXPECT_EQ(log.data()(2, goal_size - 1), 3.3); } } // namespace } // namespace systems } // namespace drake
4dac6c6e3589b2f13a61056fefd93f1f6a5c2998
dceeae4b5d254744ac2293f905ed7ddff186722b
/Code_Cpp/Cpp_Single/chapter-8/ConstReturnValues.cpp
a71cc2a0ea1677436164983f9cceb2776765fe39
[]
no_license
robot007num/Cpp_Study
3694a8bc8e2cbe8a45d1047727d3c7098b1dc2e4
ef3d754cb752ae4b5b50ccfe4557e8909f924f40
refs/heads/master
2023-07-08T18:42:50.000301
2021-08-09T03:51:57
2021-08-09T03:51:57
390,266,532
0
0
null
null
null
null
UTF-8
C++
false
false
372
cpp
ConstReturnValues.cpp
//Const return by value //Result cannot be used as an lvalue class X { private: int i_; public: X(int ii = 0); void modify(); }; X::X(int ii) { i_ = ii;} void X::modify() { i_++;} X f5() { return X();} const X f6() { return X();} void f7(X&x) { x.modify();} int main01() { f5() = X(1); // ok -- non-const return value f5().modify(); //ok }
89086a371d8d8fffedfe0b29ca646082c50438a9
c4eaa3e6cdca0ef6eea9487735369fb4d215949f
/2DAE07_Geers_Pieter_digdug/Minigin/TextureRenderComponent.cpp
33e88722464688d8ed7670083b51fc41be4c31d1
[]
no_license
PieterGeers/DigDug
483fc09f6425501aea7e690831517d695c56bea2
b69e05ca025558a089d1d10bda1ee01677292a54
refs/heads/master
2022-02-26T02:42:53.016532
2019-10-31T15:37:02
2019-10-31T15:37:02
175,878,736
0
0
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
TextureRenderComponent.cpp
#include "MiniginPCH.h" #include "TextureRenderComponent.h" #include "ResourceManager.h" #include "Renderer.h" #include "GameTime.h" TextureRenderComponent::TextureRenderComponent(const std::shared_ptr<dae::Texture2D>& text) : m_IsSprite(false) , m_Texture(std::move(text)) { } TextureRenderComponent::TextureRenderComponent(std::string path, int scale) :m_IsSprite(false) ,m_Scale(scale) { m_Texture = dae::ResourceManager::GetInstance().LoadTexture(path); } TextureRenderComponent::TextureRenderComponent(std::string path, int tRows, int tColumns, int scale) : m_IsSprite(true) , m_Scale(scale) { m_Rows = tRows; m_Columns = tColumns; m_Texture = dae::ResourceManager::GetInstance().LoadTexture(path); } void TextureRenderComponent::Update() { if (m_IsSprite) { m_Acctime += dae::GameTime::GetInstance().DeltaT(); if (m_Acctime > 0.2f) { m_Acctime -= 0.2f; ++m_CurrentColumn; if (m_CurrentColumn > m_StartColumn + m_ColumnOffset) { m_CurrentColumn = m_StartColumn; if (m_RowOffset > 0) { ++m_CurrentRow; if (m_CurrentRow > m_StartRow + m_RowOffset) { m_CurrentRow = m_StartRow; } } } } } } void TextureRenderComponent::FixedUpdate() { } void TextureRenderComponent::Render() { if (!m_StopRender && m_Texture != nullptr) { if (!m_IsSprite) dae::Renderer::GetInstance().RenderTexture(*m_Texture, SDL_Rect{ int(m_X), int(m_Y), m_Texture->GetWidth()* m_Scale, m_Texture->GetHeight()*m_Scale }, m_Angle, SDL_Point{(m_Texture->GetWidth() / 2) * m_Scale, (m_Texture->GetHeight() / 2)*m_Scale}); else if (m_IsSprite) dae::Renderer::GetInstance().RenderTexture(*m_Texture, SDL_Rect{ int(m_X), int(m_Y), m_Texture->GetWidth() / m_Columns * m_Scale, m_Texture->GetHeight() / m_Rows * m_Scale }, SDL_Rect{ m_CurrentColumn*(m_Texture->GetWidth() / m_Columns), m_CurrentRow*(m_Texture->GetHeight() / m_Rows), m_Texture->GetWidth() / m_Columns , m_Texture->GetHeight() / m_Rows }, 0, SDL_Point{0,0}); } } void TextureRenderComponent::SetTransform(float x, float y, float) { m_X = x; m_Y = y; } void TextureRenderComponent::SetSpritePosition(Animation info) { if (m_ActiveAnimation == info.name) return; m_ActiveAnimation = info.name; m_CurrentRow = info.info.startRow; m_CurrentColumn = info.info.startColumn; m_ColumnOffset = info.info.ColumnOffset; m_RowOffset = info.info.RowOffset; m_StartColumn = info.info.startColumn; m_StartRow = info.info.startRow; } void TextureRenderComponent::SetSpritePosition(unsigned startRow, unsigned startColumn, unsigned rowOffset, unsigned columnOffset) { m_CurrentRow = startRow; m_CurrentColumn = startColumn; m_ColumnOffset = columnOffset; m_RowOffset = rowOffset; m_StartColumn = startColumn; m_StartRow = startRow; }
5144f794db88d180f7508a46d570b1f052f370b5
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/a7/d94bb5ec9750fa/main.cpp
55a3a649c4d8dca237fb4f7a474b5273ea8cef99
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
408
cpp
main.cpp
#include <cstdlib> #include <iostream> int simpleMemLeak() { //dynamic memory allocation int* pint = new int; //assign value by dereference *pint = 10; //return value by dereference //allocated memory is lost in every function call return *pint; } int main() { //it will cause bad_alloc exception because of memory leaks for (int i = 0; i < 100000; i++) simpleMemLeak(); system("pause"); }
499d575fb802cee1f2d4207977a0cde75e04f3e3
7b8a91034de5176cd851cd32f02101e020944ed8
/SoftwareTriangleRasterizer/MathStuff.h
8031583155b9e3b4e18ee86b894f7d80261fa03b
[]
no_license
LouisMayor/SoftwareRasterizer
ee1186e5d378e7e4ffce2b5311f8ea9154edecc5
8c86b6150dba943eb42c341a2140a5d6a4ab2e32
refs/heads/master
2020-03-20T02:11:55.831961
2018-07-10T19:10:21
2018-07-10T19:10:21
137,103,072
0
0
null
null
null
null
UTF-8
C++
false
false
375
h
MathStuff.h
#pragma once #define _USE_MATH_DEFINES #include <math.h> #include <cfloat> namespace math { static constexpr double _pi = M_PI; static constexpr float _epsilon = FLT_EPSILON; inline float radians_to_degrees( const float& _rads ) { return (_rads * 180.0f) / _pi; } inline float degrees_to_radians( const float& _degrees ) { return (_degrees * _pi) / 180.0f; } }
fa48b960b76ca6cf30d767872324546e6736b249
213fa55d526ffa2c70c6230e9f93d73a2fa806ed
/Stereoscopic_3D_Vita/Build/CourseWork/main.cpp
658948ff4859922538dd06c4c10b7d4c0a1618be
[]
no_license
petmac/CourseWork
7987ba17493ea4a97f022a7bdc4a7552eeafb106
48df4f5467680cb893c8249a6e7364690015e594
refs/heads/master
2020-03-12T00:36:40.735555
2015-06-03T13:48:26
2015-06-03T13:48:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
main.cpp
#include <system/d3d11/platform_d3d11.h> #include "s3d.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow) { // initialisation abfw::PlatformD3D11 platform(hInstance, 960, 544, false, true); S3D myApp(platform); myApp.Run(); return 0; }
687f1f5f8e4a30e06f2fe638097e543904944621
93d1fb0f9b13abc322935befb9c3fe43c6ff245e
/Towerdefense/paint/mybutton.cpp
c4ce021e83df42dcf191dca08369955c025c96cb
[]
no_license
ZizhenWei/TowerGame
780042decfb28b681cefd64de22168265be3f17b
74db224fb1674a697756e59af6b48bffebdef17c
refs/heads/master
2022-11-09T14:39:24.721731
2020-06-28T13:37:39
2020-06-28T13:37:39
269,600,113
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
mybutton.cpp
#include "mybutton.h" #include <QPixmap> #include <QBitmap> MyButton::MyButton(QString pix) : QPushButton (0){ QPixmap pixmap(pix); // pixmap.fill(QColor(0,0,0,0)); pixmap.setMask(pixmap.mask()); this->setFixedSize(pixmap.width(),pixmap.height()); this->setStyleSheet("QPushButton{border.Opx;}"); this->setIcon(pixmap); this->setIconSize(QSize(pixmap.width(),pixmap.height())); }
34ca611b270bc09e11e26a786d1b3dcc61f1721e
8a1f5a8d6b603042e52a10f4153b3d5d3c696867
/sources/source.cpp
1a7388ed943957705972570f73b372716531df31
[ "MIT" ]
permissive
kirill050/lab-03-shared-ptr
cad4d8b5387fb84b49be49e395bf3ac7292356d1
ffd239ff95c23ee96d1c59cc97a682bd8bc9f291
refs/heads/master
2020-10-01T20:36:13.773848
2019-12-20T14:09:43
2019-12-20T14:09:43
227,620,657
0
2
null
null
null
null
UTF-8
C++
false
false
61
cpp
source.cpp
// Copyright 2019 Kirill <your_email> #include <header.hpp>
500962b3aa2474e39ae9c4419cafce64b88cd22b
9dcfb99b63845a99b8823dd6c72e3933f4b95a27
/BigMod.cpp
b7096ef4f7a34418f13d5963082268f0c42712cb
[]
no_license
ismail102/Algorithm
a2e5983d2e3d65c57f5f44f82df2fced853f16ad
1a8f36dad284b384b44b0ff623a746060a81d5f1
refs/heads/master
2020-03-25T19:03:18.049868
2019-10-24T20:38:45
2019-10-24T20:38:45
144,062,362
0
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
BigMod.cpp
/// Author: Ismail Hossain(Mukul) /// Univarsity: Chittagong University of Engineering Annd Technology(Bangladesh) /// Uva:ISMAIL_HOSSAIN /// Codeforces: ISMAIL_HOSSAIN /// SPOJ:ismail_102 /// HackerRank: ismail_102 /// csacademy: ISMAIL_HOSSAIN /// Facebook: Smily Mukul //BISMILLAHIR RAHMANIR RAHIM #include<bits/stdc++.h> #define sf scanf #define pf print #define dd double #define fr first #define sc second #define pb push_back #define MP make_pair #define ll long long #define PI acos(-1.0) #define vci vector<ll> #define pll pair<ll, ll> #define vcc vector<char> #define sz(a) (a.size()) #define pii pair<int, int> #define vcs vector<string> #define read(a) scanf("%d",&a) #define readI1(a) scanf("%I64d",&a) #define read2(a,b) scanf("%d%d",&a,&b) #define FOR(i, s, e) for(ll i=s; i<e; i++) #define read3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define readI2(a,b) scanf("%I64d %I64d",&a,&b) #define mem(a, b) memset(ara, value, sizeof(ara)) #define readI3(a,b,C) scanf("%I64d %I64d %I64d",&a,&b,&c) #define open() freopen("input.txt", "r", stdin) #define show() freopen("output.txt", "w", stdout) #define one(a) __biltin_popcount(a) #define Max 2000+5 #define inf INFINITY using namespace std; const ll Mod = 10000007; ull bigmod ( ull a, ull p ) { if ( p == 0 )return (ull)1; if ( p % 2 ){ return ( ( a % Mod ) * ( bigmod ( a, p - 1 ) ) ) % Mod; } else{ ull c = bigmod ( a, p / 2); return ( (c%Mod) * (c%Mod) ) % Mod; } }
dd054f7e1109064de825caebac2c95b9ab248e8d
f96ce3c28e5bf6ffa4e3301f090f30d6be912365
/ListiniSet.cpp
e71bb2ba63723628845f7ee196cf22e2fc312751
[]
no_license
simonecalamai/WinSigma
2d210f5ab04c6d4005e4dff66380133e8db53039
2aa40830103e64efba736576601480debc57da97
refs/heads/master
2021-07-15T05:15:43.610892
2021-03-09T12:27:20
2021-03-09T12:27:20
54,917,808
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
cpp
ListiniSet.cpp
// ListiniSet.cpp : implementation file // #include "stdafx.h" #include "winsigma.h" #include "ListiniSet.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CListiniSet IMPLEMENT_DYNAMIC(CListiniSet, CRecordset) CListiniSet::CListiniSet(CDatabase* pdb) : CRecordset(pdb) { //{{AFX_FIELD_INIT(CListiniSet) m_Codice = 0; m_Azienda = 0; m_Autore = _T(""); m_Nome = _T(""); m_nFields = 7; m_Inizio = 0; m_Fine = 0; m_CertOgniSerie = TRUE; //}}AFX_FIELD_INIT m_nDefaultType = snapshot; } CString CListiniSet::GetDefaultConnect() { return ((CWinSigmaApp*)AfxGetApp())->m_csDefaultConnect; } CString CListiniSet::GetDefaultSQL() { return _T("[LISTINI]"); } void CListiniSet::DoFieldExchange(CFieldExchange* pFX) { //{{AFX_FIELD_MAP(CListiniSet) pFX->SetFieldType(CFieldExchange::outputColumn); RFX_Long(pFX, _T("[Codice]"), m_Codice); RFX_Long(pFX, _T("[Azienda]"), m_Azienda); RFX_Text(pFX, _T("[Autore]"), m_Autore); RFX_Date(pFX, _T("[Fine]"), m_Fine); RFX_Date(pFX, _T("[Inizio]"), m_Inizio); RFX_Text(pFX, _T("[Nome]"), m_Nome); RFX_Byte(pFX, _T("[CertOgniSerie]"), m_CertOgniSerie); //}}AFX_FIELD_MAP } ///////////////////////////////////////////////////////////////////////////// // CListiniSet diagnostics #ifdef _DEBUG void CListiniSet::AssertValid() const { CRecordset::AssertValid(); } void CListiniSet::Dump(CDumpContext& dc) const { CRecordset::Dump(dc); } #endif //_DEBUG
4299ccf607899a1524727b3d5c7b2aab0f14ffe2
e5c4cc27ac9f80341990714d4401e6568cb85a6d
/Source/RibRenderLib/include/RRL_Net_RenderBucketsServer.h
ff88e8cdb3e4de3a6e86e7ae0e40bc4eb686d225
[ "BSD-3-Clause" ]
permissive
wubugui/RibTools
42f606ef6963a62a6539da9fc4b5c84c0d158043
fd917920069ab73d6fa4091cb32b9e3ca6a81494
refs/heads/master
2020-12-26T01:12:07.895683
2014-05-22T06:51:28
2014-05-22T06:51:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
h
RRL_Net_RenderBucketsServer.h
//================================================================== /// RRL_Net_RenderBucketsServer.h /// /// Created by Davide Pasca - 2009/8/6 /// See the file "license.txt" that comes with this project for /// copyright info. //================================================================== #ifndef RRL_NET_RENDERBUCKETSSERVER_H #define RRL_NET_RENDERBUCKETSSERVER_H #include "DSystem/include/DTypes.h" #include "DSystem/include/DNetwork.h" #include "DSystem/include/DUtils.h" #include "RI_System/include/RI_Framework.h" #include "RRL_Net.h" //================================================================== namespace RRL { //================================================================== namespace NET { //================================================================== /// RenderBucketsServer //================================================================== class RenderBucketsServer : public RI::RenderBucketsBase { DNET::PacketManager *mpPakMan; public: RenderBucketsServer( DNET::PacketManager &pakMan ); void Render( RI::Hider &hider ); private: void rendBucketsRange( RI::Hider &hider, int buckRangeX1, int buckRangeX2 ); void sendBucketsData( RI::Hider &hider, int buckRangeX1, int buckRangeX2 ); }; //================================================================== } //================================================================== } #endif
aa8563ce22d64ddd56172b859e023729e5e7fd93
72ee22c4cfbb7f011cb88e8f96cc8c7da4a707f5
/phonelog queue.cpp
99d03748818747155ba276d5f550b820bf4351bc
[]
no_license
tmoynandy/DataStructure-C
51500d7d97f9b85a754600de4a0645e81f1e3274
4f69234613e2063aed3da8d35c75f4eae2718016
refs/heads/master
2023-08-15T08:47:07.312566
2021-10-03T05:46:53
2021-10-03T05:46:53
100,859,637
1
20
null
2022-04-03T22:07:37
2017-08-20T12:23:10
C
UTF-8
C++
false
false
1,521
cpp
phonelog queue.cpp
#include<iostream> #include<ctime> #include<cstdlib> using namespace std; struct Node { string data; string name; string t; struct Node *next; }; struct Node*front=NULL; struct Node *rear=NULL; void enqueue(string y,string w,string x) { struct Node *temp; temp=new Node; if(temp==NULL) cout<<"Queue is FUll\n"; else { temp->data=x; temp->name=y; temp->t=w; temp->next=NULL; if(front==NULL) front=rear=temp; else { rear->next=temp; rear=temp; } } } void dequeue() { struct Node* temp; if(front==NULL) cout<<"NO Call Log"; else { temp=front; front=front->next; free(temp); } } void display(Node *temp) { if (temp == NULL) return; display(temp->next); cout<<temp->name<<" "<<temp->data<<" "<<temp->t<<endl; cout<<endl; } int main() { int n,count =0; string x,w; string y; time_t now = time(0); do { cout<<"enter 1 for input"<<endl<<"enter 2 for output"<< endl<<"Enter 0 to exit"<<endl; cin>>n; switch(n) { case 1: if(count >=10) dequeue(); cout<<"Enter Name: "; cin>>x; cout<<"Enter Phone number :"; cin>>y; w = ctime(&now); enqueue(x,w,y); count++; break; case 2: if(count==0) cout<<"No Call Log"<<endl; cout<<"Name\t"<<"Phone number\t\t"<<"date and time"<<endl; display(front); break; } }while(n!=0); return 0; }
96b41a09a3e983aa63b7ab09b75fd8ff39dd1e6d
e371c4f4f5b1d4812fdbd50ab27eb767eba6faaf
/RayTracer - Rasterization/Cameras/PinHole.cpp
dd9077460f9497e2b7a2c8927cf04ca5a480caaa
[]
no_license
tsargs/Ray-tracer
ce01baba0e2175f25bec97d74a0681e2ebab7934
b069aa16fbf0e3d2a77bd42e589382dbae4d408c
refs/heads/master
2021-03-22T04:59:53.057456
2018-02-12T01:40:07
2018-02-12T01:40:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,088
cpp
PinHole.cpp
// ============================================================================= // // Created by Shyam Prathish Sargunam on 02/05/15. // Copyright © 2015 Shyam Prathish Sargunam. All rights reserved. // // ============================================================================= #include "PinHole.h" //Default Constructor PinHole::PinHole(void) { } PinHole::PinHole(World* worldPointer, const Point3D& eyePosition, const Point3D& lookAtPosition, const Vector3D& upVector, const float& distance, const float& rollAngle) { worldPtr = worldPointer; eyePos = eyePosition; lookAtPos = lookAtPosition; up = upVector; d = distance; roll = rollAngle; SetupOrthonormalBase(); } //Destructor PinHole::~PinHole(void) { } void PinHole::RenderScene(void) { std::cout << "PinHole::RenderScene"; World world = *worldPtr; ViewPlane viewPlane = worldPtr->viewPlane; Tracer *tracerPtr = worldPtr->tracerPtr; Ray ray; double rayX; double rayY; RGBColor currentPixelColor; Sampler *sampler = viewPlane.samplerPtr; Point2D samplePoint; ray.origin = Point3D(eyePos.x, eyePos.y, eyePos.z); for (int i = 0; i < viewPlane.height; i++) { for (int j = 0; j < viewPlane.width; j++) { currentPixelColor = black; for (int k = 0; k < viewPlane.samplesPerPixel; k++) { samplePoint = sampler->FetchSample(); rayY = (i * viewPlane.pixelSize) + samplePoint.y - (viewPlane.pixelSize * viewPlane.height * 0.5); rayX = ((j * viewPlane.pixelSize) + samplePoint.x - (viewPlane.pixelSize * viewPlane.width * 0.5)); ray.rayDirection = Vector3D(u*rayX + v*rayY - w*d).UnitVector(); // negative sign for w*d is because w is pointing the opposite direction currentPixelColor += tracerPtr->TraceRay(ray, 0); } int index = ((i * (viewPlane.width)) + (j)) * 3; world.pixmap[index] = (currentPixelColor.r * 255) / viewPlane.samplesPerPixel; world.pixmap[++index] = (currentPixelColor.g * 255) / viewPlane.samplesPerPixel; world.pixmap[++index] = (currentPixelColor.b * 255) / viewPlane.samplesPerPixel; } } std::cout << "End of pixels\n"; }
5469017660a1bde0faf3edaccd4549bcb576d6c8
29f98a758c63c30afba852f52921f08f0d705258
/src/shared/flags.cc
892e4de9433a5afff6c1e993b255ea56236c30a1
[ "BSD-3-Clause" ]
permissive
lukechurch/fletch
ff4ba589d73efb6e653559de7579206d20c6e551
f3e1769d3ac26900e7e15028d07bb1211ff30ff6
refs/heads/master
2021-01-22T12:17:23.618221
2015-06-28T07:08:49
2015-06-28T07:08:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,976
cc
flags.cc
// Copyright (c) 2014, the Fletch project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE.md file. #include "src/shared/flags.h" #include <string.h> #include <stdlib.h> #include <stdio.h> namespace fletch { #ifdef DEBUG #define MATERIALIZE_DEBUG_FLAG(type, prefix, name, value, doc) \ type Flags::name = value; #else #define MATERIALIZE_DEBUG_FLAG(type, prefix, name, value, doc) \ /* Do nothing. */ #endif #define MATERIALIZE_RELEASE_FLAG(type, prefix, name, value, doc) \ type Flags::name = value; APPLY_TO_FLAGS(MATERIALIZE_DEBUG_FLAG, MATERIALIZE_RELEASE_FLAG) char* Flags::executable_ = NULL; // Tells whether the given string is a valid flag argument. static bool IsValidFlag(const char* argument) { return (strncmp(argument, "-X", 2) == 0) && (strlen(argument) > 2); } static void PrintFlagBoolean(const char* name, bool value, bool init, const char* doc) { printf(" - bool %s = %s\n", name, value ? "true" : "false"); } static void PrintFlagInteger(const char* name, int value, int init, const char* doc) { printf(" - int %s = %d\n", name, value); } static void PrintFlagString(const char* name, const char* value, const char* init, const char* doc) { printf(" - char* %s = \"%s\"\n", name, value); } #define XSTR(n) #n #ifdef DEBUG #define PRINT_DEBUG_FLAG(type, prefix, name, value, doc) \ PrintFlag##prefix(XSTR(name), Flags::name, value, doc); #else #define PRINT_DEBUG_FLAG(type, prefix, name, value, doc) \ /* Do nothing. */ #endif #define PRINT_RELEASE_FLAG(type, prefix, name, value, doc) \ PrintFlag##prefix(XSTR(name), Flags::name, value, doc); static void PrintFlags() { printf("List of command line flags:\n"); APPLY_TO_FLAGS(PRINT_DEBUG_FLAG, PRINT_RELEASE_FLAG); // Terminate the process with error code. exit(-1); } static bool FlagMatches(const char* a, const char* b) { for (; *b != '\0'; a++, b++) { if ((*a != *b) && ((*a != '-') || (*b != '_'))) return false; } return (*a == '\0') || (*a == '='); } static bool ProcessFlagBoolean(const char* name_ptr, const char* value_ptr, const char* name, bool* field) { // -Xname if (value_ptr == NULL) { if (FlagMatches(name_ptr, name)) { *field = true; return true; } return false; } // -Xname=<boolean> if (FlagMatches(name_ptr, name)) { if (strcmp(value_ptr, "false") == 0) { *field = false; return true; } if (strcmp(value_ptr, "true") == 0) { *field = true; return true; } } return false; } static bool ProcessFlagInteger(const char* name_ptr, const char* value_ptr, const char* name, int* field) { // -Xname=<int> if (FlagMatches(name_ptr, name)) { char* end; int value = strtol(value_ptr, &end, 10); // NOLINT if (*end == '\0') { *field = value; return true; } } return false; } static bool ProcessFlagString(const char* name_ptr, const char* value_ptr, const char* name, const char** field) { // -Xname=<string> if (FlagMatches(name_ptr, name)) { *field = value_ptr; return true; } return false; } #ifdef DEBUG #define PROCESS_DEBUG_FLAG(type, prefix, name, value, doc) \ if (ProcessFlag##prefix(name_ptr, value_ptr, XSTR(name), &Flags::name)) \ return; #else #define PROCESS_DEBUG_FLAG(type, prefix, name, value, doc) \ /* Do nothing */ #endif #define PROCESS_RELEASE_FLAG(type, prefix, name, value, doc) \ if (ProcessFlag##prefix(name_ptr, value_ptr, XSTR(name), &Flags::name)) \ return; static void ProcessArgument(const char* argument) { ASSERT(IsValidFlag(argument)); const char* name_ptr = argument + 2; // skip "-X" const char* equals_ptr = strchr(name_ptr, '='); // Locate '=' const char* value_ptr = equals_ptr != NULL ? equals_ptr + 1 : NULL; APPLY_TO_FLAGS(PROCESS_DEBUG_FLAG, PROCESS_RELEASE_FLAG); printf("Failed to recognize flag argument: %s\n", argument); // Terminate the process with error code. exit(-1); } void Flags::ExtractFromCommandLine(int* argc, char** argv) { // Set the executable name. executable_ = argv[0]; // Compute number of provided flag arguments. int number_of_flags = 0; for (int index = 1; index < *argc; index++) { if (IsValidFlag(argv[index])) number_of_flags++; } if (number_of_flags == 0) return; // Process the the individual flags and shrink argc and argv. int count = 1; for (int index = 1; index < *argc; index++) { if (IsValidFlag(argv[index])) { ProcessArgument(argv[index]); } else { argv[count++] = argv[index]; } } *argc = count; if (Flags::print_flags) { PrintFlags(); // Process is terminated and will not return. } } } // namespace fletch
6b0e3b166d8b5615ada1b3e3132fcec85be1af4a
408b7c5c45d0e27e53a7dd9602088525abc3ef30
/prefix/PREFIX_Trie.cpp
8a9dc0d1454ab9f4eb3583c9b75b7343cef51076
[]
no_license
JMistral/Large_Scale_Data_Structure
1d0e22dd54307b1c03f5341076ee4990f55d53f6
93cc84f611d599476c626063748637f104fb76e5
refs/heads/master
2020-05-21T06:20:30.944050
2017-04-28T00:29:17
2017-04-28T00:29:17
84,587,572
0
0
null
null
null
null
UTF-8
C++
false
false
2,035
cpp
PREFIX_Trie.cpp
// // PREFIX_Trie.cpp // // // Created by Jiaming CHEN on 4/5/17. // // #include "PREFIX_Trie.hpp" #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #define MAXIMUM 5 using namespace std; int value(char g){ if (g == 'A'){ return 0; } else if (g == 'C'){ return 1; } else if (g == 'G'){ return 2; } else{ return 3; } } struct TrieNode{ TrieNode *Children[4]; bool isEnd; }; class Trie { public: TrieNode *root; Trie() { root = new TrieNode; } ~Trie() { TrieNode *temp; temp = root; for(int i=0;i<4;++i) { if(temp->Children[i]!=NULL) { delete(temp->Children[i]); } } delete(temp); } void insert(char *read,int n) { TrieNode *p = root; for(int i = 0; i < n; ++ i) { if(p -> Children[value(read[i])] == NULL){ p -> Children[value(read[i])] = new TrieNode; } p = p -> Children[value(read[i])]; } p -> isEnd = true; } bool search(char *key,int n) { TrieNode *p = find(key,n); return p != NULL && p -> isEnd; } private: TrieNode* find(char *key,int n) { TrieNode *p = root; for(int i = 0; i < n && p != NULL; ++ i) p = p -> Children[value(key[i])]; return p; } }; int main() { char **Head = (char**)malloc(MAXIMUM*sizeof(char*)); for(int i=0;i<MAXIMUM;i++){ Head[i] = (char*)malloc(5*sizeof(char)); } Head[0][0] = 'A'; Head[0][1] = 'C'; Head[0][2] = 'T'; Head[0][3] = 'G'; Head[0][4] = 'A'; Trie trie; trie.insert(Head[0],5); // trie.insert("ACTGT"); // trie.insert("ACTGG"); // trie.insert("ACTTA"); // trie.insert("ACTCC"); if(trie.search(Head[0],5)) { cout<<"Found"<<endl; } return 0; }
284cc5e3722ab3721554c71d5f21d13d016097e8
661b5874c1b132d632ee5278a39c61229116cf1b
/player.cpp
b4070ed0f6b3fa3f2f7fd98cb8398a45c6234685
[]
no_license
SilentSib/tictactoecpp
b7f96a37befbc13af0399526719d750a116abc2d
2e16c1460777f382c69a13c69e7f00efb59d535a
refs/heads/master
2020-04-23T11:10:09.633239
2019-02-17T13:46:05
2019-02-17T13:46:05
171,127,094
0
0
null
null
null
null
UTF-8
C++
false
false
108
cpp
player.cpp
#include "player.h" using namespace std; void Player::setPlayerName(string name) { playerName = name; }
1404482a4e58ebd198c20e43d5a96c6c78c33302
370188c6d1515da7d7784db002fd4c558678441a
/src/ShaderSourceBuilder.cpp
4cb287d5272e15d873b97ca2f77969b96fe4e4e0
[ "MIT" ]
permissive
fernandomv3/post3D
8dcd1b912bdc44783a8af7e85351e25e8d5f521c
f97e4e092f7e47a964d2420681e6c282e0dcb868
refs/heads/master
2021-01-22T11:38:08.183355
2015-09-04T17:13:03
2015-09-04T17:13:03
32,222,847
0
0
null
null
null
null
UTF-8
C++
false
false
13,320
cpp
ShaderSourceBuilder.cpp
#include "post3D/ShaderSourceBuilder.h" #include <fstream> #include <streambuf> #include <cerrno> namespace material{ ShaderSourceBuilder::ShaderSourceBuilder(){ this->attribute = { //inputs from vertex shader (attributes) {"normal","layout(location = 0)in vec3 normal;\n"}, {"position","layout(location = 1)in vec3 position;\n"}, {"uv","layout(location = 2)in vec2 uv;\n"}, {"tangent","layout(location = 3)in vec3 tangent;\n"}, //inputs from vertexShader to fragmentShader {"depthPosition", "#ifdef SHADOWMAP\n" "in vec4 depthPosition;\n" "#endif\n"}, {"vertexPosition","in vec4 vertexPosition;\n"}, {"vertexNormal", "in vec4 vertexNormal;\n"}, {"worldSpacePosition", "in vec4 worldSpacePosition;\n"}, {"vertexUV", "in vec2 vertexUV;\n"}, {"vertexTangent", "in vec4 vertexTangent;\n"} }; this->output ={ //output from vertex shader to fragment shader {"depthPosition", "#ifdef SHADOWMAP\n" "out vec4 depthPosition;\n" "#endif\n"}, {"vertexPosition","out vec4 vertexPosition;\n"}, {"vertexNormal", "out vec4 vertexNormal;\n"}, {"worldSpacePosition", "out vec4 worldSpacePosition;\n"}, {"vertexUV", "out vec2 vertexUV;\n"}, {"vertexTangent", "out vec4 vertexTangent;\n"}, //output to render targets {"color","layout(location = 0) out vec4 outputColor;\n"}, {"normal","layout(location = 1) out vec4 outputNormal;\n"}, {"position","layout(location = 2) out vec4 outputPosition;\n"}, {"uv","layout(location = 3) out vec4 outputUV;\n"}, {"depth", "#ifdef SHADOWMAP\n" "layout(location = 4)out vec4 depthPosition;\n" "#endif\n"} }; this->uniform ={ {"modelMatrix","uniform mat4 modelMatrix;\n"}, {"worldMatrix","uniform mat4 worldMatrix;\n"}, {"projectionMatrix","uniform mat4 projectionMatrix;\n"}, {"depthWorldMatrix", "#ifdef SHADOWMAP\n" "uniform mat4 depthWorldMatrix;\n" "#endif"}, {"material", "struct Material{\n" " vec4 diffuseColor;\n" " vec4 specularColor;\n" " float shininess;\n" "};\n" "uniform Material material;\n"}, {"dirLights", "#if MAX_DIR_LIGHTS > 0\n" "uniform vec4 dirLightColor[MAX_DIR_LIGHTS];\n" "uniform vec4 dirLightVectorToLight[MAX_DIR_LIGHTS];\n" "uniform float dirLightIntensity[MAX_DIR_LIGHTS];\n" "#endif\n"}, {"pLights", "#if MAX_P_LIGHTS > 0\n" "uniform vec4 pointLightColor[MAX_P_LIGHTS];\n" "uniform vec4 pointLightPosition[MAX_P_LIGHTS];\n" "uniform float pointLightIntensity[MAX_P_LIGHTS];\n" "uniform float pointLightAttenuation[MAX_P_LIGHTS];\n" "#endif\n"}, {"ambientLight","uniform vec4 ambientLight;\n"}, {"dirLight", "uniform vec4 dirLightColor;\n" "uniform vec4 dirLightVectorToLight;\n" "uniform float dirLightIntensity;\n"}, {"colorMap", "#ifdef MAP\n" "uniform sampler2D colorMap;\n" "#endif\n"}, {"normalMap", "#ifdef NORMALMAP\n" "uniform sampler2D normalMap;\n" "#endif\n"}, //texturemaps for deferred shading {"deferredPositionMap","uniform sampler2D positionMap;\n"}, {"deferredWorldPositionMap","uniform sampler2D worldPositionMap;\n"}, {"deferredColorMap","uniform sampler2D colorMap;\n"}, {"deferredNormalMap","uniform sampler2D normalMap;\n"}, {"deferredUvMap","uniform sampler2D uvMap;\n"}, {"maxLightIntensity","uniform float maxLightIntensity;\n"}, {"invGamma","uniform float invGamma;\n"}, {"shadowMap", "#ifdef SHADOWMAP\n" "uniform sampler2D shadowMap;\n" "#endif\n"}, {"PCFShadow", "#if defined(SHADOWMAP) && defined(PCFSHADOW)\n" "uniform vec2 shadowMapSize;\n" "uniform int sampleSize;\n" "#endif\n"}, {"screenSize","uniform vec2 screenSize;\n"} }; this->vertexChunk = { {"homogenizeVertex"," vec4 pos = vec4(position,1.0);\n"}, {"modelSpace"," vec4 modelSpace = modelMatrix * pos;\n"}, {"worldSpace"," vec4 worldSpace = worldMatrix * modelSpace;\n"}, {"nDCSpace"," vec4 nDCSpace = projectionMatrix * worldSpace;\n"}, {"gl_Position_h"," gl_Position = pos;\n"}, {"gl_Position_m"," gl_Position = modelSpace;\n"}, {"gl_Position_w"," gl_Position = worldSpace;\n"}, {"gl_Position_n"," gl_Position = nDCSpace;\n"}, {"outDepthPosition", " #ifdef SHADOWMAP\n" " depthPosition = depthWorldMatrix * modelMatrix *pos;\n" " #endif\n"}, {"outVertexPosition"," vertexPosition = pos;\n"}, {"outVertexNormal", " vertexNormal = normalize(worldMatrix * modelMatrix * vec4(normal,0.0));\n"}, {"outWorldSpacePosition", " worldSpacePosition = worldSpace;\n"}, {"outVertexUV", " vertexUV = uv;\n"}, {"outVertexTangent", " vertexTangent = normalize(worldMatrix * modelMatrix * vec4(tangent,0.0));\n"} }; this->helpers = { {"attenuateLightFunc", "#if MAX_P_LIGHTS > 0\n" "vec4 attenuateLight(in vec4 color, in float attenuation, in vec4 vectorToLight){\n" " float distSqr = dot(vectorToLight,vectorToLight);\n" " vec4 attenLightIntensity = color * (1/(1.0 + attenuation * sqrt(distSqr)));\n" " return attenLightIntensity;\n" "}\n" "#endif\n"}, {"PCFShadowFactorFunc", "#ifdef PCFSHADOW\n" "float calculateShadowFactorPCF(in vec4 lightSpacePos){\n" " vec3 projCoords = lightSpacePos.xyz / lightSpacePos.w;\n" " vec3 uv = 0.5 * projCoords + 0.5;\n" " if(uv.x > 1.0 || uv.y > 1.0 || uv.x < 0.0 || uv.y < 0.0) return 1.0;\n" " vec2 offset = vec2(1.0/shadowMapSize.x,1.0/shadowMapSize.y);\n" " float result = 0.0;\n" " for(int i = -sampleSize; i< sampleSize;i++){\n" " for(int j = -sampleSize; j < sampleSize; j++){\n" " vec2 offsets = vec2(i*offset.x , j*offset.y);\n" " vec3 uvc = vec3(uv.xy +offsets, uv.z + 0.00001);\n" " float mapDepth = texture(shadowMap,uv.xy+offsets).x;\n" " if( mapDepth < uv.z + 0.00001){\n" " result += 0.0;\n" " }\n" " else{\n" " result += 1.0;\n" " }\n" " }\n" " }\n" " float numSamples = (1 + 2*sampleSize)*(1 + 2*sampleSize);\n" " return 0.5 + (result/numSamples);\n" "}\n" "#endif"}, {"shadowFactorFunc", "#ifdef SHADOWMAP\n" "float calculateShadowFactor(in vec4 lightSpacePos){\n" " vec3 projCoords = lightSpacePos.xyz / lightSpacePos.w;\n" " vec3 uv = 0.5 * projCoords + 0.5;\n" " if(uv.x > 1.0 || uv.y > 1.0 || uv.x < 0.0 || uv.y < 0.0) return 1.0;\n" " float depth = texture(shadowMap,uv.xy).x;\n" " if (depth < uv.z + 0.00001){\n" " return 0.5;\n" " }\n" " return 1.0;\n" "}\n" "#endif\n"}, {"calculateNormalFunc", "#ifdef NORMALMAP\n" "vec4 calculateNormal(in vec4 vNormal,in vec4 vTangent, in vec2 uv ,in sampler2D normalMap){\n" " vec3 normal = normalize(vNormal).xyz;\n" " vec3 tangent = normalize(vTangent).xyz;\n" " tangent = normalize(tangent - dot(tangent,normal) * normal);\n" " vec3 bitangent = -cross(tangent,normal);\n" " vec3 texNormal = 255 * texture(normalMap,uv).xyz /128 - vec3(1.0,1.0,1.0);\n" " mat3 TBN = mat3(tangent, bitangent, normal);\n" " texNormal = TBN * texNormal;\n" " texNormal = normalize(texNormal);\n" " return vec4(texNormal,0.0);\n" "}\n" "#endif"}, {"warpFunc", "float warp (in float value,in float factor){\n" " return (value + factor ) / (1+ clamp(factor,0,1));\n" "}\n"}, {"calculateCosAngIncidenceFunc", "float calculateCosAngIncidence(in vec4 direction, in vec4 normal,in float warpFactor){\n" " //use warpFactor = 0 for no warp\n" " float cosAngIncidence = dot(normal,direction);\n" " cosAngIncidence = warp(cosAngIncidence,warpFactor);\n" " cosAngIncidence = clamp(cosAngIncidence,0,1);\n" " return cosAngIncidence;\n" "}\n"}, {"calculateBlinnPhongTermFunc", "float calculateBlinnPhongTerm(in vec4 direction,vec4 normal, in vec4 viewDirection, in float shininess, out float cosAngIncidence){\n" " cosAngIncidence = calculateCosAngIncidence(normal,direction,0);\n" " vec4 halfAngle = normalize(direction + viewDirection);\n" " float blinnPhongTerm = dot(normal, halfAngle);\n" " blinnPhongTerm = clamp(blinnPhongTerm, 0, 1);\n" " blinnPhongTerm = cosAngIncidence != 0.0 ? blinnPhongTerm : 0.0;\n" " blinnPhongTerm = pow(blinnPhongTerm, shininess);\n" " return blinnPhongTerm;\n" "}\n"} }; this->fragmentChunk ={ {"viewDirection"," vec4 viewDirection = normalize(-worldSpacePosition);\n"}, {"texCoord"," vec2 texCoord = gl_FragCoord.xy / screenSize;\n"}, {"mappedDepthPosition"," vec4 depthPosition = depthWorldMatrix * texture(positionMap,texCoord);\n"}, {"mappedViewDirection"," vec4 viewDirection = normalize(-texture(worldPositionMap,texCoord));\n"}, {"mappedDiffuseColor"," vec4 diffuseColor = texture(colorMap,texCoord);\n"}, {"mappedNormal"," vec4 normal = normalize(texture(normalMap,texCoord));"}, {"directionalLightFactor", " vec4 normDirection = normalize(dirLightVectorToLight);\n" " float cosAngIncidence;\n" " float blinnPhongTerm = calculateBlinnPhongTerm(normDirection,normal,viewDirection,material.shininess,cosAngIncidence);\n" " outputColor = outputColor + (shadowFactor * dirLightColor * diffuseColor * cosAngIncidence * dirLightIntensity / maxLightIntensity);\n" " outputColor = outputColor + (shadowFactor * dirLightColor * specularColor * blinnPhongTerm * dirLightIntensity / maxLightIntensity);\n"}, {"initOutputColor"," outputColor = vec4(0.0,0.0,0.0,1.0);\n"}, {"materialDiffuseColor"," vec4 diffuseColor = material.diffuseColor;\n"}, {"materialSpecularColor"," vec4 specularColor = material.specularColor;\n"}, {"interpolatedNormal"," vec4 normal = normalize(vertexNormal);\n"}, {"mapDiffuseColor", " #ifdef MAP\n" " diffuseColor = texture(colorMap,texCoord);\n" " #endif\n"}, {"mapNormal", " #ifdef NORMALMAP\n" " normal = calculateNormal(vertexNormal,vertexTangent,vertexUV,normalMap);\n" " #endif\n"}, {"initShadowFactor","float shadowFactor = 1.0;\n"}, {"PFCshadowFactor", " #ifdef PCFSHADOW\n" " shadowFactor = calculateShadowFactorPCF(depthPosition);\n" " #endif\n"}, {"shadowFactor", " #ifdef SHADOWMAP\n" " shadowFactor = calculateShadowFactor(depthPosition);\n" " #endif\n"}, {"addDirectionalLightsFactor", " #if MAX_DIR_LIGHTS > 0\n" " for(int i=0; i< MAX_DIR_LIGHTS ;i++){\n" " vec4 normDirection = normalize(dirLightVectorToLight[i]);\n" " float cosAngIncidence;\n" " float blinnPhongTerm = calculateBlinnPhongTerm(normDirection,normal,viewDirection,material.shininess,cosAngIncidence);\n" " outputColor = outputColor + (shadowFactor * dirLightColor[i] * diffuseColor * cosAngIncidence * dirLightIntensity[i] / maxLightIntensity);\n" " outputColor = outputColor + (shadowFactor * dirLightColor[i] * specularColor * blinnPhongTerm * dirLightIntensity[i] / maxLightIntensity);\n" " }\n" " #endif\n"}, {"addPointLightsFactor", " #if MAX_P_LIGHTS > 0\n" " for(int i=0; i< MAX_P_LIGHTS ;i++){\n" " vec4 difference = pointLightPosition[i] - worldSpacePosition;\n" " vec4 normDirection = normalize(difference);\n" " vec4 attenLightIntensity = attenuateLight(pointLightColor[i],pointLightAttenuation[i],difference);\n" " float cosAngIncidence;\n" " float blinnPhongTerm = calculateBlinnPhongTerm(normDirection,normal,viewDirection,material.shininess,cosAngIncidence);\n" " \n" " outputColor = outputColor + (attenLightIntensity * diffuseColor * cosAngIncidence * pointLightIntensity[i] / maxLightIntensity);\n" " outputColor = outputColor + (specularColor * attenLightIntensity * blinnPhongTerm * pointLightIntensity[i] / maxLightIntensity);\n" " }\n" " #endif\n"}, {"addAmbientLightFactor", "outputColor = outputColor + (diffuseColor * ambientLight);\n"}, {"gammaCorrection", " vec4 gamma = vec4(invGamma);\n" " gamma.w = 1.0;\n" " outputColor = pow(outputColor,gamma);\n"}, {"outputMapColor"," outputColor= texture2D(colorMap,vertexPosition.xy * 0.5 + 0.5);\n"}, {"outputDepth", " float depth = texture(colorMap,vertexPosition.xy).x;\n" " depth = 1.0 - (1.0 - depth) *25.0;\n" " outputColor= vec4(depth);\n"}, {"outputColorTarget","outputColor = diffuseColor;"}, {"outputNormalTarget","outputNormal = normal;"}, {"outputPositionTarget","outputPosition = worldSpacePosition;"}, {"outputUVTarget","outputUV = vec4(vertexUV,0.0,0.0);"} }; } string get_file_contents(const char *filename){ ifstream in(filename, ios::in | ios::binary); if (in){ return(std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>())); } throw(errno); } }
4d7c00dec355ced17bf1fad090d9616cae85295d
a5e3fbdf73ad3a361bf3723dc514516896d1907b
/code/ray_tracing/src/core/base.cpp
8bd1beaf6a1ed2aa7f0a01fabb95abc4380dd3bc
[ "MIT" ]
permissive
kmfu/ray_tracing_tutorial
0ed0740215f9916446996b1b6352c1383fb23877
a2d9c5596334d45e5937b33d87b4b8f5db9cd4b5
refs/heads/master
2022-07-01T22:47:32.167795
2020-05-08T07:16:14
2020-05-08T07:16:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,447
cpp
base.cpp
#include<core.h> ray_tracing::ray::ray(const vec::vec3 &origin,const vec::vec3 &direction):origin_(origin),direction_(direction.normalized()){} ray_tracing::ray::ray(const ray &r):origin_(r.origin()),direction_(r.direction()){} const vec::vec3& ray_tracing::ray::origin()const{return origin_;} const vec::vec3& ray_tracing::ray::direction()const{return direction_;} vec::vec3 ray_tracing::ray::go(const vec::real &t)const{return origin_+direction_*t;} ray_tracing::ray ray_tracing::camera::get_ray(vec::real u,vec::real v){return ray(vec::vec3(0,0,0),vec::vec3(1,2*v-1,0.5-u));} ray_tracing::ray ray_tracing::camera::get_ray(vec::vec2 p){return ray(vec::vec3(0,0,0),vec::vec3(1,2*p.y()-1,0.5-p.x()));} ray_tracing::intersections::intersections(ray_tracing::intersect** list,size_t n):list_(list),size_(n){} bool ray_tracing::intersections::hit(const ray_tracing::ray &sight,vec::real t_min,vec::real t_max,hitpoint &rec)const { ray_tracing::hitpoint t_rec;//一个临时的交点消息记录变量 bool hitSomething=0;//记录是否击中物体 vec::real far=t_max;//刚开始可以看到最远距离,chapter 2 中的m的作用 for(int i=0;i<size_;i++)if(list_[i]->hit(sight,t_min,far,t_rec))//枚举每一个物体,如果这个物体存在距离大于t_min小于far的交点,则更新far { hitSomething=1; far=t_rec.t;//将上一次的最近撞击点作为视线可达最远处(更新far) rec=t_rec; } return hitSomething; }
38cac6282aca0e3f5889efe0efa73fbc5da20209
624d28b7da6b547d64706f59e336c99f92d5a26e
/Caravel/DRODLib1.5/Files.h
3259c7cfe390355a919a92a734ccd8b608c00ae6
[]
no_license
anderssonn/drod
543828e11956bc56dca631ad3371cc430098e432
48f99a4c261824f41694cfa446daccb09228598a
refs/heads/master
2020-12-01T11:38:34.588601
2013-10-20T19:44:24
2013-10-20T19:44:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,704
h
Files.h
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Deadly Rooms of Death. * * The Initial Developer of the Original Code is * Caravel Software. * Portions created by the Initial Developer are Copyright (C) 1995, 1996, * 1997, 2000, 2001, 2002 Caravel Software. All Rights Reserved. * * Contributor(s): * Mike Rimer (mrimer) * * ***** END LICENSE BLOCK ***** */ //Files.h //Declarations for CFiles. //Class for handling file-related tasks. #ifndef FILES_H #define FILES_H #include "Assert.h" #include "StretchyBuffer.h" #define MAX_PROFILE_STRING 80 #ifndef MAX_PATH #define MAX_PATH 260 #endif //File separator. const char szFILE_SEP[] = "\\"; class CFiles { public: CFiles(void); ~CFiles(void); static void AppendErrorLog(const char *pszText); static bool DoesFileExist(const char *pszFilepath); static const char *GetAppPath(void) {ASSERT(pszAppPath); return pszAppPath;} static const char *GetDatPath(void) {ASSERT(pszDatPath); return pszDatPath;} bool GetDRODProfileString(const char *pszSection, const char *pszKey, char *pszValue); static bool HasReadWriteAccess(const char *pszFilepath); static bool ReadFileIntoBuffer(const char *pszFilepath, CStretchyBuffer &Buffer); static void TryToFixDataPath(); bool WriteDRODProfileString(const char *pszSection, const char *pszKey, const char *pszValue); static bool WriteBufferToFile(const char *pszFilepath, const CStretchyBuffer &Buffer); //File encryption/unencryption. static bool FileIsEncrypted(const char *pszFilepath) { return pszFilepath[strlen(pszFilepath) - 1] == '_';} static void EncodeBuffer(CStretchyBuffer &buffer); static bool ProtectFile(const char *pszFilepath); //symmetric operations static void DecodeBuffer(CStretchyBuffer &buffer) {EncodeBuffer(buffer);} static bool UnprotectFile(const char *pszFilepath) {return ProtectFile(pszFilepath);} static bool GetTrueDatafileName(char *const pszFilepath); static void MutateFileName(char *pszFilepath); private: void DeinitClass(void); static bool FindPossibleDatPath(const char *pszStartPath, char *pszPossibleDatPath); void InitClass(void); static bool WriteDataPathTxt(const char *pszFilepath, const char *pszDatPath, const bool overwrite); static char *pszAppPath; static char *pszDatPath; static unsigned long dwRefCount; PREVENT_DEFAULT_COPY(CFiles); }; #endif //...#ifndef FILES_H // $Log: Files.h,v $ // Revision 1.2 2003/05/19 21:12:14 mrimer // Some code maintenance. // // Revision 1.1 2003/02/25 00:01:34 erikh2000 // Initial check-in. // // Revision 1.16 2003/02/24 17:04:21 erikh2000 // Added file separator constant. // // Revision 1.15 2002/11/13 23:18:35 mrimer // Made a parameter const. // // Revision 1.14 2002/09/24 21:14:28 mrimer // Declared general file operations as static. // // Revision 1.13 2002/08/29 09:17:50 erikh2000 // Added method to write a buffer to a file. // // Revision 1.12 2002/08/23 23:24:20 erikh2000 // Changed some params. // // Revision 1.11 2002/07/18 20:15:42 mrimer // Added GetTrueDatafileName() and MutateFileName(). Revised ProtectFile(). // // Revision 1.10 2002/07/05 17:59:34 mrimer // Minor fixes (includes, etc.) // // Revision 1.9 2002/07/02 23:53:31 mrimer // Added file encryption/unencryption routines. // // Revision 1.8 2002/04/28 23:51:11 erikh2000 // Added new method to check for read/write access on a file. // // Revision 1.7 2002/04/11 10:08:29 erikh2000 // Wrote CFiles::ReadFileIntoBuffer(). // // Revision 1.6 2002/04/09 01:04:31 erikh2000 // Twiddling. // // Revision 1.5 2002/03/14 03:51:40 erikh2000 // Added TryToFixDataPath() and overwrite parameter to WriteDataPathTxt(). (Committed on behalf of mrimer.) // // Revision 1.4 2002/03/05 01:54:10 erikh2000 // Added 2002 copyright notice to top of file. // // Revision 1.3 2001/12/08 01:44:59 erikh2000 // Added PREVENT_DEFAULT_COPY() macro to class declaration. // // Revision 1.2 2001/10/13 02:37:53 erikh2000 // If DataPath.txt is not present, DRODLib will now search for a possible data path to use and write this path to DataPath.txt. // // Revision 1.1.1.1 2001/10/01 22:20:15 erikh2000 // Initial check-in. //
a08e4a994d869fcbc18b6f2ec5934d913c57c101
1741984c3681edca8cdf26cc4412d73c0a8c9646
/source/engine/rendering.cpp
9dfd4a4c239b588505ed08d138bada5dcfecdd24
[]
no_license
kochol/DiceInvaders
f4ced344c5cdc792c257bf0739e5c7ad97775c9f
bfe5e679a1b39c3ae67f67f552fd2633fd246c5d
refs/heads/master
2020-04-09T06:09:46.863915
2016-06-24T15:26:18
2016-06-24T15:26:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,497
cpp
rendering.cpp
/* --------------------------------------------------------------------------- ** ** rendering.cpp ** Rendering stuff, implemented as a part of "Model" component ** ** Author: Ali Salehi ** -------------------------------------------------------------------------*/ #include "engine.h" namespace Engine { static void _RenderLayer( const uint16_t *const indexes, const Transform *const transforms, const ResourceHandle *const sprites, const uint16_t count, const uint16_t *const i_sprites_indexes, ISprite **const i_sprites) { for (uint16_t i = 0; i < count; ++i) { const uint16_t index = indexes[i]; const uint16_t iSpriteIndex = i_sprites_indexes[sprites[index].index]; ISprite *const sprite = i_sprites[iSpriteIndex]; sprite->draw( static_cast<int>(transforms[index].position.x), static_cast<int>(transforms[index].position.y)); } } void Render(ComponentManager::LayerData *const data) { ISprite **const i_sprites = ResolveSpriteData(); const uint16_t *const i_sprites_indexes = ResolveSpriteIndexes(); const uint16_t count = data->components.Size(); if (count == 0) return; const uint16_t *const indexes = data->components.Indexes(); const Transform *const transforms = data->components.Data<Transform>(MODEL_DATA_TRANSFORM); const ResourceHandle *const sprites = data->components.Data<ResourceHandle>(MODEL_DATA_SPRITE); _RenderLayer( indexes, transforms, sprites, count, i_sprites_indexes, i_sprites); } }
ec7342f2fe9be234812c3ce8934827c521e68cb2
96d0ade155d33078d4a1c848e4d929b39aed173e
/src/problem.cc
991053d6661bc3277e686af3a9ecca45e02fc9cd
[]
no_license
maxencedb/plam2
7f45c8dd827dbffab7e33d5fdee2a01e18e591a0
b2a4f37c40374bba90a8170ad3fd24c15c49ec18
refs/heads/master
2020-06-30T02:56:58.426189
2018-10-07T08:59:50
2018-10-07T08:59:50
40,079,774
0
0
null
null
null
null
UTF-8
C++
false
false
5,660
cc
problem.cc
#include <iostream> #include <glpk.h> #include "problem.hh" Problem::Problem() : lp(glp_create_prob()) , smcp() , iocp() , c0(0.0) , obj_coefs() , row_index() , col_index() , values() , variables() , constraints() , var_indexes() { } Problem::~Problem() { glp_delete_prob(lp); } void Problem::set_name(std::string str) { glp_set_prob_name(lp, str.c_str()); } std::string Problem::get_name() { return std::string(glp_get_prob_name(lp)); } void Problem::set_maximize() { glp_set_obj_dir(lp, GLP_MAX); } void Problem::set_minimize() { glp_set_obj_dir(lp, GLP_MIN); } bool Problem::is_maximize() { return glp_get_obj_dir(lp) == GLP_MAX; } void Problem::set_c0_shift(double c0) { this->c0 = c0; } double Problem::get_c0_shift() { return this->c0; } bool Problem::add_var_coef(std::string name, double coef) { if (variables.find(name) == variables.end()) return false; obj_coefs[name] = coef; return true; } bool Problem::add_variable(const Variable& v) { if (variables.find(v.get_name()) != variables.end()) return false; else { variables[v.get_name()] = v; return true; } } bool Problem::add_constraint(const Constraint& c) { if (constraints.find(c.get_name()) != constraints.end()) return false; else { constraints[c.get_name()] = c; return true; } } double Problem::get_var_value(std::string name) { return glp_mip_col_val(lp, var_indexes[name]); } double Problem::get_obj_value() { return glp_mip_col_val(lp, 0); } void Problem::process_variables() { glp_add_cols(lp, variables.size()); int index = 1; for (auto couple : variables) { var_indexes[couple.second.get_name()] = index; glp_set_col_name(lp, index, couple.second.get_name().c_str()); glp_set_col_kind(lp, index, couple.second.get_variable_kind()); int tmp_choice = GLP_FR; Variable& tmp_var = couple.second; if (tmp_var.has_lower_bound()) { if (tmp_var.has_higher_bound()) { if (tmp_var.get_lower_bound() == tmp_var.get_higher_bound()) tmp_choice = GLP_FX; else tmp_choice = GLP_DB; } else tmp_choice = GLP_LO; } else { if (tmp_var.has_higher_bound()) tmp_choice = GLP_UP; else tmp_choice = GLP_FR; } glp_set_col_bnds(lp, index, tmp_choice, tmp_var.get_lower_bound(), tmp_var.get_higher_bound()); ++index; } } void Problem::process_constraints() { glp_add_rows(lp, constraints.size()); // empty 0 because [0] is not used row_index.push_back(0); col_index.push_back(0); values.push_back(0.0); int index = 1; for (auto couple : constraints) { Constraint& tmp_cons = couple.second; // Name glp_set_row_name(lp, index, tmp_cons.get_name().c_str()); // Bounds glp_set_row_bnds(lp, index, tmp_cons.get_bnds_type(), tmp_cons.get_lower_bound(), tmp_cons.get_higher_bound()); // Constraint matrix for (auto coef_couple : tmp_cons.get_var_coefs()) { const std::string& var_name = coef_couple.first; double var_coef = coef_couple.second; // Find the corresponding variable in var map. auto tmp_var = variables.find(var_name); if (tmp_var == variables.end()) { // cannot find required variable std::cerr << "Constraint: \"" << tmp_cons.get_name() << "\" requires variable: \"" << var_name << "\" but no such variable is present in the problem\n"; continue; } else { // found required variable int tmp_var_index = var_indexes[var_name]; row_index.push_back(index); col_index.push_back(tmp_var_index); values.push_back(var_coef); } } // switch to a new constraint index ++index; } // Load constraint matrix glp_load_matrix(lp, row_index.size() - 1, row_index.data(), col_index.data(), values.data()); } void Problem::process_objective() { // Set c0 constant problem shift glp_set_obj_coef(lp, 0, this->c0); // Set other coefs // Checking if variables exist has already been done in var adding for (auto couple : obj_coefs) glp_set_obj_coef(lp, var_indexes[couple.first], couple.second); } void Problem::launch_computing() { /* solve in real domain */ // Shut trivial messages up glp_init_smcp(&smcp); smcp.msg_lev = GLP_MSG_ERR; // launch simplex and abort on error if (glp_simplex(lp, &smcp) != 0) { std::cerr << "Some errors occured when computing simplex on real domain\n"; return; } /* Solve on integer domain */ // Shut trivial messages up glp_init_iocp(&iocp); iocp.msg_lev = GLP_MSG_ERR; // launch branch and cut glp_intopt(lp, &iocp); } void Problem::display_solution(std::ostream& output) { output << "Z = " << glp_mip_obj_val(lp) << "\n\n"; for (auto couple : var_indexes) output << couple.first << ": " << glp_mip_col_val(lp, couple.second) << "\n"; } void Problem::solve() { process_variables(); process_constraints(); process_objective(); launch_computing(); }
87a35a472e690877f58194fab25a069296f35b8a
4b62774fb7958d8917ff0eca29b105c160aa3408
/Contest Programming/Codes/Codeforces/831B. Keyboard Layouts.cpp
ab8ca49cd05c0ee6625b015006e01b9869bc9707
[]
no_license
talhaibnaziz/projects
1dd6e43c281d45ea29ee42ad93dd7faa9c845bbd
95a5a05a938bc06a65a74f7b7b75478694e175db
refs/heads/master
2022-01-21T08:00:37.636644
2021-12-30T01:58:34
2021-12-30T01:58:34
94,550,719
0
0
null
2021-12-26T02:01:24
2017-06-16T14:16:24
Java
UTF-8
C++
false
false
452
cpp
831B. Keyboard Layouts.cpp
#include <bits/stdc++.h> using namespace std; map <char, char> mp; int main() { string a, b, input; cin>>a>>b>>input; for(int i=0; i<26; i++) { mp[a[i]] = b[i]; } for(int i=0; i<input.size(); i++) { if(input[i]>='a' && input[i]<='z') input[i] = mp[input[i]]; else if(input[i]>='A' && input[i]<='Z') input[i] = (mp[input[i]+32])-32; } cout<<input; return 0; }
4159d7e4fc291c1834cfafc3ec665cfd883f888a
25034d16145cf69dd6d8df778af0de1f4b0046d5
/src/Main.h
64283d3236f598ecb3c0e4c21c2459e27347a3b6
[]
no_license
FeldrinH/Densiotropic-Universe
20b1cf5deeec63e9ebf334ce19d2a337bf213ad5
f90701e82cf6fc0c1b9d5c1430664c533c8b69c1
refs/heads/master
2020-04-16T23:35:58.813180
2016-08-09T18:14:59
2016-08-09T18:14:59
46,986,968
0
0
null
null
null
null
UTF-8
C++
false
false
138
h
Main.h
#pragma once #include <ppl.h> #include <concurrent_queue.h> #include "SDL.h" extern concurrency::concurrent_queue<std::string> cmdQueue;
a1ab9080f7c0767dd142f82a47ab2bf36b952fc1
880d2da6a66b63fe88b1f334504a2386e17feb2e
/integrationtest/WordMapLayout/WordMapLayout/WordMapLayoutDriver.cpp
dd6254163e1971a3af4393bb1403c82371d1f670
[]
no_license
firesidedata/WordMap
7e0335db7816ab0f485d8df175bacb9d31cf022f
98061e6fb84dbc5dcee4fdbc695fdc33f569686c
refs/heads/master
2020-04-10T17:53:04.680409
2018-12-10T14:34:42
2018-12-10T14:34:42
161,187,272
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
WordMapLayoutDriver.cpp
#include "ColumnLayout.h" #include "WordMapMaker.h" #include "DocList.h" #include "FreqList.h" #include "WordCount.h" #include "WordMap.h" #include "MapItem.h" #include "Rectangle.h" #include "FontSize.h" //#include "LatexFactory.h" #include "IRenderFactory.h" #include "latexutil.h" #include "LatexMaker.h" #include <iostream> int main() { DocList* doclist = new DocList("page.txt", new FreqList()); WordMapMaker* mapmaker = new WordMapMaker(); WordMap* map = new WordMap(); doclist->read(doclist->getFileName()); doclist->getFreqList().write("output.txt"); map=mapmaker->convertFreqList(doclist); ICloudLayout* layout = NewLayout(); LatexMaker* maker = new LatexMaker(); layout->updateWordMap(map); cout << "created file maker.tex"<<endl; cout << "testing all mapitems in the map" << endl; maker->generateDoc(map, "maker"); for (int i = 0; i < map->size(); i++) { cout << i << ". width= " << map->at(i)->getWidth() << "\t"; cout << " height= " << map->at(i)->getHeight() << "\t"; cout << " x= " << map->at(i)->getX() << "\t"; cout << " y= " << map->at(i)->getY() << "\t" << endl << endl; } system("pause"); }
0792d7f7f8b7a77bb975d5ef156d8641af27e70d
9ee974fc2bbfbd85a8530d7e986a39ad35ceb15c
/Geometric_shapes_inheritance/Rhombus.cpp
ef07b869ca13ef13cba29fdc5e65e37a241a077e
[]
no_license
Pulkit219/Cpp-projects
5d9619462eab0076a2bae6f98fc8b7c4d274b83f
a3eea595aeedc27fc25c722fd846e0ce93cc2e13
refs/heads/master
2022-12-10T18:33:24.131387
2020-09-06T00:57:16
2020-09-06T00:57:16
269,184,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,822
cpp
Rhombus.cpp
#include "Rhombus.h" Rhombus::Rhombus(int diag, string name, string desc):Shape{name,desc},d{diag} { d = diag % 2 == 0 ? diag + 1 : diag; // if d is even then make it d+1 else store d } int Rhombus::get_height() const { return this->d; } int Rhombus::get_width() const { return this->d; } void Rhombus::set_d(int dia) { dia % 2 == 0 ? d = dia + 1 : d = dia; // if d is even then make it d+1 else store d } double Rhombus::get_area() const { return pow(d, 2.0) / 2; } double Rhombus::get_perimeter() const { return 2 * sqrt(2.0) * d; } int Rhombus::get_screen_area() const { double n = d / 2; return (2 * n * (n + 1) + 1); } int Rhombus::get_screen_perimeter() const { return 2 * (this->d-1); } int Rhombus::get_bounding_box_height() const { return this->d; } int Rhombus::get_bounding_box_width() const { return this->d; } Grid Rhombus::draw(char fChar, char bChar) const { Grid rhombus_grid; // position and position2 are used to keep track of the edges of the rhombus int position{ this->get_height() / 2 }; int position2{ this->get_height() / 2 }; for (int r = 0; r < this->get_height(); ++r) { rhombus_grid.push_back(vector<char>()); // For the top half of the rhombus if (r < this->get_height() / 2) { for (int c = 0; c < this->get_width(); ++c) { if (c >= position && c <= position2) { rhombus_grid[r].push_back(fChar); } else { rhombus_grid[r].push_back(bChar); } } position -= 1; position2 += 1; } else { // For the bottom half of the rhombus for (int c = 0; c < this->get_width(); ++c) { if (c >= position && c <= position2) { rhombus_grid[r].push_back(fChar); } else { rhombus_grid[r].push_back(bChar); } } position += 1; position2 -= 1; } } return rhombus_grid; }
d81d1fbc4767a9ce6b819dae156a7f0f08da3c29
8bcb75e4fa8fe4e0557c17417f2b53ed2dce6bbd
/TxtCopyMacro/simplification.cpp
8113b193695b7d73ffed0ec3f8b20a2a9d86ac61
[]
no_license
scdoit22/Projects
ec8120545bbdfe707e917727770803c108176f46
dc94e4dcc16d23d0da5835be21db2dc55c56144f
refs/heads/main
2023-03-08T02:42:07.790334
2021-02-26T14:00:36
2021-02-26T14:00:36
342,250,141
0
0
null
null
null
null
UTF-8
C++
false
false
1,955
cpp
simplification.cpp
#include <fstream> #include <string> #include <iostream> #include <regex> #include <vector> class simplification { private: char chapter[1]; std::regex chapterRegex; // 챕터 찾는 정규표현식 std::regex wordRegex; std::vector<std::string> output; const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public: simplification() { chapterRegex = "[A-Z] [가-힣]+( [가-힣]*)*"; wordRegex = "•[a-z ]*"; } void Input() { std::ifstream f; f.open("D:\\Programming\\DB\\XiBasicVoca.txt", std::ios::in); if (!f.is_open()) { std::cout << "파일을 찾을 수 없습니다!" << std::endl; } std::string buf; int count = 0; std::smatch match; while (!f.eof()) { std::getline(f, buf); if(std::regex_search(buf, match, wordRegex)) { buf = match.str(); buf.erase(0,3); output.push_back(buf); std::cout << buf << "\n"; } else if(std::regex_search(buf, chapterRegex)) { buf = buf[0]; buf += std::to_string(count); output.push_back(buf); std::cout << buf << std::endl;; ++count; } } f.close(); } void Output() { std::ofstream f; f.open("D:\\Programming\\C++\\Projects\\TxtCopyMacro\\simple.txt"); std::string tmp; for(int i = 0; i < output.size(); ++i) { tmp = output[i]; if (i != output.size() - 1) { tmp += "\n"; //마지막 단어 빼고 엔터 넣어주기 } f.write(tmp.c_str(), tmp.size()); } } }; int main(void) { simplification si; si.Input(); si.Output(); return 0; }
18242868d20c84b08f3b9e5cdfe99bc519501baf
5e3ba38ab7cc72cafb31e9d2f0dc763cbd2ac3e3
/tlg-wic-codec/libtlg/slide.cpp
be8f03a5dedc108c03612ae7e7dcef8d17f47f9d
[ "MIT" ]
permissive
SegaraRai/tlg-wic-codec
262715bd4fa2904f1244d9df7582c440976472d6
4dd7b3f2e3a2c674083140b7b9a61ea9dc0d8017
refs/heads/master
2022-11-27T20:20:32.014939
2020-08-10T17:38:09
2020-08-10T17:38:09
283,404,546
1
0
null
2020-07-29T05:12:29
2020-07-29T05:12:29
null
UTF-8
C++
false
false
4,609
cpp
slide.cpp
//--------------------------------------------------------------------------- #include "slide.h" //--------------------------------------------------------------------------- SlideCompressor::SlideCompressor() { for (int i = SLIDE_N - 1; i >= 0; i--) { AddMap(i); } } //--------------------------------------------------------------------------- SlideCompressor::~SlideCompressor() {} //--------------------------------------------------------------------------- int SlideCompressor::GetMatch(const unsigned char* cur, int curlen, int& pos, int s) { // get match length if (curlen < 3) return 0; int place = cur[0] + ((int)cur[1] << 8); int maxlen = 0; if ((place = Map[place]) != -1) { int place_org; curlen -= 1; do { place_org = place; if (s == place || s == ((place + 1) & (SLIDE_N - 1))) continue; place += 2; int lim = (SLIDE_M < curlen ? SLIDE_M : curlen) + place_org; const unsigned char* c = cur + 2; if (lim >= SLIDE_N) { if (place_org <= s && s < SLIDE_N) lim = s; else if (s < (lim & (SLIDE_N - 1))) lim = s + SLIDE_N; } else { if (place_org <= s && s < lim) lim = s; } while (Text[place] == *(c++) && place < lim) place++; int matchlen = place - place_org; if (matchlen > maxlen) pos = place_org, maxlen = matchlen; if (matchlen == SLIDE_M) return maxlen; } while ((place = Chains[place_org].Next) != -1); } return maxlen; } //--------------------------------------------------------------------------- void SlideCompressor::AddMap(int p) { int place = Text[p] + ((int)Text[(p + 1) & (SLIDE_N - 1)] << 8); if (Map[place] == -1) { // first insertion Map[place] = p; } else { // not first insertion int old = Map[place]; Map[place] = p; Chains[old].Prev = p; Chains[p].Next = old; Chains[p].Prev = -1; } } //--------------------------------------------------------------------------- void SlideCompressor::DeleteMap(int p) { int n; if ((n = Chains[p].Next) != -1) Chains[n].Prev = Chains[p].Prev; if ((n = Chains[p].Prev) != -1) { Chains[n].Next = Chains[p].Next; } else if (Chains[p].Next != -1) { int place = Text[p] + ((int)Text[(p + 1) & (SLIDE_N - 1)] << 8); Map[place] = Chains[p].Next; } else { int place = Text[p] + ((int)Text[(p + 1) & (SLIDE_N - 1)] << 8); Map[place] = -1; } Chains[p].Prev = -1; Chains[p].Next = -1; } //--------------------------------------------------------------------------- void SlideCompressor::Encode(const unsigned char* in, long inlen, unsigned char* out, long& outlen) { unsigned char code[40], codeptr, mask; if (inlen == 0) return; outlen = 0; code[0] = 0; codeptr = mask = 1; int s = S; while (inlen > 0) { int pos = 0; int len = GetMatch(in, inlen, pos, s); if (len >= 3) { code[0] |= mask; if (len >= 18) { code[codeptr++] = pos & 0xff; code[codeptr++] = ((pos & 0xf00) >> 8) | 0xf0; code[codeptr++] = len - 18; } else { code[codeptr++] = pos & 0xff; code[codeptr++] = ((pos & 0xf00) >> 8) | ((len - 3) << 4); } while (len--) { unsigned char c = 0 [in++]; DeleteMap((s - 1) & (SLIDE_N - 1)); DeleteMap(s); if (s < SLIDE_M - 1) Text[s + SLIDE_N] = c; Text[s] = c; AddMap((s - 1) & (SLIDE_N - 1)); AddMap(s); s++; inlen--; s &= (SLIDE_N - 1); } } else { unsigned char c = 0 [in++]; DeleteMap((s - 1) & (SLIDE_N - 1)); DeleteMap(s); if (s < SLIDE_M - 1) Text[s + SLIDE_N] = c; Text[s] = c; AddMap((s - 1) & (SLIDE_N - 1)); AddMap(s); s++; inlen--; s &= (SLIDE_N - 1); code[codeptr++] = c; } mask <<= 1; if (mask == 0) { for (int i = 0; i < codeptr; i++) out[outlen++] = code[i]; mask = codeptr = 1; code[0] = 0; } } if (mask != 1) { for (int i = 0; i < codeptr; i++) out[outlen++] = code[i]; } S = s; } //--------------------------------------------------------------------------- void SlideCompressor::Store() { S2 = S; Text2 = Text; Map2 = Map; Chains2 = Chains; } //--------------------------------------------------------------------------- void SlideCompressor::Restore() { S = S2; Text = Text2; Map = Map2; Chains = Chains2; } //---------------------------------------------------------------------------
3579914643cf35e94b72b1c05ddff84a6c2ebf46
7ea1e4c7eda6ee1ba4ed3a98a4d513c68e6b715f
/src/main.cpp
7a31d3bdf13e02168bfd28d35844571cbb8680de
[]
no_license
addisgithub/graph
3ef28f3dc649bba1e5c37e576a6f7324881b4a48
cfa5a64f2aba1cd6310286f076b21a5813f2be08
refs/heads/main
2023-06-05T22:19:48.609592
2021-06-29T19:16:12
2021-06-29T19:16:12
355,223,477
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cpp
main.cpp
/* * @author Addis Bogale * @date 4/2/2021 */ #include <iostream> #include <vector> using namespace std; class Graph { private: int n; public: int Matrix[10][10] = { 0 }; Graph(int input) { n = input; } void addEdge(int i, int j) { Matrix[i][j] = true; } void removeEdge(int i, int j) { Matrix[i][j] = false; } bool hasEdge(int i, int j) { return Matrix[i][j]; } void displayMatrix() { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cout << Matrix[i][j]; } cout << endl; } } void outEdges(int i, vector<int> &edges) { for (int j = 0; j < n; j++) if (Matrix[i][j]) edges.push_back(j); } void inEdges(int i, vector<int> &edges) { for (int j = 0; j < n; j++) if (Matrix[j][i]) edges.push_back(j); } int nVertices() { return n * n; } void bfs(Graph &g, int r) { bool *seen = new bool[g.nVertices()]; vector<int> q; q.push_back(r); seen[r] = true; while (q.size() > 0) { int i = q.back(); cout << endl << i << " > " << "This is BFS" << endl; q.pop_back(); vector<int> edges; g.outEdges(i, edges); for (int k = 0; k < edges.size(); k++) { int j = edges[k]; if (!seen[j]) { q.push_back(j); seen[j] = true; } } } delete[] seen; } void dfs2(Graph &g, int r) { bool *c = new bool[g.nVertices()]; vector<int> s; s.push_back(r); while (s.size() > 0) { int i = s.back(); cout << endl << i << " > " << "This is DFS"<< endl; s.pop_back(); if (c[i] == *c) { c[i] = c; vector<int> edges; g.outEdges(i, edges); for (int k = 0; k < edges.size(); k++) s.push_back(edges[k]); } } delete[] c; } }; int main(int, char**) { Graph value(10); value.addEdge(0,1); value.addEdge(3,3); value.displayMatrix(); value.bfs(value, 0); value.removeEdge(3,3); value.displayMatrix(); value.addEdge(2,3); value.addEdge(1,3); value.hasEdge(0,1); value.dfs2(value, 2); value.displayMatrix(); }
9b84da4672ee3d3f098fb2ce4dda49dd55abf656
002c0b330b5a154aa2e4c638bd6e5618c77ff810
/pieces.cpp
336bdd7c9ae7c60b1625af09da656b947bf41e8d
[]
no_license
emilyws27/tictactoebase
63d77d21a7b5edefcb19964e22c8026d257dda29
d95427b931e025e498f17e92cf040c16ea46248d
refs/heads/main
2023-08-30T17:11:43.641907
2021-11-05T16:55:02
2021-11-05T16:55:02
425,020,772
0
0
null
null
null
null
UTF-8
C++
false
false
188
cpp
pieces.cpp
#include "pieces.h" game_pieces::game_pieces() : name(" "), appearance(" ") {} game_pieces::game_pieces(std::string name, std::string appearance) :name(name), appearance(appearance) { }
457e2e6d89e4290713ea1b8d9ec1e20923006281
b676cf48543e03726ced5f6fff0400f32b71ef13
/PongGame/src/game.cpp
4740cee5b1c9267048bdd2a0039391399dd3cf0a
[]
no_license
Xysar/PongGame
f8d84f8d9c422e4d17d04d6928841f481b9c7d7f
a8362997de1e0ba480ab96005d1ebfb0a48bd76f
refs/heads/main
2023-03-18T13:04:23.487393
2021-03-18T04:38:44
2021-03-18T04:38:44
348,942,120
1
0
null
null
null
null
UTF-8
C++
false
false
3,210
cpp
game.cpp
#define is_down(b) input->buttons[b].is_down #define pressed(b) (input-> buttons[b].is_down && input->buttons[b].changed) #define released(b) (!input-> buttons[b].is_down && input->buttons[b].changed) float player1P, player1V; float player2P, player2V; float ballXP = 0, ballXV = 75, ballXA = 0.f; float ballYP = 0, ballYV = 0.f, ballYA = 0.f; float ballHalfSize = 1; float arenaHalfSize = 45; float player1HalfSizey = 12, player1HalfSizex = 2.5; float player2HalfSizey = 12, player2HalfSizex = 2.5; void simulateGame(Input* input, float dt){ clear_screen(0xff5500); drawRect(0, 0, 85, arenaHalfSize, 0xffaa33); float player1A = 0.f; if (is_down(BUTTON_UP)) player1A += 2000; if (is_down(BUTTON_DOWN)) player1A -= 2000; float player2A = 0.f; if (is_down(BUTTON_W)) player2A += 2000; if (is_down(BUTTON_S)) player2A -= 2000; if (ballYV > 100) ballYV = 100; if (ballYV < -100) ballYV = -100; if (ballXV > 150) ballXV = 150; if (ballXV < -150) ballXV = -150; player1A -= player1V * 10.f; player1P = player1P + player1V * dt + ((player1A * dt * dt) / 2); player1V = player1V + player1A * dt; player2A -= player2V * 10.f; player2V = player2V + player2A * dt; player2P = player2P + player2V * dt + ((player2A * dt * dt) / 2); //ballXV = ballXV + ballXA * dt; ballXP = ballXP + ballXV * dt + ((ballXA * dt * dt) / 2); // ballYV = ballYV + ballYA * dt; ballYP = ballYP + ballYV * dt + ((ballYA * dt * dt) / 2); if (player1P + player1HalfSizey > arenaHalfSize) { player1P = arenaHalfSize - player1HalfSizey; player1V = 0; } if (-(player1P - player1HalfSizey) > arenaHalfSize) { player1P = -arenaHalfSize + player1HalfSizey; player1V = 0; } if (player2P + player2HalfSizey > arenaHalfSize) { player2P = arenaHalfSize - player2HalfSizey; player2V = 0; } if (-(player2P - player2HalfSizey) > arenaHalfSize) { player2P = -arenaHalfSize + player2HalfSizey; player2V = 0; } if (-(ballYP - ballHalfSize) > arenaHalfSize) { ballYP = -arenaHalfSize + ballHalfSize; ballYV = -ballYV; } if ((ballYP + ballHalfSize) > arenaHalfSize) { ballYP = arenaHalfSize - ballHalfSize; ballYV = -ballYV; } if ((ballXP + ballHalfSize > 80 - player1HalfSizex) && (ballXP < 80 + player1HalfSizex)&& (ballYP < player1P + player1HalfSizey + ballHalfSize) && (ballYP > player1P - player1HalfSizey - ballHalfSize)){ float curve = ballYP - player1P; ballYV += curve * 3; ballYV += player1V /2; ballXP = 80 - player1HalfSizex - 1; ballXV = -ballXV - 5; } if ((ballXP - ballHalfSize < -80 + player2HalfSizex) && (ballXP > -80 - player2HalfSizex) && (ballYP < player2P + player2HalfSizey + ballHalfSize) && (ballYP > player2P - player2HalfSizey - ballHalfSize)){ float curve = ballYP - player2P; ballYV += curve * 3; ballYV += player2V / 2; ballXP = -79 + player2HalfSizex; ballXV = -ballXV +5; } if (ballXP > 85 || ballXP < -85) { ballXP = 0; ballYP = 0; ballXV = ballXV < 0 ? 75 : -75; ballYV = 0; } drawRect(-80, player2P, player2HalfSizex, player2HalfSizey, 0xff0000); //player 2 drawRect(80, player1P, player1HalfSizex, player1HalfSizey, 0xff0000); //player 1 drawRect(ballXP, ballYP, ballHalfSize, ballHalfSize, 0xffffff); }
cd11e87949ff69fdbfe96ea3a7344360bef08af3
6f6a88ba519d9569b8bf17a1dd87537c24f28098
/Filters/src/VetoIncorrectHits_module.cc
b2b9d4d00d80ea9ba43c443af7dc0c8e52610084
[ "Apache-2.0" ]
permissive
Mu2e/Offline
728e3d9cd8144702aefbf35e98d2ddd65d113084
d4083c0223d31ca42e87288009aa127b56354855
refs/heads/main
2023-08-31T06:28:23.289967
2023-08-31T02:23:04
2023-08-31T02:23:04
202,804,692
12
73
Apache-2.0
2023-09-14T19:55:58
2019-08-16T22:03:57
C++
UTF-8
C++
false
false
11,340
cc
VetoIncorrectHits_module.cc
// Reject events with incorrect hits (initially, outside the given detector volume) // Heavily based on ReadBack_module // Krzysztof Genser, 2015 #include <string> #include <iostream> #include <cmath> // art includes. #include "fhiclcpp/ParameterSet.h" #include "art/Framework/Core/EDFilter.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Principal/Handle.h" #include "CLHEP/Units/SystemOfUnits.h" #include "messagefacility/MessageLogger/MessageLogger.h" #include "Offline/Mu2eUtilities/inc/TwoLinePCA.hh" #include "Offline/TrackerGeom/inc/Tracker.hh" #include "Offline/MCDataProducts/inc/StepPointMC.hh" #include "Offline/GeometryService/inc/GeomHandle.hh" #include "Offline/CosmicRayShieldGeom/inc/CosmicRayShield.hh" namespace mu2e { //================================================================ class VetoIncorrectHits : public art::EDFilter { public: explicit VetoIncorrectHits(const fhicl::ParameterSet& pset); virtual bool filter(art::Event& event) override; virtual void endJob() override; bool doTracker(const art::Event& event); bool doCRV(const art::Event& event); private: // Diagnostics printout level int diagLevel_; // Limit on number of events for which there will be full printout. int maxFullPrint_; // sould throw or not bool doNotThrow_; // Module label of the geant4 module that made the hits. std::string g4ModuleLabel_; // Name of the tracker StepPoint collection std::string trackerStepPoints_; // by how much the straw gas and hit relative positions can differ double strawHitPositionTolerance_; // Name of the CRSScintillatorBar(CRV) StepPoint collection std::string crvStepPoints_; // by how much the crv bar and hit relative positions can differ double crvHitPositionTolerance_; // End: run time parameters // Number of events processed. int nProcessed_; // a map of passed events per object std::map<std::string,int> passedEventsMap_; // a map of seen hits per object std::map<std::string,int> seenHitsMap_; // a map of passed hits per object std::map<std::string,int> passedHitsMap_; }; //================================================================ VetoIncorrectHits::VetoIncorrectHits(fhicl::ParameterSet const& pset) : art::EDFilter{pset}, // Run time parameters diagLevel_(pset.get<int>("diagLevel")), maxFullPrint_(pset.get<int>("maxFullPrint")), doNotThrow_(pset.get<bool>("doNotThrow")), g4ModuleLabel_(pset.get<std::string>("g4ModuleLabel")), trackerStepPoints_(pset.get<std::string>("trackerStepPoints")), strawHitPositionTolerance_(pset.get<double>("shPositionTolerance")), crvStepPoints_(pset.get<std::string>("crvStepPoints")), crvHitPositionTolerance_(pset.get<double>("crvPositionTolerance")), // End of run time parameters nProcessed_(0), passedEventsMap_(std::map<std::string,int>()), passedHitsMap_(std::map<std::string,int>()) { std::cout << __func__ << std::endl << pset.to_indented_string(); } //================================================================ bool VetoIncorrectHits::filter(art::Event& theEvent) { // will not modify the event, so force the const const art::Event& event = const_cast<art::Event&>(theEvent); bool passed = true; bool trackerResult = doTracker(event); bool crvResult = doCRV(event); // a simple && for now passed = trackerResult && crvResult; ++nProcessed_; return passed; } //================================================================ bool VetoIncorrectHits::doCRV(const art::Event& event){ bool passed = true; // Get a reference to CosmicRayShield (it contains crv) GeomHandle<CosmicRayShield> cosmicRayShieldGeomHandle; CosmicRayShield const& crv(*cosmicRayShieldGeomHandle); // Ask the event to give us a "handle" to the requested hits. art::Handle<StepPointMCCollection> hits; event.getByLabel(g4ModuleLabel_,crvStepPoints_,hits); // no hits means hits are "good" if ( ! hits.isValid() ) { return passed; } // Loop over all hits. for ( size_t i=0; i<hits->size(); ++i ){ ++seenHitsMap_[crvStepPoints_]; // Alias, used for readability. const StepPointMC& hit = (*hits)[i]; // Get the hit information. const CLHEP::Hep3Vector& pos = hit.position(); // Get the CRSScintillatorBar information: const CRSScintillatorBar& bar = crv.getBar( hit.barIndex() ); CLHEP::Hep3Vector const & mid = bar.getPosition(); CLHEP::Hep3Vector hitLocal = pos-mid; CLHEP::Hep3Vector hitLocalN = CLHEP::Hep3Vector(hitLocal.x()/bar.getHalfLengths()[0], hitLocal.y()/bar.getHalfLengths()[1], hitLocal.z()/bar.getHalfLengths()[2]); // Print out limited to the first few events. if ( diagLevel_ > 1 && nProcessed_ < maxFullPrint_ ){ // mf::LogInfo("GEOM") << "VetoIncorrectHits::doCRV" std::cout << "VetoIncorrectHits::doCRV" << " Event/Hit: " << event.id().event() << " as " << nProcessed_ << " " << i << " " << hit.trackId() << " " << hit.volumeId() << " " << bar.id() << " | " << pos << " " << mid << " " << (mid-pos) << " | " << hitLocalN << " | " << std::endl; } if ( ( std::abs(hitLocalN.x()) - 1. > crvHitPositionTolerance_ ) || ( std::abs(hitLocalN.y()) - 1. > crvHitPositionTolerance_ ) || ( std::abs(hitLocalN.z()) - 1. > crvHitPositionTolerance_ ) ) { passed = false; std::ostringstream os; os << __func__ << " Event " << event.id().event() << " as " << nProcessed_ << " Hit " << i << " " << pos << " " << " ouside the crv bar " << bar.id() << " inconsistent tracker geometry file? " << "; relative differences: " << std::abs(hitLocalN.x()) - 1. << ", " << std::abs(hitLocalN.y()) - 1. << ", " << std::abs(hitLocalN.z()) - 1. << "; tolerance : " << crvHitPositionTolerance_ << std::endl; if ( doNotThrow_ ) { if ( diagLevel_ > -1 && nProcessed_< maxFullPrint_ ){ // mf::LogWarning("GEOM") << os.str(); std::cout << os.str(); } } else { throw cet::exception("GEOM") << os.str(); } } passed && ++passedHitsMap_[crvStepPoints_]; } // end loop over hits. passed && ++passedEventsMap_[crvStepPoints_]; return passed; } // end doCRV //================================================================ bool VetoIncorrectHits::doTracker(const art::Event& event){ // Get a reference to the tracker // Throw exception if not successful. const Tracker& tracker = *GeomHandle<Tracker>(); bool passed = true; // Ask the event to give us a "handle" to the requested hits. art::Handle<StepPointMCCollection> hits; event.getByLabel(g4ModuleLabel_,trackerStepPoints_,hits); // no hits means hits are "good" if ( ! hits.isValid() ) { return passed; } // Loop over all hits. for ( size_t i=0; i<hits->size(); ++i ){ ++seenHitsMap_[trackerStepPoints_]; // Alias, used for readability. const StepPointMC& hit = (*hits)[i]; // Get the hit information. const CLHEP::Hep3Vector& pos = hit.position(); const CLHEP::Hep3Vector& mom = hit.momentum(); // Get the straw information: const Straw& straw = tracker.getStraw( hit.strawId() ); const CLHEP::Hep3Vector& mid = straw.getMidPoint(); const CLHEP::Hep3Vector& w = straw.getDirection(); // Compute an estimate of the drift distance. TwoLinePCA pca( mid, w, pos, mom); // Get the radius of the reference point in the local // coordinates of the straw double s = w.dot(pos-mid); CLHEP::Hep3Vector point = pos - (mid + s*w); double normPointMag = point.mag()/tracker.strawInnerRadius(); double normS = s/straw.halfLength(); if ( diagLevel_ > 1 && nProcessed_< maxFullPrint_ ){ std::cout << "VetoIncorrectHits::doTracker" << " Event " << event.id().event() << " as " << nProcessed_ << " normalized reference point - 1 : " << std::scientific << normPointMag - 1. << " normalized wire z of reference point - 1 : " << std::abs(normS) -1. << std::fixed << std::endl; } if ( ( normPointMag - 1. > strawHitPositionTolerance_ ) || ( std::abs(normS) - 1. > strawHitPositionTolerance_ ) ) { passed = false; std::ostringstream os; os << __func__ << " Event " << event.id().event() << " as " << nProcessed_ << " Hit " << i << " " << pos << " " << " ouside the straw " << straw.id() << " inconsistent tracker geometry file? " << "; radial difference: " << normPointMag - 1. << ", longitudinal difference: " << std::abs(normS) - 1. << "; tolerance : " << strawHitPositionTolerance_ << std::endl; if ( doNotThrow_ ) { if ( diagLevel_ > -1 && nProcessed_< maxFullPrint_ ){ // mf::LogWarning("GEOM") << os.str(); std::cout << os.str(); } } else { throw cet::exception("GEOM") << os.str(); } } passed && ++passedHitsMap_[trackerStepPoints_]; } // end loop over hits. passed && ++passedEventsMap_[trackerStepPoints_]; return passed; } //================================================================ void VetoIncorrectHits::endJob() { std::ostringstream os; os << "VetoIncorrectHits_module " << std::setw(20) << "summary: processed :" << " " << std::setw(20) << nProcessed_ << " events" << std::endl; // std::cout << " VetoIncorrectHits::endJob size of the map " << statMap_.size() << std::endl; for(const auto &i : passedEventsMap_) { os << "VetoIncorrectHits_module " << std::setw(20) << i.first << " : " << std::setw(20) << i.second << " events passed " << std::endl << "VetoIncorrectHits_module " << std::setw(20) << i.first << " : " << std::setw(20) << seenHitsMap_[i.first] << " hits processed " << std::endl << "VetoIncorrectHits_module " << std::setw(20) << i.first << " : " << std::setw(20) << passedHitsMap_[i.first] << " hits passed " << std::endl; } mf::LogInfo("Summary")<<os.str(); } //================================================================ } // namespace mu2e DEFINE_ART_MODULE(mu2e::VetoIncorrectHits)
3d2a75d9ba4259262b507998c8a0d8c672b99883
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/type_erasure/detail/macro.hpp
77b8f55d877cd405804de082f93b38a6605f7e0b
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
71
hpp
macro.hpp
#include "thirdparty/boost_1_55_0/boost/type_erasure/detail/macro.hpp"
80cbd9cd7f5bc33efe080186fbd94b80b761146f
db400f68d15e2af8ea2a499816fb63de320fadf4
/binary_trans/backend/main.cpp
65e36d672a15209f14a15066158c6e776185b55e
[]
no_license
Arv1k/2_sem
6803a737695981902de58af52e0e7ce75ad30f74
8c359f77d54539cfafba5a19505c608c1a24897c
refs/heads/master
2021-07-17T11:38:03.740943
2020-07-17T20:28:34
2020-07-17T20:28:34
185,005,386
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
main.cpp
#include "backend.h" int main(int argc, char* argv[]) { FILE* max = fopen(argv[1], "rb"); long num_symbols = Size(max); char* buffer = (char*) calloc(num_symbols + 1, sizeof(char)); fread(buffer, sizeof(char), num_symbols, max); fclose(max); Function funcs[10] = {}; make_std(buffer, funcs); for (int j = 0; j < 10; j++) if (funcs[j].tree_func) std_tree_dot(funcs[j].tree_func, argv[2]); make_elf(funcs, argv[3], argv[4]); for (int i = 0; i < 10; i++) if (funcs[i].tree_func) FunctionDtor(&(funcs[i])); free(buffer); }
3bd177c31cb8c2e3789cef7cb000679f4e226ab2
7d3c0c3718fbd433e9f1614aec34903200bfb112
/lista5/zad1/Structures.h
8bdb26cfbeb7c059a16a2f56b8f9396bfad44c94
[]
no_license
mateuszkochanek/algorithms-and-data-structures
aed7d1430f7e27ee47d338bba11d06a309171577
35be67a2bbeb8bc164353738db9be9c79d48b83f
refs/heads/main
2023-01-13T00:56:02.506502
2020-11-18T09:34:55
2020-11-18T09:34:55
306,346,574
0
0
null
null
null
null
UTF-8
C++
false
false
899
h
Structures.h
// // Created by erthax on 06.06.2020. // #ifndef ZAD1_STRUCTURES_H #define ZAD1_STRUCTURES_H #include <iostream> #include <vector> #include <cmath> struct Node{ Node(int index, int val): index(index), val(val) {} int index; int val; }; struct Element{ Element(int val, int p): value(val), p(p) {} int value; int p; }; class Queue { public: std::vector <Element*> heap; Queue(); int parent(int i); int left(int i); int right(int i); void heapify(int i); void insert(int x, int p); // działa na intach, po prostu mam je już w Nodzie żeby było przygotowane do pracy z grafami, nic to nie zmienia w praktyce bool empty(); void top(); void pop(); void priority(int x, int p); void decreaseKey(int i); void print(); }; class Graph { //zostanei zalmplementowany w przyszłych zadaniach }; #endif //ZAD1_STRUCTURES_H
c50cc1fe0c09be1e4a60b28fe70dcc81b71935fd
904441a3953ee970325bdb4ead916a01fcc2bacd
/src/sys/misc/static_node_array.h
6a72ba10f1695a4c438c6cd82535b187fafa6f65
[ "MIT" ]
permissive
itm/shawn
5a75053bc490f338e35ea05310cdbde50401fb50
49cb715d0044a20a01a19bc4d7b62f9f209df83c
refs/heads/master
2020-05-30T02:56:44.820211
2013-05-29T13:34:51
2013-05-29T13:34:51
5,994,638
16
4
null
2014-06-29T05:29:00
2012-09-28T08:33:42
C++
UTF-8
C++
false
false
3,010
h
static_node_array.h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef __SHAWN_SYS_MISC_STATIC_NODE_ARRAY_H #define __SHAWN_SYS_MISC_STATIC_NODE_ARRAY_H #include "sys/world.h" #include "sys/misc/node_change_listener.h" #include <cassert> namespace shawn { class Node; template<typename T> class StaticNodeArray : public NodeChangeListener { public: typedef T value_type; typedef T& reference; typedef const T& const_reference; typedef int size_type; StaticNodeArray( const World& w ) : world_ ( w ), size_ ( w.node_id_space_size() ), data_ ( new value_type[size_] ) {} ~StaticNodeArray() { delete [] data_; } inline reference operator [] ( const Node& v ) throw() { assert( world_.node_id_space_size() == size_ ); assert( v.id() >= 0 ); assert( v.id() < size_ ); return data_[v.id()]; } inline const_reference operator [] ( const Node& v ) const throw() { assert( world_.node_id_space_size() == size_ ); assert( v.id() >= 0 ); assert( v.id() < size_ ); return data_[v.id()]; } inline const_reference operator() ( const Node& v ) const throw() { return operator[](v); } inline void set( const Node& v, const_reference val ) throw() { operator[](v) = val; } inline const_reference get( const Node& v ) const throw() { return operator[](v); } inline void clear_to( const value_type& val ) throw() { std::fill( data_, data_+size_, val ); } virtual void node_added( Node& v ) throw() { ABORT_NOT_IMPLEMENTED; } virtual void node_removed( Node& v ) throw() { ABORT_NOT_IMPLEMENTED; } virtual void id_changed( int old_id, int new_id ) throw() { ABORT_NOT_IMPLEMENTED; } virtual bool invalidate( void ) throw() { return false; } private: const World& world_; int size_; value_type* data_; }; } #endif /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/sys/misc/static_node_array.h,v $ * Version $Revision: 42 $ * Date $Date: 2007-06-12 18:55:07 +0200 (Tue, 12 Jun 2007) $ *----------------------------------------------------------------------- * $Log: static_node_array.h,v $ *-----------------------------------------------------------------------*/
944b5670a31afe847537b0be96da5d9256d2e9c8
f51e79184a877c0d207b93fa6cc415b7d4afc151
/pr_10/Huffman.cpp
4af91dbf26503e527ab8606da8ef684708e2baf6
[]
no_license
UDQD/Cpp_MIREA
8c3acc2479c49a418d6a3fcbef010740221bd60b
4127b11662d166e3f1affa2de4dad6aebc45f150
refs/heads/master
2023-01-24T11:28:18.109259
2020-12-13T15:35:10
2020-12-13T15:35:10
294,608,273
0
0
null
null
null
null
UTF-8
C++
false
false
1,521
cpp
Huffman.cpp
#include "Huffman.h" #include <string> void Huffman::set_string(string s) { name = s; for (int i = 0; i < name.length(); i++) { if (los.find_ell(name[i]) == NULL) { los.add_ell(name[i]); } else { los.inc_ell(los.find_ell(name[i])); } } } void Huffman::make_tree() { tree = los; while (tree.count_true() > 1) { int number_of_true = tree.count_true(); int id_1 = tree.pare_min()[0]; int id_2 = tree.pare_min()[1]; Node *new_node = new Node; new_node->id = tree.get_id(); tree.inc_id(); tree.find_ell(id_1)->next_layer = new_node; tree.find_ell(id_2)->next_layer = new_node; tree.find_ell(id_1)->is_last_layer = false; tree.find_ell(id_2)->is_last_layer = false; tree.find_ell(id_1)->binar_code = 0; tree.find_ell(id_2)->binar_code = 1; new_node->number = tree.find_ell(id_1)->number + tree.find_ell(id_2)->number; tree.add_ell(new_node); } } void Huffman::compress() { for (int i = 0; i < name.length(); i++) { string simb_code = ""; Node *temp = tree.find_ell(name[i]); while (temp->binar_code != -1) { simb_code += to_string(temp->binar_code); temp = temp->next_layer; } string out = ""; for (int i = simb_code.length() - 1; i >= 0; i--) out += simb_code[i]; code += out; } } string Huffman::get_code() { return code; }
a90b59acfca5027686642de345bfe3a33b931b24
73c7fe37bf6af775cac65f58b81d2284dae117f2
/LeetCode/79. Word Search.cpp
062a92073543ee80e64b6b0d111805608aabe8f2
[]
no_license
atique7465/Competetive_programming
9ad03427682270e889f751b8a8e2e9ab3b309be2
840b8b9133f5b993730ecde186ef4d4fdfca9c46
refs/heads/master
2023-08-03T15:16:47.582253
2023-07-25T04:07:01
2023-07-25T04:07:01
186,138,178
3
0
null
null
null
null
UTF-8
C++
false
false
1,124
cpp
79. Word Search.cpp
class Solution { int r,c; public: bool exist(vector<vector<char>>& board, string word) { r = board.size(); c = board[0].size(); bool res = false; for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ if(board[i][j] == word[0]){ res = res | solve(i , j, 0, board, word); if(res) break; } } if(res) break; } return res; } bool solve(int i, int j, int pos, vector<vector<char>>& board, string word){ if(i < 0 || j < 0 || i >=r || j >= c || board[i][j] == '*' || board[i][j] != word[pos]) return false; if(pos == word.size() - 1) return true; bool res = false; char c = board[i][j]; board[i][j] = '*'; res = res | solve(i-1, j, pos+1, board, word); res = res | solve(i+1, j, pos+1, board, word); res = res | solve(i, j+1, pos+1, board, word); res = res | solve(i, j-1, pos+1, board, word); board[i][j] = c; return res; } };
b96ffb10f38664abbec9d2c98e049291fa9a66ea
92531c6349e1dca29adfbc4ad3de62d8ea8475ec
/9_semestre/POO_II/Ex_UdpSocket/FTP_Server/pacote.h
4bbaa5e9d126b713318ce1bdefbb23e535411f6d
[]
no_license
fhgrings/College
9856441afe084f0ceb5b2ff5287968686916acaf
7a5139063ed24867b36149bb95f7dc3a6e9ded9d
refs/heads/master
2021-07-07T23:08:04.323000
2020-08-02T03:48:59
2020-08-02T03:48:59
155,631,305
0
0
null
null
null
null
UTF-8
C++
false
false
704
h
pacote.h
#ifndef PACOTE_H #define PACOTE_H #pragma once #include <QString> class pacote { public: // construtores e destrutores pacote(); ~pacote(); void setNomeArquivo(QString nomeArquivo); QString getNomeArquivo(); void setConteudoArquivo(QString conteudoArquivo); QString getConteudoArquivo(); void setRemetente(QString remetente); QString getRemetente(); void setDestinatario(QString destinatario); QString getDestinatario(); bool empacotarMensagem(QString* mensagem); bool desempacotarMensagem(QString mensagem); private: QString nomeArquivo; QString conteudoArquivo; QString remetente; QString destinatario; }; #endif // PACOTE_H
ada90bee0c3845099212031de9a0291e9742fbda
170ff0c2065c2b907891a4bff305063d491adfcc
/matching/copmem/Hashes.h
d526948b1703e915f33dd24f7678a8901b041eef
[]
no_license
kowallus/PgRC
0c8bb0cc22a4272aaee89abf96adb404f3ff1dd8
668b4b2555893ebe8055e7a6bade96edc8916eea
refs/heads/master
2021-06-07T04:25:54.864486
2021-05-27T11:08:26
2021-05-27T11:08:26
144,006,868
9
2
null
null
null
null
UTF-8
C++
false
false
1,861
h
Hashes.h
#pragma once #ifndef _HASHES_H #define _HASHES_H #include <cstdint> #define XXH_INLINE_ALL #define XXH_PRIVATE_API #include "xxhash.h" #include "metrohash64.h" #include "city.h" template <size_t K> inline std::uint32_t xxhash32(const char* key) { XXH32_hash_t result = XXH32((const void*)key, K, (uint32_t) 9876543210UL); return (std::uint32_t)(result); } template <size_t K> inline std::uint32_t xxhash64(const char* key) { XXH64_hash_t result = XXH64((const void*)key, K, 9876543210UL); return (std::uint32_t)(result); } unsigned long long result = 0ULL; template <size_t K> inline std::uint32_t metroHash64(const char* key) { MetroHash64::Hash((const uint8_t*)key, K, (uint8_t*)(&result), 9876543210ULL); return (std::uint32_t)(result); } template <size_t K> inline std::uint32_t cityHash64(const char* key) { return (std::uint32_t)(CityHash64(key, K)); } // based on http://www.amsoftware.narod.ru/algo2.html template <size_t K> inline std::uint32_t maRushPrime1HashSimplified(const char *str) { std::uint64_t hash = K; for (std::uint32_t j = 0; j < K/4; ) { std::uint32_t k; memcpy(&k, str, 4); k += j++; hash ^= k; hash *= 171717; str += 4; } return (std::uint32_t)(hash); } const uint32_t SPARSIFY_MASK_A = 0x00FFFFFF; const int SPARSIFY_MASK_A_COUNT = 3; const uint32_t SPARSIFY_MASK_B = 0x0000FFFF; // based on http://www.amsoftware.narod.ru/algo2.html template <size_t K> inline std::uint32_t maRushPrime1HashSparsified(const char *str) { std::uint64_t hash = K; std::uint32_t j = 0; std::uint32_t k; while (j < SPARSIFY_MASK_A_COUNT) { memcpy(&k, str, 4); k &= SPARSIFY_MASK_A; k += j++; hash ^= k; hash *= 171717; str += 4; } while (j < K/4) { memcpy(&k, str, 4); k &= SPARSIFY_MASK_B; k += j++; hash ^= k; hash *= 171717; str += 4; } return (std::uint32_t)(hash); } #endif //!_HASHES_H
38141ba9c7e612fb4250defcfdb1e1b4a146bc70
bdd1f460bdeb99a1f6d1a2d5173dc10a4970739d
/snow_logger/snow_logger.ino
1db465497b4b1cbf7651dd0d9de166e1979f6d6a
[ "MIT" ]
permissive
caternuson/Snow-Temperature-Profiler
90fb0933ccf21ef6fd43767afcd2dd556ab8af34
3eab5304a122c77c0abaebe01c2481d728ad56db
refs/heads/master
2021-08-30T05:12:26.314360
2017-12-16T01:42:30
2017-12-16T01:42:30
114,318,640
0
0
null
null
null
null
UTF-8
C++
false
false
5,628
ino
snow_logger.ino
//-------------------------------------------------------------------------------------- // Snow Logger // // 2017-12-14 // Carter Nelson //-------------------------------------------------------------------------------------- #include <SD.h> #include <SPI.h> #include <OneWire.h> #include <DallasTemperature.h> #include <Adafruit_SSD1306.h> #include "oled_stuff.h" #define ONEWIRE_PIN 18 #define CARDCS 4 #define MAX_FILES 999 #define MAX_DATA_POINTS 37 #define DEBOUNCE 250 #define DISPLAY_RATE 100 Adafruit_SSD1306 oled = Adafruit_SSD1306(); OneWire onewireBus(ONEWIRE_PIN); DallasTemperature ds18(&onewireBus); File dataFile; float temperature; int dataFileCounter, dataPointCounter; int lastUpdate; char* fileName = "SNOWXXX.DAT"; enum mode { STOPPED, LOGGING, } currentMode = STOPPED; //-------------------------------------------------------------------------------------- // S E T U P //-------------------------------------------------------------------------------------- void setup() { //while (!Serial); Serial.begin(9600); Serial.println(F("Snow Logger ****")); initStuff(); Serial.print(F("Counting files...")); countFiles(SD.open("/"), 0); Serial.println(dataFileCounter); } //-------------------------------------------------------------------------------------- // L O O P //-------------------------------------------------------------------------------------- void loop() { // Get current temperature. temperature = getTemperature(); // Start logging / take a data point if (buttonA()) { oled.setCursor(50,18); oled.print("o"); oled.display(); if (currentMode != LOGGING) { openNewFile(dataFileCounter++); } currentMode = LOGGING; Serial.print(dataPointCounter); Serial.print(" "); Serial.println(temperature); dataFile.print(dataPointCounter); dataFile.print(" "); dataFile.println(temperature); dataPointCounter++; if (dataPointCounter >= MAX_DATA_POINTS) { stopLogging(); } delay(DEBOUNCE); } // Abort if (buttonC() && currentMode == LOGGING) { stopLogging(); } // Update display if (millis() - lastUpdate > DISPLAY_RATE) { updateDisplay(); } } //-------------------------------------------------------------------------------------- void stopLogging() { Serial.println("Closing file."); closeFile(); dataPointCounter = 0; currentMode = STOPPED; } //-------------------------------------------------------------------------------------- void openNewFile(int counter) { // Not enough room for sprintf!!! fileName[4] = 0x30 + dataFileCounter / 100 % 10; fileName[5] = 0x30 + dataFileCounter / 10 % 10; fileName[6] = 0x30 + dataFileCounter % 10; Serial.print("Opening file..."); Serial.println(fileName); dataFile = SD.open(fileName, FILE_WRITE); } //-------------------------------------------------------------------------------------- void closeFile() { dataFile.flush(); dataFile.close(); } //-------------------------------------------------------------------------------------- void updateDisplay() { oled.clearDisplay(); // // Stuff on the right side // oled.setCursor(65,0); oled.print(temperature); oled.setCursor(65,18); oled.print(dataFileCounter); // // Mode base info // oled.setCursor(0,0); switch (currentMode) { case STOPPED: oled.print("PRESS"); oled.setCursor(0,18); oled.print(" A"); break; case LOGGING: oled.print("POINT"); oled.setCursor(0,18); oled.print(dataPointCounter); break; default: oled.print("????"); } oled.display(); } //-------------------------------------------------------------------------------------- void initStuff() { // // OLED // oled.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Splash screen for warm fuzzy oled.display(); delay(1000); oled.clearDisplay(); oled.display(); oled.setTextSize(2); oled.setTextColor(WHITE); oled.setCursor(0,0); // // Buttons // pinMode(BUTTON_A, INPUT_PULLUP); pinMode(BUTTON_B, INPUT_PULLUP); pinMode(BUTTON_C, INPUT_PULLUP); // // SD Card // if (!SD.begin(CARDCS)) { Serial.println("SD failed, or not present"); oled.print("SD FAILED"); oled.display(); while (1); } // // Misc. // dataFileCounter = 0; dataPointCounter = 0; lastUpdate = millis(); } //-------------------------------------------------------------------------------------- float getTemperature() { ds18.requestTemperatures(); return ds18.getTempFByIndex(0); } //-------------------------------------------------------------------------------------- void countFiles(File dir, int level) { while (true) { File entry = dir.openNextFile(); if (!entry) return; if (entry.isDirectory()) { // Recursive call to scan next dir level countFiles(entry, level + 1); } else { // Only count files in root dir if (level == 0) { dataFileCounter++; } } entry.close(); // Stop scanning if we hit max if (dataFileCounter >= MAX_FILES) return; } } //-------------------------------------------------------------------------------------- bool buttonA() { return ! digitalRead(BUTTON_A); } //-------------------------------------------------------------------------------------- bool buttonB() { return ! digitalRead(BUTTON_B); } //-------------------------------------------------------------------------------------- bool buttonC() { return ! digitalRead(BUTTON_C); }
1ae985d2ce4f270509bed96a7018458e570d13c5
79ad09b0d27ca0f825bcb54dc9e7a455926c6f57
/SVFEngine/SVFEngine/mathematics.h
a883ef918a9bbe56c0c5be534847751ba12eb5ce
[ "Apache-2.0" ]
permissive
safiar/SVFEngine
a9f0cbed517c50028e16536b0ffb3e47de8a28f9
5038143a0f369e88dd4fab364a0c22f7729217b3
refs/heads/master
2021-06-29T23:59:35.291815
2020-09-12T12:36:31
2020-09-12T12:36:31
131,051,362
1
0
Apache-2.0
2019-06-24T09:58:18
2018-04-25T19:02:18
C++
UTF-8
C++
false
false
111,237
h
mathematics.h
// ----------------------------------------------------------------------- // // // MODULE : mathematics.h // // PURPOSE : Вспомогательные математические функции и определения // // CREATED : SavF. ⚡ Savenkov Filipp A. (2017) // // ----------------------------------------------------------------------- // #ifndef _MATHS_H #define _MATHS_H #include <stdio.h> #include <string.h> #include <cmath> #include "helper.h" using namespace SAVFGAME; struct D3DXMATRIX; // DX9 struct D3DXVECTOR4; // DX9 #ifndef FLOAT #define FLOAT float #endif #ifndef BYTE #define BYTE unsigned char #endif #ifndef DWORD #define DWORD unsigned long #endif typedef double Int3D; #define ANGLES_ISTEP 100 // 1 / STEP #define ANGLES_NUM 36000 // 360 * ISTEP #define ANGLES_STEP 0.01f // 1 / ISTEP #define MathPI 3.141592654f // 3.14159265358979323846 #define MathPI2 6.283185307f // 6.28318530717958647692 #define MathSqrt2 1.414213538f // sqrt(2) == 1.4142135623730950488016887242097 #define MathSqrt2inv 0.707106769f // 1 / sqrt(2) == 0.70710678118654752440 #define TORADIANS(x) (x*(MathPI/180.0f)) #define TODEGREES(x) (x*(180.0f/MathPI)) #define COLORBYTE(x) (min(0xFF,static_cast<int>(0xFF*x))) // float color (0.0f..1.0f) to byte (00..FF) #define COLORFLOAT(x) (static_cast<float>(min(0xFF,x)) * (1.f/255)) // byte color (00..FF) to float (0.0f..1.0f) #define _VECSET(from,to) { to.x = from.x; to.y = from.y; to.z = from.z; } #define _VECSET2(from,to) { to.x = from.x; to.y = from.y; } #define _VECSET3(from,to) { to.x = from.x; to.y = from.y; to.z = from.z; } #define _VECSET4(from,to) { to.x = from.x; to.y = from.y; to.z = from.z; to.w = from.w; } #define _MATSET(from,to) { to._11 = from._11; to._12 = from._12; to._13 = from._13; to._14 = from._14; } \ { to._21 = from._21; to._22 = from._22; to._23 = from._23; to._24 = from._24; } \ { to._31 = from._31; to._32 = from._32; to._33 = from._33; to._34 = from._34; } \ { to._41 = from._41; to._42 = from._42; to._43 = from._43; to._44 = from._44; } #define MATH3DVEC3 MATH3DVEC #define COLORVEC3 MATH3DVEC #define COLORVEC MATH3DVEC4 #define COLORVEC4 MATH3DVEC4 #define PRECISION 0.001f // default float compare precision #define MATSIZE 16*sizeof(float) #define X_AXIS 1,0,0 #define Y_AXIS 0,1,0 #define Z_AXIS 0,0,1 #define OX_VEC MATH3DVEC(X_AXIS) #define OY_VEC MATH3DVEC(Y_AXIS) #define OZ_VEC MATH3DVEC(Z_AXIS) ////////////////////// QUICK SHARED CODE ////////////////////// // FLOAT x,y,z position ; ret MT #define MATH_TRANSLATE_MATRIX(x,y,z) MATH3DMATRIX MT; \ MT._41 = x; \ MT._42 = y; \ MT._43 = z; // FLOAT x,y,z,w QUATERNION ; ret MR #define MATH_ROTATE_MATRIX(x,y,z,w) MATH3DMATRIX MR; \ float QXX = x * x; float QXW = x * w; float QXY = x * y; \ float QYY = y * y; float QYW = y * w; float QXZ = x * z; \ float QZZ = z * z; float QZW = z * w; float QYZ = y * z; \ \ MR._11 = 1.0f - 2.0f * ( QYY + QZZ ); \ MR._12 = 2.0f * ( QXY + QZW ); \ MR._13 = 2.0f * ( QXZ - QYW ); \ MR._21 = 2.0f * ( QXY - QZW ); \ MR._22 = 1.0f - 2.0f * ( QXX + QZZ ); \ MR._23 = 2.0f * ( QYZ + QXW ); \ MR._31 = 2.0f * ( QXZ + QYW ); \ MR._32 = 2.0f * ( QYZ - QXW ); \ MR._33 = 1.0f - 2.0f * ( QXX + QYY ); // FLOAT x,y,z scale ; ret MS #define MATH_SCALE_MATRIX(x,y,z) MATH3DMATRIX MS; \ MS._11 = x; \ MS._22 = y; \ MS._33 = z; ////////////////////// QUICK SHARED CODE ////////////////////// // FLOAT axis X angle ; ret MRx #define MATH_ROTATE_MATRIX_X(ax) MATH3DMATRIX MRx; \ MRx._22 = CTAB::cosA(ax); MRx._33 = MRx._22; \ MRx._23 = CTAB::sinA(ax); MRx._32 = -MRx._23; // FLOAT axis Y angle ; ret MRy #define MATH_ROTATE_MATRIX_Y(ay) MATH3DMATRIX MRy; \ MRy._11 = CTAB::cosA(ay); MRy._33 = MRy._11; \ MRy._31 = CTAB::sinA(ay); MRy._13 = -MRy._31; // FLOAT axis Z angle ; ret MRz #define MATH_ROTATE_MATRIX_Z(az) MATH3DMATRIX MRz; \ MRz._11 = CTAB::cosA(az); MRz._22 = MRz._11; \ MRz._12 = CTAB::sinA(az); MRz._21 = -MRz._12; // FLOAT x,y,z angles ; ret MRz #define MATH_ROTATE_MATRIX_A(ax,ay,az) MATH_ROTATE_MATRIX_X(ax) \ MATH_ROTATE_MATRIX_Y(ay) \ MATH_ROTATE_MATRIX_Z(az) \ MRz *= MRx; \ MRz *= MRy; //#define _INVSQRT(x) 1 / sqrt(x) #define _INVSQRT(x) InvSqrt(x) /////////////////////////////////////////////////////////////// namespace SAVFGAME { class CTAB // Таблицы констант для быстрого вызова { private: static float sinAngleTab [ANGLES_NUM]; static float cosAngleTab [ANGLES_NUM]; static float tanAngleTab [ANGLES_NUM]; static bool isInit; public: static void Init(); static float sinA(float); static float cosA(float); static float tanA(float); static float sinR(float); static float cosR(float); static float tanR(float); private: virtual void __DO_NOT_CREATE_OBJECT_OF_THIS_CLASS() = 0; }; // out_f = 1 / sqrt(in_f) inline float __fastcall InvSqrt(float in_f) { #define __ONE__ ((uint32)(0x3F800000)) uint32 tmp = ((__ONE__ << 1) + __ONE__ - *(uint32*)& in_f) >> 1; float f = *(float*) & tmp; return f * (1.47f - 0.47f * in_f * f * f); #undef __ONE__ } struct MATH3DMATRIX { MATH3DMATRIX(): _11(1), _12(0), _13(0), _14(0), _21(0), _22(1), _23(0), _24(0), _31(0), _32(0), _33(1), _34(0), _41(0), _42(0), _43(0), _44(1) {}; // Identity matrix (Единичная матрица) MATH3DMATRIX(const float x, const float y, const float z, const byte Nx, const byte Ny, const byte Nz) : _11(1), _12(0), _13(0), _14(0), _21(0), _22(1), _23(0), _24(0), _31(0), _32(0), _33(1), _34(0), _41(0), _42(0), _43(0), _44(1) { switch(Nx) { case 11: _11=x; break; case 12: _12=x; break; case 13: _13=x; break; case 14: _14=x; break; case 21: _21=x; break; case 22: _22=x; break; case 23: _23=x; break; case 24: _24=x; break; case 31: _31=x; break; case 32: _32=x; break; case 33: _33=x; break; case 34: _34=x; break; case 41: _41=x; break; case 42: _42=x; break; case 43: _43=x; break; case 44: _44=x; break; } switch(Ny) { case 11: _11=y; break; case 12: _12=y; break; case 13: _13=y; break; case 14: _14=y; break; case 21: _21=y; break; case 22: _22=y; break; case 23: _23=y; break; case 24: _24=y; break; case 31: _31=y; break; case 32: _32=y; break; case 33: _33=y; break; case 34: _34=y; break; case 41: _41=y; break; case 42: _42=y; break; case 43: _43=y; break; case 44: _44=y; break; } switch(Nz) { case 11: _11=z; break; case 12: _12=z; break; case 13: _13=z; break; case 14: _14=z; break; case 21: _21=z; break; case 22: _22=z; break; case 23: _23=z; break; case 24: _24=z; break; case 31: _31=z; break; case 32: _32=z; break; case 33: _33=z; break; case 34: _34=z; break; case 41: _41=z; break; case 42: _42=z; break; case 43: _43=z; break; case 44: _44=z; break; } }; MATH3DMATRIX operator * (const MATH3DMATRIX & M) const { MATH3DMATRIX out; // for (i=0; i<4; i++) for (j=0; j<4; j++) [i][j] = [i][0]*[0][j] + [i][1]*[1][j] + [i][2]*[2][j] + [i][3]*[3][j] out._11 = (_11 * M._11) + (_12 * M._21) + (_13 * M._31) + (_14 * M._41) ; out._12 = (_11 * M._12) + (_12 * M._22) + (_13 * M._32) + (_14 * M._42) ; out._13 = (_11 * M._13) + (_12 * M._23) + (_13 * M._33) + (_14 * M._43) ; out._14 = (_11 * M._14) + (_12 * M._24) + (_13 * M._34) + (_14 * M._44) ; out._21 = (_21 * M._11) + (_22 * M._21) + (_23 * M._31) + (_24 * M._41) ; out._22 = (_21 * M._12) + (_22 * M._22) + (_23 * M._32) + (_24 * M._42) ; out._23 = (_21 * M._13) + (_22 * M._23) + (_23 * M._33) + (_24 * M._43) ; out._24 = (_21 * M._14) + (_22 * M._24) + (_23 * M._34) + (_24 * M._44) ; out._31 = (_31 * M._11) + (_32 * M._21) + (_33 * M._31) + (_34 * M._41) ; out._32 = (_31 * M._12) + (_32 * M._22) + (_33 * M._32) + (_34 * M._42) ; out._33 = (_31 * M._13) + (_32 * M._23) + (_33 * M._33) + (_34 * M._43) ; out._34 = (_31 * M._14) + (_32 * M._24) + (_33 * M._34) + (_34 * M._44) ; out._41 = (_41 * M._11) + (_42 * M._21) + (_43 * M._31) + (_44 * M._41) ; out._42 = (_41 * M._12) + (_42 * M._22) + (_43 * M._32) + (_44 * M._42) ; out._43 = (_41 * M._13) + (_42 * M._23) + (_43 * M._33) + (_44 * M._43) ; out._44 = (_41 * M._14) + (_42 * M._24) + (_43 * M._34) + (_44 * M._44) ; return out; }; //*/ MATH3DMATRIX& operator *= (const MATH3DMATRIX & M) { // for (i=0; i<4; i++) for (j=0; j<4; j++) [i][j] = [i][0]*[0][j] + [i][1]*[1][j] + [i][2]*[2][j] + [i][3]*[3][j] float f0, f1, f2, f3; f0 = _11; f1 = _12; f2 = _13; f3 = _14; _11 = (f0 * M._11) + (f1 * M._21) + (f2 * M._31) + (f3 * M._41); _12 = (f0 * M._12) + (f1 * M._22) + (f2 * M._32) + (f3 * M._42); _13 = (f0 * M._13) + (f1 * M._23) + (f2 * M._33) + (f3 * M._43); _14 = (f0 * M._14) + (f1 * M._24) + (f2 * M._34) + (f3 * M._44); f0 = _21; f1 = _22; f2 = _23; f3 = _24; _21 = (f0 * M._11) + (f1 * M._21) + (f2 * M._31) + (f3 * M._41); _22 = (f0 * M._12) + (f1 * M._22) + (f2 * M._32) + (f3 * M._42); _23 = (f0 * M._13) + (f1 * M._23) + (f2 * M._33) + (f3 * M._43); _24 = (f0 * M._14) + (f1 * M._24) + (f2 * M._34) + (f3 * M._44); f0 = _31; f1 = _32; f2 = _33; f3 = _34; _31 = (f0 * M._11) + (f1 * M._21) + (f2 * M._31) + (f3 * M._41); _32 = (f0 * M._12) + (f1 * M._22) + (f2 * M._32) + (f3 * M._42); _33 = (f0 * M._13) + (f1 * M._23) + (f2 * M._33) + (f3 * M._43); _34 = (f0 * M._14) + (f1 * M._24) + (f2 * M._34) + (f3 * M._44); f0 = _41; f1 = _42; f2 = _43; f3 = _44; _41 = (f0 * M._11) + (f1 * M._21) + (f2 * M._31) + (f3 * M._41); _42 = (f0 * M._12) + (f1 * M._22) + (f2 * M._32) + (f3 * M._42); _43 = (f0 * M._13) + (f1 * M._23) + (f2 * M._33) + (f3 * M._43); _44 = (f0 * M._14) + (f1 * M._24) + (f2 * M._34) + (f3 * M._44); return *this; }; MATH3DMATRIX operator + (const MATH3DMATRIX & M) const { MATH3DMATRIX out; out._11 = (_11 + M._11); out._12 = (_12 + M._12); out._13 = (_13 + M._13); out._14 = (_14 + M._14); out._21 = (_21 + M._21); out._22 = (_22 + M._22); out._23 = (_23 + M._23); out._24 = (_24 + M._24); out._31 = (_31 + M._31); out._32 = (_32 + M._32); out._33 = (_33 + M._33); out._34 = (_34 + M._34); out._41 = (_41 + M._41); out._42 = (_42 + M._42); out._43 = (_43 + M._43); out._44 = (_44 + M._44); return out; }; //*/ MATH3DMATRIX& operator += (const MATH3DMATRIX & M) { _11 = (_11 + M._11); _12 = (_12 + M._12); _13 = (_13 + M._13); _14 = (_14 + M._14); _21 = (_21 + M._21); _22 = (_22 + M._22); _23 = (_23 + M._23); _24 = (_24 + M._24); _31 = (_31 + M._31); _32 = (_32 + M._32); _33 = (_33 + M._33); _34 = (_34 + M._34); _41 = (_41 + M._41); _42 = (_42 + M._42); _43 = (_43 + M._43); _44 = (_44 + M._44); return *this; }; MATH3DMATRIX operator - (const MATH3DMATRIX & M) const { MATH3DMATRIX out; out._11 = (_11 - M._11); out._12 = (_12 - M._12); out._13 = (_13 - M._13); out._14 = (_14 - M._14); out._21 = (_21 - M._21); out._22 = (_22 - M._22); out._23 = (_23 - M._23); out._24 = (_24 - M._24); out._31 = (_31 - M._31); out._32 = (_32 - M._32); out._33 = (_33 - M._33); out._34 = (_34 - M._34); out._41 = (_41 - M._41); out._42 = (_42 - M._42); out._43 = (_43 - M._43); out._44 = (_44 - M._44); return out; }; //*/ MATH3DMATRIX& operator -= (const MATH3DMATRIX & M) { _11 = (_11 - M._11); _12 = (_12 - M._12); _13 = (_13 - M._13); _14 = (_14 - M._14); _21 = (_21 - M._21); _22 = (_22 - M._22); _23 = (_23 - M._23); _24 = (_24 - M._24); _31 = (_31 - M._31); _32 = (_32 - M._32); _33 = (_33 - M._33); _34 = (_34 - M._34); _41 = (_41 - M._41); _42 = (_42 - M._42); _43 = (_43 - M._43); _44 = (_44 - M._44); return *this; }; D3DXMATRIX* D3DCAST() { return reinterpret_cast<D3DXMATRIX*>(this); } operator D3DXMATRIX*() { return reinterpret_cast <D3DXMATRIX*> (this); } operator float*() { return reinterpret_cast <float*> (this); } void _printf() { printf("\n%f %f %f %f" "\n%f %f %f %f" "\n%f %f %f %f" "\n%f %f %f %f\n", _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44); } void _transpose() { // const auto matsz = MATSIZE; // float temp[4][4]; // for(int i=0; i<4; i++) // for(int j=0; j<4; j++) // temp[i][j] = _[j][i]; // memcpy(_,temp,matsz); _SWAP(_13, _31); _SWAP(_21, _12); _SWAP(_32, _23); _SWAP(_41, _14); _SWAP(_42, _24); _SWAP(_43, _34); } void _default() { _11=1; _12=0; _13=0; _14=0; _21=0; _22=1; _23=0; _24=0; _31=0; _32=0; _33=1; _34=0; _41=0; _42=0; _43=0; _44=1; } union { struct { FLOAT _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44; }; FLOAT _[4][4]; }; }; struct MATH3DVEC { MATH3DVEC() : x(0), y(0), z(0) { }; MATH3DVEC(const float _x, const float _y, const float _z) : x(_x), y(_y), z(_z) { }; MATH3DVEC operator * (const float f) const { MATH3DVEC vec(x*f, y*f, z*f); return vec; }; MATH3DVEC operator - (const float f) const { MATH3DVEC vec(x-f, y-f, z-f); return vec; }; MATH3DVEC operator + (const float f) const { MATH3DVEC vec(x+f, y+f, z+f); return vec; }; MATH3DVEC& operator *= (const float f) { x *= f; y *= f; z *= f; return *this; }; MATH3DVEC& operator -= (const float f) { x -= f; y -= f; z -= f; return *this; }; MATH3DVEC& operator += (const float f) { x += f; y += f; z += f; return *this; }; MATH3DVEC operator - (const MATH3DVEC & v) const { MATH3DVEC vec(x-v.x, y-v.y, z-v.z); return vec; }; MATH3DVEC operator + (const MATH3DVEC & v) const { MATH3DVEC vec(x+v.x, y+v.y, z+v.z); return vec; }; //>> простое перемножение компонент MATH3DVEC operator * (const MATH3DVEC & v) const { MATH3DVEC vec(x*v.x, y*v.y, z*v.z); return vec; } MATH3DVEC& operator -= (const MATH3DVEC & v) { x -= v.x; y -= v.y; z -= v.z; return *this; }; MATH3DVEC& operator += (const MATH3DVEC & v) { x += v.x; y += v.y; z += v.z; return *this; }; //>> простое перемножение компонент MATH3DVEC& operator *= (const MATH3DVEC & v) { x *= v.x; y *= v.y; z *= v.z; return *this; } bool operator == (const MATH3DVEC & v) const { if (x >= v.x - PRECISION && x <= v.x + PRECISION && y >= v.y - PRECISION && y <= v.y + PRECISION && z >= v.z - PRECISION && z <= v.z + PRECISION ) return true; return false; }; bool operator != (const MATH3DVEC & v) const { if (x >= v.x - PRECISION && x <= v.x + PRECISION && y >= v.y - PRECISION && y <= v.y + PRECISION && z >= v.z - PRECISION && z <= v.z + PRECISION ) return false; return true; }; bool operator >= (const MATH3DVEC & v) const { if (x >= v.x - PRECISION && y >= v.y - PRECISION && z >= v.z - PRECISION ) return true; return false; }; bool operator <= (const MATH3DVEC & v) const { if (x <= v.x + PRECISION && y <= v.y + PRECISION && z <= v.z + PRECISION ) return true; return false; }; bool operator > (const MATH3DVEC & v) const { if (x > v.x - PRECISION && y > v.y - PRECISION && z > v.z - PRECISION ) return true; return false; }; bool operator < (const MATH3DVEC & v) const { if (x < v.x + PRECISION && y < v.y + PRECISION && z < v.z + PRECISION ) return true; return false; }; bool operator ! () const { if (*this != MATH3DVEC()) return false; return true; }; bool operator && (const MATH3DVEC & v) const { if (*this != MATH3DVEC() && v != MATH3DVEC() ) return true; return false; }; bool operator || (const MATH3DVEC & v) const { if (*this != MATH3DVEC() || v != MATH3DVEC() ) return true; return false; }; MATH3DVEC operator * (const MATH3DMATRIX & M) const { MATH3DVEC vec; float norm = (x * M._14) + (y * M._24) + (z * M._34) + M._44; if (norm) { vec.x = ((x * M._11) + (y * M._21) + (z * M._31) + M._41) / norm; vec.y = ((x * M._12) + (y * M._22) + (z * M._32) + M._42) / norm; vec.z = ((x * M._13) + (y * M._23) + (z * M._33) + M._43) / norm; } else { vec.x = 0; vec.y = 0; vec.z = 0; } return vec; }//*/ MATH3DVEC& operator *= (const MATH3DMATRIX & M) { float _x, _y, _z; float norm = (x * M._14) + (y * M._24) + (z * M._34) + M._44; if (norm) { _x = ((x * M._11) + (y * M._21) + (z * M._31)) / norm; _y = ((x * M._12) + (y * M._22) + (z * M._32)) / norm; _z = ((x * M._13) + (y * M._23) + (z * M._33)) / norm; } else { _x = 0; _y =0; _z = 0; } x = _x; y = _y; z = _z; return *this; } template <class TYPE> MATH3DVEC& _set(const TYPE & src) { x = src.x; y = src.y; z = src.z; return *this; } operator float*() { return reinterpret_cast <float*> (this); } void _printf() { printf("\n%f %f %f", x, y, z); } void _normalize() { float norm = x*x + y*y + z*z; if (!norm) return; float mod = _INVSQRT(norm); x *= mod; y *= mod; z *= mod; } void _normalize_check() { float norm = x*x + y*y + z*z; if (!norm) return; if ( norm > (1.000f + PRECISION) || norm < (1.000f - PRECISION) ) { float mod = _INVSQRT(norm); x *= mod; y *= mod; z *= mod; } } void _default() { x = y = z = 0; } union { struct { float x, y, z; }; // coordinate-обращение struct { float ax, ay, az; }; // angle-обращение struct { float sx, sy, sz; }; // scale-обращение struct { float nx, ny, nz; }; // normal-обращение struct { float tx, ty, tz; }; // tangent-обращение struct { float bx, by, bz; }; // binormal-обращение struct { float u, v, w; }; // texture1_UV-обращение struct { float u2, v2, w2; }; // texture2_UV-обращение struct { float u3, v3, w3; }; // texture3_UV-обращение struct { float r, g, b; }; // color-обращение struct { float A, B, C; }; // plane-обращение float _[3]; }; }; struct MATH3DVEC4 { MATH3DVEC4() : x(0), y(0), z(0), w(0) {}; MATH3DVEC4(const float _x, const float _y, const float _z) : x(_x), y(_y), z(_z), w(0) {}; MATH3DVEC4(const float _x, const float _y, const float _z, const float _w) : x(_x), y(_y), z(_z), w(_w) {}; MATH3DVEC4 operator * (const float f) const { MATH3DVEC4 vec(x*f, y*f, z*f, w*f); return vec; }; MATH3DVEC4 operator - (const MATH3DVEC4 & v) const { MATH3DVEC4 vec(x-v.x, y-v.y, z-v.z, w-v.w); return vec; }; MATH3DVEC4 operator + (const MATH3DVEC4 & v) const { MATH3DVEC4 vec(x+v.x, y+v.y, z+v.z, w+v.w); return vec; }; bool operator == (const MATH3DVEC4 & v) const { if (x >= v.x - PRECISION && x <= v.x + PRECISION && y >= v.y - PRECISION && y <= v.y + PRECISION && z >= v.z - PRECISION && z <= v.z + PRECISION && w >= v.w - PRECISION && w <= v.w + PRECISION ) return true; return false; }; bool operator != (const MATH3DVEC4 & v) const { if (x >= v.x - PRECISION && x <= v.x + PRECISION && y >= v.y - PRECISION && y <= v.y + PRECISION && z >= v.z - PRECISION && z <= v.z + PRECISION && w >= v.w - PRECISION && w <= v.w + PRECISION ) return false; return true; }; template <class TYPE> MATH3DVEC4& _set(const TYPE & src) { x = src.x; y = src.y; z = src.z; w = src.w; return *this; } operator float*() { return reinterpret_cast <float*> (this); } // COLOR argb uint32 operator operator uint32() const { uint32 argb = 0; argb |= COLORBYTE(a) << 24; argb |= COLORBYTE(r) << 16; argb |= COLORBYTE(g) << 8; argb |= COLORBYTE(b); return argb; } void _printf() { printf("\n%f %f %f %f", x, y, z, w); } void _normalize() { float norm = x*x + y*y + z*z + w*w; if (!norm) return; float mod = _INVSQRT(norm); x *= mod; y *= mod; z *= mod; w *= mod; } void _normalize_check() { float norm = x*x + y*y + z*z + w*w; if (!norm) return; if (norm > (1.000f + PRECISION) || norm < (1.000f - PRECISION)) { float mod = _INVSQRT(norm); x *= mod; y *= mod; z *= mod; w *= mod; } } void _default() { x = y = z = w = 0; } union { struct { float x, y, z, w; }; struct { float r, g, b, a; }; struct { float A, B, C, D; }; float _[4]; }; }; struct MATH3DVEC2 { MATH3DVEC2() : x(0), y(0) {}; MATH3DVEC2(const float _x, const float _y) : x(_x), y(_y) {}; template <class TYPE> MATH3DVEC2& _set(const TYPE & src) { x = src.x; y = src.y; return *this; } operator float*() { return reinterpret_cast<FLOAT*>(this); } void _printf() { printf("\n%f %f", x, y); } void _normalize() { float norm = x*x + y*y; if (!norm) return; float mod = _INVSQRT(norm); x *= mod; y *= mod; } void _normalize_check() { float norm = x*x + y*y; if (!norm) return; if (norm > (1.000f + PRECISION) || norm < (1.000f - PRECISION)) { float mod = _INVSQRT(norm); x *= mod; y *= mod; } } void _default() { x = y = 0; } union { struct { float x, y; }; struct { float u, v; }; float _[2]; }; }; struct MATH3DPLANE { MATH3DPLANE() : a(0), b(0), c(0), d(0), P(MATH3DVEC(0,0,0)), N(MATH3DVEC(0,0,0)) {}; MATH3DPLANE(const MATH3DVEC& point, const MATH3DVEC& normal) { a = normal.x; b = normal.y; c = normal.z; d = (-point.x*normal.x) + (-point.y*normal.y) + (-point.z*normal.z); P = point; N = normal; }; MATH3DPLANE(const MATH3DVEC& point, const MATH3DVEC& point2, const MATH3DVEC& point3) { MATH3DVEC vec1(point2.x - point.x, point2.y - point.y, point2.z - point.z); MATH3DVEC vec2(point3.x - point.x, point3.y - point.y, point3.z - point.z); MATH3DVEC normal(vec1.y * vec2.z - vec1.z * vec2.y, vec1.z * vec2.x - vec1.x * vec2.z, vec1.x * vec2.y - vec1.y * vec2.x); normal._normalize_check(); a = normal.x; b = normal.y; c = normal.z; d = (-point.x*normal.x) + (-point.y*normal.y) + (-point.z*normal.z); P = point; N = normal; }; void _normalize() { float norm = a*a + b*b + c*c; if (norm) { float mod = _INVSQRT(norm); a *= mod; b *= mod; c *= mod; d *= mod; N.x = a; N.y = b; N.z = c; } } void _default() { a = b = c = d = 0; P._default(); N._default(); } float a, b, c, d; MATH3DVEC P; MATH3DVEC N; }; MATH3DVEC MathOrthogonalVec(const MATH3DVEC & v); struct MATH3DQUATERNION { // http://www.gamedev.ru/code/articles/?id=4215&page=2 MATH3DQUATERNION() : x(0), y(0), z(0), w(1) {}; //>> Конструктор из углов Эйлера MATH3DQUATERNION(const float ax, const float ay, const float az) { float s_ax = CTAB::sinA(ax * 0.5f); float c_ax = CTAB::cosA(ax * 0.5f); float s_ay = CTAB::sinA(ay * 0.5f); float c_ay = CTAB::cosA(ay * 0.5f); float s_az = CTAB::sinA(az * 0.5f); float c_az = CTAB::cosA(az * 0.5f); x = s_ay * c_ax * s_az + c_ay * s_ax * c_az; y = s_ay * c_ax * c_az - c_ay * s_ax * s_az; z = c_ay * c_ax * s_az - s_ay * s_ax * c_az; w = c_ay * c_ax * c_az + s_ay * s_ax * s_az; _normalize_check(); }; //>> Конструктор из углов Эйлера MATH3DQUATERNION(const MATH3DVEC & angles) { float s_ax = CTAB::sinA(angles.ax * 0.5f); float c_ax = CTAB::cosA(angles.ax * 0.5f); float s_ay = CTAB::sinA(angles.ay * 0.5f); float c_ay = CTAB::cosA(angles.ay * 0.5f); float s_az = CTAB::sinA(angles.az * 0.5f); float c_az = CTAB::cosA(angles.az * 0.5f); x = s_ay * c_ax * s_az + c_ay * s_ax * c_az; y = s_ay * c_ax * c_az - c_ay * s_ax * s_az; z = c_ay * c_ax * s_az - s_ay * s_ax * c_az; w = c_ay * c_ax * c_az + s_ay * s_ax * s_az; _normalize_check(); } //>> Конструктор из сферических координат MATH3DQUATERNION(const float latitude, const float longitude, const float angle, bool _reserved) { float sin_a = CTAB::sinA(angle * 0.5f); float cos_a = CTAB::cosA(angle * 0.5f); float sin_lat = CTAB::sinA(latitude); float cos_lat = CTAB::cosA(latitude); float sin_long = CTAB::sinA(longitude); float cos_long = CTAB::cosA(longitude); x = sin_a * cos_lat * sin_long; y = sin_a * sin_lat; z = y * cos_long; w = cos_a; _normalize_check(); // Обратно /* cos_angle = q->qw; sin_angle = sqrt(1.0 - cos_angle * cos_angle); angle = acos(cos_angle) * 2 * RADIANS; if (fabs(sin_angle) < 0.0005) sa = 1; tx = q->qx / sa; ty = q->qy / sa; tz = q->qz / sa; latitude = -asin(ty); if (tx * tx + tz * tz < 0.0005) longitude = 0; else longitude = atan2(tx, tz) * RADIANS; if (longitude < 0) longitude += 360.0; //*/ } //>> Конструктор из произвольной оси MATH3DQUATERNION(const float X, const float Y, const float Z, const float angle) { float sin = CTAB::sinA(angle * 0.5f); float cos = CTAB::cosA(angle * 0.5f); x = sin * X; y = sin * Y; z = sin * Z; w = cos; _normalize_check(); } //>> Конструктор из произвольной оси MATH3DQUATERNION(const MATH3DVEC & axis, const float angle) { float sin = CTAB::sinA(angle * 0.5f); float cos = CTAB::cosA(angle * 0.5f); x = sin * axis.x; y = sin * axis.y; z = sin * axis.z; w = cos; _normalize_check(); } /* //>> Конструктор кратчайшей дуги (shortest arc) MATH3DQUATERNION(const MATH3DVEC & from, const MATH3DVEC & to) { // half vector method // MATH3DVEC _from = from; MATH3DVEC _to = to; _from._normalize_check(); _to._normalize_check(); if (_from == (_to * -1)) // разворот на 180 вокруг любого ортогонального { MATH3DVEC ortho = MathOrthogonalVec(_from); ortho._normalize_check(); x = ortho.x; y = ortho.y; z = ortho.z; w = 0; } else { MATH3DVEC half = _from + _to; half._normalize_check(); float dot = _from.x * half.x + _from.y * half.y + _from.z * half.z; MATH3DVEC cross(_from.y * half.z - _from.z * half.y, _from.z * half.x - _from.x * half.z, _from.x * half.y - _from.y * half.x); x = cross.x; y = cross.y; z = cross.z; w = dot; } }//*/ //>> Конструктор кратчайшей дуги (shortest arc) MATH3DQUATERNION(const MATH3DVEC & from, const MATH3DVEC & to) { // half quat method // в 3 раза быстрее чем half vector method float dot = from.x * to.x + from.y * to.y + from.z * to.z ; float len_from = from.x * from.x + from.y * from.y + from.z * from.z ; float len_to = to.x * to.x + to.y * to.y + to.z * to.z ; float k = sqrt(len_from * len_to); if (dot / k == -1) { MATH3DVEC ortho = MathOrthogonalVec(from); ortho._normalize_check(); x = ortho.x; y = ortho.y; z = ortho.z; w = 0; } else { MATH3DVEC cross(from.y * to.z - from.z * to.y, from.z * to.x - from.x * to.z, from.x * to.y - from.y * to.x); x = cross.x; y = cross.y; z = cross.z; w = dot + k; _normalize(); } } /* //>> Конструктор кратчайшей дуги (shortest arc) :: test MATH3DQUATERNION(const MATH3DVEC & _from, const MATH3DVEC & _to, bool gems_method) { MATH3DVEC from = _from; MATH3DVEC to = _to; from._normalize_check(); to._normalize_check(); float dot = from.x * to.x + from.y * to.y + from.z * to.z; if (gems_method) { float s = sqrt((1 + dot) * 2); if (s < std::numeric_limits<float>::epsilon()) { // // Generate an axis // Vector3f a = Vector3f::UnitX().cross(v0); // // pick another if collinear // if (a.squaredNorm() < std::numeric_limits<float>::epsilon()) // { // a = Vector3f::UnitY().cross(v0); // } // a.normalize(); // return Quaternionf(AngleAxisf(boost::math::constants::pi<float>(), a)); MATH3DVEC ortho; MathOrthogonalVec(from, ortho); ortho._normalize_check(); x = ortho.x; y = ortho.y; z = ortho.z; w = 0; } else { MATH3DVEC cross(from.y * to.z - from.z * to.y, from.z * to.x - from.x * to.z, from.x * to.y - from.y * to.x); float s_ = 1 / s ; x = cross.x * s_ ; y = cross.y * s_ ; z = cross.z * s_ ; w = 0.5f * s ; } } else { MATH3DVEC cross(from.y * to.z - from.z * to.y, from.z * to.x - from.x * to.z, from.x * to.y - from.y * to.x); float len_from = from.x * from.x + from.y * from.y + from.z * from.z ; float len_to = to.x * to.x + to.y * to.y + to.z * to.z ; x = cross.x; y = cross.y; x = cross.z; // w = dot; w = dot + sqrt(len_from * len_to); _normalize_check(); // w += 1.0f; // reducing angle to halfangle // if (w <= TINY) // angle close to PI // { // if ((from.z*from.z) > (from.x*from.x)) // set(0, from.z, -from.y, w); //from*vector3(1,0,0) // else // set(from.y, -from.x, 0, w); //from*vector3(0,0,1) // } // normalize(); } _normalize_check(); }//*/ //>> Конструктор из матрицы вращения MATH3DQUATERNION(const MATH3DMATRIX & M) { float s, s_, trace; trace = M._11 + M._22 + M._33 + 1.0f; if (trace > 1.0f) { s = 2.0f * sqrt(trace); s_ = 1 / s; x = (M._23 - M._32) * s_; y = (M._31 - M._13) * s_; z = (M._12 - M._21) * s_; w = 0.25f * s; } else { int maxi = 0; for (int i=1; i<3; i++) if (M._[i][i] > M._[maxi][maxi]) maxi = i; switch (maxi) { case 0: s = 2.0f * sqrt(1.0f + M._11 - M._22 - M._33); s_ = 1 / s; x = 0.25f * s; y = (M._12 + M._21) * s_; z = (M._13 + M._31) * s_; w = (M._23 - M._32) * s_; break; case 1: s = 2.0f * sqrt(1.0f + M._22 - M._11 - M._33); s_ = 1 / s; x = (M._12 + M._21) * s_; y = 0.25f * s; z = (M._23 + M._32) * s_; w = (M._31 - M._13) * s_; break; case 2: s = 2.0f * sqrt(1.0f + M._33 - M._11 - M._22); s_ = 1 / s; x = (M._13 + M._31) * s_; y = (M._23 + M._32) * s_; z = 0.25f * s; w = (M._12 - M._21) * s_; break; } } _normalize_check(); } //>> Конструктор RAW MATH3DQUATERNION(const MATH3DVEC4 & raw) { x = raw.x; y = raw.y; z = raw.z; w = raw.w; } MATH3DQUATERNION operator + (const MATH3DQUATERNION & Q) const { MATH3DQUATERNION out; out.x = Q.x + x; out.y = Q.y + y; out.z = Q.z + z; out.w = Q.w + w; return out; } MATH3DQUATERNION& operator += (const MATH3DQUATERNION & Q) { x += Q.x; y += Q.y; z += Q.z; w += Q.w; return *this; } MATH3DQUATERNION operator - (const MATH3DQUATERNION & Q) const { MATH3DQUATERNION out; out.x = Q.x - x; out.y = Q.y - y; out.z = Q.z - z; out.w = Q.w - w; return out; } MATH3DQUATERNION& operator -= (const MATH3DQUATERNION & Q) { x -= Q.x; y -= Q.y; z -= Q.z; w -= Q.w; return *this; } MATH3DQUATERNION operator * (const MATH3DQUATERNION & Q) const { MATH3DQUATERNION out; // out = this * Q out.x = Q.w * x + Q.x * w + Q.y * z - Q.z * y; out.y = Q.w * y - Q.x * z + Q.y * w + Q.z * x; out.z = Q.w * z + Q.x * y - Q.y * x + Q.z * w; out.w = Q.w * w - Q.x * x - Q.y * y - Q.z * z; return out; } MATH3DQUATERNION& operator *= (const MATH3DQUATERNION & Q) { MATH3DQUATERNION out; // out = this * Q out.x = Q.w * x + Q.x * w + Q.y * z - Q.z * y; out.y = Q.w * y - Q.x * z + Q.y * w + Q.z * x; out.z = Q.w * z + Q.x * y - Q.y * x + Q.z * w; out.w = Q.w * w - Q.x * x - Q.y * y - Q.z * z; x = out.x; y = out.y; z = out.z; w = out.w; return *this; } bool operator == (const MATH3DQUATERNION & Q) const { if (x >= Q.x - PRECISION && x <= Q.x + PRECISION && y >= Q.y - PRECISION && y <= Q.y + PRECISION && z >= Q.z - PRECISION && z <= Q.z + PRECISION && w >= Q.w - PRECISION && w <= Q.w + PRECISION) return true; return false; }; bool operator != (const MATH3DQUATERNION & Q) const { if (x >= Q.x - PRECISION && x <= Q.x + PRECISION && y >= Q.y - PRECISION && y <= Q.y + PRECISION && z >= Q.z - PRECISION && z <= Q.z + PRECISION && w >= Q.w - PRECISION && w <= Q.w + PRECISION) return false; return true; }; operator float*() { return reinterpret_cast<float*>(this); } void _default() { x = y = z = 0; w = 1; } void _printf() { printf("\n%f %f %f %f", x, y, z, w); } void _normalize() { float norm = x*x + y*y + z*z + w*w; if (!norm) return; float mod = _INVSQRT(norm); x *= mod; y *= mod; z *= mod; w *= mod; } void _normalize_check() { float norm = x*x + y*y + z*z + w*w; if (!norm) return; if ( norm > (1.000f + PRECISION) || norm < (1.000f - PRECISION) ) { float mod = _INVSQRT(norm); x *= mod; y *= mod; z *= mod; w *= mod; } } void _conjugate() { x *= -1; y *= -1; z *= -1; } void _inverse() { float norm = x*x + y*y + z*z + w*w; if (norm > (1.000f + PRECISION) || norm < (1.000f - PRECISION)) { if (!norm) return; float mod = _INVSQRT(norm); x *= -mod; y *= -mod; z *= -mod; w *= mod; } else { x *= -1; y *= -1; z *= -1; } } void _angles(MATH3DVEC & v) { // ...надо будет ещё посмотреть... // qx2 = q.x * q.x // qy2 = q.y * q.y // qz2 = q.z * q.z // bank = atan2(2 * (q.x * q.w + q.y * q.z), 1 - 2 * (qx2 + qy2)) // altitude = Asin(2 * (q.y * q.w - q.z * q.x)) // heading = atan2(2 * (q.z * q.w + q.x * q.y), 1 - 2 * (qy2 + qz2)) // https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles // https://www.mathworks.com/help/robotics/ref/quat2eul.html // https://github.com/tminnigaliev/euler_angles/blob/master/eul_from_rotm.m // https://www.mathworks.com/help/robotics/ref/quat2eul.html float sinr = 2.0f * (x*w - y*z); // -M._32 = 2.0f * -(QYZ - QXW); sinr = (sinr >= 1.0f) ? 1.0f : sinr; sinr = (sinr <= -1.0f) ? -1.0f : sinr; v.x = TODEGREES(asin(sinr)); /* if (sinr > 0.99f || sinr < -0.99f) { FLOAT siny = 2.0f * (x*z - y*w); // M._13 = 2.0f * ( QXZ - QYW ); FLOAT cosy = 1.0f - 2.0f * (y*y + z*z); // M._11 = 1.0f - 2.0f * ( QYY + QZZ ); v.z = TODEGREES(atan2(siny,cosy)); FLOAT sinp = 2.0f * (x*y - z*w); // FLOAT cosp = 1.0f - 2.0f * (z*z + y*y); // v.y = 90 + TODEGREES(atan2(sinp,cosp)); } else { //*/ float siny = 2.0f * (x*z + y*w); // M._31 = 2.0f * ( QXZ + QYW ); float cosy = 1.0f - 2.0f * (x*x + y*y); // M._33 = 1.0f - 2.0f * ( QXX + QYY ); v.y = TODEGREES(atan2(siny,cosy)); float sinp = 2.0f * (x*y + z*w); // M._12 = 2.0f * ( QXY + QZW ); float cosp = 1.0f - 2.0f * (x*x + z*z); // M._22 = 1.0f - 2.0f * ( QXX + QZZ ); v.z = TODEGREES(atan2(sinp,cosp)); // } //*/ } union { struct { float x, y, z, w; }; float _[4]; }; }; ///////////////////////////////////////// inline const D3DXMATRIX* D3DCAST(const MATH3DMATRIX* ptr) { return reinterpret_cast<const D3DXMATRIX*>(ptr); } inline const D3DXVECTOR4* D3DCAST(const MATH3DVEC4* ptr) { return reinterpret_cast<const D3DXVECTOR4*>(ptr); } inline const MATH3DMATRIX* D3DCAST(const D3DXMATRIX* ptr) { return reinterpret_cast<const MATH3DMATRIX*>(ptr); } inline const MATH3DVEC4* D3DCAST(const D3DXVECTOR4* ptr) { return reinterpret_cast<const MATH3DVEC4*>(ptr); } inline D3DXMATRIX* D3DCAST (MATH3DMATRIX* ptr) { return reinterpret_cast<D3DXMATRIX*>(ptr); } inline D3DXVECTOR4* D3DCAST (MATH3DVEC4* ptr) { return reinterpret_cast<D3DXVECTOR4*>(ptr); } inline MATH3DMATRIX* D3DCAST (D3DXMATRIX* ptr) { return reinterpret_cast<MATH3DMATRIX*>(ptr); } inline MATH3DVEC4* D3DCAST (D3DXVECTOR4* ptr) { return reinterpret_cast<MATH3DVEC4*>(ptr); } inline const float* FCAST (const MATH3DMATRIX* ptr) { return reinterpret_cast<const float*>(ptr); } inline const float* FCAST(const MATH3DVEC4* ptr) { return reinterpret_cast<const float*>(ptr); } inline const float* FCAST(const MATH3DVEC3* ptr) { return reinterpret_cast<const float*>(ptr); } inline float* FCAST(MATH3DMATRIX* ptr) { return reinterpret_cast<float*>(ptr); } inline float* FCAST(MATH3DVEC4* ptr) { return reinterpret_cast<float*>(ptr); } inline float* FCAST(MATH3DVEC3* ptr) { return reinterpret_cast<float*>(ptr); } //>> Измеряет длину (модуль) вектора inline float MathLenVec(const MATH3DVEC & vec) { return sqrt(vec.x*vec.x + vec.y*vec.y + vec.z*vec.z); }; //>> Измеряет длину (модуль) вектора inline void MathLenVec(const MATH3DVEC & vec, float& length) { length = sqrt(vec.x*vec.x + vec.y*vec.y + vec.z*vec.z); }; //>> Измеряет расстояние между двумя точками inline float MathDistance(const MATH3DVEC & P1, const MATH3DVEC & P2) { return MathLenVec(P1 - P2); } //>> Измеряет расстояние между двумя точками inline void MathDistance(const MATH3DVEC & P1, const MATH3DVEC & P2, float & out) { out = MathLenVec(P1 - P2); } //>> Вычитает vec1 - vec2 /* inline MATH3DVEC MathSubtractVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2) { return MATH3DVEC(vec1.x - vec2.x, vec1.y - vec2.y, vec1.z - vec2.z); } //*/ ; ; //>> Вычитает vec1 - vec2 /* inline void MathSubtractVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2, MATH3DVEC& vec) { vec = MATH3DVEC(vec1.x - vec2.x, vec1.y - vec2.y, vec1.z - vec2.z); } //*/ ; //>> Складывает vec1 + vec2 /* inline MATH3DVEC MathAddVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2) { return MATH3DVEC(vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z); } //*/ ; //>> Складывает vec1 + vec2 /* inline void MathAddVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2, MATH3DVEC& vec) { vec = MATH3DVEC(vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z); } //*/ ; //>> Возвращает скалярное произведение 2 векторов (DOT product) inline float MathDotVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2) { return vec1.x*vec2.x + vec1.y*vec2.y + vec1.z*vec2.z; }; //>> Возвращает скалярное произведение 2 векторов (DOT product) inline void MathDotVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2, float& dot) { dot = vec1.x*vec2.x + vec1.y*vec2.y + vec1.z*vec2.z; }; //>> Возвращает косинус угла между 2 векторами (скалярное произведение + нормализация) inline float MathCosVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2) { return MathDotVec(vec1,vec2) / MathLenVec(vec1) * MathLenVec(vec2); }; //>> Возвращает векторное произведение 2 векторов (CROSS product) inline MATH3DVEC MathCrossVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2) { return MATH3DVEC(vec1.y * vec2.z - vec1.z * vec2.y, vec1.z * vec2.x - vec1.x * vec2.z, vec1.x * vec2.y - vec1.y * vec2.x); }; //>> Возвращает векторное произведение 2 векторов (CROSS product) inline void MathCrossVec(const MATH3DVEC & vec1, const MATH3DVEC & vec2, MATH3DVEC& out) { out = MATH3DVEC(vec1.y * vec2.z - vec1.z * vec2.y, vec1.z * vec2.x - vec1.x * vec2.z, vec1.x * vec2.y - vec1.y * vec2.x); }; //>> Приведение вектора к единичной длине inline MATH3DVEC MathNormalizeVec(const MATH3DVEC & vec) { float m, l = vec.x*vec.x + vec.y*vec.y + vec.z*vec.z; if (!l) m = 1; else m = _INVSQRT(l); return MATH3DVEC(vec.x * m, vec.y * m, vec.z * m); }; //>> Вектор из абсолютных значений /* inline MATH3DVEC MathAbsVec(const MATH3DVEC & vec) { return MATH3DVEC(abs(vec.x), abs(vec.y), abs(vec.z)); }; //*/ ; //>> Составляет ортогональный вектор inline MATH3DVEC MathOrthogonalVec(const MATH3DVEC & v) { float x = abs(v.x); float y = abs(v.y); float z = abs(v.z); MATH3DVEC other = x < y ? (x < z ? OX_VEC : OZ_VEC) : (y < z ? OY_VEC : OZ_VEC); return MathCrossVec(v, other); } //>> Составляет ортогональный вектор inline void MathOrthogonalVec(const MATH3DVEC & v, MATH3DVEC & out) { float x = abs(v.x); float y = abs(v.y); float z = abs(v.z); MATH3DVEC other = x<y ? (x<z ? OX_VEC : OZ_VEC) : (y<z ? OY_VEC : OZ_VEC); MathCrossVec(v, other, out); } //>> Применение world-матрицы к точке пространства inline MATH3DVEC MathVecTransformCoord(const MATH3DVEC & v, const MATH3DMATRIX & M) { MATH3DVEC out; float norm = (v.x * M._14) + (v.y * M._24) + (v.z * M._34) + M._44; if (norm) { out.x = ((v.x * M._11) + (v.y * M._21) + (v.z * M._31) + M._41) / norm; out.y = ((v.x * M._12) + (v.y * M._22) + (v.z * M._32) + M._42) / norm; out.z = ((v.x * M._13) + (v.y * M._23) + (v.z * M._33) + M._43) / norm; } else { out.x = 0; out.y = 0; out.z = 0; } return out; } //*/ ; //>> Применение world-матрицы к точке пространства inline void MathVecTransformCoord(const MATH3DVEC & v, const MATH3DMATRIX & M, MATH3DVEC& out) { MATH3DVEC _out; float norm = (v.x * M._14) + (v.y * M._24) + (v.z * M._34) + M._44; if (norm) { _out.x = ((v.x * M._11) + (v.y * M._21) + (v.z * M._31) + M._41) / norm; _out.y = ((v.x * M._12) + (v.y * M._22) + (v.z * M._32) + M._42) / norm; _out.z = ((v.x * M._13) + (v.y * M._23) + (v.z * M._33) + M._43) / norm; } else { _out.x = 0; out.y = 0; out.z = 0; } out = _out; } //>> Применение world-матрицы к точке пространства inline void MathVecTransformCoord(const MATH3DMATRIX & M, MATH3DVEC& in_out) { float norm = (in_out.x * M._14) + (in_out.y * M._24) + (in_out.z * M._34) + M._44; if (norm) { MATH3DVEC v = in_out; in_out.x = ((v.x * M._11) + (v.y * M._21) + (v.z * M._31) + M._41) / norm; in_out.y = ((v.x * M._12) + (v.y * M._22) + (v.z * M._32) + M._42) / norm; in_out.z = ((v.x * M._13) + (v.y * M._23) + (v.z * M._33) + M._43) / norm; } else { in_out.x = 0; in_out.y = 0; in_out.z = 0; } } //>> Применение world-матрицы к вектору inline MATH3DVEC MathVecTransformNormal(const MATH3DVEC & v, const MATH3DMATRIX & M) { MATH3DVEC out; out.x = (v.x * M._11) + (v.y * M._21) + (v.z * M._31); out.y = (v.x * M._12) + (v.y * M._22) + (v.z * M._32); out.z = (v.x * M._13) + (v.y * M._23) + (v.z * M._33); return out; } //*/ ; //>> Применение world-матрицы к вектору inline void MathVecTransformNormal(const MATH3DVEC & v, const MATH3DMATRIX & M, MATH3DVEC& out) { MATH3DVEC _out; _out.x = (v.x * M._11) + (v.y * M._21) + (v.z * M._31); _out.y = (v.x * M._12) + (v.y * M._22) + (v.z * M._32); _out.z = (v.x * M._13) + (v.y * M._23) + (v.z * M._33); out = _out; } //>> Применение world-матрицы к вектору inline void MathVecTransformNormal(const MATH3DMATRIX & M, MATH3DVEC& in_out) { MATH3DVEC v = in_out; in_out.x = (v.x * M._11) + (v.y * M._21) + (v.z * M._31); in_out.y = (v.x * M._12) + (v.y * M._22) + (v.z * M._32); in_out.z = (v.x * M._13) + (v.y * M._23) + (v.z * M._33); } //>> Составление кватерниона из углов Эйлера /* inline MATH3DQUATERNION MathQuaternionRotationXYZ(const float ax, const float ay, const float az) { MATH3DQUATERNION Q; float s_ax = CTAB::sinA(ax * 0.5f); float c_ax = CTAB::cosA(ax * 0.5f); float s_ay = CTAB::sinA(ay * 0.5f); float c_ay = CTAB::cosA(ay * 0.5f); float s_az = CTAB::sinA(az * 0.5f); float c_az = CTAB::cosA(az * 0.5f); Q.x = s_ay * c_ax * s_az + c_ay * s_ax * c_az; Q.y = s_ay * c_ax * c_az - c_ay * s_ax * s_az; Q.z = c_ay * c_ax * s_az - s_ay * s_ax * c_az; Q.w = c_ay * c_ax * c_az + s_ay * s_ax * s_az; return Q; } //*/ ; //>> Составление кватерниона из углов Эйлера /* inline void MathQuaternionRotationXYZ(const float ax, const float ay, const float az, MATH3DQUATERNION& Q) { float s_ax = CTAB::sinA(ax * 0.5f); float c_ax = CTAB::cosA(ax * 0.5f); float s_ay = CTAB::sinA(ay * 0.5f); float c_ay = CTAB::cosA(ay * 0.5f); float s_az = CTAB::sinA(az * 0.5f); float c_az = CTAB::cosA(az * 0.5f); Q.x = s_ay * c_ax * s_az + c_ay * s_ax * c_az; Q.y = s_ay * c_ax * c_az - c_ay * s_ax * s_az; Q.z = c_ay * c_ax * s_az - s_ay * s_ax * c_az; Q.w = c_ay * c_ax * c_az + s_ay * s_ax * s_az; } //*/ ; //>> Составление кватерниона из углов Эйлера /* inline MATH3DQUATERNION MathQuaternionRotationXYZ(const MATH3DVEC& angles) { return MathQuaternionRotationXYZ(angles.ax, angles.ay, angles.az); } //*/ ; //>> Составление кватерниона из углов Эйлера /* inline void MathQuaternionRotationXYZ(const MATH3DVEC& angles, MATH3DQUATERNION& Q) { MathQuaternionRotationXYZ(angles.ax, angles.ay, angles.az, Q); } //*/ ; //>> Составление кватерниона из произвольной оси /* inline MATH3DQUATERNION MathQuaternionRotationAxis(const float X, const float Y, const float Z, const float angle) { MATH3DQUATERNION Q; float sin = CTAB::sinA(angle * 0.5f); float cos = CTAB::cosA(angle * 0.5f); Q.x = sin * X; Q.y = sin * Y; Q.z = sin * Z; Q.w = cos; return Q; } //*/ ; //>> Составление кватерниона из произвольной оси /* inline void MathQuaternionRotationAxis(const float X, const float Y, const float Z, const float angle, MATH3DQUATERNION& Q) { float sin = CTAB::sinA(angle * 0.5f); float cos = CTAB::cosA(angle * 0.5f); Q.x = sin * X; Q.y = sin * Y; Q.z = sin * Z; Q.w = cos; } //*/ ; //>> Составление кватерниона из произвольной оси /* inline MATH3DQUATERNION MathQuaternionRotationAxis(const MATH3DVEC & axis, const float angle) { return MathQuaternionRotationAxis(axis.x, axis.y, axis.z, angle); } //*/ ; //>> Составление кватерниона из произвольной оси /* inline void MathQuaternionRotationAxis(const MATH3DVEC& axis, const float angle, MATH3DQUATERNION& Q) { MathQuaternionRotationAxis(axis.x, axis.y, axis.z, angle, Q); } //*/ ; //>> Конвертация кватерниона в ось и угол inline void MathQuaternionToRotationAxis(const MATH3DQUATERNION& Q, MATH3DVEC& axis, float& angle) { float val = sqrt(Q.x*Q.x + Q.y*Q.y + Q.z*Q.z); if (val >= PRECISION) { float val_ = 1.0f / val; // TODO: оптимизировать atan2() axis.x = Q.x * val_; axis.y = Q.y * val_; axis.z = Q.z * val_; if (Q.w < 0) angle = TODEGREES(2.0f * atan2(-val, -Q.w)); // [-PI, 0] else angle = TODEGREES(2.0f * atan2(val, Q.w)); // [0, PI] } else { axis.x = axis.y = axis.z = 0; angle = 0; } } //>> Составление кватерниона из матрицы вращения /* inline MATH3DQUATERNION MathQuaternionRotationMatrix(const MATH3DMATRIX & M) { MATH3DQUATERNION out; float s, trace; trace = M._11 + M._22 + M._33 + 1.0f; if (trace > 1.0f) { s = 2.0f * sqrt(trace); out.x = (M._23 - M._32) / s; out.y = (M._31 - M._13) / s; out.z = (M._12 - M._21) / s; out.w = 0.25f * s; } else { int i, maxi = 0; for (i=1; i<3; i++) if (M._[i][i] > M._[maxi][maxi]) maxi = i; switch (maxi) { case 0: s = 2.0f * sqrt(1.0f + M._11 - M._22 - M._33); out.x = 0.25f * s; out.y = (M._12 + M._21) / s; out.z = (M._13 + M._31) / s; out.w = (M._23 - M._32) / s; break; case 1: s = 2.0f * sqrt(1.0f + M._22 - M._11 - M._33); out.x = (M._12 + M._21) / s; out.y = 0.25f * s; out.z = (M._23 + M._32) / s; out.w = (M._31 - M._13) / s; break; case 2: s = 2.0f * sqrt(1.0f + M._33 - M._11 - M._22); out.x = (M._13 + M._31) / s; out.y = (M._23 + M._32) / s; out.z = 0.25f * s; out.w = (M._12 - M._21) / s; break; } } return out; } //*/ ; //>> Составление кватерниона из матрицы вращения /* inline void MathQuaternionRotationMatrix(const MATH3DMATRIX & M, MATH3DQUATERNION & out) { out = MathQuaternionRotationMatrix(M); } //*/ ; //>> Магнитуда кватерниона (длина) inline float MathQuaternionLength(const MATH3DQUATERNION & Q) { return sqrt(Q.x*Q.x + Q.y*Q.y + Q.z*Q.z + Q.w*Q.w); } //>> Магнитуда кватерниона (длина) inline void MathQuaternionLength(const MATH3DQUATERNION & Q, float & out) { out = sqrt(Q.x*Q.x + Q.y*Q.y + Q.z*Q.z + Q.w*Q.w); } //>> Квадрат длины кватерниона (норма) inline float MathQuaternionLengthSq(const MATH3DQUATERNION & Q) { return Q.x*Q.x + Q.y*Q.y + Q.z*Q.z + Q.w*Q.w; } //>> Квадрат длины кватерниона (норма) inline void MathQuaternionLengthSq(const MATH3DQUATERNION & Q, float & out) { out = Q.x*Q.x + Q.y*Q.y + Q.z*Q.z + Q.w*Q.w; } //>> Обратный / инверсный кватернион / сопряжение (conjugate) /* inline void MathQuaternionInvert(MATH3DQUATERNION & Q) { Q.x *= -1; Q.y *= -1; Q.z *= -1; } //*/ ; //>> Нормализация кватерниона /* inline MATH3DQUATERNION MathQuaternionNormalize(const MATH3DQUATERNION & Q) { MATH3DQUATERNION out; float len = sqrt(Q.x*Q.x + Q.y*Q.y + Q.z*Q.z + Q.w*Q.w); if (!len) return Q; out.x = Q.x / len; out.y = Q.y / len; out.z = Q.z / len; out.w = Q.w / len; return out; } //*/ ; //>> Умножение кватернионов (скалярное) inline float MathQuaternionDot(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2) { return (Q1.x * Q2.x) + (Q1.y * Q2.y) + (Q1.z * Q2.z) + (Q1.w * Q2.w); } //>> Умножение кватернионов (скалярное) inline void MathQuaternionDot(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, float & out) { out = (Q1.x * Q2.x) + (Q1.y * Q2.y) + (Q1.z * Q2.z) + (Q1.w * Q2.w); } //>> Умножение кватернионов /* inline MATH3DQUATERNION MathQuaternionMultiply(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2) { MATH3DQUATERNION Q; Q.x = Q2.w * Q1.x + Q2.x * Q1.w + Q2.y * Q1.z - Q2.z * Q1.y; Q.y = Q2.w * Q1.y - Q2.x * Q1.z + Q2.y * Q1.w + Q2.z * Q1.x; Q.z = Q2.w * Q1.z + Q2.x * Q1.y - Q2.y * Q1.x + Q2.z * Q1.w; Q.w = Q2.w * Q1.w - Q2.x * Q1.x - Q2.y * Q1.y - Q2.z * Q1.z; return Q; } //*/ ; //>> Умножение кватернионов /* inline void MathQuaternionMultiply(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, MATH3DQUATERNION& out) { out.x = Q2.w * Q1.x + Q2.x * Q1.w + Q2.y * Q1.z - Q2.z * Q1.y; out.y = Q2.w * Q1.y - Q2.x * Q1.z + Q2.y * Q1.w + Q2.z * Q1.x; out.z = Q2.w * Q1.z + Q2.x * Q1.y - Q2.y * Q1.x + Q2.z * Q1.w; out.w = Q2.w * Q1.w - Q2.x * Q1.x - Q2.y * Q1.y - Q2.z * Q1.z; } //*/ ; //>> Умножение кватернионов (более долгий вариант) /* inline void MathQuaternionMultiplyAlt(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, MATH3DQUATERNION& out) { float A, B, C, D, E, F, G, H; A = (Q1.w + Q1.x) * (Q2.w + Q2.x); B = (Q1.z - Q1.y) * (Q2.y - Q2.z); C = (Q1.x - Q1.w) * (Q2.y + Q2.z); D = (Q1.y + Q1.z) * (Q2.x - Q2.w); E = (Q1.x + Q1.z) * (Q2.x + Q2.y); F = (Q1.x - Q1.z) * (Q2.x - Q2.y); G = (Q1.w + Q1.y) * (Q2.w - Q2.z); H = (Q1.w - Q1.y) * (Q2.w + Q2.z); out.w = B + (-E - F + G + H) * 0.5f; out.x = A - (E + F + G + H) * 0.5f; out.y = -C + (E - F + G - H) * 0.5f; out.z = -D + (E - F - G + H) * 0.5f; } //*/ //>> Умножение кватерниона и вектора inline void MathQuaternionMultiply(const MATH3DQUATERNION & Q, const MATH3DVEC & V, MATH3DQUATERNION & out) { MATH3DQUATERNION _Q = Q; out.x = V.x * _Q.w + V.y * _Q.z - V.z * _Q.y; out.y = V.x * _Q.z + V.y * _Q.w + V.z * _Q.x; out.z = V.x * _Q.y - V.y * _Q.x + V.z * _Q.w; out.w = V.x * _Q.x - V.y * _Q.y - V.z * _Q.z; } //>> Умножение кватерниона и вектора inline void MathQuaternionMultiply(const MATH3DVEC & V, const MATH3DQUATERNION & Q, MATH3DQUATERNION & out) { MATH3DQUATERNION _Q = Q; out.x = _Q.w * V.x + _Q.y * V.z - _Q.z * V.y; out.y = _Q.w * V.y - _Q.x * V.z + _Q.z * V.x; out.z = _Q.w * V.z + _Q.x * V.y - _Q.y * V.x; out.w = _Q.x * V.x - _Q.y * V.y - _Q.z * V.z; } //>> Применение кватерниона к вектору V'= q * V * q–1 inline void MathQuaternionApply(const MATH3DQUATERNION & Q, MATH3DVEC & in_out) { MATH3DQUATERNION _Q, _Q_inv(-Q.x, -Q.y, -Q.z, Q.w); _Q.x = Q.w * in_out.x + Q.y * in_out.z - Q.z * in_out.y; _Q.y = Q.w * in_out.y - Q.x * in_out.z + Q.z * in_out.x; _Q.z = Q.w * in_out.z + Q.x * in_out.y - Q.y * in_out.x; _Q.w = Q.x * in_out.x - Q.y * in_out.y - Q.z * in_out.z; _Q = _Q * _Q_inv; in_out.x = _Q.x; in_out.y = _Q.y; in_out.z = _Q.z; } //>> Сферическая линейная интерполяция между 2 кватернионами inline MATH3DQUATERNION MathQuaternionSLERP(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const float t) { // (p sin((1–t)a) – q sin(ta)) / sin(a); t = [0..1]; a->cos(a) = DOT(q, p) // http://wat.gamedev.ru/articles/quaternions?page=2 char epsilon = 1; float cos_a = MathQuaternionDot(Q1, Q2); if (cos_a < 0) epsilon = -1; float scale_1, scale_2; float delta_a = 0.9848f; // до 10 градусов - линейно if (cos_a * epsilon < delta_a) // большой угол { float angle = TODEGREES(acos(cos_a)); float sin_a = 1.f / CTAB::sinA(angle); scale_1 = CTAB::sinA((1.f - t) * angle) * sin_a; scale_2 = CTAB::sinA( t * angle) * sin_a; } else // маленький угол -> линейно { scale_1 = 1.f - t; scale_2 = t; } scale_2 *= epsilon; MATH3DQUATERNION out; out.x = scale_1 * Q1.x + scale_2 * Q2.x; out.y = scale_1 * Q1.y + scale_2 * Q2.y; out.z = scale_1 * Q1.z + scale_2 * Q2.z; out.w = scale_1 * Q1.w + scale_2 * Q2.w; out._normalize_check(); return out; } //>> Сферическая линейная интерполяция между 2 кватернионами inline void MathQuaternionSLERP(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const float t, MATH3DQUATERNION & out) { char epsilon = 1; float cos_a = MathQuaternionDot(Q1, Q2); if (cos_a < 0) epsilon = -1; float scale_1, scale_2; float delta_a = 0.9848f; // до 10 градусов - линейно if (cos_a * epsilon < delta_a) // большой угол { float angle = TODEGREES(acos(cos_a)); float sin_a = 1.f / CTAB::sinA(angle); scale_1 = CTAB::sinA((1.f - t) * angle) * sin_a; scale_2 = CTAB::sinA( t * angle) * sin_a; } else // маленький угол -> линейно { scale_1 = 1.f - t; scale_2 = t; } scale_2 *= epsilon; out.x = scale_1 * Q1.x + scale_2 * Q2.x; out.y = scale_1 * Q1.y + scale_2 * Q2.y; out.z = scale_1 * Q1.z + scale_2 * Q2.z; out.w = scale_1 * Q1.w + scale_2 * Q2.w; out._normalize_check(); } //>> Сферическая линейная интерполяция между 2 кватернионами inline MATH3DQUATERNION MathQuaternionSLERP(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const float t, const float cos_linear) { char epsilon = 1; float cos_a = MathQuaternionDot(Q1, Q2); if (cos_a < 0) epsilon = -1; float scale_1, scale_2; float cos_a__ = cos_a * epsilon; // избегаем деления на ноль // sin(0.5f) < 0.009 // cos(0.5f) > 0.99995 if (cos_a__ < 0.99995f && cos_a__ < cos_linear) // большой угол { float angle = TODEGREES(acos(cos_a)); float sin_a = 1.f / CTAB::sinA(angle); scale_1 = CTAB::sinA((1.f - t) * angle) * sin_a; scale_2 = CTAB::sinA( t * angle) * sin_a; } else // маленький угол -> линейно { scale_1 = 1.f - t; scale_2 = t; } scale_2 *= epsilon; MATH3DQUATERNION out; out.x = scale_1 * Q1.x + scale_2 * Q2.x; out.y = scale_1 * Q1.y + scale_2 * Q2.y; out.z = scale_1 * Q1.z + scale_2 * Q2.z; out.w = scale_1 * Q1.w + scale_2 * Q2.w; out._normalize_check(); return out; } //>> Сферическая линейная интерполяция между 2 кватернионами inline void MathQuaternionSLERP(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const float t, const float cos_linear, MATH3DQUATERNION & out) { char epsilon = 1; float cos_a = MathQuaternionDot(Q1, Q2); if (cos_a < 0) epsilon = -1; float scale_1, scale_2; float cos_a__ = cos_a * epsilon; // избегаем деления на ноль // sin(0.5f) < 0.009 // cos(0.5f) > 0.99995 if (cos_a__ < 0.99995f && cos_a__ < cos_linear) // большой угол { float angle = TODEGREES(acos(cos_a)); float sin_a = 1.f / CTAB::sinA(angle); scale_1 = CTAB::sinA((1.f - t) * angle) * sin_a; scale_2 = CTAB::sinA( t * angle) * sin_a; } else // маленький угол -> линейно { scale_1 = 1.f - t; scale_2 = t; } scale_2 *= epsilon; out.x = scale_1 * Q1.x + scale_2 * Q2.x; out.y = scale_1 * Q1.y + scale_2 * Q2.y; out.z = scale_1 * Q1.z + scale_2 * Q2.z; out.w = scale_1 * Q1.w + scale_2 * Q2.w; out._normalize_check(); } //>> Кубическая интерполяция между 4 кватернионами inline void MathQuaternionSQUAD(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const MATH3DQUATERNION & Q3, const MATH3DQUATERNION & Q4, const float t, MATH3DQUATERNION & out) { MATH3DQUATERNION Q14, Q23; MathQuaternionSLERP(Q1, Q4, t, Q14); MathQuaternionSLERP(Q2, Q3, t, Q23); MathQuaternionSLERP(Q14, Q23, 2.0f * t * (1.0f - t), out); } //>> Кубическая интерполяция между 4 кватернионами inline void MathQuaternionSQUAD(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const MATH3DQUATERNION & Q3, const MATH3DQUATERNION & Q4, const float t, const float cos_linear, MATH3DQUATERNION & out) { MATH3DQUATERNION Q14, Q23; MathQuaternionSLERP(Q1, Q4, t, cos_linear, Q14); MathQuaternionSLERP(Q2, Q3, t, cos_linear, Q23); MathQuaternionSLERP(Q14, Q23, 2.0f * t * (1.0f - t), cos_linear, out); } //>> Задаёт кватернион в барицентрических координатах inline void MathQuaternionBaryCentric(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const MATH3DQUATERNION & Q3, const float f, const float g, MATH3DQUATERNION & out) { MATH3DQUATERNION Q12, Q13; float fg = f + g; MathQuaternionSLERP(Q1, Q2, fg, Q12); MathQuaternionSLERP(Q1, Q3, fg, Q13); MathQuaternionSLERP(Q12, Q13, g / fg, out); } //>> Задаёт кватернион в барицентрических координатах inline void MathQuaternionBaryCentric(const MATH3DQUATERNION & Q1, const MATH3DQUATERNION & Q2, const MATH3DQUATERNION & Q3, const float f, const float g, const float cos_linear, MATH3DQUATERNION & out) { MATH3DQUATERNION Q12, Q13; float fg = f + g; MathQuaternionSLERP(Q1, Q2, fg, cos_linear, Q12); MathQuaternionSLERP(Q1, Q3, fg, cos_linear, Q13); MathQuaternionSLERP(Q12, Q13, g / fg, cos_linear, out); } //>> Поиск точки пересечения луча и плоскости (плоскость по 3 точкам) inline MATH3DVEC MathRayToPlaneIntersect(const MATH3DVEC & p, const MATH3DVEC & p2, const MATH3DVEC & p3, const MATH3DVEC & rp, const MATH3DVEC & rp2, bool& NON) { MATH3DVEC vec1(p2.x-p.x, p2.y-p.y, p2.z-p.z); MATH3DVEC vec2(p3.x-p.x, p3.y-p.y, p3.z-p.z); MATH3DVEC normal(vec1.y*vec2.z - vec1.z*vec2.y, vec1.z*vec2.x - vec1.x*vec2.z, vec1.x*vec2.y - vec1.y*vec2.x); normal._normalize_check(); NON = 0; MATH3DVEC sub(rp - p); MATH3DVEC dir(rp2 - rp); float d = MathDotVec(normal, sub); // длина по нормали от точки ray_point до плоскости float e = MathDotVec(normal, dir); // длина по нормали от точки ray_point до ray_point2 //printf("\n%f %f %f", normal.x, normal.y, normal.z); //printf("\n%f %f %f\n", subd.x, subd.y, subd.z); //printf("\n%f %f", e, d); if (e) return (rp + (dir * (-d / e))); // точка пересечения else if (!d) return (rp); // прямая лежит в плоскости else NON = 1; // прямая параллельна плоскости return MATH3DVEC(0,0,0); } //*/ ; //>> Поиск точки пересечения луча и плоскости (плоскость по 3 точкам) inline void MathRayToPlaneIntersect(const MATH3DVEC & p, const MATH3DVEC & p2, const MATH3DVEC & p3, const MATH3DVEC & rp, const MATH3DVEC & rp2, MATH3DVEC& out, bool& NON) { MATH3DVEC vec1(p2.x-p.x, p2.y-p.y, p2.z-p.z); MATH3DVEC vec2(p3.x-p.x, p3.y-p.y, p3.z-p.z); MATH3DVEC normal(vec1.y*vec2.z - vec1.z*vec2.y, vec1.z*vec2.x - vec1.x*vec2.z, vec1.x*vec2.y - vec1.y*vec2.x); normal._normalize_check(); NON = 0; MATH3DVEC sub(rp - p); MATH3DVEC dir(rp2 - rp); float d = MathDotVec(normal, sub); // длина по нормали от точки ray_point до плоскости float e = MathDotVec(normal, dir); // длина по нормали от точки ray_point до ray_point2 //printf("\n%f %f %f", normal.x, normal.y, normal.z); //printf("\n%f %f %f\n", subd.x, subd.y, subd.z); //printf("\n%f %f", e, d); if (e) { out = rp + (dir * (-d / e)); return; } // точка пересечения else if (!d) { out = rp; return; } // прямая лежит в плоскости else NON = 1; // прямая параллельна плоскости out.x = out.y = out.z = 0; } //>> Поиск точки пересечения луча и плоскости (плоскость по точке и нормали) inline MATH3DVEC MathRayToPlaneIntersect(const MATH3DVEC & p, const MATH3DVEC & normal, const MATH3DVEC & rp, const MATH3DVEC & rp2, bool& NON) { NON = 0; MATH3DVEC sub(rp - p); // MATH3DVEC dir(rp2 - rp); // направление взгляда float d = MathDotVec(normal, sub); // длина по нормали от точки ray_point до плоскости float e = MathDotVec(normal, dir); // длина по нормали от точки ray_point до ray_point2 if (e) return (rp + (dir * (-d / e))); // точка пересечения else if (!d) return (rp); // прямая лежит в плоскости else NON = 1; // прямая параллельна плоскости return MATH3DVEC(0,0,0); }//*/ ; //>> Поиск точки пересечения луча и плоскости (плоскость по точке и нормали) inline void MathRayToPlaneIntersect(const MATH3DVEC & p, const MATH3DVEC & normal, const MATH3DVEC & rp, const MATH3DVEC & rp2, MATH3DVEC& out, bool& NON) { NON = 0; MATH3DVEC sub(rp - p); // MATH3DVEC dir(rp2 - rp); // направление взгляда float d = MathDotVec(normal, sub); // длина по нормали от точки ray_point до плоскости float e = MathDotVec(normal, dir); // длина по нормали от точки ray_point до ray_point2 if (e) { out = rp + (dir * (-d / e)); return; } // точка пересечения else if (!d) { out = rp; return; } // прямая лежит в плоскости else NON = 1; // прямая параллельна плоскости out.x = out.y = out.z = 0; } //>> Поиск точки пересечения луча и плоскости inline MATH3DVEC MathRayToPlaneIntersect(const MATH3DPLANE plane, const MATH3DVEC rp, const MATH3DVEC rp2, bool& NON) { NON = 0; MATH3DVEC sub(rp - plane.P); MATH3DVEC dir(rp2 - rp); float d = MathDotVec(plane.N, sub); // длина по нормали от точки ray_point до плоскости float e = MathDotVec(plane.N, dir); // длина по нормали от точки ray_point до ray_point2 if (e) return (rp + (dir * (-d / e))); // точка пересечения else if (!d) return (rp); // прямая лежит в плоскости else NON = 1; // прямая параллельна плоскости return MATH3DVEC(0,0,0); // NON = 0; // MATH3DVEC sub(rp - plane.P); // MATH3DVEC dir(rp2 - rp); // FLOAT d = MathDotVec(plane.N, sub); // FLOAT e = MathDotVec(plane.N, dir); // // if (e) return (rp - (dir * ((plane.d + MathDotVec(plane.N, rp)) / e))); // else if (!d) return (rp); // else NON = 1; // // return MATH3DVEC(0,0,0); } //*/ ; //>> Поиск точки пересечения луча и плоскости inline void MathRayToPlaneIntersect(const MATH3DPLANE & plane, const MATH3DVEC & rp, const MATH3DVEC & rp2, MATH3DVEC& out, bool& NON) { NON = 0; MATH3DVEC sub(rp - plane.P); MATH3DVEC dir(rp2 - rp); float d = MathDotVec(plane.N, sub); // длина по нормали от точки ray_point до плоскости float e = MathDotVec(plane.N, dir); // длина по нормали от точки ray_point до ray_point2 if (e) { out = rp + (dir * (-d / e)); return; } // точка пересечения else if (!d) { out = rp; return; } // прямая лежит в плоскости else NON = 1; // прямая параллельна плоскости out.x = out.y = out.z = 0; } //>> Составление матрицы перемещения inline MATH3DMATRIX MathTranslateMatrix(const float dx, const float dy, const float dz) { MATH_TRANSLATE_MATRIX(dx, dy, dz) return MT; } //*/ ; //>> Составление матрицы перемещения inline MATH3DMATRIX MathTranslateMatrix(const MATH3DVEC & pos) { MATH_TRANSLATE_MATRIX(pos.x, pos.y, pos.z) return MT; }//*/ ; //>> Составление матрицы перемещения inline void MathTranslateMatrix(const float dx, const float dy, const float dz, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(dx, dy, dz) M = MT; } //>> Составление матрицы перемещения inline void MathTranslateMatrix(const MATH3DVEC & pos, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(pos.x, pos.y, pos.z) M = MT; } //>> Составление матрицы масштабирования inline MATH3DMATRIX MathScaleMatrix(const float sx, const float sy, const float sz) { MATH_SCALE_MATRIX(sx, sy, sz) return MS; } //*/ ; //>> Составление матрицы масштабирования inline MATH3DMATRIX MathScaleMatrix(const MATH3DVEC & scale) { MATH_SCALE_MATRIX(scale.x, scale.y, scale.z) return MS; } //*/ ; //>> Составление матрицы масштабирования inline void MathScaleMatrix(const float sx, const float sy, const float sz, MATH3DMATRIX& M) { MATH_SCALE_MATRIX(sx, sy, sz) M = MS; } //>> Составление матрицы масштабирования inline void MathScaleMatrix(const MATH3DVEC & scale, MATH3DMATRIX& M) { MATH_SCALE_MATRIX(scale.x, scale.y, scale.z) M = MS; } //>> Составление матрицы вращения (вокруг оси X) /* inline MATH3DMATRIX MathRotateMatrix_X(const float angle) { MATH_ROTATE_MATRIX_X(angle) return MRx; } //*/ ; //>> Составление матрицы вращения (вокруг оси Y) /* inline MATH3DMATRIX MathRotateMatrix_Y(const float angle) { MATH_ROTATE_MATRIX_Y(angle) return MRy; } //*/ ; //>> Составление матрицы вращения (вокруг оси Z) /* inline MATH3DMATRIX MathRotateMatrix_Z(const float angle) { MATH_ROTATE_MATRIX_Z(angle) return MRz; } //*/ ; //>> Составление матрицы вращения (вокруг оси X) /* inline MATH3DMATRIX MathRotateMatrix_X(const float sin, const float cos) { MATH3DMATRIX M; M._22 = cos; M._33 = M._22; M._23 = sin; M._32 = -M._23; return M; } //*/ ; //>> Составление матрицы вращения (вокруг оси Y) /* inline MATH3DMATRIX MathRotateMatrix_Y(const float sin, const float cos) { MATH3DMATRIX M; M._11 = cos; M._33 = M._11; M._31 = sin; M._13 = -M._31; return M; } //*/ ; //>> Составление матрицы вращения (вокруг оси Z) /* inline MATH3DMATRIX MathRotateMatrix_Z(const float sin, const float cos) { MATH3DMATRIX M; M._11 = cos; M._22 = M._11; M._12 = sin; M._21 = -M._12; return M; } //*/ ; //>> Составление матрицы вращения /* inline MATH3DMATRIX MathRotateMatrix(const float ax, const float ay, const float az) { MATH_ROTATE_MATRIX_A(ax,ay,az) return MRz; } //*/ ; //>> Составление матрицы вращения /* inline MATH3DMATRIX MathRotateMatrix(const MATH3DVEC & angle) { MATH_ROTATE_MATRIX_A(angle.x, angle.y, angle.z) return MRz; } //*/ ; //>> Составление матрицы вращения (обратное преобразование) /* inline MATH3DMATRIX MathRotateMatrixBack(const float ax, const float ay, const float az) { MATH_ROTATE_MATRIX_X(-ax) MATH_ROTATE_MATRIX_Y(-ay) MATH_ROTATE_MATRIX_Z(-az) MRy *= MRx; MRy *= MRz; return MRy; } //*/ ; //>> Составление матрицы вращения (обратное преобразование) /* inline MATH3DMATRIX MathRotateMatrixBack(const MATH3DVEC & angle) { MATH_ROTATE_MATRIX_X(-angle.x) MATH_ROTATE_MATRIX_Y(-angle.y) MATH_ROTATE_MATRIX_Z(-angle.z) MRy *= MRx; MRy *= MRz; return MRy; } //*/ ; //>> Составление матрицы вращения (вокруг оси X) /* inline void MathRotateMatrix_X(const float angle, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_X(angle) M = MRx; }//*/ ; //>> Составление матрицы вращения (вокруг оси Y) /* inline void MathRotateMatrix_Y(const float angle, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_Y(angle) M = MRy; }//*/ ; //>> Составление матрицы вращения (вокруг оси Z) /* inline void MathRotateMatrix_Z(const float angle, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_Z(angle) M = MRz; }//*/ ; //>> Составление матрицы вращения /* inline void MathRotateMatrix(const float ax, const float ay, const float az, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_A(ax,ay,az) M = MRz; }//*/ ; //>> Составление матрицы вращения /* inline void MathRotateMatrix(const MATH3DVEC & angle, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_A(angle.x, angle.y, angle.z) M = MRz; }//*/ ; //>> Составление матрицы вращения (обратное преобразование) /* inline void MathRotateMatrixBack(const float ax, const float ay, const float az, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_X(-ax) MATH_ROTATE_MATRIX_Y(-ay) MATH_ROTATE_MATRIX_Z(-az) MRy *= MRx; MRy *= MRz; M = MRy; } //*/ ; //>> Составление матрицы вращения (обратное преобразование) /* inline void MathRotateMatrixBack(const MATH3DVEC & angle, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX_X(-angle.x) MATH_ROTATE_MATRIX_Y(-angle.y) MATH_ROTATE_MATRIX_Z(-angle.z) MRy *= MRx; MRy *= MRz; M = MRy; } //*/ ; //>> Составление матрицы вращения вокруг произвольной оси inline MATH3DMATRIX MathRotationAxisMatrix(const MATH3DVEC & axis, const float angle) { MATH3DMATRIX M; float sin = CTAB::sinA(angle); float cos = CTAB::cosA(angle); float _cos = 1.0f - cos; float _cosX = _cos * axis.x; float _cosY = _cos * axis.y; float _cosZ = _cos * axis.z; float _sinX = sin * axis.x; float _sinY = sin * axis.y; float _sinZ = sin * axis.z; M._11 = _cosX * axis.x + cos; M._21 = _cosX * axis.y - _sinZ; M._31 = _cosX * axis.z + _sinY; M._12 = _cosY * axis.x + _sinZ; M._22 = _cosY * axis.y + cos; M._32 = _cosY * axis.z - _sinX; M._13 = _cosZ * axis.x - _sinY; M._23 = _cosZ * axis.y + _sinX; M._33 = _cosZ * axis.z + cos; return M; } //*/ ; //>> Составление матрицы вращения вокруг произвольной оси inline void MathRotationAxisMatrix(const MATH3DVEC & axis, const float angle, MATH3DMATRIX& M) { M = MATH3DMATRIX(); float sin = CTAB::sinA(angle); float cos = CTAB::cosA(angle); float _cos = 1.0f - cos; float _cosX = _cos * axis.x; float _cosY = _cos * axis.y; float _cosZ = _cos * axis.z; float _sinX = sin * axis.x; float _sinY = sin * axis.y; float _sinZ = sin * axis.z; M._11 = _cosX * axis.x + cos; M._21 = _cosX * axis.y - _sinZ; M._31 = _cosX * axis.z + _sinY; M._12 = _cosY * axis.x + _sinZ; M._22 = _cosY * axis.y + cos; M._32 = _cosY * axis.z - _sinX; M._13 = _cosZ * axis.x - _sinY; M._23 = _cosZ * axis.y + _sinX; M._33 = _cosZ * axis.z + cos; } //>> Составление матрицы вращения из кватерниона inline MATH3DMATRIX MathRotateMatrix(const MATH3DQUATERNION & Q) { MATH_ROTATE_MATRIX(Q.x, Q.y, Q.z, Q.w) return MR; } //*/ ; //>> Составление матрицы вращения из кватерниона inline void MathRotateMatrix(const MATH3DQUATERNION & Q, MATH3DMATRIX& M) { MATH_ROTATE_MATRIX(Q.x, Q.y, Q.z, Q.w) M = MR; } //>> Составление комплексной матрицы позиции в мире /* inline MATH3DMATRIX MathWorldMatrix(const float dx, const float dy, const float dz, const float ax, const float ay, const float az, const float sx, const float sy, const float sz) { return MathScaleMatrix(sx, sy, sz) * MathRotateMatrix(ax, ay, az) * MathTranslateMatrix(dx, dy, dz); }//*/ ; //>> Составление комплексной матрицы позиции в мире /* inline MATH3DMATRIX MathWorldMatrix(const MATH3DVEC & P, const MATH3DVEC & A, const MATH3DVEC & S) { MATH_TRANSLATE_MATRIX(P.x, P.y, P.z) MATH_ROTATE_MATRIX_A(A.x, A.y, A.z) MATH_SCALE_MATRIX(S.x, S.y, S.z) MS *= MRz; MS *= MT; return MS; } //*/ ; //>> Составление комплексной матрицы позиции в мире /* inline void MathWorldMatrix(const float dx, const float dy, const float dz, const float ax, const float ay, const float az, const float sx, const float sy, const float sz, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(dx, dy, dz) MATH_ROTATE_MATRIX_A(ax, ay, az) MATH_SCALE_MATRIX(sx, sy, sz) MS *= MRz; MS *= MT; M = MS; } //*/ ; //>> Составление комплексной матрицы позиции в мире /* inline void MathWorldMatrix(const MATH3DVEC & P, const MATH3DVEC & A, const MATH3DVEC & S, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(P.x, P.y, P.z) MATH_ROTATE_MATRIX_A(A.x, A.y, A.z) MATH_SCALE_MATRIX(S.x, S.y, S.z) MS *= MRz; MS *= MT; M = MS; } //*/ ; //>> Составление комплексной матрицы позиции в мире inline MATH3DMATRIX MathWorldMatrix(const MATH3DVEC & P, const MATH3DQUATERNION & Q, const MATH3DVEC & S) { MATH_TRANSLATE_MATRIX(P.x, P.y, P.z) MATH_ROTATE_MATRIX(Q.x, Q.y, Q.z, Q.w) MATH_SCALE_MATRIX(S.x, S.y, S.z) MS *= MR; MS *= MT; return MS; } //*/ ; //>> Составление комплексной матрицы позиции в мире inline void MathWorldMatrix(const MATH3DVEC & P, const MATH3DQUATERNION & Q, const MATH3DVEC & S, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(P.x, P.y, P.z) MATH_ROTATE_MATRIX(Q.x, Q.y, Q.z, Q.w) MATH_SCALE_MATRIX(S.x, S.y, S.z) MS *= MR; MS *= MT; M = MS; } //>> Составление комплексной матрицы позиции в мире /* inline MATH3DMATRIX MathWorldMatrix(const MATH3DMATRIX & mPos, const MATH3DMATRIX & mAngle, const MATH3DMATRIX & mScale) { MATH3DMATRIX M = mScale; M *= mAngle; M *= mPos; return M; }//*/ ; //>> Составление комплексной матрицы позиции в мире /* inline void MathWorldMatrix(const MATH3DMATRIX & mPos, const MATH3DMATRIX & mAngle, const MATH3DMATRIX & mScale, MATH3DMATRIX& out) { out = mScale; out *= mAngle; out *= mPos; } //*/ ; //>> Составление комплексной матрицы позиции в мире (обратное преобразование) /* inline MATH3DMATRIX MathWorldMatrixBack(const float dx, const float dy, const float dz, const float ax, const float ay, const float az, const float sx, const float sy, const float sz) { MATH_TRANSLATE_MATRIX(-dx, -dy, -dz) MATH_SCALE_MATRIX(1.f/sx, 1.f/sy, 1.f/sz) MATH_ROTATE_MATRIX_X(-ax) MATH_ROTATE_MATRIX_Y(-ay) MATH_ROTATE_MATRIX_Z(-az) MRy *= MRx; MRy *= MRz; MT *= MRy; MT *= MS; return MT; } //*/ ; //>> Составление комплексной матрицы позиции в мире (обратное преобразование) /* inline MATH3DMATRIX MathWorldMatrixBack(const MATH3DVEC & P, const MATH3DVEC & A, const MATH3DVEC & S) { MATH_TRANSLATE_MATRIX(-P.x, -P.y, -P.z) MATH_SCALE_MATRIX(1.f/S.x, 1.f/S.y, 1.f/S.z) MATH_ROTATE_MATRIX_X(-A.x) MATH_ROTATE_MATRIX_Y(-A.y) MATH_ROTATE_MATRIX_Z(-A.z) MRy *= MRx; MRy *= MRz; MT *= MRy; MT *= MS; return MT; } //*/ ; //>> Составление комплексной матрицы позиции в мире (обратное преобразование) /* inline void MathWorldMatrixBack(const float dx, const float dy, const float dz, const float ax, const float ay, const float az, const float sx, const float sy, const float sz, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(-dx, -dy, -dz) MATH_SCALE_MATRIX(1.f/sx, 1.f/sy, 1.f/sz) MATH_ROTATE_MATRIX_X(-ax) MATH_ROTATE_MATRIX_Y(-ay) MATH_ROTATE_MATRIX_Z(-az) MRy *= MRx; MRy *= MRz; MT *= MRy; MT *= MS; M = MT; } //*/ ; //>> Составление комплексной матрицы позиции в мире (обратное преобразование) /* inline void MathWorldMatrixBack(const MATH3DVEC & P, const MATH3DVEC & A, const MATH3DVEC & S, MATH3DMATRIX& M) { MATH_TRANSLATE_MATRIX(-P.x, -P.y, -P.z) MATH_SCALE_MATRIX(1.f/S.x, 1.f/S.y, 1.f/S.z) MATH_ROTATE_MATRIX_X(-A.x) MATH_ROTATE_MATRIX_Y(-A.y) MATH_ROTATE_MATRIX_Z(-A.z) MRy *= MRx; MRy *= MRz; MT *= MRy; MT *= MS; M = MT; } //*/ ; //>> Выполняет векторное произведение 3 векторов VEC4 (CROSS product) inline MATH3DVEC4 MathCrossVec(const MATH3DVEC4 & vec1, const MATH3DVEC4 & vec2, const MATH3DVEC4 & vec3) { return MATH3DVEC4( vec1.y * (vec2.z * vec3.w - vec3.z * vec2.w) - vec1.z * (vec2.y * vec3.w - vec3.y * vec2.w) + vec1.w * (vec2.y * vec3.z - vec2.z * vec3.y) , -(vec1.x * (vec2.z * vec3.w - vec3.z * vec2.w) - vec1.z * (vec2.x * vec3.w - vec3.x * vec2.w) + vec1.w * (vec2.x * vec3.z - vec3.x * vec2.z)) , vec1.x * (vec2.y * vec3.w - vec3.y * vec2.w) - vec1.y * (vec2.x * vec3.w - vec3.x * vec2.w) + vec1.w * (vec2.x * vec3.y - vec3.x * vec2.y) , -(vec1.x * (vec2.y * vec3.z - vec3.y * vec2.z) - vec1.y * (vec2.x * vec3.z - vec3.x * vec2.z) + vec1.z * (vec2.x * vec3.y - vec3.x * vec2.y)) ); }; //*/ ; //>> Выполняет векторное произведение 3 векторов VEC4 (CROSS product) inline void MathCrossVec(const MATH3DVEC4 & vec1, const MATH3DVEC4 & vec2, const MATH3DVEC4 & vec3, MATH3DVEC4& out) { out = MATH3DVEC4( vec1.y * (vec2.z * vec3.w - vec3.z * vec2.w) - vec1.z * (vec2.y * vec3.w - vec3.y * vec2.w) + vec1.w * (vec2.y * vec3.z - vec2.z * vec3.y) , -(vec1.x * (vec2.z * vec3.w - vec3.z * vec2.w) - vec1.z * (vec2.x * vec3.w - vec3.x * vec2.w) + vec1.w * (vec2.x * vec3.z - vec3.x * vec2.z)) , vec1.x * (vec2.y * vec3.w - vec3.y * vec2.w) - vec1.y * (vec2.x * vec3.w - vec3.x * vec2.w) + vec1.w * (vec2.x * vec3.y - vec3.x * vec2.y) , -(vec1.x * (vec2.y * vec3.z - vec3.y * vec2.z) - vec1.y * (vec2.x * vec3.z - vec3.x * vec2.z) + vec1.z * (vec2.x * vec3.y - vec3.x * vec2.y)) ); }; //>> Определитель матрицы inline float MathMatrixDeterminant(const MATH3DMATRIX & M) { MATH3DVEC4 v1, v2, v3; v1.x = M._11; v1.y = M._21; v1.z = M._31; v1.w = M._41; v2.x = M._12; v2.y = M._22; v2.z = M._32; v2.w = M._42; v3.x = M._13; v3.y = M._23; v3.z = M._33; v3.w = M._43; MATH3DVEC4 minor; MathCrossVec(v1, v2, v3, minor); return -( (M._14 * minor.x) + (M._24 * minor.y) + (M._34 * minor.z) + (M._44 * minor.w) ); } //>> Определитель матрицы inline void MathMatrixDeterminant(const MATH3DMATRIX & M, float& det) { MATH3DVEC4 v1, v2, v3; v1.x = M._11; v1.y = M._21; v1.z = M._31; v1.w = M._41; v2.x = M._12; v2.y = M._22; v2.z = M._32; v2.w = M._42; v3.x = M._13; v3.y = M._23; v3.z = M._33; v3.w = M._43; MATH3DVEC4 minor; MathCrossVec(v1, v2, v3, minor); det = -( (M._14 * minor.x) + (M._24 * minor.y) + (M._34 * minor.z) + (M._44 * minor.w) ); } //>> Составления матрицы обратного преобразования inline MATH3DMATRIX MathInverseMatrix(const MATH3DMATRIX & M, float& det) { MATH3DMATRIX out; MATH3DVEC4 v, _v[3]; MathMatrixDeterminant(M, det); if (!det) return MATH3DMATRIX(); for (int i=0; i<4; i++) { // i 0 1 2 3 for (int n, j=0; j<4; j++) { // j 1,2,3 0,2,3 0,1,3 0,1,2 -> 234 134 124 123 if (j != i ) { n = j; if ( j > i ) n--; // n 0,1,2 0,1,2 0,1,2 0,1,2 -> [012].xyzw = (234 134 124 123) [0123] _v[n].x = M._[j][0]; _v[n].y = M._[j][1]; _v[n].z = M._[j][2]; _v[n].w = M._[j][3]; } } MathCrossVec(_v[0],_v[1],_v[2],v); float f1, f2; switch(i) { case 0: f1 = 1; break; case 1: f1 = -1; break; case 2: f1 = 1; break; case 3: f1 = -1; break; } for (int j=0; j<4; j++) { switch(j) { case 0: f2 = v.x; break; case 1: f2 = v.y; break; case 2: f2 = v.z; break; case 3: f2 = v.w; break; } out._[j][i] = f1 * f2 / det; }} // MATH3DMATRIX out; // MATH3DVEC4 v, v1, v2, v3; // // det = MathMatrixDeterminant(M); if (!det) return MATH3DMATRIX(); // // v1.x = M._21; v2.x = M._31; v3.x = M._41; // v1.y = M._22; v2.y = M._32; v3.y = M._42; // v1.z = M._23; v2.z = M._33; v3.z = M._43; // v1.w = M._24; v2.w = M._34; v3.w = M._44; v = MathCrossVec(v1,v2,v3); // // out._11 = v.x / det; // out._21 = v.y / det; // out._31 = v.z / det; // out._41 = v.w / det; // // v1.x = M._11; v2.x = M._31; v3.x = M._41; // v1.y = M._12; v2.y = M._32; v3.y = M._42; // v1.z = M._13; v2.z = M._33; v3.z = M._43; // v1.w = M._14; v2.w = M._34; v3.w = M._44; v = MathCrossVec(v1,v2,v3); // // out._12 = -v.x / det; // out._22 = -v.y / det; // out._32 = -v.z / det; // out._42 = -v.w / det; // // v1.x = M._11; v2.x = M._21; v3.x = M._41; // v1.y = M._12; v2.y = M._22; v3.y = M._42; // v1.z = M._13; v2.z = M._23; v3.z = M._43; // v1.w = M._14; v2.w = M._24; v3.w = M._44; v = MathCrossVec(v1,v2,v3); // // out._13 = v.x / det; // out._23 = v.y / det; // out._33 = v.z / det; // out._43 = v.w / det; // // v1.x = M._11; v2.x = M._21; v3.x = M._31; // v1.y = M._12; v2.y = M._22; v3.y = M._32; // v1.z = M._13; v2.z = M._23; v3.z = M._33; // v1.w = M._14; v2.w = M._24; v3.w = M._34; v = MathCrossVec(v1,v2,v3); // // out._14 = -v.x / det; // out._24 = -v.y / det; // out._34 = -v.z / det; // out._44 = -v.w / det; return out; } //*/ ; //>> Составления матрицы обратного преобразования inline void MathInverseMatrix(const MATH3DMATRIX & M, float& det, MATH3DMATRIX& out) { MATH3DVEC4 v, _v[3]; MathMatrixDeterminant(M, det); if (!det) { out._default(); return; } for (int i=0; i<4; i++) { // i 0 1 2 3 for (int n, j=0; j<4; j++) { // j 1,2,3 0,2,3 0,1,3 0,1,2 -> 234 134 124 123 if (j != i ) { n = j; if ( j > i ) n--; // n 0,1,2 0,1,2 0,1,2 0,1,2 -> [012].xyzw = (234 134 124 123) [0123] _v[n].x = M._[j][0]; _v[n].y = M._[j][1]; _v[n].z = M._[j][2]; _v[n].w = M._[j][3]; } } MathCrossVec(_v[0],_v[1],_v[2],v); float f1, f2; switch(i) { case 0: f1 = 1; break; case 1: f1 = -1; break; case 2: f1 = 1; break; case 3: f1 = -1; break; } for (int j=0; j<4; j++) { switch(j) { case 0: f2 = v.x; break; case 1: f2 = v.y; break; case 2: f2 = v.z; break; case 3: f2 = v.w; break; } out._[j][i] = f1 * f2 / det; } } } //>> Составление транспонированной матрицы inline MATH3DMATRIX MathTransposeMatrix(const MATH3DMATRIX & M) { MATH3DMATRIX out; for(int i=0; i<4; i++) for(int j=0; j<4; j++) out._[i][j] = M._[j][i]; return out; } ; //>> Составление транспонированной матрицы inline void MathTransposeMatrix(const MATH3DMATRIX & M, MATH3DMATRIX& out) { /* MATH3DMATRIX _out; for(int i=0; i<4; i++) for(int j=0; j<4; j++) _out._[i][j] = M._[j][i]; out = _out; //*/ out = M; _SWAP(out._13, out._31); _SWAP(out._21, out._12); _SWAP(out._32, out._23); _SWAP(out._41, out._14); _SWAP(out._42, out._24); _SWAP(out._43, out._34); } ; //>> Составление транспонированной матрицы /* inline void MathTransposeMatrix(MATH3DMATRIX& in_out) { _SWAP(in_out._13, in_out._31); _SWAP(in_out._21, in_out._12); _SWAP(in_out._32, in_out._23); _SWAP(in_out._41, in_out._14); _SWAP(in_out._42, in_out._24); _SWAP(in_out._43, in_out._34); } //*/ ; //>> Составляет левостороннюю матрицу перспективной проекции (FOV based) inline MATH3DMATRIX MathPerspectiveFovLHMatrix(const float fovy, const float aspect, const float zn, const float zf) { MATH3DMATRIX M; float t = 1.0f / CTAB::tanA(fovy*0.5f); // / 2.0f); float z = zn - zf; M._11 = t / aspect; M._22 = t; M._33 = zf / -z; M._34 = 1.0f; M._43 = (zf * zn) / z; M._44 = 0.0f; return M; } //*/ ; //>> Составляет левостороннюю матрицу перспективной проекции (FOV based) inline void MathPerspectiveFovLHMatrix(const float fovy, const float aspect, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float t = 1.0f / CTAB::tanA(fovy*0.5f); // / 2.0f); float z = zn - zf; M._11 = t / aspect; M._22 = t; M._33 = zf / -z; M._34 = 1.0f; M._43 = (zf * zn) / z; M._44 = 0.0f; } //>> Составляет правостороннюю матрицу перспективной проекции (FOV based) inline MATH3DMATRIX MathPerspectiveFovRHMatrix(const float fovy, const float aspect, const float zn, const float zf) { MATH3DMATRIX M; float t = CTAB::tanA(fovy*0.5f); // / 2.0f); float z = zn - zf; M._11 = 1.0f / (aspect * t); M._22 = 1.0f / t; M._33 = zf / z; M._34 = -1.0f; M._43 = (zf * zn) / z; M._44 = 0.0f; return M; } //*/ ; //>> Составляет правостороннюю матрицу перспективной проекции (FOV based) inline void MathPerspectiveFovRHMatrix(const float fovy, const float aspect, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float t = CTAB::tanA(fovy*0.5f); // / 2.0f); float z = zn - zf; M._11 = 1.0f / (aspect * t); M._22 = 1.0f / t; M._33 = zf / z; M._34 = -1.0f; M._43 = (zf * zn) / z; M._44 = 0.0f; } //>> Составляет левостороннюю матрицу перспективной проекции inline MATH3DMATRIX MathPerspectiveLHMatrix(const float w, const float h, const float zn, const float zf) { MATH3DMATRIX M; float z = zn - zf; float z2 = 2.0f * zn; M._11 = z2 / w; M._22 = z2 / h; M._33 = zf / -z; M._43 = zn * zf / z; M._34 = 1.0f; M._44 = 0.0f; return M; } //*/ ; //>> Составляет левостороннюю матрицу перспективной проекции inline void MathPerspectiveLHMatrix(const float w, const float h, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float z = zn - zf; float z2 = 2.0f * zn; M._11 = z2 / w; M._22 = z2 / h; M._33 = zf / -z; M._43 = zn * zf / z; M._34 = 1.0f; M._44 = 0.0f; } //>> Составляет правостороннюю матрицу перспективной проекции inline MATH3DMATRIX MathPerspectiveRHMatrix(const float w, const float h, const float zn, const float zf) { MATH3DMATRIX M; float z = zn - zf; float z2 = 2.0f * zn; M._11 = z2 / w; M._22 = z2 / h; M._33 = zf / z; M._43 = zn * zf / z; M._34 = -1.0f; M._44 = 0.0f; return M; } //*/ ; //>> Составляет правостороннюю матрицу перспективной проекции inline void MathPerspectiveRHMatrix(const float & w, const float & h, const float & zn, const float & zf, MATH3DMATRIX& M) { M._default(); float z = zn - zf; float z2 = 2.0f * zn; M._11 = z2 / w; M._22 = z2 / h; M._33 = zf / z; M._43 = zn * zf / z; M._34 = -1.0f; M._44 = 0.0f; } //>> Составляет настроенную левостороннюю матрицу перспективной проекции (left, right, bottom, top, z-near, z-far) inline MATH3DMATRIX MathPerspectiveOffCenterLHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf) { MATH3DMATRIX M; float z = zn - zf; float z2 = 2.0f * zn; float rl = r - l; float bt = b - t; M._11 = z2 / rl; M._22 = -z2 / bt; M._31 = -1.0f - 2.0f * l / rl; M._32 = 1.0f + 2.0f * t / bt; M._33 = -zf / z; M._43 = (zn * zf) / z; M._34 = 1.0f; M._44 = 0.0f; return M; } //*/ ; //>> Составляет настроенную левостороннюю матрицу перспективной проекции (left, right, bottom, top, z-near, z-far) inline void MathPerspectiveOffCenterLHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float z = zn - zf; float z2 = 2.0f * zn; float rl = r - l; float bt = b - t; M._11 = z2 / rl; M._22 = -z2 / bt; M._31 = -1.0f - 2.0f * l / rl; M._32 = 1.0f + 2.0f * t / bt; M._33 = -zf / z; M._43 = (zn * zf) / z; M._34 = 1.0f; M._44 = 0.0f; } //>> Составляет настроенную правостороннюю матрицу перспективной проекции (left, right, bottom, top, z-near, z-far) inline MATH3DMATRIX MathPerspectiveOffCenterRHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf) { MATH3DMATRIX M; float z = zn - zf; float z2 = 2.0f * zn; float rl = r - l; float bt = b - t; M._11 = z2 / rl; M._22 = -z2 / bt; M._31 = 1.0f + 2.0f * l / rl; M._32 = -1.0f - 2.0f * t / bt; M._33 = zf / z; M._43 = (zn * zf) / z; M._34 = -1.0f; M._44 = 0.0f; return M; } //*/ ; //>> Составляет настроенную правостороннюю матрицу перспективной проекции (left, right, bottom, top, z-near, z-far) inline void MathPerspectiveOffCenterRHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float z = zn - zf; float z2 = 2.0f * zn; float rl = r - l; float bt = b - t; M._11 = z2 / rl; M._22 = -z2 / bt; M._31 = 1.0f + 2.0f * l / rl; M._32 = -1.0f - 2.0f * t / bt; M._33 = zf / z; M._43 = (zn * zf) / z; M._34 = -1.0f; M._44 = 0.0f; } //>> Составляет левостороннюю матрицу вида (взгляда) inline MATH3DMATRIX MathLookAtLHMatrix(const MATH3DVEC & eye, const MATH3DVEC & at, const MATH3DVEC & up) { MATH3DMATRIX M; MATH3DVEC OZ = at - eye; OZ._normalize_check(); MATH3DVEC OX = MathCrossVec(up, OZ); OX._normalize_check(); MATH3DVEC OY = MathCrossVec(OZ, OX); OY._normalize_check(); M._11 = OX.x; M._12 = OY.x; M._13 = OZ.x; M._14 = 0.0f; M._21 = OX.y; M._22 = OY.y; M._23 = OZ.y; M._24 = 0.0f; M._31 = OX.z; M._32 = OY.z; M._33 = OZ.z; M._34 = 0.0f; M._41 = -MathDotVec(OX, eye); M._42 = -MathDotVec(OY, eye); M._43 = -MathDotVec(OZ, eye); M._44 = 1.0f; return M; } //*/ ; //>> Составляет левостороннюю матрицу вида (взгляда) inline void MathLookAtLHMatrix(const MATH3DVEC & eye, const MATH3DVEC & at, const MATH3DVEC & up, MATH3DMATRIX& M) { MATH3DVEC OZ = at - eye; OZ._normalize_check(); MATH3DVEC OX = MathCrossVec(up, OZ); OX._normalize_check(); MATH3DVEC OY = MathCrossVec(OZ, OX); OY._normalize_check(); M._11 = OX.x; M._12 = OY.x; M._13 = OZ.x; M._14 = 0.0f; M._21 = OX.y; M._22 = OY.y; M._23 = OZ.y; M._24 = 0.0f; M._31 = OX.z; M._32 = OY.z; M._33 = OZ.z; M._34 = 0.0f; M._41 = -MathDotVec(OX, eye); M._42 = -MathDotVec(OY, eye); M._43 = -MathDotVec(OZ, eye); M._44 = 1.0f; } //>> Составляет правостороннюю матрицу вида (взгляда) inline MATH3DMATRIX MathLookAtRHMatrix(const MATH3DVEC & eye, const MATH3DVEC & at, const MATH3DVEC & up) { MATH3DMATRIX M; MATH3DVEC OZ = at - eye; OZ._normalize_check(); MATH3DVEC OX = MathCrossVec(up, OZ); OX._normalize_check(); MATH3DVEC OY = MathCrossVec(OZ, OX); OY._normalize_check(); M._11 = -OX.x; M._12 = OY.x; M._13 = -OZ.x; M._14 = 0.0f; M._21 = -OX.y; M._22 = OY.y; M._23 = -OZ.y; M._24 = 0.0f; M._31 = -OX.z; M._32 = OY.z; M._33 = -OZ.z; M._34 = 0.0f; M._41 = MathDotVec(OX, eye); M._42 = -MathDotVec(OY, eye); M._43 = MathDotVec(OZ, eye); M._44 = 1.0f; return M; } //*/ //>> Составляет правостороннюю матрицу вида (взгляда) inline void MathLookAtRHMatrix(const MATH3DVEC & eye, const MATH3DVEC & at, const MATH3DVEC & up, MATH3DMATRIX& M) { MATH3DVEC OZ = at - eye; OZ._normalize_check(); MATH3DVEC OX = MathCrossVec(up, OZ); OX._normalize_check(); MATH3DVEC OY = MathCrossVec(OZ, OX); OY._normalize_check(); M._11 = -OX.x; M._12 = OY.x; M._13 = -OZ.x; M._14 = 0.0f; M._21 = -OX.y; M._22 = OY.y; M._23 = -OZ.y; M._24 = 0.0f; M._31 = -OX.z; M._32 = OY.z; M._33 = -OZ.z; M._34 = 0.0f; M._41 = MathDotVec(OX, eye); M._42 = -MathDotVec(OY, eye); M._43 = MathDotVec(OZ, eye); M._44 = 1.0f; } //>> Составляет настроенную левостороннюю матрицу ортогональной проекции (left, right, bottom, top, z-near, z-far) inline MATH3DMATRIX MathOrthoOffCenterLHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf) { MATH3DMATRIX M; float rl = 2.0f / (r - l); float bt = 2.0f / (b - t); float z = zn - zf; M._11 = rl; M._22 = -bt; M._33 = 1.0f / -z; M._41 = -1.0f - l * rl; M._42 = 1.0f + t * bt; M._43 = zn / z; return M; } //*/ ; //>> Составляет настроенную левостороннюю матрицу ортогональной проекции (left, right, bottom, top, z-near, z-far) inline void MathOrthoOffCenterLHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float rl = 2.0f / (r - l); float bt = 2.0f / (b - t); float z = zn - zf; M._11 = rl; M._22 = -bt; M._33 = 1.0f / -z; M._41 = -1.0f - l * rl; M._42 = 1.0f + t * bt; M._43 = zn / z; } //>> Составляет настроенную правостороннюю матрицу ортогональной проекции (left, right, bottom, top, z-near, z-far) inline MATH3DMATRIX MathOrthoOffCenterRHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf) { MATH3DMATRIX M; float rl = 2.0f / (r - l); float bt = 2.0f / (b - t); float z = zn - zf; M._11 = rl; M._22 = -bt; M._33 = 1.0f / z; M._41 = -1.0f - l * rl; M._42 = 1.0f + t * bt; M._43 = zn / z; return M; } //*/ ; //>> Составляет настроенную правостороннюю матрицу ортогональной проекции (left, right, bottom, top, z-near, z-far) inline void MathOrthoOffCenterRHMatrix(const float l, const float r, const float b, const float t, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float rl = 2.0f / (r - l); float bt = 2.0f / (b - t); float z = zn - zf; M._11 = rl; M._22 = -bt; M._33 = 1.0f / z; M._41 = -1.0f - l * rl; M._42 = 1.0f + t * bt; M._43 = zn / z; } //>> Составляет левостороннюю матрицу ортогональной проекции inline MATH3DMATRIX MathOrthoLHMatrix(const float w, const float h, const float zn, const float zf) { MATH3DMATRIX M; float z = zn - zf; M._11 = 2.0f / w; M._22 = 2.0f / h; M._33 = 1.0f / -z; M._43 = zn / z; return M; } //*/ ; //>> Составляет левостороннюю матрицу ортогональной проекции inline void MathOrthoLHMatrix(const float w, const float h, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float z = zn - zf; M._11 = 2.0f / w; M._22 = 2.0f / h; M._33 = 1.0f / -z; M._43 = zn / z; } //>> Составляет правостороннюю матрицу ортогональной проекции inline MATH3DMATRIX MathOrthoRHMatrix(const float w, const float h, const float zn, const float zf) { MATH3DMATRIX M; float z = zn - zf; M._11 = 2.0f / w; M._22 = 2.0f / h; M._33 = 1.0f / z; M._43 = zn / z; return M; } //*/ ; //>> Составляет правостороннюю матрицу ортогональной проекции inline void MathOrthoRHMatrix(const float w, const float h, const float zn, const float zf, MATH3DMATRIX& M) { M._default(); float z = zn - zf; M._11 = 2.0f / w; M._22 = 2.0f / h; M._33 = 1.0f / z; M._43 = zn / z; } //>> Составляет матрицу отражения относительно плоскости inline MATH3DMATRIX MathReflectMatrix(const MATH3DPLANE & plane) { MATH3DMATRIX M; M._11 = 1.0f - 2.0f * plane.a * plane.a; M._12 = - 2.0f * plane.a * plane.b; M._13 = - 2.0f * plane.a * plane.c; M._21 = - 2.0f * plane.a * plane.b; M._22 = 1.0f - 2.0f * plane.b * plane.b; M._23 = - 2.0f * plane.b * plane.c; M._31 = - 2.0f * plane.c * plane.a; M._32 = - 2.0f * plane.c * plane.b; M._33 = 1.0f - 2.0f * plane.c * plane.c; M._41 = - 2.0f * plane.d * plane.a; M._42 = - 2.0f * plane.d * plane.b; M._43 = - 2.0f * plane.d * plane.c; return M; } //*/ ; //>> Составляет матрицу отражения относительно плоскости inline void MathReflectMatrix(const MATH3DPLANE & plane, MATH3DMATRIX& M) { M._11 = 1.0f - 2.0f * plane.a * plane.a; M._12 = - 2.0f * plane.a * plane.b; M._13 = - 2.0f * plane.a * plane.c; M._14 = 0; M._21 = - 2.0f * plane.a * plane.b; M._22 = 1.0f - 2.0f * plane.b * plane.b; M._23 = - 2.0f * plane.b * plane.c; M._24 = 0; M._31 = - 2.0f * plane.c * plane.a; M._32 = - 2.0f * plane.c * plane.b; M._33 = 1.0f - 2.0f * plane.c * plane.c; M._34 = 0; M._41 = - 2.0f * plane.d * plane.a; M._42 = - 2.0f * plane.d * plane.b; M._43 = - 2.0f * plane.d * plane.c; M._44 = 1; } //>> Нормализация компонент плоскости /* inline MATH3DPLANE MathPlaneNormalize(const MATH3DPLANE & plane) { MATH3DPLANE out; float norm = sqrt(plane.a * plane.a + plane.b * plane.b + plane.c * plane.c); if (norm) { out.a = plane.a / norm; out.b = plane.b / norm; out.c = plane.c / norm; out.d = plane.d / norm; out.N.x = out.a; out.N.y = out.b; out.N.z = out.c; out.P.x = plane.P.x; out.P.y = plane.P.y; out.P.z = plane.P.z; } else { out.a = 0.0f; out.b = 0.0f; out.c = 0.0f; out.d = 0.0f; out.N.x = 0.0f; out.N.y = 0.0f; out.N.z = 0.0f; out.P.x = plane.P.x; out.P.y = plane.P.y; out.P.z = plane.P.z; } return out; } //*/ ; //>> Проверка местоположения точки относительно плоскости (возращает 0, если лежит в ней) inline float MathPlaneDotCoord(const MATH3DPLANE & plane, const MATH3DVEC & coord) { float ret = (plane.a * coord.x + plane.b * coord.y + plane.c * coord.z + plane.d); if (ret < + PRECISION && ret > - PRECISION) ret = 0; return ret; } //>> Проверка местоположения точки относительно плоскости (возращает 0, если лежит в ней) inline void MathPlaneDotCoord(const MATH3DPLANE & plane, const MATH3DVEC & coord, float& out) { out = (plane.a * coord.x + plane.b * coord.y + plane.c * coord.z + plane.d); if (out < + PRECISION && out > - PRECISION) out = 0; } ///////////////////////////////////////////////////////////////////////////////////////// //>> Сравнение (V1 == V2) с точностью < precision > inline bool MathCompareV3_Equal(const MATH3DVEC & v1, const MATH3DVEC & v2, float precision) { if (v1.x >= v2.x - precision && v1.x <= v2.x + precision && v1.y >= v2.y - precision && v1.y <= v2.y + precision && v1.z >= v2.z - precision && v1.z <= v2.z + precision) return true; return false; } //>> Сравнение (V1 != V2) с точностью < precision > inline bool MathCompareV3_NotEqual(const MATH3DVEC & v1, const MATH3DVEC & v2, float precision) { if (v1.x >= v2.x - precision && v1.x <= v2.x + precision && v1.y >= v2.y - precision && v1.y <= v2.y + precision && v1.z >= v2.z - precision && v1.z <= v2.z + precision) return false; return true; } //>> Сравнение (V1 > V2) с точностью < precision > inline bool MathCompareV3_Greater(const MATH3DVEC & v1, const MATH3DVEC & v2, float precision) { if (v1.x > v2.x - precision && v1.y > v2.y - precision && v1.z > v2.z - precision) return true; return false; } //>> Сравнение (V1 >= V2) с точностью < precision > inline bool MathCompareV3_GreaterEqual(const MATH3DVEC & v1, const MATH3DVEC & v2, float precision) { if (v1.x >= v2.x - precision && v1.y >= v2.y - precision && v1.z >= v2.z - precision) return true; return false; } //>> Сравнение (V1 < V2) с точностью < precision > inline bool MathCompareV3_Less(const MATH3DVEC & v1, const MATH3DVEC & v2, float precision) { if (v1.x < v2.x + precision && v1.y < v2.y + precision && v1.z < v2.z + precision) return true; return false; } //>> Сравнение (V1 <= V2) с точностью < precision > inline bool MathCompareV3_LessEqual(const MATH3DVEC & v1, const MATH3DVEC & v2, float precision) { if (v1.x <= v2.x + precision && v1.y <= v2.y + precision && v1.z <= v2.z + precision) return true; return false; } ///////////////////////////////////////////////////////////////////////////////////////// template <typename T> //>> Линейная интерполяция между 2 числами inline T MathSimpleLERP(const T & previous, const T & current, float t) { return previous + static_cast<T>(t * (current - previous)); } template <typename T> //>> Линейная интерполяция между 2 числами inline void MathSimpleLERP(const T & previous, const T & current, float t, T & out) { T = previous + static_cast<T>(t * (current - previous)); } //>> Линейная интерполяция между 2 точками inline MATH3DVEC MathPointLERP(const MATH3DVEC & p1, const MATH3DVEC & p2, float t) { return p1 + (p2 - p1) * t; } //>> Линейная интерполяция между 2 точками inline void MathPointLERP(const MATH3DVEC & p1, const MATH3DVEC & p2, float t, MATH3DVEC & out) { out = p1; out += (p2 - p1) * t; } //>> TODO Cubic Spline interpolation inline void MathPointSQUAD(){} }; #endif // _MATHS_H
9ab3a9ef234fef0b67ff66d223b4897fd26f40e3
09b8fd2258b2092b1d25c9ba2af3797f88d904fd
/include/DX10/System.Drawing.Texture.h
1f85ac530b391a9cad87b994f85cd62f4cf4b0b4
[]
no_license
playercd8/cppFramework
4fa9f1a4ae8bdbad7028ce7780741f37e4524e98
5b0524f2bd8d0e38b8d199a2244e792988883881
refs/heads/master
2021-01-10T19:39:17.987843
2015-06-17T13:07:21
2015-06-17T13:07:21
37,526,854
0
0
null
null
null
null
UTF-8
C++
false
false
3,260
h
System.Drawing.Texture.h
/* * System.Drawing.Texture.h * * Created on: Taiwan * Author: player */ #include "../stdafx.h" #if (_DRAWING_MODE == _DRAWING_MODE_DX10) #ifndef SYSTEM_DRAWING_TEXTURE_H_ #define SYSTEM_DRAWING_TEXTURE_H_ #if _MSC_VER > 1000 #pragma once #endif #include "DX10.h" #include "System.Drawing.Graphics.h" #include "../System.Buffer.h" #include "../System.ComPtr.h" namespace System { namespace Drawing { class Renderer; Renderer* GetDefaultRendererPtr(); typedef D3D10_TEXTURE1D_DESC Texture1D_Desc; typedef D3D10_TEXTURE2D_DESC Texture2D_Desc; typedef D3D10_TEXTURE3D_DESC Texture3D_Desc; //--------------------------------------------------------------------------------------------------------- // class Texture1D #pragma region class Texture1D class Texture1D : public ComPtr < ID3D10Texture1D > { protected: ComPtr<ID3D10ShaderResourceView> _ResourceView; float _width; float _invW; friend class Renderer; public: Texture1D(Texture1D_Desc& desc, Renderer* pRender = DefaultRendererPtr); Texture1D(ID3D10Texture1D* pTexture = NULL, Renderer* pRender = DefaultRendererPtr); operator ID3D10ShaderResourceView*() { return _ResourceView.GetPtr(); } static Texture1D* FromFile(LPCTSTR pFileName, Renderer* pRender = DefaultRendererPtr); static Texture1D* FromBuffer(Buffer& buf, Renderer* pRender = DefaultRendererPtr); }; #pragma endregion class Texture1D //--------------------------------------------------------------------------------------------------------- // class Texture2D #pragma region class Texture2D class Texture2D : public ComPtr < ID3D10Texture2D > { protected: ComPtr<ID3D10ShaderResourceView> _ResourceView; float _width; float _height; float _invW; float _invH; friend class Renderer; public: Texture2D(Texture2D_Desc& desc, Renderer* pRender = DefaultRendererPtr); Texture2D(ID3D10Texture2D* pTexture = NULL, Renderer* pRender = DefaultRendererPtr); operator ID3D10ShaderResourceView*() { return _ResourceView.GetPtr(); } static Texture2D* FromFile(LPCTSTR pFileName, Renderer* pRender = DefaultRendererPtr); static Texture2D* FromBuffer(Buffer& buf, Renderer* pRender = DefaultRendererPtr); }; #pragma endregion class Texture2D //--------------------------------------------------------------------------------------------------------- // class Texture3D #pragma region class Texture3D class Texture3D : public ComPtr < ID3D10Texture3D > { protected: ComPtr<ID3D10ShaderResourceView> _ResourceView; float _width; float _height; float _depth; float _invW; float _invH; float _invD; friend class Renderer; public: Texture3D(Texture3D_Desc& desc, Renderer* pRender = DefaultRendererPtr); Texture3D(ID3D10Texture3D* pTexture = NULL, Renderer* pRender = DefaultRendererPtr); operator ID3D10ShaderResourceView*() { return _ResourceView.GetPtr(); } static Texture3D* FromFile(LPCTSTR pFileName, Renderer* pRender = DefaultRendererPtr); static Texture3D* FromBuffer(Buffer& buf, Renderer* pRender = DefaultRendererPtr); }; #pragma region class Texture3D } /* namespace Drawing */ } /* namespace System */ #endif /* SYSTEM_DRAWING_TEXTURE_H_ */ #endif
97a8a47d17a822ff5af52ae1381823a7f64eec1e
52b28b80e514bccd0e9506a2a9b83adbb83320ad
/WPFLib/include/AVUIImageSource.h
714b21428ce0a325868ee6ab7560d82fcbca9f35
[]
no_license
RobinKa/wpfg
8bb3e9e433bc7d3deae888189cf7961d8fc27023
0986c0cb277d55d7ddb50401f167abf9740e90d9
refs/heads/master
2023-01-03T02:54:09.452491
2020-10-26T18:50:11
2020-10-26T18:50:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
72
h
AVUIImageSource.h
namespace AVUI { class ImageSource : public DependencyObject { }; };
cef377b032d99805d330fa27269ca69f9d2251e5
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_5729.cpp
ccfdb8b1bc4fd88def2f9c91bc8f7ff35eed4042
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,836
cpp
hunk_5729.cpp
tt->rn_b = -1 - off; *ttt = *tt; ttt->rn_key = rn_ones; - rnh->rnh_addaddr = rn_addroute; - rnh->rnh_deladdr = rn_delete; - rnh->rnh_matchaddr = rn_match; - rnh->rnh_lookup = rn_lookup; - rnh->rnh_walktree = rn_walktree; + rnh->rnh_addaddr = squid_rn_addroute; + rnh->rnh_deladdr = squid_rn_delete; + rnh->rnh_matchaddr = squid_rn_match; + rnh->rnh_lookup = squid_rn_lookup; + rnh->rnh_walktree = squid_rn_walktree; rnh->rnh_treetop = t; return (1); } void -rn_init(void) +squid_rn_init(void) { char *cp, *cplim; #ifdef KERNEL struct domain *dom; for (dom = domains; dom; dom = dom->dom_next) - if (dom->dom_maxrtkey > max_keylen) - max_keylen = dom->dom_maxrtkey; + if (dom->dom_maxrtkey > squid_max_keylen) + squid_max_keylen = dom->dom_maxrtkey; #endif - if (max_keylen == 0) { + if (squid_max_keylen == 0) { fprintf(stderr, - "rn_init: radix functions require max_keylen be set\n"); + "squid_rn_init: radix functions require squid_max_keylen be set\n"); return; } - R_Malloc(rn_zeros, char *, 3 * max_keylen); + squid_R_Malloc(rn_zeros, char *, 3 * squid_max_keylen); if (rn_zeros == NULL) { - fprintf(stderr, "rn_init failed.\n"); + fprintf(stderr, "squid_rn_init failed.\n"); exit(-1); } - memset(rn_zeros, '\0', 3 * max_keylen); - rn_ones = cp = rn_zeros + max_keylen; - addmask_key = cplim = rn_ones + max_keylen; + memset(rn_zeros, '\0', 3 * squid_max_keylen); + rn_ones = cp = rn_zeros + squid_max_keylen; + addmask_key = cplim = rn_ones + squid_max_keylen; while (cp < cplim) *cp++ = -1; - if (rn_inithead((void **) &mask_rnhead, 0) == 0) { + if (squid_rn_inithead((void **) &squid_mask_rnhead, 0) == 0) { fprintf(stderr, "rn_init2 failed.\n"); exit(-1); }
defe90c415dc05646d27f24e4423307698d2c304
8d52a45ccb7606a1565e92fddd70bee1aa39e41a
/extensions/common/xwalk_external_instance.cc
7b3b158afd5d70e8912564add859f6e17e66ada8
[ "BSD-3-Clause" ]
permissive
ks32/crosswalk
78e32e5336df6c8fed473fabe148a67d9024e31a
6a212832e0d55f88eb9390619b1d91c73c5551f5
refs/heads/ks_chromium_58
2023-07-08T20:31:05.252833
2019-07-11T10:28:34
2019-07-11T10:28:34
147,612,423
41
38
NOASSERTION
2020-08-12T20:51:57
2018-09-06T03:27:34
C++
UTF-8
C++
false
false
3,330
cc
xwalk_external_instance.cc
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/extensions/common/xwalk_external_instance.h" #include <string> #include "base/logging.h" #include "xwalk/extensions/common/xwalk_external_extension.h" #include "xwalk/extensions/common/xwalk_external_adapter.h" namespace xwalk { namespace extensions { XWalkExternalInstance::XWalkExternalInstance( XWalkExternalExtension* extension, XW_Instance xw_instance) : xw_instance_(xw_instance), extension_(extension), instance_data_(NULL), is_handling_sync_msg_(false) { XWalkExternalAdapter::GetInstance()->RegisterInstance(this); XW_CreatedInstanceCallback callback = extension_->created_instance_callback_; if (callback) callback(xw_instance_); } XWalkExternalInstance::~XWalkExternalInstance() { XW_DestroyedInstanceCallback callback = extension_->destroyed_instance_callback_; if (callback) callback(xw_instance_); XWalkExternalAdapter::GetInstance()->UnregisterInstance(this); } void XWalkExternalInstance::HandleMessage(std::unique_ptr<base::Value> msg) { XW_HandleMessageCallback callback = extension_->handle_msg_callback_; XW_HandleBinaryMessageCallback binary_callback = extension_->handle_binary_msg_callback_; if (!callback && !binary_callback) { LOG(WARNING) << "Ignoring message sent for external extension '" << extension_->name() << "' which doesn't support it."; return; } std::string string_msg; const base::BinaryValue* binary_msg = nullptr; if (callback && msg->GetAsString(&string_msg)) { callback(xw_instance_, string_msg.c_str()); } else if (binary_callback && msg->GetAsBinary(&binary_msg)) { binary_callback(xw_instance_, binary_msg->GetBuffer(), binary_msg->GetSize()); } else { LOG(WARNING) << "Failed to retrieve the message's value."; } return; } void XWalkExternalInstance::HandleSyncMessage(std::unique_ptr<base::Value> msg) { XW_HandleSyncMessageCallback callback = extension_->handle_sync_msg_callback_; if (!callback) { LOG(WARNING) << "Ignoring sync message sent for external extension '" << extension_->name() << "' which doesn't support it."; return; } std::string string_msg; if (!msg->GetAsString(&string_msg)) { LOG(WARNING) << "Failed to retrieve the sync message's value."; return; } callback(xw_instance_, string_msg.c_str()); } void XWalkExternalInstance::CoreSetInstanceData(void* data) { instance_data_ = data; } void* XWalkExternalInstance::CoreGetInstanceData() { return instance_data_; } void XWalkExternalInstance::MessagingPostMessage(const char* msg) { PostMessageToJS(std::unique_ptr<base::Value>(new base::StringValue(msg))); } void XWalkExternalInstance::MessagingPostBinaryMessage(const char* msg, const size_t size) { PostMessageToJS(std::unique_ptr<base::Value>( base::BinaryValue::CreateWithCopiedBuffer(msg, size))); } void XWalkExternalInstance::SyncMessagingSetSyncReply(const char* reply) { SendSyncReplyToJS(std::unique_ptr<base::Value>(new base::StringValue(reply))); } } // namespace extensions } // namespace xwalk
c369640fea3701de09f9ae2209b606e6405c5614
802ef2010da89d12e2ecde7cdee229fca50814d1
/Code/Engine/Renderer/DeviceManager/DeviceObjects.h
7794c1f6d5273bcc137c8ad024db1d2f0138345c
[ "MIT" ]
permissive
fromasmtodisasm/BlackBox
1fd20cbb7aa9ac8a575d17523592d05727a8db03
ef2fc9cb09100a4b0a5f59e69fd5c4edb5009d6e
refs/heads/master
2022-07-22T10:16:54.983156
2022-01-25T19:35:11
2022-01-25T19:35:11
173,405,446
4
3
MIT
2020-02-17T21:14:32
2019-03-02T05:02:09
C++
UTF-8
C++
false
false
7,514
h
DeviceObjects.h
#pragma once #include "DeviceResources.hpp" struct SInputLayoutCompositionDescriptor { const InputLayoutHandle VertexFormat; const uint8_t StreamMask; // EStreamMasks const uint8_t ShaderMask; const bool bInstanced; static uint8_t GenerateShaderMask(const InputLayoutHandle VertexFormat, D3DShaderReflection* pShaderReflection); SInputLayoutCompositionDescriptor(InputLayoutHandle VertexFormat, EStreamMasks Stream, D3DShaderReflection* pShaderReflection) noexcept : VertexFormat(VertexFormat) , StreamMask(static_cast<uint8_t>(Stream & VSM_MASK)) , ShaderMask(GenerateShaderMask(VertexFormat, pShaderReflection)) , bInstanced((Stream & VSM_INSTANCED) != 0) {} SInputLayoutCompositionDescriptor(SInputLayoutCompositionDescriptor&&) = default; SInputLayoutCompositionDescriptor(const SInputLayoutCompositionDescriptor&) = default; bool operator==(const SInputLayoutCompositionDescriptor &rhs) const noexcept { return static_cast<size_t>(*this) == static_cast<size_t>(rhs); } bool operator!=(const SInputLayoutCompositionDescriptor &rhs) const noexcept { return !(*this == rhs); } struct hasher { size_t operator()(const SInputLayoutCompositionDescriptor &d) const noexcept { const auto x = static_cast<size_t>(d); return std::hash<size_t>()(x); } }; private: explicit operator size_t() const { return static_cast<size_t>(StreamMask) | (static_cast<size_t>(ShaderMask) << 8) | (static_cast<size_t>(VertexFormat.value) << 16) | (static_cast<size_t>(bInstanced) << 24); } }; class CDeviceObjectFactory { static CDeviceObjectFactory m_singleton; CDeviceObjectFactory(); ~CDeviceObjectFactory(); public: void AssignDevice(D3DDevice* pDevice); static ILINE CDeviceObjectFactory& GetInstance() { return m_singleton; } // Low-level resource management API (TODO: remove D3D-dependency by abstraction) enum EResourceAllocationFlags : uint32 { // for Create*Texture() only BIND_DEPTH_STENCIL = BIT(0), // Bind flag BIND_RENDER_TARGET = BIT(1), // Bind flag BIND_UNORDERED_ACCESS = BIT(2), // Bind flag BIND_VERTEX_BUFFER = BIT(3), // Bind flag, DX11+Vk BIND_INDEX_BUFFER = BIT(4), // Bind flag, DX11+Vk BIND_CONSTANT_BUFFER = BIT(5), // Bind flag, DX11+Vk BIND_SHADER_RESOURCE = BIT(6), // Bind flag, any shader stage BIND_STREAM_OUTPUT = BIT(7), // Bits [8, 15] free USAGE_UAV_READWRITE = BIT(16), // Reading from UAVs is only possible through typeless formats under DX11 USAGE_UAV_OVERLAP = BIT(17), // Concurrent access to UAVs should be allowed USAGE_UAV_COUNTER = BIT(18), // Allocate a counter resource for the UAV as well (size = ?) USAGE_AUTOGENMIPS = BIT(19), // Generate mip-maps automatically whenever the contents of the resource change USAGE_STREAMING = BIT(20), // Use placed resources and allow changing LOD clamps for streamable textures USAGE_STAGE_ACCESS = BIT(21), // Use persistent buffer resources to stage uploads/downloads to the texture USAGE_STRUCTURED = BIT(22), // Resource contains structured data instead of fundamental datatypes USAGE_INDIRECTARGS = BIT(23), // Resource can be used for indirect draw/dispatch argument buffers USAGE_RAW = BIT(24), // Resource can be bound byte-addressable USAGE_LODABLE = BIT(25), // Resource consists of multiple LODs which can be selected at GPU run-time // for UMA or persistent MA only USAGE_DIRECT_ACCESS = BIT(26), USAGE_DIRECT_ACCESS_CPU_COHERENT = BIT(27), USAGE_DIRECT_ACCESS_GPU_COHERENT = BIT(28), // The CPU access flags determine the heap on which the resource will be placed. // For porting old heap flags, you should use the following table to select the heap. // Note for CDevTexture: When USAGE_STAGE_ACCESS is set, the heap is always DEFAULT, and additional dedicated staging resources are created alongside. // CPU_READ | CPU_WRITE -> D3D HEAP // no | no -> DEFAULT // no | yes -> DYNAMIC // yes | yes or no -> STAGING USAGE_CPU_READ = BIT(29), USAGE_CPU_WRITE = BIT(30), USAGE_HIFREQ_HEAP = BIT(31) // Resource is reallocated every frame or multiple times each frame, use a recycling heap with delayed deletes }; // Resource Usage | Default | Dynamic | Immutable | Staging // -----------------+-----------+-----------+-----------+-------- // GPU - Read | yes | yes1 | yes | yes1, 2 // GPU - Write | yes1 | | | yes1, 2 // CPU - Read | | | | yes1, 2 // CPU - Write | | yes | | yes1, 2 // // 1 - This is restricted to ID3D11DeviceContext::CopySubresourceRegion, ID3D11DeviceContext::CopyResource, // ID3D11DeviceContext::UpdateSubresource, and ID3D11DeviceContext::CopyStructureCount. // 2 - Cannot be a depth - stencil buffer or a multi-sampled render target. //============================================================================= static uint8* CDeviceObjectFactory::Map(D3DBuffer* buffer, uint32 subresource, buffer_size_t offset, buffer_size_t size, D3D11_MAP mode); static void CDeviceObjectFactory::Unmap(D3DBuffer* buffer, uint32 subresource, buffer_size_t offset, buffer_size_t size, D3D11_MAP mode); //////////////////////////////////////////////////////////////////////////// // InputLayout API static void AllocatePredefinedInputLayouts(); static void TrimInputLayouts(); static void ReleaseInputLayouts(); public: using SInputLayoutPair = std::pair<SInputLayout, CDeviceInputLayout*>; static const SInputLayout* GetInputLayoutDescriptor(const InputLayoutHandle VertexFormat); // Higher level input-layout composition / / / / / / / / / / / / / / / / / / static SInputLayout CreateInputLayoutForPermutation(const SShaderBlob* m_pConsumingVertexShader, const SInputLayoutCompositionDescriptor &compositionDescription, EStreamMasks StreamMask, const InputLayoutHandle VertexFormat); static const SInputLayoutPair* GetOrCreateInputLayout(const SShaderBlob* pVS, EStreamMasks StreamMask, const InputLayoutHandle VertexFormat); static const SInputLayoutPair* GetOrCreateInputLayout(const SShaderBlob* pVS, const InputLayoutHandle VertexFormat); static InputLayoutHandle CreateCustomVertexFormat(size_t numDescs, const D3D11_INPUT_ELEMENT_DESC* inputLayout); // Shader API ID3D11VertexShader* CreateVertexShader(const void* pData, size_t bytes); ID3D11PixelShader* CreatePixelShader(const void* pData, size_t bytes); ID3D11GeometryShader* CreateGeometryShader(const void* pData, size_t bytes); ID3D11HullShader* CreateHullShader(const void* pData, size_t bytes); ID3D11DomainShader* CreateDomainShader(const void* pData, size_t bytes); ID3D11ComputeShader* CreateComputeShader(const void* pData, size_t bytes); private: //////////////////////////////////////////////////////////////////////////// // InputLayout API // A heap containing all permutations of InputLayout, they are global and are never evicted static CDeviceInputLayout* CreateInputLayout(const SInputLayout& pState, const SShaderBlob* m_pConsumingVertexShader); static std::vector<SInputLayout> m_vertexFormatToInputLayoutCache; // Higher level input-layout composition / / / / / / / / / / / / / / / / / / static std::unordered_map<SInputLayoutCompositionDescriptor, SInputLayoutPair, SInputLayoutCompositionDescriptor::hasher> s_InputLayoutCompositions; }; static ILINE CDeviceObjectFactory& GetDeviceObjectFactory() { return CDeviceObjectFactory::GetInstance(); }