blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
efef95d36217c2c7fdce18ffdb0dbe16fe236079
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/boost/1.78.0/boost/fusion/container/generation/detail/preprocessed/make_vector10.hpp
c38c78f03c7ae851f5e58be172f6177accafada5
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode-public-domain", "JSON", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-4-Clause", "Python-2.0", "LGPL-2.1-or-later" ]
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
15,119
hpp
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This is an auto-generated file. Do not edit! ==============================================================================*/ namespace boost { namespace fusion { struct void_; namespace result_of { template < typename T0 = void_ , typename T1 = void_ , typename T2 = void_ , typename T3 = void_ , typename T4 = void_ , typename T5 = void_ , typename T6 = void_ , typename T7 = void_ , typename T8 = void_ , typename T9 = void_ , typename Extra = void_ > struct make_vector; template <> struct make_vector<> { typedef vector0<> type; }; } BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector0<> make_vector() { return vector0<>(); } namespace result_of { template <typename T0> struct make_vector< T0 , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ > { typedef vector1<typename detail::as_fusion_element<T0>::type> type; }; } template <typename T0> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector1<typename detail::as_fusion_element<T0>::type> make_vector(T0 const& arg0) { return vector1<typename detail::as_fusion_element<T0>::type>( arg0); } namespace result_of { template <typename T0 , typename T1> struct make_vector< T0 , T1 , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ > { typedef vector2<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type> type; }; } template <typename T0 , typename T1> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector2<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type> make_vector(T0 const& arg0 , T1 const& arg1) { return vector2<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type>( arg0 , arg1); } namespace result_of { template <typename T0 , typename T1 , typename T2> struct make_vector< T0 , T1 , T2 , void_ , void_ , void_ , void_ , void_ , void_ , void_ , void_ > { typedef vector3<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type> type; }; } template <typename T0 , typename T1 , typename T2> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector3<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2) { return vector3<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type>( arg0 , arg1 , arg2); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3> struct make_vector< T0 , T1 , T2 , T3 , void_ , void_ , void_ , void_ , void_ , void_ , void_ > { typedef vector4<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector4<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3) { return vector4<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type>( arg0 , arg1 , arg2 , arg3); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4> struct make_vector< T0 , T1 , T2 , T3 , T4 , void_ , void_ , void_ , void_ , void_ , void_ > { typedef vector5<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector5<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3 , T4 const& arg4) { return vector5<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type>( arg0 , arg1 , arg2 , arg3 , arg4); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5> struct make_vector< T0 , T1 , T2 , T3 , T4 , T5 , void_ , void_ , void_ , void_ , void_ > { typedef vector6<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector6<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3 , T4 const& arg4 , T5 const& arg5) { return vector6<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type>( arg0 , arg1 , arg2 , arg3 , arg4 , arg5); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6> struct make_vector< T0 , T1 , T2 , T3 , T4 , T5 , T6 , void_ , void_ , void_ , void_ > { typedef vector7<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector7<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3 , T4 const& arg4 , T5 const& arg5 , T6 const& arg6) { return vector7<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type>( arg0 , arg1 , arg2 , arg3 , arg4 , arg5 , arg6); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7> struct make_vector< T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , void_ , void_ , void_ > { typedef vector8<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector8<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3 , T4 const& arg4 , T5 const& arg5 , T6 const& arg6 , T7 const& arg7) { return vector8<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type>( arg0 , arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8> struct make_vector< T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , void_ , void_ > { typedef vector9<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type , typename detail::as_fusion_element<T8>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector9<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type , typename detail::as_fusion_element<T8>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3 , T4 const& arg4 , T5 const& arg5 , T6 const& arg6 , T7 const& arg7 , T8 const& arg8) { return vector9<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type , typename detail::as_fusion_element<T8>::type>( arg0 , arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8); } namespace result_of { template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9> struct make_vector< T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , void_ > { typedef vector10<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type , typename detail::as_fusion_element<T8>::type , typename detail::as_fusion_element<T9>::type> type; }; } template <typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline vector10<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type , typename detail::as_fusion_element<T8>::type , typename detail::as_fusion_element<T9>::type> make_vector(T0 const& arg0 , T1 const& arg1 , T2 const& arg2 , T3 const& arg3 , T4 const& arg4 , T5 const& arg5 , T6 const& arg6 , T7 const& arg7 , T8 const& arg8 , T9 const& arg9) { return vector10<typename detail::as_fusion_element<T0>::type , typename detail::as_fusion_element<T1>::type , typename detail::as_fusion_element<T2>::type , typename detail::as_fusion_element<T3>::type , typename detail::as_fusion_element<T4>::type , typename detail::as_fusion_element<T5>::type , typename detail::as_fusion_element<T6>::type , typename detail::as_fusion_element<T7>::type , typename detail::as_fusion_element<T8>::type , typename detail::as_fusion_element<T9>::type>( arg0 , arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 , arg9); } }}
74d34626328779d227b120a4e75e54a9f6c492c6
65fb98fc0dd146c6143d37a69a4e77560b031f37
/Self-Driving_Car_part_2/Lesson_09_Behavior_Planning/Lesson_9.16-cost2/main.cpp
8b82f8f782e9ac00922718653f2796e154cb571c
[]
no_license
jack239/udacity_CarND
7b1e0e68fd5901237a92f9b861c3b5faae4a3eb8
2dd9008b9f64d4f12bbe61bff5ecbfb33292104d
refs/heads/main
2023-07-11T04:54:56.909996
2021-08-23T13:47:18
2021-08-23T13:47:27
391,993,976
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
cpp
#include <iostream> #include <vector> #include "cost.h" using std::cout; using std::endl; int main() { // Target speed of our vehicle int target_speed = 10; // Lane speeds for each lane std::vector<int> lane_speeds = {6, 7, 8, 9}; // Test cases used for grading - do not change. double cost; cout << "Costs for (intended_lane, final_lane):" << endl; cout << "---------------------------------------------------------" << endl; cost = inefficiency_cost(target_speed, 3, 3, lane_speeds); cout << "The cost is " << cost << " for " << "(3, 3)" << endl; cost = inefficiency_cost(target_speed, 2, 3, lane_speeds); cout << "The cost is " << cost << " for " << "(2, 3)" << endl; cost = inefficiency_cost(target_speed, 2, 2, lane_speeds); cout << "The cost is " << cost << " for " << "(2, 2)" << endl; cost = inefficiency_cost(target_speed, 1, 2, lane_speeds); cout << "The cost is " << cost << " for " << "(1, 2)" << endl; cost = inefficiency_cost(target_speed, 1, 1, lane_speeds); cout << "The cost is " << cost << " for " << "(1, 1)" << endl; cost = inefficiency_cost(target_speed, 0, 1, lane_speeds); cout << "The cost is " << cost << " for " << "(0, 1)" << endl; cost = inefficiency_cost(target_speed, 0, 0, lane_speeds); cout << "The cost is " << cost << " for " << "(0, 0)" << endl; return 0; }
a08f36de6f661e9daa3d82ce654f2bfc406bee00
e9e00c79ea1841fab915751e9b0b9eae843a57e1
/Source/Core/Logger.h
d34a6affd450fc81446b4b6736cd00897b30ceb8
[]
no_license
blizmax/CppTrial
38a30c6117bbc9e88e9855bf3d0530d5daad969f
d5a0505f778df13b03ff5391dca8529a1a09c10a
refs/heads/master
2022-12-11T00:12:16.922501
2020-08-31T12:23:53
2020-08-31T12:23:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,107
h
#pragma once #include "Core/.Package.h" #include "Core/Delegate.h" #include "Core/String.h" #include "Core/Time.h" #include <iostream> enum class LogLevel { None = 0, Debug = 1, Info = 2, Warning = 3, Error = 4, Fatal = 5, }; class Logger { public: static constexpr LogLevel DEFAULT_LEVEL = LogLevel::Debug; Logger() = delete; Logger(const Logger &) = delete; Logger(Logger &&) = delete; Logger &operator=(const Logger &) = delete; Logger &operator=(Logger &&) = delete; ~Logger() = default; explicit Logger(const String &tag, LogLevel lv = DEFAULT_LEVEL) : tag(tag), level(lv) { printHandler.On([](LogLevel l, const String &s) { std::wcout << s.CStr() << std::endl; }); } void SetLevel(LogLevel lv) { level = lv; } LogLevel GetLevel() const { return level; } template <typename... Args> void Debug(const String &msg, Args &&... args) const { Log(LogLevel::Debug, msg, std::forward<Args>(args)...); } template <typename... Args> void Info(const String &msg, Args &&... args) const { Log(LogLevel::Info, msg, std::forward<Args>(args)...); } template <typename... Args> void Warning(const String &msg, Args &&... args) const { Log(LogLevel::Warning, msg, std::forward<Args>(args)...); } template <typename... Args> void Error(const String &msg, Args &&... args) const { Log(LogLevel::Error, msg, std::forward<Args>(args)...); } template <typename... Args> void Log(LogLevel lv, const String &msg, Args &&... args) const { if (((int32)level - (int32)lv) <= 0) { Print(lv, msg, std::forward<Args>(args)...); } } static Logger &GetGlobal() { return sGlobal; } private: template <typename... Args> void Print(const LogLevel &lv, const String &msg, Args &&... args) const { String prefix; switch (lv) { case LogLevel::Debug: prefix = CT_TEXT("D"); break; case LogLevel::Info: prefix = CT_TEXT("I"); break; case LogLevel::Warning: prefix = CT_TEXT("W"); break; case LogLevel::Error: prefix = CT_TEXT("E"); break; case LogLevel::Fatal: prefix = CT_TEXT("F"); break; default: //should not be here return; } String fmtMsg = String::Format(msg, std::forward<Args>(args)...); String fmtTime = Time::ToString(CT_TEXT("%Y-%m-%d %H:%M:%S")); printHandler(lv, String::Format(CT_TEXT("[{0}] <{1}>[{2}] {3}"), fmtTime, prefix, tag, fmtMsg)); } public: mutable Delegate<void(LogLevel, const String &)> printHandler; private: static Logger sGlobal; String tag; LogLevel level = DEFAULT_LEVEL; }; inline Logger Logger::sGlobal(CT_TEXT("Core")); #define CT_LOG(lv, ...) Logger::GetGlobal().Log(LogLevel::lv, __VA_ARGS__)
f7de59cfcae1545539f67b45a3fb9c349522b7d6
9c875266d568ce5ca2bc7df3147d7cd536af652e
/bbst/basic/lazy.cpp
8115d17ffed325dc4b78cf963d0c630d30da65df
[]
no_license
hoget157/library-1
0408d122af8733292faffb298ba97f419d88a66c
1301f03a3f5d300a0fdcbac44067070a40d683f5
refs/heads/master
2020-11-29T15:58:29.537377
2019-12-24T01:16:13
2019-12-24T01:16:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,992
cpp
#ifndef call_from_test #include<bits/stdc++.h> using namespace std; #define call_from_test #include "base.cpp" #undef call_from_test #endif //BEGIN CUT HERE template<typename Tp, typename Ep> struct NodeBase{ using T = Tp; using E = Ep; NodeBase *l,*r,*p; size_t cnt; bool rev; T val,dat; E laz; NodeBase():cnt(0),rev(0){l=r=p=nullptr;} NodeBase(T val,E laz): cnt(1),rev(0),val(val),dat(val),laz(laz){l=r=p=nullptr;} }; template<typename Node, size_t LIM> struct Lazy : BBSTBase<Node, LIM>{ using super = BBSTBase<Node, LIM>; using T = typename Node::T; using E = typename Node::E; using F = function<T(T, T)>; using G = function<T(T, E)>; using H = function<E(E, E)>; using S = function<T(T)>; F f; G g; H h; S flip; T ti; E ei; Lazy(F f,G g,H h,T ti,E ei): super(),f(f),g(g),h(h),ti(ti),ei(ei){ flip=[](T a){return a;}; } Lazy(F f,G g,H h,S flip,T ti,E ei): super(),f(f),g(g),h(h),flip(flip),ti(ti),ei(ei){} using super::create; using super::merge; using super::split; T query(const Node *a){ return a?a->dat:ti; } using super::count; Node* recalc(Node *a){ a->cnt=count(a->l)+1+count(a->r); a->dat=a->val; if(a->l) a->dat=f(a->l->dat,a->dat); if(a->r) a->dat=f(a->dat,a->r->dat); return a; } void propagate(Node *a,E v){ a->laz=h(a->laz,v); a->val=g(a->val,v); a->dat=g(a->dat,v); } using super::toggle; void toggle(Node *a){ swap(a->l,a->r); a->dat=flip(a->dat); a->rev^=1; } // remove "virtual" for optimization virtual Node* eval(Node* a){ if(a->laz!=ei){ if(a->l) propagate(a->l,a->laz); if(a->r) propagate(a->r,a->laz); a->laz=ei; } if(a->rev){ if(a->l) toggle(a->l); if(a->r) toggle(a->r); a->rev=false; } return recalc(a); } T query(Node *&a,size_t l,size_t r){ auto s=split(a,l); auto t=split(s.second,r-l); auto u=t.first; T res=query(u); a=merge(s.first,merge(u,t.second)); return res; } Node* update(Node *a,size_t l,size_t r,E x){ auto s=split(a,l); auto t=split(s.second,r-l); auto u=eval(t.first); propagate(u,x); return merge(s.first,merge(u,t.second)); } Node* set_val(Node *a,size_t k,T val){ assert(k<count(a)); a=eval(a); size_t num=count(a->l); if(k<num) a->l=set_val(a->l,k,val); if(k>num) a->r=set_val(a->r,k-(num+1),val); if(k==num) a->val=val; return recalc(a); } T get_val(Node *a,size_t k){ assert(k<count(a)); a=eval(a); size_t num=count(a->l); if(k<num) return get_val(a->l,k); if(k>num) return get_val(a->r,k-(num+1)); return a->val; } void dump(Node* a,typename vector<T>::iterator it){ if(!count(a)) return; a=eval(a); dump(a->l,it); *(it+count(a->l))=a->val; dump(a->r,it+count(a->l)+1); } vector<T> dump(Node* a){ vector<T> vs(count(a)); dump(a,vs.begin()); return vs; } }; //END CUT HERE #ifndef call_from_test //INSERT ABOVE HERE char buf[114514]; signed CODEFESTIVAL2014EXHIBITION_B(){ int Q; scanf("%d",&Q); scanf("%s\n",buf); string S(buf); using T = tuple<int, int, int>; using P = pair<int, int>; auto f=[](T a,T b){ return T(min(get<0>(a),get<0>(b)),min(get<1>(a),get<1>(b)),0); }; auto g=[](T a,P b){ return T(get<0>(a)+b.first,get<1>(a)+b.second,get<2>(a)); }; auto h=[](P a,P b){ return P(a.first+b.first,a.second+b.second); }; const int INF = 1e9; using Node = NodeBase<T, P>; constexpr size_t LIM = 1e6; Lazy<Node, LIM> G(f,g,h,T(INF,INF,0),P(0,0)); vector<T> v(S.size()+2,T(0,0,0)); for(int i=0;i<(int)S.size();i++) get<2>(v[i+1])=(S[i]=='('?1:-1); auto rt=G.build(v); for(int i=1;i<=(int)S.size();i++){ int z=get<2>(G.get_val(rt,i)); rt=G.update(rt,i,G.count(rt),P(z,0)); rt=G.update(rt,0,i+1,P(0,-z)); } for(int i=0;i<Q;i++){ char x; int y,z; scanf("%c %d %d\n",&x,&y,&z); z++; if(x=='('||x==')'){ z=(x=='('?1:-1); T prev=G.get_val(rt,y-1); T next=G.get_val(rt,y); T curr(get<0>(prev),get<1>(next),z); rt=G.insert(rt,y,Node(curr,P(0,0))); rt=G.update(rt,y,G.count(rt),P(z,0)); rt=G.update(rt,0,y+1,P(0,-z)); } if(x=='D'){ z=get<2>(G.get_val(rt,y)); rt=G.erase(rt,y); rt=G.update(rt,y,G.count(rt),P(-z,0)); rt=G.update(rt,0,y,P(0,z)); } if(x=='Q'){ T prev=G.get_val(rt,y-1); T curr=G.query(rt,y,z); T next=G.get_val(rt,z); int ans=0; if(get<0>(prev)>get<0>(curr)) ans+=get<0>(prev)-get<0>(curr); if(get<1>(next)>get<1>(curr)) ans+=get<1>(next)-get<1>(curr); printf("%d\n",ans); } } return 0; } /* verified on 2019/10/22 https://atcoder.jp/contests/code-festival-2014-exhibition-open/tasks/code_festival_exhibition_b */ signed main(){ CODEFESTIVAL2014EXHIBITION_B(); return 0; } #endif
ebcb05fe9678754a9cebcc7d1baecdb56b5437d2
6c4e391046022177244aeade63b03fc0824a4c50
/chrome/browser/password_manager/password_store_mac_unittest.cc
c01cbd9f65e15a2503a26154d2fe6514ab18594b
[ "BSD-3-Clause" ]
permissive
woshihoujinxin/chromium-2
d17cae43153d14673778bbdf0b739886d2461902
71aec55e801f801f89a81cfb219a219d953a5d5c
refs/heads/master
2022-11-15T00:18:39.821920
2017-07-14T19:59:33
2017-07-14T19:59:33
97,331,019
1
0
null
2017-07-15T17:16:35
2017-07-15T17:16:35
null
UTF-8
C++
false
false
11,549
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/password_manager/password_store_mac.h" #include <utility> #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/scoped_observer.h" #include "base/strings/utf_string_conversions.h" #include "base/test/histogram_tester.h" #include "chrome/browser/prefs/browser_prefs.h" #include "components/os_crypt/os_crypt_mocker.h" #include "components/password_manager/core/browser/login_database.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using autofill::PasswordForm; using content::BrowserThread; using password_manager::MigrationStatus; using password_manager::PasswordStore; using password_manager::PasswordStoreChange; using password_manager::PasswordStoreChangeList; using testing::_; using testing::ElementsAre; using testing::IsEmpty; using testing::Pointee; class MockPasswordStoreConsumer : public password_manager::PasswordStoreConsumer { public: MockPasswordStoreConsumer() = default; void WaitForResult() { base::RunLoop run_loop; nested_loop_ = &run_loop; run_loop.Run(); nested_loop_ = nullptr; } const std::vector<std::unique_ptr<PasswordForm>>& forms() const { return forms_; } private: void OnGetPasswordStoreResults( std::vector<std::unique_ptr<PasswordForm>> results) override { forms_.swap(results); if (nested_loop_) nested_loop_->Quit(); } std::vector<std::unique_ptr<PasswordForm>> forms_; base::RunLoop* nested_loop_ = nullptr; DISALLOW_COPY_AND_ASSIGN(MockPasswordStoreConsumer); }; class MockPasswordStoreObserver : public password_manager::PasswordStore::Observer { public: explicit MockPasswordStoreObserver(PasswordStoreMac* password_store) : guard_(this) { guard_.Add(password_store); } MOCK_METHOD1(OnLoginsChanged, void(const password_manager::PasswordStoreChangeList& changes)); private: ScopedObserver<PasswordStoreMac, MockPasswordStoreObserver> guard_; DISALLOW_COPY_AND_ASSIGN(MockPasswordStoreObserver); }; // A mock LoginDatabase that simulates a failing Init() method. class BadLoginDatabase : public password_manager::LoginDatabase { public: BadLoginDatabase() : password_manager::LoginDatabase(base::FilePath()) {} ~BadLoginDatabase() override {} // LoginDatabase: bool Init() override { return false; } private: DISALLOW_COPY_AND_ASSIGN(BadLoginDatabase); }; class PasswordStoreMacTest : public testing::TestWithParam<MigrationStatus> { public: PasswordStoreMacTest(); ~PasswordStoreMacTest() override; void CreateAndInitPasswordStore( std::unique_ptr<password_manager::LoginDatabase> login_db); void ClosePasswordStore(); // Do a store-level query to wait for all the previously enqueued operations // to finish. void FinishAsyncProcessing(); // Add/Update/Remove |form| and verify the operation succeeded. void AddForm(const PasswordForm& form); void UpdateForm(const PasswordForm& form); void RemoveForm(const PasswordForm& form); base::FilePath test_login_db_file_path() const; // Returns the expected migration status after the password store was inited. MigrationStatus GetTargetStatus() const; password_manager::LoginDatabase* login_db() const { return store_->login_metadata_db(); } PasswordStoreMac* store() { return store_.get(); } protected: content::TestBrowserThreadBundle ui_thread_; base::ScopedTempDir db_dir_; scoped_refptr<PasswordStoreMac> store_; sync_preferences::TestingPrefServiceSyncable testing_prefs_; }; PasswordStoreMacTest::PasswordStoreMacTest() { EXPECT_TRUE(db_dir_.CreateUniqueTempDir()); chrome::RegisterUserProfilePrefs(testing_prefs_.registry()); testing_prefs_.SetInteger(password_manager::prefs::kKeychainMigrationStatus, static_cast<int>(GetParam())); // Ensure that LoginDatabase will use the mock keychain if it needs to // encrypt/decrypt a password. OSCryptMocker::SetUpWithSingleton(); } PasswordStoreMacTest::~PasswordStoreMacTest() { ClosePasswordStore(); OSCryptMocker::TearDown(); } void PasswordStoreMacTest::CreateAndInitPasswordStore( std::unique_ptr<password_manager::LoginDatabase> login_db) { store_ = new PasswordStoreMac( BrowserThread::GetTaskRunnerForThread(BrowserThread::UI), std::move(login_db), &testing_prefs_); ASSERT_TRUE(store_->Init(syncer::SyncableService::StartSyncFlare(), nullptr)); } void PasswordStoreMacTest::ClosePasswordStore() { if (!store_) return; store_->ShutdownOnUIThread(); EXPECT_FALSE(store_->GetBackgroundTaskRunner()); store_ = nullptr; } void PasswordStoreMacTest::FinishAsyncProcessing() { // Do a store-level query to wait for all the previously enqueued operations // to finish. MockPasswordStoreConsumer consumer; store_->GetLogins({PasswordForm::SCHEME_HTML, std::string(), GURL()}, &consumer); consumer.WaitForResult(); } base::FilePath PasswordStoreMacTest::test_login_db_file_path() const { return db_dir_.GetPath().Append(FILE_PATH_LITERAL("login.db")); } MigrationStatus PasswordStoreMacTest::GetTargetStatus() const { if (GetParam() == MigrationStatus::NOT_STARTED || GetParam() == MigrationStatus::FAILED_ONCE || GetParam() == MigrationStatus::FAILED_TWICE) { return MigrationStatus::MIGRATION_STOPPED; } return GetParam(); } void PasswordStoreMacTest::AddForm(const PasswordForm& form) { MockPasswordStoreObserver mock_observer(store()); password_manager::PasswordStoreChangeList list; list.push_back(password_manager::PasswordStoreChange( password_manager::PasswordStoreChange::ADD, form)); EXPECT_CALL(mock_observer, OnLoginsChanged(list)); store()->AddLogin(form); FinishAsyncProcessing(); } void PasswordStoreMacTest::UpdateForm(const PasswordForm& form) { MockPasswordStoreObserver mock_observer(store()); password_manager::PasswordStoreChangeList list; list.push_back(password_manager::PasswordStoreChange( password_manager::PasswordStoreChange::UPDATE, form)); EXPECT_CALL(mock_observer, OnLoginsChanged(list)); store()->UpdateLogin(form); FinishAsyncProcessing(); } void PasswordStoreMacTest::RemoveForm(const PasswordForm& form) { MockPasswordStoreObserver mock_observer(store()); password_manager::PasswordStoreChangeList list; list.push_back(password_manager::PasswordStoreChange( password_manager::PasswordStoreChange::REMOVE, form)); EXPECT_CALL(mock_observer, OnLoginsChanged(list)); store()->RemoveLogin(form); FinishAsyncProcessing(); } // ----------- Tests ------------- TEST_P(PasswordStoreMacTest, Sanity) { base::HistogramTester histogram_tester; CreateAndInitPasswordStore(base::MakeUnique<password_manager::LoginDatabase>( test_login_db_file_path())); FinishAsyncProcessing(); ClosePasswordStore(); int status = testing_prefs_.GetInteger( password_manager::prefs::kKeychainMigrationStatus); EXPECT_EQ(static_cast<int>(GetTargetStatus()), status); histogram_tester.ExpectUniqueSample( "PasswordManager.KeychainMigration.Status", status, 1); } TEST_P(PasswordStoreMacTest, StartAndStop) { base::HistogramTester histogram_tester; // PasswordStore::ShutdownOnUIThread() immediately follows // PasswordStore::Init(). The message loop isn't running in between. Anyway, // PasswordStore should not collapse. CreateAndInitPasswordStore(base::MakeUnique<password_manager::LoginDatabase>( test_login_db_file_path())); ClosePasswordStore(); histogram_tester.ExpectUniqueSample( "PasswordManager.KeychainMigration.Status", static_cast<int>(GetTargetStatus()), 1); } TEST_P(PasswordStoreMacTest, OperationsOnABadDatabaseSilentlyFail) { // Verify that operations on a PasswordStore with a bad database cause no // explosions, but fail without side effect, return no data and trigger no // notifications. CreateAndInitPasswordStore(base::MakeUnique<BadLoginDatabase>()); FinishAsyncProcessing(); EXPECT_FALSE(login_db()); // The store should outlive the observer. scoped_refptr<PasswordStoreMac> store_refptr = store(); MockPasswordStoreObserver mock_observer(store()); EXPECT_CALL(mock_observer, OnLoginsChanged(_)).Times(0); // Add a new autofillable login + a blacklisted login. password_manager::PasswordFormData www_form_data = { PasswordForm::SCHEME_HTML, "http://www.facebook.com/", "http://www.facebook.com/index.html", "login", L"username", L"password", L"submit", L"not_joe_user", L"12345", true, 1}; std::unique_ptr<PasswordForm> form = CreatePasswordFormFromDataForTesting(www_form_data); std::unique_ptr<PasswordForm> blacklisted_form(new PasswordForm(*form)); blacklisted_form->signon_realm = "http://foo.example.com"; blacklisted_form->origin = GURL("http://foo.example.com/origin"); blacklisted_form->action = GURL("http://foo.example.com/action"); blacklisted_form->blacklisted_by_user = true; store()->AddLogin(*form); store()->AddLogin(*blacklisted_form); FinishAsyncProcessing(); // Get all logins; autofillable logins; blacklisted logins. MockPasswordStoreConsumer mock_consumer; store()->GetLogins(PasswordStore::FormDigest(*form), &mock_consumer); mock_consumer.WaitForResult(); EXPECT_THAT(mock_consumer.forms(), IsEmpty()); store()->GetAutofillableLogins(&mock_consumer); mock_consumer.WaitForResult(); EXPECT_THAT(mock_consumer.forms(), IsEmpty()); store()->GetBlacklistLogins(&mock_consumer); mock_consumer.WaitForResult(); EXPECT_THAT(mock_consumer.forms(), IsEmpty()); // Report metrics. store()->ReportMetrics("Test Username", true); FinishAsyncProcessing(); // Change the login. form->password_value = base::ASCIIToUTF16("a different password"); store()->UpdateLogin(*form); FinishAsyncProcessing(); // Delete one login; a range of logins. store()->RemoveLogin(*form); store()->RemoveLoginsCreatedBetween(base::Time(), base::Time::Max(), base::Closure()); store()->RemoveLoginsSyncedBetween(base::Time(), base::Time::Max()); FinishAsyncProcessing(); // Verify no notifications are fired during shutdown either. ClosePasswordStore(); } INSTANTIATE_TEST_CASE_P(, PasswordStoreMacTest, testing::Values(MigrationStatus::NOT_STARTED, MigrationStatus::MIGRATED, MigrationStatus::FAILED_ONCE, MigrationStatus::FAILED_TWICE, MigrationStatus::MIGRATED_DELETED, MigrationStatus::MIGRATED_PARTIALLY, MigrationStatus::MIGRATION_STOPPED)); } // namespace
71629eb454340fceca03ff485da6a4d848f7588a
c28205ee0d8a5fa4b4202ec08d1d1526ba083852
/PreparationK1/01_ArrayWorkout.cpp
a07a94c1e9e03b953eefe365541158b5856ccf44
[]
no_license
GerganaLp/introduction-to-programming-fmi
30f1ad70badca21da2c155f5f35031ced6fc91c9
0c1873dc51f3826c70ac85a9a154aaef47ffe52d
refs/heads/main
2023-02-21T11:51:51.954672
2021-01-22T07:38:50
2021-01-22T07:38:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,042
cpp
#include <iostream> using namespace std; void inputArray(int arr[], int size) { for (int i = 0; i < size; i++) cin >> arr[i]; } void removeElementAtIndex(int arr[], int size, int index) { if (index == size) return; for (int i = index + 1; i < size; i++) arr[i - 1] = arr[i]; } void insertElementAfterIndex(int arr[], int size, int element, int index) { for (int i = size; i > index; i--) arr[i] = arr[i - 1]; arr[index + 1] = element; } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << ' '; cout << endl; } bool isSaw(int arr[], int size) { bool isSaw = true; for (int i = size - 1; i > 0; i--) { if (!((arr[i + 1] >= arr[i] && arr[i] <= arr[i - 1]) || (arr[i + 1] <= arr[i] && arr[i] >= arr[i - 1]))) return false; } return true; } int main() { const int size = 6; int arr[size] = {1, 2, 0, 4, 3, 6}; // making a copy of an array int copy[size]; for (int i = 0; i < size; i++) copy[i] = arr[i]; cout << "This is a copy of our array: "; printArray(copy, size); cout << "Please enter the index of the element you would like to remove: "; int i; cin >> i; if (i < 0 || i > 5) { cout << "Invalid index. Romving last element..." << endl; i = 5; } cout << "The element to be removed is: " << arr[i] << endl; removeElementAtIndex(arr, size, i); cout << "The array after we have removed the element looks like this: "; printArray(arr, size - 1); cout << "Please enter a number you would like to insert into the array: "; int X; cin >> X; cout << "Please enter the index of the element after which you would like to insert your element: "; int j; cin >> j; if (j < 0 || j > 4) { cout << "Invalid index. Inserting element at the last position..." << endl; j = 4; } cout << "The array after we have inserted the element looks like this: "; insertElementAfterIndex(arr, size - 1, X, j); printArray(arr, size); if (isSaw(arr, size)) cout << "The array is \"saw\"" << endl; else cout << "The array is not \"saw\"" << endl; }
6a349ca47c5f846af1e8e89583def743b9cb11fc
030722883e7ae5dffcffe447e22adcc45b293399
/src/esp/bindings/MetadataMediatorBindings.cpp
9312b0daa4baf91266a71688b891e92ccdec79b4
[ "MIT" ]
permissive
super5-22/habitat-vis
f6236533c143cf013f73f77bcdbe315b3875c75f
dfddf38761ebe1185a6d84d82134db107c42036b
refs/heads/master
2023-07-09T06:56:22.625924
2021-08-06T02:22:01
2021-08-06T02:22:01
393,222,628
1
0
null
null
null
null
UTF-8
C++
false
false
3,763
cpp
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "esp/bindings/bindings.h" #include <Magnum/Magnum.h> #include <Magnum/PythonBindings.h> #include "esp/metadata/MetadataMediator.h" namespace py = pybind11; using py::literals::operator""_a; namespace esp { namespace metadata { void initMetadataMediatorBindings(py::module& m) { py::class_<MetadataMediator, MetadataMediator::ptr>(m, "MetadataMediator") .def(py::init(&MetadataMediator::create<>)) .def(py::init<const sim::SimulatorConfiguration&>()) .def_property( "active_dataset", &MetadataMediator::getActiveSceneDatasetName, &MetadataMediator::setActiveSceneDatasetName, R"(The currently active dataset being used. Will attempt to load configuration files specified if does not already exist.)") /* --- Methods --- */ .def( "dataset_exists", &MetadataMediator::sceneDatasetExists, R"(Returns whether the passed name references an existing scene dataset or not.)", "dataset_name"_a) .def( "remove_dataset", &MetadataMediator::removeSceneDataset, R"(Remove the given dataset from MetadataMediator. If specified dataset is currently active, this will fail.)", "dataset_name"_a) /* --- Template Manager accessors --- */ .def_property_readonly( "asset_template_manager", &MetadataMediator::getAssetAttributesManager, pybind11::return_value_policy::reference, R"(The current dataset's AssetAttributesManager instance for configuring primitive asset templates.)") .def_property_readonly( "lighting_template_manager", &MetadataMediator::getLightLayoutAttributesManager, pybind11::return_value_policy::reference, R"(The current dataset's LightLayoutAttributesManager instance for configuring light templates and layouts.)") .def_property_readonly( "object_template_manager", &MetadataMediator::getObjectAttributesManager, pybind11::return_value_policy::reference, R"(The current dataset's ObjectAttributesManager instance for configuring object templates.)") .def_property_readonly("physics_template_manager", &MetadataMediator::getPhysicsAttributesManager, pybind11::return_value_policy::reference, R"(The current PhysicsAttributesManager instance for configuring PhysicsManager templates.)") .def_property_readonly( "stage_template_manager", &MetadataMediator::getStageAttributesManager, pybind11::return_value_policy::reference, R"(The current dataset's StageAttributesManager instance for configuring simulation stage templates.)") .def( "get_scene_handles", &MetadataMediator::getAllSceneInstanceHandles, R"(Returns a list the names of all the available scene instances in the currently active dataset.)") .def_property_readonly( "summary", &MetadataMediator::getDatasetsOverview, R"(This provides a summary of the datasets currently loaded.)") .def( "dataset_report", &MetadataMediator::createDatasetReport, R"(This provides an indepth report of the loaded templates for the specified dataset. If no dataset_name is specified, returns a report on the currently active dataset)", "dataset_name"_a = ""); } // initMetadataMediatorBindings } // namespace metadata } // namespace esp
a53c5b2acfab7baa1e04a47fd8d9dceff1d9d3cb
9a3b99b1eeb4f10400a799b51d789d0fde156be9
/crowcoin/src/qt/recentrequeststablemodel.cpp
9f446a2e49b41335e0b4a4cc4ace149cc04258e2
[ "MIT" ]
permissive
aijs/blockchain
077e7e8bf515cac5afde04498e560f300041ceff
89ee5dc0b243847688d7063820dc1ec58394c896
refs/heads/master
2020-03-28T02:55:05.362321
2018-08-20T09:58:32
2018-08-20T09:58:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,361
cpp
// Copyright (c) 2011-2015 The Crowcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "recentrequeststablemodel.h" #include "crowcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "clientversion.h" #include "streams.h" #include <boost/foreach.hpp> RecentRequestsTableModel::RecentRequestsTableModel(CWallet *wallet, WalletModel *parent) : walletModel(parent) { Q_UNUSED(wallet); nReceiveRequestsMaxId = 0; // Load entries from wallet std::vector<std::string> vReceiveRequests; parent->loadReceiveRequests(vReceiveRequests); BOOST_FOREACH(const std::string& request, vReceiveRequests) addNewRequest(request); /* These columns must match the indices in the ColumnIndex enumeration */ columns << tr("Date") << tr("Label") << tr("Message") << getAmountTitle(); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } RecentRequestsTableModel::~RecentRequestsTableModel() { /* Intentionally left empty */ } int RecentRequestsTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return list.length(); } int RecentRequestsTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant RecentRequestsTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid() || index.row() >= list.length()) return QVariant(); const RecentRequestEntry *rec = &list[index.row()]; if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Date: return GUIUtil::dateTimeStr(rec->date); case Label: if(rec->recipient.label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->recipient.label; } case Message: if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole) { return tr("(no message)"); } else { return rec->recipient.message; } case Amount: if (rec->recipient.amount == 0 && role == Qt::DisplayRole) return tr("(no amount)"); else if (role == Qt::EditRole) return CrowcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount, false, CrowcoinUnits::separatorNever); else return CrowcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount); } } else if (role == Qt::TextAlignmentRole) { if (index.column() == Amount) return (int)(Qt::AlignRight|Qt::AlignVCenter); } return QVariant(); } bool RecentRequestsTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { return true; } QVariant RecentRequestsTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void RecentRequestsTableModel::updateAmountColumnTitle() { columns[Amount] = getAmountTitle(); Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } /** Gets title for amount column including current display unit if optionsModel reference available. */ QString RecentRequestsTableModel::getAmountTitle() { QString amountTitle = tr("Amount"); if (this->walletModel->getOptionsModel() != NULL) { amountTitle += " ("+CrowcoinUnits::name(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")"; } return amountTitle; } QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); return createIndex(row, column); } bool RecentRequestsTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); if(count > 0 && row >= 0 && (row+count) <= list.size()) { const RecentRequestEntry *rec; for (int i = 0; i < count; ++i) { rec = &list[row+i]; if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, "")) return false; } beginRemoveRows(parent, row, row + count - 1); list.erase(list.begin() + row, list.begin() + row + count); endRemoveRows(); return true; } else { return false; } } Qt::ItemFlags RecentRequestsTableModel::flags(const QModelIndex &index) const { return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } // called when adding a request from the GUI void RecentRequestsTableModel::addNewRequest(const SendCoinsRecipient &recipient) { RecentRequestEntry newEntry; newEntry.id = ++nReceiveRequestsMaxId; newEntry.date = QDateTime::currentDateTime(); newEntry.recipient = recipient; CDataStream ss(SER_DISK, CLIENT_VERSION); ss << newEntry; if (!walletModel->saveReceiveRequest(recipient.address.toStdString(), newEntry.id, ss.str())) return; addNewRequest(newEntry); } // called from ctor when loading from wallet void RecentRequestsTableModel::addNewRequest(const std::string &recipient) { std::vector<char> data(recipient.begin(), recipient.end()); CDataStream ss(data, SER_DISK, CLIENT_VERSION); RecentRequestEntry entry; ss >> entry; if (entry.id == 0) // should not happen return; if (entry.id > nReceiveRequestsMaxId) nReceiveRequestsMaxId = entry.id; addNewRequest(entry); } // actually add to table in GUI void RecentRequestsTableModel::addNewRequest(RecentRequestEntry &recipient) { beginInsertRows(QModelIndex(), 0, 0); list.prepend(recipient); endInsertRows(); } void RecentRequestsTableModel::sort(int column, Qt::SortOrder order) { qSort(list.begin(), list.end(), RecentRequestEntryLessThan(column, order)); Q_EMIT dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex())); } void RecentRequestsTableModel::updateDisplayUnit() { updateAmountColumnTitle(); } bool RecentRequestEntryLessThan::operator()(RecentRequestEntry &left, RecentRequestEntry &right) const { RecentRequestEntry *pLeft = &left; RecentRequestEntry *pRight = &right; if (order == Qt::DescendingOrder) std::swap(pLeft, pRight); switch(column) { case RecentRequestsTableModel::Date: return pLeft->date.toTime_t() < pRight->date.toTime_t(); case RecentRequestsTableModel::Label: return pLeft->recipient.label < pRight->recipient.label; case RecentRequestsTableModel::Message: return pLeft->recipient.message < pRight->recipient.message; case RecentRequestsTableModel::Amount: return pLeft->recipient.amount < pRight->recipient.amount; default: return pLeft->id < pRight->id; } }
68c2a1f13f3497a270720deeda46411a5fc089cf
78f9095ab29cb5480b6ae191c73e4305f4b95098
/Entity.h
48e65fe36fec24a70328487e85937a06102d489c
[]
no_license
JamGrif/SDL-Project
d39ca17b9882267afaec0292c15c70c988d398ad
28fb4c810930c0a38dd12c639ea4b87b5fcf8505
refs/heads/master
2022-03-27T20:06:16.446355
2019-12-09T21:12:10
2019-12-09T21:12:10
213,755,511
0
0
null
null
null
null
UTF-8
C++
false
false
1,225
h
#pragma once #include <string> #include "SDL.h" #include "SDL_render.h" #include <iostream> #include <vector> #include "Level.h" class Entity { public: Entity(SDL_Renderer* renderer, int xpos, int ypos, Level* pLevel, bool useTransparency = true); ~Entity(); void UpdateBitmap(std::string filename, bool useTransparency); //Changes the loaded texture to something else virtual void draw(); //Draws the bitmap on screen void GetCollisionPosition(); //Gets the world position of all 4 corners of the object int GetX(); //Returns X position int GetY(); //Returns Y position virtual void Update() = 0; protected: SDL_Surface* m_pbitmapSurface; SDL_Texture* m_pbitmapTexture; SDL_Renderer* m_pRenderer; struct Vector { int x; int y; }; Vector Position = { 0,0 }; Vector Velocity{ 0, 0 }; //float m_X = 0; //float m_Y = 0; int m_PrevX = 0; int m_PrevY = 0; int m_DrawX = 0; std::string Filename = ""; std::string CurrentPicture = ""; Level* levelinfo; int TopLeftPosX = 0; int TopLeftPosY = 0; int TopRightPosX = 0; int TopRightPosY = 0; int BotLeftPosX = 0; int BotLeftPosY = 0; int BotRightPosX = 0; int BotRightPosY = 0; //Size of Entity int m_Width = 0; int m_Height = 0; };
be6de7b0d860020eb69a4cb9d2857bc0d0d0bc83
bdbe8119eb532aedaab3658089c9b6bf1a546a34
/icecommunicatorfactory.cpp
c793bf3ce2d70af0ba0f5fb751f29a4b229ed606
[]
no_license
lixudong1991/qt-GGrobot
7af30befffb2318e880aa9e1756afcb6e6ded8d0
8aaf3bde2406c4365279a83a07b75585f176c58e
refs/heads/master
2021-09-11T01:49:14.589880
2018-04-06T01:44:58
2018-04-06T01:44:58
115,530,153
0
0
null
2018-03-23T09:01:29
2017-12-27T14:42:55
C
WINDOWS-1252
C++
false
false
758
cpp
#include "icecommunicatorfactory.h" #include "log4z.h" IceCommunicatorFactory::IceCommunicatorFactory() { try { ic= Ice::initialize(); adapte = ic->createObjectAdapterWithEndpoints ("CmdStatusAdapter", "default -p 10000"); } catch(const Ice::Exception &e) { LOGE("ice ³õʼ»¯Ê§°Ü : "<<e.what()); } } IceCommunicatorFactory::~IceCommunicatorFactory() { } IceCommunicatorFactory* IceCommunicatorFactory::instance=new IceCommunicatorFactory(); IceCommunicatorFactory* IceCommunicatorFactory::getInstance() { return instance; } Ice::CommunicatorPtr IceCommunicatorFactory::communicator() { return ic; } Ice::ObjectAdapterPtr IceCommunicatorFactory::adapter() { return adapte; }
27ce5b8dc33a59640de291dacb9e1e0ece4e65a7
fc2f3a5404c1c3dfb5cd6b92196aa452d614e69d
/src/game_client.cpp
4c7b61cfab689bdf2a0079df9800c939b0772f95
[]
no_license
kevinchen2015/my_test_ls
719f13395dc9e3ec571d1af5642a4893cb70b70d
f41988a2c3fff4552ddb7aabc8abf9d238f41e25
refs/heads/master
2021-01-06T20:39:38.508236
2017-08-07T05:08:51
2017-08-07T05:08:51
99,538,660
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,527
cpp
#include "game_client.h" #include "frame_world_slave.h" #include "frame_cmd.h" #include "game_cmd.h" #include "game_msg_helper.h" #include "game_input.h" #include "game_predict.h" #include "game_world_client.h" #include "game_system.h" #include "move_system.h" #include "actor_helper.h" #include <iostream> #include <assert.h> void GameClient::c_on_recv_data(char* buff, unsigned int size, void* conn, int channel, void* user_data) { GameClient* client = static_cast<GameClient*>(user_data); if (client->status_ == GAME_WAIT_READY && channel == TCP) { if (size == 4) { int conv = 0; memcpy(&conv, buff, 4); client->game_world_->game_predict_->ResetUID(conv); client->frame_world_->Start(); sl_client_switch_kcp(client->net_client_, conv); return; } } if (client->status_ != GAME_RUNNING)return; //todo parse net msg ParseMsg(buff,size, nullptr,client->cmd_queue_in_); } void GameClient::c_on_connected(void* conn, int status, int channel, void* user_data) { GameClient* client = static_cast<GameClient*>(user_data); if (channel == TCP && status == 0) { int conv = 1; //just for test! sl_client_send_data(client->net_client_, (char*)&conv, 4); } if (client->status_ == GAME_WAIT_READY && channel == KCP && status == 0) { client->status_ = GAME_RUNNING; } } void GameClient::c_on_close(void* conn, int channel, void* user_data) { GameClient* client = static_cast<GameClient*>(user_data); } //---------------------------------------------------------------------- GameClient::GameClient() { frame_end_ = false; cmd_queue_in_ = new FrameCmdQueue(); cmd_queue_out_ = new FrameCmdQueue(); frame_world_ = new FrameWorldSlave(GAME_CMD_NUM,cmd_queue_in_); game_world_ = new GameWorldClient(GAME_CMD_NUM); game_world_->SetRealFrameTime(frame_world_->GetFrameTime()); game_world_->game_predict_->predict_sync_out_ = cmd_queue_out_; frame_world_->on_pre_frame = std::bind(&GameClient::OnPreFrame, this); frame_world_->on_post_frame = std::bind(&GameClient::OnPostFrame, this); frame_world_->RegistHandle(FRAME_START_CMD, std::bind(&GameClient::FrameStartHandle, this, std::placeholders::_1)); frame_world_->RegistHandle(FRAME_END_CMD, std::bind(&GameClient::FrameEndHandle, this, std::placeholders::_1)); frame_world_->RegistHandle(GAME_MOVE_CMD, std::bind(&GameClient::InputCmdHandle, this, std::placeholders::_1)); frame_world_->RegistHandle(GAME_CREATE_ENTITY_CMD, std::bind(&GameClient::CreateEntityHandle, this, std::placeholders::_1)); sl_client_create(&net_client_, this); sl_client_cb(net_client_, c_on_connected, c_on_recv_data, c_on_close); status_ = GAME_INIT; GameSystem* system = game_world_->GetSystem(); system->AddSystem(new MoveSystem()); game_world_->RegistHandler(GAME_MOVE_CMD, std::bind(handle_move_cmd, std::placeholders::_1, std::placeholders::_2)); game_world_->GetPredictSystem()->AddSystem(new MovePredictSystem()); } GameClient::~GameClient() { delete game_world_; delete frame_world_; delete cmd_queue_in_; delete cmd_queue_out_; sl_client_shutdown(net_client_); sl_client_release(net_client_); } void GameClient::Start() { status_ = GAME_WAIT_READY; sl_client_init(net_client_, "127.0.0.1", 6000, 6668); sl_client_connect(net_client_); } void GameClient::OnFixedUpdate(unsigned int time, int delta) { sl_client_update(net_client_); frame_world_->OnFixedUpdate(time, delta); game_world_->OnLocalFixedUpdate(time, delta); if (cmd_queue_out_->GetSize() > 0) { //·¢ËÍÔ¤²âÊäÈë char* buf = nullptr; unsigned int size = 0; PackMsg(cmd_queue_out_,buf,size); cmd_queue_out_->Clear(); if(size > 0) sl_client_send_data(net_client_, buf, size); } } void GameClient::OnUpdate(unsigned int time, int delta) { game_world_->OnLocalUpdate(time, delta); } void GameClient::OnPreFrame() { frame_end_ = false; //cmd_queue_out_->Clear(); } void GameClient::OnPostFrame() { game_world_->OnFixedUpdate(frame_world_->GetFrameTime()); frame_end_ = true; } void GameClient::FrameStartHandle(FrameCmd* cmd) { //if(cmd->frame_id % 15 == 1) // std::cout <<"frame start cmd,id:"<<cmd->frame_id << " time:"<< cmd->time << std::endl; } void GameClient::FrameEndHandle(FrameCmd* cmd) { if (cmd->frame_id % 15 == 1) { // std::cout << "frame end cmd,id:" << cmd->frame_id << " time:" << cmd->time << std::endl; // std::cout << "predict end cmd,id:" << game_world_->game_predict_->GetFrameTime()->GetFrameID() << " time:" << game_world_->game_predict_->GetFrameTime()->GetTime() << std::endl; FrameID real_frame_id = frame_world_->GetFrameTime()->GetFrameID(); FrameID predict_frame_id = game_world_->game_predict_->GetFrameTime()->GetFrameID(); int frame_dis = predict_frame_id - real_frame_id; std::cout <<"frame dis :"<< frame_dis << " predict frame id:" << predict_frame_id << " real frame id :" << real_frame_id << std::endl; } } void GameClient::InputCmdHandle(FrameCmd* cmd) { //std::cout << "move cmd,frame_id:"<< cmd->frame_id << std::endl; game_world_->OnRecvNetCmd(cmd); } void GameClient::CreateEntityHandle(FrameCmd* cmd) { CreateEntityCmd* create_cmd = (CreateEntityCmd*)cmd->cmd; if (create_cmd->type == ENTITY_ACTOR) { bool predict = create_cmd->uid == game_world_->GetPredictUID(); ecs::Entity* entity = ActorHelper::CreateClientActor(create_cmd->entity_id, predict); entity->user_data_ = game_world_->GetInput(create_cmd->uid); entity->user_data2_ = game_world_->game_predict_->GetPredictInput(); game_world_->AddEntity(entity); } }
26ac6b71132cc710b465d8c4209873f0c7b4fcda
04251e142abab46720229970dab4f7060456d361
/lib/rosetta/source/src/core/pack/annealer/FixbbLinkingRotamerSimAnnealer.cc
465d9df00175f958753c6cc815829dd9d6e8fc85
[]
no_license
sailfish009/binding_affinity_calculator
216257449a627d196709f9743ca58d8764043f12
7af9ce221519e373aa823dadc2005de7a377670d
refs/heads/master
2022-12-29T11:15:45.164881
2020-10-22T09:35:32
2020-10-22T09:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,699
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: [email protected]. /// @file core/pack/annealer/FixbbLinkingRotamerSimAnnealer.cc /// @brief Packer's standard simulated annealing class implementation /// @author Andrew Leaver-Fay ([email protected]) // Unit Headers #include <core/pack/annealer/FixbbLinkingRotamerSimAnnealer.hh> // Package Headers #include <core/pack/rotamer_set/RotamerSets.hh> #include <core/pack/rotamer_set/RotamerSet.hh> #include <core/pack/rotamer_set/RotamerLinks.hh> #include <core/pack/interaction_graph/AnnealableGraphBase.hh> #include <core/conformation/Residue.hh> #include <core/conformation/ResidueMatcher.hh> #include <basic/Tracer.hh> #include <utility> #include <utility/exit.hh> #include <numeric/random/random.hh> #include <iostream> #include <basic/options/option.hh> #include <basic/options/keys/packing.OptionKeys.gen.hh> using namespace ObjexxFCL; namespace core { namespace pack { namespace annealer { static basic::Tracer TR( "core.pack.annealer.FixbbLinkingRotamerSimAnnealer", basic::t_info ); //////////////////////////////////////////////////////////////////////////////// /// /// @brief /// constructor /// /// @details /// /// @global_read /// /// @global_write /// /// @remarks /// /// @references /// /// @author //////////////////////////////////////////////////////////////////////////////// FixbbLinkingRotamerSimAnnealer::FixbbLinkingRotamerSimAnnealer( utility::vector0<int> & rot_to_pack, FArray1D_int & bestrotamer_at_seqpos, core::PackerEnergy & bestenergy, bool start_with_current, // start simulation with current rotamers interaction_graph::AnnealableGraphBaseOP ig, FixbbRotamerSetsCOP rotamer_sets, FArray1_int & current_rot_index, bool calc_rot_freq, FArray1D< core::PackerEnergy > & rot_freq, RotamerLinksCOP rotamer_links ): RotamerAssigningAnnealer( rot_to_pack, (int) rot_to_pack.size(), bestrotamer_at_seqpos, bestenergy, start_with_current, // start simulation with current rotamers rotamer_sets, current_rot_index, calc_rot_freq, rot_freq ), ig_(std::move(ig)) { setup_rotamer_links( rotamer_links ); } FixbbLinkingRotamerSimAnnealer::FixbbLinkingRotamerSimAnnealer( FArray1D_int & bestrotamer_at_seqpos, core::PackerEnergy & bestenergy, bool start_with_current, // start simulation with current rotamers interaction_graph::AnnealableGraphBaseOP ig, FixbbRotamerSetsCOP rotamer_set, FArray1_int & current_rot_index, bool calc_rot_freq, FArray1D< core::PackerEnergy > & rot_freq, RotamerLinksCOP rotamer_links ): RotamerAssigningAnnealer( (ig->get_num_total_states()), bestrotamer_at_seqpos, bestenergy, start_with_current, // start simulation with current rotamers rotamer_set, current_rot_index, calc_rot_freq, rot_freq ), ig_(ig) { setup_rotamer_links( rotamer_links ); } // rotamer links provide a map for each position and all the positions linking // together, including itself. void FixbbLinkingRotamerSimAnnealer::setup_rotamer_links( RotamerLinksCOP rotamer_links ) { // setup the rotamer links // for each moltenres rotamer_links_ = utility::pointer::make_shared< rotamer_set::RotamerLinks >(); rotamer_links_->resize( rotamer_sets()->nmoltenres() ); TR.Debug << "nmoltenres " << rotamer_sets()->nmoltenres()<< std::endl; for ( Size moltenres_id=1; moltenres_id<= rotamer_sets()->nmoltenres(); ++moltenres_id ) { uint const resid( rotamer_sets()->moltenres_2_resid( moltenres_id ) ); //init anything linking to it locally //iterate over the associated set to check the positions, if molten if ( ! rotamer_links->has(resid) ) { TR.Debug << "singular unlinked position" << std::endl; } else { utility::vector1<int> copies = rotamer_links->get_equiv(resid); TR.Debug << "copies" << copies.size() << std::endl; for ( Size i = 1; i <= copies.size(); ++i ) { if ( rotamer_sets()->resid_2_moltenres( copies[i] ) ) { TR.Debug << "setting equivalent" << moltenres_id << "==" << rotamer_sets()->resid_2_moltenres(copies[i]) << std::endl; rotamer_links_->set_equiv(moltenres_id, rotamer_sets()->resid_2_moltenres(copies[i])); } else { TR.Debug << "a position in the link isn't to be changed" << std::endl; } } } } } /// @brief virtual destructor FixbbLinkingRotamerSimAnnealer::~FixbbLinkingRotamerSimAnnealer() = default; void FixbbLinkingRotamerSimAnnealer::run() { using namespace core::conformation; core::Size const nmoltenres = ig_->get_num_nodes(); FArray1D_int state_on_node( nmoltenres, 0 ); // parallel representation of interaction graph's state FArray1D_int best_state_on_node( nmoltenres, 0 ); FArray1D< core::PackerEnergy > loopenergy(maxouteriterations,0.0); //bk variables for calculating rotamer frequencies during simulation core::Size nsteps = 0; FArray1D_int nsteps_for_rot( ig_->get_num_total_states(), 0 ); //-------------------------------------------------------------------- //initialize variables core::PackerEnergy currentenergy = 0.0; ig_->prepare_graph_for_simulated_annealing(); ig_->blanket_assign_state_0(); //-------------------------------------------------------------------- if ( num_rots_to_pack() == 0 ) return; /*// Detect the quasisymmetrical case by checking to see that there are // residues with only 1 link to themselves as well as residues with multiple // links. // // Repeat proteins are also qua bool flag1 = false; bool flag2 = false; for ( core::Size i = 1; i <= nmoltenres; ++i ) { utility::vector1<Size> these_links = rotamer_links_->get_equiv(i); if ( flag1 && flag2 ) break; if ( these_links.size() == 1 && these_links[1] == i ) { flag1 = true; TR.Debug << "quasisymmetric annealer flag 1: ON" << std::endl; } if ( these_links.size() > 1 ) { flag2 = true; TR.Debug << "quasisymmetric annealer flag 2: ON" << std::endl; } }*/ bool quasiflag = false; //this quasisymmetry flag turns on a lot of bypasses below if ( basic::options::option[ basic::options::OptionKeys::packing::quasisymmetry]() == true ) { quasiflag = true; TR << "NOTICE: QUASISYMMETRIC PACKING IS TURNED ON in FixbbLinkingRotamerSimAnnealer. (quasiflag = " << quasiflag << ")" << std::endl; } core::Size totalrot = 0; // totalrot needs to be calculated differently for the quasisymmetrical case if ( quasiflag ) { for ( core::Size res=1; res<=nmoltenres; ++res ) { totalrot += rotamer_sets()->nrotamers_for_moltenres( res ); } TR << "QUASIBYPASS: quasisymmetric totalrot = " << totalrot << std::endl; } else { //experimental utility::vector1<Size> segmentTest = rotamer_links_->get_equiv(nmoltenres); for ( Size ii=1; ii<=segmentTest.size(); ++ii ) { // get the first element of the last repeat. it should be segment length why? :: Bad logic. //std::cout<< "SEGMENTLENGTH from ROTAMER LINK" << segmentTest[1] << std::endl; //Size repeat_number = segmentTest.back()/segmentTest[1]; //std::cout<< "number of repeats" << repeat_number << std::endl; for ( core::Size res = segmentTest[1]; res <= segmentTest[1]*2 ; res++ ) { totalrot += rotamer_sets()->nrotamers_for_moltenres(res); } } //std::cout << "TOTAL ROTAMER " << totalrot << std::endl; } // end calculate totalrot //setup_iterations(); //setup_iterations(num_rots_to_pack()/repeat_number); setup_iterations(totalrot*2); FArray1D< core::PackerEnergy > previous_nsteps_for_rot( rotamer_sets()->nrotamers(), 0.0); int outeriterations = get_outeriterations(); // some rotamer may not exist on other repeats, and use a new vector to // iterate the "good" rotamers int allrot = rotamer_sets()->nrotamers(); utility::vector1<bool> rot_valid(allrot, true); //outer loop for ( int nn = 1; nn <= outeriterations; ++nn ) { setup_temperature(loopenergy,nn); if ( quench() ) { currentenergy = bestenergy(); state_on_node = best_state_on_node; ig_->set_network_state( state_on_node ); } //rh std::cout << "Sim Annealer Temperature: " << get_temperature() << std::endl; int inneriterations = get_inneriterations(); //std::cout << "inner iteration: " << inneriterations << std::endl; core::PackerEnergy treshold_for_deltaE_inaccuracy = std::sqrt( get_temperature() ); ig_->set_errorfull_deltaE_threshold( treshold_for_deltaE_inaccuracy ); //inner loop for ( int n = 1; n <= inneriterations; ++n ) { int ranrotamer = -1; bool invalid_rotamer = false; while ( !invalid_rotamer ) { ranrotamer = static_cast<int>( numeric::random::rg().random_range(1, allrot )); if ( rot_valid[ ranrotamer ] ) { invalid_rotamer = true; } } //int const ranrotamer = pick_a_rotamer( n ); if ( ranrotamer == -1 ) continue; int const moltenres_id = rotamer_sets()->moltenres_for_rotamer( ranrotamer ); int const rotamer_state_on_moltenres = rotamer_sets()->rotid_on_moltenresidue( ranrotamer ); int const prevrotamer_state = state_on_node(moltenres_id); if ( rotamer_state_on_moltenres == prevrotamer_state ) continue; //skip iteration core::PackerEnergy previous_energy_for_node, delta_energy; ig_->consider_substitution( moltenres_id, rotamer_state_on_moltenres, delta_energy, previous_energy_for_node); // specialize to the case of coupled pairs in this first pass implementation // assume all couplings are between moltenres -- couplings between fixed and moltenres could // have been used to trim the residueset utility::vector1<int> linked_residues = rotamer_links_->get_equiv(moltenres_id); RotamerSetCOP rotamer_set( rotamer_sets()->rotamer_set_for_moltenresidue( moltenres_id ) ); ResidueCOP new_rotamer( rotamer_set->rotamer( rotamer_state_on_moltenres ) ); //core::PackerEnergy tmp_currentenergy; //setup energy to keep track of changes core::PackerEnergy delta_energy_accumulated=0, previous_energy_for_node_accumulated=0; std::map<Size, Size> resid_states; //record the seeding position resid_states[moltenres_id] = rotamer_state_on_moltenres; int other_prevrotamer_state(0); bool found_rotamer = false; Size num_linked_res =0; for ( auto itr = linked_residues.begin(), ite = linked_residues.end(); itr != ite; ++itr ) { // go through each linked residue num_linked_res++; TR.Debug << "analyzing num_linked_res: " << num_linked_res << std::endl; if ( ( *itr != 0 ) && ( *itr != moltenres_id ) ) { //skip this step if residue is self //try multiple substitutions if ( TR.Trace.visible() ) { TR.Trace << "moltenres_id " << moltenres_id << " coupled to moltenres_id " << *itr << std::endl; } other_prevrotamer_state = state_on_node(*itr); //pick a rotamer at a linked position RotamerSetCOP other_rotamer_set( rotamer_sets()->rotamer_set_for_moltenresidue( *itr ) ); //ResidueCOP other_rotamer( other_prevrotamer_state == 0 ? ResidueCOP(0) : other_rotamer_set->rotamer( other_prevrotamer_state ) ); ResidueCOP other_rotamer( ResidueCOP(nullptr) ); utility::vector1<int> passed_states; int const other_nrotamers( other_rotamer_set->num_rotamers() ); int tries = other_nrotamers; found_rotamer = false; while ( tries ) { // pick a rotamer at the other position int other_rotamer_state = tries; other_rotamer = other_rotamer_set->rotamer(other_rotamer_state); --tries; // For quasisymmetric case, check for the same AA at linked positions, // but not the same rotamer. if ( quasiflag ) { if ( new_rotamer->is_similar_aa( *other_rotamer ) ) { TR.Debug << "QUASIBYPASS: similar AAs found: " << moltenres_id << " (" << new_rotamer->aa() << ") and "<< *itr << " (" << other_rotamer->aa() << ")"; if ( new_rotamer->is_similar_rotamer( *other_rotamer ) ) { //found the same rotamer TR.Debug << " [IDENTICAL ROTAMERS]" << std::endl; } else { TR.Debug << std::endl; } //generate new list of all AAs that pass passed_states.push_back( other_rotamer_state ); continue; } else { TR.Debug << "QUASIBYPASS: AAs not similar, tries remaining: " << tries << std::endl; } } else { // not quasisymmetric if ( new_rotamer->is_similar_rotamer( *other_rotamer ) ) { //found the same rotamer, move on //if ( new_rotamer->is_similar_aa( *other_rotamer ) ) { //found the same rotamer, move on //std::cout << "found the same rotamer for " << moltenres_id << " and " << *itr << "of types " << new_rotamer->aa() << " and " << other_rotamer->aa() << std::endl; found_rotamer = true; // record the state resid_states[*itr] = other_rotamer_state; break; } } } //tries if ( quasiflag ) { //if quasisymmetric case, RNG pick a rotamer from the newly compiled list of similar AAs TR.Debug << "QUASIBYPASS: number of states with similar AA: " << passed_states.size() << std::endl; auto ranrotamer2 = static_cast<int>( numeric::random::rg().random_range(1, passed_states.size() )); found_rotamer = true; //flags this rotamer to be "same" for the sake of code downstream resid_states[*itr] = passed_states[ ranrotamer2 ]; //record state of "other rotamer" } if ( !found_rotamer ) { // any of the linked position without the same rotamer should be passed TR.Debug << "same rotamer not found for " << moltenres_id << " and " << *itr << std::endl; break; } } else if ( (*itr == moltenres_id) && (linked_residues.size() == 1) ) { // For quasisymmetrical design, one might have designable positions that are not // quasisymmetrical, and therefore do not need RotamerLinks to other residues. But in // order to get around a segfault in src/core/pack/rotamer_sets/RotamerSets.cc, // these residues must have RotamerLinks to only themselves; they therefore fail the // if above, leading to a continue directly below at if (!foundrotamer). So, here we // will detect these positions and set found_rotamer to true. TR.Debug << "QUASIBYPASS: SELF-LINKED AA found: " << moltenres_id << " (" << new_rotamer->aa() << ")" << std::endl; found_rotamer = true; other_prevrotamer_state = state_on_node(*itr); } } //for linked residues if ( ( !found_rotamer ) && ( ! ( quasiflag ) ) ) { // any of the linked position without the same rotamer should be passed (don't do this for quasisymmetry) //invalidate all the linked positions TR.Debug << "invalidate " ; for ( auto & resid_state : resid_states ) { rot_valid[ rotamer_sets()->moltenres_rotid_2_rotid( resid_state.first, resid_state.second ) ] = false; TR.Debug << resid_state.first << "(" << resid_state.second << ")" ; } TR.Debug << std::endl; continue; } //score the good rotamers and pass through metropolis core::PackerEnergy totalenergy = 0.0; //reset totalenergy for ( auto & resid_state : resid_states ) { core::PackerEnergy delta_energy_temp( 0.0 ), previous_energy_for_node_temp( 0.0 ); //initialize to zero? ig_->consider_substitution( resid_state.first, resid_state.second, delta_energy_temp, previous_energy_for_node_temp ); currentenergy = ig_->commit_considered_substitution(); TR.Debug << "current energy(" << resid_state << "): " << currentenergy << std::endl; totalenergy += currentenergy; TR.Debug << "total energy: " << totalenergy << std::endl; delta_energy_accumulated += delta_energy_temp; previous_energy_for_node_accumulated += previous_energy_for_node_temp; } core::PackerEnergy avgenergy = ( totalenergy / resid_states.size() ); //calculate avgenergy TR.Debug << "average energy: " << totalenergy << "/" << resid_states.size() << " = " << avgenergy << std::endl; core::PackerEnergy previous_energy_average = ( previous_energy_for_node + previous_energy_for_node_accumulated ); core::PackerEnergy delta_energy_average = ( delta_energy + delta_energy_accumulated ); if ( prevrotamer_state == 0 || other_prevrotamer_state == 0 || pass_metropolis( previous_energy_average, delta_energy_average ) ) { // accept !!!!!!! if ( TR.Trace.visible() ) { TR.Trace << "accepting multiple rotamer substitution (pass_metropolis)" << std::endl; } //set state for ( auto & resid_state : resid_states ) { TR.Debug << "resid_states " << resid_state << " first(residue): " << resid_state.first << " second(rotamer): " << resid_state.second << std::endl; state_on_node( resid_state.first ) = resid_state.second; } TR.Debug << "current (avg) energy: " << avgenergy << " best energy: " << bestenergy() << std::endl; //if ( ( prevrotamer_state == 0 ) || ( other_prevrotamer_state == 0 ) || ( currentenergy <= bestenergy() ) ) { //prevrotamerstate == 0 means this position has not taken a new rotamer before if ( ( prevrotamer_state == 0 ) || ( other_prevrotamer_state == 0 ) || ( avgenergy <= bestenergy() ) ) { //prevrotamerstate == 0 means this position has not taken a new rotamer before TR.Debug << "accepted rotamer stored in best (linked)" << std::endl; //bestenergy() = currentenergy; bestenergy() = avgenergy; best_state_on_node = state_on_node; } } else { // reject if ( TR.Trace.visible() ) { TR.Trace << "rejecting multiple rotamer substitution (fail_metropolis)" << std::endl; } //revert changes: for ( auto & resid_state : resid_states ) { core::PackerEnergy dE, oldE; ig_->consider_substitution( resid_state.first, state_on_node(resid_state.first), dE, oldE ); currentenergy = ig_->commit_considered_substitution(); } } // accept or reject? loopenergy(nn) = currentenergy; debug_assert( !calc_rot_freq() ); // skip the logic below for single-rotamer substitution //////////////////////////////////// continue; //bk keep new rotamer if it is lower in energy or accept it at some //bk probability if it is higher in energy, if it is the first //bk rotamer to be tried at this position automatically accept it. if ( (prevrotamer_state == 0) || pass_metropolis(previous_energy_for_node,delta_energy) ) { TR.Debug << "entering bk outer loop" << std::endl; state_on_node(moltenres_id) = rotamer_state_on_moltenres; if ( (prevrotamer_state == 0)||(currentenergy < bestenergy() ) ) { TR.Debug << "entering bk inner loop" << std::endl; bestenergy() = currentenergy; best_state_on_node = state_on_node; } } // accept loopenergy(nn) = currentenergy; core::PackerEnergy const temperature = get_temperature(); if ( calc_rot_freq() && ( temperature <= calc_freq_temp ) ) { ++nsteps; for ( Size ii = 1; ii <= nmoltenres; ++ii ) { int iistate = state_on_node(ii); if ( iistate != 0 ) { ++nsteps_for_rot( rotamer_sets()->moltenres_rotid_2_rotid(ii, iistate) ); } } } } // end of inneriteration loop } //end of outeriteration loop if ( ig_->any_vertex_state_unassigned() ) { std::cerr << "Critical error -- In FixbbLinkingRotamerSimAnnealer, one or more vertex states unassigned at annealing's completion." << std::endl; std::cerr << "Critical error -- assignment and energy of assignment meaningless" << std::endl; FArray1D_int nstates_for_moltenres( rotamer_sets()->nmoltenres(), 0 ); for ( uint ii = 0; ii < num_rots_to_pack(); ++ii ) { ++nstates_for_moltenres( rotamer_sets()->res_for_rotamer( rot_to_pack()[ ii ] ) ); } for ( uint ii = 1; ii <= rotamer_sets()->nmoltenres(); ++ii ) { if ( best_state_on_node( ii ) == 0 ) { std::cout << "Molten res " << ii << " (residue " << rotamer_sets()->moltenres_2_resid( ii ); std::cout << " ) assigned state 0 despite having " << nstates_for_moltenres( ii ) << " states to choose from" << std::endl; } } debug_assert( ! ig_->any_vertex_state_unassigned() ); utility_exit(); } //convert best_state_on_node into best_rotamer_at_seqpos for ( Size ii = 1; ii <= nmoltenres; ++ii ) { Size const iiresid = rotamer_sets()->moltenres_2_resid( ii ); bestrotamer_at_seqpos()( iiresid ) = rotamer_sets()->moltenres_rotid_2_rotid( ii, best_state_on_node(ii)); } } }//end namespace annealer }//end namespace pack }//end namespace core
0f0ada857d8d2d80af1bf9d30699f7f9b31c80dd
0c27fd0c92876d52f7d68d3a1b60d124f37281ac
/libs/geodata/pointmap/geodatapointmapbreakline.cpp
63505272e8fa50d3e2ee37773b5868c213c520a4
[]
no_license
waternk/prepost-gui
6892bee3640f432037d0fed37a8d7130eda8ad0e
abe29b2022ea016153f0d957da3acbaa0bb2dbb9
refs/heads/master
2022-10-14T12:09:04.869461
2020-06-01T18:10:20
2020-06-01T18:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,291
cpp
#include "geodatapointmap.h" #include "geodatapointmapbreakline.h" #include <misc/errormessage.h> #include <QPointF> #include <vtkCellArray.h> #include <vtkIndent.h> #include <vtkLine.h> #include <vtkProperty.h> #include <vtkRenderer.h> #include <vtkSmartPointer.h> #include <vtkVertex.h> #include <fstream> GeoDataPointmapBreakLine::GeoDataPointmapBreakLine(GeoDataPointmap* parent) : QObject(parent) { m_parent = parent; setupContainers(); setupActors(); // only for test m_verticesActor->VisibilityOff(); vtkRenderer* r = m_parent->renderer(); r->AddActor(m_edgesActor); r->AddActor(m_verticesActor); vtkActorCollection* col = m_parent->actorCollection(); col->AddItem(m_edgesActor); m_parent->updateVisibilityWithoutRendering(); } GeoDataPointmapBreakLine::~GeoDataPointmapBreakLine() { vtkRenderer* r = m_parent->renderer(); r->RemoveActor(m_edgesActor); r->RemoveActor(m_verticesActor); vtkActorCollection* col = m_parent->actorCollection(); col->RemoveItem(m_edgesActor); col->RemoveItem(m_verticesActor); } bool GeoDataPointmapBreakLine::isEdgeSelectable(const QVector2D& pos, double limitdist) { double x[3] = {pos.x(), pos.y(), 0.0}; double closestPoint[3]; int subId; double pcoords[3]; double weights[32]; double d = limitdist * limitdist; for (vtkIdType i = 0; i < m_edges->GetNumberOfCells(); ++i) { vtkCell* cell = m_edges->GetCell(i); double dist; if (1 == cell->EvaluatePosition(x, closestPoint, subId, pcoords, dist, weights)) { if (dist < d) { // this is the selected edge. m_selectedEdgeId = i; return true; } } } return false; } const QVector<QPointF> GeoDataPointmapBreakLine::polyLine() const { QVector<QPointF> ret; vtkIdList* idlist = m_vtkPolyLine->GetPointIds(); vtkPoints* points = m_vtkPolyLine->GetPoints(); if (points->GetNumberOfPoints() == 0) {return ret;} int vCount = idlist->GetNumberOfIds(); QPointF lastP, newP; for (int i = 0; i < vCount; ++i) { vtkIdType id = idlist->GetId(i); double* p = points->GetPoint(id); newP = QPointF(*p, *(p + 1)); if (i == 0 || lastP != newP) { ret << newP; } lastP = newP; } return ret; } void GeoDataPointmapBreakLine::setVertexIndices(const QVector<vtkIdType>& indices) { m_vertexIndices = indices; updateShapeData(); } void GeoDataPointmapBreakLine::setPolyLine(const QVector<QPointF>& polyline) { m_vtkPolyLine->Initialize(); vtkPoints* points = m_vtkPolyLine->GetPoints(); points->SetNumberOfPoints(polyline.count()); for (int i = 0; i < polyline.count(); ++i) { QPointF point = polyline.at(i); points->SetPoint(i, point.x(), point.y(), 0); } points->Modified(); updateShapeData(); } void GeoDataPointmapBreakLine::setupContainers() { m_vtkPolyLine = vtkSmartPointer<vtkPolyLine>::New(); m_vtkPolyLine->GetPoints()->SetDataTypeToDouble(); // setup grid. m_edges = vtkSmartPointer<vtkPolyData>::New(); m_vertices = vtkSmartPointer<vtkPolyData>::New(); m_selectedVertexId = 0; m_selectedEdgeId = 0; } void GeoDataPointmapBreakLine::setupActors() { m_edgesActor = vtkSmartPointer<vtkActor>::New(); m_verticesActor = vtkSmartPointer<vtkActor>::New(); m_edgesActor->GetProperty()->SetLighting(false); m_verticesActor->GetProperty()->SetLighting(false); // set properties m_edgesActor->GetProperty()->SetLineWidth(3); m_edgesActor->GetProperty()->SetColor(0, 0, 0); m_verticesActor->GetProperty()->SetPointSize(9); m_verticesActor->GetProperty()->SetColor(0, 0, 0); m_edgesMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); m_edgesMapper->UseLookupTableScalarRangeOff(); m_edgesMapper->ImmediateModeRenderingOn(); m_verticesMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); m_verticesMapper->UseLookupTableScalarRangeOff(); m_verticesMapper->ImmediateModeRenderingOn(); m_edgesMapper->SetInputData(m_edges); m_verticesMapper->SetInputData(m_vertices); m_edgesActor->SetMapper(m_edgesMapper); m_verticesActor->SetMapper(m_verticesMapper); } void GeoDataPointmapBreakLine::updateShapeData() { // update points. m_vtkPolyLine->Points->UnRegister(m_vtkPolyLine); m_vtkPolyLine->Points = m_parent->vtkGrid()->GetPoints(); m_vtkPolyLine->Points->Register(m_vtkPolyLine); vtkIdList* idlist = m_vtkPolyLine->GetPointIds(); idlist->Initialize(); for (int i = 0; i < m_vertexIndices.count(); ++i) { idlist->InsertNextId(m_vertexIndices[i]); } // edge grid is constructed. m_edges->Reset(); m_edges->SetPoints(m_vtkPolyLine->GetPoints()); int edgeCount = idlist->GetNumberOfIds() - 1; vtkSmartPointer<vtkCellArray> edges = vtkSmartPointer<vtkCellArray>::New(); edges->Allocate(edgeCount); vtkIdType points[2]; for (int i = 0; i < edgeCount; ++i) { points[0] = idlist->GetId(i); points[1] = idlist->GetId(i + 1); edges->InsertNextCell(2, points); } m_edges->SetLines(edges); m_edges->Modified(); // points are constructed. m_vertices->Reset(); m_vertices->SetPoints(m_vtkPolyLine->GetPoints()); int vertexCount = idlist->GetNumberOfIds(); vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New(); vertices->Allocate(vertexCount); vtkIdType pointId; for (int i = 0; i < vertexCount; ++i) { pointId = idlist->GetId(i); vertices->InsertNextCell(1, &pointId); } m_vertices->SetVerts(vertices); m_vertices->Modified(); } void GeoDataPointmapBreakLine::setZDepthRange(double /*min*/, double max) { m_verticesActor->SetPosition(0, 0, max); m_edgesActor->SetPosition(0, 0, max); } void GeoDataPointmapBreakLine::setActive(bool active) { vtkActorCollection* col = m_parent->actorCollection(); m_verticesActor->VisibilityOff(); col->RemoveItem(m_verticesActor); if (active) { col->AddItem(m_verticesActor); } m_parent->updateVisibilityWithoutRendering(); } void GeoDataPointmapBreakLine::setHidden(bool hidden) { vtkActorCollection* col = m_parent->actorCollection(); col->RemoveItem(m_verticesActor); col->RemoveItem(m_edgesActor); m_verticesActor->VisibilityOff(); m_edgesActor->VisibilityOff(); if (! hidden) { col->AddItem(m_edgesActor); } m_parent->updateVisibilityWithoutRendering(); }
[ "kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0" ]
kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0
f3353d1ebf50ec8badea7e6fa97e964a2f0a0b51
6102311bf844b6985164d016b005afcca9ad3c25
/Source/Graphics/Textures/TextureFormat.h
a6057ebdafcd2452380e1c13fdb11a1eaba7d66b
[]
no_license
GriffynWilkinson/Tank-Game
a5f03ed34155a82d9c5d82eef1c49629d7a5111c
6e0270a1ccf7cacc4301e017eead8956d05dc6d2
refs/heads/master
2020-04-08T12:04:37.869576
2018-11-27T13:27:57
2018-11-27T13:27:57
159,332,401
0
0
null
null
null
null
UTF-8
C++
false
false
200
h
#ifndef __GameDev2D__TextureFormat__ #define __GameDev2D__TextureFormat__ namespace GameDev2D { enum TextureFormat { TextureFormat_RGB = 0, TextureFormat_RGBA }; } #endif
a2ab7f5c90c706c23685b6ddf4ecb780b099edb3
c7ccfd9de1692aafaa5ee576980e7381e52cb346
/sourceCode/3.0/WebsocketServer/WebsocketProtocol/WebsocketContext.cpp
3bd221627ad355e10ef4da846809758ea55bc4fd
[ "BSL-1.0" ]
permissive
chenzuo/PushFramework
c3f98eac2dad75dca5da1e13382627b3bff35285
a1a2a63cdc7517499e165dde68373bccca6e24d3
refs/heads/master
2020-03-23T18:18:22.176058
2018-09-06T05:52:26
2018-09-06T05:52:26
141,900,087
2
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
#include "stdafx.h" #include "WebsocketContext.h" WebsocketContext::WebsocketContext(void) :bufferedContent(RecyclableBuffer::Single) { currentContinuationOpCode = -1; } WebsocketContext::~WebsocketContext(void) { } void WebsocketContext::recycle() { bufferedContent.clearBytes(); currentContinuationOpCode = -1; }
81bc67a3368d2480031ae3e5ba17b86726a2d6a9
d6b4bdf418ae6ab89b721a79f198de812311c783
/teo/src/v20220106/model/DescribeOverviewL7DataResponse.cpp
91528523db4a8ed4027ade50228c51b6fa713608
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
6,202
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/teo/v20220106/model/DescribeOverviewL7DataResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Teo::V20220106::Model; using namespace std; DescribeOverviewL7DataResponse::DescribeOverviewL7DataResponse() : m_typeHasBeenSet(false), m_intervalHasBeenSet(false), m_dataHasBeenSet(false) { } CoreInternalOutcome DescribeOverviewL7DataResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("Type") && !rsp["Type"].IsNull()) { if (!rsp["Type"].IsString()) { return CoreInternalOutcome(Core::Error("response `Type` IsString=false incorrectly").SetRequestId(requestId)); } m_type = string(rsp["Type"].GetString()); m_typeHasBeenSet = true; } if (rsp.HasMember("Interval") && !rsp["Interval"].IsNull()) { if (!rsp["Interval"].IsString()) { return CoreInternalOutcome(Core::Error("response `Interval` IsString=false incorrectly").SetRequestId(requestId)); } m_interval = string(rsp["Interval"].GetString()); m_intervalHasBeenSet = true; } if (rsp.HasMember("Data") && !rsp["Data"].IsNull()) { if (!rsp["Data"].IsArray()) return CoreInternalOutcome(Core::Error("response `Data` is not array type")); const rapidjson::Value &tmpValue = rsp["Data"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { TimingDataRecord item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_data.push_back(item); } m_dataHasBeenSet = true; } return CoreInternalOutcome(true); } string DescribeOverviewL7DataResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_typeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Type"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator); } if (m_intervalHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Interval"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_interval.c_str(), allocator).Move(), allocator); } if (m_dataHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Data"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_data.begin(); itr != m_data.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } string DescribeOverviewL7DataResponse::GetType() const { return m_type; } bool DescribeOverviewL7DataResponse::TypeHasBeenSet() const { return m_typeHasBeenSet; } string DescribeOverviewL7DataResponse::GetInterval() const { return m_interval; } bool DescribeOverviewL7DataResponse::IntervalHasBeenSet() const { return m_intervalHasBeenSet; } vector<TimingDataRecord> DescribeOverviewL7DataResponse::GetData() const { return m_data; } bool DescribeOverviewL7DataResponse::DataHasBeenSet() const { return m_dataHasBeenSet; }
26965528f452a0f39b2973b5a49f6fc8cb8371d5
c9287937c4d7900d311640a2b16c08c42eedfe58
/tensorflow/lite/delegates/gpu/common/model_builder_helper.cc
453e33ec91615f5979009746470bbea7c4761326
[ "Apache-2.0" ]
permissive
Purplme/tensorflow
e868e9bf59cc8eb680f1c35bf0b8615ec2b68c62
d2d6c3f07a0b874e64a024c767deb7c9fb39b704
refs/heads/master
2022-11-23T23:38:00.243591
2020-07-16T06:20:19
2020-07-16T06:25:23
280,074,885
2
0
Apache-2.0
2020-07-16T06:39:14
2020-07-16T06:39:13
null
UTF-8
C++
false
false
11,438
cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/common/model_builder_helper.h" #include <string> #include <fp16.h> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "tensorflow/lite/builtin_ops.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/context.h" #include "tensorflow/lite/context_util.h" #include "tensorflow/lite/delegates/gpu/common/model.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/utils.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace gpu { absl::Status GetNodeAndRegistration(TfLiteContext* context, int node_id, TfLiteNode** tflite_node, TfLiteRegistration** registration) { if (context->GetNodeAndRegistration(context, node_id, tflite_node, registration) != kTfLiteOk) { return absl::InvalidArgumentError(absl::StrCat( "Couldn't get node and registration info for op: ", node_id)); } return absl::OkStatus(); } DataType ToDataType(TfLiteType type) { switch (type) { case kTfLiteFloat32: return DataType::FLOAT32; case kTfLiteInt32: return DataType::INT32; case kTfLiteInt64: return DataType::INT64; case kTfLiteInt8: return DataType::INT8; case kTfLiteUInt8: return DataType::UINT8; default: return DataType::UNKNOWN; } } absl::Status ExtractTensorShape(const TfLiteTensor& tflite_tensor, BHWC* bhwc) { const TfLiteIntArray* dims = tflite_tensor.dims; switch (dims->size) { case 1: *bhwc = BHWC(dims->data[0], 1, 1, 1); return absl::OkStatus(); case 2: *bhwc = BHWC(dims->data[0], 1, 1, dims->data[1]); return absl::OkStatus(); case 3: *bhwc = BHWC(dims->data[0], 1, dims->data[1], dims->data[2]); return absl::OkStatus(); case 4: *bhwc = BHWC(dims->data[0], dims->data[1], dims->data[2], dims->data[3]); return absl::OkStatus(); default: return absl::InvalidArgumentError(absl::StrCat( "Tensor \"", tflite_tensor.name ? tflite_tensor.name : "nullptr", "\" has bad input dims size: ", dims->size, ".")); } } absl::Status ConvertTfLiteTensorToTensorRef(const TfLiteTensor& tflite_tensor, TensorRef<BHWC>* tensor_ref) { tensor_ref->type = ToDataType(tflite_tensor.type); return ExtractTensorShape(tflite_tensor, &tensor_ref->shape); } absl::Status PopulateQuantParams(const TfLiteTensor& tensor, QuantizationParams* quant_params) { const TfLiteQuantization& quant = tensor.quantization; if (quant.type != TfLiteQuantizationType::kTfLiteAffineQuantization) { return absl::InvalidArgumentError( absl::StrCat("Tensor not quantized: ", std::string(tensor.name))); } const TfLiteAffineQuantization* params = static_cast<const TfLiteAffineQuantization*>(quant.params); if (params->scale->size > 1) { return absl::InvalidArgumentError( absl::StrCat("Non-constant per-channel quantized tensor: ", std::string(tensor.name))); } const float scale = params->scale->data[0]; const float zero_point = static_cast<float>(params->zero_point->data[0]); float qmin_value = 0; float qmax_value = 0; if (tensor.type == kTfLiteUInt8) { qmin_value = static_cast<float>(std::numeric_limits<uint8_t>::min()); qmax_value = static_cast<float>(std::numeric_limits<uint8_t>::max()); } else if (tensor.type == kTfLiteInt8) { qmin_value = static_cast<float>(std::numeric_limits<int8_t>::min()); qmax_value = static_cast<float>(std::numeric_limits<int8_t>::max()); } else { return absl::InvalidArgumentError(absl::StrCat( "Type invalid for quantized tensor: ", std::string(tensor.name))); } quant_params->min = scale * (static_cast<float>(qmin_value) - zero_point); quant_params->max = scale * (static_cast<float>(qmax_value) - zero_point); quant_params->scale = scale; return absl::OkStatus(); } int GetNumberOfRuntimeInputsForNode(const TfLiteContext* context, const TfLiteNode* tflite_node) { int number_of_runtime_inputs = 0; for (int i = 0; i < NumInputs(tflite_node); i++) { const TfLiteTensor* tensor = GetOptionalInputTensor(context, tflite_node, i); if (tensor != nullptr && !IsConstantTensor(tensor)) { number_of_runtime_inputs++; } } return number_of_runtime_inputs; } int GetNumberOfConstInputsForNode(const TfLiteContext* context, const TfLiteNode* tflite_node) { return NumInputs(tflite_node) - GetNumberOfRuntimeInputsForNode(context, tflite_node); } absl::Status CheckInputsOutputs(const TfLiteContext* context, const TfLiteNode* tflite_node, int runtime_inputs, int outputs) { const int runtime_inputs_from_model = GetNumberOfRuntimeInputsForNode(context, tflite_node); if (runtime_inputs_from_model != runtime_inputs) { return absl::InternalError(absl::StrCat( "Expected ", runtime_inputs, " runtime input tensor(s), but node has ", runtime_inputs_from_model, " runtime input(s).")); } const int outputs_from_model = NumOutputs(tflite_node); if (outputs_from_model != outputs) { return absl::InternalError(absl::StrCat("Expected ", outputs, " output tensor(s), but node has ", outputs_from_model, " output(s).")); } return absl::OkStatus(); } absl::Status CheckInputsConstsOutputs(const TfLiteContext* context, const TfLiteNode* tflite_node, int runtime_inputs, int const_inputs, int outputs) { const int const_inputs_from_model = GetNumberOfConstInputsForNode(context, tflite_node); if (const_inputs_from_model != const_inputs) { return absl::InternalError(absl::StrCat( "Expected ", const_inputs, " const input tensor(s), but node has ", const_inputs_from_model, " const input(s).")); } return CheckInputsOutputs(context, tflite_node, runtime_inputs, outputs); } void ConvertFloat16ToFloat32(size_t num_elements, const uint16_t* src, float* dst) { for (size_t i = 0; i < num_elements; i++) { *dst++ = fp16_ieee_to_fp32_value(*src++); } } template <> absl::Status CreateVectorCopyData<float>(const TfLiteTensor& tensor, float* tensor_data) { switch (tensor.type) { case kTfLiteFloat32: std::memcpy(tensor_data, tensor.data.f, tensor.bytes); break; case kTfLiteFloat16: ConvertFloat16ToFloat32( NumElements(&tensor), reinterpret_cast<uint16_t const*>(tensor.data.f16), tensor_data); break; case kTfLiteInt8: DequantizeConstantTensor(tensor, tensor.data.int8, tensor_data); break; case kTfLiteUInt8: DequantizeConstantTensor(tensor, tensor.data.uint8, tensor_data); break; case kTfLiteInt32: DequantizeConstantTensor(tensor, tensor.data.i32, tensor_data); break; default: return absl::InvalidArgumentError( "Unsupported data type for float32 tensor"); } return absl::OkStatus(); } const std::string GetDimensionString(const TfLiteIntArray* dimensions) { return absl::StrJoin(TfLiteIntArrayView(dimensions), "x"); } absl::Status SetAllDimensions(const TfLiteIntArray* dimensions, Scalar* shape) { if (dimensions->size < 0) { return absl::InvalidArgumentError("Invalid Scalar dimensions"); } for (int i = 0; i < dimensions->size; ++i) { if (dimensions->data[i] != 1) { return absl::InvalidArgumentError(absl::StrCat( GetDimensionString(dimensions), " cannot be reduced to scalar.")); } } shape->v = 1; return absl::OkStatus(); } absl::Status CheckIfLinearConvertible(const TfLiteIntArray* dimensions) { if (dimensions->size <= 0) { return absl::InvalidArgumentError("Dimension is empty."); } for (int i = 0; i < dimensions->size - 1; ++i) { if (dimensions->data[i] != 1) { return absl::InvalidArgumentError(absl::StrCat( GetDimensionString(dimensions), " cannot be reduced to linear.")); } } return absl::OkStatus(); } absl::Status SetAllDimensions(const TfLiteIntArray* dimensions, Linear* shape) { RETURN_IF_ERROR(CheckIfLinearConvertible(dimensions)); shape->v = dimensions->data[dimensions->size - 1]; return absl::OkStatus(); } absl::Status SetAllDimensions(const TfLiteIntArray* dimensions, HWC* shape) { if (dimensions->size == 3) { shape->h = dimensions->data[0]; shape->w = dimensions->data[1]; shape->c = dimensions->data[2]; return absl::OkStatus(); } if (dimensions->size == 4) { if (dimensions->data[0] != 1) { return absl::UnimplementedError("Batch size is not equal to 1."); } shape->h = dimensions->data[1]; shape->w = dimensions->data[2]; shape->c = dimensions->data[3]; return absl::OkStatus(); } return absl::InvalidArgumentError( absl::StrCat("Expected a 3D tensor of shape HxWxC or a 4D tensor of " "shape 1xHxWxC but got ", GetDimensionString(dimensions))); } absl::Status SetAllDimensions(const TfLiteIntArray* dimensions, HW* shape) { if (dimensions->size != 2) { return absl::InvalidArgumentError( absl::StrCat("Expected a 2D tensor of shape HxW but got ", GetDimensionString(dimensions))); } shape->h = dimensions->data[0]; shape->w = dimensions->data[1]; return absl::OkStatus(); } absl::Status SetAllDimensions(const TfLiteIntArray* dimensions, OHWI* shape) { if (dimensions->size != 4) { return absl::InvalidArgumentError( absl::StrCat("Expected a 4D tensor of shape OxHxWxI but got ", GetDimensionString(dimensions))); } shape->o = dimensions->data[0]; shape->h = dimensions->data[1]; shape->w = dimensions->data[2]; shape->i = dimensions->data[3]; return absl::OkStatus(); } absl::Status SetAllDimensions(const TfLiteIntArray* dimensions, BHWC* shape) { if (dimensions->size != 4) { return absl::InvalidArgumentError( absl::StrCat("Expected a 4D tensor of shape BxHxWxC but got ", GetDimensionString(dimensions))); } shape->b = dimensions->data[0]; shape->h = dimensions->data[1]; shape->w = dimensions->data[2]; shape->c = dimensions->data[3]; return absl::OkStatus(); } } // namespace gpu } // namespace tflite
f76930336dd224082a684bd755ac4cf5bdadb829
d000f2ee3e2a5e9e6bb69f3a2785d9e37becd7f4
/pea/Action.cpp
fd5ff66b8a495a51804991ae8b7eb9c6163e39c4
[]
no_license
krzemien888/pea
79cfcb4a4718d91c2d7f93680337d96b7f3f0d71
c235e47968ccf2d81e06ce6a28a3ff65a5d0f800
refs/heads/master
2021-09-04T04:39:34.582155
2018-01-15T22:50:54
2018-01-15T22:50:54
106,030,481
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
#include "stdafx.h" #include "Action.h" Action::Action(int index, std::string name, std::function<void(void)> task) : actionIndex(index), actionName(name), actionTask(task) { } Action::Action() { actionIndex = 15; actionName = std::string("Default action"); actionTask = []() {std::cout << "Default action taken" << std::endl;system("pause");}; } int Action::getIndex() const { return actionIndex; } std::string Action::getName() const { return actionName; } void Action::Run() { actionTask(); }
61b01bee5f5f08e3dcd9314bac9219ce500a89bf
b99e6a122bc377e6eabfe2ece650b3f26eaaa6d8
/src/poj/2138.cc
6742faec9fe2b8719e203d8a976667ff07e76347
[]
no_license
cedric-sun/toys
8a853317885a56faf01628d32a94f5e759952c8e
492156c0f70d4ddad4f943e7ea1a024a36cdb54b
refs/heads/master
2023-02-27T01:50:53.148846
2021-02-06T22:41:35
2021-02-06T22:41:35
293,705,256
0
0
null
null
null
null
UTF-8
C++
false
false
2,519
cc
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <cstring> #include <queue> using namespace std; const int N=1005,inf=0x7f7f7f7f; int n,maxlen,minlen,si; int dist[N]; bool inq[N]; vector<vector<int> > g; vector<int> List[81]; //按字符串长度分类 string inttostr[N]; bool diff1(int a,int b) //判断两个字符串是否仅有一个字母不同 { string::iterator ssit=inttostr[a].begin(), //short string iterator sse=inttostr[a].end(), lsit=inttostr[b].begin(), //long string iterator lse=inttostr[b].end(); while (ssit!=sse && lsit!=lse) { if (*ssit==*lsit) ++ssit,++lsit; else ++lsit; } if (ssit==sse) return 1; return 0; } void read() { string s; cin>>n>>s; maxlen=0;minlen=inf; for (int i=0;i<n;i++) { string tmp; cin>>tmp; if (tmp==s) si=i; inttostr[i]=tmp; int len=tmp.length(); List[len].push_back(i); maxlen=max(maxlen,len); minlen=min(minlen,len); } } void build() { g.resize(n); for (int i=minlen;i<maxlen;i++) { for (vector<int>::iterator it1=List[i].begin();it1!=List[i].end();++it1) for (vector<int>::iterator it2=List[i+1].begin();it2!=List[i+1].end();++it2) if (diff1(*it1,*it2)) g[*it1].push_back(*it2); } } void spfa() { memset(dist,0x7f,sizeof dist); dist[si]=0; deque<int> q; inq[si]=1; q.push_back(si); while (!q.empty()) { const int cur=q.front();q.pop_front(); inq[cur]=0; for (vector<int>::iterator it=g[cur].begin();it!=g[cur].end();++it) { if (dist[cur]<inf && dist[cur]-1<dist[*it]) { dist[*it]=dist[cur]-1; if (!inq[*it]) { if (q.empty()) q.push_back(*it); else if (dist[*it]<dist[q.front()]) q.push_front(*it); else q.push_back(*it); inq[*it]=1; } } } } } int findmax() { int maxdist=inf,index; for (int i=0;i<n;i++) if (dist[i]<maxdist) maxdist=dist[index=i]; return index; } int main() { read(); build(); spfa(); cout<<inttostr[findmax()]<<endl; return 0; }
933f78bdcdbeff1d3989fc28a28b0f1fa701cdd3
f68aec9db181fb324c82f4a2f943ebc5524a9349
/1.两数之和.cpp
d8b788c6459484cdcc813a1d584d61401b844be2
[]
no_license
y19941115mx/.leetcode
d845a96ede1935f26e86ad501f49c78622b246a2
051ea938e355290266069a2a28c031ab16ec7973
refs/heads/master
2020-09-15T03:26:27.938516
2020-02-26T09:49:47
2020-02-26T09:49:47
223,337,307
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
/* * @lc app=leetcode.cn id=1 lang=cpp * * [1] 两数之和 * * https://leetcode-cn.com/problems/two-sum/description/ * * algorithms * Easy (47.03%) * Likes: 6984 * Dislikes: 0 * Total Accepted: 691.8K * Total Submissions: 1.5M * Testcase Example: '[2,7,11,15]\n9' * * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 * * 示例: * * 给定 nums = [2, 7, 11, 15], target = 9 * * 因为 nums[0] + nums[1] = 2 + 7 = 9 * 所以返回 [0, 1] * * */ #include <vector> #include <map> using namespace std; //@lc code=start class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { map<int, int> cacheMap; for (int i = 0; i < nums.size(); i++) { int curr = nums[i]; int component = target - curr; if (cacheMap.find(component) != cacheMap.end()) { return vector<int>{cacheMap[component], i}; } cacheMap[curr] = i; } return vector<int>{-1}; } }; // @lc code=end
0355441b0963cd57fa5eada507feb60b53252f50
ff18d5236425e7aa0b46a9ce939c7cf28777fc4d
/WhispEngine/WhispEngine/GPUdetect/DeviceId.cpp
006f0b33c25d5e477eff9db1b74f0ec6ae32b5dc
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Empty-Whisper/WhispEngine
04377a9da44cae87e4cd2f3aef2f4c0bf479cc14
f1f8412377db24569ea2e2db7118b0339a11e85d
refs/heads/master
2020-07-28T10:33:35.044397
2020-07-02T17:25:57
2020-07-02T17:25:57
209,391,424
12
5
MIT
2019-12-29T17:28:13
2019-09-18T19:48:14
C++
UTF-8
C++
false
false
8,635
cpp
// Copyright 2010 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED ""AS IS."" // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. // // DeviceId.cpp : Implements the GPU Device detection and graphics settings // configuration functions. // #include <wrl.h> #include "DeviceId.h" #include <stdio.h> #include <string> #include <InitGuid.h> #include <D3D11.h> #include <D3DCommon.h> #include "dxgi1_4.h" #include <oleauto.h> #include <wbemidl.h> #include <ObjBase.h> /***************************************************************************************** * getGraphicsDeviceInfo * * Function to retrieve information about the primary graphics driver. This includes * the device's Vendor ID, Device ID, and available memory. * *****************************************************************************************/ static bool first_time = true; static HMODULE hDXGI = NULL; bool getGraphicsDeviceInfo( unsigned int* VendorId, unsigned int* DeviceId, std::wstring* GFXBrand, unsigned __int64* VideoMemoryBudget, unsigned __int64* VideoMemoryCurrentUsage, unsigned __int64* VideoMemoryAvailable, unsigned __int64* VideoMemoryReserved) { // // DXGI is supported on Windows Vista and later. Define a function pointer to the // CreateDXGIFactory function. DXGIFactory1 is supported by Windows Store Apps so // try that first. // if (first_time) { first_time = false; hDXGI = LoadLibrary("dxgi.dll"); if (hDXGI == NULL) { return false; } } typedef HRESULT(WINAPI*LPCREATEDXGIFACTORY)(REFIID riid, void** ppFactory); LPCREATEDXGIFACTORY pCreateDXGIFactory = (LPCREATEDXGIFACTORY)GetProcAddress(hDXGI, "CreateDXGIFactory1"); if (pCreateDXGIFactory == NULL) { pCreateDXGIFactory = (LPCREATEDXGIFACTORY)GetProcAddress(hDXGI, "CreateDXGIFactory"); if (pCreateDXGIFactory == NULL) { FreeLibrary(hDXGI); return false; } } // // We have the CreateDXGIFactory function so use it to actually create the factory and enumerate // through the adapters. Here, we are specifically looking for the Intel gfx adapter. // IDXGIAdapter* pAdapter; IDXGIFactory* pFactory; DXGI_ADAPTER_DESC AdapterDesc; if (FAILED((*pCreateDXGIFactory)(__uuidof(IDXGIFactory), (void**)(&pFactory)))) { FreeLibrary(hDXGI); return false; } if (FAILED(pFactory->EnumAdapters(0, (IDXGIAdapter**)&pAdapter))) { FreeLibrary(hDXGI); return false; } unsigned int intelAdapterIndex = 0; while (pFactory->EnumAdapters(intelAdapterIndex, &pAdapter) != DXGI_ERROR_NOT_FOUND) { pAdapter->GetDesc(&AdapterDesc); //if (AdapterDesc.VendorId == 0x8086) { break; //} intelAdapterIndex++; } if (pAdapter == NULL) { FreeLibrary(hDXGI); return false; } // // If we are on Windows 10 then the Adapter3 interface should be available. This is recommended over using // the AdapterDesc for getting the amount of memory available. // IDXGIAdapter3* pAdapter3; pAdapter->QueryInterface(IID_IDXGIAdapter3, (void**)&pAdapter3); if (pAdapter3) { DXGI_QUERY_VIDEO_MEMORY_INFO memInfo; pAdapter3->QueryVideoMemoryInfo(intelAdapterIndex, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &memInfo); //*VideoMemory = memInfo.AvailableForReservation; *VideoMemoryBudget = memInfo.Budget; *VideoMemoryCurrentUsage = memInfo.CurrentUsage; *VideoMemoryAvailable = memInfo.AvailableForReservation; *VideoMemoryReserved = memInfo.CurrentReservation; pAdapter3->Release(); } else { *VideoMemoryBudget = (unsigned __int64)(AdapterDesc.DedicatedVideoMemory); *VideoMemoryCurrentUsage = 0; *VideoMemoryAvailable = (unsigned __int64)(AdapterDesc.SharedSystemMemory); *VideoMemoryReserved = 0; } if(VendorId != nullptr) *VendorId = AdapterDesc.VendorId; if(DeviceId != nullptr) *DeviceId = AdapterDesc.DeviceId; if(GFXBrand != nullptr) *GFXBrand = AdapterDesc.Description; pAdapter->Release(); FreeLibrary(hDXGI); return true; } /****************************************************************************************************************************************** * getIntelDeviceInfo * * Description: * Gets device information which is stored in a D3D counter. First, a D3D device must be created, the Intel counter located, and * finally queried. * * Supported device info: GPU Max Frequency, GPU Min Frequency, GT Generation, EU Count, Package TDP, Max Fill Rate * * Parameters: * unsigned int VendorId - [in] - Input: system's vendor id * IntelDeviceInfoHeader *pIntelDeviceInfoHeader - [in/out] - Input: allocated IntelDeviceInfoHeader * * Output: Intel device info header, if found * void *pIntelDeviceInfoBuffer - [in/out] - Input: allocated void * * Output: IntelDeviceInfoV[#], cast based on IntelDeviceInfoHeader * Return: * GGF_SUCCESS: Able to find Data is valid * GGF_E_UNSUPPORTED_HARDWARE: Unsupported hardware, data is invalid * GGF_E_UNSUPPORTED_DRIVER: Unsupported driver on Intel, data is invalid * *****************************************************************************************************************************************/ /***************************************************************************************** * getCPUInfo * * Parses CPUID output to find the brand and vendor strings. * *****************************************************************************************/ void getCPUInfo(std::string* cpubrand, std::string* cpuvendor) { // Get extended ids. int CPUInfo[4] = { -1 }; __cpuid(CPUInfo, 0x80000000); unsigned int nExIds = CPUInfo[0]; // Get the information associated with each extended ID. char CPUBrandString[0x40] = { 0 }; char CPUVendorString[0x40] = { 0 }; __cpuid(CPUInfo, 0); memcpy_s(CPUVendorString, sizeof(CPUInfo), &CPUInfo[1], sizeof(int)); memcpy_s(CPUVendorString + 4, sizeof(CPUInfo), &CPUInfo[3], sizeof(int)); memcpy_s(CPUVendorString + 8, sizeof(CPUInfo), &CPUInfo[2], sizeof(int)); *cpuvendor = CPUVendorString; for (unsigned int i = 0x80000000; i <= nExIds; ++i) { __cpuid(CPUInfo, i); if (i == 0x80000002) { memcpy_s(CPUBrandString, sizeof(CPUInfo), CPUInfo, 4 * sizeof(int)); } else if (i == 0x80000003) { memcpy_s(CPUBrandString + 16, sizeof(CPUInfo), CPUInfo, 4 * sizeof(int)); } else if (i == 0x80000004) { memcpy_s(CPUBrandString + 32, sizeof(CPUInfo), CPUInfo, 4 * sizeof(int)); } } *cpubrand = CPUBrandString; } /***************************************************************************************** * getGTGeneration * * Returns the generation by parsing the device id. The first two digits of the hex * number generally denote the generation. Sandybridge and Ivybridge share the same * numbers so they must be further parsed. * * Comparison of the deviceIds (for example to see if a device is more recent than * another) does not always work. * *****************************************************************************************/ PRODUCT_FAMILY getGTGeneration(unsigned int deviceId) { unsigned int maskedDeviceId = deviceId & 0xFF00; // // Device is Sandybridge or Ivybridge // if (maskedDeviceId == 0x0100) { if ( ((deviceId & 0x0050) == 0x0050) || ((deviceId & 0x0060) == 0x0060) ) { return IGFX_IVYBRIDGE; } if ( ((deviceId & 0x0010) == 0x0010) || ((deviceId & 0x00F0) == 0x0000) ) { return IGFX_SANDYBRIDGE; } } if (maskedDeviceId == 0x0400 || maskedDeviceId == 0x0A00 || maskedDeviceId == 0x0D00) { return IGFX_HASWELL; } if (maskedDeviceId == 0x1600) { return IGFX_BROADWELL; } if (maskedDeviceId == 0x1900) { return IGFX_SKYLAKE; } return IGFX_UNKNOWN; }
063ee6a08a6d4a2567ad3924ff75e5072af83e9a
6b95158bedf856771632fc761812b137e1c784f8
/Utils/CmdLineArgs.h
e80a5805782934b7dd0273dedb5849b03c08fa12
[ "MIT" ]
permissive
hhuangwx/sidecar
dabaa8b87ee7ab1160f60c73bc7ee70f52bcd74e
fe4fa1832410f815a566fbb1934c84e55d153992
refs/heads/master
2021-06-02T08:10:32.349881
2016-08-30T00:39:42
2016-08-30T00:39:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,296
h
#ifndef UTILS_CMDLINEARGS_H // -*- C++ -*- #define UTILS_CMDLINEARGS_H #include <iostream> #include <map> #include <stdexcept> #include <string> #include <vector> #include "Utils/Exception.h" namespace Utils { /** Command-line processor. Visits data found in argc and argv (as given to main(), and creates entries in instances of Options and Arguments based on what was found on the command-line. Parsing of the command-line is governed by user-supplied arrays that define what options are supported, and what arguments are required. @code OptionDef opts[] = { { 'd', "debug", "turn on debugging", "" }, { 'o', "output", "write output to FILE", "FILE" } }; ArgumentDef args[] = { { "FILE", "read input from FILE" } }; int main(int argc, const char* argv[]) { std::string inputFile(""), outputFile(""); CmdLineArgs cla(argc, argv, opts, sizeof(opts), args, sizeof(args)); if (cla.hasOpt("debug")) enableDebugging(); if (cla.hasOpt("output", outputFile)) redirect(outputFile); inputFile = cla.arg(0); ... ... } @endcode */ class CmdLineArgs { public: /** Collection of attributes used to define a command-line option. - shortName the short version (one character) of the option name. If 0, then the option does not have a short name. - longName the long version of the option name. If an empty string, then the option does not have a long name. - help text to print out for this option in `usage' messages - valueTag identifier for an option value. If an empty string, the option does not take a value. */ struct OptionDef { char shortName; const char* longName; const char* help; const char* valueTag; }; /** Define collection of OptionDef instances. */ using OptionDefVector = std::vector<OptionDef>; /** Define macro to help create an OptionDefVector from an C++ array of OptionDefs. */ #define OPTION_DEF_VECTOR(A) A, sizeof(A) #define NULL_OPTION_DEF_VECTOR 0, 0 /** Collection of attributes used to define a command-line argument. A zero-length name signals the start of optional arguments. - name the name of the argument. Only used in `usage' texts. - help text to print out for this argument in `usage' messages. */ struct ArgumentDef { const char* name; const char* help; }; /** Define collection of ArgumentDef instances. */ using ArgumentDefVector = std::vector<ArgumentDef>; /** Define macro to help create an ArgumentDefVector from an C++ array of ArgumentDefs. */ #define ARGUMENT_DEF_VECTOR(A) A, sizeof(A) #define NULL_ARGUMENT_DEF_VECTOR 0, 0 /** Map of options found on the command line. If an option was given a value, then its value is stored; otherwise, an empty string is stored for the value. */ class Options { public: using ValueVector = std::vector<std::string>; using OptionMap = std::map<std::string,ValueVector>; /** Constructor. */ Options() : values_() {} /** Add a new option under one or two names. \param name name of the option (long or short name) \param alt an alternative name for the option. If `name' is a long name, then this would be a short name. \param value the value to store under the given name and alt. */ void add(const std::string& name, const std::string& alt, const std::string& value); /** Lookup an option to see if it was set by the user. \param key the name of the option to look for \return TRUE if the option was found */ bool has(const std::string& key) const { return values_.find(key) != values_.end(); } /** Lookup an option to see if it was set by the user. \param key the name of the option to look for \return TRUE if the option was found */ bool has(char key) const { return has(std::string(1, key)); } /** Lookup an option to see if it was set by the user. If so, return the first value found under the option name. \param key the name of the option to look for \param value reference to string that is updated with the first option value found. If option was not set, then this value is left alone \return TRUE if the option was found */ bool has(const std::string& key, std::string& value) const; /** Lookup an option to see if it was set by the user. If so, return the first value found under the option name. \param key the name of the option to look for \param value reference to string that is updated with the first option value found. If option was not set, then this value is left alone \return TRUE if the option was found */ bool has(char key, std::string& value) const { return has(std::string(1, key), value); } /** Fetch all of the values for a long option key. \param key the name of the option to look for. \return vector of values set for the option. If option was never set, size of vector will be zero. */ ValueVector& operator[](const std::string& key) { return values_[key]; } /** Fetch all of the values for a short option key. \param key the name of the option to look for. \return vector of values set for the option. If option was never set, size of vector will be zero. */ ValueVector& operator[](char key) { return operator[](std::string(1, key)); } private: OptionMap values_; ///< collection of key/value pairs }; // class Options /** Collection arguments found on the command-line. */ class Arguments : public std::vector<std::string> {}; /** Constructor. Processes the given command-line argument values, argc and argv. These should be the values given to the main() routine by the system. The first value in argv is taken as the running program's name. After processing, the remaining argc and argv values may be obtained via the CmdLineArgs::argc() and CmdLineArgs::argv() methods. \param argc number of values in argv \param argv array of C strings representing the command line values \param description short description of the program \param optDefs vector of option definition values \param argDefs vector of argument definition values \param quitOnError control whether the program call ::exit or throws an exception on an error. */ CmdLineArgs(size_t argc, char* const* argv, const std::string& description, const OptionDefVector& optDefs, const ArgumentDefVector& argDefs, bool quitOnError = true); /** Constructor. Processes the given command-line argument values, argc and argv. These should be the values given to the main() routine by the system. The first value in argv is taken as the running program's name. After processing, the remaining argc and argv values may be obtained via the CmdLineArgs::argc() and CmdLineArgs::argv() methods. \param argc number of values in argv \param argv array of C strings representing the command line values \param description short description of the program \param optDefs array of option definitions \param sizeofOptDefs value of the sizeof operator applied to the optDefs value. Note that this must be done against the array object itself, and not a pointer to it. \param argDefs array of argument definitions \param sizeofArgDefs value of the sizeof operator applied to the argDefs value. Note that this must be done against the array object itself, and not a pointer to it. \param quitOnError control whether the program call ::exit or throws an exception on an error. */ CmdLineArgs(size_t argc, char* const* argv, const std::string& description, const OptionDef* optDefs, size_t sizeofOptDefs, const ArgumentDef* argDefs, size_t sizeofArgDefs, bool quitOnError = true); /** \return the full path of the executable */ const std::string& fullPath() const { return fullPath_; } /** \return the program name as taken from the first value in argv, sans any path. */ const std::string& progName() const { return progName_; } /** Write out an error message to std::cerr and exit the program with a non-zero value. \param txt error message text \param quit if true, call ::exit when done; otherwise throw std::runtime_error exception */ void usage(const std::string& txt, bool quit = true) const; /** Show the usage text for the program, and exit with a zero value. */ void help(bool quit = true) const; /** Obtain the options set on the command line. \return reference to Options instance */ Options& opts() { return opts_; } /** Obtain the arguments provided on the command line. \return reference to Arguments instance */ Arguments& args() { return args_; } /** Lookup an option to see if it was set by the user. \param key the name of the option to look for \return true if the option was found; false otherwise. */ bool hasOpt(const std::string& key) const { return verifyOptionDef(key), opts_.has(key); } /** Lookup an option to see if it was set by the user. \param key the name of the option to look for \return true if the option was found; false otherwise. */ bool hasOpt(char key) const { return verifyOptionDef(key), opts_.has(std::string(1, key)); } /** Lookup an option to see if it was set by the user. If so, return the first value found under the option name. \param key the name of the option to look for \param value reference to string that is updated with the first option value found. If option was not set, then this value is left alone \return true if the option was found; false otherwise. */ bool hasOpt(const std::string& key, std::string& value) const { return verifyOptionDef(key), opts_.has(key, value); } /** Lookup an option to see if it was set by the user. If so, return the first value found under the option name. \param key the name of the option to look for \param value reference to string that is updated with the first option value found. If option was not set, then this value is left alone \return true if the option was found; false otherwise */ bool hasOpt(char key, std::string& value) const { return verifyOptionDef(key), opts_.has(std::string(1, key), value); } /** Fetch all of the values for an option key. \param key the name of the option to look for. \return vector of values set for the option. If option was never set, size of vector will be zero. */ Options::ValueVector& opt(const std::string& key) { return opts_[key]; } /** Fetch all of the values for an option key. \param key the name of the option to look for. \return vector of values set for the option. If option was never set, size of vector will be zero. */ Options::ValueVector& opt(char key) { return opts_[std::string(1, key)]; } /** Check if a certain argument is available. \param index which argument to look for \return true if the argument is present; false otherwise */ bool hasArg(size_t index) const { return index < args_.size(); } /** Check if a certain argument is available. If so, return its value. \param index which argument to look for \param value reference to string that is updated with the argument value, if the argument exists \return TRUE if the argument was found; false otherwise */ bool hasArg(size_t index, std::string& value) const; /** Fetch a specific argument value. \param index which argument to obtain (zero-based) \return argument value */ const std::string& arg(size_t index) const { return args_[index]; } /** Obtain the residual argc value after all option and argument processing. \return number of values remaining in argv array */ int argc() const { return argc_; } /** Obtain the residual argv value after all option and argument processing. \return address of first unprocessed argument item */ char* const* argv() const { return argv_; } /** Obtain the arguments representing all of the command-line arguments processed up to this point. \return string of processed arguments */ const std::string& cmdline() const { return cmdline_; } private: /** Perform common initialization tasks for constructors. */ void initialize(); /** Fetch the next value from the system-supplied argv value. \return next value or throw exception if none available */ const char* getArg(); /** Locate the OptionDef record that has a given short name. If the option is not found, cause an error message to display to the user. \param shortName the short option to look for \return reference to matching OptionDef. If none found, then an error is printed and the program will exit. */ const OptionDef& findOptionDef(char shortName) const; /** Locate the OptionDef record that has a given long name. If the option is not found, cause an error message to display to the user. \param opt the name to look for \return reference to matching OptionDef. If none found, then an error is printed and the program will exit. */ const OptionDef& findOptionDef(const std::string& opt) const; /** Verify that there is an OptionDef record that has a given short name. If the option does not exist, throws std::logic_error. \param shortName the short option to look for */ void verifyOptionDef(char shortName) const; /** Verify that there is an OptionDef record that has a given long name. If the option does not exist, throws std::logic_error. \param opt the name to look for */ void verifyOptionDef(const std::string& opt) const; /** Process the argument list and record which options were found, along with any values they require. */ void processOptions(); /** Process a long option. \param opt option name */ void processLongOption(std::string opt); /** Process a short option. \param opt option name */ void processShortOption(const std::string& opt); /** Process the argument list and record which arguments were provided by the user. */ void processArguments(); /** Create a `usage' text made up from the user-supplied option and argument definitions, and write to std::cerr. */ void printUsage() const; /** Convenience method that generates an error message. \param txt error text \param opt short option that had the error */ void error(const char* txt, char opt) const; /** Convenience method that generates an error message. \param txt error text \param opt long option that had the error */ void error(const char* txt, const std::string& opt) const; size_t argc_; ///< Number of command line arguments left char* const* argv_; ///< Pointer to next command line argument std::string fullPath_; ///< Full path of executable std::string progName_; ///< Name of the running program std::string description_; ///< Description to show in help OptionDefVector optDefs_; ///< Option definitions from user ArgumentDefVector argDefs_; ///< Argument definitions from user Options opts_; ///< Options found during processing Arguments args_; ///< Arguments found during processin std::string cmdline_; ///< Copy of the full command line bool quitOnError_; ///< If true, call ::exit after reporting error }; // class CmdLineArgs } // namespace Utils /** \file */ #endif
0530c70b848db4bde9c32165a476580d8cbd9af2
68de3cf64bed153c466de0e0abb90e0cddb499da
/RHeroes/data/insdata.cpp
a82c080eb8cd56234636cc8e884e3e454911da3c
[]
no_license
yuyuyu00/Tesi
d2e5610eae0773220256b7641ac36cb2cb78b778
8ecb2f089ec6a6bb9cea79eac679e297ca7d416b
refs/heads/master
2021-01-19T09:37:33.337054
2016-03-09T21:35:18
2016-03-09T21:35:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
442
cpp
#include "insdata.h" namespace Data{ INSData::INSData() : Message() { } INSData::INSData(double timestamp, const Pose3D &pose) : Message(),timestamp(timestamp), pose(pose) { } INSData::INSData(const INSData &ins) : Message(), timestamp(ins.timestamp), pose(ins.pose) { } INSData::~INSData(){ } double INSData::getTimestamp() const { return timestamp; } const Pose3D &INSData::getPose() const { return pose; } }
d49f8002e8fd9c060d03b7177200701e25f5dbfd
0d99bcb8b8717008c1ec9b080c6c86c2b1710eee
/날씨/build/Android/Preview2/app/src/main/include/Fuse.Node.ISiblingDataProvider.h
b48b937939176fcb5f423281445e813463aa5257
[]
no_license
shj4849/Fuse
526d92bc49a0a2d8087beece987b1701dc35cccc
447f49f96f9dadf203f5f91e8a1d67f19d8ecc04
refs/heads/master
2021-05-15T23:08:09.523726
2017-12-21T05:28:53
2017-12-21T05:28:53
106,758,124
0
0
null
null
null
null
UTF-8
C++
false
false
646
h
// This file was generated based on C:/Users/t2/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.4.0/Node.DataContext.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{ namespace Fuse{ // public abstract interface Node.ISiblingDataProvider :9 // { uInterfaceType* Node__ISiblingDataProvider_typeof(); struct Node__ISiblingDataProvider { void(*fp_get_Data)(uObject*, uObject**); static uObject* Data(const uInterface& __this) { uObject* __retval; return __this.VTable<Node__ISiblingDataProvider>()->fp_get_Data(__this, &__retval), __retval; } }; // } }} // ::g::Fuse
59b02a0773e20d1ec8dcf4866981f1b45009a31c
ff99c6a7e0375516e435a60903f0a7c7d4c777bb
/Engine 4/GameObject.h
cee95ef2fd8dcd6347fdb411be9505bfdca4d1ae
[]
no_license
gustifur89/Engine-4
fde9c3e3b2a477e905b544351fd50551a3578a3f
945e1e44af72d74d9471bba77eea110cfa46cef6
refs/heads/master
2021-02-06T02:25:40.796525
2020-07-19T20:17:09
2020-07-19T20:17:09
243,864,680
0
0
null
null
null
null
UTF-8
C++
false
false
2,830
h
#pragma once #include "Headers.h" #include "Mesh.h" #include "Transform.h" #include "Shader.h" #include "Camera.h" #include "Texture.h" #include "Collision.h" class GameObject { public: enum TYPE { BASIC, COLOR, TEXTURE }; GameObject(std::shared_ptr<Mesh> mesh, std::shared_ptr<Shader> shader); GameObject() : GameObject(NULL, NULL) { type = TYPE::BASIC; } void addChild(std::shared_ptr<GameObject> gameObject); void render(std::shared_ptr<Camera> camera, glm::mat4 parentTransform); virtual void renderFunc(std::shared_ptr<Camera> camera, glm::mat4 parentTransform); static void cleanUp(std::shared_ptr<GameObject> object, bool removeChildren = false); std::vector<std::shared_ptr<GameObject>> children; //Render stuff int type; bool visible; bool persistentVisible; Transform transform; std::shared_ptr<Mesh> mesh; std::shared_ptr<Shader> shader; bool toRemove; //Physics stuff: std::shared_ptr<Collider> collider; float mass; float invMass; float elasticity; float friction; float staticFriction; float dynamicFriction; float radius; bool collisionReactEnabled; bool gravityAffected; bool physiceEnabled; bool neverDisable; static float stopSpeed; bool noClip; static float coyoteTime; float offgroundTime; bool onGround; //animation stuff std::map<std::string, std::shared_ptr<AnimationData>> animations; int currentFrame; void updateAnimation(double time, std::string state); glm::vec3 velocity; glm::vec3 force; glm::vec3 impulse; bool isColliding; void setMass(float mass); void setElasticity(float elasticity); void applyImpulse(glm::vec3 impulse, glm::vec3 position); void applyForce(glm::vec3 force, glm::vec3 position); }; class GameObjectColor : public GameObject { public: GameObjectColor(std::shared_ptr<ColorMesh> mesh, std::shared_ptr<ColorShader> shader); GameObjectColor() : GameObjectColor(NULL, NULL) { type = TYPE::COLOR; } glm::mat4 colorMatrix; float shininess; std::shared_ptr<ColorShader> shader; void setShininess(float shininess); void setFillColor(int r, int g, int b); void renderFunc(std::shared_ptr<Camera> camera, glm::mat4 parentTransform); }; class GameObjectTexture : public GameObject { public: GameObjectTexture(std::shared_ptr<TextureMesh> mesh, std::shared_ptr<TextureShader> shader); GameObjectTexture() : GameObjectTexture(NULL, NULL) { type = TYPE::TEXTURE; } bool multiMesh; float shininess; glm::mat4 colorMatrix; std::vector<std::shared_ptr<Texture>> multiTextures; std::shared_ptr<Texture> texture; std::shared_ptr<TextureShader> shader; void assignMultiTextures(std::map<std::string, std::shared_ptr<Texture>> textureCollection); void setShininess(float shininess); void setFillColor(int r, int g, int b); void renderFunc(std::shared_ptr<Camera> camera, glm::mat4 parentTransform); };
3560fb818f111d8ac65319ed503d5fed381c52e5
4a9f253d5a56fe86f8056e123c1b554d8a964de0
/WinSysDir.cpp
a8488e7942781bb6f76be3d708a9c03058263a2d
[]
no_license
joshua3403/Window_System_Programming
0ff6a85edfcc1207c66f63c1e7c0b678697e3c65
82df9ec95eadb64d5a27cbd58a0f4902523cf4aa
refs/heads/master
2020-12-28T15:55:10.116080
2020-03-09T05:32:40
2020-03-09T05:32:40
238,395,608
0
0
null
null
null
null
UHC
C++
false
false
536
cpp
/* WinSysDir.cpp 프로그램 설명 : 시스템 디렉터리와 Windows 디렉터리 확인 */ #include <stdio.h> #include <tchar.h> #include <windows.h> #define DIR_LEN MAX_PATH + 1 int _tmain(int agrc, TCHAR* argv[]) { TCHAR sysDir[DIR_LEN]; TCHAR winDir[DIR_LEN]; // 시스템 디렉터리 정보 추출 GetSystemDirectory(sysDir, DIR_LEN); // Windows 디렉터리 정보 추출 GetWindowsDirectory(winDir, DIR_LEN); _tprintf(_T("System Dir : %s\n"), sysDir); _tprintf(_T("Window Dir : %s\n"), winDir); return 0; }
1a38d6a81f722050b0d6e8d229b3b4c3edf0dfd6
d0fbe5fdc9889d05bf06a6e785c2cf0cfbea68c5
/csrc/wrappers.h
753abb26d297a209df732becf0a075b7054cac2c
[]
no_license
vssousa/python-cspade
cb8b9b428568408bfe28317e5106a29923099a63
e3af0ff86934457b0cbbca5d32f973ca86ead7fa
refs/heads/master
2020-04-10T18:01:24.268726
2018-12-02T17:10:07
2018-12-02T17:10:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
385
h
// // Created by Yukio Fukuzawa on 3/12/18. // #ifndef SPADE_UTILITY_WRAPPERS_H #define SPADE_UTILITY_WRAPPERS_H #include <iostream> #include "utils.h" using namespace std; void spadeWrapper(const string& s); void exttposeWrapper(const string& s); void getconfWrapper(const string& s); void makebinWrapper(const string& s); result_t getResult(); #endif //SPADE_UTILITY_WRAPPERS_H
ea97d30df85dd7a7a584bed75f99b5c6d5727db1
ed313bf0460c93ad03ad34e86175250b3c0e6ab4
/library/lca_st_table.cpp
35ae1067795497d1f41521ebf59d2be1fa6da171
[]
no_license
ThereWillBeOneDaypyf/Summer_SolveSet
fd41059c5ddcbd33e2420277119613e991fb6da9
9895a9c035538c95a31f66ad4f85b6268b655331
refs/heads/master
2022-10-20T02:31:07.625252
2020-04-24T11:51:32
2020-04-24T11:51:32
94,217,614
1
1
null
null
null
null
UTF-8
C++
false
false
1,874
cpp
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<vector> using namespace std; //thanks to pyf ... //thanks to qhl ... const int N = 4e4 + 7; long long dis[N]; int dep[N*4]; int dp[N*4][22]; int rec[N*4]; int first[N]; int LOG2[N*4]; int tot = 0; vector<pair<int,int> > G[N]; void init() { for(int i = 0; i< N;i++) G[i].clear(); for(int i = 0;i<4*N;i++) LOG2[i] = (i == 0 ? -1 : LOG2[i>>1] + 1); tot = 0; } void add_edge(int u,int v,int d) { G[u].push_back(make_pair(v,d)); G[v].push_back(make_pair(u,d)); } void dfs(int u,int fa,int d,long long w) { dis[u] = w; first[u] = ++ tot; rec[tot] = u; dep[tot] = d; for(int i = 0;i != G[u].size();i++) { int v = G[u][i].first; int dd = G[u][i].second; if(v == fa) continue; dfs(v,u,d+1,w + dd); rec[++ tot] = u; dep[tot] = d; } } void init_st() { for(int i = 1;i<=tot;i++) dp[i][0] = i; for(int j = 1;(1 << j)<= tot;j++) { for(int i = 1;i + (1 << j) <= tot + 1;i++) { int a = dp[i][j-1],b = dp[i + (1 << j -1)][j-1]; dp[i][j] = dep[a] < dep[b] ? a : b; } } } int rmq(int l,int r) { int k = LOG2[r - l + 1]; int a = dp[l][k], b = dp[r - (1 << k) + 1][k]; return dep[a] < dep[b] ? a : b; } int lca(int u,int v) { int x = first[u], y = first[v]; if(x > y) swap(x,y); int res = rmq(x,y); return rec[res]; } void debug() { for(int i = 1;i<=tot;i++) cout << i << " "; cout << endl; for(int i = 1;i<=tot;i++) cout << rec[i] << " "; cout << endl; } int main() { int T; scanf("%d",&T); while(T--) { int n,m; scanf("%d%d",&n,&m); init(); for(int i = 1;i<n;i++) { int u,v,d; scanf("%d%d%d",&u,&v,&d); add_edge(u,v,d); } dfs(1,1,0,0); init_st(); //debug(); for(int i = 0;i<m;i++) { int u,v; scanf("%d%d",&u,&v); int anc = lca(u,v); printf("%lld\n",dis[u] + dis[v] - 2 * dis[anc]); } } }
96dec31d6bc6c8c8e7b24fb81d3455f82def52a5
e96ee2dfb356902cb618286025aa907b0931f71c
/Matricula.h
a40022c4cc78a9a859eb0dfcfd5b406566e68095
[]
no_license
Rafa0407/proyectoEstructuras
82b572b6d8911954fac660057168be1644b60e8f
ee36ff02aee890fe3a18a6082609681d1c10a741
refs/heads/master
2021-09-03T09:13:58.853606
2018-01-08T00:29:05
2018-01-08T00:29:05
109,077,123
0
0
null
null
null
null
UTF-8
C++
false
false
1,490
h
#pragma once #include <cstring> #include <iomanip> #include <string> #include <iostream> using namespace std; class Matricula { public: int cedula; // #0###0### short int ciclo; // ciclo 1 o 2 char fecha[11]; // dd/mm/aaaa short int codigoCurso; // ### string nombreCurso; short int grupo; short int creditos; short int estado; //0 para activo y 1 para error Matricula(int cedula = 0, short int ciclo = 0, string fecha = " ", short int codigoCurso = 0, string nombreCurso = " ", short int grupo = 0, short int creditos = 0, short int estado = 0) { setCedula(cedula); setCiclo(ciclo); setFecha(fecha); setCodigoCurso(codigoCurso); setNombreCurso(nombreCurso); setGrupo(grupo); setCreditos(creditos); setEstado(estado); } ~Matricula() { } //METODOS SET void setCedula(int cedula) { this->cedula = cedula; } void setCiclo(short int ciclo) { this->ciclo = ciclo; } void setFecha(string fecha) { const char *pNombreCurso = fecha.data(); int tam = fecha.size(); strncpy_s(this->fecha, pNombreCurso, 11); // 8 por el formato de dd/mm/yy //this->nombreCurso[8] = '\0'; } void setCodigoCurso(short int codigoCurso) { this->codigoCurso = codigoCurso; } void setNombreCurso(string nombreCurso) { this->nombreCurso = nombreCurso; } void setGrupo(short int grupo) { this->grupo = grupo; } void setCreditos(short int creditos) { this->creditos = creditos; } void setEstado(short int estado) { this->estado = estado; } };
fea090cba3db9e2a5ff293c9b20ef7ee9fe575cd
a995091ae322b16728a5be9f1c551e413f57cfa9
/logdevice/server/rebuilding/RebuildingReadStorageTaskV2.h
fb760af9ace09c7789ee0c8183e5e15306ff3d3c
[ "BSD-3-Clause" ]
permissive
ethio123/LogDevice
3fb387058eedee05c52fffd9b05384a093b3dd4a
f5083568dd295fb750ed39d2a336a22486bd106c
refs/heads/master
2020-04-08T00:59:19.185546
2018-11-23T14:48:08
2018-11-23T14:49:53
158,876,580
1
0
NOASSERTION
2018-11-23T20:46:37
2018-11-23T20:46:37
null
UTF-8
C++
false
false
10,332
h
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "logdevice/server/locallogstore/LocalLogStore.h" #include "logdevice/server/rebuilding/ChunkRebuilding.h" #include "logdevice/server/rebuilding/RebuildingPlan.h" #include "logdevice/server/storage_tasks/StorageTask.h" namespace facebook { namespace logdevice { /** * @file Task created by LogRebuilding state machines when they need data read * from the local log store. Upon completion, the task (including the * result) gets sent back to the worker thread. */ class RebuildingReadStorageTaskV2 : public StorageTask { public: struct Context { struct LogState { LogState() = default; explicit LogState(RebuildingPlan p) : plan(std::move(p)) {} RebuildingPlan plan; lsn_t lastSeenLSN = LSN_INVALID; // The copyset of the last record we've read. std::vector<ShardID> lastSeenCopyset; // Whenever the copyset of a record doesn't match the copyset of the // previous one, this counter is bumped. It is used to hash the copyset // selector's RNG to preserve sticky copyset blocks after rebuilding. size_t currentBlockID{0}; // A counter we keep to split blocks that get too large. Without this // blocks that get accidentally "fused" together because they happen to // have identical copysets will never get split. In a cluster with a // small number of nodes this could lead to very large block sizes after // rebuilding a significant part of the cluster, which will create an // unbalanced distribution of data. size_t bytesInCurrentBlock{0}; // Cached information about epoch metadata for last seen record, and the // range of epochs it covers (right-open interval), as looked up in // `plan`. If currentEpochRange is valid but currentEpochMetadata is // nullptr, it's a cached negative result: it means this epoch range is // not covered by `plan`. std::pair<epoch_t, epoch_t> currentEpochRange{EPOCH_INVALID, EPOCH_INVALID}; std::shared_ptr<EpochMetaData> currentEpochMetadata; // ReplicationScheme corresponding to currentEpochMetadata. // Initialized lazily, can be nullptr even if currentEpochMetadata is not. std::shared_ptr<ReplicationScheme> currentReplication; // Just for admin command. size_t bytesDelivered = 0; size_t recordsDelivered = 0; size_t chunksDelivered = 0; }; // Immutable parameters. // The onDone callback is called from worker thread. std::function<void(std::vector<std::unique_ptr<ChunkData>>)> onDone; std::shared_ptr<const RebuildingSet> rebuildingSet; UpdateableSettings<RebuildingSettings> rebuildingSettings; ShardID myShardID; // The mutex protects the LogState-s in `logs`, which are only accessed by // the storage task and getDebugInfo(). // // The other mutable fields are accessed by storage task on storage thread // and by ShardRebuilding on worker thread. The ShardRebuilding only // accesses them when there's no storage task in flight or in queue, so // there's no need for a mutex. mutable std::mutex logsMutex; // What to read. std::unordered_map<logid_t, LogState> logs; // A long-living main iterator. If nullptr, the storage task will create it. // After storage task is done, iterator is either invalid or points // at nextLocation. std::unique_ptr<LocalLogStore::AllLogsIterator> iterator; // The first location not processed yet. // Next storage task needs to start reading from here. std::shared_ptr<LocalLogStore::AllLogsIterator::Location> nextLocation; // If we encounter too many invalid records, stall rebuilding just in case. size_t numMalformedRecordsSeen{0}; // true if we're finished reading. bool reachedEnd = false; // true if we're not going to be able to read everything we need. bool persistentError = false; void getLogsDebugInfo(InfoRebuildingLogsTable& table) const; }; class Filter : public LocalLogStoreReadFilter { public: enum class FilteredReason { SCD, NOT_DIRTY, DRAINED, TIMESTAMP, EPOCH_RANGE }; Filter(RebuildingReadStorageTaskV2* task, Context* context); bool operator()(logid_t log, lsn_t lsn, const ShardID* copyset, const copyset_size_t copyset_size, const csi_flags_t csi_flags, RecordTimestamp min_ts, RecordTimestamp max_ts) override; bool shouldProcessTimeRange(RecordTimestamp min, RecordTimestamp max) override; bool shouldProcessRecordRange(logid_t log, lsn_t min_lsn, lsn_t max_lsn, RecordTimestamp min_ts, RecordTimestamp max_ts) override; // Finds the log in `context->logs` and puts it in `currentLogState`. // Has a fast path for consecutive lookups of the same log. // If the log is not in `context->logs`, sets currentLogState = nullptr // and returns false. bool lookUpLogState(logid_t log); // Update stats regarding skipped records. // @param late true if the filter was called on the full record rather // than CSI entry. void noteRecordFiltered(FilteredReason reason, bool late); RebuildingReadStorageTaskV2* task; Context* context; // Just a cache to avoid lookup in context->logs. // If currentLog is valid but currentLogState is nullptr, it means this log // is not in context->logs, i.e. we're not interested in it. logid_t currentLog = LOGID_INVALID; Context::LogState* currentLogState = nullptr; // Cached set of shards that are effectively not in the rebuilding set, // as long as the given time range is concerned. // This struct uses the fact that operator() is usually called many times // in a row with the same min_ts and max_ts. struct { RecordTimestamp minTs = RecordTimestamp::min(); RecordTimestamp maxTs = RecordTimestamp::max(); // ShardID+DataClass pairs whose dirty ranges have no intersection with // time range [minTs, maxTs]. // The dirty ranges are rebuildingSet.shards[s].dc_dirty_ranges[dc]. std::unordered_set<std::pair<ShardID, DataClass>> shardsOutsideTimeRange; bool valid(RecordTimestamp min_ts, RecordTimestamp max_ts) const { return min_ts == minTs && max_ts == maxTs; } void clear() { minTs = RecordTimestamp::min(); maxTs = RecordTimestamp::max(); shardsOutsideTimeRange.clear(); } } timeRangeCache; // How many records we filtered out for various reasons. Used for logging. size_t nRecordsLateFiltered{0}; size_t nRecordsSCDFiltered{0}; size_t nRecordsNotDirtyFiltered{0}; size_t nRecordsDrainedFiltered{0}; size_t nRecordsTimestampFiltered{0}; size_t nRecordsEpochRangeFiltered{0}; }; explicit RebuildingReadStorageTaskV2(std::weak_ptr<Context> context); void execute() override; void onDone() override; void onDropped() override; // There can be at most one task of this type in queue at any given time. // Dropping it won't achieve much in way of clearing the queue. bool isDroppable() const override { return false; } ThreadType getThreadType() const override { // Read tasks may take a while to execute, so they shouldn't block fast // write operations. return ThreadType::SLOW; } Priority getPriority() const override { // Rebuilding reads should be lo-pri compared to regular reads return Priority::LOW; } protected: // Can be overridden in tests. virtual UpdateableSettings<Settings> getSettings(); virtual std::shared_ptr<UpdateableConfig> getConfig(); virtual StatsHolder* getStats(); virtual std::unique_ptr<LocalLogStore::AllLogsIterator> createIterator(const LocalLogStore::ReadOptions& opts, const std::vector<logid_t>& logs); private: std::weak_ptr<Context> context_; std::vector<std::unique_ptr<ChunkData>> result_; // Checks if the copyset has changed compared to the last seen record and // bumps currentBlockID if it has. // @param temp_copyset is just a scratch buffer for use inside the function. // The function will resize it as needed. The caller can reuse the buffer // between calls as an optimization to avoid a memory allocation. // If record is invalid, sets erro to E::MALFORMED_RECORD and returns -1. int checkRecordForBlockChange(logid_t log, lsn_t lsn, Slice record, Context* context, Context::LogState* log_state, std::vector<ShardID>* temp_copyset, RecordTimestamp* out_timestamp); // Makes sure that log_state->currentEpochMetadata covers `lsn`. // Returns false if `lsn` is not covered by RebuildingPlan and should be // skipped. // If `create_replication_scheme` is true, also creates // log_state->currentReplication if it's null. bool lookUpEpochMetadata(logid_t log, lsn_t lsn, Context* context, Context::LogState* log_state, bool create_replication_scheme); /** * Mark all nodes in the rebuilding set as not available to receive copies. * * While a storage node is rebuilding, it replies to STORE messages with * STORED(status=E::DISABLED). We mark these recipients as unavailable so that * RecordRebuildingStore does not try to store copies on them. */ void markNodesInRebuildingSetNotAvailable(NodeSetState* nodeset_state, Context* context); void getDebugInfoDetailed(StorageTaskDebugInfo&) const override; }; }} // namespace facebook::logdevice
b9bb7fd5c78c22a20bf28530bd6ccd052280e124
4861ba3eb53d4ddc3a2a409eeea35aa466495952
/Good Feature Experiments/gcMatches2Points.cpp
375c98d9c2b2a77b188d8465940685d38e591f13
[ "MIT" ]
permissive
msl-kist/Good-Feature-Experiments
0c86649accc908239b729bfbf32c8de4c0c8de63
3deabb38ccdf9413bba72f0ffaaf4eb03d458028
refs/heads/master
2021-01-25T08:28:39.709621
2014-06-10T08:26:59
2014-06-10T08:26:59
19,815,286
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include "parameters.h" void gcMatches2Points(vector<DMatch> matches, vector<Point2f>& _keypointsA_filtered, vector<Point2f>& _keypointsB_filtered, vector<KeyPoint> _keypointsA, vector<KeyPoint> _keypointsB) { for( int i = 0; i < matches.size(); i++ ) { //-- Get the keypoints from the best matches _keypointsA_filtered.push_back( _keypointsA[ matches[i].queryIdx ].pt ); _keypointsB_filtered.push_back( _keypointsB[ matches[i].trainIdx ].pt ); } }
b73b5e1419309a2e8c4e850943dc7e5b97fcebc3
58210a4f2745b96340190f1d6d295d44f93dbe6a
/flash-graph/tools/rmat-gen.cpp
fc8a5336b7c9f0040b5cd7bc6f8f1bb2b902b179
[ "Apache-2.0" ]
permissive
Smerity/FlashGraph
3a6be2af79d4e62b7f2471a75aa3f1715a3e7e6f
9c3509ad8e97236eab273b4db27f03c55a7887d8
refs/heads/graph-release
2023-06-25T14:28:13.374922
2014-12-06T00:54:57
2014-12-06T00:54:57
30,141,913
10
4
null
2015-02-01T09:32:29
2015-02-01T09:32:29
null
UTF-8
C++
false
false
1,686
cpp
#include <boost/graph/adjacency_list.hpp> #include <boost/graph/rmat_graph_generator.hpp> #include <boost/random/linear_congruential.hpp> #include <boost/graph/graph_traits.hpp> #include <iostream> #include <ctime> #include <stdio.h> using namespace boost; typedef adjacency_list<> Graph; typedef rmat_iterator<minstd_rand, Graph> RMATGen; typedef graph_traits<Graph>::vertex_iterator vertex_iter; typedef property_map<Graph, vertex_index_t>::type IndexMap; int main(int argc, char* argv[]) { if (argc < 3) { fprintf(stderr, "usage: make_graph #vertices, #numedges\n"); return EXIT_FAILURE; } std::size_t n = atol(argv[1]); std::size_t m = atol(argv[2]); fprintf(stderr, "Vertices = %ld\n", n); fprintf(stderr, "Edges = %ld\n", m); std::clock_t start; start = std::clock(); minstd_rand gen; RMATGen gen_it(gen, n, m, 0.57, 0.19, 0.19, 0.05, true); RMATGen gen_end; for (; gen_it != gen_end; ++gen_it) { std::cout << gen_it->first << " " << gen_it->second << std::endl; } #if 0 // Create graph with 100 nodes and 400 edges Graph g(RMATGen(gen, n, m, 0.57, 0.19, 0.19, 0.05, true), RMATGen(), n); IndexMap index = get(vertex_index, g); // Get vertex set #if 0 std::pair<vertex_iter, vertex_iter> vp; for (vp = vertices(g); vp.first != vp.second; ++vp.first) std::cout << index[*vp.first] << " "; std::cout << std::endl; #endif // Get edge set graph_traits<Graph>::edge_iterator ei, ei_end; for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) std::cout << index[source(*ei, g)]<< " " << index[target(*ei, g)] << "\n"; #endif std::cerr << "The time to build the graph = " << (std::clock()-start)/(double)CLOCKS_PER_SEC << std::endl; return 0; }
39f45923f883c09a1aaf40c8d0cfd8132d072b1c
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_7630.cpp
5333e2600fea41636a277e6e90f63a68ac990358
[]
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
554
cpp
{ struct _ip_pending *pending = xcalloc(1, sizeof(struct _ip_pending)); struct _ip_pending **I = NULL; pending->fd = fd; pending->handler = handler; pending->handlerData = handlerData; for (I = &(i->pending_head); *I; I = &((*I)->next)); *I = pending; } int ipcache_nbgethostbyname(name, fd, handler, handlerData) char *name; int fd; IPH handler; void *handlerData; { ipcache_entry *i = NULL; dnsserver_t *dnsData = NULL; if (!handler) fatal_dump("ipcache_nbgethostbyname: NULL handler");
2b3837eb5de0fda53f5ae9d631247115ea38c9f7
2a36fd92dc6803adf43872658f3f62d4f74c094a
/internal/I2C.h
ee2cb1ce267f6eec7343a8f189ae6823a05d730d
[ "MIT" ]
permissive
milligan22963/seps525
de0ed8c5d4bfba7c37ea90c0f7c7ec233bc521a8
8b277e15db08d38b5b2dbf31f5832a434df179ba
refs/heads/master
2022-07-15T06:02:04.368622
2020-05-16T00:47:46
2020-05-16T00:47:46
264,057,032
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
h
/** * I2C.h * * I2C implementation defining a port that can read/write * * Copyright 2020 AFM Software */ #ifndef _H_I2C #define _H_I2C #include "Constants.h" #include "Port.h" namespace afm { namespace communication { class I2C : public Port { public: I2C(); virtual bool read(uint8_t &value) override; virtual bool write(uint8_t value) override; virtual uint16_t read(data::Buffer &buffer) override; virtual uint16_t write(const data::Buffer &buffer) override; virtual uint16_t transfer(const data::Buffer &output_buffer, data::Buffer &input_buffer) override; protected: virtual bool setup_device() override; virtual void shutdown_device() override; private: bool select_address(); private: int m_device_handle = constants::sc_invalid_file_handle; }; } } #endif
f41c6c6b775da5c6234aa77fa89068843e0ed6a1
c9c2e4acae7ecb32774f4d8d44698082787d6ad7
/mounter/App/mounter.cpp
2f7679df2c12287c176d88c190ec9631b93da1c9
[]
no_license
holem2k/ext2mount
ce382340e25dd9b0cf82da7ce12cf9796f4b3b5d
93d56884bd9453c9cb1bcdea8e65bf944f4f1d34
refs/heads/master
2020-04-14T23:58:45.705229
2019-01-05T20:50:51
2019-01-05T20:50:51
164,223,863
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
// mounter.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #include "MountGUI.h" #include "MountMan.h" #include "herlpers.h" int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { CRunOnce once(_T("Mounter.Runonce.Mutex")); if (once.IsRunning()) once.Show(NULL); else { CMountMan manager; CMountGUI gui(&manager); gui.Run(); } return 0; }
6c53d650d38f64ca42cdbdf5e870f3ec60d6b771
f27f63ab395bbbdbc2a0b2c66ab38b12701d54f5
/QQTang/Map.h
8994c52bf3761755fae9f8d9b4708e434e24aa9b
[]
no_license
daiker0330/QQTang
dfe50b8ea660cec38531760e6cbcf915b66df0c5
9129d90cbf0f462f728ef5d1f2867a75a114b72b
refs/heads/master
2021-01-17T05:20:49.690640
2015-03-20T06:22:33
2015-03-20T06:22:44
32,069,107
2
0
null
null
null
null
UTF-8
C++
false
false
1,338
h
#define MAP_L_MAX 100 #define MAP_H_MAX 100 #define MAP_NO_OBJECT -1 #define MAP_GRID_PIXEL 30 class Map{ private: int Background_Index[MAP_H_MAX][MAP_L_MAX]; int Destroyable_Object_Index[MAP_H_MAX][MAP_L_MAX]; int Undestroyable_Object_Index[MAP_H_MAX][MAP_L_MAX]; int Tool_Object_Index[MAP_H_MAX][MAP_L_MAX]; int Bomb_Object_Index[MAP_H_MAX][MAP_L_MAX]; int Actor_Object_Index[MAP_H_MAX][MAP_L_MAX]; public: Map(){ for (int i = 0; i < MAP_H_MAX; i++){ for (int j = 0; j < MAP_L_MAX; j++){ Background_Index[i][j] = MAP_NO_OBJECT; Destroyable_Object_Index[i][j] = MAP_NO_OBJECT; Undestroyable_Object_Index[i][j] = MAP_NO_OBJECT; } } } int Get_Background_Index(int _h,int _l); void Set_Background_Index(int _index, int _h, int _l); int Get_Destroyable_Object_Index(int _h, int _l); void Set_Destroyable_Object_Index(int _index, int _h, int _l); int Get_Undestroyable_Object_Index(int _h, int _l); void Set_Undestroyable_Object_Index(int _index, int _h, int _l); int Get_Tools_Object_Index(int _h, int _l); void Set_Tools_Object_Index(int _index, int _h, int _l); int Get_Bomb_Object_Index(int _h, int _l); void Set_Bomb_Object_Index(int _index, int _h, int _l); int Get_Actor_Object_Index(int _h, int _l); void Set_Actor_Object_Index(int _index, int _h, int _l); bool Is_Block(int _h, int _l); };
954fe81b2870adfce055e8469a8881b7f6d9e8d0
e50b5f066628ef65fd7f79078b4b1088f9d11e87
/llvm/tools/clang/test/CXX/expr/expr.unary/expr.unary.op/p4.cpp
192fb48573cf17e1644fc811577db2aa71e3dee3
[ "NCSA" ]
permissive
uzleo/coast
1471e03b2a1ffc9883392bf80711e6159917dca1
04bd688ac9a18d2327c59ea0c90f72e9b49df0f4
refs/heads/master
2020-05-16T11:46:24.870750
2019-04-23T13:57:53
2019-04-23T13:57:53
183,025,687
0
0
null
2019-04-23T13:52:28
2019-04-23T13:52:27
null
UTF-8
C++
false
false
1,089
cpp
// RUN: %clang_cc1 -fsyntax-only -verify %s // rdar://problem/8347416 namespace test0 { struct A { void foo(void (A::*)(int)); // expected-note {{passing argument to parameter here}} template<typename T> void g(T); void test() { foo(&g<int>); // expected-error-re {{cannot form member pointer of type 'void (test0::A::*)(int){{( __attribute__\(\(thiscall\)\))?}}' without '&' and class name}} } }; } // This should succeed. namespace test1 { struct A { static void f(void (A::*)()); static void f(void (*)(int)); void g(); static void g(int); void test() { f(&g); } }; } // Also rdar://problem/8347416 namespace test2 { struct A { static int foo(short); static int foo(float); int foo(int); int foo(double); void test(); }; void A::test() { // FIXME: The error message in this case is less than clear, we can do // better. int (A::*ptr)(int) = &(A::foo); // expected-error {{cannot create a non-constant pointer to member function}} } }
3d207ecaaf79386d489a0950fa8ce9cf80b5e4ff
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1480487_1/C++/JohnSmith/a.cpp
d2ec0bb1808e6f41a85695583bdfc72c052f90fc
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
3,099
cpp
// // Google codejam - 2012 - Round 1b - question A - John.Smith // #include <cstdio> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <iostream> #include <iomanip> #include <map> #include <set> #include <algorithm> #include <queue> #include <sstream> #include <gmpxx.h> using namespace std; typedef long long big_int; typedef pair<int,int> pii; #define SZ(x) (int)(x.size()) const int inf = 1000000009; const double pi = atan(1.0)*4.0; const double eps = 1e-8; big_int gcd(big_int x, big_int y) { return y ? gcd(y, x%y) : x; } int bc(int n) { return n ? bc((n-1)&n)+1 : 0; } mpz_class total = 0; double boundary( unsigned int sum, vector<unsigned int> v, double x ) { unsigned int v_sum; double y; double y_prev = -1.0; //cout << "boundary: v.size() = "<< v.size() << endl; for (auto r=1u; r<=v.size(); r++) { v_sum = 0; for (auto j=0u; j<r; j++) { v_sum += v.at(j); } y = (v_sum+sum*x)/r; //cout << "y = " << y << " v_sum = " << v_sum << endl; if ((y-v.at(r-1)) < 0) { return y_prev; } y_prev= y; } return y_prev; } double solve( unsigned int sum, unsigned int x, vector<unsigned int> v ) { //cout << sum << " : "; //cout << x << " : "; if (0) { for (auto y : v ) { cout << y << " "; } cout << endl; } double p_lo = 0.0; double p_hi = 1.0; //double s_lo = x + p_lo * sum ; //double s_hi = x + p_hi * sum ; //double b_lo = boundary( sum, v, 1-p_lo ); //double b_hi = boundary( sum, v, 1-p_hi ); double p; for (auto k=0u; k<50;k++) { p = (p_lo+p_hi)/2; double s = x+p*sum; double b = boundary( sum, v, 1-p); if (0) { cout << setw(10) << p_lo << " "; cout << setw(10) << p_hi << " "; cout << setw(10) << p << " "; cout << setw(10) << s << " "; cout << setw(10) << b << endl; } if (s<b) { p_lo = p; } else { p_hi = p; } } return p; } vector<double> solve( vector<unsigned int> v ) { vector<double> r; unsigned int sum=0; for (auto s : v) { sum += s; } for (auto i=0u; i<v.size(); i++) { vector<unsigned int> vv; for (auto j=0u; j<v.size(); j++) { if (j != i) { vv.push_back(v.at(j)); } } sort(begin(vv), end(vv)); r.push_back( solve( sum, v.at(i), vv )); } return r; } int main( int argc, char ** argv ) { unsigned int t; unsigned int i; unsigned int k; string w; char s[200]; cin >> t; cin.getline( s, 200 ); for (i=1; i<=t; i++) { cin >> k; vector<unsigned int> v; for (auto j=0u; j<k; j++) { unsigned int s; cin >> s; v.push_back(s); } vector<double> r = solve(v); cout << "Case #" << i << ": "; cout << setprecision(10); for (auto x : r) cout << x*100 << " "; cout << endl; } cout << setw(4) ; return 0; }
8b67a004b24964a7dfac34748c277b43c3a74ffe
de6e84cb5ad92498d556ac5f8e7f5a59ded51bf4
/rip_defs.h
5f70690d8fbbc401d9097f85a72fdaefcb4016e1
[]
no_license
xcurda02/ISA-rip_sniffer
437d1ca5a1c52f29febd7fb22cd874caef552cc0
72d7728f69cf774adb0f524b51a7f44b1c1e0d00
refs/heads/main
2023-02-03T06:14:39.795386
2020-12-20T21:16:55
2020-12-20T21:16:55
323,165,671
0
0
null
null
null
null
UTF-8
C++
false
false
1,959
h
/** * soubor: rip_defs.h * autor: Vojtech Curda, 3BIT * */ #ifndef PROJ_RIP_DEFS_H #define PROJ_RIP_DEFS_H #include <cstdint> #include <zconf.h> #include <netinet/in.h> /* Headers */ #define IPV6_HEADER_LENGTH 40 #define ETH_HEADER_LENGTH 14 #define UDP_HEADER_LENGTH 8 #define RIP_HEADER_LENGTH 4 /* Entry length */ #define RIP_ENTRY_LENGTH 20 /* RIP command */ #define RIP_REQUEST 1 #define RIP_RESPONSE 2 /* RIP ports */ #define RIP_PORT 520 #define RIPNG_PORT 521 /* Multicast IPv6 address */ #define RIPNG_MULTICAST_ADDRESS "FF02::9" /* Entry types */ typedef enum{ IP_ENTRY, NEXT_HOP_ENTRY, ROUTE_TABLE_ENTRY, SIMPLE_AUTH_ENTRY, MD5_AUTH_ENTRY, AUTH_DATA_TRAILER} entry_type; /* * RIP header structure */ typedef struct rip_header { u_int8_t command; u_int8_t version; u_int16_t must_be_zero; } rip_header; /* * RIP entry structure * universal for all RIPv1/2 entries */ typedef struct rip_entry{ uint16_t afi; // Address Family uint16_t route_tag; // Route Tag union{ struct{ // Classic RIPv1/2 entry struct in_addr ip; struct in_addr mask; struct in_addr next_hop; uint32_t metric; }simple_entry; struct { // Simple password authentification entry u_int8_t password[16]; }auth_pass; struct{ // MD5 authentification entry u_int16_t digest_offset; u_int8_t key_id; u_int8_t auth_data_len; u_int32_t seq_num; }md5_auth; struct { // MD5 data trailer entry u_int8_t data[16]; }md5_data_trailer; } data; } rip_entry; /* RIPng entry */ typedef struct ripng_entry{ struct in6_addr ip_prefix; uint16_t route_tag; u_int8_t prefix_length; u_int8_t metric; } ripng_entry; #endif //PROJ_RIP_DEFS_H
f330705cceac8418640ebbe50ec311a8aa04a605
3ee0b4f9a84c7e04b5ce1720a353e9430347008a
/Source/SceneSmall.h
635ccab7e7f911a8b3d1b21936235d8c8ac0d995
[]
no_license
MonkeyD-IchiJou/LunaProject
66b81fd658d6fee779f6ef3d634391b23a337600
0f3df447e5ff2b66c50eaefd45a23fd6d10a7d02
refs/heads/master
2021-01-11T06:19:25.777485
2016-12-07T18:00:39
2016-12-07T18:00:39
68,982,855
5
0
null
null
null
null
UTF-8
C++
false
false
527
h
#ifndef SCENE_SMALL_H #define SCENE_SMALL_H #include "SceneVolume.h" #include <array> namespace luna { class SceneSmall : public SceneVolume { protected: SceneSmall(); virtual ~SceneSmall(); /* The max entity allowed in a small scene */ const static int MAX_ENTITIES = 25; /* find the entity which is not awakened */ Entity* GetAvailableEntity_() override; private: /* all entities are here, every scenes have its own total num of entity */ std::array<Entity, MAX_ENTITIES> m_entities{}; }; } #endif
6aadff12eab646de26fd637587505b89fe4cf923
489dbe342c7ef3e8bf031005d1c1dcaffed82300
/src/bench/base58.cpp
e2dd287e576461785481195726e4524ea90e245f
[ "MIT" ]
permissive
knotcoin/knotcoin
d5355f92bedbd0e70800a0bc0300669b299b9236
3f4ade4e2cabf94acd80bc043deec3d9a4209938
refs/heads/master
2021-01-25T13:57:29.669239
2018-03-02T20:52:29
2018-03-02T20:52:29
123,625,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,551
cpp
// Copyright (c) 2016-2017 The Knotcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <validation.h> #include <base58.h> #include <array> #include <vector> #include <string> static void Base58Encode(benchmark::State& state) { static const std::array<unsigned char, 32> buff = { { 17, 79, 8, 99, 150, 189, 208, 162, 22, 23, 203, 163, 36, 58, 147, 227, 139, 2, 215, 100, 91, 38, 11, 141, 253, 40, 117, 21, 16, 90, 200, 24 } }; while (state.KeepRunning()) { EncodeBase58(buff.data(), buff.data() + buff.size()); } } static void Base58CheckEncode(benchmark::State& state) { static const std::array<unsigned char, 32> buff = { { 17, 79, 8, 99, 150, 189, 208, 162, 22, 23, 203, 163, 36, 58, 147, 227, 139, 2, 215, 100, 91, 38, 11, 141, 253, 40, 117, 21, 16, 90, 200, 24 } }; std::vector<unsigned char> vch; vch.assign(buff.begin(), buff.end()); while (state.KeepRunning()) { EncodeBase58Check(vch); } } static void Base58Decode(benchmark::State& state) { const char* addr = "17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem"; std::vector<unsigned char> vch; while (state.KeepRunning()) { DecodeBase58(addr, vch); } } BENCHMARK(Base58Encode, 470 * 1000); BENCHMARK(Base58CheckEncode, 320 * 1000); BENCHMARK(Base58Decode, 800 * 1000);
fdc5e4d11be912b970383ff2ac85a7c969452461
2b75d98fdf245f760d16e344da421c89831305b6
/lib/lf/geometry/tria_o2.cc
bb34ac85722a64e790920acbef85f8abebfb94e5
[ "MIT" ]
permissive
baigm11/lehrfempp
de1411570cf1f4fc867d8dcad68e98fe6e7b66dd
bdd55f52732ca8c761117d4c5e13f33e2f7f7a8c
refs/heads/master
2020-04-23T12:28:08.783070
2019-02-13T19:04:03
2019-02-13T19:04:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,587
cc
/** * @file * @brief Implementation of second-order parametric triangles * @author Anian Ruoss * @date 2018-12-05 22:37:17 * @copyright MIT License */ #include "tria_o2.h" #include "point.h" namespace lf::geometry { TriaO2::TriaO2(Eigen::Matrix<double, Eigen::Dynamic, 6> coords) : coords_(std::move(coords)), alpha_(coords_.rows()), beta_(coords_.rows(), 2), gamma_(coords_.rows(), 2), delta_(coords_.rows()), gamma_x_2_(coords_.rows(), 2) { /* * 2 C * | \ | \ * 5 4 -> F E * | \ | \ * 0 - 3 - 1 A - D - B */ const Eigen::VectorXd& A = coords_.col(0); const Eigen::VectorXd& B = coords_.col(1); const Eigen::VectorXd& C = coords_.col(2); const Eigen::VectorXd& D = coords_.col(3); const Eigen::VectorXd& E = coords_.col(4); const Eigen::VectorXd& F = coords_.col(5); alpha_ << A; beta_ << 4. * D - 3. * A - B, 4. * F - 3. * A - C; gamma_ << 2. * (A + B) - 4. * D, 2. * (A + C) - 4. * F; delta_ << 4. * (A + E - D - F); // coefficient for Jacobian() gamma_x_2_ << 2. * gamma_; } Eigen::MatrixXd TriaO2::Global(const Eigen::MatrixXd& local) const { LF_VERIFY_MSG((0. <= local.array()).all() && (local.array() <= 1.).all(), "local coordinates out of bounds for reference element"); return ((beta_ * local) + (gamma_ * local.array().square().matrix()) + (delta_ * local.row(0).cwiseProduct(local.row(1)))) .colwise() + alpha_; } Eigen::MatrixXd TriaO2::Jacobian(const Eigen::MatrixXd& local) const { LF_VERIFY_MSG((0. <= local.array()).all() && (local.array() <= 1.).all(), "local coordinates out of bounds for reference element"); Eigen::MatrixXd tmp(gamma_.rows(), 2 * local.cols()); for (int i = 0; i < local.cols(); ++i) { tmp.block(0, 2 * i, tmp.rows(), 2) = gamma_x_2_.array().rowwise() * local.col(i).transpose().array(); } Eigen::MatrixXd local_reversed = local.colwise().reverse(); local_reversed.resize(1, local.size()); return beta_.replicate(1, local.cols()) + tmp + (local_reversed.replicate(delta_.rows(), 1).array().colwise() * delta_.array()) .matrix(); } Eigen::MatrixXd TriaO2::JacobianInverseGramian( const Eigen::MatrixXd& local) const { LF_VERIFY_MSG((0. <= local.array()).all() && (local.array() <= 1.).all(), "local coordinates out of bounds for reference element"); Eigen::MatrixXd jac = Jacobian(local); Eigen::MatrixXd jacInvGram(jac.rows(), jac.cols()); if (DimGlobal() == 2) { for (int i = 0; i < local.cols(); ++i) { auto jacobian = jac.block(0, 2 * i, 2, 2); jacInvGram.block(0, 2 * i, 2, 2) << jacobian(1, 1), -jacobian(1, 0), -jacobian(0, 1), jacobian(0, 0); jacInvGram.block(0, 2 * i, 2, 2) /= jacobian.determinant(); } } else { for (int i = 0; i < local.cols(); ++i) { auto jacobian = jac.block(0, 2 * i, jac.rows(), 2); auto A = jacobian.col(0); auto B = jacobian.col(1); auto AB = A.dot(B); Eigen::MatrixXd tmp(2, 2); tmp << B.dot(B), -AB, -AB, A.dot(A); jacInvGram.block(0, 2 * i, jac.rows(), 2) = jacobian * tmp / tmp.determinant(); } } return jacInvGram; } Eigen::VectorXd TriaO2::IntegrationElement(const Eigen::MatrixXd& local) const { LF_VERIFY_MSG((0. <= local.array()).all() && (local.array() <= 1.).all(), "local coordinates out of bounds for reference element"); Eigen::MatrixXd jac = Jacobian(local); Eigen::VectorXd intElem(local.cols()); if (DimGlobal() == 2) { for (int i = 0; i < local.cols(); ++i) { intElem(i) = std::abs(jac.block(0, 2 * i, 2, 2).determinant()); } } else { for (int i = 0; i < local.cols(); ++i) { auto jacobian = jac.block(0, 2 * i, jac.rows(), 2); auto A = jacobian.col(0); auto B = jacobian.col(1); auto AB = A.dot(B); intElem(i) = std::sqrt(std::abs(A.dot(A) * B.dot(B) - AB * AB)); } } return intElem; } std::unique_ptr<Geometry> TriaO2::SubGeometry(dim_t codim, dim_t i) const { switch (codim) { case 0: { LF_ASSERT_MSG(i == 0, "i is out of bounds"); return std::make_unique<TriaO2>(coords_); } case 1: { LF_ASSERT_MSG(0 <= i && i <= 2, "i is out of bounds"); return std::make_unique<SegmentO2>( (Eigen::Matrix<double, Eigen::Dynamic, 3>(DimGlobal(), 3) << coords_.col(i), coords_.col((i + 1) % 3), coords_.col(i + 3)) .finished()); } case 2: { LF_ASSERT_MSG(0 <= i && i <= 5, "i is out of bounds"); return std::make_unique<Point>(coords_.col(i)); } default: { LF_VERIFY_MSG(false, "codim is out of bounds") } } } std::vector<std::unique_ptr<Geometry>> TriaO2::ChildGeometry( const RefinementPattern& ref_pat, lf::base::dim_t codim) const { LF_VERIFY_MSG(ref_pat.RefEl() == lf::base::RefEl::kTria(), "Refinement pattern for " << ref_pat.RefEl().ToString()); LF_VERIFY_MSG(codim < 3, "Illegal codim " << codim); const double hLattice = 1. / static_cast<double>(ref_pat.LatticeConst()); std::vector<std::unique_ptr<Geometry>> childGeoPtrs = {}; // get coordinates of childGeometries std::vector<Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>> childPolygons( ref_pat.ChildPolygons(codim)); const int noChildren = childPolygons.size(); LF_VERIFY_MSG( noChildren == ref_pat.noChildren(codim), "noChildren " << noChildren << " <-> " << ref_pat.noChildren(codim)); // create a geometry object for each child for (size_t child = 0; child < noChildren; ++child) { // codim == 0: a child triangle is described by a lattice polygon with six // vertices // codim == 1: a child segment is described by a polygon with three vertices // codim == 2: a child point by a single point ("polygon with one corner") LF_VERIFY_MSG( childPolygons[child].rows() == 2, "childPolygons[child].rows() = " << childPolygons[child].rows()); LF_VERIFY_MSG( childPolygons[child].cols() == (3 - codim), "childPolygons[child].cols() = " << childPolygons[child].cols()); const Eigen::MatrixXd locChildPolygonCoords( hLattice * childPolygons[child].cast<double>()); switch (codim) { case 0: { Eigen::MatrixXd locChildCoords(locChildPolygonCoords.rows(), 6); locChildCoords << locChildPolygonCoords, (locChildPolygonCoords.col(0) + locChildPolygonCoords.col(1)) / 2., (locChildPolygonCoords.col(1) + locChildPolygonCoords.col(2)) / 2., (locChildPolygonCoords.col(2) + locChildPolygonCoords.col(0)) / 2.; childGeoPtrs.push_back( std::make_unique<TriaO2>(Global(locChildCoords))); break; } case 1: { Eigen::MatrixXd locChildCoords(locChildPolygonCoords.rows(), 3); locChildCoords << locChildPolygonCoords, (locChildPolygonCoords.col(0) + locChildPolygonCoords.col(1)) / 2.; childGeoPtrs.push_back( std::make_unique<SegmentO2>(Global(locChildCoords))); break; } case 2: { childGeoPtrs.push_back( std::make_unique<Point>(Global(locChildPolygonCoords))); break; } default: { LF_VERIFY_MSG(false, "Illegal co-dimension"); } } } return childGeoPtrs; } } // namespace lf::geometry
f011c2f7f7896a566c30d9e2da7edd5f1890d6ca
05bafec1c5bb9ab3fc435b6148386304575d6b44
/nuto/mechanics/interpolation/InterpolationTetrahedronQuadratic.cpp
a7d2a98584d71edc1a01308d0ae925bbedcaaf28
[ "BSL-1.0" ]
permissive
nutofem/nuto
7b816b645b0a855bc393065798d999c5d14a59b2
c416c4f1ac954e783a9f7e5bf0bb97758c75b6ee
refs/heads/develop
2020-04-12T03:56:09.670125
2018-09-19T05:52:34
2018-09-19T05:52:34
63,241,285
20
7
BSL-1.0
2018-09-19T05:52:35
2016-07-13T11:42:57
C++
UTF-8
C++
false
false
4,517
cpp
#include "nuto/base/Exception.h" #include "InterpolationTetrahedronQuadratic.h" using namespace NuTo; std::unique_ptr<InterpolationSimple> InterpolationTetrahedronQuadratic::Clone() const { return std::make_unique<InterpolationTetrahedronQuadratic>(*this); } Eigen::VectorXd InterpolationTetrahedronQuadratic::GetShapeFunctions(const NaturalCoords& naturalIpCoords) const { return ShapeFunctions(naturalIpCoords); } Eigen::MatrixXd InterpolationTetrahedronQuadratic::GetDerivativeShapeFunctions(const NaturalCoords& coords) const { return DerivativeShapeFunctions(coords); } NaturalCoords InterpolationTetrahedronQuadratic::GetLocalCoords(int nodeId) const { return LocalCoords(nodeId); } int InterpolationTetrahedronQuadratic::GetNumNodes() const { return 10; } const Shape& InterpolationTetrahedronQuadratic::GetShape() const { return mShape; } Eigen::Matrix<double, 3, 1> InterpolationTetrahedronQuadratic::LocalCoords(int rNodeIndex) { switch (rNodeIndex) { case 0: return Eigen::Vector3d(0.0, 0.0, 0.0); case 1: return Eigen::Vector3d(1.0, 0.0, 0.0); case 2: return Eigen::Vector3d(0.0, 1.0, 0.0); case 3: return Eigen::Vector3d(0.0, 0.0, 1.0); case 4: return Eigen::Vector3d(0.5, 0.0, 0.0); case 5: return Eigen::Vector3d(0.5, 0.5, 0.0); case 6: return Eigen::Vector3d(0.0, 0.5, 0.0); case 7: return Eigen::Vector3d(0.0, 0.0, 0.5); case 8: return Eigen::Vector3d(0.0, 0.5, 0.5); case 9: return Eigen::Vector3d(0.5, 0.0, 0.5); default: throw NuTo::Exception(__PRETTY_FUNCTION__, "node index out of range (0..9)"); } } Eigen::Matrix<double, 10, 1> InterpolationTetrahedronQuadratic::ShapeFunctions(const Eigen::VectorXd& rCoordinates) { Eigen::Matrix<double, 10, 1> shapeFunctions; double r = rCoordinates[0]; double s = rCoordinates[1]; double t = rCoordinates[2]; // node 0 (0,0,0) shapeFunctions[0] = 1. - 3. * (r + s + t) + 2. * (r * r + s * s + t * t) + 4. * (r * s + r * t + s * t); // node 1 (1,0,0) shapeFunctions[1] = -r + 2. * r * r; // node 2 (0,1,0) shapeFunctions[2] = -s + 2. * s * s; // node 3 (0,0,1) shapeFunctions[3] = -t + 2. * t * t; // node 4 (0.5,0,0) shapeFunctions[4] = 4. * r * (1. - r - s - t); // node 5 (0.5,0.5,0) shapeFunctions[5] = 4. * r * s; // node 6 (0,0.5,0) shapeFunctions[6] = 4. * s * (1. - r - s - t); // node 7 (0,0,0.5) shapeFunctions[7] = 4. * t * (1. - r - s - t); // node 8 (0,0.5,0.5) shapeFunctions[8] = 4. * s * t; // node 9 (0.5,0,0.5) shapeFunctions[9] = 4. * r * t; return shapeFunctions; } Eigen::Matrix<double, 10, 3> InterpolationTetrahedronQuadratic::DerivativeShapeFunctions(const Eigen::VectorXd& rCoordinates) { Eigen::Matrix<double, 10, 3> derivativeShapeFunctions; double r = rCoordinates[0]; double s = rCoordinates[1]; double t = rCoordinates[2]; derivativeShapeFunctions(0, 0) = -3. + 4. * (r + s + t); derivativeShapeFunctions(0, 1) = -3. + 4. * (r + s + t); derivativeShapeFunctions(0, 2) = -3. + 4. * (r + s + t); derivativeShapeFunctions(1, 0) = -1. + 4. * r; derivativeShapeFunctions(1, 1) = 0; derivativeShapeFunctions(1, 2) = 0; derivativeShapeFunctions(2, 0) = 0; derivativeShapeFunctions(2, 1) = -1. + 4. * s; derivativeShapeFunctions(2, 2) = 0; derivativeShapeFunctions(3, 0) = 0; derivativeShapeFunctions(3, 1) = 0; derivativeShapeFunctions(3, 2) = -1. + 4. * t; derivativeShapeFunctions(4, 0) = 4. - 8. * r - 4. * s - 4. * t; derivativeShapeFunctions(4, 1) = -4. * r; derivativeShapeFunctions(4, 2) = -4. * r; derivativeShapeFunctions(5, 0) = 4. * s; derivativeShapeFunctions(5, 1) = 4. * r; derivativeShapeFunctions(5, 2) = 0.; derivativeShapeFunctions(6, 0) = -4. * s; derivativeShapeFunctions(6, 1) = 4. - 8. * s - 4. * r - 4. * t; derivativeShapeFunctions(6, 2) = -4. * s; derivativeShapeFunctions(7, 0) = -4. * t; derivativeShapeFunctions(7, 1) = -4. * t; derivativeShapeFunctions(7, 2) = 4. - 8. * t - 4. * r - 4. * s; derivativeShapeFunctions(8, 0) = 0.; derivativeShapeFunctions(8, 1) = 4. * t; derivativeShapeFunctions(8, 2) = 4. * s; derivativeShapeFunctions(9, 0) = 4. * t; derivativeShapeFunctions(9, 1) = 0; derivativeShapeFunctions(9, 2) = 4. * r; return derivativeShapeFunctions; }
659cb3c8c65d25ebe03ed7137b1ad3923def8016
54ee740d18f2f6167d38a68594796d0ee4bc4754
/include/vulkan_renderer/internal/utility/vk_mem_alloc.h
b9baf3793e56828388d376f49c2544564d15551c
[]
no_license
161563/Vulkan-graphics-engine
7e1f3c3d5ba6f06c9b732c250423014576927ccc
680e2d3655010d6d40f86bff8eeba2198c1a3dc8
refs/heads/master
2020-04-15T02:17:45.287402
2019-01-08T20:15:15
2019-01-08T20:15:15
164,309,496
1
0
null
null
null
null
UTF-8
C++
false
false
285,649
h
// // Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "utility/Defines.hpp" #ifdef USING_VULKAN #ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H #define AMD_VULKAN_MEMORY_ALLOCATOR_H #ifdef __cplusplus extern "C" { #endif /** \mainpage Vulkan Memory Allocator <b>Version 2.0.0-alpha.7</b> (2018-02-09) Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved. \n License: MIT Documentation of all members: vk_mem_alloc.h Table of contents: - User guide - \subpage quick_start - \subpage choosing_memory_type - \subpage memory_mapping - \subpage custom_memory_pools - \subpage defragmentation - \subpage lost_allocations - \subpage allocation_annotation - \subpage configuration - \subpage vk_khr_dedicated_allocation - \subpage thread_safety - \subpage about_the_library See also: - [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator) - [Product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/) \page quick_start Quick start \section project_setup Project setup In your project code: -# Include "vk_mem_alloc.h" file wherever you want to use the library. -# In exacly one C++ file define following macro before include to build library implementation. \code #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" \endcode \section initialization Initialization At program startup: -# Initialize Vulkan to have `VkPhysicalDevice` and `VkDevice` object. -# Fill VmaAllocatorCreateInfo structure and create `VmaAllocator` object by calling vmaCreateAllocator(). \code VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = physicalDevice; allocatorInfo.device = device; VmaAllocator allocator; vmaCreateAllocator(&allocatorInfo, &allocator); \endcode \section resource_allocation Resource allocation When you want to create a buffer or image: -# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure. -# Fill VmaAllocationCreateInfo structure. -# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory already allocated and bound to it. \code VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufferInfo.size = 65536; bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo = {}; allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); \endcode Don't forget to destroy your objects when no longer needed: \code vmaDestroyBuffer(allocator, buffer, allocation); vmaDestroyAllocator(allocator); \endcode \page choosing_memory_type Choosing memory type Physical devices in Vulkan support various combinations of memory heaps and types. Help with choosing correct and optimal memory type for your specific resource is one of the key features of this library. You can use it by filling appropriate members of VmaAllocationCreateInfo structure, as described below. You can also combine multiple methods. -# If you just want to find memory type index that meets your requirements, you can use function vmaFindMemoryTypeIndex(). -# If you want to allocate a region of device memory without association with any specific image or buffer, you can use function vmaAllocateMemory(). Usage of this function is not recommended and usually not needed. -# If you already have a buffer or an image created, you want to allocate memory for it and then you will bind it yourself, you can use function vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(). -# If you want to create a buffer or an image, allocate memory for it and bind them together, all in one call, you can use function vmaCreateBuffer(), vmaCreateImage(). This is the recommended way to use this library. When using 3. or 4., the library internally queries Vulkan for memory types supported for that buffer or image (function `vkGetBufferMemoryRequirements()`) and uses only one of these types. If no memory type can be found that meets all the requirements, these functions return `VK_ERROR_FEATURE_NOT_PRESENT`. You can leave VmaAllocationCreateInfo structure completely filled with zeros. It means no requirements are specified for memory type. It is valid, although not very useful. \section choosing_memory_type_usage Usage The easiest way to specify memory requirements is to fill member VmaAllocationCreateInfo::usage using one of the values of enum `VmaMemoryUsage`. It defines high level, common usage types. For example, if you want to create a uniform buffer that will be filled using transfer only once or infrequently and used for rendering every frame, you can do it using following code: \code VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufferInfo.size = 65536; bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo = {}; allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); \endcode \section choosing_memory_type_required_preferred_flags Required and preferred flags You can specify more detailed requirements by filling members VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags with a combination of bits from enum `VkMemoryPropertyFlags`. For example, if you want to create a buffer that will be persistently mapped on host (so it must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`, use following code: \code VmaAllocationCreateInfo allocInfo = {}; allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); \endcode A memory type is chosen that has all the required flags and as many preferred flags set as possible. If you use VmaAllocationCreateInfo::usage, it is just internally converted to a set of required and preferred flags. \section choosing_memory_type_explicit_memory_types Explicit memory types If you inspected memory types available on the physical device and you have a preference for memory types that you want to use, you can fill member VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set means that a memory type with that index is allowed to be used for the allocation. Special value 0, just like UINT32_MAX, means there are no restrictions to memory type index. Please note that this member is NOT just a memory type index. Still you can use it to choose just one, specific memory type. For example, if you already determined that your buffer should be created in memory type 2, use following code: \code uint32_t memoryTypeIndex = 2; VmaAllocationCreateInfo allocInfo = {}; allocInfo.memoryTypeBits = 1u << memoryTypeIndex; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); \endcode \section choosing_memory_type_custom_memory_pools Custom memory pools If you allocate from custom memory pool, all the ways of specifying memory requirements described above are not applicable and the aforementioned members of VmaAllocationCreateInfo structure are ignored. Memory type is selected explicitly when creating the pool and then used to make all the allocations from that pool. For further details, see \ref custom_memory_pools. \page memory_mapping Memory mapping \section persistently_mapped_memory Persistently mapped memory If you need to map memory on host, it may happen that two allocations are assigned to the same `VkDeviceMemory` block, so if you map them both at the same time, it will cause error because mapping single memory block multiple times is illegal in Vulkan. TODO update this... It is safer, more convenient and more efficient to use special feature designed for that: persistently mapped memory. Allocations made with `VMA_ALLOCATION_CREATE_MAPPED_BIT` flag set in VmaAllocationCreateInfo::flags are returned from device memory blocks that stay mapped all the time, so you can just access CPU pointer to it. VmaAllocationInfo::pMappedData pointer is already offseted to the beginning of particular allocation. Example: \code VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = 1024; bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY; allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; VkBuffer buf; VmaAllocation alloc; VmaAllocationInfo allocInfo; vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); // Buffer is immediately mapped. You can access its memory. memcpy(allocInfo.pMappedData, myData, 1024); \endcode Memory in Vulkan doesn't need to be unmapped before using it e.g. for transfers, but if you are not sure whether it's `HOST_COHERENT` (here is surely is because it's created with `VMA_MEMORY_USAGE_CPU_ONLY`), you should check it. If it's not, you should call `vkInvalidateMappedMemoryRanges()` before reading and `vkFlushMappedMemoryRanges()` after writing to mapped memory on CPU. Example: \code VkMemoryPropertyFlags memFlags; vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags); if((memFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE }; memRange.memory = allocInfo.deviceMemory; memRange.offset = allocInfo.offset; memRange.size = allocInfo.size; vkFlushMappedMemoryRanges(device, 1, &memRange); } \endcode \section amd_perf_note Note on performance There is a situation that you should be careful about. It happens only if all of following conditions are met: -# You use AMD GPU. -# You use the memory type that is both `DEVICE_LOCAL` and `HOST_VISIBLE` (used when you specify `VMA_MEMORY_USAGE_CPU_TO_GPU`). -# Operating system is Windows 7 or 8.x (Windows 10 is not affected because it uses WDDM2). Then whenever a `VkDeviceMemory` block allocated from this memory type is mapped for the time of any call to `vkQueueSubmit()` or `vkQueuePresentKHR()`, this block is migrated by WDDM to system RAM, which degrades performance. It doesn't matter if that particular memory block is actually used by the command buffer being submitted. To avoid this problem, either make sure to unmap all allocations made from this memory type before your Submit and Present, or use `VMA_MEMORY_USAGE_GPU_ONLY` and transfer from a staging buffer in `VMA_MEMORY_USAGE_CPU_ONLY`, which can safely stay mapped all the time. \page custom_memory_pools Custom memory pools The library automatically creates and manages default memory pool for each memory type available on the device. A pool contains a number of `VkDeviceMemory` blocks. You can create custom pool and allocate memory out of it. It can be useful if you want to: - Keep certain kind of allocations separate from others. - Enforce particular size of Vulkan memory blocks. - Limit maximum amount of Vulkan memory allocated for that pool. To use custom memory pools: -# Fill VmaPoolCreateInfo structure. -# Call vmaCreatePool() to obtain `VmaPool` handle. -# When making an allocation, set VmaAllocationCreateInfo::pool to this handle. You don't need to specify any other parameters of this structure, like usage. Example: \code // Create a pool that could have at most 2 blocks, 128 MiB each. VmaPoolCreateInfo poolCreateInfo = {}; poolCreateInfo.memoryTypeIndex = ... poolCreateInfo.blockSize = 128ull * 1024 * 1024; poolCreateInfo.maxBlockCount = 2; VmaPool pool; vmaCreatePool(allocator, &poolCreateInfo, &pool); // Allocate a buffer out of it. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = 1024; bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.pool = pool; VkBuffer buf; VmaAllocation alloc; VmaAllocationInfo allocInfo; vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); \endcode You have to free all allocations made from this pool before destroying it. \code vmaDestroyBuffer(allocator, buf, alloc); vmaDestroyPool(allocator, pool); \endcode \section custom_memory_pools_MemTypeIndex Choosing memory type index When creating a pool, you must explicitly specify memory type index. To find the one suitable for your buffers or images, you can use code similar to the following: \code VkBufferCreateInfo dummyBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; dummyBufCreateInfo.size = 1024; // Whatever. dummyBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Change if needed. VkBuffer dummyBuf; vkCreateBuffer(device, &dummyBufCreateInfo, nullptr, &dummyBuf); VkMemoryRequirements memReq; vkGetBufferMemoryRequirements(device, dummyBuf, &memReq); VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; // Change if needed. uint32_t memTypeIndex; vmaFindMemoryTypeIndex(allocator, memReq.memoryTypeBits, &allocCreateInfo, &memTypeIndex); vkDestroyBuffer(device, dummyBuf, nullptr); VmaPoolCreateInfo poolCreateInfo = {}; poolCreateInfo.memoryTypeIndex = memTypeIndex; // ... \endcode Dummy buffer is needed to query driver for `memReq.memoryTypeBits`. Memory is never allocated for this buffer. You should fill structures `dummyBufCreateInfo` and `allocCreateInfo` with the same parameters as you are going to use for buffers created in your pool. \page defragmentation Defragmentation Interleaved allocations and deallocations of many objects of varying size can cause fragmentation, which can lead to a situation where the library is unable to find a continuous range of free memory for a new allocation despite there is enough free space, just scattered across many small free ranges between existing allocations. To mitigate this problem, you can use vmaDefragment(). Given set of allocations, this function can move them to compact used memory, ensure more continuous free space and possibly also free some `VkDeviceMemory`. It can work only on allocations made from memory type that is `HOST_VISIBLE`. Allocations are modified to point to the new `VkDeviceMemory` and offset. Data in this memory is also `memmove`-ed to the new place. However, if you have images or buffers bound to these allocations (and you certainly do), you need to destroy, recreate, and bind them to the new place in memory. For further details and example code, see documentation of function vmaDefragment(). \page lost_allocations Lost allocations If your game oversubscribes video memory, if may work OK in previous-generation graphics APIs (DirectX 9, 10, 11, OpenGL) because resources are automatically paged to system RAM. In Vulkan you can't do it because when you run out of memory, an allocation just fails. If you have more data (e.g. textures) that can fit into VRAM and you don't need it all at once, you may want to upload them to GPU on demand and "push out" ones that are not used for a long time to make room for the new ones, effectively using VRAM (or a cartain memory pool) as a form of cache. Vulkan Memory Allocator can help you with that by supporting a concept of "lost allocations". To create an allocation that can become lost, include `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT` flag in VmaAllocationCreateInfo::flags. Before using a buffer or image bound to such allocation in every new frame, you need to query it if it's not lost. To check it: call vmaGetAllocationInfo() and see if VmaAllocationInfo::deviceMemory is not `VK_NULL_HANDLE`. If the allocation is lost, you should not use it or buffer/image bound to it. You mustn't forget to destroy this allocation and this buffer/image. To create an allocation that can make some other allocations lost to make room for it, use `VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT` flag. You will usually use both flags `VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT` and `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT` at the same time. Warning! Current implementation uses quite naive, brute force algorithm, which can make allocation calls that use `VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT` flag quite slow. A new, more optimal algorithm and data structure to speed this up is planned for the future. <b>When interleaving creation of new allocations with usage of existing ones, how do you make sure that an allocation won't become lost while it's used in the current frame?</b> It is ensured because vmaGetAllocationInfo() not only returns allocation parameters and checks whether it's not lost, but when it's not, it also atomically marks it as used in the current frame, which makes it impossible to become lost in that frame. It uses lockless algorithm, so it works fast and doesn't involve locking any internal mutex. <b>What if my allocation may still be in use by the GPU when it's rendering a previous frame while I already submit new frame on the CPU?</b> You can make sure that allocations "touched" by vmaGetAllocationInfo() will not become lost for a number of additional frames back from the current one by specifying this number as VmaAllocatorCreateInfo::frameInUseCount (for default memory pool) and VmaPoolCreateInfo::frameInUseCount (for custom pool). <b>How do you inform the library when new frame starts?</b> You need to call function vmaSetCurrentFrameIndex(). Example code: \code struct MyBuffer { VkBuffer m_Buf = nullptr; VmaAllocation m_Alloc = nullptr; // Called when the buffer is really needed in the current frame. void EnsureBuffer(); }; void MyBuffer::EnsureBuffer() { // Buffer has been created. if(m_Buf != VK_NULL_HANDLE) { // Check if its allocation is not lost + mark it as used in current frame. VmaAllocationInfo allocInfo; vmaGetAllocationInfo(allocator, m_Alloc, &allocInfo); if(allocInfo.deviceMemory != VK_NULL_HANDLE) { // It's all OK - safe to use m_Buf. return; } } // Buffer not yet exists or lost - destroy and recreate it. vmaDestroyBuffer(allocator, m_Buf, m_Alloc); VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = 1024; bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; allocCreateInfo.flags = VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT | VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT; vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &m_Buf, &m_Alloc, nullptr); } \endcode When using lost allocations, you may see some Vulkan validation layer warnings about overlapping regions of memory bound to different kinds of buffers and images. This is still valid as long as you implement proper handling of lost allocations (like in the example above) and don't use them. The library uses following algorithm for allocation, in order: -# Try to find free range of memory in existing blocks. -# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size. -# If failed, try to create such block with size/2 and size/4. -# If failed and `VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT` flag was specified, try to find space in existing blocks, possilby making some other allocations lost. -# If failed, try to allocate separate `VkDeviceMemory` for this allocation, just like when you use `VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT`. -# If failed, choose other memory type that meets the requirements specified in VmaAllocationCreateInfo and go to point 1. -# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`. \page allocation_annotation Allocation names and user data \section allocation_user_data Allocation user data You can annotate allocations with your own information, e.g. for debugging purposes. To do that, fill VmaAllocationCreateInfo::pUserData field when creating an allocation. It's an opaque `void*` pointer. You can use it e.g. as a pointer, some handle, index, key, ordinal number or any other value that would associate the allocation with your custom metadata. \code VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; // Fill bufferInfo... MyBufferMetadata* pMetadata = CreateBufferMetadata(); VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; allocCreateInfo.pUserData = pMetadata; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocCreateInfo, &buffer, &allocation, nullptr); \endcode The pointer may be later retrieved as VmaAllocationInfo::pUserData: \code VmaAllocationInfo allocInfo; vmaGetAllocationInfo(allocator, allocation, &allocInfo); MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData; \endcode It can also be changed using function vmaSetAllocationUserData(). Values of (non-zero) allocations' `pUserData` are printed in JSON report created by vmaBuildStatsString(), in hexadecimal form. \section allocation_names Allocation names There is alternative mode available where `pUserData` pointer is used to point to a null-terminated string, giving a name to the allocation. To use this mode, set `VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT` flag in VmaAllocationCreateInfo::flags. Then `pUserData` passed as VmaAllocationCreateInfo::pUserData or argument to vmaSetAllocationUserData() must be either null or pointer to a null-terminated string. The library creates internal copy of the string, so the pointer you pass doesn't need to be valid for whole lifetime of the allocation. You can free it after the call. \code VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; // Fill imageInfo... std::string imageName = "Texture: "; imageName += fileName; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; allocCreateInfo.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT; allocCreateInfo.pUserData = imageName.c_str(); VkImage image; VmaAllocation allocation; vmaCreateImage(allocator, &imageInfo, &allocCreateInfo, &image, &allocation, nullptr); \endcode The value of `pUserData` pointer of the allocation will be different than the one you passed when setting allocation's name - pointing to a buffer managed internally that holds copy of the string. \code VmaAllocationInfo allocInfo; vmaGetAllocationInfo(allocator, allocation, &allocInfo); const char* imageName = (const char*)allocInfo.pUserData; printf("Image name: %s\n", imageName); \endcode That string is also printed in JSON report created by vmaBuildStatsString(). \page configuration Configuration Please check "CONFIGURATION SECTION" in the code to find macros that you can define before each include of this file or change directly in this file to provide your own implementation of basic facilities like assert, `min()` and `max()` functions, mutex etc. C++ STL is used by default, but changing these allows you to get rid of any STL usage if you want, as many game developers tend to do. \section config_Vulkan_functions Pointers to Vulkan functions The library uses Vulkan functions straight from the `vulkan.h` header by default. If you want to provide your own pointers to these functions, e.g. fetched using `vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`: -# Define `VMA_STATIC_VULKAN_FUNCTIONS 0`. -# Provide valid pointers through VmaAllocatorCreateInfo::pVulkanFunctions. \section custom_memory_allocator Custom host memory allocator If you use custom allocator for CPU memory rather than default operator `new` and `delete` from C++, you can make this library using your allocator as well by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These functions will be passed to Vulkan, as well as used by the library itself to make any CPU-side allocations. \section allocation_callbacks Device memory allocation callbacks The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally. You can setup callbacks to be informed about these calls, e.g. for the purpose of gathering some statistics. To do it, fill optional member VmaAllocatorCreateInfo::pDeviceMemoryCallbacks. \section heap_memory_limit Device heap memory limit If you want to test how your program behaves with limited amount of Vulkan device memory available without switching your graphics card to one that really has smaller VRAM, you can use a feature of this library intended for this purpose. To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit. \page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve performance on some GPUs. It augments Vulkan API with possibility to query driver whether it prefers particular buffer or image to have its own, dedicated allocation (separate `VkDeviceMemory` block) for better efficiency - to be able to do some internal optimizations. The extension is supported by this library. It will be used automatically when enabled. To enable it: 1 . When creating Vulkan device, check if following 2 device extensions are supported (call `vkEnumerateDeviceExtensionProperties()`). If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`). - VK_KHR_get_memory_requirements2 - VK_KHR_dedicated_allocation If you enabled these extensions: 2 . Use `VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT` flag when creating your `VmaAllocator` to inform the library that you enabled required extensions and you want the library to use them. \code allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; vmaCreateAllocator(&allocatorInfo, &allocator); \endcode That's all. The extension will be automatically used whenever you create a buffer using vmaCreateBuffer() or image using vmaCreateImage(). When using the extension together with Vulkan Validation Layer, you will receive warnings like this: vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer. It is OK, you should just ignore it. It happens because you use function `vkGetBufferMemoryRequirements2KHR()` instead of standard `vkGetBufferMemoryRequirements()`, while the validation layer seems to be unaware of it. To learn more about this extension, see: - [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VK_KHR_dedicated_allocation) - [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5) \page thread_safety Thread safety - The library has no global state, so separate `VmaAllocator` objects can be used independently. - By default, all calls to functions that take `VmaAllocator` as first parameter are safe to call from multiple threads simultaneously because they are synchronized internally when needed. - When the allocator is created with `VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT` flag, calls to functions that take such `VmaAllocator` object must be synchronized externally. - Access to a `VmaAllocation` object must be externally synchronized. For example, you must not call vmaGetAllocationInfo() and vmaMapMemory() from different threads at the same time if you pass the same `VmaAllocation` object to these functions. \page about_the_library About the library \section about_the_library_features_not_supported Features not supported Features deliberately excluded from the scope of this library: - Data transfer - issuing commands that transfer data between buffers or images, any usage of `VkCommandList` or `VkCommandQueue` and related synchronization is responsibility of the user. - Support for any programming languages other than C/C++. Bindings to other languages are welcomed as external projects. */ #include <vulkan/vulkan.h> VK_DEFINE_HANDLE(VmaAllocator) /// Callback function called after successful vkAllocateMemory. typedef void (VKAPI_PTR *PFN_vmaAllocateDeviceMemoryFunction)( VmaAllocator allocator, uint32_t memoryType, VkDeviceMemory memory, VkDeviceSize size); /// Callback function called before vkFreeMemory. typedef void (VKAPI_PTR *PFN_vmaFreeDeviceMemoryFunction)( VmaAllocator allocator, uint32_t memoryType, VkDeviceMemory memory, VkDeviceSize size); /** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`. Provided for informative purpose, e.g. to gather statistics about number of allocations or total amount of memory allocated in Vulkan. Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks. */ typedef struct VmaDeviceMemoryCallbacks { /// Optional, can be null. PFN_vmaAllocateDeviceMemoryFunction pfnAllocate; /// Optional, can be null. PFN_vmaFreeDeviceMemoryFunction pfnFree; } VmaDeviceMemoryCallbacks; /// Flags for created VmaAllocator. typedef enum VmaAllocatorCreateFlagBits { /** \brief Allocator and all objects created from it will not be synchronized internally, so you must guarantee they are used from only one thread at a time or synchronized externally by you. Using this flag may increase performance because internal mutexes are not used. */ VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001, /** \brief Enables usage of VK_KHR_dedicated_allocation extension. Using this extenion will automatically allocate dedicated blocks of memory for some buffers and images instead of suballocating place for them out of bigger memory blocks (as if you explicitly used VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag) when it is recommended by the driver. It may improve performance on some GPUs. You may set this flag only if you found out that following device extensions are supported, you enabled them while creating Vulkan device passed as VmaAllocatorCreateInfo::device, and you want them to be used internally by this library: - VK_KHR_get_memory_requirements2 - VK_KHR_dedicated_allocation When this flag is set, you can experience following warnings reported by Vulkan validation layer. You can ignore them. > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer. */ VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002, VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } VmaAllocatorCreateFlagBits; typedef VkFlags VmaAllocatorCreateFlags; /** \brief Pointers to some Vulkan functions - a subset used by the library. Used in VmaAllocatorCreateInfo::pVulkanFunctions. */ typedef struct VmaVulkanFunctions { PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; PFN_vkAllocateMemory vkAllocateMemory; PFN_vkFreeMemory vkFreeMemory; PFN_vkMapMemory vkMapMemory; PFN_vkUnmapMemory vkUnmapMemory; PFN_vkBindBufferMemory vkBindBufferMemory; PFN_vkBindImageMemory vkBindImageMemory; PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; PFN_vkCreateBuffer vkCreateBuffer; PFN_vkDestroyBuffer vkDestroyBuffer; PFN_vkCreateImage vkCreateImage; PFN_vkDestroyImage vkDestroyImage; PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR; PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR; } VmaVulkanFunctions; /// Description of a Allocator to be created. typedef struct VmaAllocatorCreateInfo { /// Flags for created allocator. Use VmaAllocatorCreateFlagBits enum. VmaAllocatorCreateFlags flags; /// Vulkan physical device. /** It must be valid throughout whole lifetime of created allocator. */ VkPhysicalDevice physicalDevice; /// Vulkan device. /** It must be valid throughout whole lifetime of created allocator. */ VkDevice device; /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. /** Set to 0 to use default, which is currently 256 MiB. */ VkDeviceSize preferredLargeHeapBlockSize; /// Custom CPU memory allocation callbacks. /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */ const VkAllocationCallbacks* pAllocationCallbacks; /// Informative callbacks for vkAllocateMemory, vkFreeMemory. /** Optional, can be null. */ const VmaDeviceMemoryCallbacks* pDeviceMemoryCallbacks; /** \brief Maximum number of additional frames that are in use at the same time as current frame. This value is used only when you make allocations with VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount. For example, if you double-buffer your command buffers, so resources used for rendering in previous frame may still be in use by the GPU at the moment you allocate resources needed for the current frame, set this value to 1. If you want to allow any allocations other than used in the current frame to become lost, set this value to 0. */ uint32_t frameInUseCount; /** \brief Either NULL or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap. If not NULL, it must be a pointer to an array of `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on maximum number of bytes that can be allocated out of particular Vulkan memory heap. Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that heap. This is also the default in case of `pHeapSizeLimit` = NULL. If there is a limit defined for a heap: - If user tries to allocate more memory from that heap using this allocator, the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the value of this limit will be reported instead when using vmaGetMemoryProperties(). Warning! Using this feature may not be equivalent to installing a GPU with smaller amount of memory, because graphics driver doesn't necessary fail new allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is exceeded. It may return success and just silently migrate some device memory blocks to system RAM. */ const VkDeviceSize* pHeapSizeLimit; /** \brief Pointers to Vulkan functions. Can be null if you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1`. If you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1` in configuration section, you can pass null as this member, because the library will fetch pointers to Vulkan functions internally in a static way, like: vulkanFunctions.vkAllocateMemory = &vkAllocateMemory; Fill this member if you want to provide your own pointers to Vulkan functions, e.g. fetched using `vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`. */ const VmaVulkanFunctions* pVulkanFunctions; } VmaAllocatorCreateInfo; /// Creates Allocator object. VkResult vmaCreateAllocator( const VmaAllocatorCreateInfo* pCreateInfo, VmaAllocator* pAllocator); /// Destroys allocator object. void vmaDestroyAllocator( VmaAllocator allocator); /** PhysicalDeviceProperties are fetched from physicalDevice by the allocator. You can access it here, without fetching it again on your own. */ void vmaGetPhysicalDeviceProperties( VmaAllocator allocator, const VkPhysicalDeviceProperties** ppPhysicalDeviceProperties); /** PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator. You can access it here, without fetching it again on your own. */ void vmaGetMemoryProperties( VmaAllocator allocator, const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties); /** \brief Given Memory Type Index, returns Property Flags of this memory type. This is just a convenience function. Same information can be obtained using vmaGetMemoryProperties(). */ void vmaGetMemoryTypeProperties( VmaAllocator allocator, uint32_t memoryTypeIndex, VkMemoryPropertyFlags* pFlags); /** \brief Sets index of the current frame. This function must be used if you make allocations with `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT` and `VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT` flags to inform the allocator when a new frame begins. Allocations queried using vmaGetAllocationInfo() cannot become lost in the current frame. */ void vmaSetCurrentFrameIndex( VmaAllocator allocator, uint32_t frameIndex); /** \brief Calculated statistics of memory usage in entire allocator. */ typedef struct VmaStatInfo { /// Number of `VkDeviceMemory` Vulkan memory blocks allocated. uint32_t blockCount; /// Number of `VmaAllocation` allocation objects allocated. uint32_t allocationCount; /// Number of free ranges of memory between allocations. uint32_t unusedRangeCount; /// Total number of bytes occupied by all allocations. VkDeviceSize usedBytes; /// Total number of bytes occupied by unused ranges. VkDeviceSize unusedBytes; VkDeviceSize allocationSizeMin, allocationSizeAvg, allocationSizeMax; VkDeviceSize unusedRangeSizeMin, unusedRangeSizeAvg, unusedRangeSizeMax; } VmaStatInfo; /// General statistics from current state of Allocator. typedef struct VmaStats { VmaStatInfo memoryType[VK_MAX_MEMORY_TYPES]; VmaStatInfo memoryHeap[VK_MAX_MEMORY_HEAPS]; VmaStatInfo total; } VmaStats; /// Retrieves statistics from current state of the Allocator. void vmaCalculateStats( VmaAllocator allocator, VmaStats* pStats); #define VMA_STATS_STRING_ENABLED 1 #if VMA_STATS_STRING_ENABLED /// Builds and returns statistics as string in JSON format. /** @param[out] ppStatsString Must be freed using vmaFreeStatsString() function. */ void vmaBuildStatsString( VmaAllocator allocator, char** ppStatsString, VkBool32 detailedMap); void vmaFreeStatsString( VmaAllocator allocator, char* pStatsString); #endif // #if VMA_STATS_STRING_ENABLED VK_DEFINE_HANDLE(VmaPool) typedef enum VmaMemoryUsage { /** No intended memory usage specified. Use other members of VmaAllocationCreateInfo to specify your requirements. */ VMA_MEMORY_USAGE_UNKNOWN = 0, /** Memory will be used on device only, so fast access from the device is preferred. It usually means device-local GPU (video) memory. No need to be mappable on host. It is roughly equivalent of D3D12_HEAP_TYPE_DEFAULT. Usage: - Resources written and read by device, e.g. images used as attachments. - Resources transferred from host once (immutable) or infrequently and read by device multiple times, e.g. textures to be sampled, vertex buffers, uniform (constant) buffers, and majority of other types of resources used by device. Allocation may still end up in `HOST_VISIBLE` memory on some implementations. In such case, you are free to map it. You can use `VMA_ALLOCATION_CREATE_MAPPED_BIT` with this usage type. */ VMA_MEMORY_USAGE_GPU_ONLY = 1, /** Memory will be mappable on host. It usually means CPU (system) memory. Resources created in this pool are still accessible to the device, but access to them can be slower. Guarantees to be `HOST_VISIBLE` and `HOST_COHERENT`. CPU read may be uncached. It is roughly equivalent of D3D12_HEAP_TYPE_UPLOAD. Usage: Staging copy of resources used as transfer source. */ VMA_MEMORY_USAGE_CPU_ONLY = 2, /** Memory that is both mappable on host (guarantees to be `HOST_VISIBLE`) and preferably fast to access by GPU. CPU reads may be uncached and very slow. Usage: Resources written frequently by host (dynamic), read by device. E.g. textures, vertex buffers, uniform buffers updated every frame or every draw call. */ VMA_MEMORY_USAGE_CPU_TO_GPU = 3, /** Memory mappable on host (guarantees to be `HOST_VISIBLE`) and cached. It is roughly equivalent of D3D12_HEAP_TYPE_READBACK. Usage: - Resources written by device, read by host - results of some computations, e.g. screen capture, average scene luminance for HDR tone mapping. - Any resources read on host, e.g. CPU-side copy of vertex buffer used as source of transfer, but also used for collision detection. */ VMA_MEMORY_USAGE_GPU_TO_CPU = 4, VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF } VmaMemoryUsage; /// Flags to be passed as VmaAllocationCreateInfo::flags. typedef enum VmaAllocationCreateFlagBits { /** \brief Set this flag if the allocation should have its own memory block. Use it for special, big resources, like fullscreen images used as attachments. This flag must also be used for host visible resources that you want to map simultaneously because otherwise they might end up as regions of the same `VkDeviceMemory`, while mapping same `VkDeviceMemory` multiple times simultaneously is illegal. You should not use this flag if VmaAllocationCreateInfo::pool is not null. */ VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001, /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block. If new allocation cannot be placed in any of the existing blocks, allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error. You should not use `VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT` and `VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT` at the same time. It makes no sense. If VmaAllocationCreateInfo::pool is not null, this flag is implied and ignored. */ VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002, /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it. Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData. Is it valid to use this flag for allocation made from memory type that is not `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is useful if you need an allocation that is efficient to use on GPU (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that support it (e.g. Intel GPU). You should not use this flag together with `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT`. */ VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004, /** Allocation created with this flag can become lost as a result of another allocation with `VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT` flag, so you must check it before use. To check if allocation is not lost, call vmaGetAllocationInfo() and check if VmaAllocationInfo::deviceMemory is not `VK_NULL_HANDLE`. For details about supporting lost allocations, see Lost Allocations chapter of User Guide on Main Page. You should not use this flag together with `VMA_ALLOCATION_CREATE_MAPPED_BIT`. */ VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT = 0x00000008, /** While creating allocation using this flag, other allocations that were created with flag `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT` can become lost. For details about supporting lost allocations, see Lost Allocations chapter of User Guide on Main Page. */ VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT = 0x00000010, /** Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a null-terminated string. Instead of copying pointer value, a local copy of the string is made and stored in allocation's pUserData. The string is automatically freed together with the allocation. It is also used in vmaBuildStatsString(). */ VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020, VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } VmaAllocationCreateFlagBits; typedef VkFlags VmaAllocationCreateFlags; typedef struct VmaAllocationCreateInfo { /// Use VmaAllocationCreateFlagBits enum. VmaAllocationCreateFlags flags; /** \brief Intended usage of memory. You can leave `VMA_MEMORY_USAGE_UNKNOWN` if you specify memory requirements in other way. \n If `pool` is not null, this member is ignored. */ VmaMemoryUsage usage; /** \brief Flags that must be set in a Memory Type chosen for an allocation. Leave 0 if you specify memory requirements in other way. \n If `pool` is not null, this member is ignored.*/ VkMemoryPropertyFlags requiredFlags; /** \brief Flags that preferably should be set in a memory type chosen for an allocation. Set to 0 if no additional flags are prefered. \n If `pool` is not null, this member is ignored. */ VkMemoryPropertyFlags preferredFlags; /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation. Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if it meets other requirements specified by this structure, with no further restrictions on memory type index. \n If `pool` is not null, this member is ignored. */ uint32_t memoryTypeBits; /** \brief Pool that this allocation should be created in. Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members: `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored. */ VmaPool pool; /** \brief Custom general-purpose pointer that will be stored in VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData(). If `VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT` is used, it must be either null or pointer to a null-terminated string. The string will be then copied to internal buffer, so it doesn't need to be valid after allocation call. */ void* pUserData; } VmaAllocationCreateInfo; /** This algorithm tries to find a memory type that: - Is allowed by memoryTypeBits. - Contains all the flags from pAllocationCreateInfo->requiredFlags. - Matches intended usage. - Has as many flags from pAllocationCreateInfo->preferredFlags as possible. \return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result from this function or any other allocating function probably means that your device doesn't support any memory type with requested features for the specific type of resource you want to use it for. Please check parameters of your resource, like image layout (OPTIMAL versus LINEAR) or mip level count. */ VkResult vmaFindMemoryTypeIndex( VmaAllocator allocator, uint32_t memoryTypeBits, const VmaAllocationCreateInfo* pAllocationCreateInfo, uint32_t* pMemoryTypeIndex); /// Flags to be passed as VmaPoolCreateInfo::flags. typedef enum VmaPoolCreateFlagBits { /** \brief Use this flag if you always allocate only buffers and linear images or only optimal images out of this pool and so Buffer-Image Granularity can be ignored. This is na optional optimization flag. If you always allocate using vmaCreateBuffer(), vmaCreateImage(), vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator knows exact type of your allocations so it can handle Buffer-Image Granularity in the optimal way. If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(), exact type of such allocations is not known, so allocator must be conservative in handling Buffer-Image Granularity, which can lead to suboptimal allocation (wasted memory). In that case, if you can make sure you always allocate only buffers and linear images or only optimal images out of this pool, use this flag to make allocator disregard Buffer-Image Granularity and so make allocations more optimal. */ VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002, VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } VmaPoolCreateFlagBits; typedef VkFlags VmaPoolCreateFlags; /** \brief Describes parameter of created `VmaPool`. */ typedef struct VmaPoolCreateInfo { /** \brief Vulkan memory type index to allocate this pool from. */ uint32_t memoryTypeIndex; /** \brief Use combination of `VmaPoolCreateFlagBits`. */ VmaPoolCreateFlags flags; /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional. Leave 0 to use default. */ VkDeviceSize blockSize; /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty. Set to 0 to have no preallocated blocks and let the pool be completely empty. */ size_t minBlockCount; /** \brief Maximum number of blocks that can be allocated in this pool. Optional. Set to 0 to use `SIZE_MAX`, which means no limit. Set to same value as minBlockCount to have fixed amount of memory allocated throuout whole lifetime of this pool. */ size_t maxBlockCount; /** \brief Maximum number of additional frames that are in use at the same time as current frame. This value is used only when you make allocations with `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT` flag. Such allocation cannot become lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount. For example, if you double-buffer your command buffers, so resources used for rendering in previous frame may still be in use by the GPU at the moment you allocate resources needed for the current frame, set this value to 1. If you want to allow any allocations other than used in the current frame to become lost, set this value to 0. */ uint32_t frameInUseCount; } VmaPoolCreateInfo; /** \brief Describes parameter of existing `VmaPool`. */ typedef struct VmaPoolStats { /** \brief Total amount of `VkDeviceMemory` allocated from Vulkan for this pool, in bytes. */ VkDeviceSize size; /** \brief Total number of bytes in the pool not used by any `VmaAllocation`. */ VkDeviceSize unusedSize; /** \brief Number of VmaAllocation objects created from this pool that were not destroyed or lost. */ size_t allocationCount; /** \brief Number of continuous memory ranges in the pool not used by any `VmaAllocation`. */ size_t unusedRangeCount; /** \brief Size of the largest continuous free memory region. Making a new allocation of that size is not guaranteed to succeed because of possible additional margin required to respect alignment and buffer/image granularity. */ VkDeviceSize unusedRangeSizeMax; } VmaPoolStats; /** \brief Allocates Vulkan device memory and creates `VmaPool` object. @param allocator Allocator object. @param pCreateInfo Parameters of pool to create. @param[out] pPool Handle to created pool. */ VkResult vmaCreatePool( VmaAllocator allocator, const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool); /** \brief Destroys VmaPool object and frees Vulkan device memory. */ void vmaDestroyPool( VmaAllocator allocator, VmaPool pool); /** \brief Retrieves statistics of existing VmaPool object. @param allocator Allocator object. @param pool Pool object. @param[out] pPoolStats Statistics of specified pool. */ void vmaGetPoolStats( VmaAllocator allocator, VmaPool pool, VmaPoolStats* pPoolStats); /** \brief Marks all allocations in given pool as lost if they are not used in current frame or VmaPoolCreateInfo::frameInUseCount back from now. @param allocator Allocator object. @param pool Pool. @param[out] pLostAllocationCount Number of allocations marked as lost. Optional - pass null if you don't need this information. */ void vmaMakePoolAllocationsLost( VmaAllocator allocator, VmaPool pool, size_t* pLostAllocationCount); VK_DEFINE_HANDLE(VmaAllocation) /** \brief Parameters of `VmaAllocation` objects, that can be retrieved using function vmaGetAllocationInfo(). */ typedef struct VmaAllocationInfo { /** \brief Memory type index that this allocation was allocated from. It never changes. */ uint32_t memoryType; /** \brief Handle to Vulkan memory object. Same memory object can be shared by multiple allocations. It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost. If the allocation is lost, it is equal to `VK_NULL_HANDLE`. */ VkDeviceMemory deviceMemory; /** \brief Offset into deviceMemory object to the beginning of this allocation, in bytes. (deviceMemory, offset) pair is unique to this allocation. It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost. */ VkDeviceSize offset; /** \brief Size of this allocation, in bytes. It never changes, unless allocation is lost. */ VkDeviceSize size; /** \brief Pointer to the beginning of this allocation as mapped data. If the allocation hasn't been mapped using vmaMapMemory() and hasn't been created with `VMA_ALLOCATION_CREATE_MAPPED_BIT` flag, this value null. It can change after call to vmaMapMemory(), vmaUnmapMemory(). It can also change after call to vmaDefragment() if this allocation is passed to the function. */ void* pMappedData; /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData(). It can change after call to vmaSetAllocationUserData() for this allocation. */ void* pUserData; } VmaAllocationInfo; /** \brief General purpose memory allocation. @param[out] pAllocation Handle to allocated memory. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). You should free the memory using vmaFreeMemory(). It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(), vmaCreateBuffer(), vmaCreateImage() instead whenever possible. */ VkResult vmaAllocateMemory( VmaAllocator allocator, const VkMemoryRequirements* pVkMemoryRequirements, const VmaAllocationCreateInfo* pCreateInfo, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo); /** @param[out] pAllocation Handle to allocated memory. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). You should free the memory using vmaFreeMemory(). */ VkResult vmaAllocateMemoryForBuffer( VmaAllocator allocator, VkBuffer buffer, const VmaAllocationCreateInfo* pCreateInfo, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo); /// Function similar to vmaAllocateMemoryForBuffer(). VkResult vmaAllocateMemoryForImage( VmaAllocator allocator, VkImage image, const VmaAllocationCreateInfo* pCreateInfo, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo); /// Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage(). void vmaFreeMemory( VmaAllocator allocator, VmaAllocation allocation); /// Returns current information about specified allocation. void vmaGetAllocationInfo( VmaAllocator allocator, VmaAllocation allocation, VmaAllocationInfo* pAllocationInfo); /** \brief Sets pUserData in given allocation to new value. If the allocation was created with VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT, pUserData must be either null, or pointer to a null-terminated string. The function makes local copy of the string and sets it as allocation's pUserData. String passed as pUserData doesn't need to be valid for whole lifetime of the allocation - you can free it after this call. String previously pointed by allocation's pUserData is freed from memory. If the flag was not used, the value of pointer pUserData is just copied to allocation's pUserData. It is opaque, so you can use it however you want - e.g. as a pointer, ordinal number or some handle to you own data. */ void vmaSetAllocationUserData( VmaAllocator allocator, VmaAllocation allocation, void* pUserData); /** \brief Creates new allocation that is in lost state from the beginning. It can be useful if you need a dummy, non-null allocation. You still need to destroy created object using vmaFreeMemory(). Returned allocation is not tied to any specific memory pool or memory type and not bound to any image or buffer. It has size = 0. It cannot be turned into a real, non-empty allocation. */ void vmaCreateLostAllocation( VmaAllocator allocator, VmaAllocation* pAllocation); /** \brief Maps memory represented by given allocation and returns pointer to it. Maps memory represented by given allocation to make it accessible to CPU code. When succeeded, `*ppData` contains pointer to first byte of this memory. If the allocation is part of bigger `VkDeviceMemory` block, the pointer is correctly offseted to the beginning of region assigned to this particular allocation. Mapping is internally reference-counted and synchronized, so despite raw Vulkan function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory` multiple times simultaneously, it is safe to call this function on allocations assigned to the same memory block. Actual Vulkan memory will be mapped on first mapping and unmapped on last unmapping. If the function succeeded, you must call vmaUnmapMemory() to unmap the allocation when mapping is no longer needed or before freeing the allocation, at the latest. It also safe to call this function multiple times on the same allocation. You must call vmaUnmapMemory() same number of times as you called vmaMapMemory(). It is also safe to call this function on allocation created with `VMA_ALLOCATION_CREATE_MAPPED_BIT` flag. Its memory stays mapped all the time. You must still call vmaUnmapMemory() same number of times as you called vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the "0-th" mapping made automatically due to `VMA_ALLOCATION_CREATE_MAPPED_BIT` flag. This function fails when used on allocation made in memory type that is not `HOST_VISIBLE`. This function always fails when called for allocation that was created with `VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT` flag. Such allocations cannot be mapped. */ VkResult vmaMapMemory( VmaAllocator allocator, VmaAllocation allocation, void** ppData); /** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory(). For details, see description of vmaMapMemory(). */ void vmaUnmapMemory( VmaAllocator allocator, VmaAllocation allocation); /** \brief Optional configuration parameters to be passed to function vmaDefragment(). */ typedef struct VmaDefragmentationInfo { /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places. Default is `VK_WHOLE_SIZE`, which means no limit. */ VkDeviceSize maxBytesToMove; /** \brief Maximum number of allocations that can be moved to different place. Default is `UINT32_MAX`, which means no limit. */ uint32_t maxAllocationsToMove; } VmaDefragmentationInfo; /** \brief Statistics returned by function vmaDefragment(). */ typedef struct VmaDefragmentationStats { /// Total number of bytes that have been copied while moving allocations to different places. VkDeviceSize bytesMoved; /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects. VkDeviceSize bytesFreed; /// Number of allocations that have been moved to different places. uint32_t allocationsMoved; /// Number of empty `VkDeviceMemory` objects that have been released to the system. uint32_t deviceMemoryBlocksFreed; } VmaDefragmentationStats; /** \brief Compacts memory by moving allocations. @param pAllocations Array of allocations that can be moved during this compation. @param allocationCount Number of elements in pAllocations and pAllocationsChanged arrays. @param[out] pAllocationsChanged Array of boolean values that will indicate whether matching allocation in pAllocations array has been moved. This parameter is optional. Pass null if you don't need this information. @param pDefragmentationInfo Configuration parameters. Optional - pass null to use default values. @param[out] pDefragmentationStats Statistics returned by the function. Optional - pass null if you don't need this information. @return VK_SUCCESS if completed, VK_INCOMPLETE if succeeded but didn't make all possible optimizations because limits specified in pDefragmentationInfo have been reached, negative error code in case of error. This function works by moving allocations to different places (different `VkDeviceMemory` objects and/or different offsets) in order to optimize memory usage. Only allocations that are in pAllocations array can be moved. All other allocations are considered nonmovable in this call. Basic rules: - Only allocations made in memory types that have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag can be compacted. You may pass other allocations but it makes no sense - these will never be moved. - You may pass allocations made with `VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT` but it makes no sense - they will never be moved. - Both allocations made with or without `VMA_ALLOCATION_CREATE_MAPPED_BIT` flag can be compacted. If not persistently mapped, memory will be mapped temporarily inside this function if needed. - You must not pass same `VmaAllocation` object multiple times in pAllocations array. The function also frees empty `VkDeviceMemory` blocks. After allocation has been moved, its VmaAllocationInfo::deviceMemory and/or VmaAllocationInfo::offset changes. You must query them again using vmaGetAllocationInfo() if you need them. If an allocation has been moved, data in memory is copied to new place automatically, but if it was bound to a buffer or an image, you must destroy that object yourself, create new one and bind it to the new memory pointed by the allocation. You must use `vkDestroyBuffer()`, `vkDestroyImage()`, `vkCreateBuffer()`, `vkCreateImage()` for that purpose and NOT vmaDestroyBuffer(), vmaDestroyImage(), vmaCreateBuffer(), vmaCreateImage()! Example: \code VkDevice device = ...; VmaAllocator allocator = ...; std::vector<VkBuffer> buffers = ...; std::vector<VmaAllocation> allocations = ...; std::vector<VkBool32> allocationsChanged(allocations.size()); vmaDefragment(allocator, allocations.data(), allocations.size(), allocationsChanged.data(), nullptr, nullptr); for(size_t i = 0; i < allocations.size(); ++i) { if(allocationsChanged[i]) { VmaAllocationInfo allocInfo; vmaGetAllocationInfo(allocator, allocations[i], &allocInfo); vkDestroyBuffer(device, buffers[i], nullptr); VkBufferCreateInfo bufferInfo = ...; vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]); // You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning. vkBindBufferMemory(device, buffers[i], allocInfo.deviceMemory, allocInfo.offset); } } \endcode Warning! This function is not correct according to Vulkan specification. Use it at your own risk. That's becuase Vulkan doesn't guarantee that memory requirements (size and alignment) for a new buffer or image are consistent. They may be different even for subsequent calls with the same parameters. It really does happen on some platforms, especially with images. This function may be time-consuming, so you shouldn't call it too often (like every frame or after every resource creation/destruction), but rater you can call it on special occasions (like when reloading a game level, when you just destroyed a lot of objects). */ VkResult vmaDefragment( VmaAllocator allocator, VmaAllocation* pAllocations, size_t allocationCount, VkBool32* pAllocationsChanged, const VmaDefragmentationInfo *pDefragmentationInfo, VmaDefragmentationStats* pDefragmentationStats); /** @param[out] pBuffer Buffer that was created. @param[out] pAllocation Allocation that was created. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). This function automatically: -# Creates buffer. -# Allocates appropriate memory for it. -# Binds the buffer with the memory. If any of these operations fail, buffer and allocation are not created, returned value is negative error code, *pBuffer and *pAllocation are null. If the function succeeded, you must destroy both buffer and allocation when you no longer need them using either convenience function vmaDestroyBuffer() or separately, using `vkDestroyBuffer()` and vmaFreeMemory(). If VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used, VK_KHR_dedicated_allocation extension is used internally to query driver whether it requires or prefers the new buffer to have dedicated allocation. If yes, and if dedicated allocation is possible (VmaAllocationCreateInfo::pool is null and VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated allocation for this buffer, just like when using VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. */ VkResult vmaCreateBuffer( VmaAllocator allocator, const VkBufferCreateInfo* pBufferCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, VkBuffer* pBuffer, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo); /** \brief Destroys Vulkan buffer and frees allocated memory. This is just a convenience function equivalent to: \code vkDestroyBuffer(device, buffer, allocationCallbacks); vmaFreeMemory(allocator, allocation); \endcode It it safe to pass null as buffer and/or allocation. */ void vmaDestroyBuffer( VmaAllocator allocator, VkBuffer buffer, VmaAllocation allocation); /// Function similar to vmaCreateBuffer(). VkResult vmaCreateImage( VmaAllocator allocator, const VkImageCreateInfo* pImageCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, VkImage* pImage, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo); /** \brief Destroys Vulkan image and frees allocated memory. This is just a convenience function equivalent to: \code vkDestroyImage(device, image, allocationCallbacks); vmaFreeMemory(allocator, allocation); \endcode It it safe to pass null as image and/or allocation. */ void vmaDestroyImage( VmaAllocator allocator, VkImage image, VmaAllocation allocation); #ifdef __cplusplus } #endif #endif // AMD_VULKAN_MEMORY_ALLOCATOR_H // For Visual Studio IntelliSense. #ifdef __INTELLISENSE__ #define VMA_IMPLEMENTATION #endif #ifdef VMA_IMPLEMENTATION #undef VMA_IMPLEMENTATION #include <cstdint> #include <cstdlib> #include <cstring> /******************************************************************************* CONFIGURATION SECTION Define some of these macros before each #include of this header or change them here if you need other then default behavior depending on your environment. */ /* Define this macro to 1 to make the library fetch pointers to Vulkan functions internally, like: vulkanFunctions.vkAllocateMemory = &vkAllocateMemory; Define to 0 if you are going to provide you own pointers to Vulkan functions via VmaAllocatorCreateInfo::pVulkanFunctions. */ #if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES) #define VMA_STATIC_VULKAN_FUNCTIONS 1 #endif // Define this macro to 1 to make the library use STL containers instead of its own implementation. //#define VMA_USE_STL_CONTAINERS 1 /* Set this macro to 1 to make the library including and using STL containers: std::pair, std::vector, std::list, std::unordered_map. Set it to 0 or undefined to make the library using its own implementation of the containers. */ #if VMA_USE_STL_CONTAINERS #define VMA_USE_STL_VECTOR 1 #define VMA_USE_STL_UNORDERED_MAP 1 #define VMA_USE_STL_LIST 1 #endif #if VMA_USE_STL_VECTOR #include <vector> #endif #if VMA_USE_STL_UNORDERED_MAP #include <unordered_map> #endif #if VMA_USE_STL_LIST #include <list> #endif /* Following headers are used in this CONFIGURATION section only, so feel free to remove them if not needed. */ #include <cassert> // for assert #include <algorithm> // for min, max #include <mutex> // for std::mutex #include <atomic> // for std::atomic #if !defined(_WIN32) && !defined(__APPLE__) #include <malloc.h> // for aligned_alloc() #endif #if defined(__APPLE__) #include <cstdlib> void *aligned_alloc(size_t alignment, size_t size) { void *pointer; posix_memalign(&pointer, alignment, size); return pointer; } #endif // Normal assert to check for programmer's errors, especially in Debug configuration. #ifndef VMA_ASSERT #ifdef _DEBUG #define VMA_ASSERT(expr) assert(expr) #else #define VMA_ASSERT(expr) #endif #endif // Assert that will be called very often, like inside data structures e.g. operator[]. // Making it non-empty can make program slow. #ifndef VMA_HEAVY_ASSERT #ifdef _DEBUG #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr) #else #define VMA_HEAVY_ASSERT(expr) #endif #endif #ifndef VMA_NULL // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0. #define VMA_NULL nullptr #endif #ifndef VMA_ALIGN_OF #define VMA_ALIGN_OF(type) (__alignof(type)) #endif #ifndef VMA_SYSTEM_ALIGNED_MALLOC #if defined(_WIN32) #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (_aligned_malloc((size), (alignment))) #else #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (aligned_alloc((alignment), (size) )) #endif #endif #ifndef VMA_SYSTEM_FREE #if defined(_WIN32) #define VMA_SYSTEM_FREE(ptr) _aligned_free(ptr) #else #define VMA_SYSTEM_FREE(ptr) free(ptr) #endif #endif #ifndef VMA_MIN #define VMA_MIN(v1, v2) (std::min((v1), (v2))) #endif #ifndef VMA_MAX #define VMA_MAX(v1, v2) (std::max((v1), (v2))) #endif #ifndef VMA_SWAP #define VMA_SWAP(v1, v2) std::swap((v1), (v2)) #endif #ifndef VMA_SORT #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp) #endif #ifndef VMA_DEBUG_LOG #define VMA_DEBUG_LOG(format, ...) /* #define VMA_DEBUG_LOG(format, ...) do { \ printf(format, __VA_ARGS__); \ printf("\n"); \ } while(false) */ #endif // Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString. #if VMA_STATS_STRING_ENABLED static inline void VmaUint32ToStr(char* outStr, size_t strLen, uint32_t num) { snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num)); } static inline void VmaUint64ToStr(char* outStr, size_t strLen, uint64_t num) { snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num)); } static inline void VmaPtrToStr(char* outStr, size_t strLen, const void* ptr) { snprintf(outStr, strLen, "%p", ptr); } #endif #ifndef VMA_MUTEX class VmaMutex { public: VmaMutex() { } ~VmaMutex() { } void Lock() { m_Mutex.lock(); } void Unlock() { m_Mutex.unlock(); } private: std::mutex m_Mutex; }; #define VMA_MUTEX VmaMutex #endif /* If providing your own implementation, you need to implement a subset of std::atomic: - Constructor(uint32_t desired) - uint32_t load() const - void store(uint32_t desired) - bool compare_exchange_weak(uint32_t& expected, uint32_t desired) */ #ifndef VMA_ATOMIC_UINT32 #define VMA_ATOMIC_UINT32 std::atomic<uint32_t> #endif #ifndef VMA_BEST_FIT /** Main parameter for function assessing how good is a free suballocation for a new allocation request. - Set to 1 to use Best-Fit algorithm - prefer smaller blocks, as close to the size of requested allocations as possible. - Set to 0 to use Worst-Fit algorithm - prefer larger blocks, as large as possible. Experiments in special testing environment showed that Best-Fit algorithm is better. */ #define VMA_BEST_FIT (1) #endif #ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY /** Every allocation will have its own memory block. Define to 1 for debugging purposes only. */ #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0) #endif #ifndef VMA_DEBUG_ALIGNMENT /** Minimum alignment of all suballocations, in bytes. Set to more than 1 for debugging purposes only. Must be power of two. */ #define VMA_DEBUG_ALIGNMENT (1) #endif #ifndef VMA_DEBUG_MARGIN /** Minimum margin between suballocations, in bytes. Set nonzero for debugging purposes only. */ #define VMA_DEBUG_MARGIN (0) #endif #ifndef VMA_DEBUG_GLOBAL_MUTEX /** Set this to 1 for debugging purposes only, to enable single mutex protecting all entry calls to the library. Can be useful for debugging multithreading issues. */ #define VMA_DEBUG_GLOBAL_MUTEX (0) #endif #ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY /** Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity. Set to more than 1 for debugging purposes only. Must be power of two. */ #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1) #endif #ifndef VMA_SMALL_HEAP_MAX_SIZE /// Maximum size of a memory heap in Vulkan to consider it "small". #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024) #endif #ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE /// Default size of a block allocated as single VkDeviceMemory from a "large" heap. #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024) #endif static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX; /******************************************************************************* END OF CONFIGURATION */ static VkAllocationCallbacks VmaEmptyAllocationCallbacks = { VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL }; // Returns number of bits set to 1 in (v). static inline uint32_t VmaCountBitsSet(uint32_t v) { uint32_t c = v - ((v >> 1) & 0x55555555); c = ((c >> 2) & 0x33333333) + (c & 0x33333333); c = ((c >> 4) + c) & 0x0F0F0F0F; c = ((c >> 8) + c) & 0x00FF00FF; c = ((c >> 16) + c) & 0x0000FFFF; return c; } // Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16. // Use types like uint32_t, uint64_t as T. template <typename T> static inline T VmaAlignUp(T val, T align) { return (val + align - 1) / align * align; } // Division with mathematical rounding to nearest number. template <typename T> inline T VmaRoundDiv(T x, T y) { return (x + (y / (T)2)) / y; } #ifndef VMA_SORT template<typename Iterator, typename Compare> Iterator VmaQuickSortPartition(Iterator beg, Iterator end, Compare cmp) { Iterator centerValue = end; --centerValue; Iterator insertIndex = beg; for(Iterator memTypeIndex = beg; memTypeIndex < centerValue; ++memTypeIndex) { if(cmp(*memTypeIndex, *centerValue)) { if(insertIndex != memTypeIndex) { VMA_SWAP(*memTypeIndex, *insertIndex); } ++insertIndex; } } if(insertIndex != centerValue) { VMA_SWAP(*insertIndex, *centerValue); } return insertIndex; } template<typename Iterator, typename Compare> void VmaQuickSort(Iterator beg, Iterator end, Compare cmp) { if(beg < end) { Iterator it = VmaQuickSortPartition<Iterator, Compare>(beg, end, cmp); VmaQuickSort<Iterator, Compare>(beg, it, cmp); VmaQuickSort<Iterator, Compare>(it + 1, end, cmp); } } #define VMA_SORT(beg, end, cmp) VmaQuickSort(beg, end, cmp) #endif // #ifndef VMA_SORT /* Returns true if two memory blocks occupy overlapping pages. ResourceA must be in less memory offset than ResourceB. Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)" chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity". */ static inline bool VmaBlocksOnSamePage( VkDeviceSize resourceAOffset, VkDeviceSize resourceASize, VkDeviceSize resourceBOffset, VkDeviceSize pageSize) { VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0); VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1; VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1); VkDeviceSize resourceBStart = resourceBOffset; VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1); return resourceAEndPage == resourceBStartPage; } enum VmaSuballocationType { VMA_SUBALLOCATION_TYPE_FREE = 0, VMA_SUBALLOCATION_TYPE_UNKNOWN = 1, VMA_SUBALLOCATION_TYPE_BUFFER = 2, VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3, VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4, VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5, VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF }; /* Returns true if given suballocation types could conflict and must respect VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer or linear image and another one is optimal image. If type is unknown, behave conservatively. */ static inline bool VmaIsBufferImageGranularityConflict( VmaSuballocationType suballocType1, VmaSuballocationType suballocType2) { if(suballocType1 > suballocType2) { VMA_SWAP(suballocType1, suballocType2); } switch(suballocType1) { case VMA_SUBALLOCATION_TYPE_FREE: return false; case VMA_SUBALLOCATION_TYPE_UNKNOWN: return true; case VMA_SUBALLOCATION_TYPE_BUFFER: return suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN: return suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR || suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR: return suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL: return false; default: VMA_ASSERT(0); return true; } } // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope). struct VmaMutexLock { public: VmaMutexLock(VMA_MUTEX& mutex, bool useMutex) : m_pMutex(useMutex ? &mutex : VMA_NULL) { if(m_pMutex) { m_pMutex->Lock(); } } ~VmaMutexLock() { if(m_pMutex) { m_pMutex->Unlock(); } } private: VMA_MUTEX* m_pMutex; }; #if VMA_DEBUG_GLOBAL_MUTEX static VMA_MUTEX gDebugGlobalMutex; #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true); #else #define VMA_DEBUG_GLOBAL_MUTEX_LOCK #endif // Minimum size of a free suballocation to register it in the free suballocation collection. static const VkDeviceSize VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16; /* Performs binary search and returns iterator to first element that is greater or equal to (key), according to comparison (cmp). Cmp should return true if first argument is less than second argument. Returned value is the found element, if present in the collection or place where new element with value (key) should be inserted. */ template <typename IterT, typename KeyT, typename CmpT> static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, CmpT cmp) { size_t down = 0, up = (end - beg); while(down < up) { const size_t mid = (down + up) / 2; if(cmp(*(beg+mid), key)) { down = mid + 1; } else { up = mid; } } return beg + down; } //////////////////////////////////////////////////////////////////////////////// // Memory allocation static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment) { if((pAllocationCallbacks != VMA_NULL) && (pAllocationCallbacks->pfnAllocation != VMA_NULL)) { return (*pAllocationCallbacks->pfnAllocation)( pAllocationCallbacks->pUserData, size, alignment, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); } else { return VMA_SYSTEM_ALIGNED_MALLOC(size, alignment); } } static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr) { if((pAllocationCallbacks != VMA_NULL) && (pAllocationCallbacks->pfnFree != VMA_NULL)) { (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr); } else { VMA_SYSTEM_FREE(ptr); } } template<typename T> static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks) { return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T)); } template<typename T> static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count) { return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T)); } #define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type) #define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type) template<typename T> static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr) { ptr->~T(); VmaFree(pAllocationCallbacks, ptr); } template<typename T> static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count) { if(ptr != VMA_NULL) { for(size_t i = count; i--; ) { ptr[i].~T(); } VmaFree(pAllocationCallbacks, ptr); } } // STL-compatible allocator. template<typename T> class VmaStlAllocator { public: const VkAllocationCallbacks* const m_pCallbacks; typedef T value_type; VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) { } template<typename U> VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) { } T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); } void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); } template<typename U> bool operator==(const VmaStlAllocator<U>& rhs) const { return m_pCallbacks == rhs.m_pCallbacks; } template<typename U> bool operator!=(const VmaStlAllocator<U>& rhs) const { return m_pCallbacks != rhs.m_pCallbacks; } VmaStlAllocator& operator=(const VmaStlAllocator& x) = delete; }; #if VMA_USE_STL_VECTOR #define VmaVector std::vector template<typename T, typename allocatorT> static void VmaVectorInsert(std::vector<T, allocatorT>& vec, size_t index, const T& item) { vec.insert(vec.begin() + index, item); } template<typename T, typename allocatorT> static void VmaVectorRemove(std::vector<T, allocatorT>& vec, size_t index) { vec.erase(vec.begin() + index); } #else // #if VMA_USE_STL_VECTOR /* Class with interface compatible with subset of std::vector. T must be POD because constructors and destructors are not called and memcpy is used for these objects. */ template<typename T, typename AllocatorT> class VmaVector { public: typedef T value_type; VmaVector(const AllocatorT& allocator) : m_Allocator(allocator), m_pArray(VMA_NULL), m_Count(0), m_Capacity(0) { } VmaVector(size_t count, const AllocatorT& allocator) : m_Allocator(allocator), m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL), m_Count(count), m_Capacity(count) { } VmaVector(const VmaVector<T, AllocatorT>& src) : m_Allocator(src.m_Allocator), m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL), m_Count(src.m_Count), m_Capacity(src.m_Count) { if(m_Count != 0) { memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T)); } } ~VmaVector() { VmaFree(m_Allocator.m_pCallbacks, m_pArray); } VmaVector& operator=(const VmaVector<T, AllocatorT>& rhs) { if(&rhs != this) { resize(rhs.m_Count); if(m_Count != 0) { memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T)); } } return *this; } bool empty() const { return m_Count == 0; } size_t size() const { return m_Count; } T* data() { return m_pArray; } const T* data() const { return m_pArray; } T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; } const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; } T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; } const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; } T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; } const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; } void reserve(size_t newCapacity, bool freeMemory = false) { newCapacity = VMA_MAX(newCapacity, m_Count); if((newCapacity < m_Capacity) && !freeMemory) { newCapacity = m_Capacity; } if(newCapacity != m_Capacity) { T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL; if(m_Count != 0) { memcpy(newArray, m_pArray, m_Count * sizeof(T)); } VmaFree(m_Allocator.m_pCallbacks, m_pArray); m_Capacity = newCapacity; m_pArray = newArray; } } void resize(size_t newCount, bool freeMemory = false) { size_t newCapacity = m_Capacity; if(newCount > m_Capacity) { newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8)); } else if(freeMemory) { newCapacity = newCount; } if(newCapacity != m_Capacity) { T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL; const size_t elementsToCopy = VMA_MIN(m_Count, newCount); if(elementsToCopy != 0) { memcpy(newArray, m_pArray, elementsToCopy * sizeof(T)); } VmaFree(m_Allocator.m_pCallbacks, m_pArray); m_Capacity = newCapacity; m_pArray = newArray; } m_Count = newCount; } void clear(bool freeMemory = false) { resize(0, freeMemory); } void insert(size_t index, const T& src) { VMA_HEAVY_ASSERT(index <= m_Count); const size_t oldCount = size(); resize(oldCount + 1); if(index < oldCount) { memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T)); } m_pArray[index] = src; } void remove(size_t index) { VMA_HEAVY_ASSERT(index < m_Count); const size_t oldCount = size(); if(index < oldCount - 1) { memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T)); } resize(oldCount - 1); } void push_back(const T& src) { const size_t newIndex = size(); resize(newIndex + 1); m_pArray[newIndex] = src; } void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); } void push_front(const T& src) { insert(0, src); } void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); } typedef T* iterator; iterator begin() { return m_pArray; } iterator end() { return m_pArray + m_Count; } private: AllocatorT m_Allocator; T* m_pArray; size_t m_Count; size_t m_Capacity; }; template<typename T, typename allocatorT> static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item) { vec.insert(index, item); } template<typename T, typename allocatorT> static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index) { vec.remove(index); } #endif // #if VMA_USE_STL_VECTOR template<typename CmpLess, typename VectorT> size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value) { const size_t indexToInsert = VmaBinaryFindFirstNotLess( vector.data(), vector.data() + vector.size(), value, CmpLess()) - vector.data(); VmaVectorInsert(vector, indexToInsert, value); return indexToInsert; } template<typename CmpLess, typename VectorT> bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value) { CmpLess comparator; typename VectorT::iterator it = VmaBinaryFindFirstNotLess( vector.begin(), vector.end(), value, comparator); if((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it)) { size_t indexToRemove = it - vector.begin(); VmaVectorRemove(vector, indexToRemove); return true; } return false; } template<typename CmpLess, typename VectorT> size_t VmaVectorFindSorted(const VectorT& vector, const typename VectorT::value_type& value) { CmpLess comparator; typename VectorT::iterator it = VmaBinaryFindFirstNotLess( vector.data(), vector.data() + vector.size(), value, comparator); if(it != vector.size() && !comparator(*it, value) && !comparator(value, *it)) { return it - vector.begin(); } else { return vector.size(); } } //////////////////////////////////////////////////////////////////////////////// // class VmaPoolAllocator /* Allocator for objects of type T using a list of arrays (pools) to speed up allocation. Number of elements that can be allocated is not bounded because allocator can create multiple blocks. */ template<typename T> class VmaPoolAllocator { public: VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, size_t itemsPerBlock); ~VmaPoolAllocator(); void Clear(); T* Alloc(); void Free(T* ptr); private: union Item { uint32_t NextFreeIndex; T Value; }; struct ItemBlock { Item* pItems; uint32_t FirstFreeIndex; }; const VkAllocationCallbacks* m_pAllocationCallbacks; size_t m_ItemsPerBlock; VmaVector< ItemBlock, VmaStlAllocator<ItemBlock> > m_ItemBlocks; ItemBlock& CreateNewBlock(); }; template<typename T> VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, size_t itemsPerBlock) : m_pAllocationCallbacks(pAllocationCallbacks), m_ItemsPerBlock(itemsPerBlock), m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks)) { VMA_ASSERT(itemsPerBlock > 0); } template<typename T> VmaPoolAllocator<T>::~VmaPoolAllocator() { Clear(); } template<typename T> void VmaPoolAllocator<T>::Clear() { for(size_t i = m_ItemBlocks.size(); i--; ) vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemsPerBlock); m_ItemBlocks.clear(); } template<typename T> T* VmaPoolAllocator<T>::Alloc() { for(size_t i = m_ItemBlocks.size(); i--; ) { ItemBlock& block = m_ItemBlocks[i]; // This block has some free items: Use first one. if(block.FirstFreeIndex != UINT32_MAX) { Item* const pItem = &block.pItems[block.FirstFreeIndex]; block.FirstFreeIndex = pItem->NextFreeIndex; return &pItem->Value; } } // No block has free item: Create new one and use it. ItemBlock& newBlock = CreateNewBlock(); Item* const pItem = &newBlock.pItems[0]; newBlock.FirstFreeIndex = pItem->NextFreeIndex; return &pItem->Value; } template<typename T> void VmaPoolAllocator<T>::Free(T* ptr) { // Search all memory blocks to find ptr. for(size_t i = 0; i < m_ItemBlocks.size(); ++i) { ItemBlock& block = m_ItemBlocks[i]; // Casting to union. Item* pItemPtr; memcpy(&pItemPtr, &ptr, sizeof(pItemPtr)); // Check if pItemPtr is in address range of this block. if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + m_ItemsPerBlock)) { const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems); pItemPtr->NextFreeIndex = block.FirstFreeIndex; block.FirstFreeIndex = index; return; } } VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool."); } template<typename T> typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock() { ItemBlock newBlock = { vma_new_array(m_pAllocationCallbacks, Item, m_ItemsPerBlock), 0 }; m_ItemBlocks.push_back(newBlock); // Setup singly-linked list of all free items in this block. for(uint32_t i = 0; i < m_ItemsPerBlock - 1; ++i) newBlock.pItems[i].NextFreeIndex = i + 1; newBlock.pItems[m_ItemsPerBlock - 1].NextFreeIndex = UINT32_MAX; return m_ItemBlocks.back(); } //////////////////////////////////////////////////////////////////////////////// // class VmaRawList, VmaList #if VMA_USE_STL_LIST #define VmaList std::list #else // #if VMA_USE_STL_LIST template<typename T> struct VmaListItem { VmaListItem* pPrev; VmaListItem* pNext; T Value; }; // Doubly linked list. template<typename T> class VmaRawList { public: typedef VmaListItem<T> ItemType; VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks); ~VmaRawList(); void Clear(); size_t GetCount() const { return m_Count; } bool IsEmpty() const { return m_Count == 0; } ItemType* Front() { return m_pFront; } const ItemType* Front() const { return m_pFront; } ItemType* Back() { return m_pBack; } const ItemType* Back() const { return m_pBack; } ItemType* PushBack(); ItemType* PushFront(); ItemType* PushBack(const T& value); ItemType* PushFront(const T& value); void PopBack(); void PopFront(); // Item can be null - it means PushBack. ItemType* InsertBefore(ItemType* pItem); // Item can be null - it means PushFront. ItemType* InsertAfter(ItemType* pItem); ItemType* InsertBefore(ItemType* pItem, const T& value); ItemType* InsertAfter(ItemType* pItem, const T& value); void Remove(ItemType* pItem); private: const VkAllocationCallbacks* const m_pAllocationCallbacks; VmaPoolAllocator<ItemType> m_ItemAllocator; ItemType* m_pFront; ItemType* m_pBack; size_t m_Count; // Declared not defined, to block copy constructor and assignment operator. VmaRawList(const VmaRawList<T>& src); VmaRawList<T>& operator=(const VmaRawList<T>& rhs); }; template<typename T> VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) : m_pAllocationCallbacks(pAllocationCallbacks), m_ItemAllocator(pAllocationCallbacks, 128), m_pFront(VMA_NULL), m_pBack(VMA_NULL), m_Count(0) { } template<typename T> VmaRawList<T>::~VmaRawList() { // Intentionally not calling Clear, because that would be unnecessary // computations to return all items to m_ItemAllocator as free. } template<typename T> void VmaRawList<T>::Clear() { if(IsEmpty() == false) { ItemType* pItem = m_pBack; while(pItem != VMA_NULL) { ItemType* const pPrevItem = pItem->pPrev; m_ItemAllocator.Free(pItem); pItem = pPrevItem; } m_pFront = VMA_NULL; m_pBack = VMA_NULL; m_Count = 0; } } template<typename T> VmaListItem<T>* VmaRawList<T>::PushBack() { ItemType* const pNewItem = m_ItemAllocator.Alloc(); pNewItem->pNext = VMA_NULL; if(IsEmpty()) { pNewItem->pPrev = VMA_NULL; m_pFront = pNewItem; m_pBack = pNewItem; m_Count = 1; } else { pNewItem->pPrev = m_pBack; m_pBack->pNext = pNewItem; m_pBack = pNewItem; ++m_Count; } return pNewItem; } template<typename T> VmaListItem<T>* VmaRawList<T>::PushFront() { ItemType* const pNewItem = m_ItemAllocator.Alloc(); pNewItem->pPrev = VMA_NULL; if(IsEmpty()) { pNewItem->pNext = VMA_NULL; m_pFront = pNewItem; m_pBack = pNewItem; m_Count = 1; } else { pNewItem->pNext = m_pFront; m_pFront->pPrev = pNewItem; m_pFront = pNewItem; ++m_Count; } return pNewItem; } template<typename T> VmaListItem<T>* VmaRawList<T>::PushBack(const T& value) { ItemType* const pNewItem = PushBack(); pNewItem->Value = value; return pNewItem; } template<typename T> VmaListItem<T>* VmaRawList<T>::PushFront(const T& value) { ItemType* const pNewItem = PushFront(); pNewItem->Value = value; return pNewItem; } template<typename T> void VmaRawList<T>::PopBack() { VMA_HEAVY_ASSERT(m_Count > 0); ItemType* const pBackItem = m_pBack; ItemType* const pPrevItem = pBackItem->pPrev; if(pPrevItem != VMA_NULL) { pPrevItem->pNext = VMA_NULL; } m_pBack = pPrevItem; m_ItemAllocator.Free(pBackItem); --m_Count; } template<typename T> void VmaRawList<T>::PopFront() { VMA_HEAVY_ASSERT(m_Count > 0); ItemType* const pFrontItem = m_pFront; ItemType* const pNextItem = pFrontItem->pNext; if(pNextItem != VMA_NULL) { pNextItem->pPrev = VMA_NULL; } m_pFront = pNextItem; m_ItemAllocator.Free(pFrontItem); --m_Count; } template<typename T> void VmaRawList<T>::Remove(ItemType* pItem) { VMA_HEAVY_ASSERT(pItem != VMA_NULL); VMA_HEAVY_ASSERT(m_Count > 0); if(pItem->pPrev != VMA_NULL) { pItem->pPrev->pNext = pItem->pNext; } else { VMA_HEAVY_ASSERT(m_pFront == pItem); m_pFront = pItem->pNext; } if(pItem->pNext != VMA_NULL) { pItem->pNext->pPrev = pItem->pPrev; } else { VMA_HEAVY_ASSERT(m_pBack == pItem); m_pBack = pItem->pPrev; } m_ItemAllocator.Free(pItem); --m_Count; } template<typename T> VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem) { if(pItem != VMA_NULL) { ItemType* const prevItem = pItem->pPrev; ItemType* const newItem = m_ItemAllocator.Alloc(); newItem->pPrev = prevItem; newItem->pNext = pItem; pItem->pPrev = newItem; if(prevItem != VMA_NULL) { prevItem->pNext = newItem; } else { VMA_HEAVY_ASSERT(m_pFront == pItem); m_pFront = newItem; } ++m_Count; return newItem; } else return PushBack(); } template<typename T> VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem) { if(pItem != VMA_NULL) { ItemType* const nextItem = pItem->pNext; ItemType* const newItem = m_ItemAllocator.Alloc(); newItem->pNext = nextItem; newItem->pPrev = pItem; pItem->pNext = newItem; if(nextItem != VMA_NULL) { nextItem->pPrev = newItem; } else { VMA_HEAVY_ASSERT(m_pBack == pItem); m_pBack = newItem; } ++m_Count; return newItem; } else return PushFront(); } template<typename T> VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value) { ItemType* const newItem = InsertBefore(pItem); newItem->Value = value; return newItem; } template<typename T> VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value) { ItemType* const newItem = InsertAfter(pItem); newItem->Value = value; return newItem; } template<typename T, typename AllocatorT> class VmaList { public: class iterator { public: iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) { } T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; } iterator& operator--() { if(m_pItem != VMA_NULL) { m_pItem = m_pItem->pPrev; } else { VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); m_pItem = m_pList->Back(); } return *this; } iterator operator++(int) { iterator result = *this; ++*this; return result; } iterator operator--(int) { iterator result = *this; --*this; return result; } bool operator==(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } bool operator!=(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } private: VmaRawList<T>* m_pList; VmaListItem<T>* m_pItem; iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) { } friend class VmaList<T, AllocatorT>; }; class const_iterator { public: const_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) { } const_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) { } const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } const_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; } const_iterator& operator--() { if(m_pItem != VMA_NULL) { m_pItem = m_pItem->pPrev; } else { VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); m_pItem = m_pList->Back(); } return *this; } const_iterator operator++(int) { const_iterator result = *this; ++*this; return result; } const_iterator operator--(int) { const_iterator result = *this; --*this; return result; } bool operator==(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } bool operator!=(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } private: const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) { } const VmaRawList<T>* m_pList; const VmaListItem<T>* m_pItem; friend class VmaList<T, AllocatorT>; }; VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) { } bool empty() const { return m_RawList.IsEmpty(); } size_t size() const { return m_RawList.GetCount(); } iterator begin() { return iterator(&m_RawList, m_RawList.Front()); } iterator end() { return iterator(&m_RawList, VMA_NULL); } const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); } const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); } void clear() { m_RawList.Clear(); } void push_back(const T& value) { m_RawList.PushBack(value); } void erase(iterator it) { m_RawList.Remove(it.m_pItem); } iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); } private: VmaRawList<T> m_RawList; }; #endif // #if VMA_USE_STL_LIST //////////////////////////////////////////////////////////////////////////////// // class VmaMap // Unused in this version. #if 0 #if VMA_USE_STL_UNORDERED_MAP #define VmaPair std::pair #define VMA_MAP_TYPE(KeyT, ValueT) \ std::unordered_map< KeyT, ValueT, std::hash<KeyT>, std::equal_to<KeyT>, VmaStlAllocator< std::pair<KeyT, ValueT> > > #else // #if VMA_USE_STL_UNORDERED_MAP template<typename T1, typename T2> struct VmaPair { T1 first; T2 second; VmaPair() : first(), second() { } VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) { } }; /* Class compatible with subset of interface of std::unordered_map. KeyT, ValueT must be POD because they will be stored in VmaVector. */ template<typename KeyT, typename ValueT> class VmaMap { public: typedef VmaPair<KeyT, ValueT> PairType; typedef PairType* iterator; VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) { } iterator begin() { return m_Vector.begin(); } iterator end() { return m_Vector.end(); } void insert(const PairType& pair); iterator find(const KeyT& key); void erase(iterator it); private: VmaVector< PairType, VmaStlAllocator<PairType> > m_Vector; }; #define VMA_MAP_TYPE(KeyT, ValueT) VmaMap<KeyT, ValueT> template<typename FirstT, typename SecondT> struct VmaPairFirstLess { bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const { return lhs.first < rhs.first; } bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const { return lhs.first < rhsFirst; } }; template<typename KeyT, typename ValueT> void VmaMap<KeyT, ValueT>::insert(const PairType& pair) { const size_t indexToInsert = VmaBinaryFindFirstNotLess( m_Vector.data(), m_Vector.data() + m_Vector.size(), pair, VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data(); VmaVectorInsert(m_Vector, indexToInsert, pair); } template<typename KeyT, typename ValueT> VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key) { PairType* it = VmaBinaryFindFirstNotLess( m_Vector.data(), m_Vector.data() + m_Vector.size(), key, VmaPairFirstLess<KeyT, ValueT>()); if((it != m_Vector.end()) && (it->first == key)) { return it; } else { return m_Vector.end(); } } template<typename KeyT, typename ValueT> void VmaMap<KeyT, ValueT>::erase(iterator it) { VmaVectorRemove(m_Vector, it - m_Vector.begin()); } #endif // #if VMA_USE_STL_UNORDERED_MAP #endif // #if 0 //////////////////////////////////////////////////////////////////////////////// class VmaDeviceMemoryBlock; struct VmaAllocation_T { private: static const uint8_t MAP_COUNT_FLAG_PERSISTENT_MAP = 0x80; enum FLAGS { FLAG_USER_DATA_STRING = 0x01, }; public: enum ALLOCATION_TYPE { ALLOCATION_TYPE_NONE, ALLOCATION_TYPE_BLOCK, ALLOCATION_TYPE_DEDICATED, }; VmaAllocation_T(uint32_t currentFrameIndex, bool userDataString) : m_Alignment(1), m_Size(0), m_pUserData(VMA_NULL), m_LastUseFrameIndex(currentFrameIndex), m_Type((uint8_t)ALLOCATION_TYPE_NONE), m_SuballocationType((uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN), m_MapCount(0), m_Flags(userDataString ? (uint8_t)FLAG_USER_DATA_STRING : 0) { } ~VmaAllocation_T() { VMA_ASSERT((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) == 0 && "Allocation was not unmapped before destruction."); // Check if owned string was freed. VMA_ASSERT(m_pUserData == VMA_NULL); } void InitBlockAllocation( VmaPool hPool, VmaDeviceMemoryBlock* block, VkDeviceSize offset, VkDeviceSize alignment, VkDeviceSize size, VmaSuballocationType suballocationType, bool mapped, bool canBecomeLost) { VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); VMA_ASSERT(block != VMA_NULL); m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; m_Alignment = alignment; m_Size = size; m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0; m_SuballocationType = (uint8_t)suballocationType; m_BlockAllocation.m_hPool = hPool; m_BlockAllocation.m_Block = block; m_BlockAllocation.m_Offset = offset; m_BlockAllocation.m_CanBecomeLost = canBecomeLost; } void InitLost() { VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); VMA_ASSERT(m_LastUseFrameIndex.load() == VMA_FRAME_INDEX_LOST); m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; m_BlockAllocation.m_hPool = VK_NULL_HANDLE; m_BlockAllocation.m_Block = VMA_NULL; m_BlockAllocation.m_Offset = 0; m_BlockAllocation.m_CanBecomeLost = true; } void ChangeBlockAllocation( VmaAllocator hAllocator, VmaDeviceMemoryBlock* block, VkDeviceSize offset); // pMappedData not null means allocation is created with MAPPED flag. void InitDedicatedAllocation( uint32_t memoryTypeIndex, VkDeviceMemory hMemory, VmaSuballocationType suballocationType, void* pMappedData, VkDeviceSize size) { VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); VMA_ASSERT(hMemory != VK_NULL_HANDLE); m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED; m_Alignment = 0; m_Size = size; m_SuballocationType = (uint8_t)suballocationType; m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0; m_DedicatedAllocation.m_MemoryTypeIndex = memoryTypeIndex; m_DedicatedAllocation.m_hMemory = hMemory; m_DedicatedAllocation.m_pMappedData = pMappedData; } ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; } VkDeviceSize GetAlignment() const { return m_Alignment; } VkDeviceSize GetSize() const { return m_Size; } bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; } void* GetUserData() const { return m_pUserData; } void SetUserData(VmaAllocator hAllocator, void* pUserData); VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; } VmaDeviceMemoryBlock* GetBlock() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_Block; } VkDeviceSize GetOffset() const; VkDeviceMemory GetMemory() const; uint32_t GetMemoryTypeIndex() const; bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; } void* GetMappedData() const; bool CanBecomeLost() const; VmaPool GetPool() const; uint32_t GetLastUseFrameIndex() const { return m_LastUseFrameIndex.load(); } bool CompareExchangeLastUseFrameIndex(uint32_t& expected, uint32_t desired) { return m_LastUseFrameIndex.compare_exchange_weak(expected, desired); } /* - If hAllocation.LastUseFrameIndex + frameInUseCount < allocator.CurrentFrameIndex, makes it lost by setting LastUseFrameIndex = VMA_FRAME_INDEX_LOST and returns true. - Else, returns false. If hAllocation is already lost, assert - you should not call it then. If hAllocation was not created with CAN_BECOME_LOST_BIT, assert. */ bool MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); void DedicatedAllocCalcStatsInfo(VmaStatInfo& outInfo) { VMA_ASSERT(m_Type == ALLOCATION_TYPE_DEDICATED); outInfo.blockCount = 1; outInfo.allocationCount = 1; outInfo.unusedRangeCount = 0; outInfo.usedBytes = m_Size; outInfo.unusedBytes = 0; outInfo.allocationSizeMin = outInfo.allocationSizeMax = m_Size; outInfo.unusedRangeSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMax = 0; } void BlockAllocMap(); void BlockAllocUnmap(); VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData); void DedicatedAllocUnmap(VmaAllocator hAllocator); private: VkDeviceSize m_Alignment; VkDeviceSize m_Size; void* m_pUserData; VMA_ATOMIC_UINT32 m_LastUseFrameIndex; uint8_t m_Type; // ALLOCATION_TYPE uint8_t m_SuballocationType; // VmaSuballocationType // Bit 0x80 is set when allocation was created with VMA_ALLOCATION_CREATE_MAPPED_BIT. // Bits with mask 0x7F are reference counter for vmaMapMemory()/vmaUnmapMemory(). uint8_t m_MapCount; uint8_t m_Flags; // enum FLAGS // Allocation out of VmaDeviceMemoryBlock. struct BlockAllocation { VmaPool m_hPool; // Null if belongs to general memory. VmaDeviceMemoryBlock* m_Block; VkDeviceSize m_Offset; bool m_CanBecomeLost; }; // Allocation for an object that has its own private VkDeviceMemory. struct DedicatedAllocation { uint32_t m_MemoryTypeIndex; VkDeviceMemory m_hMemory; void* m_pMappedData; // Not null means memory is mapped. }; union { // Allocation out of VmaDeviceMemoryBlock. BlockAllocation m_BlockAllocation; // Allocation for an object that has its own private VkDeviceMemory. DedicatedAllocation m_DedicatedAllocation; }; void FreeUserDataString(VmaAllocator hAllocator); }; /* Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as allocated memory block or free. */ struct VmaSuballocation { VkDeviceSize offset; VkDeviceSize size; VmaAllocation hAllocation; VmaSuballocationType type; }; typedef VmaList< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > VmaSuballocationList; // Cost of one additional allocation lost, as equivalent in bytes. static const VkDeviceSize VMA_LOST_ALLOCATION_COST = 1048576; /* Parameters of planned allocation inside a VmaDeviceMemoryBlock. If canMakeOtherLost was false: - item points to a FREE suballocation. - itemsToMakeLostCount is 0. If canMakeOtherLost was true: - item points to first of sequence of suballocations, which are either FREE, or point to VmaAllocations that can become lost. - itemsToMakeLostCount is the number of VmaAllocations that need to be made lost for the requested allocation to succeed. */ struct VmaAllocationRequest { VkDeviceSize offset; VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation. VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation. VmaSuballocationList::iterator item; size_t itemsToMakeLostCount; VkDeviceSize CalcCost() const { return sumItemSize + itemsToMakeLostCount * VMA_LOST_ALLOCATION_COST; } }; /* Data structure used for bookkeeping of allocations and unused ranges of memory in a single VkDeviceMemory block. */ class VmaBlockMetadata { public: VmaBlockMetadata(VmaAllocator hAllocator); ~VmaBlockMetadata(); void Init(VkDeviceSize size); // Validates all data structures inside this object. If not valid, returns false. bool Validate() const; VkDeviceSize GetSize() const { return m_Size; } size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; } VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; } VkDeviceSize GetUnusedRangeSizeMax() const; // Returns true if this block is empty - contains only single free suballocation. bool IsEmpty() const; void CalcAllocationStatInfo(VmaStatInfo& outInfo) const; void AddPoolStats(VmaPoolStats& inoutStats) const; #if VMA_STATS_STRING_ENABLED void PrintDetailedMap(class VmaJsonWriter& json) const; #endif // Creates trivial request for case when block is empty. void CreateFirstAllocationRequest(VmaAllocationRequest* pAllocationRequest); // Tries to find a place for suballocation with given parameters inside this block. // If succeeded, fills pAllocationRequest and returns true. // If failed, returns false. bool CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, VmaSuballocationType allocType, bool canMakeOtherLost, VmaAllocationRequest* pAllocationRequest); bool MakeRequestedAllocationsLost( uint32_t currentFrameIndex, uint32_t frameInUseCount, VmaAllocationRequest* pAllocationRequest); uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); // Makes actual allocation based on request. Request must already be checked and valid. void Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, VmaAllocation hAllocation); // Frees suballocation assigned to given memory region. void Free(const VmaAllocation allocation); void FreeAtOffset(VkDeviceSize offset); private: VkDeviceSize m_Size; uint32_t m_FreeCount; VkDeviceSize m_SumFreeSize; VmaSuballocationList m_Suballocations; // Suballocations that are free and have size greater than certain threshold. // Sorted by size, ascending. VmaVector< VmaSuballocationList::iterator, VmaStlAllocator< VmaSuballocationList::iterator > > m_FreeSuballocationsBySize; bool ValidateFreeSuballocationList() const; // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem. // If yes, fills pOffset and returns true. If no, returns false. bool CheckAllocation( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, VmaSuballocationType allocType, VmaSuballocationList::const_iterator suballocItem, bool canMakeOtherLost, VkDeviceSize* pOffset, size_t* itemsToMakeLostCount, VkDeviceSize* pSumFreeSize, VkDeviceSize* pSumItemSize) const; // Given free suballocation, it merges it with following one, which must also be free. void MergeFreeWithNext(VmaSuballocationList::iterator item); // Releases given suballocation, making it free. // Merges it with adjacent free suballocations if applicable. // Returns iterator to new free suballocation at this place. VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem); // Given free suballocation, it inserts it into sorted list of // m_FreeSuballocationsBySize if it's suitable. void RegisterFreeSuballocation(VmaSuballocationList::iterator item); // Given free suballocation, it removes it from sorted list of // m_FreeSuballocationsBySize if it's suitable. void UnregisterFreeSuballocation(VmaSuballocationList::iterator item); }; // Helper class that represents mapped memory. Synchronized internally. class VmaDeviceMemoryMapping { public: VmaDeviceMemoryMapping(); ~VmaDeviceMemoryMapping(); void* GetMappedData() const { return m_pMappedData; } // ppData can be null. VkResult Map(VmaAllocator hAllocator, VkDeviceMemory hMemory, uint32_t count, void **ppData); void Unmap(VmaAllocator hAllocator, VkDeviceMemory hMemory, uint32_t count); private: VMA_MUTEX m_Mutex; uint32_t m_MapCount; void* m_pMappedData; }; /* Represents a single block of device memory (`VkDeviceMemory`) with all the data about its regions (aka suballocations, `VmaAllocation`), assigned and free. Thread-safety: This class must be externally synchronized. */ class VmaDeviceMemoryBlock { public: uint32_t m_MemoryTypeIndex; VkDeviceMemory m_hMemory; VmaDeviceMemoryMapping m_Mapping; VmaBlockMetadata m_Metadata; VmaDeviceMemoryBlock(VmaAllocator hAllocator); ~VmaDeviceMemoryBlock() { VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); } // Always call after construction. void Init( uint32_t newMemoryTypeIndex, VkDeviceMemory newMemory, VkDeviceSize newSize); // Always call before destruction. void Destroy(VmaAllocator allocator); // Validates all data structures inside this object. If not valid, returns false. bool Validate() const; // ppData can be null. VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData); void Unmap(VmaAllocator hAllocator, uint32_t count); }; struct VmaPointerLess { bool operator()(const void* lhs, const void* rhs) const { return lhs < rhs; } }; class VmaDefragmentator; /* Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific Vulkan memory type. Synchronized internally with a mutex. */ struct VmaBlockVector { VmaBlockVector( VmaAllocator hAllocator, uint32_t memoryTypeIndex, VkDeviceSize preferredBlockSize, size_t minBlockCount, size_t maxBlockCount, VkDeviceSize bufferImageGranularity, uint32_t frameInUseCount, bool isCustomPool); ~VmaBlockVector(); VkResult CreateMinBlocks(); uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; } VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; } uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; } void GetPoolStats(VmaPoolStats* pStats); bool IsEmpty() const { return m_Blocks.empty(); } VkResult Allocate( VmaPool hCurrentPool, uint32_t currentFrameIndex, const VkMemoryRequirements& vkMemReq, const VmaAllocationCreateInfo& createInfo, VmaSuballocationType suballocType, VmaAllocation* pAllocation); void Free( VmaAllocation hAllocation); // Adds statistics of this BlockVector to pStats. void AddStats(VmaStats* pStats); #if VMA_STATS_STRING_ENABLED void PrintDetailedMap(class VmaJsonWriter& json); #endif void MakePoolAllocationsLost( uint32_t currentFrameIndex, size_t* pLostAllocationCount); VmaDefragmentator* EnsureDefragmentator( VmaAllocator hAllocator, uint32_t currentFrameIndex); VkResult Defragment( VmaDefragmentationStats* pDefragmentationStats, VkDeviceSize& maxBytesToMove, uint32_t& maxAllocationsToMove); void DestroyDefragmentator(); private: friend class VmaDefragmentator; const VmaAllocator m_hAllocator; const uint32_t m_MemoryTypeIndex; const VkDeviceSize m_PreferredBlockSize; const size_t m_MinBlockCount; const size_t m_MaxBlockCount; const VkDeviceSize m_BufferImageGranularity; const uint32_t m_FrameInUseCount; const bool m_IsCustomPool; VMA_MUTEX m_Mutex; // Incrementally sorted by sumFreeSize, ascending. VmaVector< VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*> > m_Blocks; /* There can be at most one allocation that is completely empty - a hysteresis to avoid pessimistic case of alternating creation and destruction of a VkDeviceMemory. */ bool m_HasEmptyBlock; VmaDefragmentator* m_pDefragmentator; size_t CalcMaxBlockSize() const; // Finds and removes given block from vector. void Remove(VmaDeviceMemoryBlock* pBlock); // Performs single step in sorting m_Blocks. They may not be fully sorted // after this call. void IncrementallySortBlocks(); VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex); }; struct VmaPool_T { public: VmaBlockVector m_BlockVector; // Takes ownership. VmaPool_T( VmaAllocator hAllocator, const VmaPoolCreateInfo& createInfo); ~VmaPool_T(); VmaBlockVector& GetBlockVector() { return m_BlockVector; } #if VMA_STATS_STRING_ENABLED //void PrintDetailedMap(class VmaStringBuilder& sb); #endif }; class VmaDefragmentator { const VmaAllocator m_hAllocator; VmaBlockVector* const m_pBlockVector; uint32_t m_CurrentFrameIndex; VkDeviceSize m_BytesMoved; uint32_t m_AllocationsMoved; struct AllocationInfo { VmaAllocation m_hAllocation; VkBool32* m_pChanged; AllocationInfo() : m_hAllocation(VK_NULL_HANDLE), m_pChanged(VMA_NULL) { } }; struct AllocationInfoSizeGreater { bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const { return lhs.m_hAllocation->GetSize() > rhs.m_hAllocation->GetSize(); } }; // Used between AddAllocation and Defragment. VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations; struct BlockInfo { VmaDeviceMemoryBlock* m_pBlock; bool m_HasNonMovableAllocations; VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations; BlockInfo(const VkAllocationCallbacks* pAllocationCallbacks) : m_pBlock(VMA_NULL), m_HasNonMovableAllocations(true), m_Allocations(pAllocationCallbacks), m_pMappedDataForDefragmentation(VMA_NULL) { } void CalcHasNonMovableAllocations() { const size_t blockAllocCount = m_pBlock->m_Metadata.GetAllocationCount(); const size_t defragmentAllocCount = m_Allocations.size(); m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount; } void SortAllocationsBySizeDescecnding() { VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoSizeGreater()); } VkResult EnsureMapping(VmaAllocator hAllocator, void** ppMappedData); void Unmap(VmaAllocator hAllocator); private: // Not null if mapped for defragmentation only, not originally mapped. void* m_pMappedDataForDefragmentation; }; struct BlockPointerLess { bool operator()(const BlockInfo* pLhsBlockInfo, const VmaDeviceMemoryBlock* pRhsBlock) const { return pLhsBlockInfo->m_pBlock < pRhsBlock; } bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const { return pLhsBlockInfo->m_pBlock < pRhsBlockInfo->m_pBlock; } }; // 1. Blocks with some non-movable allocations go first. // 2. Blocks with smaller sumFreeSize go first. struct BlockInfoCompareMoveDestination { bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const { if(pLhsBlockInfo->m_HasNonMovableAllocations && !pRhsBlockInfo->m_HasNonMovableAllocations) { return true; } if(!pLhsBlockInfo->m_HasNonMovableAllocations && pRhsBlockInfo->m_HasNonMovableAllocations) { return false; } if(pLhsBlockInfo->m_pBlock->m_Metadata.GetSumFreeSize() < pRhsBlockInfo->m_pBlock->m_Metadata.GetSumFreeSize()) { return true; } return false; } }; typedef VmaVector< BlockInfo*, VmaStlAllocator<BlockInfo*> > BlockInfoVector; BlockInfoVector m_Blocks; VkResult DefragmentRound( VkDeviceSize maxBytesToMove, uint32_t maxAllocationsToMove); static bool MoveMakesSense( size_t dstBlockIndex, VkDeviceSize dstOffset, size_t srcBlockIndex, VkDeviceSize srcOffset); public: VmaDefragmentator( VmaAllocator hAllocator, VmaBlockVector* pBlockVector, uint32_t currentFrameIndex); ~VmaDefragmentator(); VkDeviceSize GetBytesMoved() const { return m_BytesMoved; } uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; } void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged); VkResult Defragment( VkDeviceSize maxBytesToMove, uint32_t maxAllocationsToMove); }; // Main allocator object. struct VmaAllocator_T { bool m_UseMutex; bool m_UseKhrDedicatedAllocation; VkDevice m_hDevice; bool m_AllocationCallbacksSpecified; VkAllocationCallbacks m_AllocationCallbacks; VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks; // Number of bytes free out of limit, or VK_WHOLE_SIZE if not limit for that heap. VkDeviceSize m_HeapSizeLimit[VK_MAX_MEMORY_HEAPS]; VMA_MUTEX m_HeapSizeLimitMutex; VkPhysicalDeviceProperties m_PhysicalDeviceProperties; VkPhysicalDeviceMemoryProperties m_MemProps; // Default pools. VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES]; // Each vector is sorted by memory (handle value). typedef VmaVector< VmaAllocation, VmaStlAllocator<VmaAllocation> > AllocationVectorType; AllocationVectorType* m_pDedicatedAllocations[VK_MAX_MEMORY_TYPES]; VMA_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES]; VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo); ~VmaAllocator_T(); const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : 0; } const VmaVulkanFunctions& GetVulkanFunctions() const { return m_VulkanFunctions; } VkDeviceSize GetBufferImageGranularity() const { return VMA_MAX( static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY), m_PhysicalDeviceProperties.limits.bufferImageGranularity); } uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; } uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; } uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const { VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount); return m_MemProps.memoryTypes[memTypeIndex].heapIndex; } void GetBufferMemoryRequirements( VkBuffer hBuffer, VkMemoryRequirements& memReq, bool& requiresDedicatedAllocation, bool& prefersDedicatedAllocation) const; void GetImageMemoryRequirements( VkImage hImage, VkMemoryRequirements& memReq, bool& requiresDedicatedAllocation, bool& prefersDedicatedAllocation) const; // Main allocation function. VkResult AllocateMemory( const VkMemoryRequirements& vkMemReq, bool requiresDedicatedAllocation, bool prefersDedicatedAllocation, VkBuffer dedicatedBuffer, VkImage dedicatedImage, const VmaAllocationCreateInfo& createInfo, VmaSuballocationType suballocType, VmaAllocation* pAllocation); // Main deallocation function. void FreeMemory(const VmaAllocation allocation); void CalculateStats(VmaStats* pStats); #if VMA_STATS_STRING_ENABLED void PrintDetailedMap(class VmaJsonWriter& json); #endif VkResult Defragment( VmaAllocation* pAllocations, size_t allocationCount, VkBool32* pAllocationsChanged, const VmaDefragmentationInfo* pDefragmentationInfo, VmaDefragmentationStats* pDefragmentationStats); void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo); VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool); void DestroyPool(VmaPool pool); void GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats); void SetCurrentFrameIndex(uint32_t frameIndex); void MakePoolAllocationsLost( VmaPool hPool, size_t* pLostAllocationCount); void CreateLostAllocation(VmaAllocation* pAllocation); VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory); void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory); VkResult Map(VmaAllocation hAllocation, void** ppData); void Unmap(VmaAllocation hAllocation); private: VkDeviceSize m_PreferredLargeHeapBlockSize; VkPhysicalDevice m_PhysicalDevice; VMA_ATOMIC_UINT32 m_CurrentFrameIndex; VMA_MUTEX m_PoolsMutex; // Protected by m_PoolsMutex. Sorted by pointer value. VmaVector<VmaPool, VmaStlAllocator<VmaPool> > m_Pools; VmaVulkanFunctions m_VulkanFunctions; void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions); VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex); VkResult AllocateMemoryOfType( const VkMemoryRequirements& vkMemReq, bool dedicatedAllocation, VkBuffer dedicatedBuffer, VkImage dedicatedImage, const VmaAllocationCreateInfo& createInfo, uint32_t memTypeIndex, VmaSuballocationType suballocType, VmaAllocation* pAllocation); // Allocates and registers new VkDeviceMemory specifically for single allocation. VkResult AllocateDedicatedMemory( VkDeviceSize size, VmaSuballocationType suballocType, uint32_t memTypeIndex, bool map, bool isUserDataString, void* pUserData, VkBuffer dedicatedBuffer, VkImage dedicatedImage, VmaAllocation* pAllocation); // Tries to free pMemory as Dedicated Memory. Returns true if found and freed. void FreeDedicatedMemory(VmaAllocation allocation); }; //////////////////////////////////////////////////////////////////////////////// // Memory allocation #2 after VmaAllocator_T definition static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment) { return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment); } static void VmaFree(VmaAllocator hAllocator, void* ptr) { VmaFree(&hAllocator->m_AllocationCallbacks, ptr); } template<typename T> static T* VmaAllocate(VmaAllocator hAllocator) { return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T)); } template<typename T> static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count) { return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T)); } template<typename T> static void vma_delete(VmaAllocator hAllocator, T* ptr) { if(ptr != VMA_NULL) { ptr->~T(); VmaFree(hAllocator, ptr); } } template<typename T> static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count) { if(ptr != VMA_NULL) { for(size_t i = count; i--; ) ptr[i].~T(); VmaFree(hAllocator, ptr); } } //////////////////////////////////////////////////////////////////////////////// // VmaStringBuilder #if VMA_STATS_STRING_ENABLED class VmaStringBuilder { public: VmaStringBuilder(VmaAllocator alloc) : m_Data(VmaStlAllocator<char>(alloc->GetAllocationCallbacks())) { } size_t GetLength() const { return m_Data.size(); } const char* GetData() const { return m_Data.data(); } void Add(char ch) { m_Data.push_back(ch); } void Add(const char* pStr); void AddNewLine() { Add('\n'); } void AddNumber(uint32_t num); void AddNumber(uint64_t num); void AddPointer(const void* ptr); private: VmaVector< char, VmaStlAllocator<char> > m_Data; }; void VmaStringBuilder::Add(const char* pStr) { const size_t strLen = strlen(pStr); if(strLen > 0) { const size_t oldCount = m_Data.size(); m_Data.resize(oldCount + strLen); memcpy(m_Data.data() + oldCount, pStr, strLen); } } void VmaStringBuilder::AddNumber(uint32_t num) { char buf[11]; VmaUint32ToStr(buf, sizeof(buf), num); Add(buf); } void VmaStringBuilder::AddNumber(uint64_t num) { char buf[21]; VmaUint64ToStr(buf, sizeof(buf), num); Add(buf); } void VmaStringBuilder::AddPointer(const void* ptr) { char buf[21]; VmaPtrToStr(buf, sizeof(buf), ptr); Add(buf); } #endif // #if VMA_STATS_STRING_ENABLED //////////////////////////////////////////////////////////////////////////////// // VmaJsonWriter #if VMA_STATS_STRING_ENABLED class VmaJsonWriter { public: VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb); ~VmaJsonWriter(); void BeginObject(bool singleLine = false); void EndObject(); void BeginArray(bool singleLine = false); void EndArray(); void WriteString(const char* pStr); void BeginString(const char* pStr = VMA_NULL); void ContinueString(const char* pStr); void ContinueString(uint32_t n); void ContinueString(uint64_t n); void ContinueString_Pointer(const void* ptr); void EndString(const char* pStr = VMA_NULL); void WriteNumber(uint32_t n); void WriteNumber(uint64_t n); void WriteBool(bool b); void WriteNull(); private: static const char* const INDENT; enum COLLECTION_TYPE { COLLECTION_TYPE_OBJECT, COLLECTION_TYPE_ARRAY, }; struct StackItem { COLLECTION_TYPE type; uint32_t valueCount; bool singleLineMode; }; VmaStringBuilder& m_SB; VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack; bool m_InsideString; void BeginValue(bool isString); void WriteIndent(bool oneLess = false); }; const char* const VmaJsonWriter::INDENT = " "; VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) : m_SB(sb), m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)), m_InsideString(false) { } VmaJsonWriter::~VmaJsonWriter() { VMA_ASSERT(!m_InsideString); VMA_ASSERT(m_Stack.empty()); } void VmaJsonWriter::BeginObject(bool singleLine) { VMA_ASSERT(!m_InsideString); BeginValue(false); m_SB.Add('{'); StackItem item; item.type = COLLECTION_TYPE_OBJECT; item.valueCount = 0; item.singleLineMode = singleLine; m_Stack.push_back(item); } void VmaJsonWriter::EndObject() { VMA_ASSERT(!m_InsideString); WriteIndent(true); m_SB.Add('}'); VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT); m_Stack.pop_back(); } void VmaJsonWriter::BeginArray(bool singleLine) { VMA_ASSERT(!m_InsideString); BeginValue(false); m_SB.Add('['); StackItem item; item.type = COLLECTION_TYPE_ARRAY; item.valueCount = 0; item.singleLineMode = singleLine; m_Stack.push_back(item); } void VmaJsonWriter::EndArray() { VMA_ASSERT(!m_InsideString); WriteIndent(true); m_SB.Add(']'); VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY); m_Stack.pop_back(); } void VmaJsonWriter::WriteString(const char* pStr) { BeginString(pStr); EndString(); } void VmaJsonWriter::BeginString(const char* pStr) { VMA_ASSERT(!m_InsideString); BeginValue(true); m_SB.Add('"'); m_InsideString = true; if(pStr != VMA_NULL && pStr[0] != '\0') { ContinueString(pStr); } } void VmaJsonWriter::ContinueString(const char* pStr) { VMA_ASSERT(m_InsideString); const size_t strLen = strlen(pStr); for(size_t i = 0; i < strLen; ++i) { char ch = pStr[i]; if(ch == '\'') { m_SB.Add("\\\\"); } else if(ch == '"') { m_SB.Add("\\\""); } else if(ch >= 32) { m_SB.Add(ch); } else switch(ch) { case '\b': m_SB.Add("\\b"); break; case '\f': m_SB.Add("\\f"); break; case '\n': m_SB.Add("\\n"); break; case '\r': m_SB.Add("\\r"); break; case '\t': m_SB.Add("\\t"); break; default: VMA_ASSERT(0 && "Character not currently supported."); break; } } } void VmaJsonWriter::ContinueString(uint32_t n) { VMA_ASSERT(m_InsideString); m_SB.AddNumber(n); } void VmaJsonWriter::ContinueString(uint64_t n) { VMA_ASSERT(m_InsideString); m_SB.AddNumber(n); } void VmaJsonWriter::ContinueString_Pointer(const void* ptr) { VMA_ASSERT(m_InsideString); m_SB.AddPointer(ptr); } void VmaJsonWriter::EndString(const char* pStr) { VMA_ASSERT(m_InsideString); if(pStr != VMA_NULL && pStr[0] != '\0') { ContinueString(pStr); } m_SB.Add('"'); m_InsideString = false; } void VmaJsonWriter::WriteNumber(uint32_t n) { VMA_ASSERT(!m_InsideString); BeginValue(false); m_SB.AddNumber(n); } void VmaJsonWriter::WriteNumber(uint64_t n) { VMA_ASSERT(!m_InsideString); BeginValue(false); m_SB.AddNumber(n); } void VmaJsonWriter::WriteBool(bool b) { VMA_ASSERT(!m_InsideString); BeginValue(false); m_SB.Add(b ? "true" : "false"); } void VmaJsonWriter::WriteNull() { VMA_ASSERT(!m_InsideString); BeginValue(false); m_SB.Add("null"); } void VmaJsonWriter::BeginValue(bool isString) { if(!m_Stack.empty()) { StackItem& currItem = m_Stack.back(); if(currItem.type == COLLECTION_TYPE_OBJECT && currItem.valueCount % 2 == 0) { VMA_ASSERT(isString); } if(currItem.type == COLLECTION_TYPE_OBJECT && currItem.valueCount % 2 != 0) { m_SB.Add(": "); } else if(currItem.valueCount > 0) { m_SB.Add(", "); WriteIndent(); } else { WriteIndent(); } ++currItem.valueCount; } } void VmaJsonWriter::WriteIndent(bool oneLess) { if(!m_Stack.empty() && !m_Stack.back().singleLineMode) { m_SB.AddNewLine(); size_t count = m_Stack.size(); if(count > 0 && oneLess) { --count; } for(size_t i = 0; i < count; ++i) { m_SB.Add(INDENT); } } } #endif // #if VMA_STATS_STRING_ENABLED //////////////////////////////////////////////////////////////////////////////// void VmaAllocation_T::SetUserData(VmaAllocator hAllocator, void* pUserData) { if(IsUserDataString()) { VMA_ASSERT(pUserData == VMA_NULL || pUserData != m_pUserData); FreeUserDataString(hAllocator); if(pUserData != VMA_NULL) { const char* const newStrSrc = (char*)pUserData; const size_t newStrLen = strlen(newStrSrc); char* const newStrDst = vma_new_array(hAllocator, char, newStrLen + 1); memcpy(newStrDst, newStrSrc, newStrLen + 1); m_pUserData = newStrDst; } } else { m_pUserData = pUserData; } } void VmaAllocation_T::ChangeBlockAllocation( VmaAllocator hAllocator, VmaDeviceMemoryBlock* block, VkDeviceSize offset) { VMA_ASSERT(block != VMA_NULL); VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); // Move mapping reference counter from old block to new block. if(block != m_BlockAllocation.m_Block) { uint32_t mapRefCount = m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP; if(IsPersistentMap()) ++mapRefCount; m_BlockAllocation.m_Block->Unmap(hAllocator, mapRefCount); block->Map(hAllocator, mapRefCount, VMA_NULL); } m_BlockAllocation.m_Block = block; m_BlockAllocation.m_Offset = offset; } VkDeviceSize VmaAllocation_T::GetOffset() const { switch(m_Type) { case ALLOCATION_TYPE_BLOCK: return m_BlockAllocation.m_Offset; case ALLOCATION_TYPE_DEDICATED: return 0; default: VMA_ASSERT(0); return 0; } } VkDeviceMemory VmaAllocation_T::GetMemory() const { switch(m_Type) { case ALLOCATION_TYPE_BLOCK: return m_BlockAllocation.m_Block->m_hMemory; case ALLOCATION_TYPE_DEDICATED: return m_DedicatedAllocation.m_hMemory; default: VMA_ASSERT(0); return VK_NULL_HANDLE; } } uint32_t VmaAllocation_T::GetMemoryTypeIndex() const { switch(m_Type) { case ALLOCATION_TYPE_BLOCK: return m_BlockAllocation.m_Block->m_MemoryTypeIndex; case ALLOCATION_TYPE_DEDICATED: return m_DedicatedAllocation.m_MemoryTypeIndex; default: VMA_ASSERT(0); return UINT32_MAX; } } void* VmaAllocation_T::GetMappedData() const { switch(m_Type) { case ALLOCATION_TYPE_BLOCK: if(m_MapCount != 0) { void* pBlockData = m_BlockAllocation.m_Block->m_Mapping.GetMappedData(); VMA_ASSERT(pBlockData != VMA_NULL); return (char*)pBlockData + m_BlockAllocation.m_Offset; } else { return VMA_NULL; } break; case ALLOCATION_TYPE_DEDICATED: VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0)); return m_DedicatedAllocation.m_pMappedData; default: VMA_ASSERT(0); return VMA_NULL; } } bool VmaAllocation_T::CanBecomeLost() const { switch(m_Type) { case ALLOCATION_TYPE_BLOCK: return m_BlockAllocation.m_CanBecomeLost; case ALLOCATION_TYPE_DEDICATED: return false; default: VMA_ASSERT(0); return false; } } VmaPool VmaAllocation_T::GetPool() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_hPool; } bool VmaAllocation_T::MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) { VMA_ASSERT(CanBecomeLost()); /* Warning: This is a carefully designed algorithm. Do not modify unless you really know what you're doing :) */ uint32_t localLastUseFrameIndex = GetLastUseFrameIndex(); for(;;) { if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST) { VMA_ASSERT(0); return false; } else if(localLastUseFrameIndex + frameInUseCount >= currentFrameIndex) { return false; } else // Last use time earlier than current time. { if(CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, VMA_FRAME_INDEX_LOST)) { // Setting hAllocation.LastUseFrameIndex atomic to VMA_FRAME_INDEX_LOST is enough to mark it as LOST. // Calling code just needs to unregister this allocation in owning VmaDeviceMemoryBlock. return true; } } } } void VmaAllocation_T::FreeUserDataString(VmaAllocator hAllocator) { VMA_ASSERT(IsUserDataString()); if(m_pUserData != VMA_NULL) { char* const oldStr = (char*)m_pUserData; const size_t oldStrLen = strlen(oldStr); vma_delete_array(hAllocator, oldStr, oldStrLen + 1); m_pUserData = VMA_NULL; } } void VmaAllocation_T::BlockAllocMap() { VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK); if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F) { ++m_MapCount; } else { VMA_ASSERT(0 && "Allocation mapped too many times simultaneously."); } } void VmaAllocation_T::BlockAllocUnmap() { VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK); if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0) { --m_MapCount; } else { VMA_ASSERT(0 && "Unmapping allocation not previously mapped."); } } VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData) { VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED); if(m_MapCount != 0) { if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F) { VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL); *ppData = m_DedicatedAllocation.m_pMappedData; ++m_MapCount; return VK_SUCCESS; } else { VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously."); return VK_ERROR_MEMORY_MAP_FAILED; } } else { VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)( hAllocator->m_hDevice, m_DedicatedAllocation.m_hMemory, 0, // offset VK_WHOLE_SIZE, 0, // flags ppData); if(result == VK_SUCCESS) { m_DedicatedAllocation.m_pMappedData = *ppData; m_MapCount = 1; } return result; } } void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator) { VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED); if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0) { --m_MapCount; if(m_MapCount == 0) { m_DedicatedAllocation.m_pMappedData = VMA_NULL; (*hAllocator->GetVulkanFunctions().vkUnmapMemory)( hAllocator->m_hDevice, m_DedicatedAllocation.m_hMemory); } } else { VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped."); } } #if VMA_STATS_STRING_ENABLED // Correspond to values of enum VmaSuballocationType. static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = { "FREE", "UNKNOWN", "BUFFER", "IMAGE_UNKNOWN", "IMAGE_LINEAR", "IMAGE_OPTIMAL", }; static void VmaPrintStatInfo(VmaJsonWriter& json, const VmaStatInfo& stat) { json.BeginObject(); json.WriteString("Blocks"); json.WriteNumber(stat.blockCount); json.WriteString("Allocations"); json.WriteNumber(stat.allocationCount); json.WriteString("UnusedRanges"); json.WriteNumber(stat.unusedRangeCount); json.WriteString("UsedBytes"); json.WriteNumber(stat.usedBytes); json.WriteString("UnusedBytes"); json.WriteNumber(stat.unusedBytes); if(stat.allocationCount > 1) { json.WriteString("AllocationSize"); json.BeginObject(true); json.WriteString("Min"); json.WriteNumber(stat.allocationSizeMin); json.WriteString("Avg"); json.WriteNumber(stat.allocationSizeAvg); json.WriteString("Max"); json.WriteNumber(stat.allocationSizeMax); json.EndObject(); } if(stat.unusedRangeCount > 1) { json.WriteString("UnusedRangeSize"); json.BeginObject(true); json.WriteString("Min"); json.WriteNumber(stat.unusedRangeSizeMin); json.WriteString("Avg"); json.WriteNumber(stat.unusedRangeSizeAvg); json.WriteString("Max"); json.WriteNumber(stat.unusedRangeSizeMax); json.EndObject(); } json.EndObject(); } #endif // #if VMA_STATS_STRING_ENABLED struct VmaSuballocationItemSizeLess { bool operator()( const VmaSuballocationList::iterator lhs, const VmaSuballocationList::iterator rhs) const { return lhs->size < rhs->size; } bool operator()( const VmaSuballocationList::iterator lhs, VkDeviceSize rhsSize) const { return lhs->size < rhsSize; } }; //////////////////////////////////////////////////////////////////////////////// // class VmaBlockMetadata VmaBlockMetadata::VmaBlockMetadata(VmaAllocator hAllocator) : m_Size(0), m_FreeCount(0), m_SumFreeSize(0), m_Suballocations(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())), m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(hAllocator->GetAllocationCallbacks())) { } VmaBlockMetadata::~VmaBlockMetadata() { } void VmaBlockMetadata::Init(VkDeviceSize size) { m_Size = size; m_FreeCount = 1; m_SumFreeSize = size; VmaSuballocation suballoc = {}; suballoc.offset = 0; suballoc.size = size; suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; m_Suballocations.push_back(suballoc); VmaSuballocationList::iterator suballocItem = m_Suballocations.end(); --suballocItem; m_FreeSuballocationsBySize.push_back(suballocItem); } bool VmaBlockMetadata::Validate() const { if(m_Suballocations.empty()) { return false; } // Expected offset of new suballocation as calculates from previous ones. VkDeviceSize calculatedOffset = 0; // Expected number of free suballocations as calculated from traversing their list. uint32_t calculatedFreeCount = 0; // Expected sum size of free suballocations as calculated from traversing their list. VkDeviceSize calculatedSumFreeSize = 0; // Expected number of free suballocations that should be registered in // m_FreeSuballocationsBySize calculated from traversing their list. size_t freeSuballocationsToRegister = 0; // True if previous visisted suballocation was free. bool prevFree = false; for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin(); suballocItem != m_Suballocations.cend(); ++suballocItem) { const VmaSuballocation& subAlloc = *suballocItem; // Actual offset of this suballocation doesn't match expected one. if(subAlloc.offset != calculatedOffset) { return false; } const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE); // Two adjacent free suballocations are invalid. They should be merged. if(prevFree && currFree) { return false; } if(currFree != (subAlloc.hAllocation == VK_NULL_HANDLE)) { return false; } if(currFree) { calculatedSumFreeSize += subAlloc.size; ++calculatedFreeCount; if(subAlloc.size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER) { ++freeSuballocationsToRegister; } } else { if(subAlloc.hAllocation->GetOffset() != subAlloc.offset) { return false; } if(subAlloc.hAllocation->GetSize() != subAlloc.size) { return false; } } calculatedOffset += subAlloc.size; prevFree = currFree; } // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't // match expected one. if(m_FreeSuballocationsBySize.size() != freeSuballocationsToRegister) { return false; } VkDeviceSize lastSize = 0; for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i) { VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i]; // Only free suballocations can be registered in m_FreeSuballocationsBySize. if(suballocItem->type != VMA_SUBALLOCATION_TYPE_FREE) { return false; } // They must be sorted by size ascending. if(suballocItem->size < lastSize) { return false; } lastSize = suballocItem->size; } // Check if totals match calculacted values. if(!ValidateFreeSuballocationList() || (calculatedOffset != m_Size) || (calculatedSumFreeSize != m_SumFreeSize) || (calculatedFreeCount != m_FreeCount)) { return false; } return true; } VkDeviceSize VmaBlockMetadata::GetUnusedRangeSizeMax() const { if(!m_FreeSuballocationsBySize.empty()) { return m_FreeSuballocationsBySize.back()->size; } else { return 0; } } bool VmaBlockMetadata::IsEmpty() const { return (m_Suballocations.size() == 1) && (m_FreeCount == 1); } void VmaBlockMetadata::CalcAllocationStatInfo(VmaStatInfo& outInfo) const { outInfo.blockCount = 1; const uint32_t rangeCount = (uint32_t)m_Suballocations.size(); outInfo.allocationCount = rangeCount - m_FreeCount; outInfo.unusedRangeCount = m_FreeCount; outInfo.unusedBytes = m_SumFreeSize; outInfo.usedBytes = m_Size - outInfo.unusedBytes; outInfo.allocationSizeMin = UINT64_MAX; outInfo.allocationSizeMax = 0; outInfo.unusedRangeSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMax = 0; for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin(); suballocItem != m_Suballocations.cend(); ++suballocItem) { const VmaSuballocation& suballoc = *suballocItem; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) { outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size); outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, suballoc.size); } else { outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, suballoc.size); outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, suballoc.size); } } } void VmaBlockMetadata::AddPoolStats(VmaPoolStats& inoutStats) const { const uint32_t rangeCount = (uint32_t)m_Suballocations.size(); inoutStats.size += m_Size; inoutStats.unusedSize += m_SumFreeSize; inoutStats.allocationCount += rangeCount - m_FreeCount; inoutStats.unusedRangeCount += m_FreeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax()); } #if VMA_STATS_STRING_ENABLED void VmaBlockMetadata::PrintDetailedMap(class VmaJsonWriter& json) const { json.BeginObject(); json.WriteString("TotalBytes"); json.WriteNumber(m_Size); json.WriteString("UnusedBytes"); json.WriteNumber(m_SumFreeSize); json.WriteString("Allocations"); json.WriteNumber((uint64_t)m_Suballocations.size() - m_FreeCount); json.WriteString("UnusedRanges"); json.WriteNumber(m_FreeCount); json.WriteString("Suballocations"); json.BeginArray(); size_t i = 0; for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin(); suballocItem != m_Suballocations.cend(); ++suballocItem, ++i) { json.BeginObject(true); json.WriteString("Type"); json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[suballocItem->type]); json.WriteString("Size"); json.WriteNumber(suballocItem->size); json.WriteString("Offset"); json.WriteNumber(suballocItem->offset); if(suballocItem->type != VMA_SUBALLOCATION_TYPE_FREE) { const void* pUserData = suballocItem->hAllocation->GetUserData(); if(pUserData != VMA_NULL) { json.WriteString("UserData"); if(suballocItem->hAllocation->IsUserDataString()) { json.WriteString((const char*)pUserData); } else { json.BeginString(); json.ContinueString_Pointer(pUserData); json.EndString(); } } } json.EndObject(); } json.EndArray(); json.EndObject(); } #endif // #if VMA_STATS_STRING_ENABLED /* How many suitable free suballocations to analyze before choosing best one. - Set to 1 to use First-Fit algorithm - first suitable free suballocation will be chosen. - Set to UINT32_MAX to use Best-Fit/Worst-Fit algorithm - all suitable free suballocations will be analized and best one will be chosen. - Any other value is also acceptable. */ //static const uint32_t MAX_SUITABLE_SUBALLOCATIONS_TO_CHECK = 8; void VmaBlockMetadata::CreateFirstAllocationRequest(VmaAllocationRequest* pAllocationRequest) { VMA_ASSERT(IsEmpty()); pAllocationRequest->offset = 0; pAllocationRequest->sumFreeSize = m_SumFreeSize; pAllocationRequest->sumItemSize = 0; pAllocationRequest->item = m_Suballocations.begin(); pAllocationRequest->itemsToMakeLostCount = 0; } bool VmaBlockMetadata::CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, VmaSuballocationType allocType, bool canMakeOtherLost, VmaAllocationRequest* pAllocationRequest) { VMA_ASSERT(allocSize > 0); VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); VMA_ASSERT(pAllocationRequest != VMA_NULL); VMA_HEAVY_ASSERT(Validate()); // There is not enough total free space in this block to fullfill the request: Early return. if(canMakeOtherLost == false && m_SumFreeSize < allocSize) { return false; } // New algorithm, efficiently searching freeSuballocationsBySize. const size_t freeSuballocCount = m_FreeSuballocationsBySize.size(); if(freeSuballocCount > 0) { if(VMA_BEST_FIT) { // Find first free suballocation with size not less than allocSize. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess( m_FreeSuballocationsBySize.data(), m_FreeSuballocationsBySize.data() + freeSuballocCount, allocSize, VmaSuballocationItemSizeLess()); size_t index = it - m_FreeSuballocationsBySize.data(); for(; index < freeSuballocCount; ++index) { if(CheckAllocation( currentFrameIndex, frameInUseCount, bufferImageGranularity, allocSize, allocAlignment, allocType, m_FreeSuballocationsBySize[index], false, // canMakeOtherLost &pAllocationRequest->offset, &pAllocationRequest->itemsToMakeLostCount, &pAllocationRequest->sumFreeSize, &pAllocationRequest->sumItemSize)) { pAllocationRequest->item = m_FreeSuballocationsBySize[index]; return true; } } } else { // Search staring from biggest suballocations. for(size_t index = freeSuballocCount; index--; ) { if(CheckAllocation( currentFrameIndex, frameInUseCount, bufferImageGranularity, allocSize, allocAlignment, allocType, m_FreeSuballocationsBySize[index], false, // canMakeOtherLost &pAllocationRequest->offset, &pAllocationRequest->itemsToMakeLostCount, &pAllocationRequest->sumFreeSize, &pAllocationRequest->sumItemSize)) { pAllocationRequest->item = m_FreeSuballocationsBySize[index]; return true; } } } } if(canMakeOtherLost) { // Brute-force algorithm. TODO: Come up with something better. pAllocationRequest->sumFreeSize = VK_WHOLE_SIZE; pAllocationRequest->sumItemSize = VK_WHOLE_SIZE; VmaAllocationRequest tmpAllocRequest = {}; for(VmaSuballocationList::iterator suballocIt = m_Suballocations.begin(); suballocIt != m_Suballocations.end(); ++suballocIt) { if(suballocIt->type == VMA_SUBALLOCATION_TYPE_FREE || suballocIt->hAllocation->CanBecomeLost()) { if(CheckAllocation( currentFrameIndex, frameInUseCount, bufferImageGranularity, allocSize, allocAlignment, allocType, suballocIt, canMakeOtherLost, &tmpAllocRequest.offset, &tmpAllocRequest.itemsToMakeLostCount, &tmpAllocRequest.sumFreeSize, &tmpAllocRequest.sumItemSize)) { tmpAllocRequest.item = suballocIt; if(tmpAllocRequest.CalcCost() < pAllocationRequest->CalcCost()) { *pAllocationRequest = tmpAllocRequest; } } } } if(pAllocationRequest->sumItemSize != VK_WHOLE_SIZE) { return true; } } return false; } bool VmaBlockMetadata::MakeRequestedAllocationsLost( uint32_t currentFrameIndex, uint32_t frameInUseCount, VmaAllocationRequest* pAllocationRequest) { while(pAllocationRequest->itemsToMakeLostCount > 0) { if(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE) { ++pAllocationRequest->item; } VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end()); VMA_ASSERT(pAllocationRequest->item->hAllocation != VK_NULL_HANDLE); VMA_ASSERT(pAllocationRequest->item->hAllocation->CanBecomeLost()); if(pAllocationRequest->item->hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { pAllocationRequest->item = FreeSuballocation(pAllocationRequest->item); --pAllocationRequest->itemsToMakeLostCount; } else { return false; } } VMA_HEAVY_ASSERT(Validate()); VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end()); VMA_ASSERT(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE); return true; } uint32_t VmaBlockMetadata::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) { uint32_t lostAllocationCount = 0; for(VmaSuballocationList::iterator it = m_Suballocations.begin(); it != m_Suballocations.end(); ++it) { if(it->type != VMA_SUBALLOCATION_TYPE_FREE && it->hAllocation->CanBecomeLost() && it->hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { it = FreeSuballocation(it); ++lostAllocationCount; } } return lostAllocationCount; } void VmaBlockMetadata::Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, VmaAllocation hAllocation) { VMA_ASSERT(request.item != m_Suballocations.end()); VmaSuballocation& suballoc = *request.item; // Given suballocation is a free block. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); // Given offset is inside this suballocation. VMA_ASSERT(request.offset >= suballoc.offset); const VkDeviceSize paddingBegin = request.offset - suballoc.offset; VMA_ASSERT(suballoc.size >= paddingBegin + allocSize); const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - allocSize; // Unregister this free suballocation from m_FreeSuballocationsBySize and update // it to become used. UnregisterFreeSuballocation(request.item); suballoc.offset = request.offset; suballoc.size = allocSize; suballoc.type = type; suballoc.hAllocation = hAllocation; // If there are any free bytes remaining at the end, insert new free suballocation after current one. if(paddingEnd) { VmaSuballocation paddingSuballoc = {}; paddingSuballoc.offset = request.offset + allocSize; paddingSuballoc.size = paddingEnd; paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; VmaSuballocationList::iterator next = request.item; ++next; const VmaSuballocationList::iterator paddingEndItem = m_Suballocations.insert(next, paddingSuballoc); RegisterFreeSuballocation(paddingEndItem); } // If there are any free bytes remaining at the beginning, insert new free suballocation before current one. if(paddingBegin) { VmaSuballocation paddingSuballoc = {}; paddingSuballoc.offset = request.offset - paddingBegin; paddingSuballoc.size = paddingBegin; paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; const VmaSuballocationList::iterator paddingBeginItem = m_Suballocations.insert(request.item, paddingSuballoc); RegisterFreeSuballocation(paddingBeginItem); } // Update totals. m_FreeCount = m_FreeCount - 1; if(paddingBegin > 0) { ++m_FreeCount; } if(paddingEnd > 0) { ++m_FreeCount; } m_SumFreeSize -= allocSize; } void VmaBlockMetadata::Free(const VmaAllocation allocation) { for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin(); suballocItem != m_Suballocations.end(); ++suballocItem) { VmaSuballocation& suballoc = *suballocItem; if(suballoc.hAllocation == allocation) { FreeSuballocation(suballocItem); VMA_HEAVY_ASSERT(Validate()); return; } } VMA_ASSERT(0 && "Not found!"); } void VmaBlockMetadata::FreeAtOffset(VkDeviceSize offset) { for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin(); suballocItem != m_Suballocations.end(); ++suballocItem) { VmaSuballocation& suballoc = *suballocItem; if(suballoc.offset == offset) { FreeSuballocation(suballocItem); return; } } VMA_ASSERT(0 && "Not found!"); } bool VmaBlockMetadata::ValidateFreeSuballocationList() const { VkDeviceSize lastSize = 0; for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i) { const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i]; if(it->type != VMA_SUBALLOCATION_TYPE_FREE) { VMA_ASSERT(0); return false; } if(it->size < VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER) { VMA_ASSERT(0); return false; } if(it->size < lastSize) { VMA_ASSERT(0); return false; } lastSize = it->size; } return true; } bool VmaBlockMetadata::CheckAllocation( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, VmaSuballocationType allocType, VmaSuballocationList::const_iterator suballocItem, bool canMakeOtherLost, VkDeviceSize* pOffset, size_t* itemsToMakeLostCount, VkDeviceSize* pSumFreeSize, VkDeviceSize* pSumItemSize) const { VMA_ASSERT(allocSize > 0); VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); VMA_ASSERT(suballocItem != m_Suballocations.cend()); VMA_ASSERT(pOffset != VMA_NULL); *itemsToMakeLostCount = 0; *pSumFreeSize = 0; *pSumItemSize = 0; if(canMakeOtherLost) { if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE) { *pSumFreeSize = suballocItem->size; } else { if(suballocItem->hAllocation->CanBecomeLost() && suballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex) { ++*itemsToMakeLostCount; *pSumItemSize = suballocItem->size; } else { return false; } } // Remaining size is too small for this request: Early return. if(m_Size - suballocItem->offset < allocSize) { return false; } // Start from offset equal to beginning of this suballocation. *pOffset = suballocItem->offset; // Apply VMA_DEBUG_MARGIN at the beginning. if((VMA_DEBUG_MARGIN > 0) && suballocItem != m_Suballocations.cbegin()) { *pOffset += VMA_DEBUG_MARGIN; } // Apply alignment. const VkDeviceSize alignment = VMA_MAX(allocAlignment, static_cast<VkDeviceSize>(VMA_DEBUG_ALIGNMENT)); *pOffset = VmaAlignUp(*pOffset, alignment); // Check previous suballocations for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if(bufferImageGranularity > 1) { bool bufferImageGranularityConflict = false; VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; while(prevSuballocItem != m_Suballocations.cbegin()) { --prevSuballocItem; const VmaSuballocation& prevSuballoc = *prevSuballocItem; if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) { bufferImageGranularityConflict = true; break; } } else // Already on previous page. break; } if(bufferImageGranularityConflict) { *pOffset = VmaAlignUp(*pOffset, bufferImageGranularity); } } // Now that we have final *pOffset, check if we are past suballocItem. // If yes, return false - this function should be called for another suballocItem as starting point. if(*pOffset >= suballocItem->offset + suballocItem->size) { return false; } // Calculate padding at the beginning based on current offset. const VkDeviceSize paddingBegin = *pOffset - suballocItem->offset; // Calculate required margin at the end if this is not last suballocation. VmaSuballocationList::const_iterator next = suballocItem; ++next; const VkDeviceSize requiredEndMargin = (next != m_Suballocations.cend()) ? VMA_DEBUG_MARGIN : 0; const VkDeviceSize totalSize = paddingBegin + allocSize + requiredEndMargin; // Another early return check. if(suballocItem->offset + totalSize > m_Size) { return false; } // Advance lastSuballocItem until desired size is reached. // Update itemsToMakeLostCount. VmaSuballocationList::const_iterator lastSuballocItem = suballocItem; if(totalSize > suballocItem->size) { VkDeviceSize remainingSize = totalSize - suballocItem->size; while(remainingSize > 0) { ++lastSuballocItem; if(lastSuballocItem == m_Suballocations.cend()) { return false; } if(lastSuballocItem->type == VMA_SUBALLOCATION_TYPE_FREE) { *pSumFreeSize += lastSuballocItem->size; } else { VMA_ASSERT(lastSuballocItem->hAllocation != VK_NULL_HANDLE); if(lastSuballocItem->hAllocation->CanBecomeLost() && lastSuballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex) { ++*itemsToMakeLostCount; *pSumItemSize += lastSuballocItem->size; } else { return false; } } remainingSize = (lastSuballocItem->size < remainingSize) ? remainingSize - lastSuballocItem->size : 0; } } // Check next suballocations for BufferImageGranularity conflicts. // If conflict exists, we must mark more allocations lost or fail. if(bufferImageGranularity > 1) { VmaSuballocationList::const_iterator nextSuballocItem = lastSuballocItem; ++nextSuballocItem; while(nextSuballocItem != m_Suballocations.cend()) { const VmaSuballocation& nextSuballoc = *nextSuballocItem; if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) { VMA_ASSERT(nextSuballoc.hAllocation != VK_NULL_HANDLE); if(nextSuballoc.hAllocation->CanBecomeLost() && nextSuballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex) { ++*itemsToMakeLostCount; } else { return false; } } } else { // Already on next page. break; } ++nextSuballocItem; } } } else { const VmaSuballocation& suballoc = *suballocItem; VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); *pSumFreeSize = suballoc.size; // Size of this suballocation is too small for this request: Early return. if(suballoc.size < allocSize) { return false; } // Start from offset equal to beginning of this suballocation. *pOffset = suballoc.offset; // Apply VMA_DEBUG_MARGIN at the beginning. if((VMA_DEBUG_MARGIN > 0) && suballocItem != m_Suballocations.cbegin()) { *pOffset += VMA_DEBUG_MARGIN; } // Apply alignment. const VkDeviceSize alignment = VMA_MAX(allocAlignment, static_cast<VkDeviceSize>(VMA_DEBUG_ALIGNMENT)); *pOffset = VmaAlignUp(*pOffset, alignment); // Check previous suballocations for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if(bufferImageGranularity > 1) { bool bufferImageGranularityConflict = false; VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; while(prevSuballocItem != m_Suballocations.cbegin()) { --prevSuballocItem; const VmaSuballocation& prevSuballoc = *prevSuballocItem; if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) { bufferImageGranularityConflict = true; break; } } else // Already on previous page. break; } if(bufferImageGranularityConflict) { *pOffset = VmaAlignUp(*pOffset, bufferImageGranularity); } } // Calculate padding at the beginning based on current offset. const VkDeviceSize paddingBegin = *pOffset - suballoc.offset; // Calculate required margin at the end if this is not last suballocation. VmaSuballocationList::const_iterator next = suballocItem; ++next; const VkDeviceSize requiredEndMargin = (next != m_Suballocations.cend()) ? VMA_DEBUG_MARGIN : 0; // Fail if requested size plus margin before and after is bigger than size of this suballocation. if(paddingBegin + allocSize + requiredEndMargin > suballoc.size) { return false; } // Check next suballocations for BufferImageGranularity conflicts. // If conflict exists, allocation cannot be made here. if(bufferImageGranularity > 1) { VmaSuballocationList::const_iterator nextSuballocItem = suballocItem; ++nextSuballocItem; while(nextSuballocItem != m_Suballocations.cend()) { const VmaSuballocation& nextSuballoc = *nextSuballocItem; if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) { return false; } } else { // Already on next page. break; } ++nextSuballocItem; } } } // All tests passed: Success. pOffset is already filled. return true; } void VmaBlockMetadata::MergeFreeWithNext(VmaSuballocationList::iterator item) { VMA_ASSERT(item != m_Suballocations.end()); VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE); VmaSuballocationList::iterator nextItem = item; ++nextItem; VMA_ASSERT(nextItem != m_Suballocations.end()); VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE); item->size += nextItem->size; --m_FreeCount; m_Suballocations.erase(nextItem); } VmaSuballocationList::iterator VmaBlockMetadata::FreeSuballocation(VmaSuballocationList::iterator suballocItem) { // Change this suballocation to be marked as free. VmaSuballocation& suballoc = *suballocItem; suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; // Update totals. ++m_FreeCount; m_SumFreeSize += suballoc.size; // Merge with previous and/or next suballocation if it's also free. bool mergeWithNext = false; bool mergeWithPrev = false; VmaSuballocationList::iterator nextItem = suballocItem; ++nextItem; if((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE)) { mergeWithNext = true; } VmaSuballocationList::iterator prevItem = suballocItem; if(suballocItem != m_Suballocations.begin()) { --prevItem; if(prevItem->type == VMA_SUBALLOCATION_TYPE_FREE) { mergeWithPrev = true; } } if(mergeWithNext) { UnregisterFreeSuballocation(nextItem); MergeFreeWithNext(suballocItem); } if(mergeWithPrev) { UnregisterFreeSuballocation(prevItem); MergeFreeWithNext(prevItem); RegisterFreeSuballocation(prevItem); return prevItem; } else { RegisterFreeSuballocation(suballocItem); return suballocItem; } } void VmaBlockMetadata::RegisterFreeSuballocation(VmaSuballocationList::iterator item) { VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE); VMA_ASSERT(item->size > 0); // You may want to enable this validation at the beginning or at the end of // this function, depending on what do you want to check. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER) { if(m_FreeSuballocationsBySize.empty()) { m_FreeSuballocationsBySize.push_back(item); } else { VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item); } } //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); } void VmaBlockMetadata::UnregisterFreeSuballocation(VmaSuballocationList::iterator item) { VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE); VMA_ASSERT(item->size > 0); // You may want to enable this validation at the beginning or at the end of // this function, depending on what do you want to check. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER) { VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess( m_FreeSuballocationsBySize.data(), m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(), item, VmaSuballocationItemSizeLess()); for(size_t index = it - m_FreeSuballocationsBySize.data(); index < m_FreeSuballocationsBySize.size(); ++index) { if(m_FreeSuballocationsBySize[index] == item) { VmaVectorRemove(m_FreeSuballocationsBySize, index); return; } VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found."); } VMA_ASSERT(0 && "Not found."); } //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); } //////////////////////////////////////////////////////////////////////////////// // class VmaDeviceMemoryMapping VmaDeviceMemoryMapping::VmaDeviceMemoryMapping() : m_MapCount(0), m_pMappedData(VMA_NULL) { } VmaDeviceMemoryMapping::~VmaDeviceMemoryMapping() { VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped."); } VkResult VmaDeviceMemoryMapping::Map(VmaAllocator hAllocator, VkDeviceMemory hMemory, uint32_t count, void **ppData) { if(count == 0) { return VK_SUCCESS; } VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex); if(m_MapCount != 0) { m_MapCount += count; VMA_ASSERT(m_pMappedData != VMA_NULL); if(ppData != VMA_NULL) { *ppData = m_pMappedData; } return VK_SUCCESS; } else { VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)( hAllocator->m_hDevice, hMemory, 0, // offset VK_WHOLE_SIZE, 0, // flags &m_pMappedData); if(result == VK_SUCCESS) { if(ppData != VMA_NULL) { *ppData = m_pMappedData; } m_MapCount = count; } return result; } } void VmaDeviceMemoryMapping::Unmap(VmaAllocator hAllocator, VkDeviceMemory hMemory, uint32_t count) { if(count == 0) { return; } VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex); if(m_MapCount >= count) { m_MapCount -= count; if(m_MapCount == 0) { m_pMappedData = VMA_NULL; (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, hMemory); } } else { VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped."); } } //////////////////////////////////////////////////////////////////////////////// // class VmaDeviceMemoryBlock VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) : m_MemoryTypeIndex(UINT32_MAX), m_hMemory(VK_NULL_HANDLE), m_Metadata(hAllocator) { } void VmaDeviceMemoryBlock::Init( uint32_t newMemoryTypeIndex, VkDeviceMemory newMemory, VkDeviceSize newSize) { VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); m_MemoryTypeIndex = newMemoryTypeIndex; m_hMemory = newMemory; m_Metadata.Init(newSize); } void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator) { // This is the most important assert in the entire library. // Hitting it means you have some memory leak - unreleased VmaAllocation objects. VMA_ASSERT(m_Metadata.IsEmpty() && "Some allocations were not freed before destruction of this memory block!"); VMA_ASSERT(m_hMemory != VK_NULL_HANDLE); allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_Metadata.GetSize(), m_hMemory); m_hMemory = VK_NULL_HANDLE; } bool VmaDeviceMemoryBlock::Validate() const { if((m_hMemory == VK_NULL_HANDLE) || (m_Metadata.GetSize() == 0)) { return false; } return m_Metadata.Validate(); } VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData) { return m_Mapping.Map(hAllocator, m_hMemory, count, ppData); } void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count) { m_Mapping.Unmap(hAllocator, m_hMemory, count); } static void InitStatInfo(VmaStatInfo& outInfo) { memset(&outInfo, 0, sizeof(outInfo)); outInfo.allocationSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMin = UINT64_MAX; } // Adds statistics srcInfo into inoutInfo, like: inoutInfo += srcInfo. static void VmaAddStatInfo(VmaStatInfo& inoutInfo, const VmaStatInfo& srcInfo) { inoutInfo.blockCount += srcInfo.blockCount; inoutInfo.allocationCount += srcInfo.allocationCount; inoutInfo.unusedRangeCount += srcInfo.unusedRangeCount; inoutInfo.usedBytes += srcInfo.usedBytes; inoutInfo.unusedBytes += srcInfo.unusedBytes; inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin); inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax); inoutInfo.unusedRangeSizeMin = VMA_MIN(inoutInfo.unusedRangeSizeMin, srcInfo.unusedRangeSizeMin); inoutInfo.unusedRangeSizeMax = VMA_MAX(inoutInfo.unusedRangeSizeMax, srcInfo.unusedRangeSizeMax); } static void VmaPostprocessCalcStatInfo(VmaStatInfo& inoutInfo) { inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ? VmaRoundDiv<VkDeviceSize>(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0; inoutInfo.unusedRangeSizeAvg = (inoutInfo.unusedRangeCount > 0) ? VmaRoundDiv<VkDeviceSize>(inoutInfo.unusedBytes, inoutInfo.unusedRangeCount) : 0; } VmaPool_T::VmaPool_T( VmaAllocator hAllocator, const VmaPoolCreateInfo& createInfo) : m_BlockVector( hAllocator, createInfo.memoryTypeIndex, createInfo.blockSize, createInfo.minBlockCount, createInfo.maxBlockCount, (createInfo.flags & VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(), createInfo.frameInUseCount, true) // isCustomPool { } VmaPool_T::~VmaPool_T() { } #if VMA_STATS_STRING_ENABLED #endif // #if VMA_STATS_STRING_ENABLED VmaBlockVector::VmaBlockVector( VmaAllocator hAllocator, uint32_t memoryTypeIndex, VkDeviceSize preferredBlockSize, size_t minBlockCount, size_t maxBlockCount, VkDeviceSize bufferImageGranularity, uint32_t frameInUseCount, bool isCustomPool) : m_hAllocator(hAllocator), m_MemoryTypeIndex(memoryTypeIndex), m_PreferredBlockSize(preferredBlockSize), m_MinBlockCount(minBlockCount), m_MaxBlockCount(maxBlockCount), m_BufferImageGranularity(bufferImageGranularity), m_FrameInUseCount(frameInUseCount), m_IsCustomPool(isCustomPool), m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())), m_HasEmptyBlock(false), m_pDefragmentator(VMA_NULL) { } VmaBlockVector::~VmaBlockVector() { VMA_ASSERT(m_pDefragmentator == VMA_NULL); for(size_t i = m_Blocks.size(); i--; ) { m_Blocks[i]->Destroy(m_hAllocator); vma_delete(m_hAllocator, m_Blocks[i]); } } VkResult VmaBlockVector::CreateMinBlocks() { for(size_t i = 0; i < m_MinBlockCount; ++i) { VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL); if(res != VK_SUCCESS) { return res; } } return VK_SUCCESS; } void VmaBlockVector::GetPoolStats(VmaPoolStats* pStats) { pStats->size = 0; pStats->unusedSize = 0; pStats->allocationCount = 0; pStats->unusedRangeCount = 0; pStats->unusedRangeSizeMax = 0; VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) { const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; VMA_ASSERT(pBlock); VMA_HEAVY_ASSERT(pBlock->Validate()); pBlock->m_Metadata.AddPoolStats(*pStats); } } static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32; VkResult VmaBlockVector::Allocate( VmaPool hCurrentPool, uint32_t currentFrameIndex, const VkMemoryRequirements& vkMemReq, const VmaAllocationCreateInfo& createInfo, VmaSuballocationType suballocType, VmaAllocation* pAllocation) { const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; const bool isUserDataString = (createInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0; VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); // 1. Search existing allocations. Try to allocate without making other allocations lost. // Forward order in m_Blocks - prefer blocks with smallest amount of free space. for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex ) { VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; VMA_ASSERT(pCurrBlock); VmaAllocationRequest currRequest = {}; if(pCurrBlock->m_Metadata.CreateAllocationRequest( currentFrameIndex, m_FrameInUseCount, m_BufferImageGranularity, vkMemReq.size, vkMemReq.alignment, suballocType, false, // canMakeOtherLost &currRequest)) { // Allocate from pCurrBlock. VMA_ASSERT(currRequest.itemsToMakeLostCount == 0); if(mapped) { VkResult res = pCurrBlock->Map(m_hAllocator, 1, VMA_NULL); if(res != VK_SUCCESS) { return res; } } // We no longer have an empty Allocation. if(pCurrBlock->m_Metadata.IsEmpty()) { m_HasEmptyBlock = false; } *pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString); pCurrBlock->m_Metadata.Alloc(currRequest, suballocType, vkMemReq.size, *pAllocation); (*pAllocation)->InitBlockAllocation( hCurrentPool, pCurrBlock, currRequest.offset, vkMemReq.alignment, vkMemReq.size, suballocType, mapped, (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0); VMA_HEAVY_ASSERT(pCurrBlock->Validate()); VMA_DEBUG_LOG(" Returned from existing allocation #%u", (uint32_t)blockIndex); (*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData); return VK_SUCCESS; } } const bool canCreateNewBlock = ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) && (m_Blocks.size() < m_MaxBlockCount); // 2. Try to create new block. if(canCreateNewBlock) { // Calculate optimal size for new block. VkDeviceSize newBlockSize = m_PreferredBlockSize; uint32_t newBlockSizeShift = 0; const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3; // Allocating blocks of other sizes is allowed only in default pools. // In custom pools block size is fixed. if(m_IsCustomPool == false) { // Allocate 1/8, 1/4, 1/2 as first blocks. const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize(); for(uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i) { const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= vkMemReq.size * 2) { newBlockSize = smallerNewBlockSize; ++newBlockSizeShift; } else { break; } } } size_t newBlockIndex = 0; VkResult res = CreateBlock(newBlockSize, &newBlockIndex); // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize. if(m_IsCustomPool == false) { while(res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX) { const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; if(smallerNewBlockSize >= vkMemReq.size) { newBlockSize = smallerNewBlockSize; ++newBlockSizeShift; res = CreateBlock(newBlockSize, &newBlockIndex); } else { break; } } } if(res == VK_SUCCESS) { VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex]; VMA_ASSERT(pBlock->m_Metadata.GetSize() >= vkMemReq.size); if(mapped) { res = pBlock->Map(m_hAllocator, 1, VMA_NULL); if(res != VK_SUCCESS) { return res; } } // Allocate from pBlock. Because it is empty, dstAllocRequest can be trivially filled. VmaAllocationRequest allocRequest; pBlock->m_Metadata.CreateFirstAllocationRequest(&allocRequest); *pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString); pBlock->m_Metadata.Alloc(allocRequest, suballocType, vkMemReq.size, *pAllocation); (*pAllocation)->InitBlockAllocation( hCurrentPool, pBlock, allocRequest.offset, vkMemReq.alignment, vkMemReq.size, suballocType, mapped, (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0); VMA_HEAVY_ASSERT(pBlock->Validate()); VMA_DEBUG_LOG(" Created new allocation Size=%llu", allocInfo.allocationSize); (*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData); return VK_SUCCESS; } } const bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0; // 3. Try to allocate from existing blocks with making other allocations lost. if(canMakeOtherLost) { uint32_t tryIndex = 0; for(; tryIndex < VMA_ALLOCATION_TRY_COUNT; ++tryIndex) { VmaDeviceMemoryBlock* pBestRequestBlock = VMA_NULL; VmaAllocationRequest bestRequest = {}; VkDeviceSize bestRequestCost = VK_WHOLE_SIZE; // 1. Search existing allocations. // Forward order in m_Blocks - prefer blocks with smallest amount of free space. for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex ) { VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; VMA_ASSERT(pCurrBlock); VmaAllocationRequest currRequest = {}; if(pCurrBlock->m_Metadata.CreateAllocationRequest( currentFrameIndex, m_FrameInUseCount, m_BufferImageGranularity, vkMemReq.size, vkMemReq.alignment, suballocType, canMakeOtherLost, &currRequest)) { const VkDeviceSize currRequestCost = currRequest.CalcCost(); if(pBestRequestBlock == VMA_NULL || currRequestCost < bestRequestCost) { pBestRequestBlock = pCurrBlock; bestRequest = currRequest; bestRequestCost = currRequestCost; if(bestRequestCost == 0) { break; } } } } if(pBestRequestBlock != VMA_NULL) { if(mapped) { VkResult res = pBestRequestBlock->Map(m_hAllocator, 1, VMA_NULL); if(res != VK_SUCCESS) { return res; } } if(pBestRequestBlock->m_Metadata.MakeRequestedAllocationsLost( currentFrameIndex, m_FrameInUseCount, &bestRequest)) { // We no longer have an empty Allocation. if(pBestRequestBlock->m_Metadata.IsEmpty()) { m_HasEmptyBlock = false; } // Allocate from this pBlock. *pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString); pBestRequestBlock->m_Metadata.Alloc(bestRequest, suballocType, vkMemReq.size, *pAllocation); (*pAllocation)->InitBlockAllocation( hCurrentPool, pBestRequestBlock, bestRequest.offset, vkMemReq.alignment, vkMemReq.size, suballocType, mapped, (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0); VMA_HEAVY_ASSERT(pBestRequestBlock->Validate()); VMA_DEBUG_LOG(" Returned from existing allocation #%u", (uint32_t)blockIndex); (*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData); return VK_SUCCESS; } // else: Some allocations must have been touched while we are here. Next try. } else { // Could not find place in any of the blocks - break outer loop. break; } } /* Maximum number of tries exceeded - a very unlike event when many other threads are simultaneously touching allocations making it impossible to make lost at the same time as we try to allocate. */ if(tryIndex == VMA_ALLOCATION_TRY_COUNT) { return VK_ERROR_TOO_MANY_OBJECTS; } } return VK_ERROR_OUT_OF_DEVICE_MEMORY; } void VmaBlockVector::Free( VmaAllocation hAllocation) { VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL; // Scope for lock. { VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); if(hAllocation->IsPersistentMap()) { pBlock->m_Mapping.Unmap(m_hAllocator, pBlock->m_hMemory, 1); } pBlock->m_Metadata.Free(hAllocation); VMA_HEAVY_ASSERT(pBlock->Validate()); VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", memTypeIndex); // pBlock became empty after this deallocation. if(pBlock->m_Metadata.IsEmpty()) { // Already has empty Allocation. We don't want to have two, so delete this one. if(m_HasEmptyBlock && m_Blocks.size() > m_MinBlockCount) { pBlockToDelete = pBlock; Remove(pBlock); } // We now have first empty Allocation. else { m_HasEmptyBlock = true; } } // pBlock didn't become empty, but we have another empty block - find and free that one. // (This is optional, heuristics.) else if(m_HasEmptyBlock) { VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back(); if(pLastBlock->m_Metadata.IsEmpty() && m_Blocks.size() > m_MinBlockCount) { pBlockToDelete = pLastBlock; m_Blocks.pop_back(); m_HasEmptyBlock = false; } } IncrementallySortBlocks(); } // Destruction of a free Allocation. Deferred until this point, outside of mutex // lock, for performance reason. if(pBlockToDelete != VMA_NULL) { VMA_DEBUG_LOG(" Deleted empty allocation"); pBlockToDelete->Destroy(m_hAllocator); vma_delete(m_hAllocator, pBlockToDelete); } } size_t VmaBlockVector::CalcMaxBlockSize() const { size_t result = 0; for(size_t i = m_Blocks.size(); i--; ) { result = VMA_MAX((uint64_t)result, (uint64_t)m_Blocks[i]->m_Metadata.GetSize()); if(result >= m_PreferredBlockSize) { break; } } return result; } void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock) { for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) { if(m_Blocks[blockIndex] == pBlock) { VmaVectorRemove(m_Blocks, blockIndex); return; } } VMA_ASSERT(0); } void VmaBlockVector::IncrementallySortBlocks() { // Bubble sort only until first swap. for(size_t i = 1; i < m_Blocks.size(); ++i) { if(m_Blocks[i - 1]->m_Metadata.GetSumFreeSize() > m_Blocks[i]->m_Metadata.GetSumFreeSize()) { VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]); return; } } } VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex) { VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; allocInfo.memoryTypeIndex = m_MemoryTypeIndex; allocInfo.allocationSize = blockSize; VkDeviceMemory mem = VK_NULL_HANDLE; VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem); if(res < 0) { return res; } // New VkDeviceMemory successfully created. // Create new Allocation for it. VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator); pBlock->Init( m_MemoryTypeIndex, mem, allocInfo.allocationSize); m_Blocks.push_back(pBlock); if(pNewBlockIndex != VMA_NULL) { *pNewBlockIndex = m_Blocks.size() - 1; } return VK_SUCCESS; } #if VMA_STATS_STRING_ENABLED void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json) { VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); json.BeginObject(); if(m_IsCustomPool) { json.WriteString("MemoryTypeIndex"); json.WriteNumber(m_MemoryTypeIndex); json.WriteString("BlockSize"); json.WriteNumber(m_PreferredBlockSize); json.WriteString("BlockCount"); json.BeginObject(true); if(m_MinBlockCount > 0) { json.WriteString("Min"); json.WriteNumber((uint64_t)m_MinBlockCount); } if(m_MaxBlockCount < SIZE_MAX) { json.WriteString("Max"); json.WriteNumber((uint64_t)m_MaxBlockCount); } json.WriteString("Cur"); json.WriteNumber((uint64_t)m_Blocks.size()); json.EndObject(); if(m_FrameInUseCount > 0) { json.WriteString("FrameInUseCount"); json.WriteNumber(m_FrameInUseCount); } } else { json.WriteString("PreferredBlockSize"); json.WriteNumber(m_PreferredBlockSize); } json.WriteString("Blocks"); json.BeginArray(); for(size_t i = 0; i < m_Blocks.size(); ++i) { m_Blocks[i]->m_Metadata.PrintDetailedMap(json); } json.EndArray(); json.EndObject(); } #endif // #if VMA_STATS_STRING_ENABLED VmaDefragmentator* VmaBlockVector::EnsureDefragmentator( VmaAllocator hAllocator, uint32_t currentFrameIndex) { if(m_pDefragmentator == VMA_NULL) { m_pDefragmentator = vma_new(m_hAllocator, VmaDefragmentator)( hAllocator, this, currentFrameIndex); } return m_pDefragmentator; } VkResult VmaBlockVector::Defragment( VmaDefragmentationStats* pDefragmentationStats, VkDeviceSize& maxBytesToMove, uint32_t& maxAllocationsToMove) { if(m_pDefragmentator == VMA_NULL) { return VK_SUCCESS; } VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); // Defragment. VkResult result = m_pDefragmentator->Defragment(maxBytesToMove, maxAllocationsToMove); // Accumulate statistics. if(pDefragmentationStats != VMA_NULL) { const VkDeviceSize bytesMoved = m_pDefragmentator->GetBytesMoved(); const uint32_t allocationsMoved = m_pDefragmentator->GetAllocationsMoved(); pDefragmentationStats->bytesMoved += bytesMoved; pDefragmentationStats->allocationsMoved += allocationsMoved; VMA_ASSERT(bytesMoved <= maxBytesToMove); VMA_ASSERT(allocationsMoved <= maxAllocationsToMove); maxBytesToMove -= bytesMoved; maxAllocationsToMove -= allocationsMoved; } // Free empty blocks. m_HasEmptyBlock = false; for(size_t blockIndex = m_Blocks.size(); blockIndex--; ) { VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex]; if(pBlock->m_Metadata.IsEmpty()) { if(m_Blocks.size() > m_MinBlockCount) { if(pDefragmentationStats != VMA_NULL) { ++pDefragmentationStats->deviceMemoryBlocksFreed; pDefragmentationStats->bytesFreed += pBlock->m_Metadata.GetSize(); } VmaVectorRemove(m_Blocks, blockIndex); pBlock->Destroy(m_hAllocator); vma_delete(m_hAllocator, pBlock); } else { m_HasEmptyBlock = true; } } } return result; } void VmaBlockVector::DestroyDefragmentator() { if(m_pDefragmentator != VMA_NULL) { vma_delete(m_hAllocator, m_pDefragmentator); m_pDefragmentator = VMA_NULL; } } void VmaBlockVector::MakePoolAllocationsLost( uint32_t currentFrameIndex, size_t* pLostAllocationCount) { VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); size_t lostAllocationCount = 0; for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) { VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; VMA_ASSERT(pBlock); lostAllocationCount += pBlock->m_Metadata.MakeAllocationsLost(currentFrameIndex, m_FrameInUseCount); } if(pLostAllocationCount != VMA_NULL) { *pLostAllocationCount = lostAllocationCount; } } void VmaBlockVector::AddStats(VmaStats* pStats) { const uint32_t memTypeIndex = m_MemoryTypeIndex; const uint32_t memHeapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(memTypeIndex); VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) { const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; VMA_ASSERT(pBlock); VMA_HEAVY_ASSERT(pBlock->Validate()); VmaStatInfo allocationStatInfo; pBlock->m_Metadata.CalcAllocationStatInfo(allocationStatInfo); VmaAddStatInfo(pStats->total, allocationStatInfo); VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo); VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo); } } //////////////////////////////////////////////////////////////////////////////// // VmaDefragmentator members definition VmaDefragmentator::VmaDefragmentator( VmaAllocator hAllocator, VmaBlockVector* pBlockVector, uint32_t currentFrameIndex) : m_hAllocator(hAllocator), m_pBlockVector(pBlockVector), m_CurrentFrameIndex(currentFrameIndex), m_BytesMoved(0), m_AllocationsMoved(0), m_Allocations(VmaStlAllocator<AllocationInfo>(hAllocator->GetAllocationCallbacks())), m_Blocks(VmaStlAllocator<BlockInfo*>(hAllocator->GetAllocationCallbacks())) { } VmaDefragmentator::~VmaDefragmentator() { for(size_t i = m_Blocks.size(); i--; ) { vma_delete(m_hAllocator, m_Blocks[i]); } } void VmaDefragmentator::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged) { AllocationInfo allocInfo; allocInfo.m_hAllocation = hAlloc; allocInfo.m_pChanged = pChanged; m_Allocations.push_back(allocInfo); } VkResult VmaDefragmentator::BlockInfo::EnsureMapping(VmaAllocator hAllocator, void** ppMappedData) { // It has already been mapped for defragmentation. if(m_pMappedDataForDefragmentation) { *ppMappedData = m_pMappedDataForDefragmentation; return VK_SUCCESS; } // It is originally mapped. if(m_pBlock->m_Mapping.GetMappedData()) { *ppMappedData = m_pBlock->m_Mapping.GetMappedData(); return VK_SUCCESS; } // Map on first usage. VkResult res = m_pBlock->Map(hAllocator, 1, &m_pMappedDataForDefragmentation); *ppMappedData = m_pMappedDataForDefragmentation; return res; } void VmaDefragmentator::BlockInfo::Unmap(VmaAllocator hAllocator) { if(m_pMappedDataForDefragmentation != VMA_NULL) { m_pBlock->Unmap(hAllocator, 1); } } VkResult VmaDefragmentator::DefragmentRound( VkDeviceSize maxBytesToMove, uint32_t maxAllocationsToMove) { if(m_Blocks.empty()) { return VK_SUCCESS; } size_t srcBlockIndex = m_Blocks.size() - 1; size_t srcAllocIndex = SIZE_MAX; for(;;) { // 1. Find next allocation to move. // 1.1. Start from last to first m_Blocks - they are sorted from most "destination" to most "source". // 1.2. Then start from last to first m_Allocations - they are sorted from largest to smallest. while(srcAllocIndex >= m_Blocks[srcBlockIndex]->m_Allocations.size()) { if(m_Blocks[srcBlockIndex]->m_Allocations.empty()) { // Finished: no more allocations to process. if(srcBlockIndex == 0) { return VK_SUCCESS; } else { --srcBlockIndex; srcAllocIndex = SIZE_MAX; } } else { srcAllocIndex = m_Blocks[srcBlockIndex]->m_Allocations.size() - 1; } } BlockInfo* pSrcBlockInfo = m_Blocks[srcBlockIndex]; AllocationInfo& allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex]; const VkDeviceSize size = allocInfo.m_hAllocation->GetSize(); const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset(); const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment(); const VmaSuballocationType suballocType = allocInfo.m_hAllocation->GetSuballocationType(); // 2. Try to find new place for this allocation in preceding or current block. for(size_t dstBlockIndex = 0; dstBlockIndex <= srcBlockIndex; ++dstBlockIndex) { BlockInfo* pDstBlockInfo = m_Blocks[dstBlockIndex]; VmaAllocationRequest dstAllocRequest; if(pDstBlockInfo->m_pBlock->m_Metadata.CreateAllocationRequest( m_CurrentFrameIndex, m_pBlockVector->GetFrameInUseCount(), m_pBlockVector->GetBufferImageGranularity(), size, alignment, suballocType, false, // canMakeOtherLost &dstAllocRequest) && MoveMakesSense( dstBlockIndex, dstAllocRequest.offset, srcBlockIndex, srcOffset)) { VMA_ASSERT(dstAllocRequest.itemsToMakeLostCount == 0); // Reached limit on number of allocations or bytes to move. if((m_AllocationsMoved + 1 > maxAllocationsToMove) || (m_BytesMoved + size > maxBytesToMove)) { return VK_INCOMPLETE; } void* pDstMappedData = VMA_NULL; VkResult res = pDstBlockInfo->EnsureMapping(m_hAllocator, &pDstMappedData); if(res != VK_SUCCESS) { return res; } void* pSrcMappedData = VMA_NULL; res = pSrcBlockInfo->EnsureMapping(m_hAllocator, &pSrcMappedData); if(res != VK_SUCCESS) { return res; } // THE PLACE WHERE ACTUAL DATA COPY HAPPENS. memcpy( reinterpret_cast<char*>(pDstMappedData) + dstAllocRequest.offset, reinterpret_cast<char*>(pSrcMappedData) + srcOffset, static_cast<size_t>(size)); pDstBlockInfo->m_pBlock->m_Metadata.Alloc(dstAllocRequest, suballocType, size, allocInfo.m_hAllocation); pSrcBlockInfo->m_pBlock->m_Metadata.FreeAtOffset(srcOffset); allocInfo.m_hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlockInfo->m_pBlock, dstAllocRequest.offset); if(allocInfo.m_pChanged != VMA_NULL) { *allocInfo.m_pChanged = VK_TRUE; } ++m_AllocationsMoved; m_BytesMoved += size; VmaVectorRemove(pSrcBlockInfo->m_Allocations, srcAllocIndex); break; } } // If not processed, this allocInfo remains in pBlockInfo->m_Allocations for next round. if(srcAllocIndex > 0) { --srcAllocIndex; } else { if(srcBlockIndex > 0) { --srcBlockIndex; srcAllocIndex = SIZE_MAX; } else { return VK_SUCCESS; } } } } VkResult VmaDefragmentator::Defragment( VkDeviceSize maxBytesToMove, uint32_t maxAllocationsToMove) { if(m_Allocations.empty()) { return VK_SUCCESS; } // Create block info for each block. const size_t blockCount = m_pBlockVector->m_Blocks.size(); for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { BlockInfo* pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks()); pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex]; m_Blocks.push_back(pBlockInfo); } // Sort them by m_pBlock pointer value. VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockPointerLess()); // Move allocation infos from m_Allocations to appropriate m_Blocks[memTypeIndex].m_Allocations. for(size_t blockIndex = 0, allocCount = m_Allocations.size(); blockIndex < allocCount; ++blockIndex) { AllocationInfo& allocInfo = m_Allocations[blockIndex]; // Now as we are inside VmaBlockVector::m_Mutex, we can make final check if this allocation was not lost. if(allocInfo.m_hAllocation->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST) { VmaDeviceMemoryBlock* pBlock = allocInfo.m_hAllocation->GetBlock(); BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess()); if(it != m_Blocks.end() && (*it)->m_pBlock == pBlock) { (*it)->m_Allocations.push_back(allocInfo); } else { VMA_ASSERT(0); } } } m_Allocations.clear(); for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { BlockInfo* pBlockInfo = m_Blocks[blockIndex]; pBlockInfo->CalcHasNonMovableAllocations(); pBlockInfo->SortAllocationsBySizeDescecnding(); } // Sort m_Blocks this time by the main criterium, from most "destination" to most "source" blocks. VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockInfoCompareMoveDestination()); // Execute defragmentation rounds (the main part). VkResult result = VK_SUCCESS; for(size_t round = 0; (round < 2) && (result == VK_SUCCESS); ++round) { result = DefragmentRound(maxBytesToMove, maxAllocationsToMove); } // Unmap blocks that were mapped for defragmentation. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { m_Blocks[blockIndex]->Unmap(m_hAllocator); } return result; } bool VmaDefragmentator::MoveMakesSense( size_t dstBlockIndex, VkDeviceSize dstOffset, size_t srcBlockIndex, VkDeviceSize srcOffset) { if(dstBlockIndex < srcBlockIndex) { return true; } if(dstBlockIndex > srcBlockIndex) { return false; } if(dstOffset < srcOffset) { return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // VmaAllocator_T VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) : m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0), m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0), m_hDevice(pCreateInfo->device), m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL), m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ? *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks), m_PreferredLargeHeapBlockSize(0), m_PhysicalDevice(pCreateInfo->physicalDevice), m_CurrentFrameIndex(0), m_Pools(VmaStlAllocator<VmaPool>(GetAllocationCallbacks())) { VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device); memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks)); memset(&m_MemProps, 0, sizeof(m_MemProps)); memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties)); memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors)); memset(&m_pDedicatedAllocations, 0, sizeof(m_pDedicatedAllocations)); for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i) { m_HeapSizeLimit[i] = VK_WHOLE_SIZE; } if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL) { m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate; m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree; } ImportVulkanFunctions(pCreateInfo->pVulkanFunctions); (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties); (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps); m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ? pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE); if(pCreateInfo->pHeapSizeLimit != VMA_NULL) { for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex) { const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex]; if(limit != VK_WHOLE_SIZE) { m_HeapSizeLimit[heapIndex] = limit; if(limit < m_MemProps.memoryHeaps[heapIndex].size) { m_MemProps.memoryHeaps[heapIndex].size = limit; } } } } for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex); m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)( this, memTypeIndex, preferredBlockSize, 0, SIZE_MAX, GetBufferImageGranularity(), pCreateInfo->frameInUseCount, false); // isCustomPool // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here, // becase minBlockCount is 0. m_pDedicatedAllocations[memTypeIndex] = vma_new(this, AllocationVectorType)(VmaStlAllocator<VmaAllocation>(GetAllocationCallbacks())); } } VmaAllocator_T::~VmaAllocator_T() { VMA_ASSERT(m_Pools.empty()); for(size_t i = GetMemoryTypeCount(); i--; ) { vma_delete(this, m_pDedicatedAllocations[i]); vma_delete(this, m_pBlockVectors[i]); } } void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions) { #if VMA_STATIC_VULKAN_FUNCTIONS == 1 m_VulkanFunctions.vkGetPhysicalDeviceProperties = &vkGetPhysicalDeviceProperties; m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = &vkGetPhysicalDeviceMemoryProperties; m_VulkanFunctions.vkAllocateMemory = &vkAllocateMemory; m_VulkanFunctions.vkFreeMemory = &vkFreeMemory; m_VulkanFunctions.vkMapMemory = &vkMapMemory; m_VulkanFunctions.vkUnmapMemory = &vkUnmapMemory; m_VulkanFunctions.vkBindBufferMemory = &vkBindBufferMemory; m_VulkanFunctions.vkBindImageMemory = &vkBindImageMemory; m_VulkanFunctions.vkGetBufferMemoryRequirements = &vkGetBufferMemoryRequirements; m_VulkanFunctions.vkGetImageMemoryRequirements = &vkGetImageMemoryRequirements; m_VulkanFunctions.vkCreateBuffer = &vkCreateBuffer; m_VulkanFunctions.vkDestroyBuffer = &vkDestroyBuffer; m_VulkanFunctions.vkCreateImage = &vkCreateImage; m_VulkanFunctions.vkDestroyImage = &vkDestroyImage; if(m_UseKhrDedicatedAllocation) { m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetBufferMemoryRequirements2KHR"); m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetImageMemoryRequirements2KHR"); } #endif // #if VMA_STATIC_VULKAN_FUNCTIONS == 1 #define VMA_COPY_IF_NOT_NULL(funcName) \ if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName; if(pVulkanFunctions != VMA_NULL) { VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties); VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties); VMA_COPY_IF_NOT_NULL(vkAllocateMemory); VMA_COPY_IF_NOT_NULL(vkFreeMemory); VMA_COPY_IF_NOT_NULL(vkMapMemory); VMA_COPY_IF_NOT_NULL(vkUnmapMemory); VMA_COPY_IF_NOT_NULL(vkBindBufferMemory); VMA_COPY_IF_NOT_NULL(vkBindImageMemory); VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements); VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements); VMA_COPY_IF_NOT_NULL(vkCreateBuffer); VMA_COPY_IF_NOT_NULL(vkDestroyBuffer); VMA_COPY_IF_NOT_NULL(vkCreateImage); VMA_COPY_IF_NOT_NULL(vkDestroyImage); VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR); VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR); } #undef VMA_COPY_IF_NOT_NULL // If these asserts are hit, you must either #define VMA_STATIC_VULKAN_FUNCTIONS 1 // or pass valid pointers as VmaAllocatorCreateInfo::pVulkanFunctions. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL); if(m_UseKhrDedicatedAllocation) { VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL); } } VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex) { const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE; return isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize; } VkResult VmaAllocator_T::AllocateMemoryOfType( const VkMemoryRequirements& vkMemReq, bool dedicatedAllocation, VkBuffer dedicatedBuffer, VkImage dedicatedImage, const VmaAllocationCreateInfo& createInfo, uint32_t memTypeIndex, VmaSuballocationType suballocType, VmaAllocation* pAllocation) { VMA_ASSERT(pAllocation != VMA_NULL); VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, Size=%llu", memTypeIndex, vkMemReq.size); VmaAllocationCreateInfo finalCreateInfo = createInfo; // If memory type is not HOST_VISIBLE, disable MAPPED. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 && (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { finalCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT; } VmaBlockVector* const blockVector = m_pBlockVectors[memTypeIndex]; VMA_ASSERT(blockVector); const VkDeviceSize preferredBlockSize = blockVector->GetPreferredBlockSize(); bool preferDedicatedMemory = VMA_DEBUG_ALWAYS_DEDICATED_MEMORY || dedicatedAllocation || // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size. vkMemReq.size > preferredBlockSize / 2; if(preferDedicatedMemory && (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 && finalCreateInfo.pool == VK_NULL_HANDLE) { finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; } if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0) { if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) { return VK_ERROR_OUT_OF_DEVICE_MEMORY; } else { return AllocateDedicatedMemory( vkMemReq.size, suballocType, memTypeIndex, (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, finalCreateInfo.pUserData, dedicatedBuffer, dedicatedImage, pAllocation); } } else { VkResult res = blockVector->Allocate( VK_NULL_HANDLE, // hCurrentPool m_CurrentFrameIndex.load(), vkMemReq, finalCreateInfo, suballocType, pAllocation); if(res == VK_SUCCESS) { return res; } // 5. Try dedicated memory. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) { return VK_ERROR_OUT_OF_DEVICE_MEMORY; } else { res = AllocateDedicatedMemory( vkMemReq.size, suballocType, memTypeIndex, (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, finalCreateInfo.pUserData, dedicatedBuffer, dedicatedImage, pAllocation); if(res == VK_SUCCESS) { // Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here. VMA_DEBUG_LOG(" Allocated as DedicatedMemory"); return VK_SUCCESS; } else { // Everything failed: Return error code. VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); return res; } } } } VkResult VmaAllocator_T::AllocateDedicatedMemory( VkDeviceSize size, VmaSuballocationType suballocType, uint32_t memTypeIndex, bool map, bool isUserDataString, void* pUserData, VkBuffer dedicatedBuffer, VkImage dedicatedImage, VmaAllocation* pAllocation) { VMA_ASSERT(pAllocation); VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; allocInfo.memoryTypeIndex = memTypeIndex; allocInfo.allocationSize = size; VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR }; if(m_UseKhrDedicatedAllocation) { if(dedicatedBuffer != VK_NULL_HANDLE) { VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE); dedicatedAllocInfo.buffer = dedicatedBuffer; allocInfo.pNext = &dedicatedAllocInfo; } else if(dedicatedImage != VK_NULL_HANDLE) { dedicatedAllocInfo.image = dedicatedImage; allocInfo.pNext = &dedicatedAllocInfo; } } // Allocate VkDeviceMemory. VkDeviceMemory hMemory = VK_NULL_HANDLE; VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory); if(res < 0) { VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); return res; } void* pMappedData = VMA_NULL; if(map) { res = (*m_VulkanFunctions.vkMapMemory)( m_hDevice, hMemory, 0, VK_WHOLE_SIZE, 0, &pMappedData); if(res < 0) { VMA_DEBUG_LOG(" vkMapMemory FAILED"); FreeVulkanMemory(memTypeIndex, size, hMemory); return res; } } *pAllocation = vma_new(this, VmaAllocation_T)(m_CurrentFrameIndex.load(), isUserDataString); (*pAllocation)->InitDedicatedAllocation(memTypeIndex, hMemory, suballocType, pMappedData, size); (*pAllocation)->SetUserData(this, pUserData); // Register it in m_pDedicatedAllocations. { VmaMutexLock lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); AllocationVectorType* pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex]; VMA_ASSERT(pDedicatedAllocations); VmaVectorInsertSorted<VmaPointerLess>(*pDedicatedAllocations, *pAllocation); } VMA_DEBUG_LOG(" Allocated DedicatedMemory MemoryTypeIndex=#%u", memTypeIndex); return VK_SUCCESS; } void VmaAllocator_T::GetBufferMemoryRequirements( VkBuffer hBuffer, VkMemoryRequirements& memReq, bool& requiresDedicatedAllocation, bool& prefersDedicatedAllocation) const { if(m_UseKhrDedicatedAllocation) { VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR }; memReqInfo.buffer = hBuffer; VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR }; VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR }; memReq2.pNext = &memDedicatedReq; (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); memReq = memReq2.memoryRequirements; requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); } else { (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq); requiresDedicatedAllocation = false; prefersDedicatedAllocation = false; } } void VmaAllocator_T::GetImageMemoryRequirements( VkImage hImage, VkMemoryRequirements& memReq, bool& requiresDedicatedAllocation, bool& prefersDedicatedAllocation) const { if(m_UseKhrDedicatedAllocation) { VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR }; memReqInfo.image = hImage; VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR }; VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR }; memReq2.pNext = &memDedicatedReq; (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); memReq = memReq2.memoryRequirements; requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); } else { (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq); requiresDedicatedAllocation = false; prefersDedicatedAllocation = false; } } VkResult VmaAllocator_T::AllocateMemory( const VkMemoryRequirements& vkMemReq, bool requiresDedicatedAllocation, bool prefersDedicatedAllocation, VkBuffer dedicatedBuffer, VkImage dedicatedImage, const VmaAllocationCreateInfo& createInfo, VmaSuballocationType suballocType, VmaAllocation* pAllocation) { if((createInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 && (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) { VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense."); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } if((createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 && (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0) { VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_MAPPED_BIT together with VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT is invalid."); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } if(requiresDedicatedAllocation) { if((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) { VMA_ASSERT(0 && "VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT specified while dedicated allocation is required."); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } if(createInfo.pool != VK_NULL_HANDLE) { VMA_ASSERT(0 && "Pool specified while dedicated allocation is required."); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } } if((createInfo.pool != VK_NULL_HANDLE) && ((createInfo.flags & (VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT)) != 0)) { VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT when pool != null is invalid."); return VK_ERROR_OUT_OF_DEVICE_MEMORY; } if(createInfo.pool != VK_NULL_HANDLE) { return createInfo.pool->m_BlockVector.Allocate( createInfo.pool, m_CurrentFrameIndex.load(), vkMemReq, createInfo, suballocType, pAllocation); } else { // Bit mask of memory Vulkan types acceptable for this allocation. uint32_t memoryTypeBits = vkMemReq.memoryTypeBits; uint32_t memTypeIndex = UINT32_MAX; VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex); if(res == VK_SUCCESS) { res = AllocateMemoryOfType( vkMemReq, requiresDedicatedAllocation || prefersDedicatedAllocation, dedicatedBuffer, dedicatedImage, createInfo, memTypeIndex, suballocType, pAllocation); // Succeeded on first try. if(res == VK_SUCCESS) { return res; } // Allocation from this memory type failed. Try other compatible memory types. else { for(;;) { // Remove old memTypeIndex from list of possibilities. memoryTypeBits &= ~(1u << memTypeIndex); // Find alternative memTypeIndex. res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex); if(res == VK_SUCCESS) { res = AllocateMemoryOfType( vkMemReq, requiresDedicatedAllocation || prefersDedicatedAllocation, dedicatedBuffer, dedicatedImage, createInfo, memTypeIndex, suballocType, pAllocation); // Allocation from this alternative memory type succeeded. if(res == VK_SUCCESS) { return res; } // else: Allocation from this memory type failed. Try next one - next loop iteration. } // No other matching memory type index could be found. else { // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once. return VK_ERROR_OUT_OF_DEVICE_MEMORY; } } } } // Can't find any single memory type maching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT. else return res; } } void VmaAllocator_T::FreeMemory(const VmaAllocation allocation) { VMA_ASSERT(allocation); if(allocation->CanBecomeLost() == false || allocation->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST) { switch(allocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaBlockVector* pBlockVector = VMA_NULL; VmaPool hPool = allocation->GetPool(); if(hPool != VK_NULL_HANDLE) { pBlockVector = &hPool->m_BlockVector; } else { const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); pBlockVector = m_pBlockVectors[memTypeIndex]; } pBlockVector->Free(allocation); } break; case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: FreeDedicatedMemory(allocation); break; default: VMA_ASSERT(0); } } allocation->SetUserData(this, VMA_NULL); vma_delete(this, allocation); } void VmaAllocator_T::CalculateStats(VmaStats* pStats) { // Initialize. InitStatInfo(pStats->total); for(size_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i) InitStatInfo(pStats->memoryType[i]); for(size_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i) InitStatInfo(pStats->memoryHeap[i]); // Process default pools. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex]; VMA_ASSERT(pBlockVector); pBlockVector->AddStats(pStats); } // Process custom pools. { VmaMutexLock lock(m_PoolsMutex, m_UseMutex); for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex) { m_Pools[poolIndex]->GetBlockVector().AddStats(pStats); } } // Process dedicated allocations. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); VmaMutexLock dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex]; VMA_ASSERT(pDedicatedAllocVector); for(size_t allocIndex = 0, allocCount = pDedicatedAllocVector->size(); allocIndex < allocCount; ++allocIndex) { VmaStatInfo allocationStatInfo; (*pDedicatedAllocVector)[allocIndex]->DedicatedAllocCalcStatsInfo(allocationStatInfo); VmaAddStatInfo(pStats->total, allocationStatInfo); VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo); VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo); } } // Postprocess. VmaPostprocessCalcStatInfo(pStats->total); for(size_t i = 0; i < GetMemoryTypeCount(); ++i) VmaPostprocessCalcStatInfo(pStats->memoryType[i]); for(size_t i = 0; i < GetMemoryHeapCount(); ++i) VmaPostprocessCalcStatInfo(pStats->memoryHeap[i]); } static const uint32_t VMA_VENDOR_ID_AMD = 4098; VkResult VmaAllocator_T::Defragment( VmaAllocation* pAllocations, size_t allocationCount, VkBool32* pAllocationsChanged, const VmaDefragmentationInfo* pDefragmentationInfo, VmaDefragmentationStats* pDefragmentationStats) { if(pAllocationsChanged != VMA_NULL) { memset(pAllocationsChanged, 0, sizeof(*pAllocationsChanged)); } if(pDefragmentationStats != VMA_NULL) { memset(pDefragmentationStats, 0, sizeof(*pDefragmentationStats)); } const uint32_t currentFrameIndex = m_CurrentFrameIndex.load(); VmaMutexLock poolsLock(m_PoolsMutex, m_UseMutex); const size_t poolCount = m_Pools.size(); // Dispatch pAllocations among defragmentators. Create them in BlockVectors when necessary. for(size_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex) { VmaAllocation hAlloc = pAllocations[allocIndex]; VMA_ASSERT(hAlloc); const uint32_t memTypeIndex = hAlloc->GetMemoryTypeIndex(); // DedicatedAlloc cannot be defragmented. if((hAlloc->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK) && // Only HOST_VISIBLE memory types can be defragmented. ((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) && // Lost allocation cannot be defragmented. (hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST)) { VmaBlockVector* pAllocBlockVector = VMA_NULL; const VmaPool hAllocPool = hAlloc->GetPool(); // This allocation belongs to custom pool. if(hAllocPool != VK_NULL_HANDLE) { pAllocBlockVector = &hAllocPool->GetBlockVector(); } // This allocation belongs to general pool. else { pAllocBlockVector = m_pBlockVectors[memTypeIndex]; } VmaDefragmentator* const pDefragmentator = pAllocBlockVector->EnsureDefragmentator(this, currentFrameIndex); VkBool32* const pChanged = (pAllocationsChanged != VMA_NULL) ? &pAllocationsChanged[allocIndex] : VMA_NULL; pDefragmentator->AddAllocation(hAlloc, pChanged); } } VkResult result = VK_SUCCESS; // ======== Main processing. VkDeviceSize maxBytesToMove = SIZE_MAX; uint32_t maxAllocationsToMove = UINT32_MAX; if(pDefragmentationInfo != VMA_NULL) { maxBytesToMove = pDefragmentationInfo->maxBytesToMove; maxAllocationsToMove = pDefragmentationInfo->maxAllocationsToMove; } // Process standard memory. for(uint32_t memTypeIndex = 0; (memTypeIndex < GetMemoryTypeCount()) && (result == VK_SUCCESS); ++memTypeIndex) { // Only HOST_VISIBLE memory types can be defragmented. if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { result = m_pBlockVectors[memTypeIndex]->Defragment( pDefragmentationStats, maxBytesToMove, maxAllocationsToMove); } } // Process custom pools. for(size_t poolIndex = 0; (poolIndex < poolCount) && (result == VK_SUCCESS); ++poolIndex) { result = m_Pools[poolIndex]->GetBlockVector().Defragment( pDefragmentationStats, maxBytesToMove, maxAllocationsToMove); } // ======== Destroy defragmentators. // Process custom pools. for(size_t poolIndex = poolCount; poolIndex--; ) { m_Pools[poolIndex]->GetBlockVector().DestroyDefragmentator(); } // Process standard memory. for(uint32_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; ) { if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { m_pBlockVectors[memTypeIndex]->DestroyDefragmentator(); } } return result; } void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo) { if(hAllocation->CanBecomeLost()) { /* Warning: This is a carefully designed algorithm. Do not modify unless you really know what you're doing :) */ uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for(;;) { if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST) { pAllocationInfo->memoryType = UINT32_MAX; pAllocationInfo->deviceMemory = VK_NULL_HANDLE; pAllocationInfo->offset = 0; pAllocationInfo->size = hAllocation->GetSize(); pAllocationInfo->pMappedData = VMA_NULL; pAllocationInfo->pUserData = hAllocation->GetUserData(); return; } else if(localLastUseFrameIndex == localCurrFrameIndex) { pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); pAllocationInfo->deviceMemory = hAllocation->GetMemory(); pAllocationInfo->offset = hAllocation->GetOffset(); pAllocationInfo->size = hAllocation->GetSize(); pAllocationInfo->pMappedData = VMA_NULL; pAllocationInfo->pUserData = hAllocation->GetUserData(); return; } else // Last use time earlier than current time. { if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex)) { localLastUseFrameIndex = localCurrFrameIndex; } } } } else { pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); pAllocationInfo->deviceMemory = hAllocation->GetMemory(); pAllocationInfo->offset = hAllocation->GetOffset(); pAllocationInfo->size = hAllocation->GetSize(); pAllocationInfo->pMappedData = hAllocation->GetMappedData(); pAllocationInfo->pUserData = hAllocation->GetUserData(); } } VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool) { VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u", pCreateInfo->memoryTypeIndex); VmaPoolCreateInfo newCreateInfo = *pCreateInfo; if(newCreateInfo.maxBlockCount == 0) { newCreateInfo.maxBlockCount = SIZE_MAX; } if(newCreateInfo.blockSize == 0) { newCreateInfo.blockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex); } *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo); VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks(); if(res != VK_SUCCESS) { vma_delete(this, *pPool); *pPool = VMA_NULL; return res; } // Add to m_Pools. { VmaMutexLock lock(m_PoolsMutex, m_UseMutex); VmaVectorInsertSorted<VmaPointerLess>(m_Pools, *pPool); } return VK_SUCCESS; } void VmaAllocator_T::DestroyPool(VmaPool pool) { // Remove from m_Pools. { VmaMutexLock lock(m_PoolsMutex, m_UseMutex); bool success = VmaVectorRemoveSorted<VmaPointerLess>(m_Pools, pool); VMA_ASSERT(success && "Pool not found in Allocator."); } vma_delete(this, pool); } void VmaAllocator_T::GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats) { pool->m_BlockVector.GetPoolStats(pPoolStats); } void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex) { m_CurrentFrameIndex.store(frameIndex); } void VmaAllocator_T::MakePoolAllocationsLost( VmaPool hPool, size_t* pLostAllocationCount) { hPool->m_BlockVector.MakePoolAllocationsLost( m_CurrentFrameIndex.load(), pLostAllocationCount); } void VmaAllocator_T::CreateLostAllocation(VmaAllocation* pAllocation) { *pAllocation = vma_new(this, VmaAllocation_T)(VMA_FRAME_INDEX_LOST, false); (*pAllocation)->InitLost(); } VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory) { const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex); VkResult res; if(m_HeapSizeLimit[heapIndex] != VK_WHOLE_SIZE) { VmaMutexLock lock(m_HeapSizeLimitMutex, m_UseMutex); if(m_HeapSizeLimit[heapIndex] >= pAllocateInfo->allocationSize) { res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory); if(res == VK_SUCCESS) { m_HeapSizeLimit[heapIndex] -= pAllocateInfo->allocationSize; } } else { res = VK_ERROR_OUT_OF_DEVICE_MEMORY; } } else { res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory); } if(res == VK_SUCCESS && m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL) { (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize); } return res; } void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory) { if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL) { (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size); } (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks()); const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType); if(m_HeapSizeLimit[heapIndex] != VK_WHOLE_SIZE) { VmaMutexLock lock(m_HeapSizeLimitMutex, m_UseMutex); m_HeapSizeLimit[heapIndex] += size; } } VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData) { if(hAllocation->CanBecomeLost()) { return VK_ERROR_MEMORY_MAP_FAILED; } switch(hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); char *pBytes = VMA_NULL; VkResult res = pBlock->Map(this, 1, (void**)&pBytes); if(res == VK_SUCCESS) { *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset(); hAllocation->BlockAllocMap(); } return res; } case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: return hAllocation->DedicatedAllocMap(this, ppData); default: VMA_ASSERT(0); return VK_ERROR_MEMORY_MAP_FAILED; } } void VmaAllocator_T::Unmap(VmaAllocation hAllocation) { switch(hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); hAllocation->BlockAllocUnmap(); pBlock->Unmap(this, 1); } break; case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: hAllocation->DedicatedAllocUnmap(this); break; default: VMA_ASSERT(0); } } void VmaAllocator_T::FreeDedicatedMemory(VmaAllocation allocation) { VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); { VmaMutexLock lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); AllocationVectorType* const pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex]; VMA_ASSERT(pDedicatedAllocations); bool success = VmaVectorRemoveSorted<VmaPointerLess>(*pDedicatedAllocations, allocation); VMA_ASSERT(success); } VkDeviceMemory hMemory = allocation->GetMemory(); if(allocation->GetMappedData() != VMA_NULL) { (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory); } FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory); VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex); } #if VMA_STATS_STRING_ENABLED void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json) { bool dedicatedAllocationsStarted = false; for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { VmaMutexLock dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex); AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex]; VMA_ASSERT(pDedicatedAllocVector); if(pDedicatedAllocVector->empty() == false) { if(dedicatedAllocationsStarted == false) { dedicatedAllocationsStarted = true; json.WriteString("DedicatedAllocations"); json.BeginObject(); } json.BeginString("Type "); json.ContinueString(memTypeIndex); json.EndString(); json.BeginArray(); for(size_t i = 0; i < pDedicatedAllocVector->size(); ++i) { const VmaAllocation hAlloc = (*pDedicatedAllocVector)[i]; json.BeginObject(true); json.WriteString("Type"); json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[hAlloc->GetSuballocationType()]); json.WriteString("Size"); json.WriteNumber(hAlloc->GetSize()); const void* pUserData = hAlloc->GetUserData(); if(pUserData != VMA_NULL) { json.WriteString("UserData"); if(hAlloc->IsUserDataString()) { json.WriteString((const char*)pUserData); } else { json.BeginString(); json.ContinueString_Pointer(pUserData); json.EndString(); } } json.EndObject(); } json.EndArray(); } } if(dedicatedAllocationsStarted) { json.EndObject(); } { bool allocationsStarted = false; for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { if(m_pBlockVectors[memTypeIndex]->IsEmpty() == false) { if(allocationsStarted == false) { allocationsStarted = true; json.WriteString("DefaultPools"); json.BeginObject(); } json.BeginString("Type "); json.ContinueString(memTypeIndex); json.EndString(); m_pBlockVectors[memTypeIndex]->PrintDetailedMap(json); } } if(allocationsStarted) { json.EndObject(); } } { VmaMutexLock lock(m_PoolsMutex, m_UseMutex); const size_t poolCount = m_Pools.size(); if(poolCount > 0) { json.WriteString("Pools"); json.BeginArray(); for(size_t poolIndex = 0; poolIndex < poolCount; ++poolIndex) { m_Pools[poolIndex]->m_BlockVector.PrintDetailedMap(json); } json.EndArray(); } } } #endif // #if VMA_STATS_STRING_ENABLED static VkResult AllocateMemoryForImage( VmaAllocator allocator, VkImage image, const VmaAllocationCreateInfo* pAllocationCreateInfo, VmaSuballocationType suballocType, VmaAllocation* pAllocation) { VMA_ASSERT(allocator && (image != VK_NULL_HANDLE) && pAllocationCreateInfo && pAllocation); VkMemoryRequirements vkMemReq = {}; bool requiresDedicatedAllocation = false; bool prefersDedicatedAllocation = false; allocator->GetImageMemoryRequirements(image, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); return allocator->AllocateMemory( vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, VK_NULL_HANDLE, // dedicatedBuffer image, // dedicatedImage *pAllocationCreateInfo, suballocType, pAllocation); } //////////////////////////////////////////////////////////////////////////////// // Public interface VkResult vmaCreateAllocator( const VmaAllocatorCreateInfo* pCreateInfo, VmaAllocator* pAllocator) { VMA_ASSERT(pCreateInfo && pAllocator); VMA_DEBUG_LOG("vmaCreateAllocator"); *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo); return VK_SUCCESS; } void vmaDestroyAllocator( VmaAllocator allocator) { if(allocator != VK_NULL_HANDLE) { VMA_DEBUG_LOG("vmaDestroyAllocator"); VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks; vma_delete(&allocationCallbacks, allocator); } } void vmaGetPhysicalDeviceProperties( VmaAllocator allocator, const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties) { VMA_ASSERT(allocator && ppPhysicalDeviceProperties); *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties; } void vmaGetMemoryProperties( VmaAllocator allocator, const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties) { VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties); *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps; } void vmaGetMemoryTypeProperties( VmaAllocator allocator, uint32_t memoryTypeIndex, VkMemoryPropertyFlags* pFlags) { VMA_ASSERT(allocator && pFlags); VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount()); *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags; } void vmaSetCurrentFrameIndex( VmaAllocator allocator, uint32_t frameIndex) { VMA_ASSERT(allocator); VMA_ASSERT(frameIndex != VMA_FRAME_INDEX_LOST); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->SetCurrentFrameIndex(frameIndex); } void vmaCalculateStats( VmaAllocator allocator, VmaStats* pStats) { VMA_ASSERT(allocator && pStats); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->CalculateStats(pStats); } #if VMA_STATS_STRING_ENABLED void vmaBuildStatsString( VmaAllocator allocator, char** ppStatsString, VkBool32 detailedMap) { VMA_ASSERT(allocator && ppStatsString); VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaStringBuilder sb(allocator); { VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb); json.BeginObject(); VmaStats stats; allocator->CalculateStats(&stats); json.WriteString("Total"); VmaPrintStatInfo(json, stats.total); for(uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex) { json.BeginString("Heap "); json.ContinueString(heapIndex); json.EndString(); json.BeginObject(); json.WriteString("Size"); json.WriteNumber(allocator->m_MemProps.memoryHeaps[heapIndex].size); json.WriteString("Flags"); json.BeginArray(true); if((allocator->m_MemProps.memoryHeaps[heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0) { json.WriteString("DEVICE_LOCAL"); } json.EndArray(); if(stats.memoryHeap[heapIndex].blockCount > 0) { json.WriteString("Stats"); VmaPrintStatInfo(json, stats.memoryHeap[heapIndex]); } for(uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex) { if(allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex) { json.BeginString("Type "); json.ContinueString(typeIndex); json.EndString(); json.BeginObject(); json.WriteString("Flags"); json.BeginArray(true); VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags; if((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) { json.WriteString("DEVICE_LOCAL"); } if((flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { json.WriteString("HOST_VISIBLE"); } if((flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0) { json.WriteString("HOST_COHERENT"); } if((flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0) { json.WriteString("HOST_CACHED"); } if((flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) != 0) { json.WriteString("LAZILY_ALLOCATED"); } json.EndArray(); if(stats.memoryType[typeIndex].blockCount > 0) { json.WriteString("Stats"); VmaPrintStatInfo(json, stats.memoryType[typeIndex]); } json.EndObject(); } } json.EndObject(); } if(detailedMap == VK_TRUE) { allocator->PrintDetailedMap(json); } json.EndObject(); } const size_t len = sb.GetLength(); char* const pChars = vma_new_array(allocator, char, len + 1); if(len > 0) { memcpy(pChars, sb.GetData(), len); } pChars[len] = '\0'; *ppStatsString = pChars; } void vmaFreeStatsString( VmaAllocator allocator, char* pStatsString) { if(pStatsString != VMA_NULL) { VMA_ASSERT(allocator); size_t len = strlen(pStatsString); vma_delete_array(allocator, pStatsString, len + 1); } } #endif // #if VMA_STATS_STRING_ENABLED /* This function is not protected by any mutex because it just reads immutable data. */ VkResult vmaFindMemoryTypeIndex( VmaAllocator allocator, uint32_t memoryTypeBits, const VmaAllocationCreateInfo* pAllocationCreateInfo, uint32_t* pMemoryTypeIndex) { VMA_ASSERT(allocator != VK_NULL_HANDLE); VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); if(pAllocationCreateInfo->memoryTypeBits != 0) { memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits; } uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags; uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags; // Convert usage to requiredFlags and preferredFlags. switch(pAllocationCreateInfo->usage) { case VMA_MEMORY_USAGE_UNKNOWN: break; case VMA_MEMORY_USAGE_GPU_ONLY: preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; break; case VMA_MEMORY_USAGE_CPU_ONLY: requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; break; case VMA_MEMORY_USAGE_CPU_TO_GPU: requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; break; case VMA_MEMORY_USAGE_GPU_TO_CPU: requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; preferredFlags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; break; default: break; } *pMemoryTypeIndex = UINT32_MAX; uint32_t minCost = UINT32_MAX; for(uint32_t memTypeIndex = 0, memTypeBit = 1; memTypeIndex < allocator->GetMemoryTypeCount(); ++memTypeIndex, memTypeBit <<= 1) { // This memory type is acceptable according to memoryTypeBits bitmask. if((memTypeBit & memoryTypeBits) != 0) { const VkMemoryPropertyFlags currFlags = allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags; // This memory type contains requiredFlags. if((requiredFlags & ~currFlags) == 0) { // Calculate cost as number of bits from preferredFlags not present in this memory type. uint32_t currCost = VmaCountBitsSet(preferredFlags & ~currFlags); // Remember memory type with lowest cost. if(currCost < minCost) { *pMemoryTypeIndex = memTypeIndex; if(currCost == 0) { return VK_SUCCESS; } minCost = currCost; } } } } return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT; } VkResult vmaCreatePool( VmaAllocator allocator, const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool) { VMA_ASSERT(allocator && pCreateInfo && pPool); VMA_DEBUG_LOG("vmaCreatePool"); VMA_DEBUG_GLOBAL_MUTEX_LOCK return allocator->CreatePool(pCreateInfo, pPool); } void vmaDestroyPool( VmaAllocator allocator, VmaPool pool) { VMA_ASSERT(allocator); if(pool == VK_NULL_HANDLE) { return; } VMA_DEBUG_LOG("vmaDestroyPool"); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->DestroyPool(pool); } void vmaGetPoolStats( VmaAllocator allocator, VmaPool pool, VmaPoolStats* pPoolStats) { VMA_ASSERT(allocator && pool && pPoolStats); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->GetPoolStats(pool, pPoolStats); } void vmaMakePoolAllocationsLost( VmaAllocator allocator, VmaPool pool, size_t* pLostAllocationCount) { VMA_ASSERT(allocator && pool); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->MakePoolAllocationsLost(pool, pLostAllocationCount); } VkResult vmaAllocateMemory( VmaAllocator allocator, const VkMemoryRequirements* pVkMemoryRequirements, const VmaAllocationCreateInfo* pCreateInfo, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation); VMA_DEBUG_LOG("vmaAllocateMemory"); VMA_DEBUG_GLOBAL_MUTEX_LOCK VkResult result = allocator->AllocateMemory( *pVkMemoryRequirements, false, // requiresDedicatedAllocation false, // prefersDedicatedAllocation VK_NULL_HANDLE, // dedicatedBuffer VK_NULL_HANDLE, // dedicatedImage *pCreateInfo, VMA_SUBALLOCATION_TYPE_UNKNOWN, pAllocation); if(pAllocationInfo && result == VK_SUCCESS) { allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); } return result; } VkResult vmaAllocateMemoryForBuffer( VmaAllocator allocator, VkBuffer buffer, const VmaAllocationCreateInfo* pCreateInfo, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation); VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer"); VMA_DEBUG_GLOBAL_MUTEX_LOCK VkMemoryRequirements vkMemReq = {}; bool requiresDedicatedAllocation = false; bool prefersDedicatedAllocation = false; allocator->GetBufferMemoryRequirements(buffer, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); VkResult result = allocator->AllocateMemory( vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, buffer, // dedicatedBuffer VK_NULL_HANDLE, // dedicatedImage *pCreateInfo, VMA_SUBALLOCATION_TYPE_BUFFER, pAllocation); if(pAllocationInfo && result == VK_SUCCESS) { allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); } return result; } VkResult vmaAllocateMemoryForImage( VmaAllocator allocator, VkImage image, const VmaAllocationCreateInfo* pCreateInfo, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation); VMA_DEBUG_LOG("vmaAllocateMemoryForImage"); VMA_DEBUG_GLOBAL_MUTEX_LOCK VkResult result = AllocateMemoryForImage( allocator, image, pCreateInfo, VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN, pAllocation); if(pAllocationInfo && result == VK_SUCCESS) { allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); } return result; } void vmaFreeMemory( VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_LOG("vmaFreeMemory"); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->FreeMemory(allocation); } void vmaGetAllocationInfo( VmaAllocator allocator, VmaAllocation allocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && allocation && pAllocationInfo); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->GetAllocationInfo(allocation, pAllocationInfo); } void vmaSetAllocationUserData( VmaAllocator allocator, VmaAllocation allocation, void* pUserData) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocation->SetUserData(allocator, pUserData); } void vmaCreateLostAllocation( VmaAllocator allocator, VmaAllocation* pAllocation) { VMA_ASSERT(allocator && pAllocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK; allocator->CreateLostAllocation(pAllocation); } VkResult vmaMapMemory( VmaAllocator allocator, VmaAllocation allocation, void** ppData) { VMA_ASSERT(allocator && allocation && ppData); VMA_DEBUG_GLOBAL_MUTEX_LOCK return allocator->Map(allocation, ppData); } void vmaUnmapMemory( VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->Unmap(allocation); } VkResult vmaDefragment( VmaAllocator allocator, VmaAllocation* pAllocations, size_t allocationCount, VkBool32* pAllocationsChanged, const VmaDefragmentationInfo *pDefragmentationInfo, VmaDefragmentationStats* pDefragmentationStats) { VMA_ASSERT(allocator && pAllocations); VMA_DEBUG_LOG("vmaDefragment"); VMA_DEBUG_GLOBAL_MUTEX_LOCK return allocator->Defragment(pAllocations, allocationCount, pAllocationsChanged, pDefragmentationInfo, pDefragmentationStats); } VkResult vmaCreateBuffer( VmaAllocator allocator, const VkBufferCreateInfo* pBufferCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, VkBuffer* pBuffer, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation); VMA_DEBUG_LOG("vmaCreateBuffer"); VMA_DEBUG_GLOBAL_MUTEX_LOCK *pBuffer = VK_NULL_HANDLE; *pAllocation = VK_NULL_HANDLE; // 1. Create VkBuffer. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( allocator->m_hDevice, pBufferCreateInfo, allocator->GetAllocationCallbacks(), pBuffer); if(res >= 0) { // 2. vkGetBufferMemoryRequirements. VkMemoryRequirements vkMemReq = {}; bool requiresDedicatedAllocation = false; bool prefersDedicatedAllocation = false; allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); // Make sure alignment requirements for specific buffer usages reported // in Physical Device Properties are included in alignment reported by memory requirements. if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) != 0) { VMA_ASSERT(vkMemReq.alignment % allocator->m_PhysicalDeviceProperties.limits.minTexelBufferOffsetAlignment == 0); } if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) != 0) { VMA_ASSERT(vkMemReq.alignment % allocator->m_PhysicalDeviceProperties.limits.minUniformBufferOffsetAlignment == 0); } if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0) { VMA_ASSERT(vkMemReq.alignment % allocator->m_PhysicalDeviceProperties.limits.minStorageBufferOffsetAlignment == 0); } // 3. Allocate memory using allocator. res = allocator->AllocateMemory( vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, *pBuffer, // dedicatedBuffer VK_NULL_HANDLE, // dedicatedImage *pAllocationCreateInfo, VMA_SUBALLOCATION_TYPE_BUFFER, pAllocation); if(res >= 0) { // 3. Bind buffer with memory. res = (*allocator->GetVulkanFunctions().vkBindBufferMemory)( allocator->m_hDevice, *pBuffer, (*pAllocation)->GetMemory(), (*pAllocation)->GetOffset()); if(res >= 0) { // All steps succeeded. if(pAllocationInfo != VMA_NULL) { allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); } return VK_SUCCESS; } allocator->FreeMemory(*pAllocation); *pAllocation = VK_NULL_HANDLE; (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); *pBuffer = VK_NULL_HANDLE; return res; } (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); *pBuffer = VK_NULL_HANDLE; return res; } return res; } void vmaDestroyBuffer( VmaAllocator allocator, VkBuffer buffer, VmaAllocation allocation) { if(buffer != VK_NULL_HANDLE) { VMA_ASSERT(allocator); VMA_DEBUG_LOG("vmaDestroyBuffer"); VMA_DEBUG_GLOBAL_MUTEX_LOCK (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks()); allocator->FreeMemory(allocation); } } VkResult vmaCreateImage( VmaAllocator allocator, const VkImageCreateInfo* pImageCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, VkImage* pImage, VmaAllocation* pAllocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation); VMA_DEBUG_LOG("vmaCreateImage"); VMA_DEBUG_GLOBAL_MUTEX_LOCK *pImage = VK_NULL_HANDLE; *pAllocation = VK_NULL_HANDLE; // 1. Create VkImage. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)( allocator->m_hDevice, pImageCreateInfo, allocator->GetAllocationCallbacks(), pImage); if(res >= 0) { VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ? VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL : VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR; // 2. Allocate memory using allocator. res = AllocateMemoryForImage(allocator, *pImage, pAllocationCreateInfo, suballocType, pAllocation); if(res >= 0) { // 3. Bind image with memory. res = (*allocator->GetVulkanFunctions().vkBindImageMemory)( allocator->m_hDevice, *pImage, (*pAllocation)->GetMemory(), (*pAllocation)->GetOffset()); if(res >= 0) { // All steps succeeded. if(pAllocationInfo != VMA_NULL) { allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); } return VK_SUCCESS; } allocator->FreeMemory(*pAllocation); *pAllocation = VK_NULL_HANDLE; (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); *pImage = VK_NULL_HANDLE; return res; } (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); *pImage = VK_NULL_HANDLE; return res; } return res; } void vmaDestroyImage( VmaAllocator allocator, VkImage image, VmaAllocation allocation) { if(image != VK_NULL_HANDLE) { VMA_ASSERT(allocator); VMA_DEBUG_LOG("vmaDestroyImage"); VMA_DEBUG_GLOBAL_MUTEX_LOCK (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks()); allocator->FreeMemory(allocation); } } #endif // #ifdef VMA_IMPLEMENTATION #endif // ifdef USING_VULKAN
fdcbe93b9efabcee6845afa126a7c0cd8f4fa6c7
93315e986978d8d85dde7f5d4edeee1da3e8571e
/Source/McGill_1/Public/InteractableBase.h
622374d14c41fae0bc5cd2fbe1ae4f0381533a47
[]
no_license
gjtqiyue/UGL_2020_McGill_1
b3f82adf87c3ba60bed1d3236d11bbdba9910730
6e52f607f107eed6488dcb04d39ba5bd2709eae6
refs/heads/master
2022-08-02T18:56:32.059781
2020-05-31T09:37:46
2020-05-31T09:37:46
247,620,489
2
0
null
null
null
null
UTF-8
C++
false
false
1,051
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "InteractableBase.generated.h" class ACharacterBase; UCLASS() class MCGILL_1_API AInteractableBase : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AInteractableBase(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; UFUNCTION(BlueprintImplementableEvent, category = "Interaction") void Trigger(); UFUNCTION(BlueprintCallable, category = "Interaction") virtual void OnPlayerInRange(class AActor* OverlappedActor, class AActor* OtherActor); UFUNCTION(BlueprintCallable, category = "Interaction") virtual void OnPlayerLeaveRange(class AActor* OverlappedActor, class AActor* OtherActor); protected: class UBoxComponent* TriggerBox; TArray<ACharacterBase*> PlayersInRange; bool bInInteractRange; };
a1a8de63409378e3e36df64043f4ef8e49e511a0
45d300db6d241ecc7ee0bda2d73afd011e97cf28
/OTCDerivativesCalculatorModule/Project_Cpp/lib_static/FpmlSerialized/GenClass/fpml-shared-5-4/ContractualMatrix.hpp
363163da125046e0dad0ff4bf63c5e5c812e47a6
[]
no_license
fagan2888/OTCDerivativesCalculatorModule
50076076f5634ffc3b88c52ef68329415725e22d
e698e12660c0c2c0d6899eae55204d618d315532
refs/heads/master
2021-05-30T03:52:28.667409
2015-11-27T06:57:45
2015-11-27T06:57:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,401
hpp
// ContractualMatrix.hpp #ifndef FpmlSerialized_ContractualMatrix_hpp #define FpmlSerialized_ContractualMatrix_hpp #include <ISerialized.hpp> #include <fpml-shared-5-4/MatrixType.hpp> #include <built_in_type/XsdTypeDate.hpp> #include <fpml-shared-5-4/MatrixTerm.hpp> namespace FpmlSerialized { class ContractualMatrix : public ISerialized { public: ContractualMatrix(TiXmlNode* xmlNode); bool isMatrixType(){return this->matrixTypeIsNull_;} boost::shared_ptr<MatrixType> getMatrixType(); std::string getMatrixTypeIDRef(){return matrixTypeIDRef_;} bool isPublicationDate(){return this->publicationDateIsNull_;} boost::shared_ptr<XsdTypeDate> getPublicationDate(); std::string getPublicationDateIDRef(){return publicationDateIDRef_;} bool isMatrixTerm(){return this->matrixTermIsNull_;} boost::shared_ptr<MatrixTerm> getMatrixTerm(); std::string getMatrixTermIDRef(){return matrixTermIDRef_;} protected: boost::shared_ptr<MatrixType> matrixType_; std::string matrixTypeIDRef_; bool matrixTypeIsNull_; boost::shared_ptr<XsdTypeDate> publicationDate_; std::string publicationDateIDRef_; bool publicationDateIsNull_; boost::shared_ptr<MatrixTerm> matrixTerm_; std::string matrixTermIDRef_; bool matrixTermIsNull_; }; } //namespaceFpmlSerialized end #endif
dfb0beecb814f37a167258fa9bac9c3e6476ee57
276da4b1d93859827e228f4cf055ba6d7597fbba
/GlushchukRoman._Proga_C++._miniLabsOfCisco/Labs_Chapter5/cpa_lab_5_3_13_(5)-B.cpp
e61bca700b082de90416864ca41d4690acb52f23
[]
no_license
So1air/-CiscoCompleteLabs
4180b80ac31545d11129306f7542743d2bae3750
1ac1bfbfef6d8ec3896d80ec155099bc6498e0d1
refs/heads/master
2021-01-18T08:00:32.534262
2017-08-12T15:56:58
2017-08-12T15:56:58
84,298,949
0
0
null
null
null
null
UTF-8
C++
false
false
736
cpp
#include <iostream> #include "LinkedList.h" using namespace std; namespace LinkedLists { bool List::pop_back(int &value) { // implement me! if (head) { value = tail->value; if (head == tail) { delete tail; head = tail = nullptr; } else { Node* prev_tail = head; while (prev_tail->next != tail) prev_tail = prev_tail->next; prev_tail->next = nullptr; delete tail; tail = prev_tail; } return true; } else return false; } } using namespace LinkedLists; int Go21(void){ List list; list.push_front(1); list.push_front(2); list.push_front(3); list.push_front(4); int value = 0; while (list.pop_back(value)) { cout << value << endl; } return 0; }
4333cad938667056d83e7b8846840eda2ac3a0c6
4ccb6c096ac6ba68fa91a5c257331b20ecabf16e
/ipc/chromium/src/base/file_descriptor_shuffle.cc
5cce963fa99d1644413474bbe4b694aa99c1dfab
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
classilla/tenfourfox
ad7856e9e2309e8d0da2d3eed3090cadf493a413
17b23692fe309927badba0617b7679ed50d46acb
refs/heads/master
2023-07-08T23:59:21.137323
2023-04-20T05:34:54
2023-04-20T05:34:54
40,451,619
247
41
NOASSERTION
2023-06-25T08:42:34
2015-08-09T21:46:01
null
UTF-8
C++
false
false
2,572
cc
// Copyright (c) 2009 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 "base/file_descriptor_shuffle.h" #include <errno.h> #include <unistd.h> #include "base/eintr_wrapper.h" #include "base/logging.h" namespace base { bool PerformInjectiveMultimapDestructive( InjectiveMultimap* m, InjectionDelegate* delegate) { static const size_t kMaxExtraFDs = 16; int extra_fds[kMaxExtraFDs]; unsigned next_extra_fd = 0; // DANGER: this function may not allocate. for (InjectiveMultimap::iterator i = m->begin(); i != m->end(); ++i) { int temp_fd = -1; // We DCHECK the injectiveness of the mapping. for (InjectiveMultimap::iterator j = i + 1; j != m->end(); ++j) { DCHECK(i->dest != j->dest) << "Both fd " << i->source << " and " << j->source << " map to " << i->dest; } const bool is_identity = i->source == i->dest; for (InjectiveMultimap::iterator j = i + 1; j != m->end(); ++j) { if (!is_identity && i->dest == j->source) { if (temp_fd == -1) { if (!delegate->Duplicate(&temp_fd, i->dest)) return false; if (next_extra_fd < kMaxExtraFDs) { extra_fds[next_extra_fd++] = temp_fd; } else { DLOG(ERROR) << "PerformInjectiveMultimapDestructive overflowed " << "extra_fds. Leaking file descriptors!"; } } j->source = temp_fd; j->close = false; } if (i->close && i->source == j->dest) i->close = false; if (i->close && i->source == j->source) { i->close = false; j->close = true; } } if (!is_identity) { if (!delegate->Move(i->source, i->dest)) return false; } if (!is_identity && i->close) delegate->Close(i->source); } for (unsigned i = 0; i < next_extra_fd; i++) delegate->Close(extra_fds[i]); return true; } bool PerformInjectiveMultimap(const InjectiveMultimap& m_in, InjectionDelegate* delegate) { InjectiveMultimap m(m_in); return PerformInjectiveMultimapDestructive(&m, delegate); } bool FileDescriptorTableInjection::Duplicate(int* result, int fd) { *result = HANDLE_EINTR(dup(fd)); return *result >= 0; } bool FileDescriptorTableInjection::Move(int src, int dest) { return HANDLE_EINTR(dup2(src, dest)) != -1; } void FileDescriptorTableInjection::Close(int fd) { HANDLE_EINTR(close(fd)); } } // namespace base
62a0770baee1896f2051b748e69e80f15d3933ed
96a9dec215eb98d554c176c56928f6a4ed616579
/Compressor/compressor.cpp
62f0bf45d9b038214c1bd499d4ee770b4a7fe92f
[]
no_license
knut0815/FractalCompressor
aa61603c975bdd113f3b0b15f68f406fa02df693
78dbfbf69b69e0b62a094f1659574bb87c06fce1
refs/heads/master
2021-07-05T16:04:02.995232
2017-07-28T13:42:01
2017-07-28T13:42:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,504
cpp
#include "compressor.h" #include "quadtree.h" #include <iostream> #include <assert.h> #include <algorithm> #include <iomanip> #include <thread> #include <fstream> //#define DISABLE_QUADTREE_SUBDIVISION ////////////////////////////////////////////////////////////////////////// #define HEADER_MAGIC 'icf ' struct Header { uint32 magic; uint32 imageSize; uint32 quadtreeDataSize; // in bits uint32 numDomains; CompressorSettings settings; }; ////////////////////////////////////////////////////////////////////////// namespace { FORCE_INLINE void TransformLocation(uint32 rangeSize, uint32 x, uint32 y, uint8 transform, uint32& outX, uint32& outY) { const uint32 offset = rangeSize - 1; if (transform & 0x1) x = offset - x; switch (transform >> 1) { case 0: outX = x; outY = y; break; case 1: outX = offset - y; outY = x; break; case 2: outX = offset - x; outY = offset - y; break; case 3: outX = y; outY = offset - x; break; } } } // namespace ////////////////////////////////////////////////////////////////////////// Compressor::Compressor(const CompressorSettings& settings) : mSettings(settings) {} ////////////////////////////////////////////////////////////////////////// // Compression ////////////////////////////////////////////////////////////////////////// float Compressor::MatchDomain(const DomainMatchParams& params, uint8 rangeSize, float& outScale, float& outOffset) const { // number of pixels in the range const uint32 k = rangeSize * rangeSize; const float invK = 1.0f / (float)k; const RangeContext& rangeCtx = params.rangeContext; uint32 gh = 0, gSum = 0, gSqrSum = 0, hSum = 0, index = 0; for (uint8 y = 0; y < rangeSize; y++) { for (uint8 x = 0; x < rangeSize; x++) { // transform range location to domain location and wrap around (if coordinate is too big) uint32 tx, ty; TransformLocation(rangeSize, x, y, params.transform, tx, ty); // sample domain blocks pixel (with downsample) // TODO this could be cached const uint8 domainPixelColor = rangeCtx.image.SampleDomain(params.dx0 + 2 * tx, params.dy0 + 2 * ty); // sample range blocks pixel const uint8 rangePixelColor = rangeCtx.image.Sample(rangeCtx.rx0 + x, rangeCtx.ry0 + y); // these will be used below gh += domainPixelColor * rangePixelColor; gSqrSum += domainPixelColor * domainPixelColor; gSum += domainPixelColor; hSum += rangePixelColor; rangeCtx.domainDataCache[index] = domainPixelColor; rangeCtx.rangeDataCache[index] = rangePixelColor; index++; } } // find pixel value scaling and offset coefficients that minimizes MSE float term0 = (float)k * (float)gh - (float)gSum * (float)hSum; float term1 = (float)k * (float)gSqrSum - (float)gSum * (float)gSum; if (abs(term1) < 0.0001f) { outScale = 0.0f; outOffset = (float)hSum * invK; } else { outScale = term0 / term1; outOffset = ((float)hSum - outScale * (float)gSum) * invK; } // quantize coefficients Domain d; d.SetScale(outScale); d.SetOffset(outOffset); // calculate MSE (including color scaling and offset) uint32 diffSum = 0; for (uint32 i = 0; i < k; ++i) { int32 g = (int32)d.TransformColor(rangeCtx.domainDataCache[i]); int32 h = (int32)rangeCtx.rangeDataCache[i]; int32 diff = g - h; diffSum += diff * diff; } return (float)diffSum * invK; } float Compressor::DomainSearch(const RangeContext& rangeContext, uint8 rangeSize, Domain& outDomain) const { Domain bestDomain; float bestCost = FLT_MAX; const uint32 domainScaling = mSizeBits > DOMAIN_LOCATION_BITS ? mSizeBits - DOMAIN_LOCATION_BITS : 0; const uint32 maxDomainLocations = std::min<uint32>(mSize, 1 << DOMAIN_LOCATION_BITS); DomainMatchParams matchParams(rangeContext); // iterate through all possible domains locations for (uint32 y = 0; y < maxDomainLocations; y++) { matchParams.dy0 = y << domainScaling; for (uint32 x = 0; x < maxDomainLocations; x++) { matchParams.dx0 = x << domainScaling; // iterate through all possible domains->range transforms for (uint8 t = 0; t < DOMAIN_MAX_TRANSFORMS; ++t) { matchParams.transform = t; float scale, offset; const float currentCost = MatchDomain(matchParams, rangeSize, scale, offset); if (currentCost < bestCost) { bestDomain.x = x; bestDomain.y = y; bestDomain.transform = t; bestDomain.SetOffset(offset); bestDomain.SetScale(scale); bestCost = currentCost; } } } } outDomain = bestDomain; return bestCost; } uint32 Compressor::CompressRootRange(const RangeContext& rangeContext, QuadtreeCode& outQuadtreeCode, std::vector<Domain>& outDomains) const { // HACK (importance sampling) float distX = ((float)rangeContext.rx0 + mSettings.maxRangeSize / 2) / (float)mSize - 152.0f / 255.0f; float distY = ((float)rangeContext.ry0 + mSettings.maxRangeSize / 2) / (float)mSize - 110.0f / 255.0f; float dist = mSettings.disableImportance ? 0.0f : distX * distX + distY * distY; // MSE threshold for the first subdivision level const float initialThreshold = mSettings.mseMultiplier * (30.0f + dist * 520.0f); const float adaptiveThresholdFactor = 1.0f; // threshold multiplier for consecutive levels // TODO const uint8 minLocalRangeSize = !mSettings.disableImportance && dist > 0.020f ? (mSettings.minRangeSize * 2) : mSettings.minRangeSize; uint32 numDomainsInTree = 0; std::function<void(uint32, uint32, uint8, float)> compressSubRange; compressSubRange = [&](uint32 rx0, uint32 ry0, uint8 rangeSize, float mseThreshold) { RangeContext subRangeContext(rangeContext); subRangeContext.rx0 = rx0; subRangeContext.ry0 = ry0; Domain domain; const float mse = DomainSearch(subRangeContext, rangeSize, domain); bool subdivide = false; #ifndef DISABLE_QUADTREE_SUBDIVISION if (rangeSize > mSettings.minRangeSize) { subdivide = (mse > mseThreshold) && (rangeSize > minLocalRangeSize); outQuadtreeCode.Push(subdivide); // don't waste quadtree space if this is the lowest possible level } #endif // DISABLE_QUADTREE_SUBDIVISION // recursively subdivide range if (subdivide) { const uint8 subRangeSize = rangeSize / 2; const float subRangeThreshold = mseThreshold * adaptiveThresholdFactor; compressSubRange(rx0, ry0, subRangeSize, subRangeThreshold); compressSubRange(rx0 + subRangeSize, ry0, subRangeSize, subRangeThreshold); compressSubRange(rx0, ry0 + subRangeSize, subRangeSize, subRangeThreshold); compressSubRange(rx0 + subRangeSize, ry0 + subRangeSize, subRangeSize, subRangeThreshold); } else { /* { std::lock_guard<std::mutex> lock(mMutex); std::cout << "Range " << std::setw(3) << rx0 << ',' << std::setw(3) << ry0 << " (" << std::setw(2) << rangeSize << " px) -> " << "Domain: loc=(" << std::setw(3) << (uint32)domain.x << "," << std::setw(3) << (uint32)domain.y << ")" << ", t=" << (uint32)domain.transform << ", scale=" << std::setw(8) << std::setprecision(3) << domain.GetScale() << ", offset=" << std::setw(8) << std::setprecision(3) << domain.GetOffset() << ", " << "MSE=" << std::setw(8) << std::setprecision(3) << mse << std::endl; } */ outDomains.push_back(domain); numDomainsInTree++; } }; compressSubRange(rangeContext.rx0, rangeContext.ry0, mSettings.maxRangeSize, initialThreshold); return numDomainsInTree; } bool Compressor::Compress(const Image& image) { const uint32 maxRangeSize = mSettings.maxRangeSize; if (image.GetSize() < maxRangeSize) { std::cout << "Image is too small" << std::endl; return false; } mSize = image.GetSize(); mSizeBits = image.GetSizeBits(); mSizeMask = image.GetSizeMask(); const uint32 numRangesInColumn = image.GetSize() / maxRangeSize; const uint32 numThreads = std::min<uint32>(numRangesInColumn, std::thread::hardware_concurrency()); const uint32 rowsPerThread = numRangesInColumn / numThreads; const uint32 totalRangeBlocks = numRangesInColumn * numRangesInColumn; uint32 finishedRangeBlocks = 0; std::vector<QuadtreeCode> quadtreesPerThread; std::vector<std::vector<Domain>> domainsPerThread; quadtreesPerThread.resize(numThreads); domainsPerThread.resize(numThreads); const auto threadCallback = [&](uint32 threadID) { assert(threadID < numThreads); std::vector<Domain>& domains = domainsPerThread[threadID]; QuadtreeCode& quadtreeCode = quadtreesPerThread[threadID]; const uint32 numRangePixels = maxRangeSize * maxRangeSize; std::vector<uint8> domainDataCache; std::vector<uint8> rangeDataCache; domainDataCache.resize(numRangePixels); rangeDataCache.resize(numRangePixels); RangeContext rangeContext(image, rangeDataCache, domainDataCache); for (uint32 i = 0; i < rowsPerThread; ++i) // iterate local rows { // range block Y coordinate rangeContext.ry0 = maxRangeSize * (rowsPerThread * threadID + i); for (uint32 rx0 = 0; rx0 < image.GetSize(); rx0 += maxRangeSize) // range block X coordinate { rangeContext.rx0 = rx0; const uint32 numDomainsInTree = CompressRootRange(rangeContext, quadtreeCode, domains); // progress indicator { std::lock_guard<std::mutex> lock(mMutex); finishedRangeBlocks++; std::cout << std::setw(5) << finishedRangeBlocks << " /" << std::setw(5) << totalRangeBlocks << " (" << std::setw(8) << std::setprecision(3) << (100.0f * (float)finishedRangeBlocks / (float)totalRangeBlocks) << "%)\r"; } } } }; // launch threads std::vector<std::thread> threads; for (uint32 i = 0; i < numThreads; ++i) { threads.emplace_back(threadCallback, i); } // wait for threads and merge results (domains + quadtrees) mQuadtreeCode.Clear(); mDomains.clear(); for (uint32 i = 0; i < numThreads; ++i) { threads[i].join(); for (const Domain& domain : domainsPerThread[i]) { mDomains.push_back(domain); } mQuadtreeCode.Push(quadtreesPerThread[i]); } std::cout << std::endl; // print domains stats { DomainsStats domainStats = CalculateDomainStats(); std::cout << std::endl << "=== DOMAINS STATS ===" << std::endl; std::cout << "Average offset: " << domainStats.averageOffset << std::endl; std::cout << "Offset variance: " << domainStats.offsetVariance << std::endl; std::cout << "Min. offset: " << domainStats.minOffset << std::endl; std::cout << "Max. offset: " << domainStats.maxOffset << std::endl; std::cout << "Average scale: " << domainStats.averageScale << std::endl; std::cout << "Scale variance: " << domainStats.scaleVariance << std::endl; std::cout << "Min. scale: " << domainStats.minScale << std::endl; std::cout << "Max. scale: " << domainStats.maxScale << std::endl; std::cout << "Transform distr.: "; for (int i = 0; i < 8; ++i) std::cout << i << "(" << domainStats.transformDistribution[i] << ") "; std::cout << std::endl; } const size_t domainsDataSize = mDomains.size() * sizeof(Domain); const size_t quadtreeElements = mQuadtreeCode.GetNumElements(); const size_t totalSize = domainsDataSize + sizeof(QuadtreeCode::ElementType) * quadtreeElements; const float bitsPerPixel = (float)(totalSize * 8) / (float)(image.GetSize() * image.GetSize()); std::cout << "Num domains: " << mDomains.size() << std::endl; std::cout << "Quadtree size: " << mQuadtreeCode.GetSize() << std::endl; std::cout << "Compressed size: " << totalSize << " bytes (" << std::setw(8) << std::setprecision(4) << bitsPerPixel << " bpp)" << std::endl; return true; } DomainsStats Compressor::CalculateDomainStats() const { const float invNumOfDomains = 1.0f / (float)mDomains.size(); DomainsStats stats; for (const Domain& d : mDomains) { const float offset = (float)d.GetOffset(); const float scale = (float)d.GetScale(); stats.averageOffset += offset; stats.averageScale += scale; stats.minOffset = std::min<float>(stats.minOffset, offset); stats.maxOffset = std::max<float>(stats.maxOffset, offset); stats.minScale = std::min<float>(stats.minScale, scale); stats.maxScale = std::max<float>(stats.maxScale, scale); assert(d.transform < 8); stats.transformDistribution[d.transform]++; } stats.averageOffset *= invNumOfDomains; stats.averageScale *= invNumOfDomains; for (const Domain& d : mDomains) { const float offset = (float)d.GetOffset(); const float scale = (float)d.GetScale(); stats.offsetVariance += (stats.averageOffset - offset) * (stats.averageOffset - offset); stats.scaleVariance += (stats.averageScale - scale) * (stats.averageScale - scale); } stats.offsetVariance *= invNumOfDomains; stats.scaleVariance *= invNumOfDomains; return stats; } ////////////////////////////////////////////////////////////////////////// // Decompression ////////////////////////////////////////////////////////////////////////// void Compressor::DecompressRange(const RangeDecompressContext& context) const { assert(context.rangeSize >= mSettings.minRangeSize); assert(context.rx0 < mSize); assert(context.ry0 < mSize); // check if this range should be subdivided bool subdivide = false; if (context.rangeSize > mSettings.minRangeSize) { subdivide = context.quadtreeCode.Get(); } if (subdivide) { RangeDecompressContext childContext(context); childContext.rangeSize /= 2; for (uint32 i = 0; i < 2; ++i) { for (uint32 j = 0; j < 2; ++j) { childContext.rx0 = context.rx0 + j * childContext.rangeSize; childContext.ry0 = context.ry0 + i * childContext.rangeSize; DecompressRange(childContext); } } } else // !subdivide { const uint32 domainScaling = mSizeBits > DOMAIN_LOCATION_BITS ? mSizeBits - DOMAIN_LOCATION_BITS : 0; const Domain& domain = mDomains[context.domainIndex++]; for (uint32 y = 0; y < context.rangeSize; y++) { const uint32 ry = context.ry0 + y; for (uint32 x = 0; x < context.rangeSize; x++) { // transform range block location to domain location uint32 tx, ty; TransformLocation(context.rangeSize, x, y, domain.transform, tx, ty); // decode domain location (to picture space) const uint32 dx = (domain.x << domainScaling) + 2 * tx; const uint32 dy = (domain.y << domainScaling) + 2 * ty; // sample domain (with downsampling) const uint32 domainPixelColor = context.srcImage.SampleDomain(dx, dy); // transform color context.destImage.WritePixel(x + context.rx0, ry, domain.TransformColor((uint8)domainPixelColor)); } } } } bool Compressor::Decompress(Image& outImage) const { if (mDomains.empty()) { std::cout << "There is no encoded data" << std::endl; return false; } const uint32 MAX_ITERATIONS = 100; uint32 currentImage = 0; Image tempImages[2]; tempImages[0].Resize(mSize, 1); tempImages[1].Resize(mSize, 1); QuadtreeCode tmpQuadtreeCode(mQuadtreeCode); for (uint32 i = 0; i < MAX_ITERATIONS; ++i) { // swap images currentImage ^= 1; const Image& src = tempImages[currentImage ^ 1]; Image& dest = tempImages[currentImage]; tmpQuadtreeCode.ResetCursor(); // iterate through root domains uint32 domainIndex = 0; RangeDecompressContext context(src, dest, domainIndex, tmpQuadtreeCode); context.rangeSize = mSettings.maxRangeSize; for (uint32 ry0 = 0; ry0 < mSize; ry0 += mSettings.maxRangeSize) { for (uint32 rx0 = 0; rx0 < mSize; rx0 += mSettings.maxRangeSize) { context.rx0 = rx0; context.ry0 = ry0; DecompressRange(context); } } //assert(domainIndex == (uint32)mDomains.size()); } outImage = std::move(tempImages[currentImage]); return true; } ////////////////////////////////////////////////////////////////////////// // Input-output ////////////////////////////////////////////////////////////////////////// bool Compressor::Load(const std::string& name) { FILE* file = fopen(name.c_str(), "rb"); if (!file) { std::cout << "Failed to open compressed file '" << name << "': " << stderr << std::endl; return false; } Header header; if (fread(&header, sizeof(Header), 1, file) != 1) { std::cout << "Failed to read compressed file header: " << stderr << std::endl; fclose(file); return false; } if (header.magic != HEADER_MAGIC) { std::cout << "Corrupted/invalid file" << std::endl; fclose(file); return false; } if ((header.imageSize & (header.imageSize - 1)) != 0 || header.numDomains == 0) { std::cout << "Corrupted file" << std::endl; return false; } // read file size mSize = header.imageSize; mSizeBits = 0; { uint32 i = mSize; while (i >>= 1) ++mSizeBits; } mSizeMask = (1 << mSizeBits) - 1; if (mSettings.minRangeSize <= 2 || mSettings.maxRangeSize < mSettings.minRangeSize) { std::cout << "Corrupted/invalid file" << std::endl; fclose(file); return false; } // calculate number of elements from number of bits (round up) const uint32 quadtreeCodeElements = (header.quadtreeDataSize + 8 * sizeof(QuadtreeCode::ElementType) - 1) / (8 * sizeof(QuadtreeCode::ElementType)); if (quadtreeCodeElements > 0) { std::vector<QuadtreeCode::ElementType> code; code.resize(quadtreeCodeElements); if (fread(code.data(), quadtreeCodeElements * sizeof(QuadtreeCode::ElementType), 1, file) != 1) { std::cout << "Failed to read quadtree data: " << stderr << std::endl; fclose(file); return false; } mQuadtreeCode.Load(code, header.quadtreeDataSize); } else { mQuadtreeCode.Clear(); } // read domains mDomains.resize(header.numDomains); if (fread(mDomains.data(), mDomains.size() * sizeof(Domain), 1, file) != 1) { std::cout << "Failed to read domains data: " << stderr << std::endl; fclose(file); return false; } fclose(file); return true; } bool Compressor::Save(const std::string& name) const { FILE* file = fopen(name.c_str(), "wb"); if (!file) { std::cout << "Failed to open target encoded file '" << name << "': " << stderr << std::endl; return false; } Header header; header.magic = HEADER_MAGIC; header.imageSize = mSize; header.quadtreeDataSize = mQuadtreeCode.GetSize(); header.numDomains = (uint32)mDomains.size(); header.settings = mSettings; if (fwrite(&header, sizeof(Header), 1, file) != 1) { std::cout << "Failed to write compressed file header: " << stderr << std::endl; fclose(file); return false; } if (mQuadtreeCode.GetNumElements() > 0) { if (fwrite(mQuadtreeCode.GetCode().data(), mQuadtreeCode.GetNumElements() * sizeof(QuadtreeCode::ElementType), 1, file) != 1) { std::cout << "Failed to write quadtree data: " << stderr << std::endl; fclose(file); return false; } } if (fwrite(mDomains.data(), mDomains.size() * sizeof(Domain), 1, file) != 1) { std::cout << "Failed to write domains data: " << stderr << std::endl; fclose(file); return false; } fclose(file); return true; } bool Compressor::SaveAsSourceFile(const std::string& prefix, const std::string& name) const { std::ofstream file(name); if (!file.good()) { std::cout << "Failed to open target encoded file '" << name << "': " << stderr << std::endl; return false; } file << "#include \"demo.h\"\n\n"; if (mQuadtreeCode.GetNumElements() > 0) { file << "const unsigned int " << prefix << "QuadtreeData[] = \n{\n"; for (uint32 i = 0; i < mQuadtreeCode.GetNumElements(); ++i) { file << " 0x" << std::hex << mQuadtreeCode.GetCode().data()[i] << ",\n"; } file << "};\n\n"; } { file << "const Domain " << prefix << "DomainsData[] = \n{\n"; for (const Domain& d : mDomains) { file << std::dec << " { " << d.x << ", " << d.y << ", " << d.transform << ", " << d.offset << ", " << d.scale << " },\n"; } file << "};\n\n"; } return true; }
9d006cfb95ad76babaf6943dafc182f3a7d203cb
4cd9e058b1213ee8b8895d5e5b87c49f456d2178
/src/MainMenuState.cpp
d8b86a94e619f9d87c5f0a5248cfcdb63621c041
[ "MIT" ]
permissive
jdahlbom/ApMech
51b88f874509ff9daf79f3991cd0a09fb772914d
ebadf297854f6d6e0faff6b2ea2dc7dd8f8ae3bc
refs/heads/master
2021-01-18T15:29:59.454852
2012-04-22T20:37:22
2012-04-22T20:37:22
3,462,982
0
0
null
null
null
null
UTF-8
C++
false
false
2,144
cpp
#include "MainMenuState.h" #include <iostream> #include <string> #ifndef WIN32 #include <Ogre.h> #else #include <Ogre/Ogre.h> #endif #include "GameStateManager.h" #include "Gui.h" #include "MenuStateViewport.h" #include "types.h" #include "functions.h" #include "net/netdata.h" namespace ap { MainMenuState::MainMenuState( GameStateManager *gameStateManager, Ogre::SceneManager *sceneManager, ap::Gui *gui) : pGui(gui), pSceneManager(sceneManager) { initStateManager(gameStateManager); } MainMenuState::~MainMenuState() {} void MainMenuState::enter( void ) { createGUIWindow(); } void MainMenuState::exit( void ) { terminateGUIWindow(); } //----------------------------------------------------------------------------- void MainMenuState::createGUIWindow() { assert(pGui); pGui->setupMainMenuWindow(); pGui->setMainMenuReceiver(this); assert(pSceneManager); mViewport = new MenuStateViewport(pSceneManager); } void MainMenuState::terminateGUIWindow() { assert(pGui); pGui->hideMainMenuWindow(); delete(mViewport); } bool MainMenuState::keyPressed( const ap::ooinput::KeyEvent &e ) { if (pGui->keyPressed(e)) { return true; } switch( e.key ) { case ooinput::AP_K_ESCAPE: this->requestShutdown(); return 1; default: break; // Some other key: do nothing } return false; } bool MainMenuState::keyReleased( const ap::ooinput::KeyEvent &e ) { if(pGui->keyReleased(e)) { return true; } return false; } bool MainMenuState::mousePressed(const ap::ooinput::MouseClickedEvent &e) { return pGui->mousePressed(e); } bool MainMenuState::mouseReleased(const ap::ooinput::MouseClickedEvent &e) { return pGui->mouseReleased(e); } bool MainMenuState::mouseMoved(const ap::ooinput::MouseMovedEvent &e) { return pGui->mouseMoved(e); } // ----GuiMainMenuReceiver ------ void MainMenuState::receiveQuitGame() { requestShutdown(); } void MainMenuState::receiveConfigureKeyboard() { this->getStateManager()->enterKeyConfMenu(); } void MainMenuState::receivePlayGame() { this->getStateManager()->enterLoginMenu(); } } // namespace ap
[ "jukka@Serenity.(none)" ]
jukka@Serenity.(none)
92fb2bf467ac9281fe3b17649434df810d4e5151
c8045a13bd1ebe378b242c98f1aa3d7d0c3a8cf1
/019_Remove_Nth_Node_from_End_of_List/sol.cpp
9ab109f143959b6773792d9784f6560f9b7bbbb5
[]
no_license
IrvingW/LeetCode-problems
1e6f85c71400043f1dc97d99e11297357ce11aaa
65cd70ec4fd0335cc6e536db1e1373aa5630b4b5
refs/heads/master
2018-11-15T17:18:08.056162
2018-09-02T09:45:04
2018-09-02T09:45:04
118,145,834
0
0
null
null
null
null
UTF-8
C++
false
false
723
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(n == 0) return NULL; ListNode * tail = head; // be careful about delete the first node ListNode * dummy = new ListNode(-1); dummy->next = head; ListNode * pre = dummy; for(int i = 0; i < n; i++){ tail = tail->next; } while(tail){ tail = tail->next; pre = head; head = head->next; } pre->next = head->next; return dummy->next; } };
65d08d401575c11dbcfa246f5d32c1ffa498a695
52572f1dcfe15c1f259a0bd38ced2c539ff01db9
/src/Variables.hpp
6eadfd1264f1517a7688fd55ee1c12d1b89c3fcc
[]
no_license
MyLibh/Billiards
6d453463d4957a776d6fbe5a0292ddc693634c09
cd316b697d79f85a74db76b8da0f0ee8d4a20890
refs/heads/master
2019-07-15T06:13:55.468983
2016-11-17T09:27:58
2016-11-17T09:27:58
63,860,420
0
0
null
null
null
null
UTF-8
C++
false
false
6,142
hpp
#pragma once /* //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4514) #pragma warning(disable:4668) #pragma warning(disable:4820) #include <windows.h> #pragma warning(pop) //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4061) #pragma warning(disable:4263) #pragma warning(disable:4264) #pragma warning(disable:4265) #pragma warning(disable:4365) #pragma warning(disable:4514) #pragma warning(disable:4625) #pragma warning(disable:4626) #pragma warning(disable:4820) #include <gdiplus.h> #include <gdipluspen.h> #include <gdiplusstringformat.h> #include <gdipluspath.h> #include <gdipluslinecaps.h> #include <gdiplusgraphics.h> #include <gdiplusheaders.h> #pragma warning(pop) //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4820) #include <io.h> #pragma warning(pop) //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4514) #pragma warning(disable:4820) #include <wchar.h> #pragma warning(pop) //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4514) #define _USE_MATH_DEFINES #include <limits> #include <cmath> #pragma warning(pop) //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4350) #pragma warning(disable:4710) #include <xmemory0> #pragma warning(pop) //==================================================================================================================== #pragma warning(push) #pragma warning(disable:4350) #pragma warning(disable:4514) #include <string> #pragma warning(pop) //==================================================================================================================== */ #pragma warning(push, 4) #include <windows.h> #define _USE_MATH_DEFINES #include <limits> #include <cmath> #include <fstream> #include <Istream> #include <iostream> #include <sstream> #include <vector> #include <string> #include <map> #include <iterator> #include <locale> #include <codecvt> #include <ctime> #include <io.h> #include <gdiplus.h> #include <WinSock.h> //#include <WS2tcpip.h> #include "UPOINT.hpp" #pragma warning(pop) #include "resource.h" #include "Uncopyable.hpp" using namespace std; //=========================================================================================================== #define PAUSE system("pause"); //=========================================================================================================== BOOL SetConsoleColor(unsigned); #define $r SetConsoleColor(0x0c); #define $g SetConsoleColor(0x0a); #define $b SetConsoleColor(0x09); #define $y SetConsoleColor(0x0e); enum EXITS { WNDCLASS_FAILED = -15001, WNDCREATE_FAILED = -15002, CONSOLECREATE_FAILED = -15003, GDIPINIT_FAILED = -15004, NONEBUTTON_PRESSED = -15005, LOGFILECREATE_FAILED = -15006, CFGFILECREATE_FAILED = -15007, ESCAPE = 27, BALLS_STOPPED = 15001 }; //=========================================================================================================== struct DistanceBetweenWallAndTable { SIZE_T left, up, right, bottom; }; //========================================== CONST WORD NUMBER_OF_BALLS = 16; CONST float SCALE = 0.49f; CONST Gdiplus::Color COLOR_KEY(0, 197, 206, 5); //Ìèëëèìåòðû CONST float tagBALL_DIAMETER = 6.825f; CONST float BALL_DIAMETER = tagBALL_DIAMETER * SCALE; CONST float tagBALL_RADIUS = tagBALL_DIAMETER / 2.0f; CONST float BALL_RADIUS = tagBALL_RADIUS * SCALE; //Ñàíòèìåòðû CONST UPOINT tagTABLE_SIZE(384, 206); CONST UPOINT TABLE_SIZE = (tagTABLE_SIZE * SCALE); CONST UPOINT tagFIELD_SIZE(355, 177); CONST SIZE_T tagCUE_LENGTH = 1450; CONST SIZE_T CUE_LENGTH = tagCUE_LENGTH * static_cast<SIZE_T>(SCALE); CONST SIZE_T EXTRA_CUE_LENGTH = 30; CONST SIZE_T EXTRA_CUE_LENGTH_2 = static_cast<SIZE_T>(floor(EXTRA_CUE_LENGTH / 2)); CONST DistanceBetweenWallAndTable tagDISTANCE_BETWEEN_WALL_AND_TABLE = { CUE_LENGTH + EXTRA_CUE_LENGTH_2, CUE_LENGTH + EXTRA_CUE_LENGTH_2, CUE_LENGTH + EXTRA_CUE_LENGTH_2, CUE_LENGTH + EXTRA_CUE_LENGTH_2 }; #define DistanceBWAT tagDISTANCE_BETWEEN_WALL_AND_TABLE ///Íà âñÿêèé ñëó÷àé: http://www.billiard-klondayk.ru/razmer-bilyardnoy.htm //Âèêåïåäèÿ: https://ru.wikipedia.org/wiki/Ïóë_(áèëüÿðä) //=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= CONST double sizestenaUP = 150 * SCALE;//64; CONST double sizestenaDOWN = 100 * SCALE;//40;// CONST double sizestenaLEFT = 100 * SCALE;//40;// CONST double sizestenaRIGHT = 100 * SCALE;//32;// CONST double sizeXpol = 3550 * SCALE; // sizeX - sizestenaLEFT - sizestenaRIGHT CONST double sizeYpol = 1775 * SCALE; // sizeY - sizestenaUP - sizestenaDOWN CONST double sizeX = sizeXpol + sizestenaLEFT + sizestenaRIGHT; //1200 CONST double sizeY = sizestenaUP + sizestenaDOWN + sizeYpol; //800; CONST double cor3 = sqrt(static_cast<double>(3)); CONST INT RShari = static_cast<INT>((68 / 2) * SCALE); // 16 CONST INT RLuz = static_cast<INT>((72.5 / 2) * SCALE); //RUglLuz = 20 //RBokLuz = 82,5/2 и поменять там где боковые лузы с рлуз на рбоклуз CONST INT RBokLuz = static_cast<INT>(82.5 / 2); CONST double Ru = RLuz; // M_SQRT2 * RLuz CONST INT RDugLuz = static_cast<INT>(15 * SCALE); // 10 CONST INT ColvoCenterDugLuz = 12; //=============================================================================================================
f780f1356c0a129f4a8fd8c3f5012ddbcfa4576b
01b5d513f3b5968a63d7f3ff945a1b85e2f52e0c
/UI_Common/Core/widget_closedarrange.h
ead68be823c07fec2a104279562cc2a76e2feec0
[]
no_license
sxlfhmsl/sm_system_bui
2447e39dfdbd308b0c69b600c5cb27c2bd93c5b5
4bac806ce7e88eb6ed8326d175e9fc86ce4f7a46
refs/heads/master
2022-01-24T21:49:38.767388
2019-07-30T16:04:48
2019-07-30T16:04:48
194,415,740
2
0
null
null
null
null
UTF-8
C++
false
false
1,634
h
#pragma once #include "ui_common_global.h" #include "component\widget_base.h" namespace Ui { class Widget_ClosedArrange; }; /** * @brief The Widget_ClosedArrange class * @details “休市安排”页面 */ class UI_COMMON_EXPORT Widget_ClosedArrange : public Widget_Base { Q_OBJECT public: Widget_ClosedArrange(System_Type type, QWidget *parent = Q_NULLPTR); ~Widget_ClosedArrange(); protected: /** * @brief setHorizontalHeaderLabels * @para: labels 表头 * @author 盛录 * @details 设置表格头 */ void setHorizontalHeaderLabels(const QStringList &labels); /** * @brief setItem * @para: row 行号 * @para: col 列号 * @para: value 值 * @author 盛录 * @details 设置单元格数据 */ void setItem(const int &row, const int &col, const QVariant &value); /** * @brief setIndexWidget * @para: row 行号 * @para: col 列号 * @para: widget 窗体部件 * @author 盛录 * @details 设置单元格部件 */ void setIndexWidget(const int &row, const int &col, QWidget* widget); /** * @brief clear * @author 盛录 * @details 清空 */ void clear(); /** * @brief set_PaginationInfo * @author 盛录 * @para(counts):总数量 * @details 更改分页信息 */ void set_PaginationInfo(int counts); /** * @brief count * @author 盛录 * @details 返回行数和列数, row和col */ QMap<QString, int> count(); private: Ui::Widget_ClosedArrange *ui; private: /** * @brief init_UI * @author 盛录 * @details 初始化当前窗口 */ void init_UI(); /** * @brief init_DataGrid * @author 盛录 * @details 初始化数据表格 */ void init_DataGrid(); };
5cb4c81166419a50e47ace1eeffebdf7d495853e
f09774159c0a5791af0bab7550e7d877d6376ac8
/dev_and_design/minijson_reader-master/minijson_reader-master/minijson_reader_tests.cpp
df444861d14e013470bd641f7523e283b5348f15
[ "BSD-2-Clause" ]
permissive
WathisLove/PokemonAE
df2dfca499ba14de3c782f5f007af9c5bb3101c2
344d0ae38522f5b4aa7a56a2dc8fac83f00faf4d
refs/heads/master
2023-04-21T00:33:44.450187
2021-05-07T13:57:43
2021-05-07T13:57:43
364,509,897
0
0
null
null
null
null
UTF-8
C++
false
false
65,732
cpp
#include "minijson_reader.hpp" #include <gtest/gtest.h> #include <bitset> template<typename T, size_t Size> bool arrays_match(const T (&expected)[Size], const T (&actual)[Size]) { return std::equal(expected, expected + Size, actual); } template<typename Context> void test_context_helper(Context& context) { bool loop = true; while (loop) { switch (context.read_offset()) { case 0: ASSERT_EQ('h', context.read()); context.write('H'); break; case 1: ASSERT_EQ('e', context.read()); context.write('e'); break; case 2: ASSERT_EQ('l', context.read()); context.write('l'); break; case 3: ASSERT_EQ('l', context.read()); context.write('l'); break; case 4: ASSERT_EQ('o', context.read()); context.write('o'); break; case 5: ASSERT_EQ(' ', context.read()); context.write(0); ASSERT_STREQ("Hello", context.write_buffer()); context.new_write_buffer(); break; case 6: ASSERT_EQ('w', context.read()); context.write('W'); break; case 7: ASSERT_EQ('o', context.read()); context.write('o'); break; case 8: ASSERT_EQ('r', context.read()); context.write('r'); break; case 9: ASSERT_EQ('l', context.read()); context.write('l'); break; case 10: ASSERT_EQ('d', context.read()); context.write('d'); break; case 11: ASSERT_EQ('.', context.read()); context.write(0); break; case 12: ASSERT_EQ(0, context.read()); loop = false; break; } } ASSERT_EQ(0, context.read()); ASSERT_EQ(12U, context.read_offset()); ASSERT_STREQ("World", context.write_buffer()); ASSERT_EQ(minijson::detail::context_base::NESTED_STATUS_NONE, context.nested_status()); context.begin_nested(minijson::detail::context_base::NESTED_STATUS_OBJECT); ASSERT_EQ(minijson::detail::context_base::NESTED_STATUS_OBJECT, context.nested_status()); ASSERT_EQ(1U, context.nesting_level()); context.begin_nested(minijson::detail::context_base::NESTED_STATUS_ARRAY); ASSERT_EQ(minijson::detail::context_base::NESTED_STATUS_ARRAY, context.nested_status()); ASSERT_EQ(2U, context.nesting_level()); context.end_nested(); ASSERT_EQ(1U, context.nesting_level()); context.end_nested(); ASSERT_EQ(0U, context.nesting_level()); context.reset_nested_status(); ASSERT_EQ(minijson::detail::context_base::NESTED_STATUS_NONE, context.nested_status()); } TEST(minijson_reader, buffer_context) { char buffer[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '.' }; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); test_context_helper(buffer_context); ASSERT_STREQ("Hello", buffer); ASSERT_STREQ("World", buffer + 6); ASSERT_THROW(buffer_context.write('x'), std::runtime_error); buffer_context.new_write_buffer(); ASSERT_EQ(buffer + sizeof(buffer), buffer_context.write_buffer()); ASSERT_THROW(buffer_context.write('x'), std::runtime_error); } TEST(minijson_reader, const_buffer_context) { const char buffer[] = "hello world."; minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); const char* const original_write_buffer = const_buffer_context.write_buffer(); test_context_helper(const_buffer_context); ASSERT_STREQ("hello world.", buffer); // no side effects ASSERT_THROW(const_buffer_context.write('x'), std::runtime_error); const_buffer_context.new_write_buffer(); ASSERT_EQ(original_write_buffer + strlen(buffer), const_buffer_context.write_buffer()); ASSERT_THROW(const_buffer_context.write('x'), std::runtime_error); } TEST(minijson_reader, istream_context) { std::istringstream buffer("hello world."); minijson::istream_context istream_context(buffer); test_context_helper(istream_context); } template<typename Context> void test_context_copy_construction_helper(const Context& original) { Context copy(original); (void)copy; } TEST(minijson_reader, context_no_copy_construction) { std::istringstream ss; // this test is compile-time only: uncommenting any of the following lines should cause a compile error //test_context_copy_construction_helper(minijson::buffer_context(NULL, 0)); //test_context_copy_construction_helper(minijson::const_buffer_context(NULL, 0)); //test_context_copy_construction_helper(minijson::istream_context(ss)); (void)ss; } template<typename Context> void test_context_copy_assignment_helper(const Context& original, Context& copy) { copy = original; } TEST(minijson_reader, context_no_copy_assignment) { std::istringstream ss; minijson::buffer_context buffer_context(NULL, 0); minijson::const_buffer_context const_buffer_context(NULL, 0); minijson::istream_context istream_context(ss); // this test is compile-time only: uncommenting any of the following lines should cause a compile error //test_context_copy_assignment_helper(minijson::buffer_context(NULL, 0), buffer_context); //test_context_copy_assignment_helper(minijson::const_buffer_context(NULL, 0), const_buffer_context); //test_context_copy_assignment_helper(minijson::istream_context(ss), istream_context); (void)ss; (void)buffer_context; (void)const_buffer_context; (void)istream_context; } TEST(minijson_reader, parse_error) { { minijson::buffer_context buffer_context(NULL, 0); minijson::parse_error parse_error(buffer_context, minijson::parse_error::UNKNOWN); ASSERT_EQ(0U, parse_error.offset()); ASSERT_EQ(minijson::parse_error::UNKNOWN, parse_error.reason()); ASSERT_STREQ("Unknown parse error", parse_error.what()); } { const char buffer[] = "hello world."; minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); const_buffer_context.read(); const_buffer_context.read(); ASSERT_EQ(2U, const_buffer_context.read_offset()); minijson::parse_error parse_error(const_buffer_context, minijson::parse_error::UNKNOWN); ASSERT_EQ(1U, parse_error.offset()); ASSERT_EQ(minijson::parse_error::UNKNOWN, parse_error.reason()); ASSERT_STREQ("Unknown parse error", parse_error.what()); } } TEST(minijson_reader_detail, utf8_quad) { minijson::detail::utf8_char utf8_quad; ASSERT_EQ(0U, utf8_quad[0]); ASSERT_EQ(0U, utf8_quad[1]); ASSERT_EQ(0U, utf8_quad[2]); ASSERT_EQ(0U, utf8_quad[3]); const minijson::detail::utf8_char utf8_quad1(0, 1, 2, 3); ASSERT_EQ(0U, utf8_quad1[0]); ASSERT_EQ(1U, utf8_quad1[1]); ASSERT_EQ(2U, utf8_quad1[2]); ASSERT_EQ(3U, utf8_quad1[3]); minijson::detail::utf8_char utf8_quad2; ASSERT_TRUE(utf8_quad == utf8_quad2); ASSERT_TRUE(utf8_quad != utf8_quad1); ASSERT_FALSE(utf8_quad != utf8_quad2); ASSERT_FALSE(utf8_quad == utf8_quad1); } TEST(minijson_reader_detail, utf16_to_utf32) { // code points 0000 to D7FF and E000 to FFFF ASSERT_EQ(0x000000u, minijson::detail::utf16_to_utf32(0x0000, 0x0000)); ASSERT_EQ(0x000001u, minijson::detail::utf16_to_utf32(0x0001, 0x0000)); ASSERT_EQ(0x00D7FEu, minijson::detail::utf16_to_utf32(0xD7FE, 0x0000)); ASSERT_EQ(0x00D7FFu, minijson::detail::utf16_to_utf32(0xD7FF, 0x0000)); ASSERT_EQ(0x00E000u, minijson::detail::utf16_to_utf32(0xE000, 0x0000)); ASSERT_EQ(0x00FFFFu, minijson::detail::utf16_to_utf32(0xFFFF, 0x0000)); // code points 010000 to 10FFFF ASSERT_EQ(0x010000u, minijson::detail::utf16_to_utf32(0xD800, 0xDC00)); ASSERT_EQ(0x010001u, minijson::detail::utf16_to_utf32(0xD800, 0xDC01)); ASSERT_EQ(0x10FFFEu, minijson::detail::utf16_to_utf32(0xDBFF, 0xDFFE)); ASSERT_EQ(0x10FFFFu, minijson::detail::utf16_to_utf32(0xDBFF, 0xDFFF)); } TEST(minijson_reader_detail, utf16_to_utf32_invalid) { ASSERT_THROW(minijson::detail::utf16_to_utf32(0x0000, 0x0001), minijson::detail::encoding_error); ASSERT_THROW(minijson::detail::utf16_to_utf32(0xD800, 0xDBFF), minijson::detail::encoding_error); ASSERT_THROW(minijson::detail::utf16_to_utf32(0xD800, 0xE000), minijson::detail::encoding_error); ASSERT_THROW(minijson::detail::utf16_to_utf32(0xDC00, 0xDC00), minijson::detail::encoding_error); } TEST(minijson_reader_detail, utf32_to_utf8) { // 1 byte { const uint8_t expected[] = { 0x00, 0x00, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x000000).bytes)); } { const uint8_t expected[] = { 0x01, 0x00, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x000001).bytes)); } { const uint8_t expected[] = { 0x7E, 0x00, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x00007E).bytes)); } { const uint8_t expected[] = { 0x7F, 0x00, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x00007F).bytes)); } // 2 bytes { const uint8_t expected[] = { 0xC2, 0x80, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x000080).bytes)); } { const uint8_t expected[] = { 0xC2, 0x81, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x000081).bytes)); } { const uint8_t expected[] = { 0xDF, 0xBE, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x0007FE).bytes)); } { const uint8_t expected[] = { 0xDF, 0xBF, 0x00, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x0007FF).bytes)); } // 3 bytes { const uint8_t expected[] = { 0xE0, 0xA0, 0x80, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x000800).bytes)); } { const uint8_t expected[] = { 0xE0, 0xA0, 0x81, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x000801).bytes)); } { const uint8_t expected[] = { 0xEF, 0xBF, 0xBE, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x00FFFE).bytes)); } { const uint8_t expected[] = { 0xEF, 0xBF, 0xBF, 0x00 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x00FFFF).bytes)); } // 4 bytes { const uint8_t expected[] = { 0xF0, 0x90, 0x80, 0x80 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x010000).bytes)); } { const uint8_t expected[] = { 0xF0, 0x90, 0x80, 0x81 }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x010001).bytes)); } { const uint8_t expected[] = { 0xF7, 0xBF, 0xBF, 0xBE }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x1FFFFE).bytes)); } { const uint8_t expected[] = { 0xF7, 0xBF, 0xBF, 0xBF }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf32_to_utf8(0x1FFFFF).bytes)); } } TEST(minijson_reader_detail, utf32_to_utf8_invalid) { // invalid code unit ASSERT_THROW(minijson::detail::utf32_to_utf8(0x200000), minijson::detail::encoding_error); } TEST(minijson_reader_detail, utf16_to_utf8) { // Just one test case, since utf16_to_utf8 calls utf16_to_utf32 and utf32_to_utf8, // and other cases have been covered by previous tests const uint8_t expected[] = { 0xF4, 0x8F, 0xBF, 0xBF }; ASSERT_TRUE(arrays_match(expected, minijson::detail::utf16_to_utf8(0xDBFF, 0xDFFF).bytes)); } TEST(minijson_reader_detail, parse_long) { ASSERT_EQ(0, minijson::detail::parse_long("0")); ASSERT_EQ(42, minijson::detail::parse_long("42")); ASSERT_EQ(-42, minijson::detail::parse_long("-42")); ASSERT_EQ(42, minijson::detail::parse_long("+42")); ASSERT_EQ(42, minijson::detail::parse_long("042")); ASSERT_EQ(255, minijson::detail::parse_long("ff", 16)); ASSERT_EQ(255, minijson::detail::parse_long("0xff", 16)); ASSERT_EQ(255, minijson::detail::parse_long("0ff", 16)); char buf[64]; sprintf(buf, "%ld", LONG_MAX); ASSERT_EQ(LONG_MAX, minijson::detail::parse_long(buf)); sprintf(buf, "%ld", LONG_MIN); ASSERT_EQ(LONG_MIN, minijson::detail::parse_long(buf)); } TEST(minijson_reader_detail, parse_long_invalid) { ASSERT_THROW(minijson::detail::parse_long(""), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("+"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("-"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long(" 4"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("47f"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("_78945"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("78945_"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("78945 "), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("0x0"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("123456789012345678901234567890"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_long("-123456789012345678901234567890"), minijson::detail::number_parse_error); } TEST(minijson_reader_detail, parse_long_invalid_restore_errno) { errno = 42; ASSERT_THROW(minijson::detail::parse_long("123456789012345678901234567890"), minijson::detail::number_parse_error); ASSERT_EQ(42, errno); } TEST(minijson_reader_detail, parse_double) { ASSERT_DOUBLE_EQ(0, minijson::detail::parse_double("0")); ASSERT_DOUBLE_EQ(42, minijson::detail::parse_double("42")); ASSERT_DOUBLE_EQ(-42, minijson::detail::parse_double("-42")); ASSERT_DOUBLE_EQ(42, minijson::detail::parse_double("+42")); ASSERT_DOUBLE_EQ(42, minijson::detail::parse_double("042")); ASSERT_DOUBLE_EQ(42.42, minijson::detail::parse_double("42.42")); ASSERT_DOUBLE_EQ(42.42E+01, minijson::detail::parse_double("42.42E+01")); ASSERT_DOUBLE_EQ(42.42E-01, minijson::detail::parse_double("42.42E-01")); char buf[2048]; sprintf(buf, "%lf", std::numeric_limits<double>::max()); ASSERT_DOUBLE_EQ(std::numeric_limits<double>::max(), minijson::detail::parse_double(buf)); sprintf(buf, "%lf", -std::numeric_limits<double>::max()); ASSERT_DOUBLE_EQ(-std::numeric_limits<double>::max(), minijson::detail::parse_double(buf)); #if 0 // for some reason I have to determine, the following two tests fail sprintf(buf, "%lf", std::numeric_limits<double>::min()); ASSERT_DOUBLE_EQ(std::numeric_limits<double>::min(), minijson::detail::parse_double(buf)); sprintf(buf, "%lf", -std::numeric_limits<double>::min()); ASSERT_DOUBLE_EQ(-std::numeric_limits<double>::min(), minijson::detail::parse_double(buf)); #endif } TEST(minijson_reader_detail, parse_double_invalid) { ASSERT_THROW(minijson::detail::parse_double(""), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("+"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("-"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double(" 4"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("47f"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("_78945"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("78945_"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("78945 "), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("0x0"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("42..42"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("42.42E+094 "), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("42.42E+09.4"), minijson::detail::number_parse_error); ASSERT_THROW(minijson::detail::parse_double("1.0E+999"), minijson::detail::number_parse_error); // overflow ASSERT_THROW(minijson::detail::parse_double("-1.0E+999"), minijson::detail::number_parse_error); // overflow ASSERT_THROW(minijson::detail::parse_double("1.0E-999"), minijson::detail::number_parse_error); // underflow ASSERT_THROW(minijson::detail::parse_double("-1.0E-999"), minijson::detail::number_parse_error); // underflow } TEST(minijson_reader_detail, parse_double_invalid_restore_errno) { errno = 42; ASSERT_THROW(minijson::detail::parse_double("1.0E+999"), minijson::detail::number_parse_error); ASSERT_EQ(42, errno); } TEST(minijson_reader_detail, parse_utf16_escape_sequence) { ASSERT_EQ(0x0000u, minijson::detail::parse_utf16_escape_sequence("0000")); ASSERT_EQ(0x0001u, minijson::detail::parse_utf16_escape_sequence("0001")); ASSERT_EQ(0xA6BCu, minijson::detail::parse_utf16_escape_sequence("A6BC")); ASSERT_EQ(0xFFFEu, minijson::detail::parse_utf16_escape_sequence("FFFE")); ASSERT_EQ(0xFFFFu, minijson::detail::parse_utf16_escape_sequence("FFFF")); ASSERT_EQ(0xFFFEu, minijson::detail::parse_utf16_escape_sequence("fffe")); ASSERT_EQ(0xFFFFu, minijson::detail::parse_utf16_escape_sequence("ffff")); ASSERT_EQ(0xFFFFu, minijson::detail::parse_utf16_escape_sequence("ffFf")); } TEST(minijson_reader_detail, parse_utf16_escape_sequence_invalid) { ASSERT_THROW(minijson::detail::parse_utf16_escape_sequence("ffFp"), minijson::detail::encoding_error); ASSERT_THROW(minijson::detail::parse_utf16_escape_sequence("-bcd"), minijson::detail::encoding_error); ASSERT_THROW(minijson::detail::parse_utf16_escape_sequence(" abc"), minijson::detail::encoding_error); ASSERT_THROW(minijson::detail::parse_utf16_escape_sequence("abc "), minijson::detail::encoding_error); } static void test_write_utf8_char(minijson::detail::utf8_char c, const char* expected_str) { char buf[] = "____"; minijson::buffer_context buffer_context(buf, sizeof(buf)); buffer_context.read(); buffer_context.read(); buffer_context.read(); buffer_context.read(); minijson::detail::write_utf8_char(buffer_context, c); ASSERT_STREQ(expected_str, buf); } TEST(minijson_reader_detail, write_utf8_char) { test_write_utf8_char(minijson::detail::utf8_char(0x00, 0x00, 0x00, 0x00), ""); test_write_utf8_char(minijson::detail::utf8_char(0xFF, 0x00, 0x00, 0x00), "\xFF___"); test_write_utf8_char(minijson::detail::utf8_char(0xFF, 0xFE, 0x00, 0x00), "\xFF\xFE__"); test_write_utf8_char(minijson::detail::utf8_char(0xFF, 0xFE, 0xFD, 0x00), "\xFF\xFE\xFD_"); test_write_utf8_char(minijson::detail::utf8_char(0xFF, 0xFE, 0xFD, 0xFC), "\xFF\xFE\xFD\xFC"); } TEST(minijson_reader_detail, read_quoted_string_empty) { char buffer[] = "\"\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_one_char) { char buffer[] = "\"a\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("a", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_ascii) { char buffer[] = "\"foo\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("foo", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_utf8) { char buffer[] = "\"你好\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("你好", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_escape_sequences) { char buffer[] = "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("\"\\/\b\f\n\r\t", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_escape_sequences_utf16) { char buffer[] = "\"\\u0001\\u0002a\\ud7ff\\uE000\\uFffFb\\u4F60\\uD800\\uDC00\\uDBFF\\uDFFFà\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("\x01\x02" "a" "\xED\x9F\xBF\xEE\x80\x80\xEF\xBF\xBF" "b" "你" "\xF0\x90\x80\x80" "\xF4\x8F\xBF\xBF" "à", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_escape_sequences_nullchar) { char buffer[] = "\"a\\u0000\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context); ASSERT_STREQ("a", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_quoted_string_skip_opening_quote) { char buffer[] = "asd\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_quoted_string(buffer_context, true); ASSERT_STREQ("asd", buffer_context.write_buffer()); } template<size_t Length> void read_quoted_string_invalid_helper( const char (&buffer)[Length], minijson::parse_error::error_reason expected_reason, size_t expected_offset, const char* expected_what) { bool exception_thrown = false; try { minijson::const_buffer_context context(buffer, Length - 1); minijson::detail::read_quoted_string(context); } catch (const minijson::parse_error& parse_error) { exception_thrown = true; ASSERT_EQ(expected_reason, parse_error.reason()); ASSERT_EQ(expected_offset, parse_error.offset()); ASSERT_STREQ(expected_what, parse_error.what()); } ASSERT_TRUE(exception_thrown); } TEST(minijson_reader_detail, read_quoted_string_invalid) { read_quoted_string_invalid_helper("", minijson::parse_error::EXPECTED_OPENING_QUOTE, 0, "Expected opening quote"); read_quoted_string_invalid_helper("a", minijson::parse_error::EXPECTED_OPENING_QUOTE, 0, "Expected opening quote"); read_quoted_string_invalid_helper("\"", minijson::parse_error::EXPECTED_CLOSING_QUOTE, 0, "Expected closing quote"); read_quoted_string_invalid_helper("\"asd", minijson::parse_error::EXPECTED_CLOSING_QUOTE, 3, "Expected closing quote"); read_quoted_string_invalid_helper("\"\\h\"", minijson::parse_error::INVALID_ESCAPE_SEQUENCE, 2, "Invalid escape sequence"); read_quoted_string_invalid_helper("\"\\u0rff\"", minijson::parse_error::INVALID_UTF16_CHARACTER, 6, "Invalid UTF-16 character"); read_quoted_string_invalid_helper("\"\\uD800\\uD7FF\"", minijson::parse_error::INVALID_UTF16_CHARACTER, 12, "Invalid UTF-16 character"); read_quoted_string_invalid_helper("\"\\uDC00\"", minijson::parse_error::INVALID_UTF16_CHARACTER, 6, "Invalid UTF-16 character"); read_quoted_string_invalid_helper("\"\\uD800\"", minijson::parse_error::EXPECTED_UTF16_LOW_SURROGATE, 7, "Expected UTF-16 low surrogate"); read_quoted_string_invalid_helper("\"\\uD800a\"", minijson::parse_error::EXPECTED_UTF16_LOW_SURROGATE, 7, "Expected UTF-16 low surrogate"); } template<size_t Length> void read_unquoted_value_invalid_helper( const char (&buffer)[Length], minijson::parse_error::error_reason expected_reason, size_t expected_offset, const char* expected_what) { bool exception_thrown = false; try { minijson::const_buffer_context context(buffer, Length - 1); minijson::detail::read_unquoted_value(context); } catch (const minijson::parse_error& parse_error) { exception_thrown = true; ASSERT_EQ(expected_reason, parse_error.reason()); ASSERT_EQ(expected_offset, parse_error.offset()); ASSERT_STREQ(expected_what, parse_error.what()); } ASSERT_TRUE(exception_thrown); } TEST(minijson_reader_detail, read_unquoted_value_empty) { read_unquoted_value_invalid_helper("", minijson::parse_error::UNTERMINATED_VALUE, 0, "Unterminated value"); } TEST(minijson_reader_detail, read_unquoted_value_comma_terminated) { char buffer[] = "42.42,"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); ASSERT_EQ(',', minijson::detail::read_unquoted_value(buffer_context)); ASSERT_STREQ("42.42", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_unquoted_value_curly_bracket_terminated) { char buffer[] = "42.42E+104}"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); ASSERT_EQ('}', minijson::detail::read_unquoted_value(buffer_context)); ASSERT_STREQ("42.42E+104", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_unquoted_value_square_bracket_terminated) { char buffer[] = "42.42]"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); ASSERT_EQ(']', minijson::detail::read_unquoted_value(buffer_context)); ASSERT_STREQ("42.42", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_unquoted_value_whitespace_terminated) { char buffer[] = "true\t"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); ASSERT_EQ('\t', minijson::detail::read_unquoted_value(buffer_context)); ASSERT_STREQ("true", buffer_context.write_buffer()); } TEST(minijson_reader_detail, read_unquoted_value_unterminated) { read_unquoted_value_invalid_helper("5", minijson::parse_error::UNTERMINATED_VALUE, 0, "Unterminated value"); } TEST(minijson_reader_detail, read_unquoted_value_first_char) { char buffer[] = "true\t"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); buffer_context.read(); ASSERT_EQ('\t', minijson::detail::read_unquoted_value(buffer_context, 't')); ASSERT_STREQ("true", buffer_context.write_buffer()); } TEST(minijson_reader, value_default_constructed) { const minijson::value value; ASSERT_EQ(minijson::Null, value.type()); ASSERT_STREQ("", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE(value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); } TEST(minijson_reader, value_example) { const minijson::value value(minijson::Number, "42.42", 42, 42.42); ASSERT_EQ(minijson::Number, value.type()); ASSERT_STREQ("42.42", value.as_string()); ASSERT_EQ(42, value.as_long()); ASSERT_TRUE(value.as_bool()); ASSERT_DOUBLE_EQ(42.42, value.as_double()); } template<typename Context> void parse_unquoted_value_invalid_helper(Context& context, size_t expected_offset) { bool exception_thrown = false; try { minijson::detail::parse_unquoted_value(context); } catch (const minijson::parse_error& parse_error) { exception_thrown = true; ASSERT_EQ(minijson::parse_error::INVALID_VALUE, parse_error.reason()); ASSERT_EQ(expected_offset, parse_error.offset()); ASSERT_STREQ("Invalid value", parse_error.what()); } ASSERT_TRUE(exception_thrown); } TEST(minijson_reader_detail, parse_unquoted_value_whitespace) { char buffer[] = " 42"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); read_unquoted_value(buffer_context); parse_unquoted_value_invalid_helper(buffer_context, 0); } TEST(minijson_reader_detail, parse_unquoted_value_true) { char buffer[] = "true "; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::detail::read_unquoted_value(buffer_context); const minijson::value value = minijson::detail::parse_unquoted_value(buffer_context); ASSERT_EQ(minijson::Boolean, value.type()); ASSERT_STREQ("true", value.as_string()); ASSERT_EQ(1, value.as_long()); ASSERT_TRUE( value.as_bool()); ASSERT_DOUBLE_EQ(1.0, value.as_double()); } TEST(minijson_reader_detail, parse_unquoted_value_false) { char buffer[] = "false}"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::detail::read_unquoted_value(buffer_context); const minijson::value value = minijson::detail::parse_unquoted_value(buffer_context); ASSERT_EQ(minijson::Boolean, value.type()); ASSERT_STREQ("false", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); } TEST(minijson_reader_detail, parse_unquoted_value_null) { char buffer[] = "null}"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::detail::read_unquoted_value(buffer_context); const minijson::value value = minijson::detail::parse_unquoted_value(buffer_context); ASSERT_EQ(minijson::Null, value.type()); ASSERT_STREQ("null", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); } TEST(minijson_reader_detail, parse_unquoted_value_integer) { char buffer[] = "42]"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::detail::read_unquoted_value(buffer_context); const minijson::value value = minijson::detail::parse_unquoted_value(buffer_context); ASSERT_EQ(minijson::Number, value.type()); ASSERT_STREQ("42", value.as_string()); ASSERT_EQ(42, value.as_long()); ASSERT_TRUE( value.as_bool()); ASSERT_DOUBLE_EQ(42.0, value.as_double()); } TEST(minijson_reader_detail, parse_unquoted_value_double) { char buffer[] = "42.0e+76,"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::detail::read_unquoted_value(buffer_context); const minijson::value value = minijson::detail::parse_unquoted_value(buffer_context); ASSERT_EQ(minijson::Number, value.type()); ASSERT_STREQ("42.0e+76", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(42.0E+76, value.as_double()); } TEST(minijson_reader_detail, parse_unquoted_value_invalid) { char buffer[] = "asd,"; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); minijson::detail::read_unquoted_value(buffer_context); parse_unquoted_value_invalid_helper(buffer_context, 3); } TEST(minijson_reader_detail, read_value_object) { char buffer[] = "{..."; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); buffer_context.read(); const std::pair<minijson::value, char> result = minijson::detail::read_value(buffer_context, buffer[0]); const minijson::value value = result.first; const char ending_char = result.second; ASSERT_EQ(minijson::Object, value.type()); ASSERT_STREQ("", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); ASSERT_EQ(0, ending_char); } TEST(minijson_reader_detail, read_value_array) { char buffer[] = "[..."; minijson::buffer_context buffer_context(buffer, sizeof(buffer)); buffer_context.read(); const std::pair<minijson::value, char> result = minijson::detail::read_value(buffer_context, buffer[0]); const minijson::value value = result.first; const char ending_char = result.second; ASSERT_EQ(minijson::Array, value.type()); ASSERT_STREQ("", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); ASSERT_EQ(0, ending_char); } TEST(minijson_reader_detail, read_value_quoted_string) { char buffer[] = "\"Hello world\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); buffer_context.read(); const std::pair<minijson::value, char> result = minijson::detail::read_value(buffer_context, buffer[0]); const minijson::value value = result.first; const char ending_char = result.second; ASSERT_EQ(minijson::String, value.type()); ASSERT_STREQ("Hello world", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); ASSERT_EQ(0, ending_char); } TEST(minijson_reader_detail, read_value_quoted_string_empty) { char buffer[] = "\"\""; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); buffer_context.read(); const std::pair<minijson::value, char> result = minijson::detail::read_value(buffer_context, buffer[0]); const minijson::value value = result.first; const char ending_char = result.second; ASSERT_EQ(minijson::String, value.type()); ASSERT_STREQ("", value.as_string()); ASSERT_EQ(0, value.as_long()); ASSERT_FALSE( value.as_bool()); ASSERT_DOUBLE_EQ(0.0, value.as_double()); ASSERT_EQ(0, ending_char); } TEST(minijson_reader_detail, read_value_unquoted) { char buffer[] = "true,"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); buffer_context.read(); const std::pair<minijson::value, char> result = minijson::detail::read_value(buffer_context, buffer[0]); const minijson::value value = result.first; const char ending_char = result.second; ASSERT_EQ(minijson::Boolean, value.type()); ASSERT_STREQ("true", value.as_string()); ASSERT_EQ(1, value.as_long()); ASSERT_TRUE( value.as_bool()); ASSERT_DOUBLE_EQ(1.0, value.as_double()); ASSERT_EQ(',', ending_char); // boolean false, null, integer and double cases have been already tested with parse_unquoted_value } TEST(minijson_reader_detail, read_value_unquoted_invalid) { char buffer[] = "xxx,"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); buffer_context.read(); bool exception_thrown = false; try { minijson::detail::read_value(buffer_context, buffer[0]); } catch (const minijson::parse_error& parse_error) { exception_thrown = true; ASSERT_EQ(minijson::parse_error::INVALID_VALUE, parse_error.reason()); ASSERT_EQ(3u, parse_error.offset()); ASSERT_STREQ("Invalid value", parse_error.what()); } ASSERT_TRUE(exception_thrown); } void parse_object_empty_handler(const char*, minijson::value) { FAIL(); } void parse_array_empty_handler(minijson::value) { FAIL(); } TEST(minijson_reader, parse_object_empty) { char buffer[] = "{}"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_object(buffer_context, parse_object_empty_handler); } struct check_on_destroy_handler { mutable bool check_on_destroy; check_on_destroy_handler() : check_on_destroy(true) { } check_on_destroy_handler(const check_on_destroy_handler& other) : check_on_destroy(true) { other.check_on_destroy = false; } }; struct parse_object_single_field_handler : check_on_destroy_handler { bool read_field; explicit parse_object_single_field_handler() : read_field(false) { } ~parse_object_single_field_handler() { if (check_on_destroy) { EXPECT_TRUE(read_field); } } void operator()(const char* field_name, const minijson::value& field_value) { read_field = true; ASSERT_STREQ("field", field_name); ASSERT_EQ(minijson::String, field_value.type()); ASSERT_STREQ("value", field_value.as_string()); } }; TEST(minijson_reader, parse_object_single_field) { char buffer[] = " { \n\t\"field\" : \"value\"\t\n} "; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_object(buffer_context, parse_object_single_field_handler()); } struct parse_object_multiple_fields_handler : check_on_destroy_handler { std::bitset<7> h; ~parse_object_multiple_fields_handler() { if (check_on_destroy) { EXPECT_TRUE(h.all()); } } void operator()(const char* n, const minijson::value& v) { if (strcmp(n, "string") == 0) { h[0] = 1; ASSERT_EQ(minijson::String, v.type()); ASSERT_STREQ("value\"\\/\b\f\n\r\t", v.as_string()); } else if (strcmp(n, "integer") == 0) { h[1] = 1; ASSERT_EQ(minijson::Number, v.type()); ASSERT_EQ(42, v.as_long()); } else if (strcmp(n, "floating_point") == 0) { h[2] = 1; ASSERT_EQ(minijson::Number, v.type()); ASSERT_DOUBLE_EQ(4261826387162873618273687126387.0, v.as_double()); } else if (strcmp(n, "boolean_true") == 0) { h[3] = 1; ASSERT_EQ(minijson::Boolean, v.type()); ASSERT_TRUE(v.as_bool()); } else if (strcmp(n, "boolean_false") == 0) { h[4] = 1; ASSERT_EQ(minijson::Boolean, v.type()); ASSERT_FALSE(v.as_bool()); } else if (strcmp(n, "") == 0) { h[5] = 1; ASSERT_EQ(minijson::Null, v.type()); } else if (strcmp(n, "\xc3\xA0\x01\x02" "a" "\xED\x9F\xBF\xEE\x80\x80\xEF\xBF\xBF" "b" "你" "\xF0\x90\x80\x80" "\xF4\x8F\xBF\xBF" "à") == 0) { h[6] = 1; ASSERT_EQ(minijson::String, v.type()); ASSERT_STREQ("", v.as_string()); } else { FAIL(); } } }; TEST(minijson_reader, parse_object_multiple_fields) { char buffer[] = "{\"string\":\"value\\\"\\\\\\/\\b\\f\\n\\r\\t\",\"integer\":42,\"floating_point\":4261826387162873618273687126387," "\"boolean_true\":true,\n\"boolean_false\":false,\"\":null," "\"\\u00e0\\u0001\\u0002a\\ud7ff\\uE000\\uFffFb\\u4F60\\uD800\\uDC00\\uDBFF\\uDFFFà\":\"\"}"; { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_object(const_buffer_context, parse_object_multiple_fields_handler()); } { std::istringstream ss(buffer); minijson::istream_context istream_context(ss); minijson::parse_object(istream_context, parse_object_multiple_fields_handler()); } { buffer[sizeof(buffer) - 1] = 'x'; // damage null terminator to test robustness minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_object(buffer_context, parse_object_multiple_fields_handler()); } } template<typename Context> struct parse_object_nested_handler : check_on_destroy_handler { std::bitset<2> h; Context& context; explicit parse_object_nested_handler(Context& context) : context(context) { } ~parse_object_nested_handler() { if (check_on_destroy) { EXPECT_TRUE(h.all()); } } void operator()(const char* n, const minijson::value& v) { if (strcmp(n, "") == 0) { h[0] = 1; ASSERT_EQ(minijson::Object, v.type()); minijson::parse_object(context, nested1_handler(context)); } else if (strcmp(n, "val2") == 0) { h[1] = 1; ASSERT_EQ(minijson::Number, v.type()); ASSERT_DOUBLE_EQ(42.0, v.as_double()); } else { FAIL(); } } struct nested1_handler : check_on_destroy_handler { Context& context; bool read_field; explicit nested1_handler(Context& context) : context(context), read_field(false) { } ~nested1_handler() { if (check_on_destroy) { EXPECT_TRUE(read_field); } } void operator()(const char* n, const minijson::value& v) { read_field = true; ASSERT_STREQ("nested2", n); ASSERT_EQ(minijson::Object, v.type()); minijson::parse_object(context, nested2_handler(context)); } struct nested2_handler : check_on_destroy_handler { std::bitset<2> h; Context& context; explicit nested2_handler(Context& context) : context(context) { } ~nested2_handler() { if (check_on_destroy) { EXPECT_TRUE(h.all()); } } void operator()(const char* n, const minijson::value& v) { if (strcmp(n, "val1") == 0) { h[0] = 1; ASSERT_EQ(minijson::Number, v.type()); ASSERT_EQ(42, v.as_long()); } else if (strcmp(n, "nested3") == 0) { h[1] = 1; ASSERT_EQ(minijson::Array, v.type()); minijson::parse_array(context, parse_array_empty_handler); } else { FAIL(); } } }; }; }; TEST(minijson_reader, parse_object_nested) { char buffer[] = "{\"\":{\"nested2\":{\"val1\":42,\"nested3\":[]}},\"val2\":42.0}"; { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_object(const_buffer_context, parse_object_nested_handler<minijson::const_buffer_context>(const_buffer_context)); } { std::istringstream ss(buffer); minijson::istream_context istream_context(ss); minijson::parse_object(istream_context, parse_object_nested_handler<minijson::istream_context>(istream_context)); } { buffer[sizeof(buffer) - 1] = 'x'; // damage null terminator to test robustness minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_object(buffer_context, parse_object_nested_handler<minijson::buffer_context>(buffer_context)); } } TEST(minijson_reader, parse_array_empty) { char buffer[] = "[]"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(buffer_context, parse_array_empty_handler); } struct parse_array_single_elem_handler : check_on_destroy_handler { bool read_elem; explicit parse_array_single_elem_handler() : read_elem(false) { } ~parse_array_single_elem_handler() { if (check_on_destroy) { EXPECT_TRUE(read_elem); } } void operator()(const minijson::value& elem_value) { read_elem = true; ASSERT_EQ(minijson::String, elem_value.type()); ASSERT_STREQ("value", elem_value.as_string()); } }; TEST(minijson_reader, parse_array_single_elem) { char buffer[] = " [ \n\t\"value\"\t\n] "; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(buffer_context, parse_array_single_elem_handler()); } struct parse_array_single_elem2_handler : check_on_destroy_handler { bool read_elem; explicit parse_array_single_elem2_handler() : read_elem(false) { } ~parse_array_single_elem2_handler() { if (check_on_destroy) { EXPECT_TRUE(read_elem); } } void operator()(const minijson::value& elem_value) { read_elem = true; ASSERT_EQ(minijson:: Number, elem_value.type()); ASSERT_EQ(1, elem_value.as_long()); ASSERT_STREQ("1", elem_value.as_string()); } }; TEST(minijson_reader, parse_array_single_elem2) { char buffer[] = "[1]"; minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(buffer_context, parse_array_single_elem2_handler()); } struct parse_array_multiple_elems_handler : check_on_destroy_handler { size_t counter; parse_array_multiple_elems_handler() : counter(0) { } ~parse_array_multiple_elems_handler() { if (check_on_destroy) { EXPECT_EQ(7U, counter); } } void operator()(const minijson::value& v) { switch (counter++) { case 0: ASSERT_EQ(minijson::String, v.type()); ASSERT_STREQ("value", v.as_string()); break; case 1: ASSERT_EQ(minijson::Number, v.type()); ASSERT_EQ(42, v.as_long()); break; case 2: ASSERT_EQ(minijson::Number, v.type()); ASSERT_DOUBLE_EQ(42.0, v.as_double()); break; case 3: ASSERT_EQ(minijson::Boolean, v.type()); ASSERT_TRUE(v.as_bool()); break; case 4: ASSERT_EQ(minijson::Boolean, v.type()); ASSERT_FALSE(v.as_bool()); break; case 5: ASSERT_EQ(minijson::Null, v.type()); break; case 6: ASSERT_EQ(minijson::String, v.type()); ASSERT_STREQ("", v.as_string()); break; default: FAIL(); } } }; TEST(minijson_reader, parse_array_multiple_elems) { char buffer[] = "[\"value\",42,42.0,true,\nfalse,null,\"\"]"; { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(const_buffer_context, parse_array_multiple_elems_handler()); } { std::istringstream ss(buffer); minijson::istream_context istream_context(ss); minijson::parse_array(istream_context, parse_array_multiple_elems_handler()); } { buffer[sizeof(buffer) - 1] = 'x'; // damage null terminator to test robustness minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(buffer_context, parse_array_multiple_elems_handler()); } } template<typename Context> struct parse_array_nested_handler : check_on_destroy_handler { size_t counter; Context& context; explicit parse_array_nested_handler(Context& context) : counter(0), context(context) { } ~parse_array_nested_handler() { if (check_on_destroy) { EXPECT_EQ(2U, counter); } } void operator()(const minijson::value& v) { switch (counter++) { case 0: ASSERT_EQ(minijson::Array, v.type()); minijson::parse_array(context, nested1_handler(context)); break; case 1: ASSERT_EQ(minijson::Number, v.type()); ASSERT_DOUBLE_EQ(42.0, v.as_double()); break; default: FAIL(); } } struct nested1_handler : check_on_destroy_handler { Context& context; bool read_elem; explicit nested1_handler(Context& context) : context(context), read_elem(false) { } ~nested1_handler() { if (check_on_destroy) { EXPECT_TRUE(read_elem); } } void operator()(const minijson::value& v) { read_elem = true; ASSERT_EQ(minijson::Array, v.type()); minijson::parse_array(context, nested2_handler(context)); } struct nested2_handler : check_on_destroy_handler { size_t counter; Context& context; explicit nested2_handler(Context& context) : counter(0), context(context) { } ~nested2_handler() { if (check_on_destroy) { EXPECT_EQ(2U, counter); } } void operator()(const minijson::value& v) { switch (counter++) { case 0: ASSERT_EQ(minijson::Number, v.type()); ASSERT_EQ(42, v.as_long()); break; case 1: ASSERT_EQ(minijson::Object, v.type()); minijson::parse_object(context, parse_object_empty_handler); break; default: FAIL(); } } }; }; }; TEST(minijson_reader, parse_array_nested) { char buffer[] = "[[[42,{}]],42.0]"; { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(const_buffer_context, parse_array_nested_handler<minijson::const_buffer_context>(const_buffer_context)); } { std::istringstream ss(buffer); minijson::istream_context istream_context(ss); minijson::parse_array(istream_context, parse_array_nested_handler<minijson::istream_context>(istream_context)); } { buffer[sizeof(buffer) - 1] = 'x'; // damage null terminator to test robustness minijson::buffer_context buffer_context(buffer, sizeof(buffer) - 1); minijson::parse_array(buffer_context, parse_array_nested_handler<minijson::buffer_context>(buffer_context)); } } struct parse_dummy { void operator()(const char*, minijson::value) { } void operator()(minijson::value) { } }; template<typename Context> struct parse_dummy_consume { Context& context; explicit parse_dummy_consume(Context& context) : context(context) { } void operator()(const char*, minijson::value value) { operator()(value); } void operator()(minijson::value value) { if (value.type() == minijson::Object) { minijson::parse_object(context, *this); } else if (value.type() == minijson::Array) { minijson::parse_array(context, *this); } } }; TEST(minijson_reader, parse_object_truncated) { using minijson::parse_error; char buffer[] = "{\"str\":\"val\",\"int\":42,\"null\":null}"; for (size_t i = sizeof(buffer) - 2; i < sizeof(buffer); i--) { buffer[i] = 0; minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); bool exception_thrown = false; try { minijson::parse_object(const_buffer_context, parse_dummy()); } catch (const parse_error& e) { exception_thrown = true; switch (i) { case 0: ASSERT_EQ(parse_error::EXPECTED_OPENING_BRACKET, e.reason()); ASSERT_STREQ("Expected opening bracket", e.what()); break; case 1: ASSERT_EQ(parse_error::EXPECTED_OPENING_QUOTE, e.reason()); break; case 2: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 3: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 4: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 5: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 6: ASSERT_EQ(parse_error::EXPECTED_COLON, e.reason()); ASSERT_STREQ("Expected colon", e.what()); break; case 7: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 8: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 9: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 10: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 11: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 12: ASSERT_EQ(parse_error::EXPECTED_COMMA_OR_CLOSING_BRACKET, e.reason()); ASSERT_STREQ("Expected comma or closing bracket", e.what()); break; case 13: ASSERT_EQ(parse_error::EXPECTED_OPENING_QUOTE, e.reason()); break; case 14: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 15: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 16: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 17: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 18: ASSERT_EQ(parse_error::EXPECTED_COLON, e.reason()); break; case 19: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 20: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 21: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 22: ASSERT_EQ(parse_error::EXPECTED_OPENING_QUOTE, e.reason()); break; case 23: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 24: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 25: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 26: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 27: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 28: ASSERT_EQ(parse_error::EXPECTED_COLON, e.reason()); break; case 29: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 30: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 31: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 32: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 33: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; default: FAIL(); } } ASSERT_TRUE(exception_thrown); } } TEST(minijson_reader, parse_array_truncated) { using minijson::parse_error; char buffer[] = "[\"val\",42,null]"; for (size_t i = sizeof(buffer) - 2; i < sizeof(buffer); i--) { buffer[i] = 0; minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); bool exception_thrown = false; try { minijson::parse_array(const_buffer_context, parse_dummy()); } catch (const parse_error& e) { exception_thrown = true; switch (i) { case 0: ASSERT_EQ(parse_error::EXPECTED_OPENING_BRACKET, e.reason()); break; case 1: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 2: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 3: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 4: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 5: ASSERT_EQ(parse_error::EXPECTED_CLOSING_QUOTE, e.reason()); break; case 6: ASSERT_EQ(parse_error::EXPECTED_COMMA_OR_CLOSING_BRACKET, e.reason()); break; case 7: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 8: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 9: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 10: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 11: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 12: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 13: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; case 14: ASSERT_EQ(parse_error::UNTERMINATED_VALUE, e.reason()); break; default: FAIL(); } } ASSERT_TRUE(exception_thrown); } } template<size_t Length> void parse_object_invalid_helper(const char (&buffer)[Length], minijson::parse_error::error_reason expected_reason, const char* expected_what = NULL) { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); bool exception_thrown = false; try { minijson::parse_object(const_buffer_context, parse_dummy()); } catch (const minijson::parse_error& e) { exception_thrown = true; ASSERT_EQ(expected_reason, e.reason()); if (expected_what) { ASSERT_STREQ(expected_what, e.what()); } } ASSERT_TRUE(exception_thrown); } template<size_t Length> void parse_object_invalid_helper2(const char (&buffer)[Length], minijson::parse_error::error_reason expected_reason, const char* expected_what = NULL) { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); bool exception_thrown = false; try { minijson::parse_object(const_buffer_context, parse_dummy_consume<minijson::const_buffer_context>(const_buffer_context)); } catch (const minijson::parse_error& e) { exception_thrown = true; ASSERT_EQ(expected_reason, e.reason()); if (expected_what) { ASSERT_STREQ(expected_what, e.what()); } } ASSERT_TRUE(exception_thrown); } template<size_t Length> void parse_array_invalid_helper(const char (&buffer)[Length], minijson::parse_error::error_reason expected_reason, const char* expected_what = NULL) { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); bool exception_thrown = false; try { minijson::parse_array(const_buffer_context, parse_dummy()); } catch (const minijson::parse_error& e) { exception_thrown = true; ASSERT_EQ(expected_reason, e.reason()); if (expected_what) { ASSERT_STREQ(expected_what, e.what()); } } ASSERT_TRUE(exception_thrown); } template<size_t Length> void parse_array_invalid_helper2(const char (&buffer)[Length], minijson::parse_error::error_reason expected_reason, const char* expected_what = NULL) { minijson::const_buffer_context const_buffer_context(buffer, sizeof(buffer) - 1); bool exception_thrown = false; try { minijson::parse_array(const_buffer_context, parse_dummy_consume<minijson::const_buffer_context>(const_buffer_context)); } catch (const minijson::parse_error& e) { exception_thrown = true; ASSERT_EQ(expected_reason, e.reason()); if (expected_what) { ASSERT_STREQ(expected_what, e.what()); } } ASSERT_TRUE(exception_thrown); } TEST(minijson_reader, parse_object_invalid) { parse_object_invalid_helper("{\"x\":8.2e+62738", minijson::parse_error::UNTERMINATED_VALUE); parse_object_invalid_helper("{\"x\":8.2e+62738}", minijson::parse_error::INVALID_VALUE); parse_object_invalid_helper("{\"x\":3.4.5}", minijson::parse_error::INVALID_VALUE); parse_object_invalid_helper("{\"x\":0x1273}", minijson::parse_error::INVALID_VALUE); parse_object_invalid_helper("{\"x\":NaN}", minijson::parse_error::INVALID_VALUE); parse_object_invalid_helper("{\"x\":nuxl}", minijson::parse_error::INVALID_VALUE); parse_object_invalid_helper("{\"\\ufffx\":null}", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_object_invalid_helper("{\"x\":\"\\ufffx\"}", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_object_invalid_helper("{\"\\u\":\"\"}", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_object_invalid_helper("{\"\\ud800\":null}", minijson::parse_error::EXPECTED_UTF16_LOW_SURROGATE); parse_object_invalid_helper("{\"\\udc00\":null}", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_object_invalid_helper("{\"\\ud800\\uee00\":null}", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_object_invalid_helper("{\"\\x\":null}", minijson::parse_error::INVALID_ESCAPE_SEQUENCE); parse_object_invalid_helper("{\"a\":{}}", minijson::parse_error::NESTED_OBJECT_OR_ARRAY_NOT_PARSED, "Nested object or array not parsed"); parse_object_invalid_helper2( "{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[" "]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}", minijson::parse_error::EXCEEDED_NESTING_LIMIT, "Exceeded nesting limit (32)"); } TEST(minijson_reader, parse_array_invalid) { parse_array_invalid_helper("[8.2e+62738", minijson::parse_error::UNTERMINATED_VALUE); parse_array_invalid_helper("[8.2e+62738]", minijson::parse_error::INVALID_VALUE); parse_array_invalid_helper("[3.4.5]", minijson::parse_error::INVALID_VALUE); parse_array_invalid_helper("[0x1273]", minijson::parse_error::INVALID_VALUE); parse_array_invalid_helper("[NaN]", minijson::parse_error::INVALID_VALUE); parse_array_invalid_helper("[nuxl]", minijson::parse_error::INVALID_VALUE); parse_array_invalid_helper("[\"\\ufffx\"]", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_array_invalid_helper("[\"\\ufff\"]", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_array_invalid_helper("[\"\\ud800\"]", minijson::parse_error::EXPECTED_UTF16_LOW_SURROGATE); parse_array_invalid_helper("[\"\\udc00\"]", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_array_invalid_helper("[\"\\ud800\\uee00\"]", minijson::parse_error::INVALID_UTF16_CHARACTER); parse_array_invalid_helper("[\"\\x\"]", minijson::parse_error::INVALID_ESCAPE_SEQUENCE); parse_array_invalid_helper("[[]]", minijson::parse_error::NESTED_OBJECT_OR_ARRAY_NOT_PARSED, "Nested object or array not parsed"); parse_array_invalid_helper2( "[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{\"\":[{" "}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]", minijson::parse_error::EXCEEDED_NESTING_LIMIT, "Exceeded nesting limit (32)"); } #if MJR_CPP11_SUPPORTED TEST(minijson_dispatch, present) { bool handled[4] { }; minijson::dispatch("test2") <<"test1">> [&]{ handled[0] = true; } <<"test2">> [&]{ handled[1] = true; } // should "break" here <<"test3">> [&]{ handled[2] = true; } <<"test2">> [&]{ handled[3] = true; }; ASSERT_FALSE(handled[0]); ASSERT_TRUE(handled[1]); ASSERT_FALSE(handled[2]); ASSERT_FALSE(handled[3]); } TEST(minijson_dispatch, absent) { bool handled[3] { }; minijson::dispatch("x") <<"test1">> [&]{ handled[0] = true; } <<"test2">> [&]{ handled[1] = true; } <<"test3">> [&]{ handled[2] = true; }; ASSERT_FALSE(handled[0]); ASSERT_FALSE(handled[1]); ASSERT_FALSE(handled[2]); } TEST(minijson_dispatch, absent_with_any_handler) { bool handled[4] { }; using minijson::any; minijson::dispatch("x") <<"test1">> [&]{ handled[0] = true; } <<"test2">> [&]{ handled[1] = true; } <<"test3">> [&]{ handled[2] = true; } <<any>> [&]{ handled[3] = true; }; ASSERT_FALSE(handled[0]); ASSERT_FALSE(handled[1]); ASSERT_FALSE(handled[2]); ASSERT_TRUE(handled[3]); } TEST(minijson_dispatch, std_string) { const std::string x = "x"; bool handled = false; minijson::dispatch(x) <<x>> [&]{ handled = true; }; ASSERT_TRUE(handled); } TEST(minijson_dispatch, parse_object) { char json_obj[] = "{ \"field1\": 42, \"array\" : [ 1, 2, 3 ], \"field2\": \"asd\", " "\"nested\" : { \"field1\" : 42.0, \"field2\" : true, \"ignored_field\" : 0, \"ignored_object\" : {\"a\":[0]} }," "\"ignored_array\" : [4, 2, {\"a\":5}, [7]] }"; struct obj_type { long field1 = 0; std::string field2; struct { double field1 = std::numeric_limits<double>::quiet_NaN(); bool field2 = false; } nested; std::vector<int> array; }; obj_type obj; using namespace minijson; buffer_context ctx(json_obj, sizeof(json_obj) - 1); parse_object(ctx, [&](const char* k, value v) { dispatch (k) <<"field1">> [&]{ obj.field1 = v.as_long(); } <<"field2">> [&]{ obj.field2 = v.as_string(); } <<"nested">> [&] { parse_object(ctx, [&](const char* k, value v) { dispatch (k) <<"field1">> [&]{ obj.nested.field1 = v.as_double(); } <<"field2">> [&]{ obj.nested.field2 = v.as_bool(); } <<any>> [&]{ ignore(ctx); }; }); } <<"array">> [&] { parse_array(ctx, [&](value v) { obj.array.push_back(v.as_long()); }); } <<any>> [&]{ ignore(ctx); }; }); ASSERT_EQ(42, obj.field1); ASSERT_EQ("asd", obj.field2); ASSERT_DOUBLE_EQ(42.0, obj.nested.field1); ASSERT_TRUE(obj.nested.field2); ASSERT_EQ(3U, obj.array.size()); ASSERT_EQ(1, obj.array[0]); ASSERT_EQ(2, obj.array[1]); ASSERT_EQ(3, obj.array[2]); } #endif // MJR_CPP11_SUPPORTED int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
e29c10ce45f2ba69457f3aab0e710af2c2ca3c4d
acf6c6b9550b660f59d81be0c78bcac2a4331f94
/src/3rdparty/grt/examples/PreprocessingModulesExamples/MovingAverageFilterExample/MovingAverageFilterExample.cpp
be9f1163f08a4699275801787f7b85e5d18ec7c9
[ "MIT" ]
permissive
wangscript007/Miniwin
95ad9fff4f234cf0235a017e51a7cfb47c0b0353
001d8804d9ae7a1b265fc7a62029469b15505b92
refs/heads/master
2022-12-15T11:12:01.746551
2020-09-04T07:44:39
2020-09-04T07:44:39
293,456,945
2
0
null
2020-09-07T07:41:31
2020-09-07T07:41:30
null
UTF-8
C++
false
false
2,839
cpp
/* GRT MIT License Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* GRT MovingAverageFilter Example This example demonstrates how to create and use the GRT MovingAverageFilter PreProcessing Module. The MovingAverageFilter implements a low pass moving average filter. In this example we create an instance of a MovingAverageFilter and use this to filter some dummy data, generated from a sine wave + random noise. The test signal and filtered signals are then printed to std::cout. This example shows you how to: - Create a new MovingAverageFilter instance with a specific window size for a 1 dimensional signal - Filter some data using the MovingAverageFilter - Save the MovingAverageFilter settings to a file - Load the MovingAverageFilter settings from a file */ //You might need to set the specific path of the GRT header relative to your project #include <GRT/GRT.h> using namespace GRT; using namespace std; int main (int argc, const char * argv[]) { //Create a new instance of a moving average filter with a window size of 5 for a 1 dimensional signal MovingAverageFilter filter( 5, 1 ); //Generate some data (sine wave + noise) and filter it double x = 0; const UINT M = 1000; Random random; for(UINT i=0; i<M; i++){ double signal = sin( x ) + random.getRandomNumberUniform(-0.2,0.2); double filteredValue = filter.filter( signal ); cout << signal << "\t" << filteredValue << endl; x += TWO_PI/double(M)*10; } //Save the filter settings to a file filter.save("MovingAverageFilterSettings.grt"); //We can then load the settings later if needed filter.load("MovingAverageFilterSettings.grt"); return EXIT_SUCCESS; }
b574dc0508300f78a612b5d8be63516c1e9d9f58
ac49f1cce8ceaa17f712b7bd692820aaebfded33
/cpp/004_braced/main.cpp
b0b7b1dcb98e3914d6c9abab7d4baf64eddcffbe
[]
no_license
kogotto/experiments
a22353a474c2b57bc10c48cfa2d5f243e0dd2aa8
b70cd946ee852f83cf907a666cd9f45a5ab26ef6
refs/heads/master
2023-04-30T10:03:12.690143
2019-09-05T11:12:50
2023-04-13T21:46:07
206,544,121
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
#include <string> #include <vector> #include <iostream> struct Foo { Foo(const std::string& s): s(s) {} std::string s; }; const std::string& getFoo() { static const std::string result = "kajdfkj"; return result; } int main() { std::string s = "adfadfasdf"; Foo f{s}; std::vector<Foo> v; v.push_back({s}); v.push_back({getFoo()}); std::cout << f.s; for (const auto& f1: v) { std::cout << f1.s << std::endl; } }
b98b579ce064efeb7033e840f4051e1e86b2f4a2
195d68b4f5c66859468388a66da8ec7fd73fec76
/test/comprehensive/enc/testdeepcopy.cpp
604d5c759cbe3e9d053b5a33bb51ed7ebca9513b
[ "MIT" ]
permissive
jhand2/oeedger8r-cpp
208d82456610f36164f03df1a681cf73f94ad3f4
616ef0f40aba7efe08eda71a8620013c66bdfa29
refs/heads/master
2022-09-09T01:42:21.478613
2020-06-01T21:57:43
2020-06-01T21:57:43
268,928,234
0
0
MIT
2020-06-02T23:16:24
2020-06-02T23:16:24
null
UTF-8
C++
false
false
8,476
cpp
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include "../edltestutils.h" #include <openenclave/enclave.h> #include <openenclave/internal/tests.h> #include <stdio.h> #include <string.h> #include "all_t.h" #define oe_strcmp strcmp static uint64_t data[8] = {0x1112131415161718, 0x2122232425262728, 0x3132333435363738, 0x4142434445464748, 0x5152535455565758, 0x6162636465666768, 0x7172737475767778, 0x8182838485868788}; // Assert that the struct is copied by value, such that `s.ptr` is the // address of `data[]` in the host (also passed via `ptr`). void deepcopy_value(ShallowStruct s, uint64_t* ptr) { OE_TEST(s.count == 7); OE_TEST(s.size == 64); OE_TEST(s.ptr == ptr); OE_TEST(oe_is_outside_enclave(s.ptr, sizeof(uint64_t))); } // Assert that the struct is shallow-copied (even though it is passed // by pointer), such that `s->ptr` is the address of `data[]` in the // host (also passed via `ptr`). void deepcopy_shallow(ShallowStruct* s, uint64_t* ptr) { OE_TEST(s->count == 7); OE_TEST(s->size == 64); OE_TEST(s->ptr == ptr); OE_TEST(oe_is_outside_enclave(s->ptr, sizeof(uint64_t))); } // Assert that the struct is deep-copied such that `s->ptr` has a copy // of three elements of `data` in enclave memory. void deepcopy_count(CountStruct* s) { OE_TEST(s->count == 7); OE_TEST(s->size == 64); for (size_t i = 0; i < 3; ++i) OE_TEST(s->ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s->ptr, 3 * sizeof(uint64_t))); } // Assert that the struct is deep-copied such that `s->ptr` has a copy // of `s->count` elements of `data` in enclave memory. void deepcopy_countparam(CountParamStruct* s) { OE_TEST(s->count == 7); OE_TEST(s->size == 64); for (size_t i = 0; i < s->count; ++i) OE_TEST(s->ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s->ptr, s->count * sizeof(uint64_t))); } // Assert that the struct is deep-copied such that `s->ptr` has a copy // of `s->size` bytes of `data` in enclave memory. void deepcopy_sizeparam(SizeParamStruct* s) { OE_TEST(s->count == 7); OE_TEST(s->size == 64); for (size_t i = 0; i < s->size / sizeof(uint64_t); ++i) OE_TEST(s->ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s->ptr, s->size)); } // Assert that the struct is deep-copied such that `s->ptr` has a copy // of `s->count * s->size` bytes of `data` in enclave memory. void deepcopy_countsizeparam(CountSizeParamStruct* s) { OE_TEST(s->count == 8); OE_TEST(s->size == 4); for (size_t i = 0; i < (s->count * s->size) / sizeof(uint64_t); ++i) OE_TEST(s->ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s->ptr, s->count * s->size)); } // Assert that the struct is deep-copied such that `s->ptr` has a copy // of `s->count * s->size` bytes of `data` in enclave memory, not just // `s->count` copies. void deepcopy_countsizeparam_size(CountSizeParamStruct* s) { OE_TEST(s->count == 1); OE_TEST(s->size == (4 * sizeof(uint64_t))); for (size_t i = 0; i < 4; ++i) OE_TEST(s->ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s->ptr, (4 * sizeof(uint64_t)))); } // Assert that the struct is deep-copied such that `s->ptr` has a copy // of `s->count * s->size` bytes of `data` in enclave memory, not just // `s->size` bytes. void deepcopy_countsizeparam_count(CountSizeParamStruct* s) { OE_TEST(s->count == 4); OE_TEST(s->size == sizeof(uint64_t)); for (size_t i = 0; i < 4; ++i) OE_TEST(s->ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s->ptr, (4 * sizeof(uint64_t)))); } // Assert that the struct array is deep-copied such that each // element's `ptr` has a copy of its `count` elements of `data` in // enclave memory. void deepcopy_countparamarray(CountParamStruct* s) { OE_TEST(s[0].count == 7); OE_TEST(s[0].size == 64); for (size_t i = 0; i < s[0].count; ++i) OE_TEST(s[0].ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s[0].ptr, s[0].count * sizeof(uint64_t))); OE_TEST(s[1].count == 3); OE_TEST(s[1].size == 32); for (size_t i = 0; i < s[1].count; ++i) OE_TEST(s[1].ptr[i] == data[4 + i]); OE_TEST(oe_is_within_enclave(s[1].ptr, s[1].count * sizeof(uint64_t))); } // Assert that the struct array is deep-copied such that each // element's `ptr` has a copy of its `size` bytes of `data` in enclave // memory. void deepcopy_sizeparamarray(SizeParamStruct* s) { OE_TEST(s[0].count == 7); OE_TEST(s[0].size == 64); for (size_t i = 0; i < s[0].size / sizeof(uint64_t); ++i) OE_TEST(s[0].ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s[0].ptr, s[0].size)); OE_TEST(s[1].count == 3); OE_TEST(s[1].size == 32); for (size_t i = 0; i < s[1].size / sizeof(uint64_t); ++i) OE_TEST(s[1].ptr[i] == data[4 + i]); OE_TEST(oe_is_within_enclave(s[1].ptr, s[1].size)); } // Assert that the struct array is deep-copied such that each // element's `ptr` has a copy of its `count * size` bytes of `data` in // enclave memory. void deepcopy_countsizeparamarray(CountSizeParamStruct* s) { OE_TEST(s[0].count == 8); OE_TEST(s[0].size == 4); for (size_t i = 0; i < (s[0].count * s[0].size) / sizeof(uint64_t); ++i) OE_TEST(s[0].ptr[i] == data[i]); OE_TEST(oe_is_within_enclave(s[0].ptr, s[0].count * s[0].size)); OE_TEST(s[1].count == 3); OE_TEST(s[1].size == 8); for (size_t i = 0; i < (s[1].count * s[1].size) / sizeof(uint64_t); ++i) OE_TEST(s[1].ptr[i] == data[4 + i]); OE_TEST(oe_is_within_enclave(s[1].ptr, s[1].count * s[1].size)); } void deepcopy_nested(NestedStruct* n) { OE_TEST(oe_is_within_enclave(n, sizeof(NestedStruct))); OE_TEST(n->plain_int == 13); OE_TEST(oe_is_within_enclave(n->array_of_int, 4 * sizeof(int))); for (int i = 0; i < 4; ++i) OE_TEST(n->array_of_int[i] == i); OE_TEST(oe_is_outside_enclave(n->shallow_struct, sizeof(ShallowStruct))); OE_TEST(oe_is_within_enclave(n->array_of_struct, 3 * sizeof(CountStruct))); for (size_t i = 0; i < 3; ++i) deepcopy_count(&(n->array_of_struct[i])); } void deepcopy_super_nested(SuperNestedStruct* s, size_t n) { OE_TEST(oe_is_within_enclave(s, n * sizeof(SuperNestedStruct))); // This test exists to check that the produced size of `_ptrs` is // `n * (1 + 2 * (1 + 1 + 3))`. OE_TEST(oe_is_within_enclave( s[0].more_structs[0].array_of_struct, 3 * sizeof(CountStruct))); OE_TEST(oe_is_outside_enclave( s[0].more_structs[0].shallow_struct, sizeof(ShallowStruct))); } void deepcopy_null(CountStruct* s) { OE_UNUSED(s); } void deepcopy_in(CountStruct* s) { // Assert that it was copied in correctly. deepcopy_count(s); // Cause it to copy out incorrectly. for (size_t i = 0; i < 3; ++i) s->ptr[i] = i; } void deepcopy_inout_count(CountStruct* s) { OE_TEST(s->count == 5); OE_TEST(s->size == 6); for (size_t i = 0; i < 3; ++i) OE_TEST(s->ptr[i] == 7); s->count = 7; s->size = 64; for (size_t i = 0; i < 3; ++i) s->ptr[i] = data[i]; } void deepcopy_out_count(CountStruct* s) { s->count = 7; s->size = 64; for (size_t i = 0; i < 3; ++i) s->ptr[i] = data[i]; } void deepcopy_nested_out(NestedStruct* n) { OE_TEST(oe_is_within_enclave(n, sizeof(NestedStruct))); OE_TEST(oe_is_within_enclave(n->array_of_int, 4 * sizeof(int))); for (int i = 0; i < 4; ++i) n->array_of_int[i] = i; OE_TEST(oe_is_within_enclave(n->array_of_struct, 3 * sizeof(CountStruct))); for (size_t i = 0; i < 3; ++i) deepcopy_out_count(&(n->array_of_struct[i])); } void deepcopy_iovec(IOVEC* iov, size_t n) { OE_TEST(!(n && !iov)); OE_TEST(n == 2); for (size_t i = 0; i < n; i++) { char* str = (char*)iov[i].base; size_t len = iov[i].len; switch (i) { case 0: OE_TEST(len == 8); OE_TEST(oe_strcmp(str, "red") == 0); memcpy(str, "0000000", 8); break; case 1: OE_TEST(len == 0); OE_TEST(str == NULL); break; default: OE_TEST(false); break; } } }
45ea8e4b38f41eec6b95567a3f7f5775c97dc537
be4952850ad6a8b0abe50de671c495c6add9fae7
/codeforce/CF_785B.cpp
246656a5beea19a73738f8f6c775acef3929ea16
[]
no_license
ss5ssmi/OJ
296cb936ecf7ef292e91f24178c9c08bd2d241b5
267184cef5f1bc1f222950a71fe705bbc5f0bb3e
refs/heads/master
2022-10-29T18:15:14.290028
2022-10-12T04:42:47
2022-10-12T04:42:47
103,818,651
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include<bits/stdc++.h> using namespace std; struct node { int l,r; } p[200000],c[200000]; int main() { int n,m,t1l=0,t2l=0,t1r=1e9,t2r=1e9; scanf("%d",&n); for(int i=0; i<n; i++) { scanf("%d%d",&p[i].l,&p[i].r); t1l=max(t1l,p[i].l); t1r=min(t1r,p[i].r); } scanf("%d",&m); for(int i=0; i<m; i++) { scanf("%d%d",&c[i].l,&c[i].r); t2l=max(t2l,c[i].l); t2r=min(t2r,c[i].r); } int tmp1=t1l-t2r,tmp2=t2l-t1r; if(tmp1<=0 && tmp2<=0) { printf("0\n"); } else if(tmp1 || tmp2) { printf("%d\n",tmp1>tmp2?tmp1:tmp2); } return 0; }
4f86c36556a076b11ef46d4bbdd60312adcbd2d6
64684646c96123397d60052d7d04bb370a182b42
/dragon/include/dragon/lang/String.h
71da8cdda21e5a70932882991111e209a3b2ec0f
[]
no_license
yubing744/dragon
e6ca32726df8fe8e9e1d0586058b8628245efb55
eca9b4b6823c98ddc56ccedde486099653b13920
refs/heads/master
2020-05-22T09:11:15.052073
2017-01-02T01:30:53
2017-01-02T01:30:53
33,351,592
4
1
null
null
null
null
UTF-8
C++
false
false
31,883
h
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** * Author: Owen Wu/wcw/yubing * Email: [email protected] * Created: 2013/03/31 **********************************************************************/ #ifndef String_Lang_Dragon_H #define String_Lang_Dragon_H #include <dragon/config.h> #include <dragon/lang/Math.h> #include <dragon/lang/Array.h> #include <dragon/lang/Object.h> #include <dragon/lang/Comparable.h> #include <dragon/lang/CharSequence.h> #include <iostream> #include <cstdlib> #include <locale> #include <stdio.h> #include <stdarg.h> #include <string.h> BeginPackage2(dragon, lang) Import std; /** * The <code>String</code> class represents character strings. All * string literals in Java programs, such as <code>"abc"</code>, are * implemented as instances of this class. * <p> * Strings are constant; their values cannot be changed after they * are created. String buffers support mutable strings. * Because String objects are immutable they can be shared. For example: * <p><blockquote><pre> * String str = "abc"; * </pre></blockquote><p> * is equivalent to: * <p><blockquote><pre> * char data[] = {'a', 'b', 'c'}; * String str = new String(data); * </pre></blockquote><p> * Here are some more examples of how strings can be used: * <p><blockquote><pre> * System.out.println("abc"); * String cde = "cde"; * System.out.println("abc" + cde); * String c = "abc".substring(2,3); * String d = cde.substring(1, 2); * </pre></blockquote> * <p> * The class <code>String</code> includes methods for examining * individual characters of the sequence, for comparing strings, for * searching strings, for extracting substrings, and for creating a * copy of a string with all characters translated to uppercase or to * lowercase. Case mapping is based on the Unicode Standard version * specified by the {@link java.lang.Character Character} class. * <p> * The Java language provides special support for the string * concatenation operator (&nbsp;+&nbsp;), and for conversion of * other objects to strings. String concatenation is implemented * through the <code>StringBuilder</code>(or <code>StringBuffer</code>) * class and its <code>append</code> method. * String conversions are implemented through the method * <code>toString</code>, defined by <code>Object</code> and * inherited by all classes in Java. For additional information on * string concatenation and conversion, see Gosling, Joy, and Steele, * <i>The Java Language Specification</i>. * * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * <p>A <code>String</code> represents a string in the UTF-16 format * in which <em>supplementary characters</em> are represented by <em>surrogate * pairs</em> (see the section <a href="Character.html#unicode">Unicode * Character Representations</a> in the <code>Character</code> class for * more information). * Index values refer to <code>char</code> code units, so a supplementary * character uses two positions in a <code>String</code>. * <p>The <code>String</code> class provides methods for dealing with * Unicode code points (i.e., characters), in addition to those for * dealing with Unicode code units (i.e., <code>char</code> values). */ class _DragonExport String extends(Object) implements2(CharSequence, Comparable<String>) { public: friend wostream& operator << (wostream& os, const String& str); friend wostream& operator << (wostream& os, String* str); friend size_t hash_value(const String& str); friend bool operator<(const String& left, const String& right); //------------------------------------------------------------------- public: static const Type* TYPE; private: static const char* LOCAL_UCS4_CHARSET; static const Array<wchar_u> EMPTY_CHAR_ARRAY; static const Array<byte> EMPTY_BYTE_ARRAY; private: static char* init(); static void destroy(); public: static char* DEFAULT_CHARSET_NAME; static Array<wchar_u> decode(Array<byte> bytes, int offset, int length, const char* charset); static Array<byte> encode(Array<wchar_u> chars, int offset, int length, const char* charset); public: String(); String(const char* value); String(const char* value, int length); String(const char* value, int offset, int length); String(const wchar_t* value); String(const wchar_t* value, int length); String(const wchar_t* value, int offset, int length); String(const wchar_u* value); String(const wchar_u* value, int length); String(const wchar_u* value, int offset, int length); String(Array<byte> bytes, int length); String(Array<byte> bytes, int offset, int length); String(Array<byte> bytes, int offset, int length, const char* charset); String(const String& value); String(const String* value); ~String(); protected: // Package private constructor which shares value array for speed. String(int offset, int count, wchar_u* value); public: String* operator = (const char* str); String* operator = (const wchar_t* str); String& operator = (const String& str); String* operator->() { return this; }; const String* operator->() const { return this; }; //bool operator< (const String& str) const; /* String& operator+ (const String& str); String& operator+=(const String& str); bool operator==(const wchar_u* str); bool operator==(const String& str); operator wstring(); operator string(); operator size_t(); size_t operator()(const String& str); */ public: /** * Compares two strings lexicographically. * The comparison is based on the Unicode value of each character in * the strings. The character sequence represented by this * <code>String</code> object is compared lexicographically to the * character sequence represented by the argument string. The result is * a negative integer if this <code>String</code> object * lexicographically precedes the argument string. The result is a * positive integer if this <code>String</code> object lexicographically * follows the argument string. The result is zero if the strings * are equal; <code>compareTo</code> returns <code>0</code> exactly when * the {@link #equals(Object)} method would return <code>true</code>. * <p> * This is the definition of lexicographic ordering. If two strings are * different, then either they have different characters at some index * that is a valid index for both strings, or their lengths are different, * or both. If they have different characters at one or more index * positions, let <i>k</i> be the smallest such index; then the string * whose character at position <i>k</i> has the smaller value, as * determined by using the &lt; operator, lexicographically precedes the * other string. In this case, <code>compareTo</code> returns the * difference of the two character values at position <code>k</code> in * the two string -- that is, the value: * <blockquote><pre> * this.charAt(k)-anotherString.charAt(k) * </pre></blockquote> * If there is no index position at which they differ, then the shorter * string lexicographically precedes the longer string. In this case, * <code>compareTo</code> returns the difference of the lengths of the * strings -- that is, the value: * <blockquote><pre> * this.length()-anotherString.length() * </pre></blockquote> * * @param anotherString the <code>String</code> to be compared. * @return the value <code>0</code> if the argument string is equal to * this string; a value less than <code>0</code> if this string * is lexicographically less than the string argument; and a * value greater than <code>0</code> if this string is * lexicographically greater than the string argument. */ int compareTo(String* str); /** * Compares two strings lexicographically, ignoring case * differences. This method returns an integer whose sign is that of * calling <code>compareTo</code> with normalized versions of the strings * where case differences have been eliminated by calling * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on * each character. * <p> * Note that this method does <em>not</em> take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides <em>collators</em> to allow * locale-sensitive ordering. * * @param str the <code>String</code> to be compared. * @return a negative integer, zero, or a positive integer as the * specified String is greater than, equal to, or less * than this String, ignoring case considerations. * @see java.text.Collator#compare(String, String) * @since 1.2 */ int compareToIgnoreCase(String* str); /** * Compares this string to the specified object. * The result is <code>true</code> if and only if the argument is not * <code>null</code> and is a <code>String</code> object that represents * the same sequence of characters as this object. * * @param str the object to compare this <code>String</code> * against. * @return <code>dg_true</code> if the <code>String </code>are equal; * <code>dg_false</code> otherwise. * @see dragon.lang.String#compareTo(const dragon.lang.String*) * @see dragon.lang.String#equalsIgnoreCase(const dragon.lang.String*) */ bool equals(const String* str) const; bool equals(const String& str) const; /** * Tests if this string starts with the specified prefix beginning * a specified index. * * @param prefix the prefix. * @param toffset where to begin looking in the string. * @return <code>dg_true</code> if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index <code>toffset</code>; <code>dg_false</code> otherwise. * The result is <code>false</code> if <code>toffset</code> is * negative or greater than the length of this * <code>String</code> object; otherwise the result is the same * as the result of the expression * <pre> * this->substring(toffset)->startsWith(prefix) * </pre> */ bool startsWith(const String& prefix, int toffset) const; /** * Tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return <code>dg_true</code> if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; <code>dg_false</code> otherwise. * Note also that <code>true</code> will be returned if the * argument is an empty string or is equal to this * <code>String</code> object as determined by the * {@link #equals(Object)} method. * @since 1. 0 */ bool startsWith(const String& prefix) const; /** * Tests if this string ends with the specified suffix. * * @param suffix the suffix. * @return <code>dg_true</code> if the character sequence represented by the * argument is a suffix of the character sequence represented by * this object; <code>dg_false</code> otherwise. Note that the * result will be <code>true</code> if the argument is the * empty string or is equal to this <code>String</code> object * as determined by the {@link #equals(Object)} method. */ bool endsWith(const String& suffix) const; /** * Returns a hash code for this string. The hash code for a * <code>String</code> object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using <code>int</code> arithmetic, where <code>s[i]</code> is the * <i>i</i>th character of the string, <code>n</code> is the length of * the string, and <code>^</code> indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ int hashCode(); /** * Returns the index within this string of the first occurrence of * the specified character. If a character with value * <code>ch</code> occurs in the character sequence represented by * this <code>String</code> object, then the index (in Unicode * code units) of the first such occurrence is returned. For * values of <code>ch</code> in the range from 0 to 0xFFFF * (inclusive), this is the smallest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * smallest value <i>k</i> such that: * <blockquote><pre> * this.codePointAt(<i>k</i>) == ch * </pre></blockquote> * is true. In either case, if no such character occurs in this * string, then <code>-1</code> is returned. * * @param ch a character (Unicode code point). * @return the index of the first occurrence of the character in the * character sequence represented by this object, or * <code>-1</code> if the character does not occur. */ int indexOf(wchar_u ch) const; /** * Returns the index within this string of the first occurrence of the * specified character, starting the search at the specified index. * <p> * If a character with value <code>ch</code> occurs in the * character sequence represented by this <code>String</code> * object at an index no smaller than <code>fromIndex</code>, then * the index of the first such occurrence is returned. For values * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive), * this is the smallest value <i>k</i> such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex) * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * smallest value <i>k</i> such that: * <blockquote><pre> * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &gt;= fromIndex) * </pre></blockquote> * is true. In either case, if no such character occurs in this * string at or after position <code>fromIndex</code>, then * <code>-1</code> is returned. * * <p> * There is no restriction on the value of <code>fromIndex</code>. If it * is negative, it has the same effect as if it were zero: this entire * string may be searched. If it is greater than the length of this * string, it has the same effect as if it were equal to the length of * this string: <code>-1</code> is returned. * * <p>All indices are specified in <code>char</code> values * (Unicode code units). * * @param ch a character (Unicode code point). * @param fromIndex the index to start the search from. * @return the index of the first occurrence of the character in the * character sequence represented by this object that is greater * than or equal to <code>fromIndex</code>, or <code>-1</code> * if the character does not occur. */ int indexOf(wchar_u ch, int fromIndex) const; /** * Returns the index within this string of the first occurrence of the * specified substring. The integer returned is the smallest value * <i>k</i> such that: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * is <code>true</code>. * * @param str any string. * @return if the string argument occurs as a substring within this * object, then the index of the first character of the first * such substring is returned; if it does not occur as a * substring, <code>-1</code> is returned. */ int indexOf(String* str) const; /** * Returns the index within this string of the first occurrence of the * specified substring, starting at the specified index. The integer * returned is the smallest value <tt>k</tt> for which: * <blockquote><pre> * k &gt;= Math.min(fromIndex, str.length()) && this.startsWith(str, k) * </pre></blockquote> * If no such value of <i>k</i> exists, then -1 is returned. * * @param str the substring for which to search. * @param fromIndex the index from which to start the search. * @return the index within this string of the first occurrence of the * specified substring, starting at the specified index. */ int indexOf(String* str, int fromIndex) const; /** * Returns the index within this string of the last occurrence of * the specified character. For values of <code>ch</code> in the * range from 0 to 0xFFFF (inclusive), the index (in Unicode code * units) returned is the largest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * largest value <i>k</i> such that: * <blockquote><pre> * this.codePointAt(<i>k</i>) == ch * </pre></blockquote> * is true. In either case, if no such character occurs in this * string, then <code>-1</code> is returned. The * <code>String</code> is searched backwards starting at the last * character. * * @param ch a character (Unicode code point). * @return the index of the last occurrence of the character in the * character sequence represented by this object, or * <code>-1</code> if the character does not occur. */ int lastIndexOf(wchar_u ch); /** * Returns the index within this string of the last occurrence of * the specified character, searching backward starting at the * specified index. For values of <code>ch</code> in the range * from 0 to 0xFFFF (inclusive), the index returned is the largest * value <i>k</i> such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex) * </pre></blockquote> * is true. For other values of <code>ch</code>, it is the * largest value <i>k</i> such that: * <blockquote><pre> * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> &lt;= fromIndex) * </pre></blockquote> * is true. In either case, if no such character occurs in this * string at or before position <code>fromIndex</code>, then * <code>-1</code> is returned. * * <p>All indices are specified in <code>char</code> values * (Unicode code units). * * @param ch a character (Unicode code point). * @param fromIndex the index to start the search from. There is no * restriction on the value of <code>fromIndex</code>. If it is * greater than or equal to the length of this string, it has * the same effect as if it were equal to one less than the * length of this string: this entire string may be searched. * If it is negative, it has the same effect as if it were -1: * -1 is returned. * @return the index of the last occurrence of the character in the * character sequence represented by this object that is less * than or equal to <code>fromIndex</code>, or <code>-1</code> * if the character does not occur before that point. */ int lastIndexOf(wchar_u ch, int fromIndex); /** * Returns the index within this string of the rightmost occurrence * of the specified substring. The rightmost empty string "" is * considered to occur at the index value <code>this.length()</code>. * The returned index is the largest value <i>k</i> such that * <blockquote><pre> * this.startsWith(str, k) * </pre></blockquote> * is true. * * @param str the substring to search for. * @return if the string argument occurs one or more times as a substring * within this object, then the index of the first character of * the last such substring is returned. If it does not occur as * a substring, <code>-1</code> is returned. */ int lastIndexOf(const String& str) const; /** * Returns the index within this string of the last occurrence of the * specified substring, searching backward starting at the specified index. * The integer returned is the largest value <i>k</i> such that: * <blockquote><pre> * k &lt;= Math.min(fromIndex, str.length()) && this.startsWith(str, k) * </pre></blockquote> * If no such value of <i>k</i> exists, then -1 is returned. * * @param str the substring to search for. * @param fromIndex the index to start the search from. * @return the index within this string of the last occurrence of the * specified substring. */ int lastIndexOf(const String& str, int fromIndex) const; /** * Returns a new string that is a substring of this string. The * substring begins with the character at the specified index and * extends to the end of this string. <p> * Examples: * <blockquote><pre> * "unhappy".substring(2) returns "happy" * "Harbison".substring(3) returns "bison" * "emptiness".substring(9) returns "" (an empty string) * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if * <code>beginIndex</code> is negative or larger than the * length of this <code>String</code> object. */ String* substring(int beginIndex) const; /** * Returns a new string that is a substring of this string. The * substring begins at the specified <code>beginIndex</code> and * extends to the character at index <code>endIndex - 1</code>. * Thus the length of the substring is <code>endIndex-beginIndex</code>. * <p> * Examples: * <blockquote><pre> * "hamburger".substring(4, 8) returns "urge" * "smiles".substring(1, 5) returns "mile" * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of * this <code>String</code> object, or * <code>beginIndex</code> is larger than * <code>endIndex</code>. */ String* substring(int beginIndex, int endIndex) const; /** * Concatenates the specified string to the end of this string. * <p> * If the length of the argument string is <code>0</code>, then this * <code>String</code> object is returned. Otherwise, a new * <code>String</code> object is created, representing a character * sequence that is the concatenation of the character sequence * represented by this <code>String</code> object and the character * sequence represented by the argument string.<p> * Examples: * <blockquote><pre> * "cares".concat("s") returns "caress" * "to".concat("get").concat("her") returns "together" * </pre></blockquote> * * @param str the <code>String</code> that is concatenated to the end * of this <code>String</code>. * @return a string that represents the concatenation of this object's * characters followed by the string argument's characters. */ String* concat(const String& str) const; public: // Implements Interface CharSequence /** * Returns the length of this string. * The length is equal to the number of 16-bit * Unicode characters in the string. * * @return the length of the sequence of characters represented by this * object. */ virtual int length() const; /** * Returns the <code>char</code> value at the * specified index. An index ranges from <code>0</code> to * <code>length() - 1</code>. The first <code>char</code> value of the sequence * is at index <code>0</code>, the next at index <code>1</code>, * and so on, as for array indexing. * * <p>If the <code>char</code> value specified by the index is a * <a href="Character.html#unicode">surrogate</a>, the surrogate * value is returned. * * @param index the index of the <code>char</code> value. * @return the <code>char</code> value at the specified index of this string. * The first <code>char</code> value is at index <code>0</code>. * @exception IndexOutOfBoundsException if the <code>index</code> * argument is negative or not less than the length of this * string. */ virtual wchar_u charAt(int index) const; virtual CharSequence* subSequence(int start, int end) const; virtual String* toString() const; public: const wchar_u* toChars() const; const Array<wchar_u> toCharArray() const; void getChars(int srcBegin, int srcEnd, wchar_u* dst, int dstBegin) const; const Array<byte> getBytes() const; const Array<byte> getBytes(const char* charset) const; const Array<byte> getBytes(const String& charset) const; const Array<char> toUTF8CharArray() const; char* toUTF8String() const; char* toCString() const; wchar_t* toWCHARString() const; bool matches(const String& regex) const; bool matches(String* regex) const; bool contains(CharSequence* s) const; bool contains(const String& s) const; String* replace(wchar_u oldChar, wchar_u newChar); String* replace(CharSequence* target, CharSequence* replacement); String* replaceAll(String* regex, String* replacement); String* replaceAll(const String& regex, const String& replacement); String* replaceFirst(String* regex, String* replacement); Array<String*> split(const String& regex) const; Array<String*> split(const String* regex) const; Array<String*> split(const String* regex, int limit) const; String* toLowerCase(); String* toUpperCase(); String* trim(); public: static String* copyValueOf(const wchar_u* data, int offset, int count); static String* copyValueOf(const wchar_u* data); static String* vformat(String* format, va_list arg); static String* format(String* format, ...); static String* vformat(const char* format, va_list arg); static String* format(const char* format, ...); static String* vformat(const wchar_t* format, va_list arg); static String* format(const wchar_t* format, ...); /** * Returns the string representation of a specific subarray of the * <code>wchar_u</code> array argument. * <p> * The <code>offset</code> argument is the index of the first * wchar_uacter of the subarray. The <code>count</code> argument * specifies the length of the subarray. The contents of the subarray * are copied; subsequent modification of the wchar_uacter array does not * affect the newly created string. * * @param data the wchar_uacter array. * @param offset the initial offset into the value of the * <code>String</code>. * @param count the length of the value of the <code>String</code>. * @return a string representing the sequence of wchar_uacters contained * in the subarray of the wchar_uacter array argument. * @exception IndexOutOfBoundsException if <code>offset</code> is * negative, or <code>count</code> is negative, or * <code>offset+count</code> is larger than * <code>data.length</code>. */ static String* valueOf(const wchar_u* data, int offset, int count); static String* valueOf(const wchar_u* data); static String* valueOf(const char* value); static String* valueOf(const wchar_t* value); /** * Returns the string representation of the <code>bool</code> argument. * * @param b a <code>bool</code>. * @return if the argument is <code>dg_true</code>, a string equal to * <code>"dg_true"</code> is returned; otherwise, a string equal to * <code>"dg_false"</code> is returned. */ static String* valueOf(bool b); /** * Returns the string representation of the <code>wchar_u</code> * argument. * * @param c a <code>wchar_u</code>. * @return a string of length <code>1</code> containing * as its single wchar_uacter the argument <code>c</code>. */ static String* valueOf(wchar_u c); /** * Returns the string representation of the <code>int</code> argument. * <p> * The representation is exactly the one returned by the * <code>Integer.toString</code> method of one argument. * * @param i an <code>int</code>. * @return a string representation of the <code>int</code> argument. * @see java.lang.Integer#toString(int, int) */ static String* valueOf(int i); static String* valueOf(dg_long l); static String* valueOf(dg_float f); static String* valueOf(dg_double d); private: wchar_u* value; int offset; int count; }; // suport compare and hash inline wostream& operator << (wostream& os,const String& str) { String* theStr = const_cast<String*>(&str); Array<byte> bytes = theStr->getBytes(); os << bytes.raw(); return os; } inline wostream& operator << (wostream& os, const String* str) { String* theStr = const_cast<String*>(str); Array<byte> bytes = theStr->getBytes(); os << bytes.raw(); return os; } inline bool operator<(const String& left, const String& right) { String* theStr = const_cast<String*>(&left); String* otherStr = const_cast<String*>(&right); return theStr->compareTo(otherStr) > 0; } inline size_t hash_value(const String& str) { String* theStr = const_cast<String*>(&str); return theStr->hashCode(); } inline const char* operator+(const String& left, const String& right) { String* theStr = const_cast<String*>(&left); String* otherStr = const_cast<String*>(&right); String* retStr = theStr->concat(otherStr); const char* utf8Str = retStr->toUTF8String(); SafeRelease(retStr); return utf8Str; } EndPackage2//(dragon, lang) #endif//String_Lang_Dragon_H
81a244f75a99d35ef9ff6fb96b5ddce896c75e76
5ee2876b3eea7bde7669f2a7a7e9b9fe33a8d0aa
/Test/MultipleChoice.cpp
e919153080347fcd84dbbaa2c2966d65b5a05de8
[]
no_license
TanyaZheleva/OOP
1c6e396c9d4d10ea1cdfbb935461b35fd96e31b9
f44c67e5df69a91a77d35668f0709954546f210d
refs/heads/master
2022-02-12T03:53:00.074713
2019-08-05T10:16:20
2019-08-05T10:16:20
180,985,027
0
0
null
null
null
null
UTF-8
C++
false
false
1,175
cpp
#include "MultipleChoice.h" MultipleChoice::MultipleChoice(std::string _question, std::vector<std::string> _answers, std::vector<std::string>_correctAnswers, double _points) :totalPoints(0), question(_question), answers(_answers), correctAnswers(_correctAnswers), points(_points) {} void MultipleChoice::ask() { std::cout << question << "\n"; unsigned int length = answers.size(); for (unsigned int i = 0; i < length; i++) { std::cout << answers[i] << "\n"; } for (unsigned int i = 0; i < correctAnswers.size(); i++) { std::cin >> answer; std::cout << "\n"; int size = yourAnswers.size(); for (int j = 0; j < size; j++) { if (compare(answer, yourAnswers[j]) == true) { break; } } yourAnswers.push_back(answer); } } double MultipleChoice::grade() { unsigned int length = correctAnswers.size(); for (unsigned int i = 0; i < length; i++) { for (unsigned int j = 0; j < length; j++) { if (compare(yourAnswers[i], correctAnswers[j]) == 1) { totalPoints += points; } else { totalPoints -= points; } } } return totalPoints; } Question * MultipleChoice::clone() { return new MultipleChoice(*this); }
90ad9d8006cb963a44669e4cb1e2a51bd500ac15
ad7e901feaa95124e40a4a716fa6f68c6b6dc801
/src/awa/ServerSession.cpp
30f8cfcd48a4a499393a488e7aba5e7009ce50aa
[ "BSD-3-Clause" ]
permissive
CreatorDev/w5-domesticHeating
77ea005f5f23995c81517d70d71c7bd8b0b990b5
e09e32f52a69df4f37d6bea2af5708299e75c900
refs/heads/master
2021-01-20T03:46:27.267559
2017-05-08T11:02:31
2017-05-08T11:02:31
89,582,594
0
2
null
2017-05-08T11:02:32
2017-04-27T09:51:00
C++
UTF-8
C++
false
false
1,183
cpp
/* * ServerSession.cpp * * Created on: Feb 24, 2017 * Author: krzysztof.kocon */ #include "awa/Common.hpp" #include "awa/Consts.hpp" #include "awa/ServerSession.hpp" using namespace awa; ServerSession::ServerSession() throw (std::bad_alloc) { session = AwaServerSession_New(); if (session == NULL) { throw std::bad_alloc(); } } ServerSession::~ServerSession () { if (session) { try { AwaServerSession_Disconnect(session); AwaServerSession_Free(&session); } catch(const AwaException& e) { //skip } } } ServerSession::operator AwaServerSession*() const { return this->session; } void ServerSession::setIPCAsUDP(std::string address, unsigned short port) { AWA_CHECK(AwaServerSession_SetIPCAsUDP(session, address.c_str(), port)); } void ServerSession::connect() throw (AwaException) { AWA_CHECK(AwaServerSession_Connect(session)); } void ServerSession::process() throw (AwaException) { AWA_CHECK(AwaServerSession_Process(session, AWA_OPERATION_PERFORM_TIMEOUT)); } void ServerSession::dispatchCallbacks() throw (AwaException) { AWA_CHECK(AwaServerSession_DispatchCallbacks(session)); }
9be57e2ce54bec6bc5bc43ee5f1ba853f800753d
5d06542e65a3b017c14c9e3c35afc9a4005750e2
/ZIPSEC/ZIPSEC/libs/deflate/queue.cpp
800469b041db021bbc1f1431c5d2ea9737c4c4cb
[]
no_license
Sauro98/ZIPSEC
e39176ab44b93000073c7e80189b77562a797e6f
40b4a248c2a75cef6873b7ecb1aafb4b08263d8b
refs/heads/master
2021-09-20T18:36:21.683856
2018-08-14T07:12:16
2018-08-14T07:12:16
80,341,697
1
1
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
#include "queue.h" // class constructor Queue::Queue(int n) { array = new node_f*[n]; max_length = n; length = 0; } // class destructor Queue::~Queue() { free(array); } //adds an element void Queue::enqueue(node_f* new_node){ if(length >= max_length){ println("Insertion error: queue is full"); return; } array[length] = new_node; length++; return; } //removes an element node_f* Queue::dequeue(){ if(length == 0){ println("Dequeuing error: queue is empty"); return NULL; } node_f* to_return = array[0]; length = length -1; for(int index = 0;index < length;index++){ array[index] = array[index + 1]; } return to_return; } //return an element without removing it node_f* Queue::peek(){ if(length == 0){ println("Peek error: queue is empty"); return NULL; } return array[0]; } //returns the current array lenght int Queue::get_length(){ return length; } void Queue::print_queue(){ println("QUEUE"); for(int a = 0;a <length;a++){ val_f vf = array[a]->c_f; print("char at "<<a); int c = vf.value; print(" "<<(int)c); print(" "<< c); int f = vf.frequence; println(" frequence "<< f); } println("QUEUE END"); return; }
b25de3838bb971190294c8aec5082ff53e9feb80
2dfb61281a866cee36ad48109838af64114fc031
/Framework-EGC-master/Source/Teme/Tema2/Obiecte/Camera.h
6bd5a280b1ea5d9501ab776d1fe03d69e113e496
[]
no_license
RazvanRotaru/EGC
38498c9985d2d51f6ab66eeeb988d6dee2a29e3a
597e5cbf4e628a379e58e13070adc26d9b043cc6
refs/heads/master
2021-04-06T10:26:32.840324
2018-03-11T10:44:26
2018-03-11T10:44:26
124,691,100
0
0
null
null
null
null
UTF-8
C++
false
false
864
h
#pragma once #include <include/glm.h> #include <include/math.h> class Camera { public: Camera(); Camera(const glm::vec3 &position, const glm::vec3 &center, const glm::vec3 &up); ~Camera(); // Update camera void Set(const glm::vec3 &position, const glm::vec3 &center, const glm::vec3 &up); void MoveForward(float distance); void TranslateForward(float distance); void TranslateUpword(float distance); void TranslateRight(float distance); void RotateFirstPerson_OX(float angle); void RotateFirstPerson_OY(float angle); void RotateFirstPerson_OZ(float angle); void RotateThirdPerson_OX(float angle); void RotateThirdPerson_OY(float angle); void RotateThirdPerson_OZ(float angle); glm::mat4 GetViewMatrix(); glm::vec3 GetTargetPosition(); public: float distanceToTarget; glm::vec3 position; glm::vec3 forward; glm::vec3 right; glm::vec3 up; };
c5ee8c928c64b3007f4f2853db76a1634f754633
75b82680d7733e08dfd230c88e1cba3a2b233293
/ffead-server/src/modules/msghandler/MessageHandler.cpp
0284fd83be0151e4afae1ba01909fbebf2d53262
[]
no_license
clawplach/ffead-cpp
ad7ec4c10581cadbfd883352deb94fb6740fb20c
128b879b018b97b897b3a49d5908e48709fe9621
refs/heads/master
2020-12-27T15:37:32.949949
2013-11-30T17:29:26
2013-11-30T17:29:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,834
cpp
/* Copyright 2009-2012, Sumeet Chhetri 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. */ /* * MessageHandler.cpp * * Created on: Sep 27, 2009 * Author: sumeet */ #include "MessageHandler.h" using namespace std; MessageHandler::MessageHandler(string path) { logger = LoggerFactory::getLogger("MessageHandler"); this->path = path; } MessageHandler* _mess_instance = NULL; Message MessageHandler::readMessageFromQ(string fileName, bool erase) { ifstream file; ifstream::pos_type fileSize; char *fileContents, *remcontents; file.open(fileName.c_str(), ios::in | ios::binary | ios::ate); if (file.is_open()) { fileContents = new char[4]; file.seekg(0, ios::beg); if(!file.read(fileContents, 4)) { _mess_instance->logger << "Failed to readMessageFromQ" << endl; } int len = (int)AMEFResources::charArrayToLong(fileContents, 4); fileContents = new char[len]; file.seekg(4, ios::beg); if(!file.read(fileContents, len)) { _mess_instance->logger << "Failed to readMessageFromQ" << endl; } if(erase) { fileSize = (int)file.tellg() - len - 4; remcontents = new char[fileSize]; file.seekg(4+len, ios::beg); if(!file.read(remcontents, fileSize)) { _mess_instance->logger << "Failed to readMessageFromQ" << endl; } } file.close(); } string f(fileContents); AMEFDecoder dec; AMEFObject* obj = dec.decodeB(f, false, true); Message m; m.setTimestamp(obj->getPackets().at(0)->getValue()); m.setType(obj->getPackets().at(1)->getValue()); m.setPriority(obj->getPackets().at(2)->getValue()); m.setUserId(obj->getPackets().at(3)->getValue()); m.setEncoding(obj->getPackets().at(4)->getValue()); m.setBody(obj->getPackets().at(5)->getValue()); m.getDestination().setName(obj->getPackets().at(5)->getValue()); m.getDestination().setType(obj->getPackets().at(5)->getValue()); delete[] fileContents; if(erase) { ofstream myfile; myfile.open(fileName.c_str(), ios::binary | ios::trunc); myfile << remcontents; myfile.close(); delete[] remcontents; } return m; } void MessageHandler::writeMessageToQ(Message msg,string fileName) { AMEFEncoder enc; AMEFObject ob; ob.addPacket(msg.getTimestamp()); ob.addPacket(msg.getType()); ob.addPacket(msg.getPriority()); ob.addPacket(msg.getUserId()); ob.addPacket(msg.getEncoding()); ob.addPacket(msg.getBody()); ob.addPacket(msg.getDestination().getName()); ob.addPacket(msg.getDestination().getType()); ofstream myfile; myfile.open(fileName.c_str(), ios::binary | ios::app); myfile << enc.encodeB(&ob, true); myfile.close(); } bool MessageHandler::tempUnSubscribe(string subs,string fileName) { string subscribers; ifstream myfile1; myfile1.open(fileName.c_str()); if (myfile1.is_open()) { while(getline(myfile1,subscribers)) { //_mess_instance->logger << subscribers << flush; break; } } myfile1.close(); ofstream myfile; myfile.open(fileName.c_str()); string rep = subs + ":"; StringUtil::replaceFirst(subscribers,rep,""); myfile.write(subscribers.c_str(),subscribers.length()); myfile.close(); if(subscribers.find(":")!=string::npos) return false; else return true; } Message MessageHandler::readMessageFromT(string fileName,string subs) { bool done = tempUnSubscribe(subs,fileName+":SubslistTemp"); Message msg = readMessageFromQ(fileName, done); return msg; } void MessageHandler::writeMessageToT(Message msg,string fileName) { writeMessageToQ(msg ,fileName); } void MessageHandler::subscribe(string subs,string fileName) { ifstream myfile1; myfile1.open(fileName.c_str()); string subscribers; if (myfile1.is_open()) { while(getline(myfile1,subscribers)) { //_mess_instance->logger << subscribers << flush; break; } } myfile1.close(); ofstream myfile; myfile.open(fileName.c_str()); subscribers += (subs + ":"); myfile.write(subscribers.c_str(),subscribers.length()); myfile.close(); fileName += "Temp"; myfile.open(fileName.c_str()); myfile.write(subscribers.c_str(),subscribers.length()); myfile.close(); } void MessageHandler::unSubscribe(string subs,string fileName) { string subscribers; ifstream myfile1; myfile1.open(fileName.c_str()); if (myfile1.is_open()) { while(getline(myfile1,subscribers)) { //_mess_instance->logger << subscribers << flush; break; } } myfile1.close(); ofstream myfile; myfile.open(fileName.c_str()); string rep = subs + ":"; StringUtil::replaceFirst(subscribers,rep,""); myfile.write(subscribers.c_str(),subscribers.length()); myfile.close(); fileName += "Temp"; myfile.open(fileName.c_str()); myfile.write(subscribers.c_str(),subscribers.length()); myfile.close(); } void* MessageHandler::service(void* arg) { int fd = *(int*)arg; char buf[MAXBUFLEN]; string results; //int bytes = recv(fd, buf, sizeof buf, 0); _mess_instance->server.Receive(fd,results,1024); //string temp,results; /*stringstream ss; ss << buf; while(getline(ss,temp)) { _mess_instance->logger << temp << flush; results.append(temp); }*/ results = results.substr(0,results.find_last_of(">")+1); _mess_instance->logger << results << flush; if(results.find("<")!=string::npos && results.find(">")!=string::npos) { string h = "Received Message----"; Cont test; try { Message msg(results); string fileName = _mess_instance->path+msg.getDestination().getName()+":"+msg.getDestination().getType(); if(msg.getDestination().getType()=="Queue") _mess_instance->writeMessageToQ(msg,fileName); else if(msg.getDestination().getType()=="Topic") _mess_instance->writeMessageToT(msg,fileName); } catch(const Exception& e) { _mess_instance->logger << e.getMessage() << flush; } _mess_instance->server.Send(fd,h); //if (send(fd,&h[0] , h.length(), 0) == -1) // _mess_instance->logger << "send failed" << flush; _mess_instance->logger << h << flush; } else if(results.find("GET FROM ")!=string::npos) { Message msg; if(results.find("Queue")!=string::npos) { StringUtil::replaceFirst(results,"GET FROM ",_mess_instance->path); msg = _mess_instance->readMessageFromQ(results, true); } else if(results.find("Topic")!=string::npos) { string subs = results.substr(results.find("-")+1); string te = "-" + subs; StringUtil::replaceFirst(results,te,""); StringUtil::replaceFirst(results,"GET FROM ",_mess_instance->path); msg = _mess_instance->readMessageFromT(results,subs); } string h; if(results.find("Queue")!=string::npos || results.find("Topic")!=string::npos) { h = msg.toXml(); _mess_instance->logger << h << flush; } else h = "Improper Destination"; _mess_instance->server.Send(fd,h); //if (send(fd,&h[0] , h.length(), 0) == -1) // _mess_instance->logger << "send failed" << flush; } else if(results.find("SUBSCRIBE ")!=string::npos) { int len = results.find("TO") - results.find("SUBSCRIBE ") - 11; string subs = results.substr(results.find("SUBSCRIBE ")+10,len); results = results.substr(results.find("TO ")+3); results = (_mess_instance->path+results+":Subslist"); _mess_instance->subscribe(subs,results); string h = "Subscribed"; _mess_instance->server.Send(fd,h); //if (send(fd,&h[0] , h.length(), 0) == -1) // _mess_instance->logger << "send failed" << flush; } else if(results.find("UNSUBSCRIBE ")!=string::npos) { int len = results.find("TO") - results.find("UNSUBSCRIBE ") - 12; string subs = results.substr(results.find("UNSUBSCRIBE ")+11,len); results = results.substr(results.find("TO ")+3); results = (_mess_instance->path+results+":Subslist"); _mess_instance->subscribe(subs,results); string h = "Unsubscribed"; _mess_instance->server.Send(fd,h); //if (send(fd,&h[0] , h.length(), 0) == -1) // _mess_instance->logger << "send failed" << flush; } memset(&buf[0], 0, sizeof(buf)); close(fd); return NULL; } void MessageHandler::init(string path) { if(_mess_instance==NULL) { _mess_instance = new MessageHandler(path); _mess_instance->running = false; } } void MessageHandler::trigger(string port,string path) { init(path); if(_mess_instance->running) return; Server serv(port,false,500,&service,2); _mess_instance->server = serv; _mess_instance->server.start(); _mess_instance->running = true; return; } void MessageHandler::stop() { _mess_instance->server.stop(); }
13b17db02efbebd264fc05a4d964af4bed2803f1
d1ad68da0d7d3a71c2d43d297d6fd3cffbbf75c2
/atcoder/agc01/b.cpp
834b91618f5fa9b1eae14a76bf25ceeb5644b9bf
[]
no_license
hamko/procon
2a0a685b88a69951be7a9217dd32955f9500df57
a822f8089a3063a158d47ea48c54aca89934f855
refs/heads/master
2021-01-17T00:00:10.915298
2020-02-24T06:24:33
2020-02-24T06:24:33
55,990,248
7
1
null
2020-02-24T06:24:34
2016-04-11T16:49:50
C++
UTF-8
C++
false
false
3,257
cpp
#include <bits/stdc++.h> using namespace std; #ifdef _WIN32 #define scanfll(x) scanf("%I64d", x) #define printfll(x) printf("%I64d", x) #else #define scanfll(x) scanf("%lld", x) #define printfll(x) printf("%lld", x) #endif #define rep(i,n) for(long long i = 0; i < (long long)(n); i++) #define repi(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++) #define pb push_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define mt make_tuple #define mp make_pair template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); } template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); } using ll = long long; using ld = long double; using vll = vector<ll>; using vvll = vector<vll>; using vld = vector<ld>; using vi = vector<int>; using vvi = vector<vi>; vll conv(vi& v) { vll r(v.size()); rep(i, v.size()) r[i] = v[i]; return r; } using P = pair<ll, ll>; template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) { o << "(" << v.first << ", " << v.second << ")"; return o; } template<size_t...> struct seq{}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...>{}; template<class Ch, class Tr, class Tuple, size_t... Is> void print_tuple(basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){ using s = int[]; (void)s{0, (void(os << (Is == 0? "" : ", ") << get<Is>(t)), 0)...}; } template<class Ch, class Tr, class... Args> auto operator<<(basic_ostream<Ch, Tr>& os, tuple<Args...> const& t) -> basic_ostream<Ch, Tr>& { os << "("; print_tuple(os, t, gen_seq<sizeof...(Args)>()); return os << ")"; } ostream &operator<<(ostream &o, const vvll &v) { rep(i, v.size()) { rep(j, v[i].size()) o << v[i][j] << " "; cout << endl; } return o; } template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]"; return o; } template <typename T> ostream &operator<<(ostream &o, const set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; } template <typename T, typename U> ostream &operator<<(ostream &o, const map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; } template <typename T, typename U> ostream &operator<<(ostream &o, const unordered_map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it; o << "]"; return o; } void printbits(ll mask, ll n) { rep(i, n) { cout << !!(mask & (1ll << i)); } cout << endl; } #define ldout fixed << setprecision(40) static const double EPS = 1e-14; static const long long INF = 1e18; static const long long mo = 1e9+7; ll f(ll x, ll y) { ll tmp; if (x % y == 0ll) tmp = 2ll * x; else { tmp = (1ll + x / y * 2ll) * y + x % y; // cout << x << " " << y << " " << tmp<< endl; tmp += f(y - x % y, x % y); } return tmp; } int main(void) { cin.tie(0); ios::sync_with_stdio(false); ll n, x; cin >> n >> x; cout << f(x, n-x) + x << endl; return 0; }
e69cf3c4ee43178f8e4cccf0c8eb6b8f57f9848b
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/247/825/CWE78_OS_Command_Injection__wchar_t_file_execl_83_bad.cpp
378b41e19c9555961a3ecc73ba716af5d2595e0e
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
2,152
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_file_execl_83_bad.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-83_bad.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: file Read input from a file * GoodSource: Fixed string * Sinks: execl * BadSink : execute command with wexecl * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE78_OS_Command_Injection__wchar_t_file_execl_83.h" #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #include <process.h> #define EXECL _wexecl #else /* NOT _WIN32 */ #define EXECL execl #endif namespace CWE78_OS_Command_Injection__wchar_t_file_execl_83 { CWE78_OS_Command_Injection__wchar_t_file_execl_83_bad::CWE78_OS_Command_Injection__wchar_t_file_execl_83_bad(wchar_t * dataCopy) { data = dataCopy; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (100-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } } CWE78_OS_Command_Injection__wchar_t_file_execl_83_bad::~CWE78_OS_Command_Injection__wchar_t_file_execl_83_bad() { /* wexecl - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); } } #endif /* OMITBAD */
c52f124985779dbf25eadbb61642b84145365527
b3e546865bdd68b58df1e02da03d6c71d4523636
/Graphics/GraphicsTools/include/TextureUploaderD3D12.h
c2ca81e5f293eb1b6c6815a0c698f6079010a54c
[ "Apache-2.0" ]
permissive
kvark/DiligentCore
2275c5de829224f40920239cd8d2999f040434ae
66c4818e8dc7b2a71a9d05456a77e811a1a30697
refs/heads/master
2020-05-01T07:52:17.985342
2019-03-24T00:16:42
2019-03-24T00:16:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,096
h
/* Copyright 2015-2019 Egor Yusov * * 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 * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once #include "TextureUploaderBase.h" namespace Diligent { class TextureUploaderD3D12 : public TextureUploaderBase { public: TextureUploaderD3D12(IReferenceCounters *pRefCounters, IRenderDevice *pDevice, const TextureUploaderDesc Desc); ~TextureUploaderD3D12(); virtual void RenderThreadUpdate(IDeviceContext *pContext)override final; virtual void AllocateUploadBuffer(const UploadBufferDesc& Desc, bool IsRenderThread, IUploadBuffer **ppBuffer)override final; virtual void ScheduleGPUCopy(ITexture *pDstTexture, Uint32 ArraySlice, Uint32 MipLevel, IUploadBuffer *pUploadBuffer)override final; virtual void RecycleBuffer(IUploadBuffer *pUploadBuffer)override final; private: struct InternalData; std::unique_ptr<InternalData> m_pInternalData; }; }
190ec10626dcccdf2b9ed5857f06227eda2e3150
fb05d9ab9ee145ace279d8241797ba2539ee5f57
/Marlin2.x/pandapi/src/core/utility.cpp
bd0534f8e7b744b7aaf0e61274235f37faf3a30e
[]
no_license
markniu/PandaPi
67be05812a10225d7acdb3f8af368aadb1270b2f
b7c8477b470601751def28c50cde0f7a5cccc5be
refs/heads/master
2022-10-13T13:20:43.259105
2022-10-03T14:43:19
2022-10-03T14:43:19
203,921,005
217
42
null
null
null
null
UTF-8
C++
false
false
7,363
cpp
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "utility.h" #include "../MarlinCore.h" #include "../module/temperature.h" ////////PANDAPI #include <stdlib.h> #include <stdio.h> #include <time.h> int linux_random(int x,int y) { srand( (unsigned)time( NULL ) ); return rand()%(y-x)+x; } ///// PANDAPI char * dtostrf(double number, signed char width, unsigned char prec, char *s) { if(isnan(number)) { strcpy(s, "nan"); return s; } if(isinf(number)) { strcpy(s, "inf"); return s; } if(number > 4294967040.0 || number < -4294967040.0) { strcpy(s, "ovf"); return s; } char* out = s; // Handle negative numbers if(number < 0.0) { *out = '-'; ++out; number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for(uint8_t i = 0; i < prec; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long) number; double remainder = number - (double) int_part; out += sprintf(out, "%d", int_part); // Print the decimal point, but only if there are digits beyond if(prec > 0) { *out = '.'; ++out; } while(prec-- > 0) { remainder *= 10.0; } sprintf(out, "%d", (int) remainder); return s; } void safe_delay(millis_t ms) { while (ms > 50) { ms -= 50; delay(50); thermalManager.manage_heater(); } delay(ms); thermalManager.manage_heater(); // This keeps us safe if too many small safe_delay() calls are made } #if ENABLED(MARLIN_DEV_MODE) void early_safe_delay(millis_t ms) { while (ms > 50) { ms -= 50; delay(50); watchdog_refresh(); } delay(ms); watchdog_refresh(); } #endif // A delay to provide brittle hosts time to receive bytes #if ENABLED(SERIAL_OVERRUN_PROTECTION) #include "../gcode/gcode.h" // for set_autoreport_paused void serial_delay(const millis_t ms) { const bool was = gcode.set_autoreport_paused(true); safe_delay(ms); gcode.set_autoreport_paused(was); } #endif #if ENABLED(DEBUG_LEVELING_FEATURE) #include "../module/probe.h" #include "../module/motion.h" #include "../module/stepper.h" #include "../libs/numtostr.h" #include "../feature/bedlevel/bedlevel.h" void log_machine_info() { SERIAL_ECHOLNPGM("Machine Type: " TERN_(DELTA, "Delta") TERN_(IS_SCARA, "SCARA") TERN_(IS_CORE, "Core") TERN_(MARKFORGED_XY, "MarkForged") TERN_(IS_CARTESIAN, "Cartesian") ); SERIAL_ECHOLNPGM("Probe: " TERN_(PROBE_MANUALLY, "PROBE_MANUALLY") TERN_(NOZZLE_AS_PROBE, "NOZZLE_AS_PROBE") TERN_(FIX_MOUNTED_PROBE, "FIX_MOUNTED_PROBE") TERN_(HAS_Z_SERVO_PROBE, TERN(BLTOUCH, "BLTOUCH", "SERVO PROBE")) TERN_(TOUCH_MI_PROBE, "TOUCH_MI_PROBE") TERN_(Z_PROBE_SLED, "Z_PROBE_SLED") TERN_(Z_PROBE_ALLEN_KEY, "Z_PROBE_ALLEN_KEY") TERN_(SOLENOID_PROBE, "SOLENOID_PROBE") TERN(PROBE_SELECTED, "", "NONE") ); #if HAS_BED_PROBE #if !HAS_PROBE_XY_OFFSET SERIAL_ECHOPAIR("Probe Offset X0 Y0 Z", probe.offset.z, " ("); #else SERIAL_ECHOPAIR_P(PSTR("Probe Offset X"), probe.offset_xy.x, SP_Y_STR, probe.offset_xy.y, SP_Z_STR, probe.offset.z); if (probe.offset_xy.x > 0) SERIAL_ECHOPGM(" (Right"); else if (probe.offset_xy.x < 0) SERIAL_ECHOPGM(" (Left"); else if (probe.offset_xy.y != 0) SERIAL_ECHOPGM(" (Middle"); else SERIAL_ECHOPGM(" (Aligned With"); if (probe.offset_xy.y > 0) SERIAL_ECHOPGM_P(ENABLED(IS_SCARA) ? PSTR("-Distal") : PSTR("-Back")); else if (probe.offset_xy.y < 0) SERIAL_ECHOPGM_P(ENABLED(IS_SCARA) ? PSTR("-Proximal") : PSTR("-Front")); else if (probe.offset_xy.x != 0) SERIAL_ECHOPGM("-Center"); SERIAL_ECHOPGM(" & "); #endif SERIAL_ECHOPGM_P(probe.offset.z < 0 ? PSTR("Below") : probe.offset.z > 0 ? PSTR("Above") : PSTR("Same Z as")); SERIAL_ECHOLNPGM(" Nozzle)"); #endif #if HAS_ABL_OR_UBL SERIAL_ECHOPGM("Auto Bed Leveling: " TERN_(AUTO_BED_LEVELING_LINEAR, "LINEAR") TERN_(AUTO_BED_LEVELING_BILINEAR, "BILINEAR") TERN_(AUTO_BED_LEVELING_3POINT, "3POINT") TERN_(AUTO_BED_LEVELING_UBL, "UBL") ); if (planner.leveling_active) { SERIAL_ECHOLNPGM(" (enabled)"); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height); #endif #if ABL_PLANAR SERIAL_ECHOPGM("ABL Adjustment X"); LOOP_XYZ(a) { const float v = planner.get_axis_position_mm(AxisEnum(a)) - current_position[a]; SERIAL_CHAR(' ', XYZ_CHAR(a)); if (v > 0) SERIAL_CHAR('+'); SERIAL_DECIMAL(v); } #else #if ENABLED(AUTO_BED_LEVELING_UBL) SERIAL_ECHOPGM("UBL Adjustment Z"); const float rz = ubl.get_z_correction(current_position); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) SERIAL_ECHOPGM("ABL Adjustment Z"); const float rz = bilinear_z_offset(current_position); #endif SERIAL_ECHO(ftostr43sign(rz, '+')); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) { SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position.z), '+')); SERIAL_CHAR(')'); } #endif #endif } else SERIAL_ECHOLNPGM(" (disabled)"); SERIAL_EOL(); #elif ENABLED(MESH_BED_LEVELING) SERIAL_ECHOPGM("Mesh Bed Leveling"); if (planner.leveling_active) { SERIAL_ECHOLNPGM(" (enabled)"); SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position), '+')); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) { SERIAL_ECHOPAIR(" (", ftostr43sign( mbl.get_z(current_position, planner.fade_scaling_factor_for_z(current_position.z)), '+' )); SERIAL_CHAR(')'); } #endif } else SERIAL_ECHOPGM(" (disabled)"); SERIAL_EOL(); #endif // MESH_BED_LEVELING } #endif // DEBUG_LEVELING_FEATURE
278780ca99f5b1d951601c7755ead9ce95edaa0b
80a327693fcbc392af9bca78fe0b1646002f3b10
/OverlordProject/CourseObjects/Project/ResourceBar.h
b86596db3cd2ef6f6e0b76544cfb2c18602f3cf0
[]
no_license
Kwintenvdb/DirectX-Turret-Game
83d40b152ed7297ceeb14caa3672e844ad1388b2
d5cdb49b32fbda34a09e76cd12bcc06a3f05a5c7
refs/heads/master
2020-06-04T11:16:40.974589
2014-11-06T11:10:39
2014-11-06T11:10:39
25,698,189
1
0
null
null
null
null
UTF-8
C++
false
false
490
h
#pragma once #include "Scenegraph/GameObject.h" class ResourceBar : public GameObject { public: ResourceBar(wstring texture, wstring text, float yOffset); ~ResourceBar(void); virtual void Initialize(const GameContext& gameContext); virtual void Update(const GameContext& gameContext); virtual void Draw(const GameContext& gameContext); void SetResource(float amount, float max); private: GameObject* m_BarObj, *m_TextObj; wstring m_TextureFile, m_TextFile; float m_YOffset; };
cc2b88277d53b8e8381e7a3bd8a0472687d75c54
39d246cb9cc3048dd9b1fea8cc870ea8352c1b15
/src/include/Chip8259A.h
37f41114c6b0b9599f88bd543fe3731afaf23860
[]
no_license
XiaoYuhao/UNIX-V6
f200a03a02e2506c4a33be8af626f7a6a1243554
316c69c490d2a0eeec462a9307b248d4f3e96184
refs/heads/master
2020-05-07T13:57:14.468812
2019-04-27T02:31:20
2019-04-27T02:31:20
180,568,387
3
0
null
null
null
null
GB18030
C++
false
false
2,554
h
#ifndef CHIP8259A_H #define CHIP8259A_H /* * 定义了对8259A可编中断控制芯片(PIC)的操作。 * * 8259A芯片帮助CPU代为管理外设提出的中断请求, * 选择优先级最高的中断,转达给CPU来响应中断。 */ class Chip8259A { public: /* 初始化系统中的主、从两片8259A中断控制芯片 */ static void Init(); /* 开启中断函数。 * * 功能:通过设置8259A的中断屏蔽寄存器,将相应 * 中断屏蔽位清0,允许来自特定外设的中断。 * * 输入参数:特定外设的IRQ号。如下面定义的: IRQ_TIMER = 0;等 */ static void IrqEnable(unsigned int irq); /* 屏蔽中断函数。 和IrqEnable(unsigned int irq)执行反向功能。 * * 功能:通过设置8259A的中断屏蔽寄存器,将相应 * 中断屏蔽位置1,屏蔽来自特定外设的中断。 * * 输入参数:特定外设的IRQ号。如下面定义的: IRQ_TIMER = 0; 等 */ static void IrqDisable(unsigned int irq); public: /* 系统中有2片8259A芯片,每一片在IO地址空间中占用2个端口地址 */ /* 主片(Master)的IO端口地址 */ static const unsigned short MASTER_IO_PORT_1 = 0x20; static const unsigned short MASTER_IO_PORT_2 = 0x21; /* 从片(Slave)的IO端口地址 */ static const unsigned short SLAVE_IO_PORT_1 = 0xA0; static const unsigned short SLAVE_IO_PORT_2 = 0xA1; /* 主片各引脚对应起始中断号 */ static const unsigned char MASTER_IRQ_START = 0x20; /* 从片各引脚对应起始中断号,中断号范围起始0x28 */ static const unsigned char SLAVE_IRQ_START = MASTER_IRQ_START + 8; /* * 主片(IR0~IR7)连接到的外设对应的中断请求引脚 (这里只定义内核中 * 用到的外设)后面可以有选择性地 启用/禁用来自于该引脚的中断。 */ static const unsigned int IRQ_TIMER = 0; /* 时钟中断(IRQ0)发送到IR0引脚 */ static const unsigned int IRQ_KBD = 1; /* 键盘中断(IRQ1)发送到IR1引脚 */ static const unsigned int IRQ_SLAVE = 2; /* 级联模式下,从片发出的中断(Slave的INT引脚),发送到主片的IR2 */ /* 从片(IR0~IR7)连接到的外设对应的中断请求引脚,这里只用到的外设是硬盘 */ static const unsigned int IRQ_IDE = 14; /* 硬盘中断(IRQ14)发送到从片IR6引脚 */ /* 另外需要定义的一些常量 */ static const unsigned char MASK_ALL = 0xFF; /* 屏蔽状态字, 屏蔽所有引脚(IR0~IR7)上的中断请求 */ static const unsigned char EOI = 0x20; /* End Of Interrupt */ }; #endif
234058550cc814db662b18c0c56c58781bb91abd
d319f950fdb742b483fdde9d4038daa5dfeb013e
/project5/old_versions/main.cpp
4e146301b4cb2cbeef4bad1f22c59372a17dc748
[]
no_license
benHobbs/cs165
98803de953735538dda001e61e5e7f6f5c713bbf
cd9bd59f1b030085d384f0892d0e82f9d1caaa03
refs/heads/master
2021-01-15T16:57:39.337137
2014-12-07T08:05:24
2014-12-07T08:05:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,720
cpp
#include <iostream> #include <vector> /****************************************************************************** * Rules: * 1. Any live cell with < 2 live neighbors dies * 2. Any live cell with 2 or 3 live neighbors lives on * 3. Any live cell with > 3 live neighbors dies * 4. Any dead cell with exactly 3 live neighbors becomes a live cell ******************************************************************************/ class GameOfLife { public: GameOfLife(int iColumns, int iRows){ columns = iColumns, rows = iRows; }; void setLiveDeadChars(char cLive, char cDead){ live = cLive, dead = cDead; }; void initVectors(); void setInitParams(); void setInitParams1(); void print(std::vector<std::vector<char>> v); void printV(){ print(v); }; void printNV(){ print(nv); }; void createNextIteration(); //builds next iteration, based on this iteration int getNeighbors(int c, int r); //returns the number of living neighbors void copyVector(){ v = nv; }; private: int rows, columns; char live, dead; std::vector<std::vector<char>> v, nv; //current, next generation }; void GameOfLife::initVectors(){ for (int i = 0 ; i < columns ; i++ ){ v.push_back( std::vector<char>(rows,dead)); nv.push_back( std::vector<char>(rows,dead)); } } void GameOfLife::setInitParams(){ v.at(5).at(5) = live; //glider v.at(6).at(6) = live; v.at(6).at(7) = live; v.at(7).at(5) = live; v.at(7).at(6) = live; //setInitParams1(); } void GameOfLife::print(std::vector<std::vector<char>> v){ for (int row = 0 ; row < rows ; row++){ for (int column = 0 ; column < columns ; column++){ std::cout << v.at(column).at(row); } std::cout << std::endl; } } void GameOfLife::createNextIteration(){ for (int row = 0 ; row < rows ; row++){ for (int column = 0 ; column < columns ; column++){ int neighbors = getNeighbors(column,row); //get number of neighbors char position = v.at(column).at(row); if (position == live){ //rules 1-3 if (neighbors < 2){ //rule 1 nv.at(column).at(row) = dead; } else if (neighbors > 1 && neighbors < 4){ //rule 2 nv.at(column).at(row) = live; } else if (neighbors > 3){ //rule 3 nv.at(column).at(row) = dead; } } //end if else if (position == dead && neighbors == 3){ //rule 4 nv.at(column).at(row) = live; } //end else if | conditional } //end for loop column } //end for loop row } int GameOfLife::getNeighbors(int c, int r){ //returns the number of living neighbors int negC = (c+(columns-1))%columns, posC = (c+1)%columns; int negR = (r+(rows-1))%rows, posR = (r+1)%rows, sum = 0; sum += (v.at(negC).at(negR) == live) ? 1 : 0; sum += (v.at(negC).at(r) == live) ? 1 : 0; sum += (v.at(negC).at(posR) == live) ? 1 : 0; sum += (v.at(c).at(negR) == live) ? 1 : 0; sum += (v.at(c).at(posR) == live) ? 1 : 0; sum += (v.at(posC).at(negR) == live) ? 1 : 0; sum += (v.at(posC).at(r) == live) ? 1 : 0; sum += (v.at(posC).at(posR) == live) ? 1 : 0; return sum; } void GameOfLife::setInitParams1(){ /* v.at(0).at(0) = live; //block v.at(0).at(1) = live; v.at(1).at(0) = live; v.at(1).at(1) = live; v.at(7).at(3) = live; //blinker v.at(7).at(4) = live; v.at(7).at(5) = live; v.at(13).at(3) = live; //beacon v.at(13).at(4) = live; v.at(14).at(3) = live; v.at(14).at(4) = live; v.at(15).at(5) = live; v.at(15).at(6) = live; v.at(16).at(5) = live; v.at(16).at(6) = live; v.at(0).at(4) = live; //block v.at(0).at(5) = live; v.at(19).at(4) = live; v.at(19).at(5) = live; v.at(19).at(9) = live; // v.at(19).at(8) = live; v.at(18).at(9) = live; v.at(18).at(8) = live; */ v.at(5).at(5) = live; //glider v.at(6).at(6) = live; v.at(6).at(7) = live; v.at(7).at(5) = live; v.at(7).at(6) = live; } int main(){ GameOfLife game(40,20); game.setLiveDeadChars('X',' '); //set symbols game.initVectors(); game.setInitParams(); for (int i = 0 ; i < 20 ; i++){ game.printV(); game.createNextIteration(); game.copyVector(); std::cout << "\n\n--------------------\n\n"; } }
2f7a96bbceb6aae6a05dd69434e4893e4d3d5ae0
ef35cc4d6d5ceb174306db5fb4264eab2cc4de0e
/client/src/xmlfunc.hpp
368611ca89ccf14310db86869d13d8ca6191addf
[]
no_license
acgl17/mir2x
25bee6c6452e7f1d02b6026d27866bebf0e05fe7
91a4610af36ad543b0c4cc829b108816a91e6bb9
refs/heads/master
2021-03-25T14:39:33.750844
2020-03-12T19:15:45
2020-03-12T19:15:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,545
hpp
/* * ===================================================================================== * * Filename: xmlfunc.hpp * Created: 12/11/2018 04:01:50 * Description: * * Version: 1.0 * Revision: none * Compiler: gcc * * Author: ANHONG * Email: [email protected] * Organization: USTC * * ===================================================================================== */ #pragma once #include <vector> #include <stdexcept> #include <tinyxml2.h> #include "strfunc.hpp" namespace XMLFunc { bool CheckTextLeaf (const tinyxml2::XMLNode *); bool CheckEmojiLeaf(const tinyxml2::XMLNode *); bool CheckImageLeaf(const tinyxml2::XMLNode *); bool CheckValidLeaf(const tinyxml2::XMLNode *); const char *FindAttribute(const tinyxml2::XMLNode *, const char *, bool); // 1. current input should be a xml leaf // 2. return next xml node if exists, or nullptr tinyxml2::XMLNode *GetNextLeaf(tinyxml2::XMLNode *); tinyxml2::XMLNode *GetNodeFirstLeaf(tinyxml2::XMLNode *); tinyxml2::XMLNode *GetTreeFirstLeaf(tinyxml2::XMLNode *); tinyxml2::XMLNode *GetNodeLastLeaf(tinyxml2::XMLNode *); tinyxml2::XMLNode *GetTreeLastLeaf(tinyxml2::XMLNode *); bool ValidTagName(const std::string &); bool ValidAttributeName(const std::string &); std::string BuildXMLString( const std::string &, // tag name const std::string &, // content const std::vector<std::pair<std::string, std::string>> &); }
f32c27191eb88230cd69f9288bb68e6f05af9109
b591fbbd37b9b5e81d8f308f61d607fe7b145ed7
/include/RE/T/TogglePOVHandler.h
5b4c684388b1337ff3a3c4512a806a3df2084893
[ "MIT" ]
permissive
aquilae/CommonLibSSE
f6a1d321b16f2eb1e296f1154d697bd4bed549b6
b8e6a72875b22c91dd125202dfc6a54f91cda597
refs/heads/master
2023-02-02T16:45:00.368879
2020-12-15T03:58:22
2020-12-15T03:58:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
629
h
#pragma once #include "RE/H/HeldStateHandler.h" namespace RE { struct TogglePOVHandler : public HeldStateHandler { public: inline static constexpr auto RTTI = RTTI_TogglePOVHandler; virtual ~TogglePOVHandler(); // 00 // override (PlayerInputHandler) virtual bool CanProcess(InputEvent* a_event) override; // 01 virtual void ProcessButton(ButtonEvent* a_event, PlayerControlsData* a_data) override; // 04 // members bool pressRegistered; // 18 std::uint8_t pad19; // 19 std::uint16_t pad1A; // 1A std::uint32_t pad1C; // 1C }; static_assert(sizeof(TogglePOVHandler) == 0x20); }
2a4ef699902c6c48efdbec0a0f2a2a25ec113cd9
2c1b1c93a963c10fc1e301d8d765df0fde183fc3
/tdi/imabin.h
b114a492d3bada747a227ac7227435cef0c95168
[]
no_license
zijian-rayan/Image-processing
f6aaf98fd36dcf100aa6a22abac52fabf955fdeb
e9d703ba0457972cbafdddc07f099685db1d16d5
refs/heads/master
2020-07-25T04:09:07.192856
2019-12-21T20:34:58
2019-12-21T20:34:58
208,160,069
0
0
null
null
null
null
ISO-8859-1
C++
false
false
6,264
h
#ifndef _IMABIN_H #define _IMABIN_H #include <iostream> #include <iomanip> #include <fstream> using namespace std; //#include <stdlib.h> #include <math.h> //#include "constantes.h" #include "def.h" #include "fonctions.h" #include "pixel.h" #include "liste_pixels.h" #include "imasites.h" #include "imadata.h" class imabin : public imasites { bool *Tima; void init_zero() { // attention pas de désallocation mémoire car utilisée dans constructeurs Tima=NULL; Tima=new bool[nbpix]; for (long int i=0; i<nbpix; i++) { Tima[i]=0; Tsites[i]=&(Tima[i]); } } void re_init_zero(const int nl,const int nc) { // avec désallocation mémoire if (nblig!=nl || nbcol!=nc) { nblig=nl; nbcol=nc; if (Tsites!=NULL) {delete[] Tsites; Tsites=NULL;} Tsites=new void*[nbpix=(long int)nl*(long int)nc]; for (long int i=0; i<nbpix; i++) Tsites[i]=NULL; } if (Tima!=NULL) delete[] Tima; init_zero(); } public: imabin(const int nl=1, const int nc=1) : imasites(nl,nc) { init_zero(); } ~imabin() { if (Tima!=NULL) {delete[] Tima; Tima=NULL;} } imabin(const imabin &ima) : imasites(ima) { bool *adval; init_zero(); for (long int i=0; i<nbpix; i++) { adval=(bool*)ima.Tsites[i]; Tima[i]=*adval; } } imabin(const imadata<float> &ima, const float seuil, const int k=0) : imasites(ima) { int i,j; long int n; init_zero(); for (i=0; i<nblig; i++) { n=i*nbcol; for (j=0; j<nbcol; j++) { if (ima.valpix(i,j,k)>=seuil && n>=0 && n<nbpix) Tima[n]=1; n++; } } } imabin(const imadata<int> &ima, const float seuil, const int k=0) : imasites(ima) { int i,j; long int n; init_zero(); for (i=0; i<nblig; i++) { n=i*nbcol; for (j=0; j<nbcol; j++) { if (ima.valpix(i,j,k)>=seuil && n>=0 && n<nbpix) Tima[n]=1; n++; } } } imabin(const imadata<BYTE> &ima, const float seuil, const int k=0) : imasites(ima) { int i,j; long int n; init_zero(); for (i=0; i<nblig; i++) { n=i*nbcol; for (j=0; j<nbcol; j++) { if (ima.valpix(i,j,k)>=seuil && n>=0 && n<nbpix) Tima[n]=1; n++; } } } imabin& operator=(const imabin &ima) { if (this != &ima) { imasites *ad1, *ad2; ad1=this; ad2=(imasites*) &ima; *ad1=*ad2; if (Tima!=NULL) delete[] Tima; Tima=new bool[nbpix]; bool *adval; for (long int i=0; i<nbpix; i++) { adval=(bool*)ima.Tsites[i]; Tima[i]=*adval; Tsites[i]=&(Tima[i]); } } return *this; } bool& operator () (int i, int j) const { if (i<0 || i>=nblig || j<0 || j>=nbcol) { cout<<" debordement d''indice dans ("<<i<<","<<j<<")\n"; if (i<0) i=0; if (i>=nblig) i=nblig-1; if (j<0) j=0; if (j>=nbcol) j=nbcol-1; } bool *adval=(bool*)Tsites[i*nbcol+j]; return *adval; } bool& operator () (int i, int j) { if (i<0 || i>=nblig || j<0 || j>=nbcol) { cout<<" debordement d''indice dans ("<<i<<","<<j<<")\n"; if (i<0) i=0; if (i>=nblig) i=nblig-1; if (j<0) j=0; if (j>=nbcol) j=nbcol-1; } bool *adval=(bool*)Tsites[i*nbcol+j]; return *adval; } operator imadata<float>(); operator imadata<BYTE>(); imadata<BYTE> imaunsignedchar (const bool=1); void affiche (const int=1) const; imabin operator+ (const imabin &); imabin operator- (const imabin &); imabin operator&& (const imabin &); imabin operator|| (const imabin &); void mise_a_zero (); void mise_a_un (); imabin negatif (); imabin ajoutbords (); imabin retirebords (); bool operator== (const imabin &); bool operator!= (const imabin &); float norm () const; void sauve_Ima (char *nomfich="imagesauvee.dat", bool=1) const; imadata<int> composantes_connexes (int &, int=4, bool=0); imadata<int> boxes_rectangulaires (int &, bool=1); /* morphologie mathematique binaire */ imadata<float> Tr_dist (const imabin &, int=1) const; imadata<float> Tr_dist (int=1) const; imabin dilate (eltstruct); imabin dilate (eltstruct, int); imabin dilate (eltstruct, eltstruct); imabin dilate (const imadata<float> &, float=1.); imabin dilate (int=3, float=1.); imabin erode (eltstruct); imabin erode (eltstruct, int); imabin erode (eltstruct, eltstruct); imabin erode (const imadata<float> &, float=1.); imabin erode (int=3, float=1.); imabin ouverture (eltstruct); imabin ouverture (eltstruct, int); imabin fermeture (eltstruct); imabin fermeture (eltstruct, int); imabin tophat (eltstruct); imabin tophat_c (eltstruct); imabin reconstruction_geodesique (imabin &, int=4); imabin reconstruction_geodesique (int, int, int=4); imabin bouche_trou (int=4); imabin bouche_trou2 (int=4); imadata<int> CompoConnexes_MM (int &, int=4, bool=1); // imabin erode_ultime (eltstruct); // a ecrire et a valider imabin erode_ultime (const imadata<float> &, int=8); imabin erode_ultime (int=3); imabin transfo_tout_ou_rien (eltstruct, eltstruct, int=1) const; imabin zones_influence_geodesique(const imabin &, bool &, int=8); imadata<BYTE> detect_coin (int=1, bool=1, bool=0); imabin enveloppe_convexe (); imabin squelette (int=8, BYTE=1, bool=1); imabin squelette (imabin&, int=8, bool=1); imabin elagage (int=1, bool=0); imabin elagage_saufextrem (int=1, int=8); imabin detect_extremites_sq (); // s'applique à une image de squelette imadata<BYTE> calc_orient_sq (bool=0, bool=1); // s'applique à une image de squelette /* analyse d'image binaire */ imadata<float> transformee_Fourier(); imadata<float> transformee_Fourier_Inv(); imadata<int> transformee_Hough_1pt (bool=1); // spécifique pour espace cumulatif associé à calcul NFA imadata<int> transformee_Hough(); void reconst_hough_transform (imadata<float> &, int, int); void reconst_hough_transform (imadata<float> &, int, int, imabin); imadata<int> norme_transformee_Hough(int, int, int=1, int=1); imadata<int> norme_transformee_Hough (const imabin &); imadata<int> hough_transform(); // imadata<int> analyse_hough (imadata<int>); imadata<int> transformee_Hough_cercles(const int=25); imadata<int> transformee_Hough_squares(const int=25); imadata<float> coocurrence (int, int, int=1, unsigned short int=0); /* trace formes geometriques basiques */ void trace_line (float, float, float=0.f, float=2*PI, bool=0); void trace_line (float, float, int, int, int, int); void trace_line (int, int, int, int); }; #endif
a8e27d497ac202bd11a9c5d30c59445c4ac217de
2513fce0d1fefe295e7acc08103c627b78ddf2aa
/1/Zadanie2.cpp
0c87e19d94b9109340ba23d308559fbd4796c1b8
[]
no_license
woekweoek/gk
7c4cd6e5fa0234ffc22c8346a6fe32e9e017a55a
9783027b9adeb8389ee282802ba9418a6a0cade1
refs/heads/master
2021-01-21T21:32:42.927103
2016-06-11T06:55:07
2016-06-11T06:55:07
54,385,314
0
0
null
null
null
null
ISO-8859-2
C++
false
false
1,179
cpp
// Zadanie2.cpp : Defines the entry point for the console application. // #include "stdafx.h" #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif void RenderScene(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 1.0f, 0.0f); glBegin(GL_POLYGON); glVertex3f(0.0f, 25.0f, 0.0f); glVertex3f(-25.0f, -25.0f, 0.0f); glVertex3f(25.0f, -25.0f, 0.0f); glEnd(); glFlush(); } void SetupRC(void) { glClearColor(0.6f, 0.4f, 0.12f, 1.0f); } void ChangeSize(int w, int h) { GLfloat aspectRatio; if (h == 0) h = 1; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); aspectRatio = (GLfloat)w / (GLfloat)h; if (w <= h) glOrtho(-100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio, 1.0, -1.0); else glOrtho(-100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0, 1.0, -1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(800, 600); glutCreateWindow("Mój pierwszy program w GLUT"); glutDisplayFunc(RenderScene); glutReshapeFunc(ChangeSize); SetupRC(); glutMainLoop(); return 0; }
8b089878a34c8e12910e1208e8da11ae86ec65d5
a60a3f718cbf8828ed510918f667332f14f49433
/web/wasm/math_bindings.cpp
6593dc0cfe8dc401bb4f749c7e54156e1ed79caf
[]
no_license
Christopher-Bradshaw/learning
c2c8c453c02bba4584787cc50320d111b16cdb77
34c58a6313090c934eab3ff07d6973ddccae89ee
refs/heads/master
2022-08-24T08:23:21.616268
2022-08-04T05:55:46
2022-08-04T05:55:46
156,060,869
0
0
null
2019-09-10T21:17:12
2018-11-04T07:56:15
Jupyter Notebook
UTF-8
C++
false
false
166
cpp
#include <emscripten/bind.h> using namespace emscripten; int add(int a, int b) { return a + b; } EMSCRIPTEN_BINDINGS(my_module) { function("add", &add); }
92bf55036bfd4be66e7df9e9f8b38bde7412041f
161929c4458ca8a7d1021b0fc815433d4c7722e7
/cocos2d/cocos/2d/CCConfiguration.cpp
7adcea90db7c6b0dfeffa89143a8129fe43f037f
[]
no_license
darkcl/CCBeat
45af2142713c91474e595560811a9030d741771d
d9ede17a6eec2e891be06d4fd93b03e28ad13261
refs/heads/master
2021-01-20T06:57:26.706743
2014-04-28T13:24:16
2014-04-28T13:24:16
18,762,083
2
0
null
null
null
null
UTF-8
C++
false
false
8,821
cpp
/**************************************************************************** Copyright (c) 2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCConfiguration.h" #include <string.h> #include "ccMacros.h" #include "ccConfig.h" #include "CCDictionary.h" #include "CCInteger.h" #include "CCBool.h" #include "platform/CCFileUtils.h" using namespace std; NS_CC_BEGIN extern const char* cocos2dVersion(); Configuration* Configuration::s_sharedConfiguration = nullptr; Configuration::Configuration() : _maxTextureSize(0) , _maxModelviewStackDepth(0) , _supportsPVRTC(false) , _supportsETC1(false) , _supportsS3TC(false) , _supportsATITC(false) , _supportsNPOT(false) , _supportsBGRA8888(false) , _supportsDiscardFramebuffer(false) , _supportsShareableVAO(false) , _maxSamplesAllowed(0) , _maxTextureUnits(0) , _glExtensions(nullptr) { } bool Configuration::init() { _valueDict["cocos2d.x.version"] = Value(cocos2dVersion()); #if CC_ENABLE_PROFILERS _valueDict["cocos2d.x.compiled_with_profiler"] = Value(true); #else _valueDict["cocos2d.x.compiled_with_profiler"] = Value(false); #endif #if CC_ENABLE_GL_STATE_CACHE == 0 _valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(false); #else _valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(true); #endif #if COCOS2D_DEBUG _valueDict["cocos2d.x.build_type"] = Value("DEBUG"); #else _valueDict["cocos2d.x.build_type"] = Value("RELEASE"); #endif return true; } Configuration::~Configuration() { } std::string Configuration::getInfo() const { // And Dump some warnings as well #if CC_ENABLE_PROFILERS CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)\n"); #endif #if CC_ENABLE_GL_STATE_CACHE == 0 CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)\n"); #endif // Dump Value forDump = Value(_valueDict); return forDump.getDescription(); } void Configuration::gatherGPUInfo() { _valueDict["gl.vendor"] = Value((const char*)glGetString(GL_VENDOR)); _valueDict["gl.renderer"] = Value((const char*)glGetString(GL_RENDERER)); _valueDict["gl.version"] = Value((const char*)glGetString(GL_VERSION)); _glExtensions = (char *)glGetString(GL_EXTENSIONS); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &_maxTextureSize); _valueDict["gl.max_texture_size"] = Value((int)_maxTextureSize); glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &_maxTextureUnits); _valueDict["gl.max_texture_units"] = Value((int)_maxTextureUnits); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) glGetIntegerv(GL_MAX_SAMPLES_APPLE, &_maxSamplesAllowed); _valueDict["gl.max_samples_allowed"] = Value((int)_maxSamplesAllowed); #endif _supportsETC1 = checkForGLExtension("GL_OES_compressed_ETC1_RGB8_texture"); _valueDict["gl.supports_ETC1"] = Value(_supportsETC1); _supportsS3TC = checkForGLExtension("GL_EXT_texture_compression_s3tc"); _valueDict["gl.supports_S3TC"] = Value(_supportsS3TC); _supportsATITC = checkForGLExtension("GL_AMD_compressed_ATC_texture"); _valueDict["gl.supports_ATITC"] = Value(_supportsATITC); _supportsPVRTC = checkForGLExtension("GL_IMG_texture_compression_pvrtc"); _valueDict["gl.supports_PVRTC"] = Value(_supportsPVRTC); _supportsNPOT = true; _valueDict["gl.supports_NPOT"] = Value(_supportsNPOT); _supportsBGRA8888 = checkForGLExtension("GL_IMG_texture_format_BGRA888"); _valueDict["gl.supports_BGRA8888"] = Value(_supportsBGRA8888); _supportsDiscardFramebuffer = checkForGLExtension("GL_EXT_discard_framebuffer"); _valueDict["gl.supports_discard_framebuffer"] = Value(_supportsDiscardFramebuffer); _supportsShareableVAO = checkForGLExtension("vertex_array_object"); _valueDict["gl.supports_vertex_array_object"] = Value(_supportsShareableVAO); CHECK_GL_ERROR_DEBUG(); } Configuration* Configuration::getInstance() { if (! s_sharedConfiguration) { s_sharedConfiguration = new Configuration(); s_sharedConfiguration->init(); } return s_sharedConfiguration; } void Configuration::destroyInstance() { CC_SAFE_RELEASE_NULL(s_sharedConfiguration); } // XXX: deprecated Configuration* Configuration::sharedConfiguration() { return Configuration::getInstance(); } // XXX: deprecated void Configuration::purgeConfiguration() { Configuration::destroyInstance(); } bool Configuration::checkForGLExtension(const string &searchName) const { return (_glExtensions && strstr(_glExtensions, searchName.c_str() ) ) ? true : false; } // // getters for specific variables. // Mantained for backward compatiblity reasons only. // int Configuration::getMaxTextureSize() const { return _maxTextureSize; } int Configuration::getMaxModelviewStackDepth() const { return _maxModelviewStackDepth; } int Configuration::getMaxTextureUnits() const { return _maxTextureUnits; } bool Configuration::supportsNPOT() const { return _supportsNPOT; } bool Configuration::supportsPVRTC() const { return _supportsPVRTC; } bool Configuration::supportsETC() const { //GL_ETC1_RGB8_OES is not defined in old opengl version #ifdef GL_ETC1_RGB8_OES return _supportsETC1; #else return false; #endif } bool Configuration::supportsS3TC() const { return _supportsS3TC; } bool Configuration::supportsATITC() const { return _supportsATITC; } bool Configuration::supportsBGRA8888() const { return _supportsBGRA8888; } bool Configuration::supportsDiscardFramebuffer() const { return _supportsDiscardFramebuffer; } bool Configuration::supportsShareableVAO() const { #if CC_TEXTURE_ATLAS_USE_VAO return _supportsShareableVAO; #else return false; #endif } // // generic getters for properties // const Value& Configuration::getValue(const std::string& key, const Value& defaultValue) const { auto iter = _valueDict.find(key); if (iter != _valueDict.cend()) return _valueDict.at(key); return defaultValue; } void Configuration::setValue(const std::string& key, const Value& value) { _valueDict[key] = value; } // // load file // void Configuration::loadConfigFile(const std::string& filename) { ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); CCASSERT(!dict.empty(), "cannot create dictionary"); // search for metadata bool validMetadata = false; auto metadataIter = dict.find("metadata"); if (metadataIter != dict.cend() && metadataIter->second.getType() == Value::Type::MAP) { const auto& metadata = metadataIter->second.asValueMap(); auto formatIter = metadata.find("format"); if (formatIter != metadata.cend()) { int format = formatIter->second.asInt(); // Support format: 1 if (format == 1) { validMetadata = true; } } } if (! validMetadata) { CCLOG("Invalid config format for file: %s", filename.c_str()); return; } auto dataIter = dict.find("data"); if (dataIter == dict.cend() || dataIter->second.getType() != Value::Type::MAP) { CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str()); return; } // Add all keys in the existing dictionary const auto& dataMap = dataIter->second.asValueMap(); for (auto dataMapIter = dataMap.cbegin(); dataMapIter != dataMap.cend(); ++dataMapIter) { if (_valueDict.find(dataMapIter->first) == _valueDict.cend()) _valueDict[dataMapIter->first] = dataMapIter->second; else CCLOG("Key already present. Ignoring '%s'",dataMapIter->first.c_str()); } } NS_CC_END
e73af428bc21bb2a250ea1bcb1b4e1de42b7d664
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/new_hunk_1080.cpp
9e632c5119fbc84de0a443fb4cfceb5c0dca2cc6
[]
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
358
cpp
return 1; } else { if (Negotiate_packet_debug_enabled) { if (!token_decode(&decodedLen, decoded, c)) return 1; debug("sending 'TT' to squid with data:\n"); hex_dump(reinterpret_cast<unsigned char*>(decoded), decodedLen); printf("TT %s\n", c);
1efa88f564845ab776267ba5c1e43f3b23728d24
cd5d95502f3a69dbd3a46ce3a59fd30c048edd6f
/ch3/Ex2.cpp
a936cba94ad21ff8f20fbb6d72642b6a47f972a3
[]
no_license
a-sc/cplusplus
d3a1cc9e483fc958cb58c88ec3ba0d8caae23b79
0bcd8abe2b93743917ccc31625bccd7104a422b0
refs/heads/master
2020-03-19T05:12:38.992287
2019-02-10T19:24:07
2019-02-10T19:24:07
135,909,690
0
1
null
2018-12-02T10:45:15
2018-06-03T14:09:10
C++
UTF-8
C++
false
false
559
cpp
#include <iostream> #include <string> using namespace std; int main() { double value; string conversion; cout << "Enter a number of miles or kilometers:" << endl; cin >> value; cout << "Do you want to convert to miles (enter m) or kilometers (enter k)?" << endl; cin >> conversion; if (conversion == "m" || conversion == "M") cout << "There are " << value / 1.609 << " miles in " << value << " kilometers." << endl; else cout << "There are " << value * 1.609 << " kilometers in " << value << " miles." << endl; return 0; }
a75371635def3d2f45d286f5126f10a51ee5c226
d33f96531463288d192cf55f5e6d2a6d0cc6a19d
/main.cpp
3ce5a4d86c5adff21b25845d4e4792a92b784bc2
[]
no_license
AndrewChupin/cpp_berkley_sandbox
9d2e683503d800a29bc91074e993bb70ebba8959
3766928bb9b0692f857fda152e39402e79401d8d
refs/heads/master
2020-05-25T08:30:31.728696
2019-08-05T19:59:00
2019-08-05T19:59:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
cpp
#include <iostream> #include "concurrency/ThreadPool.h" #include "network/ConnectionPool.h" int main(int argc, char **argv) { // /*pool.execute([&] { //socket.create(); //socket.write(std::make_shared<ByteBuffer>(&message)); });*/ /*while (true) { std::string str; puts("Enter text:"); std::getline(std::cin, str); socket.write(std::make_shared<ByteBuffer>(&str)); }*/ //pool.join(); // net::NetAddress address { net::NetAddress::V4("192.168.0.240", 5001) }; // net::NetSocket socket { address, net::NetProtocol::TCP }; conc::ThreadPool pool { 3 }; auto conPool = std::make_shared<net::ConnectionPool>(); pool.execute([conPool] { conPool->loop(); }); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); conPool->create(net::NetAddress::v4("192.168.0.240", 5001)); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); conPool->create(net::NetAddress::v4("192.168.0.240", 5002)); pool.join(); }
430595046fc55df0785a56b7fb490a2e50e68e2c
d2f67d6c5933f96b816a3195401aabd56a4f7f05
/Day_05/ex03/PresidentialPardonForm.hpp
62a783755769416264f8ca73def6b6c58c6a0289
[]
no_license
florianne1212/CPP_piscine_42
2ce473fdd4cdac4ee100159b80a28ac91426843f
c151616103e606ab05f2f6ac66d5a93b2900591b
refs/heads/master
2023-03-25T03:43:53.828656
2021-03-24T11:15:04
2021-03-24T11:15:04
316,215,698
0
0
null
null
null
null
UTF-8
C++
false
false
490
hpp
#ifndef PRESIDENTIALPARDONFORM_H # define PRESIDENTIALPARDONFORM_H #include "Form.hpp" class PresidentialPardonForm : public Form { private: std::string const _target; PresidentialPardonForm(); public: PresidentialPardonForm(std::string const target); PresidentialPardonForm(PresidentialPardonForm const & copy); ~PresidentialPardonForm(); PresidentialPardonForm & operator=(PresidentialPardonForm const & ope); virtual void execute_action()const; }; #endif
f085e627123cd0f8f4830897a8ab492f6a4d16c3
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/60/1818.c
6f68beadea5477d6f30b4c3a0ff308148dddbf82
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
657
c
main() { int N,i,j,m,n,t; scanf("%d",&N); if(N>4) { for(i=3;i<=N-2;) { t=0; m=i+2; for(j=2;j<=i/2;j++) {if(i%j==0)break;} if(j==i/2+1) t=1; for(n=2;n<=m/2;n++) { if(m%n==0)break ;} if(n==m/2+1) t=t+1; if(t==2) printf("%d %d\n",i,m); i=i+2; } } else printf("empty"); }
28cebf130233bcde7dae3a694d7c9053b9e6321a
45d1768d87a8fb3418594ec64cf7ed2daf06c6e9
/darkness-engine/include/components/MaterialComponent.h
1119b32180b16bf474382456eda63f58e670e89c
[ "MIT" ]
permissive
FutureInfinity/Darkness
c54888829de48eaaeed09acde4edce7423ba8774
c87eaf067a2707a0141909125ff461f69a3812e0
refs/heads/master
2021-09-13T15:39:45.959663
2018-05-01T17:15:25
2018-05-01T17:15:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,783
h
#pragma once #include "engine/EngineComponent.h" #include "engine/graphics/Resources.h" #include "engine/graphics/Device.h" #include "tools/image/Image.h" #include "tools/Property.h" #include "tools/hash/Hash.h" #include "tools/PathTools.h" #include "platform/File.h" namespace engine { class MaterialComponent : public EngineComponent { Property m_color; bool m_hasAlbedo; bool m_hasRoughness; bool m_hasNormal; bool m_hasMetalness; bool m_hasOcclusion; Property m_albedoPath; Property m_normalPath; Property m_roughnessPath; Property m_roughnessStrength; Property m_metalnessPath; Property m_metalnessStrength; Property m_occlusionPath; Property m_occlusionStrength; Property m_materialScaleX; Property m_materialScaleY; Property m_transparent; Property m_alphaclipped; Property m_albedoUVIndex; Property m_roughnessUVIndex; Property m_normalUVIndex; Property m_metalnessUVIndex; Property m_occlusionUVIndex; bool m_cpuDirty[static_cast<int>(TextureType::COUNT)]; bool m_gpuDirty[static_cast<int>(TextureType::COUNT)]; std::shared_ptr<image::ImageIf> m_albedo; std::shared_ptr<image::ImageIf> m_roughness; std::shared_ptr<image::ImageIf> m_normal; std::shared_ptr<image::ImageIf> m_metalness; std::shared_ptr<image::ImageIf> m_occlusion; std::unique_ptr<TextureSRV> m_albedoSrv; std::unique_ptr<TextureSRV> m_roughnessSrv; std::unique_ptr<TextureSRV> m_normalSrv; std::unique_ptr<TextureSRV> m_metalnessSrv; std::unique_ptr<TextureSRV> m_occlusionSrv; bool m_albedoChanged; bool m_roughnessChanged; bool m_normalChanged; bool m_metalnessChanged; bool m_occlusionChanged; bool m_materialDirty; ResourceKey m_albedoKey; ResourceKey m_roughnessKey; ResourceKey m_normalKey; ResourceKey m_metalnessKey; ResourceKey m_occlusionKey; TextureSRV createTexture(ResourceKey key, Device& device, image::ImageIf* image, bool srgb = false) { return device.createTextureSRV(key, TextureDescription() .name("color") .width(static_cast<uint32_t>(image->width())) .height(static_cast<uint32_t>(image->height())) .format(srgb ? srgbFormat(image->format()) : image->format()) .arraySlices(static_cast<uint32_t>(image->arraySlices())) .mipLevels(static_cast<uint32_t>(image->mipCount())) .setInitialData(TextureDescription::InitialData( std::vector<uint8_t>(image->data(), image->data() + image->bytes()), static_cast<uint32_t>(image->width()), static_cast<uint32_t>(image->width() * image->height())))); } public: std::shared_ptr<EngineComponent> clone() const override { auto res = std::make_shared<engine::MaterialComponent>( m_albedoPath.value<std::string>(), m_roughnessPath.value<std::string>(), m_normalPath.value<std::string>(), m_metalnessPath.value<std::string>(), m_occlusionPath.value<std::string>(), m_albedoUVIndex.value<int>(), m_roughnessUVIndex.value<int>(), m_normalUVIndex.value<int>(), m_metalnessUVIndex.value<int>(), m_occlusionUVIndex.value<int>()); res->m_color.value<Vector3f>(m_color.value<Vector3f>()); res->m_hasAlbedo = m_hasAlbedo; res->m_hasRoughness = m_hasRoughness; res->m_hasNormal = m_hasNormal; res->m_hasMetalness = m_hasMetalness; res->m_hasOcclusion = m_hasOcclusion; res->roughnessStrength(roughnessStrength()); res->metalnessStrength(metalnessStrength()); res->occlusionStrength(occlusionStrength()); res->materialScaleX(materialScaleX()); res->materialScaleY(materialScaleY()); res->transparent(transparent()); res->alphaclipped(alphaclipped()); res->name(m_name); return res; } MaterialComponent() : m_color{ this, "Color", Vector3f{ 1.0f, 1.0f, 1.0f }, [this]() { this->m_materialDirty = true; } } , m_hasAlbedo{ false } , m_hasRoughness{ false } , m_hasNormal{ false } , m_hasMetalness{ false } , m_hasOcclusion{ false } , m_albedoPath{ this, "Albedo", std::string(""), [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Albedo)] = true; this->m_albedoChanged = true; m_hasAlbedo = checkMaterialFile(m_albedoPath, "albedo"); this->m_materialDirty = true; } } , m_normalPath{ this, "Normal", std::string(""), [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Normal)] = true; this->m_normalChanged = true; m_hasNormal = checkMaterialFile(m_normalPath, "normal"); this->m_materialDirty = true; } } , m_roughnessPath{ this, "Roughness", std::string(""), [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Roughness)] = true; this->m_roughnessChanged = true; m_hasRoughness = checkMaterialFile(m_roughnessPath, "roughness"); this->m_materialDirty = true; } } , m_roughnessStrength{ this, "Roughness Strength", 1.0f, [this]() { this->m_materialDirty = true; } } , m_metalnessPath{ this, "Metalness", std::string(""), [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Metalness)] = true; this->m_metalnessChanged = true; m_hasMetalness = checkMaterialFile(m_metalnessPath, "metalness"); this->m_materialDirty = true; } } , m_metalnessStrength{ this, "Metalness Strength", 1.0f, [this]() { this->m_materialDirty = true; } } , m_occlusionPath{ this, "Occlusion", std::string(""), [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Occlusion)] = true; this->m_occlusionChanged = true; m_hasOcclusion = checkMaterialFile(m_occlusionPath, "occlusion"); this->m_materialDirty = true; } } , m_occlusionStrength{ this, "Occlusion Strength", 1.0f, [this]() { this->m_materialDirty = true; } } , m_materialScaleX{ this, "Scale X", 1.0f, [this]() { this->m_materialDirty = true; } } , m_materialScaleY{ this, "Scale y", 1.0f, [this]() { this->m_materialDirty = true; } } , m_transparent{ this, "Transparent", ButtonToggle::NotPressed, [this]() { this->m_materialDirty = true; } } , m_alphaclipped{ this, "Alphaclipped", ButtonToggle::NotPressed, [this]() { this->m_materialDirty = true; } } , m_albedoUVIndex{ this, "Albedo UV Index", static_cast<int>(0), [this]() { this->m_materialDirty = true; } } , m_roughnessUVIndex{ this, "Roughness UV Index", static_cast<int>(0), [this]() { this->m_materialDirty = true; } } , m_normalUVIndex{ this, "Normal UV Index", static_cast<int>(0), [this]() { this->m_materialDirty = true; } } , m_metalnessUVIndex{ this, "Metalness UV Index", static_cast<int>(0), [this]() { this->m_materialDirty = true; } } , m_occlusionUVIndex{ this, "Occlusion UV Index", static_cast<int>(0), [this]() { this->m_materialDirty = true; } } , m_cpuDirty{ true, true, true, true, true, true, true, true, true, true, true, true, true } , m_gpuDirty{ false, false, false, false, false, false, false, false, false, false, false, false, false } , m_albedoChanged{ true } , m_roughnessChanged{ true } , m_normalChanged{ true } , m_metalnessChanged{ true } , m_occlusionChanged{ true } , m_materialDirty{ true } { m_name = "MaterialComponent"; } MaterialComponent( const std::string& albedoPath, const std::string& roughnessPath, const std::string& normalPath, const std::string& metalnessPath, const std::string& occlusionPath, int albedoUVIndex, int roughnessUVIndex, int normalUVIndex, int metalnessUVIndex, int occlusionUVIndex) : m_color{ this, "Color", Vector3f{ 1.0f, 1.0f, 1.0f }, [this]() { this->m_materialDirty = true; } } , m_hasAlbedo{ false } , m_hasRoughness{ false } , m_hasNormal{ false } , m_hasMetalness{ false } , m_hasOcclusion{ false } , m_albedoPath{ this, "Albedo", albedoPath, [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Albedo)] = true; this->m_albedoChanged = true; m_hasAlbedo = checkMaterialFile(m_albedoPath, "albedo");this->m_materialDirty = true; } } , m_normalPath{ this, "Normal", normalPath, [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Normal)] = true; this->m_normalChanged = true; m_hasNormal = checkMaterialFile(m_normalPath, "normal");this->m_materialDirty = true; } } , m_roughnessPath{ this, "Roughness", roughnessPath, [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Roughness)] = true; this->m_roughnessChanged = true; m_hasRoughness = checkMaterialFile(m_roughnessPath, "roughness"); this->m_materialDirty = true; } } , m_roughnessStrength{ this, "Roughness Strength", 1.0f, [this]() { this->m_materialDirty = true; } } , m_metalnessPath{ this, "Metalness", metalnessPath, [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Metalness)] = true; this->m_metalnessChanged = true; m_hasMetalness = checkMaterialFile(m_metalnessPath, "metalness"); this->m_materialDirty = true; } } , m_metalnessStrength{ this, "Metalness Strength", 1.0f, [this]() { this->m_materialDirty = true; } } , m_occlusionPath{ this, "Occlusion", occlusionPath, [this]() { this->m_cpuDirty[static_cast<int>(TextureType::Occlusion)] = true; this->m_occlusionChanged = true; m_hasOcclusion = checkMaterialFile(m_occlusionPath, "occlusion"); this->m_materialDirty = true; } } , m_occlusionStrength{ this, "Occlusion Strength", 1.0f, [this]() { this->m_materialDirty = true; } } , m_materialScaleX{ this, "Scale X", 1.0f, [this]() { this->m_materialDirty = true; } } , m_materialScaleY{ this, "Scale y", 1.0f, [this]() { this->m_materialDirty = true; } } , m_transparent{ this, "Transparent", ButtonToggle::NotPressed, [this]() { this->m_materialDirty = true; } } , m_alphaclipped{ this, "Alphaclipped", ButtonToggle::NotPressed, [this]() { this->m_materialDirty = true; } } , m_albedoUVIndex{ this, "Albedo UV Index", albedoUVIndex, [this]() { this->m_materialDirty = true; } } , m_roughnessUVIndex{ this, "Roughness UV Index", roughnessUVIndex, [this]() { this->m_materialDirty = true; } } , m_normalUVIndex{ this, "Normal UV Index", normalUVIndex, [this]() { this->m_materialDirty = true; } } , m_metalnessUVIndex{ this, "Metalness UV Index", metalnessUVIndex, [this]() { this->m_materialDirty = true; } } , m_occlusionUVIndex{ this, "Occlusion UV Index", occlusionUVIndex, [this]() { this->m_materialDirty = true; } } , m_cpuDirty{ true, true, true, true, true, true, true, true, true, true, true, true, true } , m_gpuDirty{ false, false, false, false, false, false, false, false, false, false, false, false, false } , m_albedoChanged{ true } , m_roughnessChanged{ true } , m_normalChanged{ true } , m_metalnessChanged{ true } , m_occlusionChanged{ true } , m_materialDirty{ true } { m_name = "MaterialComponent"; m_hasAlbedo = checkMaterialFile(m_albedoPath, "albedo"); m_hasNormal = checkMaterialFile(m_normalPath, "normal"); m_hasRoughness = checkMaterialFile(m_roughnessPath, "roughness"); m_hasMetalness = checkMaterialFile(m_metalnessPath, "metalness"); m_hasOcclusion = checkMaterialFile(m_occlusionPath, "occlusion"); } TextureSRV& albedo() { return *m_albedoSrv; } TextureSRV& normal() { return *m_normalSrv; } TextureSRV& roughness() { return *m_roughnessSrv; } TextureSRV& metalness() { return *m_metalnessSrv; } TextureSRV& occlusion() { return *m_occlusionSrv; } Vector3f color() const { return m_color.value<Vector3f>(); } void color(const Vector3f& col) { m_color.value<Vector3f>(col); m_materialDirty = true; } float roughnessStrength() const { return m_roughnessStrength.value<float>(); } float metalnessStrength() const { return m_metalnessStrength.value<float>(); } float occlusionStrength() const { return m_occlusionStrength.value<float>(); } float materialScaleX() const { return m_materialScaleX.value<float>(); } float materialScaleY() const { return m_materialScaleY.value<float>(); } void roughnessStrength(float val) { m_roughnessStrength.value<float>(val); m_materialDirty = true; } void metalnessStrength(float val) { m_metalnessStrength.value<float>(val); m_materialDirty = true; } void occlusionStrength(float val) { m_occlusionStrength.value<float>(val); m_materialDirty = true; } void materialScaleX(float val) { m_materialScaleX.value<float>(val); m_materialDirty = true; } void materialScaleY(float val) { m_materialScaleY.value<float>(val); m_materialDirty = true; } bool albedoChanged(bool clear = false) { bool res = m_albedoChanged; if(clear) m_albedoChanged = false; return res; } bool roughnessChanged(bool clear = false) { bool res = m_roughnessChanged; if(clear) m_roughnessChanged = false; return res; } bool normalChanged(bool clear = false) { bool res = m_normalChanged; if(clear) m_normalChanged = false; return res; } bool metalnessChanged(bool clear = false) { bool res = m_metalnessChanged; if(clear) m_metalnessChanged = false; return res; } bool occlusionChanged(bool clear = false) { bool res = m_occlusionChanged; if(clear) m_occlusionChanged = false; return res; } bool hasAlbedo() { return m_hasAlbedo; } bool hasRoughness() { return m_hasRoughness; } bool hasNormal() { return m_hasNormal; } bool hasMetalness() { return m_hasMetalness; } bool hasOcclusion() { return m_hasOcclusion; } ResourceKey albedoKey() { return m_albedoKey; } ResourceKey roughnessKey() { return m_roughnessKey; } ResourceKey normalKey() { return m_normalKey; } ResourceKey metalnessKey() { return m_metalnessKey; } ResourceKey occlusionKey() { return m_occlusionKey; } bool transparent() const { return static_cast<bool>(m_transparent.value<ButtonToggle>()); } void transparent(bool transparent) { m_transparent.value<ButtonToggle>(static_cast<ButtonToggle>(transparent)); } bool alphaclipped() const { return static_cast<bool>(m_alphaclipped.value<ButtonToggle>()); } void alphaclipped(bool alphaclipped) { m_alphaclipped.value<ButtonToggle>(static_cast<ButtonToggle>(alphaclipped)); } int albedoUVIndex() const { return m_albedoUVIndex.value<int>(); } void albedoUVIndex(int index) { m_albedoUVIndex.value<int>(index); } int roughnessUVIndex() const { return m_roughnessUVIndex.value<int>(); } void roughnessUVIndex(int index) { m_roughnessUVIndex.value<int>(index); } int normalUVIndex() const { return m_normalUVIndex.value<int>(); } void normalUVIndex(int index) { m_normalUVIndex.value<int>(index); } int metalnessUVIndex() const { return m_metalnessUVIndex.value<int>(); } void metalnessUVIndex(int index) { m_metalnessUVIndex.value<int>(index); } int occlusionUVIndex() const { return m_occlusionUVIndex.value<int>(); } void occlusionUVIndex(int index) { m_occlusionUVIndex.value<int>(index); } private: bool checkMaterialFile(const Property& path, const char* materialType) { auto pathStr = path.value<std::string>(); bool hasPath = pathStr != ""; bool foundFile = false; if (hasPath) foundFile = engine::fileExists(pathStr); if (hasPath && !foundFile) LOG_WARNING("Missing %s material file: %s", materialType, pathStr.c_str()); return hasPath && foundFile; } public: void invalidateGpu() { for(int i = 0; i < static_cast<int>(TextureType::COUNT); ++i) m_gpuDirty[i] = true; } private: InstanceMaterial m_clusterMaterial; void grabMaterialParameters() { m_clusterMaterial.materialSet = 0; if (hasAlbedo()) m_clusterMaterial.materialSet |= 0x1; if (hasMetalness()) m_clusterMaterial.materialSet |= 0x2; if (hasRoughness()) m_clusterMaterial.materialSet |= 0x4; if (hasNormal()) m_clusterMaterial.materialSet |= 0x8; if (hasOcclusion()) m_clusterMaterial.materialSet |= 0x10; m_clusterMaterial.roughnessStrength = roughnessStrength(); m_clusterMaterial.metalnessStrength = metalnessStrength(); m_clusterMaterial.occlusionStrength = occlusionStrength(); m_clusterMaterial.scaleX = materialScaleX(); m_clusterMaterial.scaleY = materialScaleY(); m_clusterMaterial.color = color(); } public: void cpuRefresh(Device& device) { if (m_materialDirty) { auto mesh = getComponent<MeshRendererComponent>(); if (mesh && mesh->meshBuffer().modelAllocations) { m_materialDirty = false; grabMaterialParameters(); device.modelResources().updateSubmeshMaterial(*mesh->meshBuffer().modelAllocations, m_clusterMaterial); auto selectedUv = m_albedoUVIndex.value<int>(); if (selectedUv < mesh->meshBuffer().modelAllocations->subMeshInstance->uvData.size()) { auto& uv = *mesh->meshBuffer().modelAllocations->subMeshInstance->uvData[selectedUv]; device.modelResources().updateSubmeshUV(*mesh->meshBuffer().modelAllocations, uv.modelResource.gpuIndex); } } } if (m_cpuDirty[static_cast<int>(TextureType::Albedo)]) { m_cpuDirty[static_cast<int>(TextureType::Albedo)] = false; if (hasAlbedo()) { auto path = m_albedoPath.value<std::string>(); m_albedoKey = tools::hash(pathClean(path)); m_albedo = device.createImage( m_albedoKey, path); } else m_albedo = nullptr; if(m_albedo) m_gpuDirty[static_cast<int>(TextureType::Albedo)] = true; } if (m_cpuDirty[static_cast<int>(TextureType::Roughness)]) { m_cpuDirty[static_cast<int>(TextureType::Roughness)] = false; if (hasRoughness()) { auto path = m_roughnessPath.value<std::string>(); m_roughnessKey = tools::hash(pathClean(path)); m_roughness = device.createImage(m_roughnessKey, path); } else m_roughness = nullptr; if(m_roughness) m_gpuDirty[static_cast<int>(TextureType::Roughness)] = true; } if (m_cpuDirty[static_cast<int>(TextureType::Normal)]) { m_cpuDirty[static_cast<int>(TextureType::Normal)] = false; if (hasNormal()) { auto path = m_normalPath.value<std::string>(); m_normalKey = tools::hash(pathClean(path)); m_normal = device.createImage(m_normalKey, path); } else m_normal = nullptr; if(m_normal) m_gpuDirty[static_cast<int>(TextureType::Normal)] = true; } if (m_cpuDirty[static_cast<int>(TextureType::Metalness)]) { m_cpuDirty[static_cast<int>(TextureType::Metalness)] = false; if (hasMetalness()) { auto path = m_metalnessPath.value<std::string>(); m_metalnessKey = tools::hash(pathClean(path)); m_metalness = device.createImage(m_metalnessKey, path); } else m_metalness = nullptr; if(m_metalness) m_gpuDirty[static_cast<int>(TextureType::Metalness)] = true; } if (m_cpuDirty[static_cast<int>(TextureType::Occlusion)]) { m_cpuDirty[static_cast<int>(TextureType::Occlusion)] = false; if (hasOcclusion()) { auto path = m_occlusionPath.value<std::string>(); m_occlusionKey = tools::hash(pathClean(path)); m_occlusion = device.createImage(m_occlusionKey, path); } else m_occlusion = nullptr; if (m_occlusion) m_gpuDirty[static_cast<int>(TextureType::Occlusion)] = true; } } bool gpuRefresh(Device& device) { bool change = false; if (m_gpuDirty[static_cast<int>(TextureType::Albedo)]) { m_gpuDirty[static_cast<int>(TextureType::Albedo)] = false; change = true; if (hasAlbedo()) { m_albedoSrv = std::make_unique<TextureSRV>( createTexture(m_albedoKey, device, m_albedo.get(), true)); m_clusterMaterial.albedo = device.modelResources().addMaterial(m_albedoKey, m_albedo.get(), true); auto mesh = getComponent<MeshRendererComponent>(); if (mesh) { grabMaterialParameters(); device.modelResources().updateSubmeshMaterial(*mesh->meshBuffer().modelAllocations, m_clusterMaterial); } } else m_albedoSrv = nullptr; } if (m_gpuDirty[static_cast<int>(TextureType::Roughness)]) { m_gpuDirty[static_cast<int>(TextureType::Roughness)] = false; change = true; if (hasRoughness()) { m_roughnessSrv = std::make_unique<TextureSRV>( createTexture(m_roughnessKey, device, m_roughness.get())); m_clusterMaterial.roughness = device.modelResources().addMaterial(m_roughnessKey, m_roughness.get()); auto mesh = getComponent<MeshRendererComponent>(); if (mesh) { grabMaterialParameters(); device.modelResources().updateSubmeshMaterial(*mesh->meshBuffer().modelAllocations, m_clusterMaterial); } } else m_roughnessSrv = nullptr; } if (m_gpuDirty[static_cast<int>(TextureType::Normal)]) { m_gpuDirty[static_cast<int>(TextureType::Normal)] = false; change = true; if (hasNormal()) { m_normalSrv = std::make_unique<TextureSRV>( createTexture(m_normalKey, device, m_normal.get())); m_clusterMaterial.normal = device.modelResources().addMaterial(m_normalKey, m_normal.get()); auto mesh = getComponent<MeshRendererComponent>(); if (mesh) { grabMaterialParameters(); device.modelResources().updateSubmeshMaterial(*mesh->meshBuffer().modelAllocations, m_clusterMaterial); } } else m_normalSrv = nullptr; } if (m_gpuDirty[static_cast<int>(TextureType::Metalness)]) { m_gpuDirty[static_cast<int>(TextureType::Metalness)] = false; change = true; if (hasMetalness()) { m_metalnessSrv = std::make_unique<TextureSRV>( createTexture(m_metalnessKey, device, m_metalness.get())); m_clusterMaterial.metalness = device.modelResources().addMaterial(m_metalnessKey, m_metalness.get()); auto mesh = getComponent<MeshRendererComponent>(); if (mesh) { grabMaterialParameters(); device.modelResources().updateSubmeshMaterial(*mesh->meshBuffer().modelAllocations, m_clusterMaterial); } } else m_metalnessSrv = nullptr; } if (m_gpuDirty[static_cast<int>(TextureType::Occlusion)]) { m_gpuDirty[static_cast<int>(TextureType::Occlusion)] = false; change = true; if (hasOcclusion()) { m_occlusionSrv = std::make_unique<TextureSRV>( createTexture(m_occlusionKey, device, m_occlusion.get())); m_clusterMaterial.ao = device.modelResources().addMaterial(m_occlusionKey, m_occlusion.get()); auto mesh = getComponent<MeshRendererComponent>(); if (mesh) { grabMaterialParameters(); device.modelResources().updateSubmeshMaterial(*mesh->meshBuffer().modelAllocations, m_clusterMaterial); } } else m_occlusionSrv = nullptr; } return change; } }; }
a3de4af4c4c621201866745308594dbf10577610
a7881a10dbeded9534f8c37d1655c1750d82518d
/application/util/app_essentials.cpp
05eb4778215bcb6c037820e8d3fbabe3154f2bf2
[ "MIT" ]
permissive
aconstlink/natus
31130e7439c1bb983c35e5f8ed2e684677c6583a
8f8ad12aa71d246a10802bf5042f407de45d66d7
refs/heads/master
2023-08-17T01:58:03.578900
2023-03-29T12:45:45
2023-03-29T12:45:45
248,593,153
1
0
null
null
null
null
UTF-8
C++
false
false
20,766
cpp
#include "app_essentials.h" #include <natus/property/property_sheet.hpp> #include <natus/tool/imgui/custom_widgets.h> #include <natus/format/global.h> #include <natus/format/nsl/nsl_module.h> #include <natus/format/future_items.hpp> #include <natus/graphics/shader/nsl_bridge.hpp> #include <natus/nsl/parser.h> #include <natus/nsl/dependency_resolver.hpp> #include <natus/nsl/generator_structs.hpp> #include <natus/math/utility/angle.hpp> using namespace natus::application ; using namespace natus::application::util ; //**************************************************************** app_essentials::app_essentials( void_t ) noexcept { } //**************************************************************** app_essentials::app_essentials( natus::graphics::async_views_t graphics ) noexcept { _graphics = graphics ; } //**************************************************************** app_essentials::app_essentials( this_rref_t rhv ) noexcept { *this = std::move( rhv ) ; } //**************************************************************** app_essentials::~app_essentials( void_t ) noexcept { } //**************************************************************** app_essentials::this_ref_t app_essentials::operator = ( this_rref_t rhv ) noexcept { _camera_0 = std::move( rhv._camera_0 ) ; _graphics = std::move( rhv._graphics ) ; _db = std::move( rhv._db ) ; _tr = std::move( rhv._tr ) ; _pr = std::move( rhv._pr ) ; _lr3 = std::move( rhv._lr3 ) ; _pr3 = std::move( rhv._pr3 ) ; _window_dims = std::move( rhv._window_dims ) ; _rs = std::move( rhv._rs ) ; _shader_mon = std::move( rhv._shader_mon ) ; _ndb = std::move( rhv._ndb ) ; return *this ; } //**************************************************************** void_t app_essentials::init( init_struct_cref_t d ) noexcept { this_t::init_database( d.idb.base, d.idb.rel, d.idb.name ) ; this_t::init_font() ; this_t::init_graphics( d.ig.app_name ) ; this_t::init_shaders( d.nsl_shaders ) ; this_t::init_device() ; } //**************************************************************** void_t app_essentials::init_font( void_t ) noexcept { // import fonts and create text render { natus::property::property_sheet_res_t ps = natus::property::property_sheet_t() ; { natus::font::code_points_t pts ; for( uint32_t i = 33; i <= 126; ++i ) pts.emplace_back( i ) ; for( uint32_t i : {uint32_t( 0x00003041 )} ) pts.emplace_back( i ) ; ps->set_value< natus::font::code_points_t >( "code_points", pts ) ; } { natus::ntd::vector< natus::io::location_t > locations = { natus::io::location_t("fonts.mitimasu.ttf"), //natus::io::location_t("") } ; ps->set_value( "additional_locations", locations ) ; } { ps->set_value<size_t>( "atlas_width", 128 ) ; ps->set_value<size_t>( "atlas_height", 512 ) ; ps->set_value<size_t>( "point_size", 90 ) ; } { natus::format::module_registry_res_t mod_reg = natus::format::global_t::registry() ; auto fitem = mod_reg->import_from( natus::io::location_t( "fonts.LCD_Solid.ttf" ), _db, ps ) ; natus::format::glyph_atlas_item_res_t ii = fitem.get() ; _tr = natus::gfx::text_render_2d_res_t( natus::gfx::text_render_2d_t( ) ) ; if( ii.is_valid() ) { _has_font = true ; _tr->set_glyph_atlas( std::move( *ii->obj ) ) ; } } } } //**************************************************************** void_t app_essentials::init_graphics( natus::ntd::string_cref_t name ) noexcept { // root render states { natus::graphics::state_object_t so = natus::graphics::state_object_t( name + ".root_render_states" ) ; { natus::graphics::render_state_sets_t rss ; rss.depth_s.do_change = true ; rss.depth_s.ss.do_activate = false ; rss.depth_s.ss.do_depth_write = false ; rss.polygon_s.do_change = true ; rss.polygon_s.ss.do_activate = true ; rss.polygon_s.ss.ff = natus::graphics::front_face::clock_wise ; rss.polygon_s.ss.cm = natus::graphics::cull_mode::back; rss.polygon_s.ss.fm = natus::graphics::fill_mode::fill ; rss.clear_s.do_change = true ; rss.clear_s.ss.do_activate = true ; rss.clear_s.ss.do_color_clear = true ; rss.clear_s.ss.clear_color = natus::math::vec4f_t( 0.5f, 0.5f, 0.5f, 1.0f ) ; so.add_render_state_set( rss ) ; } _rs = std::move( so ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( _rs ) ; } ) ; } // prepare primitive { _pr = natus::gfx::primitive_render_2d_res_t( natus::gfx::primitive_render_2d_t() ) ; _pr->init( name + ".prim_render", _graphics ) ; } // prepare primitive { _pr3 = natus::gfx::primitive_render_3d_res_t( natus::gfx::primitive_render_3d_t() ) ; _pr3->init( name + ".prim_render_3d", _graphics ) ; } // prepare line render { _lr3 = natus::gfx::line_render_3d_res_t( natus::gfx::line_render_3d_t() ) ; _lr3->init( name + ".line_render", _graphics ) ; } { _tr->init( name + ".my_text_render", _graphics ) ; } _camera_0 = natus::gfx::pinhole_camera_res_t( natus::gfx::pinhole_camera_t() ) ; _camera_0->perspective_fov( natus::math::angle<float_t>::degree_to_radian( 45.0f ) ) ; // // @todo: fix this // why setting camera position two times? // { _camera_0->look_at( natus::math::vec3f_t( 0.0f, 100.0f, -1000.0f ), natus::math::vec3f_t( 0.0f, 1.0f, 0.0f ), natus::math::vec3f_t( 0.0f, 100.0f, 0.0f )) ; } _camera_0->set_transformation( natus::math::m3d::trafof_t( 1.0f, natus::math::vec3f_t(0.0f,0.0f,0.0f), natus::math::vec3f_t(0.0f,0.0f,-1000.0f) ) ) ; } //**************************************************************** void_t app_essentials::init_database( natus::io::path_cref_t base, natus::io::path_cref_t rel, natus::io::path_cref_t name ) noexcept { _db = natus::io::database_t( base, rel, name ) ; } //**************************************************************** void_t app_essentials::init_device( void_t ) noexcept { natus::device::global_t::system()->search( [&] ( natus::device::idevice_res_t dev_in ) { if( natus::device::three_device_res_t::castable( dev_in ) ) { _dev_mouse = dev_in ; } else if( natus::device::ascii_device_res_t::castable( dev_in ) ) { _dev_ascii = dev_in ; } } ) ; if( !_dev_mouse.is_valid() ) { natus::log::global_t::status( "no three mosue found" ) ; } if( !_dev_ascii.is_valid() ) { natus::log::global_t::status( "no ascii keyboard found" ) ; } } //**************************************************************** void_t app_essentials::init_shaders( this_t::locations_cref_t shader_locations ) noexcept { if( !_ndb.is_valid() ) _ndb = natus::nsl::database_t() ; natus::ntd::vector< natus::nsl::symbol_t > config_symbols ; for( auto const & l : shader_locations ) { natus::format::module_registry_res_t mod_reg = natus::format::global_t::registry() ; auto fitem2 = mod_reg->import_from( l, _db ) ; natus::format::nsl_item_res_t ii = fitem2.get() ; if( ii.is_valid() ) _ndb->insert( std::move( ii->doc ), config_symbols ) ; _db->attach( l.as_string(), _shader_mon ) ; } // generate configs for( auto const & s : config_symbols ) { natus::nsl::generatable_t res = natus::nsl::dependency_resolver_t().resolve( _ndb, s ) ; if( res.missing.size() != 0 ) { natus::log::global_t::warning( "[simple_app_essentials] : We have missing shader symbols." ) ; for( auto const& m : res.missing ) { natus::log::global_t::status( m.expand() ) ; } } auto const sc = natus::graphics::nsl_bridge_t().create( natus::nsl::generator_t( std::move( res ) ).generate() ).set_name( s.expand() ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( sc ) ; } ) ; } } //**************************************************************** natus::ntd::vector< natus::nsl::symbol_t > app_essentials::process_shader( natus::ntd::string_cref_t shader ) noexcept { natus::ntd::vector< natus::nsl::symbol_t > config_symbols ; if( !_ndb.is_valid() ) { natus::log::global_t::error( "[app_essentials::process_shader] : nsl not initialized" ) ; return config_symbols ; } _ndb->insert( natus::nsl::parser_t("app_essentials::process_shader::nsl_parser").process( shader ), config_symbols ) ; // generate configs for( auto const & s : config_symbols ) { natus::nsl::generatable_t res = natus::nsl::dependency_resolver_t().resolve( _ndb, s ) ; if( res.missing.size() != 0 ) { natus::log::global_t::warning( "[simple_app_essentials] : We have missing shader symbols." ) ; for( auto const& m : res.missing ) { natus::log::global_t::status( m.expand() ) ; } } auto const sc = natus::graphics::nsl_bridge_t().create( natus::nsl::generator_t( std::move( res ) ).generate() ).set_name( s.expand() ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( sc ) ; } ) ; } return std::move( config_symbols ) ; } //**************************************************************** void_t app_essentials::on_event( natus::application::app::window_id_t const, natus::application::app::window_event_info_in_t wei, natus::math::vec2f_cref_t target ) noexcept { _window_dims = natus::math::vec2f_t( float_t(wei.w), float_t(wei.h) ) ; _camera_0->set_sensor_dims( float_t(wei.w), float_t(wei.h) ) ; if( _camera_0->is_perspective() ) { _camera_0->perspective_fov() ; } else if( _camera_0->is_orthographic() ) { _camera_0->orthographic() ; } natus::math::vec2f_t const ratio = _window_dims / target ; _extend = target * (ratio.x() < ratio.y() ? ratio.xx() : ratio.yy()) ; } //**************************************************************** void_t app_essentials::on_device( natus::application::app::device_data_in_t ) noexcept { natus::device::layouts::ascii_keyboard_t ascii( _dev_ascii ) ; if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f8 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f9 ) == natus::device::components::key_state::released ) { } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f2 ) == natus::device::components::key_state::released ) { _do_tool = !_do_tool ; } { _last_mouse = _cur_mouse ; natus::device::layouts::three_mouse_t mouse( _dev_mouse ) ; _cur_mouse = mouse.get_local() * natus::math::vec2f_t( 2.0f ) - natus::math::vec2f_t( 1.0f ) ; _cur_mouse = _cur_mouse * (_window_dims * natus::math::vec2f_t(0.5f) ); } { natus::device::layouts::three_mouse_t mouse( _dev_mouse ) ; _cur_mouse_nrm = mouse.get_local() * natus::math::vec2f_t( 2.0f ) - natus::math::vec2f_t( 1.0f ) ; } // rotate if( _mouse_control ) { natus::device::layouts::three_mouse_t mouse( _dev_mouse ) ; static natus::math::vec2f_t old = mouse.get_global() * natus::math::vec2f_t( 2.0f ) - natus::math::vec2f_t( 1.0f ) ; natus::math::vec2f_t const dif = (mouse.get_global()* natus::math::vec2f_t( 2.0f ) - natus::math::vec2f_t( 1.0f )) - old ; old = mouse.get_global() * natus::math::vec2f_t( 2.0f ) - natus::math::vec2f_t( 1.0f ) ; if( mouse.is_pressing(natus::device::layouts::three_mouse::button::left ) ) { _left_down = true ; } else if( mouse.is_released(natus::device::layouts::three_mouse::button::left ) ) { _left_down = false ; } if( mouse.is_pressing(natus::device::layouts::three_mouse::button::right ) ) { auto old2 = _camera_0->get_transformation() ; auto trafo = old2.rotate_by_angle_fr( natus::math::vec3f_t( -dif.y()*2.0f, dif.x()*2.0f, 0.0f ) ) ; _camera_0->set_transformation( trafo ) ; _right_down = true ; } else if( mouse.is_released(natus::device::layouts::three_mouse::button::right ) ) { _right_down = false ; } } // translate if( _mouse_control ) { natus::math::vec3f_t translate ; if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::a ) == natus::device::components::key_state::pressing ) { translate += natus::math::vec3f_t(-10.0f, 0.0f, 0.0f ) ; } if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::s ) == natus::device::components::key_state::pressing ) { translate += natus::math::vec3f_t(0.0f, 0.0f, -10.0f) ; } if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::d ) == natus::device::components::key_state::pressing ) { translate += natus::math::vec3f_t( 10.0f, 0.0f, 0.0f ) ; } if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::w ) == natus::device::components::key_state::pressing ) { translate += natus::math::vec3f_t(0.0f, 0.0f, 10.0f ) ; } if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::q ) == natus::device::components::key_state::pressing ) { translate += natus::math::vec3f_t(0.0f, -10.0f, 0.0f ) ; } if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::e ) == natus::device::components::key_state::pressing ) { translate += natus::math::vec3f_t(0.0f, 10.0f, 0.0f ) ; } auto trafo = _camera_0->get_transformation() ; trafo.translate_fr( translate ) ; _camera_0->set_transformation( trafo ) ; } } //**************************************************************** void_t app_essentials::on_update( natus::application::app_t::update_data_in_t ) noexcept { // check shader file changes // and recompile and set new shaders // @todo can be put into a task { _shader_mon->for_each_and_swap( [&] ( natus::io::location_cref_t loc, natus::io::monitor_t::notify const ) { natus::nsl::database_t::symbols_t config_symbols ; natus::log::global_t::status( "[simple_app_essentials] : File changed: " + loc.as_string() ) ; natus::format::module_registry_res_t mod_reg = natus::format::global_t::registry() ; auto fitem2 = mod_reg->import_from( loc, _db ) ; natus::format::nsl_item_res_t ii = fitem2.get() ; if( ii.is_valid() ) _ndb->insert( std::move( std::move( ii->doc ) ), config_symbols ) ; for( auto const & s : config_symbols ) { natus::nsl::generatable_t res = natus::nsl::dependency_resolver_t().resolve( _ndb, s ) ; if( res.missing.size() != 0 ) { natus::log::global_t::warning( "[simple_app_essentials] : We have missing shader symbols." ) ; for( auto const& m : res.missing ) { natus::log::global_t::warning( m.expand() ) ; } } auto const sc = natus::graphics::nsl_bridge_t().create( natus::nsl::generator_t( std::move( res ) ).generate() ).set_name( s.expand() ) ; _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.configure( sc ) ; } ) ; } } ) ; } } //**************************************************************** void_t app_essentials::on_graphics_begin( natus::application::app_t::render_data_in_t ) noexcept { { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.push( _rs ) ; } ) ; } _pr->set_view_proj( _camera_0->mat_view(), _camera_0->mat_proj() ) ; _lr3->set_view_proj( _camera_0->mat_view(), _camera_0->mat_proj() ) ; _pr3->set_view_proj( _camera_0->mat_view(), _camera_0->mat_proj() ) ; if( _has_font ) _tr->set_view_proj( _camera_0->mat_view(), _camera_0->mat_proj() ) ; } //**************************************************************** void_t app_essentials::on_graphics_end( size_t const num_layers, per_layer_funk_t funk ) noexcept { // draw extend if( _draw_debug ) { auto const cpos = _camera_0->get_position().xy() ; natus::math::vec2f_t p0 = cpos + _extend * natus::math::vec2f_t(-0.5f,-0.5f) ; natus::math::vec2f_t p1 = cpos + _extend * natus::math::vec2f_t(-0.5f,+0.5f) ; natus::math::vec2f_t p2 = cpos + _extend * natus::math::vec2f_t(+0.5f,+0.5f) ; natus::math::vec2f_t p3 = cpos + _extend * natus::math::vec2f_t(+0.5f,-0.5f) ; natus::math::vec4f_t color0( 1.0f, 1.0f, 1.0f, 0.0f ) ; natus::math::vec4f_t color1( 1.0f, 1.0f, 1.0f, 1.0f ) ; _pr->draw_rect( num_layers-2, p0, p1, p2, p3, color0, color1 ) ; } // render all { if( _has_font ) _tr->prepare_for_rendering() ; _pr->prepare_for_rendering() ; _lr3->prepare_for_rendering() ; _pr3->prepare_for_rendering() ; _pr3->render() ; _lr3->render() ; for( size_t i=0; i<num_layers; ++i ) { _pr->render( i ) ; if( _has_font ) _tr->render( i ) ; funk( i ) ; } } { _graphics.for_each( [&]( natus::graphics::async_view_t a ) { a.pop( natus::graphics::backend::pop_type::render_state ) ; } ) ; } } //**************************************************************** void_t app_essentials::on_graphics_end( size_t const num_layers ) noexcept { this_t::on_graphics_end( num_layers, [&]( size_t const ){} ) ; } //**************************************************************** bool_t app_essentials::on_tool( natus::application::app::tool_data_ref_t, bool_t const default_ui ) noexcept { if( !this_t::do_tool() ) { if( default_ui ) { natus::tool::custom_imgui_widgets::text_overlay( "nouioverlay##simple_app_essentials", "Press F2 for UI" ) ; } return false ; } if( default_ui ) { ImGui::Begin( "App Essentials Controls##simple_app_essentials" ) ; { float_t data[2] = {_extend.x(), _extend.y() } ; ImGui::SliderFloat2( "Extent##simple_app_essentials", data, 0.0f, 1000.0f, "%f" ) ; _extend.x( data[0] ) ; _extend.y( data[1] ) ; } { ImGui::Checkbox( "Draw Debug##simple_app_essentials", &_draw_debug ) ; } { ImGui::Text( "mx: %f, my: %f", _window_dims.x(), _window_dims.y() ) ; } { ImGui::Text( "mx: %f, my: %f", _cur_mouse.x(), _cur_mouse.y() ) ; } { if( ImGui::Checkbox( "ImGui Demo Window##simple_app_essentials", &_show_demo ) ){} if( _show_demo ) ImGui::ShowDemoWindow( &_show_demo ) ; } ImGui::End() ; } return true ; } //**************************************************************** void_t app_essentials::on_shutdown( void_t ) noexcept { _pr3->release() ; _lr3->release() ; _pr->release() ; _tr->release() ; _tr = natus::gfx::text_render_2d_res_t() ; _db = natus::io::database_res_t() ; _ndb = natus::nsl::database_res_t() ; _shader_mon = natus::io::monitor_res_t() ; _dev_mouse = natus::device::three_device_res_t() ; _dev_ascii = natus::device::ascii_device_res_t() ; }
b581da796b9a48ba02e5d8cbbb4263e4cb087e8d
7e06d07b3d9752b1a12874c9f647cfe809b926f8
/112_Path_Sum/112_Path_Sum.cc
dbfa3bbe766ffbec61a9e8a2c58957bc955f0b67
[]
no_license
wushangzhen/LeetCode-Practice
e44363f1e0ff72b80e060ac39984fe469dba04d8
afba5a3dc84e8615685f893b8394b5137e9a42b6
refs/heads/master
2020-03-09T18:07:32.825047
2019-09-17T00:14:40
2019-09-17T00:14:40
128,924,476
3
1
null
null
null
null
UTF-8
C++
false
false
800
cc
#include <unordered_set> #include <iostream> #include <queue> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool hasPathSum(TreeNode* root, int sum) { if (!root) return false; if (root->left == NULL && root->right == NULL) { return root->val == sum; } return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } int main() { TreeNode node0(4); TreeNode node1(2); TreeNode node2(7); TreeNode node3(1); TreeNode node4(3); TreeNode node5(6); TreeNode node6(9); node0.left = &node1; node0.right= &node2; node1.left= &node3; node1.right= &node4; node2.left= &node5; node2.right= &node6; std::cout << hasPathSum(&node0, 7) << std::endl; }
882c7e68f73cd93bae70caae4bce60150f04a1c1
d5b6115c64e556f67cf35c6078bf8469c7eb8662
/Maximum in table.cpp
4a16b966427b4221295d5c0e71a1f1a47d9d4c7f
[]
no_license
vanson9x/olympic-C-
1ceaaca7df21d5b301ac6de37e0a71f85bd716cd
93ecb8797bbfe3f01cf7325cdd70e5eb4b57d11e
refs/heads/master
2021-01-01T05:44:50.955811
2016-04-18T23:05:17
2016-04-18T23:05:17
56,548,220
0
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
#include<iostream> using namespace std; int main(){ int a[15][15],n; cin>>n; for(int i=1;i<=n;i++){ a[1][i]=1; a[i][1]=1; } for(int i=2;i<=n;i++) for(int j=2;j<=n;j++) a[i][j]=a[i-1][j]+a[i][j-1]; cout<<a[n][n]; }
4deaaa1feed511aebf3fb46ae03d5f7a8ce2e5bb
b092e85f26168dd84bdd1b8b7ef06e11f3d615a3
/universidade.h
bdc7e71dd4bb2216f66760faee74702a54581da2
[]
no_license
jpmaciels/EstudoTecProg
ed7b458e34f6d822f23babd13495771688fc9d1f
5e4e59f49622ab25ebc9bcc99661a383324b91db
refs/heads/master
2023-08-15T23:10:06.722502
2021-09-28T18:02:39
2021-09-28T18:02:39
411,385,913
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
#pragma once #include "stdafx.h" #include "departamento.h" class Universidade{ private: char nomeU[30]; Departamento* departamento; public: Universidade(char* nomeUniv = ""); ~Universidade(); void setNome(char* nomeUniv); char* getNome(); void setDepartamento(Departamento* uD); };
a8fb1532d1b22849b79240488cfd38ed3cfd96d6
a42dc3085bd433302ad9cebdcb36bce560f886f1
/src/net.h
57bfe6342fbc3f0329edcb3a5b7bd8e5116c98f4
[ "MIT" ]
permissive
BINJITCOIN/BNJ-COIN
91db0ea105876ef1ee23a8c0d85b61894c2050e3
baa29a4c1c65f0fbfeeeb68a6b8db82250c564c6
refs/heads/main
2023-03-07T14:59:07.075785
2021-02-27T15:30:57
2021-02-27T15:30:57
317,928,653
0
2
null
null
null
null
UTF-8
C++
false
false
24,026
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin developers //Copyright (c) 2015-2020 The PIVX developers //Copyright (c) 2020 The BinJit developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NET_H #define BITCOIN_NET_H #include "bloom.h" #include "compat.h" #include "fs.h" #include "hash.h" #include "limitedmap.h" #include "mruset.h" #include "netaddress.h" #include "protocol.h" #include "random.h" #include "streams.h" #include "sync.h" #include "uint256.h" #include "utilstrencodings.h" #include <deque> #include <stdint.h> #ifndef WIN32 #include <arpa/inet.h> #endif #include <boost/signals2/signal.hpp> class CAddrMan; class CBlockIndex; class CScheduler; class CNode; namespace boost { class thread_group; } // namespace boost /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */ static const int PING_INTERVAL = 2 * 60; /** Time after which to disconnect, after waiting for a ping response (or inactivity). */ static const int TIMEOUT_INTERVAL = 20 * 60; /** The maximum number of entries in an 'inv' protocol message */ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of entries in a locator */ static const unsigned int MAX_LOCATOR_SZ = 101; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024; /** Maximum length of strSubVer in `version` message */ static const unsigned int MAX_SUBVERSION_LENGTH = 256; /** -listen default */ static const bool DEFAULT_LISTEN = true; /** -upnp default */ #ifdef USE_UPNP static const bool DEFAULT_UPNP = USE_UPNP; #else static const bool DEFAULT_UPNP = false; #endif /** The maximum number of entries in mapAskFor */ static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ; /** The maximum number of peer connections to maintain. */ static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125; /** Disconnected peers are added to setOffsetDisconnectedPeers only if node has less than ENOUGH_CONNECTIONS */ #define ENOUGH_CONNECTIONS 2 /** Maximum number of peers added to setOffsetDisconnectedPeers before triggering a warning */ #define MAX_TIMEOFFSET_DISCONNECTIONS 16 static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK; unsigned int ReceiveFloodSize(); unsigned int SendBufferSize(); void AddOneShot(std::string strDest); bool RecvLine(SOCKET hSocket, std::string& strLine); void AddressCurrentlyConnected(const CService& addr); CNode* FindNode(const CNetAddr& ip); CNode* FindNode(const CSubNet& subNet); CNode* FindNode(const std::string& addrName); CNode* FindNode(const CService& ip); CNode* ConnectNode(CAddress addrConnect, const char* pszDest = NULL, bool fCountFailure = false); bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant* grantOutbound = NULL, const char* strDest = NULL, bool fOneShot = false); void MapPort(bool fUseUPnP); unsigned short GetListenPort(); bool BindListenPort(const CService& bindAddr, std::string& strError, bool fWhitelisted = false); void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler); bool StopNode(); void SocketSendData(CNode* pnode); void CheckOffsetDisconnectedPeers(const CNetAddr& ip); typedef int NodeId; // Signals for message handling struct CNodeSignals { boost::signals2::signal<int()> GetHeight; boost::signals2::signal<bool(CNode*)> ProcessMessages; boost::signals2::signal<bool(CNode*, bool)> SendMessages; boost::signals2::signal<void(NodeId, const CNode*)> InitializeNode; boost::signals2::signal<void(NodeId)> FinalizeNode; }; CNodeSignals& GetNodeSignals(); enum { LOCAL_NONE, // unknown LOCAL_IF, // address a local interface listens on LOCAL_BIND, // address explicit bound to LOCAL_UPNP, // address reported by UPnP LOCAL_MANUAL, // address explicitly specified (-externalip=) LOCAL_MAX }; bool IsPeerAddrLocalGood(CNode* pnode); void AdvertiseLocal(CNode* pnode); void SetLimited(enum Network net, bool fLimited = true); bool IsLimited(enum Network net); bool IsLimited(const CNetAddr& addr); bool AddLocal(const CService& addr, int nScore = LOCAL_NONE); bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE); bool RemoveLocal(const CService& addr); bool SeenLocal(const CService& addr); bool IsLocal(const CService& addr); bool GetLocal(CService& addr, const CNetAddr* paddrPeer = NULL); bool IsReachable(enum Network net); bool IsReachable(const CNetAddr& addr); CAddress GetLocalAddress(const CNetAddr* paddrPeer = NULL); bool validateMasternodeIP(const std::string& addrStr); // valid, reachable and routable address extern bool fDiscover; extern bool fListen; extern ServiceFlags nLocalServices; extern uint64_t nLocalHostNonce; extern CAddrMan addrman; extern int nMaxConnections; extern std::vector<CNode*> vNodes; extern RecursiveMutex cs_vNodes; extern std::map<CInv, CDataStream> mapRelay; extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration; extern RecursiveMutex cs_mapRelay; extern limitedmap<CInv, int64_t> mapAlreadyAskedFor; extern std::vector<std::string> vAddedNodes; extern RecursiveMutex cs_vAddedNodes; extern NodeId nLastNodeId; extern RecursiveMutex cs_nLastNodeId; /** Subversion as sent to the P2P network in `version` messages */ extern std::string strSubVersion; struct LocalServiceInfo { int nScore; int nPort; }; extern RecursiveMutex cs_mapLocalHost; extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost; class CNodeStats { public: NodeId nodeid; ServiceFlags nServices; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; int64_t nTimeOffset; std::string addrName; int nVersion; std::string cleanSubVer; bool fInbound; int nStartingHeight; uint64_t nSendBytes; uint64_t nRecvBytes; bool fWhitelisted; double dPingTime; double dPingWait; std::string addrLocal; }; class CNetMessage { public: bool in_data; // parsing header (false) or data (true) CDataStream hdrbuf; // partially received header CMessageHeader hdr; // complete header unsigned int nHdrPos; CDataStream vRecv; // received message data unsigned int nDataPos; int64_t nTime; // time (in microseconds) of message receipt. CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) { hdrbuf.resize(24); in_data = false; nHdrPos = 0; nDataPos = 0; nTime = 0; } bool complete() const { if (!in_data) return false; return (hdr.nMessageSize == nDataPos); } void SetVersion(int nVersionIn) { hdrbuf.SetVersion(nVersionIn); vRecv.SetVersion(nVersionIn); } int readHeader(const char* pch, unsigned int nBytes); int readData(const char* pch, unsigned int nBytes); }; typedef enum BanReason { BanReasonUnknown = 0, BanReasonNodeMisbehaving = 1, BanReasonManuallyAdded = 2 } BanReason; class CBanEntry { public: static const int CURRENT_VERSION=1; int nVersion; int64_t nCreateTime; int64_t nBanUntil; uint8_t banReason; CBanEntry() { SetNull(); } CBanEntry(int64_t nCreateTimeIn) { SetNull(); nCreateTime = nCreateTimeIn; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(nVersion); READWRITE(nCreateTime); READWRITE(nBanUntil); READWRITE(banReason); } void SetNull() { nVersion = CBanEntry::CURRENT_VERSION; nCreateTime = 0; nBanUntil = 0; banReason = BanReasonUnknown; } std::string banReasonToString() { switch (banReason) { case BanReasonNodeMisbehaving: return "node misbehaving"; case BanReasonManuallyAdded: return "manually added"; default: return "unknown"; } } }; typedef std::map<CSubNet, CBanEntry> banmap_t; /** Information about a peer */ class CNode { public: // socket ServiceFlags nServices; ServiceFlags nServicesExpected; SOCKET hSocket; CDataStream ssSend; size_t nSendSize; // total size of all vSendMsg entries size_t nSendOffset; // offset inside the first vSendMsg already sent uint64_t nSendBytes; std::deque<CSerializeData> vSendMsg; RecursiveMutex cs_vSend; std::deque<CInv> vRecvGetData; std::deque<CNetMessage> vRecvMsg; RecursiveMutex cs_vRecvMsg; uint64_t nRecvBytes; int nRecvVersion; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; int64_t nTimeOffset; CAddress addr; std::string addrName; CService addrLocal; int nVersion; // strSubVer is whatever byte array we read from the wire. However, this field is intended // to be printed out, displayed to humans in various forms and so on. So we sanitize it and // store the sanitized version in cleanSubVer. The original should be used when dealing with // the network or wire types and the cleaned string used when displayed or logged. std::string strSubVer, cleanSubVer; bool fWhitelisted; // This peer can bypass DoS banning. bool fOneShot; bool fClient; bool fInbound; bool fNetworkNode; bool fSuccessfullyConnected; bool fDisconnect; // We use fRelayTxes for two purposes - // a) it allows us to not relay tx invs before receiving the peer's version message // b) the peer may tell us in their version message that we should not relay tx invs // until they have initialized their bloom filter. bool fRelayTxes; CSemaphoreGrant grantOutbound; RecursiveMutex cs_filter; CBloomFilter* pfilter; int nRefCount; NodeId id; protected: // Denial-of-service detection/prevention // Key is IP address, value is banned-until-time static banmap_t setBanned; static RecursiveMutex cs_setBanned; static bool setBannedIsDirty; std::vector<std::string> vecRequestsFulfilled; //keep track of what client has asked for // Whitelisted ranges. Any node connecting from these is automatically // whitelisted (as well as those connecting to whitelisted binds). static std::vector<CSubNet> vWhitelistedRange; static RecursiveMutex cs_vWhitelistedRange; // Basic fuzz-testing void Fuzz(int nChance); // modifies ssSend public: uint256 hashContinue; int nStartingHeight; // flood relay std::vector<CAddress> vAddrToSend; mruset<CAddress> setAddrKnown; bool fGetAddr; std::set<uint256> setKnown; // inventory based relay mruset<CInv> setInventoryKnown; std::vector<CInv> vInventoryToSend; RecursiveMutex cs_inventory; std::multimap<int64_t, CInv> mapAskFor; std::vector<uint256> vBlockRequested; // Ping time measurement: // The pong reply we're expecting, or 0 if no pong expected. uint64_t nPingNonceSent; // Time (in usec) the last ping was sent, or 0 if no ping was ever sent. int64_t nPingUsecStart; // Last measured round-trip time. int64_t nPingUsecTime; // Whether a ping is requested. bool fPingQueued; CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn = false); ~CNode(); private: // Network usage totals static RecursiveMutex cs_totalBytesRecv; static RecursiveMutex cs_totalBytesSent; static uint64_t nTotalBytesRecv; static uint64_t nTotalBytesSent; CNode(const CNode&); void operator=(const CNode&); public: NodeId GetId() const { return id; } int GetRefCount() { assert(nRefCount >= 0); return nRefCount; } // requires LOCK(cs_vRecvMsg) unsigned int GetTotalRecvSize() { unsigned int total = 0; for (const CNetMessage& msg : vRecvMsg) total += msg.vRecv.size() + 24; return total; } // requires LOCK(cs_vRecvMsg) bool ReceiveMsgBytes(const char* pch, unsigned int nBytes); // requires LOCK(cs_vRecvMsg) void SetRecvVersion(int nVersionIn) { nRecvVersion = nVersionIn; for (CNetMessage& msg : vRecvMsg) msg.SetVersion(nVersionIn); } CNode* AddRef() { nRefCount++; return this; } void Release() { nRefCount--; } void AddAddressKnown(const CAddress& addr) { setAddrKnown.insert(addr); } void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand) { // Known checking here is only to save space from duplicates. // SendMessages will filter it again for knowns that were added // after addresses were pushed. if (_addr.IsValid() && !setAddrKnown.count(_addr)) { if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) { vAddrToSend[insecure_rand.randrange(vAddrToSend.size())] = _addr; } else { vAddrToSend.push_back(_addr); } } } void AddInventoryKnown(const CInv& inv) { { LOCK(cs_inventory); setInventoryKnown.insert(inv); } } void PushInventory(const CInv& inv) { { LOCK(cs_inventory); if (!setInventoryKnown.count(inv)) vInventoryToSend.push_back(inv); } } void AskFor(const CInv& inv); // TODO: Document the postcondition of this function. Is cs_vSend locked? void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend); // TODO: Document the precondition of this function. Is cs_vSend locked? void AbortMessage() UNLOCK_FUNCTION(cs_vSend); // TODO: Document the precondition of this function. Is cs_vSend locked? void EndMessage() UNLOCK_FUNCTION(cs_vSend); void PushVersion(); void PushMessage(const char* pszCommand) { try { BeginMessage(pszCommand); EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1> void PushMessage(const char* pszCommand, const T1& a1) { try { BeginMessage(pszCommand); ssSend << a1; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2) { try { BeginMessage(pszCommand); ssSend << a1 << a2; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10, const T11& a11) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10 << a11; EndMessage(); } catch (...) { AbortMessage(); throw; } } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10, const T11& a11, const T12& a12) { try { BeginMessage(pszCommand); ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10 << a11 << a12; EndMessage(); } catch (...) { AbortMessage(); throw; } } bool HasFulfilledRequest(std::string strRequest) { for (std::string& type : vecRequestsFulfilled) { if (type == strRequest) return true; } return false; } void ClearFulfilledRequest(std::string strRequest) { std::vector<std::string>::iterator it = vecRequestsFulfilled.begin(); while (it != vecRequestsFulfilled.end()) { if ((*it) == strRequest) { vecRequestsFulfilled.erase(it); return; } ++it; } } void FulfilledRequest(std::string strRequest) { if (HasFulfilledRequest(strRequest)) return; vecRequestsFulfilled.push_back(strRequest); } bool IsSubscribed(unsigned int nChannel); void Subscribe(unsigned int nChannel, unsigned int nHops = 0); void CancelSubscribe(unsigned int nChannel); void CloseSocketDisconnect(); bool DisconnectOldProtocol(int nVersionRequired, std::string strLastCommand = ""); // Denial-of-service detection/prevention // The idea is to detect peers that are behaving // badly and disconnect/ban them, but do it in a // one-coding-mistake-won't-shatter-the-entire-network // way. // IMPORTANT: There should be nothing I can give a // node that it will forward on that will make that // node's peers drop it. If there is, an attacker // can isolate a node and/or try to split the network. // Dropping a node for sending stuff that is invalid // now but might be valid in a later version is also // dangerous, because it can cause a network split // between nodes running old code and nodes running // new code. static void ClearBanned(); // needed for unit testing static bool IsBanned(CNetAddr ip); static bool IsBanned(CSubNet subnet); static void Ban(const CNetAddr &ip, const BanReason &banReason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false); static void Ban(const CSubNet &subNet, const BanReason &banReason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false); static bool Unban(const CNetAddr &ip); static bool Unban(const CSubNet &ip); static void GetBanned(banmap_t &banmap); static void SetBanned(const banmap_t &banmap); //!check is the banlist has unwritten changes static bool BannedSetIsDirty(); //!set the "dirty" flag for the banlist static void SetBannedSetDirty(bool dirty=true); //!clean unused entires (if bantime has expired) static void SweepBanned(); void copyStats(CNodeStats& stats); static bool IsWhitelistedRange(const CNetAddr& ip); static void AddWhitelistedRange(const CSubNet& subnet); // Network stats static void RecordBytesRecv(uint64_t bytes); static void RecordBytesSent(uint64_t bytes); static uint64_t GetTotalBytesRecv(); static uint64_t GetTotalBytesSent(); }; class CExplicitNetCleanup { public: static void callCleanup(); }; class CTransaction; void RelayTransaction(const CTransaction& tx); void RelayTransaction(const CTransaction& tx, const CDataStream& ss); void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll = false); void RelayInv(CInv& inv); /** Access to the (IP) address database (peers.dat) */ class CAddrDB { private: fs::path pathAddr; public: CAddrDB(); bool Write(const CAddrMan& addr); bool Read(CAddrMan& addr); bool Read(CAddrMan& addr, CDataStream& ssPeers); }; /** Access to the banlist database (banlist.dat) */ class CBanDB { private: fs::path pathBanlist; public: CBanDB(); bool Write(const banmap_t& banSet); bool Read(banmap_t& banSet); }; void DumpBanlist(); struct AddedNodeInfo { std::string strAddedNode; CService resolvedAddress; bool fConnected; bool fInbound; }; std::vector<AddedNodeInfo> GetAddedNodeInfo(); #endif // BITCOIN_NET_H
76161bb752c313d545fc76b4ccdf39b03b9b358b
b26935cdbee8187d6638a792134eaa9e01c22983
/src/c_fl_box.cpp
3af626f2543b96d4a6cb595b82c2b3c7ff110147
[ "Unlicense" ]
permissive
micahwelf/FLTK-Ada
3a46b3e6bceec33cd6b4e79bcdc78eae303de5b1
83e0c58ea98e5ede2cbbb158b42eae44196c3ba7
refs/heads/master
2020-09-22T05:55:15.451681
2018-05-21T04:18:28
2018-05-21T04:18:28
225,074,301
3
0
null
null
null
null
UTF-8
C++
false
false
1,403
cpp
#include <FL/Fl_Box.H> #include "c_fl_box.h" #include "c_fl_type.h" class My_Box : public Fl_Box { public: using Fl_Box::Fl_Box; friend void box_set_draw_hook(BOX n, void * d); friend void fl_box_draw(BOX n); friend void box_set_handle_hook(BOX n, void * h); friend int fl_box_handle(BOX n, int e); protected: void draw(); void real_draw(); int handle(int e); int real_handle(int e); d_hook_p draw_hook; h_hook_p handle_hook; }; void My_Box::draw() { (*draw_hook)(this->user_data()); } void My_Box::real_draw() { Fl_Box::draw(); } int My_Box::handle(int e) { return (*handle_hook)(this->user_data(), e); } int My_Box::real_handle(int e) { return Fl_Box::handle(e); } void box_set_draw_hook(BOX n, void * d) { reinterpret_cast<My_Box*>(n)->draw_hook = reinterpret_cast<d_hook_p>(d); } void fl_box_draw(BOX n) { reinterpret_cast<My_Box*>(n)->real_draw(); } void box_set_handle_hook(BOX n, void * h) { reinterpret_cast<My_Box*>(n)->handle_hook = reinterpret_cast<h_hook_p>(h); } int fl_box_handle(BOX n, int e) { return reinterpret_cast<My_Box*>(n)->real_handle(e); } BOX new_fl_box(int x, int y, int w, int h, char* label) { My_Box *b = new My_Box(x, y, w, h, label); return b; } void free_fl_box(BOX b) { delete reinterpret_cast<My_Box*>(b); }
2f51d582b2d1f26190709a5b08db3156fcb7cfea
891938160eebab49fef043811bf7eb3f790ac9b7
/src/hex/constants.h
184230a91d0253f3e8d6ba7c5a9612c42cc52e3d
[]
no_license
seanemoon/hexagons
7949eeaf0fca51678aee48f337937459ed1d040e
99f98615f3f46a6430f7369d19827e49c49a7081
refs/heads/master
2021-01-17T18:23:43.447690
2016-08-15T03:36:41
2016-08-15T03:36:41
65,259,477
0
0
null
null
null
null
UTF-8
C++
false
false
1,847
h
#ifndef HEX_CONSTANTS_H_ #define HEX_CONSTANTS_H_ #include <cmath> // We only consider regular hexagons here; any reference to a hexagon is // implicitly a reference to a regular hexagon. We use the definitions below // when working with hexagons. We choose to use the maximal radius (R) as the // base unit. That is, any quantities with unspecified units are assumed to be // in units of maximal radius (R). // // R = maximal radius or circumradius (base unit) // D = maximal diameter // = 2R // t = side length // = R // r = minimal radius or inradius // = cos(pi/6)*R = (sqrt(3)/2)*R // // _-_ --- --- // _- -_ | | // _- -_ | | // * * | R --- | // | | | | | // | | | | | // | | --- | t=R | D=2R // | | | | // | | | | // * * --- | // -_ _- | // -_ _- | // -_- --- // // |--------| // r // // |-----------------| // d=2r static const double kMaximalRadius = 1.0; // R static const double kMaximalDiameter = 2.0; // D static const double kSideLength = 1.0; // t static const double kMinimalRadius = std::cos(M_PI/6.0); // r static const double kMinimalDiameter = 2.0 * kMinimalRadius; // d static const double kVerticalSpacing = 1.5; // v static const double kHorizontalSpacing = kMinimalDiameter; // h #endif // HEX_CONSTANTS_H_
9e70321ae8ec6519f40e003a511ee2566b58a600
46b020aa85b2ffbc8a47721c3fb774bfc7d81d64
/CannyDetector/CannyDetector/IImgWriter.h
fd9c02529a3746b29e4c9f8af18efd8927f219ea
[ "MIT" ]
permissive
TeodorKawecki/CUDA-Canny-edge-detector
ec3ce02da1c169951fac58924627739cdd63452c
2a54fed6ba26931f1cd795c6fc1bf0958269e679
refs/heads/master
2020-06-23T16:56:36.703077
2019-07-24T16:22:42
2019-07-24T17:57:56
198,688,014
0
1
null
null
null
null
UTF-8
C++
false
false
177
h
#pragma once #include<string> #include "IImage.h" class IImgWriter { public: virtual void WriteImage(const std::string &path, std::shared_ptr<IImage> imagePtr) const = 0; };
dae0b10b1fff586df0f99007741f6faa170dc60a
9467e2502183e843a67736800199e31674b1d8f6
/HybridCLRData/LocalIl2CppData-OSXEditor/il2cpp/libil2cpp/os/c-api/TimeZone.cpp
ea3e136678baa354dce177c6dc6475faaa80b2ea
[ "Apache-2.0" ]
permissive
yimengfan/BDFramework.Core
3a046fcd755a84ba55d648dd3ad52c37a1cc1a04
81380fce8e84367f912777717665b53f074ab617
refs/heads/master
2023-09-04T10:08:47.644992
2023-07-05T16:22:11
2023-07-05T16:22:11
85,928,537
2,421
497
Apache-2.0
2023-03-21T06:56:21
2017-03-23T09:03:48
C#
UTF-8
C++
false
false
616
cpp
#include "os/c-api/il2cpp-config-platforms.h" #if !IL2CPP_TINY_WITHOUT_DEBUGGER #include "os/TimeZone.h" #include "Allocator.h" #include <string> extern "C" { int32_t UnityPalGetTimeZoneData(int32_t year, int64_t data[4], const char* names[2]) { std::string namesBuffer[2]; bool dst_inverted; int32_t result = il2cpp::os::TimeZone::GetTimeZoneData(year, data, namesBuffer, &dst_inverted); names[0] = Allocator::CopyToAllocatedStringBuffer(namesBuffer[0]); names[1] = Allocator::CopyToAllocatedStringBuffer(namesBuffer[1]); return result; } } #endif
93d060af5fa315fb56f628d112b508c010aa6ae3
e24e271bdcfd37a7a03ad65b6ad76a118c80b4cd
/hackerrank/crossword.cpp
178a6376cdd83a043b99da26ab2a73be534e4f52
[]
no_license
ArchitKumar1/Competitive_Programming
ed7d2389f2fade35cf8a06f8dc48494c4f7c2f66
cb064631742cfe10a956179cf4e8544eab0db516
refs/heads/master
2021-06-29T22:37:09.640350
2021-01-16T09:48:09
2021-01-16T09:48:09
204,568,696
0
0
null
null
null
null
UTF-8
C++
false
false
2,868
cpp
#include<bits/stdc++.h> using namespace std; template<class T> ostream& operator<<(ostream &os,vector<T> V){ os<<"[ ";for(auto v:V)os<<v<<" ";return os<<"]"; } template<class L,class R> ostream& operator<<(ostream &os,pair<L,R> P){ return os<<"("<<P.first<<","<<P.second<<")"; } #define TRACE #ifdef TRACE #define trace(...) __f(#__VA_ARGS__,__VA_ARGS__) template<typename Arg1> void __f(const char* name,Arg1&& arg1){ cout<<name<<" : "<<arg1<<endl; } template<typename Arg1,typename... Args> void __f(const char* names,Arg1&& arg1,Args&&... args){ const char* comma=strchr(names+1,',');cout.write(names,comma-names)<<" : "<<arg1<<" | ";__f(comma+1,args...); } #else #define trace(...) 1 #endif #define ALL(x) x.begin(),x.end() #define LL long long int #define PB push_back #define EB emplace_back #define F first #define S second #define endl "\n" #define FASTIO ios_base::sync_with_stdio(false); cin.tie(NULL); #define TC int t; cin >> t;while(t--) #define forn(i,n) for(int i=0;i<n;i++) const int mod = pow(10,9) +7; const int inf = 2e9; const LL linf = 2e18; const double eps = 1e-9; ///////////////////////////// const int N = 10; int M; vector<string> cross(10); vector<string> allwords; int dx[4] = {0,1,0,-1}; int dy[4] ={1,0,-1,0}; inline bool safe(int i,int j){ return i>=0 && i<M && j<M && j>=0; } int getlen(int i,int j,int dir,vector<string> &cross){ int cnt = 1; while(safe(i+dx[dir],j +dy[dir]) && cross[i][j] == '-'){ cnt++; i = i + dx[dir]; j = j + dy[dir]; } return cnt; } int checknode(int i,int j,vector<string>&cross){ vector<int>temp(4); forn(k,4){ temp[k] = getlen(i,j,k,cross); } sort(ALL(temp)); return (temp[0] == 1 && temp[1] == 0 && temp[2] ==0 ); } void solve(int curr,vector<string> cross){ if(curr== M){ cout << cross << endl; return; } forn(i,N){ forn(j,N){ if(cross[i][j] == '-'){ if(checknode(i,j,cross)){ int posslen = INT_MIN; int dirtogo; forn(k,4){ posslen =getlen(i,j,k,cross); } if(posslen = allwords[curr].size()){ } } } } } } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif for(int i=0;i<N;i++){ cin >> cross[i]; } string words; getline(cin,words); string temp =""; for(char c : words){ if(c!=';'){ temp+= c; }else{ allwords.PB(temp); temp =""; } } if(temp!=""){ allwords.PB(temp); } M = allwords.size(); solve(0,cross); return 0; }
91b313b7f0fb6df4a9182568cff75a6e18bfe0cf
76763c51ed3049882c1a30cc64d3a1a9f37d0cb1
/Structural Pattern/Proxy/CommunicationProxy.cpp
fd9509ca939e24d5eda35a61d84db0ecee08482b
[]
no_license
tolerance93/Design-Patterns-in-cpp
e23636a0dc0d83ed0981c886df629d8b52be2b68
ac05ea2ac981c6f8727a3517c1453ec07da68399
refs/heads/master
2023-04-06T01:07:53.681244
2021-05-08T09:23:21
2021-05-08T09:23:21
331,330,814
0
0
null
null
null
null
UTF-8
C++
false
false
1,660
cpp
#include "stdafx.h" struct Pingable { virtual wstring ping(const wstring& message) = 0; }; /** * local * 매 응답마다 새로운 문자열을 생성: 웹서비스의 동작 방식을 따라한 것 */ struct Pong : Pingable { wstring ping(const wstring& message) override { return message + L" pong"; } }; #include <cpprest/http_client.h> #include <cpprest/filestream.h> using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams /** * 커뮤니케이션 프록시. 객체의 물리적 위치를 바꾸면서도 API를 거의 동일하게 유지할 수 있게 해줌. * 프록시로 구현된 API들은 REST API와 같은 원격 서비스의 투영일 뿐이다. */ struct RemotePong : Pingable { wstring ping(const wstring& message) override { wstring result; http_client client(U("http://localhost:64959/")); uri_builder builder(U("/api/values/")); builder.append(message); auto task = client.request(methods::GET, builder.to_string()) .then([=](http_response r) { return r.extract_string(); }); task.wait(); return task.get(); } }; void tryit(Pingable& pp) { wcout << pp.ping(L"ping") << "\n"; } int main() { RemotePong pp; for (size_t i = 0; i < 3; i++) { tryit(pp); } return 0; }
cdee43510301e61eb49299d02796cfbda8d09b9d
f77f2c2fd67faf1bfd983a4505286461d54c7aac
/Server/GameServer/Server/Packets/WGCallOfHumanHandler.cpp
6621af5975c9bbc94b599f4a7f74afe6014de5a8
[]
no_license
xu561865/TL_Server
7ec4662489906cb5f83067b96cd51b498681cdb1
48968a49a088762e8792f5af9e97c816ab574bfa
refs/heads/master
2021-01-10T01:20:33.129394
2016-04-04T16:06:19
2016-04-04T16:07:21
55,425,216
1
3
null
null
null
null
GB18030
C++
false
false
2,549
cpp
#include "stdafx.h" #include "Log.h" #include "ServerManager.h" #include "GamePlayer.h" #include "PlayerPool.h" #include "Scene.h" #include "Obj_Human.h" #include "SceneManager.h" #include "WGCallOfHuman.h" uint WGCallOfHumanHandler::Execute( WGCallOfHuman* pPacket, Player* pPlayer ) { __ENTER_FUNCTION PlayerID_t PlayerID = pPacket->GetCallOfTargetPlayerID(); GamePlayer* pGamePlayer = g_pPlayerPool->GetPlayer(PlayerID); if( pGamePlayer==NULL ) { g_pLog->FastSaveLog( LOG_FILE_3, "WGCallOfHumanHandler::Execute pGamePlayer==NULL" ); return PACKET_EXE_CONTINUE; } if (pGamePlayer->m_HumanGUID != pPacket->GetGUID()) { g_pLog->FastSaveLog( LOG_FILE_3, "WGCallOfHumanHandler::Execute pGamePlayer->m_HumanGUID[%d] != pPacket->GetGUID()[%d]",pGamePlayer->m_HumanGUID, pPacket->GetGUID()); return PACKET_EXE_CONTINUE; } Obj_Human* pHuman = pGamePlayer->GetHuman(); Assert( pHuman ); Scene* pScene = pHuman->getScene(); if( pScene==NULL ) { g_pLog->FastSaveLog( LOG_FILE_3, "WGCallOfHumanHandler::Execute pHuman->getScene() == NULL" ); return PACKET_EXE_CONTINUE; } if( pPlayer->IsServerPlayer() ) {//服务器收到世界服务器发来的数据 Assert( MyGetCurrentThreadID()==g_pServerManager->m_ThreadID ); pScene->SendPacket( pPacket, PlayerID ); g_pLog->FastSaveLog( LOG_FILE_1, "WGCallOfHumanHandler: CallerGUID=%u, SceneID=%d, Pos=%f,%f, Duration=%u", pPacket->GetCallOfInfo()->m_guidCaller, pPacket->GetCallOfInfo()->m_SceneID, pPacket->GetCallOfInfo()->m_Pos.m_fX, pPacket->GetCallOfInfo()->m_Pos.m_fZ, pPacket->GetCallOfInfo()->m_uDuration); return PACKET_EXE_NOTREMOVE; } else if( pPlayer->IsGamePlayer() ) {//场景收到Cache里的消息 if(MyGetCurrentThreadID()!=pScene->m_ThreadID) { Assert( FALSE && "WGCallOfHumanHandler::Execute MyGetCurrentThreadID()!=pScene->m_ThreadID"); return PACKET_EXE_CONTINUE; } const _CALLOF_INFO *pCallOfInfo = pPacket->GetCallOfInfo(); pHuman->SetCallOfInfo(pCallOfInfo); g_pLog->FastSaveLog( LOG_FILE_1, "WGCallOfHumanHandler: CallerGUID=%u, SceneID=%d, Pos=%f,%f, Duration=%u", pPacket->GetCallOfInfo()->m_guidCaller, pPacket->GetCallOfInfo()->m_SceneID, pPacket->GetCallOfInfo()->m_Pos.m_fX, pPacket->GetCallOfInfo()->m_Pos.m_fZ, pPacket->GetCallOfInfo()->m_uDuration); return PACKET_EXE_CONTINUE ; } else { Assert(FALSE && "WGCallOfHumanHandler::Execute (!pPlayer->IsServerPlayer() && !pPlayer->IsGamePlayer())"); } return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
f3a29c2703982cb0fd14f51b0a4a376d810e4990
3ce92998b92d423306f0b7d81e7e968c259ca46a
/BOJ/10162.cpp
1b2096c29cbf601e0db90b7de0ce2c6db420c485
[]
no_license
sk7755/ACM-ICPC
0b51bd459022d59a21efa5d9e25539dd9c71cf76
12fdce8d3492a01e51f815670cc2fc5b92242fde
refs/heads/master
2021-08-23T22:10:33.501136
2017-12-06T19:53:21
2017-12-06T19:53:21
100,312,877
0
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
#include <cstdio> int main() { int t; scanf("%d", &t); int a = t / 300; t %= 300; int b = t / 60; t %= 60; int c = t/10; if (t % 10) { printf("-1\n"); return 0; } printf("%d %d %d\n", a,b,c); return 0; }
44b6297ad20700e02fae31c74a0aa5bf859ffff5
d48b00b905ed9fb27949285737601f0b3d04c857
/2018/08/20/2018多校9/1010.cpp
e3c84e0d1cb18a6458aa4d8d281df2081c73b874
[]
no_license
Smlight/Programming-Contest
1162bbd5476cc687c1afe3d2fd92e4832cf4b979
ee90ad89804ae10c9cd4b31171adb467f2493b33
refs/heads/master
2021-06-01T10:42:08.730261
2020-12-09T07:36:35
2020-12-09T07:36:35
56,766,943
3
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
#include <bits/stdc++.h> using namespace std; using PII = pair<int,int>; const int N=9; const int inf=2e9; int a[N],b[N]; PII va[2],vb[2]; int sgn() { if (va[0]<vb[0]) return 1; if (va[0]>vb[0]) return -1; if (va[1]<vb[1]) return 1; if (va[1]>vb[1]) return -1; return 0; } int main() { int T; scanf("%d",&T); while (T--) { int n,m; scanf("%d%d",&n,&m); for (int i=0;i<n;i++) { scanf("%d",&a[i]); } for (int i=0;i<m;i++) { scanf("%d",&b[i]); } if (n==3) { va[0]={a[2],a[1]+1}; if (va[0].first>va[0].second) swap(va[0].first,va[0].second); va[1]={a[0]+2,inf}; } else if (n==2) { va[0]={a[0]+2,inf}; va[1]={a[1]+1,inf}; } else { va[0]={a[0]+2,inf}; va[1]={inf,inf}; } if (m==3) { vb[0]={b[2],b[1]+1}; if (vb[0].first>vb[0].second) swap(vb[0].first,vb[0].second); vb[1]={b[0]+2,inf}; } else if (m==2) { vb[0]={b[0]+2,inf}; vb[1]={b[1]+1,inf}; } else { vb[0]={b[0]+2,inf}; vb[1]={inf,inf}; } sort(va,va+2); sort(vb,vb+2); printf("%d\n",sgn()); } return 0; }
679a96e425961cedca8ae640248994abaeeb802f
14344ea4c081bbfb9639cc33dcf843b9134b7d5b
/mindspore/lite/c_ops/gather.h
67126fca5448e05ad22ed467bffaf423766aa6af
[ "Apache-2.0", "Libpng", "LGPL-2.1-only", "MIT", "IJG", "Zlib", "BSD-3-Clause-Open-MPI", "AGPL-3.0-only", "MPL-2.0-no-copyleft-exception", "MPL-1.0", "MPL-1.1", "MPL-2.0", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Unlicense", "LicenseRef-scancode-proprietary-license", "BSL-1.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
Joejiong/mindspore
d06318e456c000f6368dbe648daa39d82ba6a2da
083fd6565cab1aa1d3114feeacccf1cba0d55e80
refs/heads/master
2022-12-05T07:17:28.737741
2020-08-18T07:51:33
2020-08-18T07:51:33
288,415,456
0
0
Apache-2.0
2020-08-18T09:43:35
2020-08-18T09:43:34
null
UTF-8
C++
false
false
1,515
h
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> #include <set> #include <cmath> #include "ir/dtype/type_id.h" #include "mindspore/lite/c_ops/primitive_c.h" #ifdef PRIMITIVE_WRITEABLE #include "schema/inner/model_generated.h" #else #include "schema/model_generated.h" #endif #ifndef LITE_MINDSPORE_LITE_C_OPS_GATHER_H_ #define LITE_MINDSPORE_LITE_C_OPS_GATHER_H_ namespace mindspore { class Gather : public PrimitiveC { public: #ifdef PRIMITIVE_WRITEABLE explicit Gather(schema::PrimitiveT *primitive) : PrimitiveC(primitive) {} #else explicit Gather(schema::Primitive *primitive) : PrimitiveC(primitive) {} #endif int InferShape(std::vector<lite::tensor::Tensor *> inputs_, std::vector<lite::tensor::Tensor *> outputs_) override; int GetAxis() const; int GetBatchDims() const; void SetAxis(int axis); void SetBatchDims(int batch_dims); }; } // namespace mindspore #endif // LITE_MINDSPORE_LITE_C_OPS_GATHER_H_
55916ce12f447ba835ebae6c20cfd00d3066cb08
162a3db1eb6017a94e9f378d7a20f61e581ecbe9
/src/components/content_settings/browser/tab_specific_content_settings.h
39583b714365c01271a88c9639889fbf89e2e580
[ "BSD-3-Clause" ]
permissive
webosose/chromium84
705fbac37c5cfecd36113b41b7a0f4e8adf249d5
5decc42bef727dc957683fb5d8fa2fcc78936f15
refs/heads/master
2023-05-29T13:53:50.190538
2021-06-08T07:56:29
2021-06-10T01:19:24
330,895,427
0
2
null
null
null
null
UTF-8
C++
false
false
19,442
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_CONTENT_SETTINGS_BROWSER_TAB_SPECIFIC_CONTENT_SETTINGS_H_ #define COMPONENTS_CONTENT_SETTINGS_BROWSER_TAB_SPECIFIC_CONTENT_SETTINGS_H_ #include <stdint.h> #include <map> #include <memory> #include <set> #include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "base/scoped_observer.h" #include "build/build_config.h" #include "components/browsing_data/content/cookie_helper.h" #include "components/browsing_data/content/local_shared_objects_container.h" #include "components/content_settings/browser/content_settings_usages_state.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_types.h" #include "content/public/browser/allow_service_worker_result.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" namespace content { class NavigationHandle; } namespace url { class Origin; } // namespace url namespace content_settings { // TODO(msramek): Media is storing their state in TabSpecificContentSettings: // |microphone_camera_state_| without being tied to a single content setting. // This state is not ideal, potential solution is to save this information via // content::WebContentsUserData // This class manages state about permissions, content settings, cookies and // site data for a specific WebContents. It tracks which content was accessed // and which content was blocked. Based on this it provides information about // which types of content were accessed and blocked. class TabSpecificContentSettings : public content::WebContentsObserver, public content_settings::Observer, public content::WebContentsUserData<TabSpecificContentSettings> { public: // Fields describing the current mic/camera state. If a page has attempted to // access a device, the XXX_ACCESSED bit will be set. If access was blocked, // XXX_BLOCKED will be set. enum MicrophoneCameraStateFlags { MICROPHONE_CAMERA_NOT_ACCESSED = 0, MICROPHONE_ACCESSED = 1 << 0, MICROPHONE_BLOCKED = 1 << 1, CAMERA_ACCESSED = 1 << 2, CAMERA_BLOCKED = 1 << 3, }; // Use signed int, that's what the enum flags implicitly convert to. typedef int32_t MicrophoneCameraState; class Delegate { public: virtual ~Delegate() = default; // Called when content settings state changes that might require updating // the location bar. virtual void UpdateLocationBar() = 0; // Notifies the delegate content settings rules have changed that need to be // sent to the renderer. virtual void SetContentSettingRules( content::RenderProcessHost* process, const RendererContentSettingRules& rules) = 0; // Gets the pref service for the current web contents. virtual PrefService* GetPrefs() = 0; // Gets the settings map for the current web contents. virtual HostContentSettingsMap* GetSettingsMap() = 0; // Gets any additional file system types which should be used when // constructing a browsing_data::FileSystemHelper. virtual std::vector<storage::FileSystemType> GetAdditionalFileSystemTypes() = 0; virtual browsing_data::CookieHelper::IsDeletionDisabledCallback GetIsDeletionDisabledCallback() = 0; // Allows the delegate to provide additional logic for detecting state // changes on top of the camera/microphone permission state. virtual bool IsMicrophoneCameraStateChanged( MicrophoneCameraState microphone_camera_state, const std::string& media_stream_selected_audio_device, const std::string& media_stream_selected_video_device) = 0; // Allows the delegate to provide additional logic for getting microphone // and camera state on top of the microphone and camera state at the last // media stream request. virtual MicrophoneCameraState GetMicrophoneCameraState() = 0; // Notifies the delegate a particular content settings type was blocked. virtual void OnContentBlocked(ContentSettingsType type) = 0; }; // Classes that want to be notified about site data events must implement // this abstract class and add themselves as observer to the // |TabSpecificContentSettings|. class SiteDataObserver { public: explicit SiteDataObserver( TabSpecificContentSettings* tab_specific_content_settings); virtual ~SiteDataObserver(); // Called whenever site data is accessed. virtual void OnSiteDataAccessed() = 0; TabSpecificContentSettings* tab_specific_content_settings() { return tab_specific_content_settings_; } // Called when the TabSpecificContentSettings is destroyed; nulls out // the local reference. void ContentSettingsDestroyed(); private: TabSpecificContentSettings* tab_specific_content_settings_; DISALLOW_COPY_AND_ASSIGN(SiteDataObserver); }; ~TabSpecificContentSettings() override; static void CreateForWebContents(content::WebContents* web_contents, std::unique_ptr<Delegate> delegate); // Returns the object given a RenderFrameHost ids. static TabSpecificContentSettings* GetForFrame(int render_process_id, int render_frame_id); // Called when a specific Web database in the current page was accessed. If // access was blocked due to the user's content settings, // |blocked_by_policy| should be true, and this function should invoke // OnContentBlocked. static void WebDatabaseAccessed(int render_process_id, int render_frame_id, const GURL& url, bool blocked_by_policy); // Called when a specific indexed db factory in the current page was // accessed. If access was blocked due to the user's content settings, // |blocked_by_policy| should be true, and this function should invoke // OnContentBlocked. static void IndexedDBAccessed(int render_process_id, int render_frame_id, const GURL& url, bool blocked_by_policy); // Called when CacheStorage::Open() is called in the current page. // If access was blocked due to the user's content settings, // |blocked_by_policy| should be true, and this function should invoke // OnContentBlocked. static void CacheStorageAccessed(int render_process_id, int render_frame_id, const GURL& url, bool blocked_by_policy); // Called when a specific file system in the current page was accessed. // If access was blocked due to the user's content settings, // |blocked_by_policy| should be true, and this function should invoke // OnContentBlocked. static void FileSystemAccessed(int render_process_id, int render_frame_id, const GURL& url, bool blocked_by_policy); // Called when a specific Shared Worker was accessed. static void SharedWorkerAccessed(int render_process_id, int render_frame_id, const GURL& worker_url, const std::string& name, const url::Origin& constructor_origin, bool blocked_by_policy); // Resets the |content_settings_status_|, except for // information which are needed for navigation: ContentSettingsType::COOKIES // for cookies and service workers, and ContentSettingsType::JAVASCRIPT for // service workers. // Only public for tests. void ClearContentSettingsExceptForNavigationRelatedSettings(); // Resets navigation related information (ContentSettingsType::COOKIES and // ContentSettingsType::JAVASCRIPT). // Only public for tests. void ClearNavigationRelatedContentSettings(); // Notifies that a Flash download has been blocked. void FlashDownloadBlocked(); // Changes the |content_blocked_| entry for popups. void ClearPopupsBlocked(); // Called when audio has been blocked on the page. void OnAudioBlocked(); // Returns whether a particular kind of content has been blocked for this // page. bool IsContentBlocked(ContentSettingsType content_type) const; // Returns whether a particular kind of content has been allowed. Currently // only tracks cookies. bool IsContentAllowed(ContentSettingsType content_type) const; const GURL& media_stream_access_origin() const { return media_stream_access_origin_; } const std::string& media_stream_requested_audio_device() const { return media_stream_requested_audio_device_; } const std::string& media_stream_requested_video_device() const { return media_stream_requested_video_device_; } // Only public for tests. const std::string& media_stream_selected_audio_device() const { return media_stream_selected_audio_device_; } // Only public for tests. const std::string& media_stream_selected_video_device() const { return media_stream_selected_video_device_; } bool camera_was_just_granted_on_site_level() { return camera_was_just_granted_on_site_level_; } bool mic_was_just_granted_on_site_level() { return mic_was_just_granted_on_site_level_; } // Returns the state of the camera and microphone usage. // The return value always includes all active media capture devices, on top // of the devices from the last request. MicrophoneCameraState GetMicrophoneCameraState() const; // Returns whether the camera or microphone permission or media device setting // has changed since the last permission request. bool IsMicrophoneCameraStateChanged() const; // Returns the ContentSettingsUsagesState that controls the // geolocation API usage on this page. const ContentSettingsUsagesState& geolocation_usages_state() const { return geolocation_usages_state_; } // Returns the ContentSettingsUsageState that controls the MIDI usage on // this page. const ContentSettingsUsagesState& midi_usages_state() const { return midi_usages_state_; } // Returns the |LocalSharedObjectsContainer| instances corresponding to all // allowed, and blocked, respectively, local shared objects like cookies, // local storage, ... . const browsing_data::LocalSharedObjectsContainer& allowed_local_shared_objects() const { return allowed_local_shared_objects_; } const browsing_data::LocalSharedObjectsContainer& blocked_local_shared_objects() const { return blocked_local_shared_objects_; } bool load_plugins_link_enabled() { return load_plugins_link_enabled_; } void set_load_plugins_link_enabled(bool enabled) { load_plugins_link_enabled_ = enabled; } // Called to indicate whether access to the Pepper broker was allowed or // blocked. void SetPepperBrokerAllowed(bool allowed); void OnContentBlocked(ContentSettingsType type); void OnContentAllowed(ContentSettingsType type); // These methods are invoked on the UI thread forwarded from the // ContentSettingsManagerImpl. void OnDomStorageAccessed(const GURL& url, bool local, bool blocked_by_policy); // These methods are invoked on the UI thread by the static functions above. // Only public for tests. void OnFileSystemAccessed(const GURL& url, bool blocked_by_policy); void OnIndexedDBAccessed(const GURL& url, bool blocked_by_policy); void OnCacheStorageAccessed(const GURL& url, bool blocked_by_policy); void OnSharedWorkerAccessed(const GURL& worker_url, const std::string& name, const url::Origin& constructor_origin, bool blocked_by_policy); void OnWebDatabaseAccessed(const GURL& url, bool blocked_by_policy); void OnGeolocationPermissionSet(const GURL& requesting_frame, bool allowed); #if defined(OS_ANDROID) || defined(OS_CHROMEOS) void OnProtectedMediaIdentifierPermissionSet(const GURL& requesting_frame, bool allowed); #endif // This method is called to update the status about the microphone and // camera stream access. void OnMediaStreamPermissionSet( const GURL& request_origin, MicrophoneCameraState new_microphone_camera_state, const std::string& media_stream_selected_audio_device, const std::string& media_stream_selected_video_device, const std::string& media_stream_requested_audio_device, const std::string& media_stream_requested_video_device); // There methods are called to update the status about MIDI access. void OnMidiSysExAccessed(const GURL& reqesting_origin); void OnMidiSysExAccessBlocked(const GURL& requesting_origin); // Adds the given |SiteDataObserver|. The |observer| is notified when a // locale shared object, like for example a cookie, is accessed. void AddSiteDataObserver(SiteDataObserver* observer); // Removes the given |SiteDataObserver|. void RemoveSiteDataObserver(SiteDataObserver* observer); // Block all content. Used for testing content setting bubbles. void BlockAllContentForTesting(); // Stores content settings changed by the user via PageInfo. void ContentSettingChangedViaPageInfo(ContentSettingsType type); // Returns true if the user changed the given ContentSettingsType via PageInfo // since the last navigation. bool HasContentSettingChangedViaPageInfo(ContentSettingsType type) const; Delegate* delegate() { return delegate_.get(); } private: friend class content::WebContentsUserData<TabSpecificContentSettings>; explicit TabSpecificContentSettings(content::WebContents* tab, std::unique_ptr<Delegate> delegate); void MaybeSendRendererContentSettingsRules( content::WebContents* web_contents); // content::WebContentsObserver overrides. void RenderFrameForInterstitialPageCreated( content::RenderFrameHost* render_frame_host) override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void AppCacheAccessed(const GURL& manifest_url, bool blocked_by_policy) override; void OnCookiesAccessed(content::NavigationHandle* navigation, const content::CookieAccessDetails& details) override; void OnCookiesAccessed(content::RenderFrameHost* rfh, const content::CookieAccessDetails& details) override; // Called when a specific Service Worker scope was accessed. // If access was blocked due to the user's content settings, // |blocked_by_policy_javascript| or/and |blocked_by_policy_cookie| should be // true, and this function should invoke OnContentBlocked for JavaScript // or/and cookies respectively. void OnServiceWorkerAccessed( content::NavigationHandle* navigation, const GURL& scope, content::AllowServiceWorkerResult allowed) override; void OnServiceWorkerAccessed( content::RenderFrameHost* frame, const GURL& scope, content::AllowServiceWorkerResult allowed) override; // content_settings::Observer implementation. void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const std::string& resource_identifier) override; // Notifies all registered |SiteDataObserver|s. void NotifySiteDataObservers(); // Clears settings changed by the user via PageInfo since the last navigation. void ClearContentSettingsChangedViaPageInfo(); // Updates Geolocation settings on navigation. void GeolocationDidNavigate(content::NavigationHandle* navigation_handle); // Updates MIDI settings on navigation. void MidiDidNavigate(content::NavigationHandle* navigation_handle); // Updates the list of allowed and blocked cookies. void OnCookiesAccessedImpl(const content::CookieAccessDetails& details); std::unique_ptr<Delegate> delegate_; // All currently registered |SiteDataObserver|s. base::ObserverList<SiteDataObserver>::Unchecked observer_list_; struct ContentSettingsStatus { bool blocked; bool allowed; }; // Stores which content setting types actually have blocked content. std::map<ContentSettingsType, ContentSettingsStatus> content_settings_status_; // Profile-bound, this will outlive this class (which is WebContents bound). HostContentSettingsMap* map_; // Stores the blocked/allowed cookies. browsing_data::LocalSharedObjectsContainer allowed_local_shared_objects_; browsing_data::LocalSharedObjectsContainer blocked_local_shared_objects_; // Manages information about Geolocation API usage in this page. ContentSettingsUsagesState geolocation_usages_state_; // Manages information about MIDI usages in this page. ContentSettingsUsagesState midi_usages_state_; // Stores whether the user can load blocked plugins on this page. bool load_plugins_link_enabled_; // The origin of the media stream request. Note that we only support handling // settings for one request per tab. The latest request's origin will be // stored here. http://crbug.com/259794 GURL media_stream_access_origin_; // The microphone and camera state at the last media stream request. MicrophoneCameraState microphone_camera_state_; // The selected devices at the last media stream request. std::string media_stream_selected_audio_device_; std::string media_stream_selected_video_device_; // The devices to be displayed in the media bubble when the media stream // request is requesting certain specific devices. std::string media_stream_requested_audio_device_; std::string media_stream_requested_video_device_; // The camera and/or microphone permission was granted to this origin from a // permission prompt that was triggered by the currently active document. bool camera_was_just_granted_on_site_level_ = false; bool mic_was_just_granted_on_site_level_ = false; // Observer to watch for content settings changed. ScopedObserver<HostContentSettingsMap, content_settings::Observer> observer_{ this}; // Stores content settings changed by the user via page info since the last // navigation. Used to determine whether to display the settings in page info. std::set<ContentSettingsType> content_settings_changed_via_page_info_; WEB_CONTENTS_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(TabSpecificContentSettings); }; } // namespace content_settings #endif // COMPONENTS_CONTENT_SETTINGS_BROWSER_TAB_SPECIFIC_CONTENT_SETTINGS_H_
4756ea1359ea23a68c49c148ae9a939b67131e91
1cab7143169415f6f259124f426ea259f8484481
/client/trezor.h
21196ec82006896f454a238b4f964fb30847b682
[ "BSD-3-Clause" ]
permissive
peronero/trezor-xmr
fb4ac01c1518fa9df1c6bc5290906e62bbec7728
d5e8bb98963c7b3533ca7620eb957ef44d3efcfa
refs/heads/master
2021-01-17T11:11:39.515965
2016-11-18T05:18:53
2016-11-18T05:18:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,825
h
#if !defined(__TREZOR_H__) #define __TREZOR_H__ #include "cryptonote_core/account.h" #include "cryptonote_core/cryptonote_format_utils.h" #include "trezor-xmr/shared/stream.h" #include "kokko.h" namespace kokko { class trezor { public: trezor(); ~trezor(); enum payment_id_type { none, normal, encrypted }; bool get_account(bool display, cryptonote::account_keys &account, uint32_t index, const std::string &password); bool get_last_account(cryptonote::account_keys &account) const; bool get_key_images(std::vector<crypto::key_image> &key_images, std::vector<cryptonote::keypair> &ephemerals, const crypto::public_key &tx_pubkey, const std::vector<size_t> &outs); bool generate_tx(cryptonote::transaction &tx, const std::vector<cryptonote::tx_source_entry> &sources, const std::vector<cryptonote::tx_destination_entry> &shuffled_dests, uint64_t unlock_time, uint64_t version, trezor::payment_id_type pid_type, const crypto::hash &pid); bool display_address(); std::string get_address() const; const tm get_timestamp() const; bool initialize(); void shutdown(); bool has_password_protection(); bool is_connected() const; bool reconnect(); private: bool get_session_key(bool renew = false); Features *get_features(); void copy_address_to_account_keys(cryptonote::account_keys &account) const; static bool check_ring_signatures(const cryptonote::transaction &tx); private: uint8_t m_session_key[64]; Features *m_features; xmr_account m_account; uint32_t m_account_index; bool m_session_initialized; bool m_account_initialized; static std::string m_password; mutable epee::critical_section m_device_lock; wire_device m_device; wire_passphrase_function_t m_default_passphrase_function; private: static int passphrase_function(char *data, size_t length); }; } #endif