hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
cb7f532dd62df74b192d8f089f816056776ea54b
473
h
C
macOS/10.13/AppKit.framework/_NSBinderPluginRegistry.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
30
2016-10-09T20:13:00.000Z
2022-01-24T04:14:57.000Z
macOS/10.12/AppKit.framework/_NSBinderPluginRegistry.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
null
null
null
macOS/10.12/AppKit.framework/_NSBinderPluginRegistry.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
7
2017-08-29T14:41:25.000Z
2022-01-19T17:14:54.000Z
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit */ @interface _NSBinderPluginRegistry : NSObject { NSMapTable * _cachedRegistry; NSMapTable * _registry; } + (id)sharedRegistry; - (void)dealloc; - (id)init; - (Class)pluginClassForObject:(id)arg1 andBinderClass:(Class)arg2 requiredPluginProtocol:(id)arg3; - (void)registerPluginClass:(Class)arg1 forObjectClass:(Class)arg2 andBinderClass:(Class)arg3; @end
26.277778
98
0.767442
3eec3ab51ae1d402c559292e62ec524796b7f6df
973
c
C
Projects/Basics/Libft/ft_isdigit.c
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
84
2020-10-13T14:50:11.000Z
2022-01-11T11:19:36.000Z
Projects/Basics/Libft/ft_isdigit.c
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
null
null
null
Projects/Basics/Libft/ft_isdigit.c
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
43
2020-09-10T19:26:37.000Z
2021-12-28T13:53:55.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isdigit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rtorres- <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/08 20:41:05 by rtorres- #+# #+# */ /* Updated: 2016/11/11 23:04:53 by rtorres- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int ft_isdigit(int c) { return ((c >= 48) && (c <= 57)); }
51.210526
80
0.137718
3e909575941fe4abc0c92150ade87972f7169207
1,062
c
C
test_client.c
martinb416/C-Server
3b1d97b68913d8995eeba1d1a3654e342c572766
[ "MIT" ]
null
null
null
test_client.c
martinb416/C-Server
3b1d97b68913d8995eeba1d1a3654e342c572766
[ "MIT" ]
null
null
null
test_client.c
martinb416/C-Server
3b1d97b68913d8995eeba1d1a3654e342c572766
[ "MIT" ]
null
null
null
/* * Test driver for server connections * * Author: Martin Buitrago * 2018 */ #include "common.h" #include "server.h" int main(){ int sock, result; /* Get the address informtation and connect to the server */ struct addrinfo info, *addr; memset(&info, 0, sizeof(struct addrinfo)); info.ai_family = AF_UNSPEC; // TODO: Change if changed in server.c info.ai_socktype = SOCK_STREAM; info.ai_flags = AI_PASSIVE; info.ai_protocol = IPPROTO_TCP; result = getaddrinfo(LOCALHOST, DEF_PORT, &info, &addr); if(result != 0){ fprintf(stderr, "getaddrinfo Error\n"); } sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (sock < 0){ fprintf(stderr, "Socket Error\n"); exit(-1); } int iSetOption = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption, sizeof(iSetOption)); result = connect(sock, addr->ai_addr, addr->ai_addrlen); if(result < 0){ close(sock); perror("client"); exit(errno); } return printf("Client Didn't Crash\n"); }
24.697674
73
0.645951
8ba2545f0f4d93514478ef4fbe8708cdaae7d624
643
c
C
r12/9s585.c
rafalmaziejuk/c-primer-plus-solutions
a169f05b77a591f3979075b11f174935d5580615
[ "MIT" ]
null
null
null
r12/9s585.c
rafalmaziejuk/c-primer-plus-solutions
a169f05b77a591f3979075b11f174935d5580615
[ "MIT" ]
null
null
null
r12/9s585.c
rafalmaziejuk/c-primer-plus-solutions
a169f05b77a591f3979075b11f174935d5580615
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ROZMIAR 10 int main(void) { int liczba_slow; char temp[ROZMIAR]; int i = 0; printf("Podaj liczbe slow do wprowadzenia: "); scanf("%d", &liczba_slow); getchar(); char **tab = (char **)malloc(liczba_slow * sizeof(char *)); printf("Wprowadz %d slow: \n", liczba_slow); while (i < liczba_slow && scanf("%10s", temp) && temp[0] != '\n') { char *pom = (char *)malloc(strlen(temp) * sizeof(char) + 1); strcpy(pom, temp); tab[i] = pom; i++; } puts("Oto wprowadzone slowa:"); for (int j = 0; j < liczba_slow; j++) puts(tab[j]); free(tab); return 0; }
17.378378
66
0.604977
eb6102ad8bd49ce776316bc70f2163be02f0c50a
28,591
h
C
converter/COLLADA2GLTF/convert/animationConverter.h
anuprao/glTF
1bd91d9676aa444dd3d3d146af1a68126e3f0294
[ "Zlib" ]
4
2015-03-07T00:53:46.000Z
2017-02-19T04:54:37.000Z
converter/COLLADA2GLTF/convert/animationConverter.h
anuprao/glTF
1bd91d9676aa444dd3d3d146af1a68126e3f0294
[ "Zlib" ]
null
null
null
converter/COLLADA2GLTF/convert/animationConverter.h
anuprao/glTF
1bd91d9676aa444dd3d3d146af1a68126e3f0294
[ "Zlib" ]
3
2018-06-06T04:38:54.000Z
2020-09-03T05:35:09.000Z
/* */ #ifndef __GLTFANIMATIONCONVERTER_H__ #define __GLTFANIMATIONCONVERTER_H__ #include "GLTF.h" #include "../GLTFOpenCOLLADA.h" #include "mathHelpers.h" namespace GLTF { //a few helper classes to help flattening animations typedef std::map<std::string , std::shared_ptr<COLLADAFW::Transformation> > IDToTransform; class GLTFTransformKey { public: GLTFTransformKey(double time, std::shared_ptr<COLLADAFW::Transformation> transform, std::string transformID) { this->_subTransforms[transformID] = transform; this->_time = time; } double getTime() { return this->_time; } IDToTransform* subTransforms() { return &this->_subTransforms; } /* bool canEvaluateTransform() { for (size_t i = 0 ; i < this->_transformsOrder->size(); i++) { std::string transformID = this->_transformsOrder->at(i); if (this->_subTransforms.count(transformID) == 0) { return false; } } return true; } */ private: IDToTransform _subTransforms; double _time; }; class GLTFAnimationFlattener { private: void _updateTransformByReplacingValueAtIndex(std::shared_ptr<COLLADAFW::Transformation> transform, size_t index, float value) { switch (transform->getTransformationType()) { case COLLADAFW::Transformation::ROTATE: { COLLADAFW::Rotate* rotate = (COLLADAFW::Rotate*)transform.get(); COLLADABU::Math::Vector3& rotationAxis = rotate->getRotationAxis(); switch (index) { case 0: rotate->setRotationAxis(value, rotationAxis.y, rotationAxis.z); break; case 1: rotate->setRotationAxis(rotationAxis.x, value, rotationAxis.z); break; case 2: rotate->setRotationAxis(rotationAxis.x, rotationAxis.y, value); break; case 3: rotate->setRotationAngle(value); break; default: break; } break; } case COLLADAFW::Transformation::TRANSLATE: { COLLADAFW::Translate* translate = (COLLADAFW::Translate*)transform.get(); COLLADABU::Math::Vector3& translation = translate->getTranslation(); switch (index) { case 0: translate->setTranslation(value, translation.y, translation.z); break; case 1: translate->setTranslation(translation.x, value, translation.z); break; case 2: translate->setTranslation(translation.x, translation.y, value); break; default: break; } } case COLLADAFW::Transformation::SCALE: { COLLADAFW::Scale* scale = (COLLADAFW::Scale*)transform.get(); COLLADABU::Math::Vector3& sc = scale->getScale(); switch (index) { case 0: scale->setScale(value, sc.y, sc.z); break; case 1: scale->setScale(sc.x, value, sc.z); break; case 2: scale->setScale(sc.x, sc.y, value); break; default: break; } } default: break; } } std::shared_ptr<COLLADAFW::Transformation> _cloneTransformByReplacingValueAtIndex(std::string transformID, size_t index, float value) { std::shared_ptr<COLLADAFW::Transformation> transform = _idToTransform[transformID]; std::shared_ptr<COLLADAFW::Transformation> clonedTransform(transform->clone()); _updateTransformByReplacingValueAtIndex(clonedTransform, index, value); return clonedTransform; } public: GLTFAnimationFlattener(COLLADAFW::Node *node) { this->_transformsOrder = std::shared_ptr <std::vector<std::string> > (new std::vector<std::string>); const COLLADAFW::TransformationPointerArray& transformations = node->getTransformations(); size_t transformationsCount = transformations.getCount(); int index = 0; this->_hasAnimatedScale = this->_hasAnimatedTranslation = this->_hasAnimatedRotation = false; this->_targetUID = node->getOriginalId(); _idIndex = (int*)malloc(sizeof(int) * transformationsCount); for (size_t i = 0 ; i < transformationsCount ; i++) { const COLLADAFW::Transformation* tr = transformations[i]; std::shared_ptr<COLLADAFW::Transformation> clonedTransform(tr->clone()); const COLLADAFW::UniqueId& animationListID = tr->getAnimationList(); if (animationListID.isValid()) { _idIndex[i] = index++; _idToTransform[animationListID.toAscii()] = clonedTransform; this->_transformsOrder->push_back(animationListID.toAscii()); } else { _idIndex[i] = -1; } _originalTransforms.push_back(clonedTransform); } } virtual ~GLTFAnimationFlattener() { free(this->_idIndex); } bool hasAnimatedScale() { return this->_hasAnimatedScale; } bool hasAnimatedTranslation() { return this->_hasAnimatedTranslation; } bool hasAnimatedRotation() { return this->_hasAnimatedRotation; } void allocAndFillAffineTransformsBuffers(float **translationsPtr, float **rotationsPtr, float **scalePtr, size_t &count) { COLLADABU::Math::Matrix4 transformationMatrix; float *translations = 0; float *rotations = 0; float *scales = 0; count = _transforms.size(); if (this->_hasAnimatedTranslation && translationsPtr) { *translationsPtr = (float*)malloc(sizeof(float) * count * 3); translations = *translationsPtr; } if (this->_hasAnimatedRotation && rotationsPtr) { *rotationsPtr = (float*)malloc(sizeof(float) * count * 4); rotations = *rotationsPtr; } if (this->_hasAnimatedScale && scalePtr) { *scalePtr = (float*)malloc(sizeof(float) * count * 3); scales = *scalePtr; } float *previousAxisAngle = 0; float axisAngle[4]; for (size_t i = 0 ; i < _transforms.size() ; i++) { std::shared_ptr<GLTFTransformKey> key = this->_transforms[i]; if ((i > 0) && (rotations != 0)) { previousAxisAngle = rotations + ((i-1) * 4); } getTransformationMatrixAtIndex(transformationMatrix, i); decomposeMatrix(transformationMatrix, (translations != 0) ? translations + (i * 3) : 0, (rotations != 0) ? axisAngle : 0, (scales != 0) ? scales + (i * 3) : 0); if ((i > 0) && (rotations != 0)) { //each quaternions have 2 possible representations from axis angle //we want to pick-up the closest one to the last orientation COLLADABU::Math::Vector3 axis(axisAngle[0], axisAngle[1], axisAngle[2]); COLLADABU::Math::Quaternion key1; COLLADABU::Math::Quaternion key2; key1.fromAngleAxis(axisAngle[3], axis); bool skip = false; if (0 == memcmp(axisAngle, previousAxisAngle, 4 * sizeof(float))) { skip = true; } key2.x = -key1.x; key2.y = -key1.y; key2.z = -key1.z; key2.w = -key1.w; key1.normalise(); key2.normalise(); COLLADABU::Math::Vector3 previousAxis(previousAxisAngle[0], previousAxisAngle[1], previousAxisAngle[2]); COLLADABU::Math::Quaternion previousKey; previousKey.fromAngleAxis(previousAxisAngle[3], previousAxis); previousKey.normalise(); double angle1 = acos(previousKey.dot(key1)); double angle2 = acos(previousKey.dot(key2)); if (angle1 > COLLADABU::Math::HALF_PI) angle1 -= COLLADABU::Math::HALF_PI; if (angle2 > COLLADABU::Math::HALF_PI) angle2 -= COLLADABU::Math::HALF_PI; COLLADABU::Math::Vector3 destAxis1; COLLADABU::Math::Vector3 destAxis2; COLLADABU::Math::Real destAngle1; COLLADABU::Math::Real destAngle2; key1.toAngleAxis ( destAngle1, destAxis1 ); key2.toAngleAxis ( destAngle2, destAxis2 ); if ((skip == false) && (angle1 > angle2)) { axisAngle[0] = (float)destAxis2[0]; axisAngle[1] = (float)destAxis2[1]; axisAngle[2] = (float)destAxis2[2]; axisAngle[3] = (float)destAngle2; } else { axisAngle[0] = (float)destAxis1[0]; axisAngle[1] = (float)destAxis1[1]; axisAngle[2] = (float)destAxis1[2]; axisAngle[3] = (float)destAngle1; } } if (rotations != 0) memcpy(rotations + (i * 4), axisAngle, sizeof(float) * 4); } } void transformWasInserted(std::shared_ptr<COLLADAFW::Transformation> tr) { switch (tr->getTransformationType()) { case COLLADAFW::Transformation::MATRIX: this->_hasAnimatedScale = this->_hasAnimatedTranslation = this->_hasAnimatedRotation = true; break; case COLLADAFW::Transformation::TRANSLATE: this->_hasAnimatedTranslation = true; break; case COLLADAFW::Transformation::ROTATE: this->_hasAnimatedRotation = true; break; case COLLADAFW::Transformation::SCALE: this->_hasAnimatedScale = true; break; default: printf("warning: unhandled animation type\n"); break; } } //to be used for whole matrices and angle axis void insertTransformAtTime(std::string transformID, std::shared_ptr<COLLADAFW::Transformation> transformation, double time) { transformWasInserted(transformation); if (_transforms.size() == 0) { std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.push_back(key); } else { for (size_t i = 0 ; i < _transforms.size() ; i++) { std::shared_ptr<GLTFTransformKey> key = _transforms[i]; if (time == key->getTime()) { if ( (*key->subTransforms()).count(transformID) > 0) { printf("INCONSISTENCY ERROR: overlap\n"); } (*key->subTransforms())[transformID] = transformation; return; } else if (time > key->getTime()) { if (i + 1 == _transforms.size()) { std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.push_back(key); return; } else if (time < _transforms[i+1]->getTime()) { std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.insert(_transforms.begin() + i, key); return; } } else { std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.insert(_transforms.begin() + i, key); return; } } } } void insertValueAtTime(std::string transformID, float value, size_t index, double time) { std::shared_ptr <COLLADAFW::Transformation> transformation; if (_transforms.size() == 0) { transformation = this->_cloneTransformByReplacingValueAtIndex(transformID, index, value); std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.push_back(key); transformWasInserted(transformation); return; } else { for (size_t i = 0 ; i < _transforms.size() ; i++) { std::shared_ptr<GLTFTransformKey> key = _transforms[i]; if (time == key->getTime()) { if ( (*key->subTransforms()).count(transformID) > 0) { transformation = (*key->subTransforms())[transformID]; this->_updateTransformByReplacingValueAtIndex(transformation, index, value); } else { transformation = this->_cloneTransformByReplacingValueAtIndex(transformID, index, value); (*key->subTransforms())[transformID] = transformation; } transformWasInserted(transformation); return; } else if (time > key->getTime()) { if (i + 1 == _transforms.size()) { transformation = this->_cloneTransformByReplacingValueAtIndex(transformID, index, value); std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.push_back(key); transformWasInserted(transformation); return; } else if (time < _transforms[i+1]->getTime()) { transformation = this->_cloneTransformByReplacingValueAtIndex(transformID, index, value); std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.insert(_transforms.begin() + i, key); transformWasInserted(transformation); return; } } else { transformation = this->_cloneTransformByReplacingValueAtIndex(transformID, index, value); std::shared_ptr <GLTFTransformKey> key(new GLTFTransformKey(time, transformation, transformID)); _transforms.insert(_transforms.begin() + i, key); transformWasInserted(transformation); return; } } } } void setTransformsOrder(std::shared_ptr<std::vector<std::string> > transformsOrder) { this->_transformsOrder = transformsOrder; } std::shared_ptr<std::vector<std::string> > getTransformsOrder() { return this->_transformsOrder; } size_t getCount() { return this->_transforms.size(); }; #define _INTERPOLATE(I1, I2, STEP) (I1 + (STEP * (I2-I1))) //TODO: might be worth checking for equality for prev & transform to be interpolated here std::shared_ptr <COLLADAFW::Transformation> _interpolateTransforms(std::shared_ptr<COLLADAFW::Transformation> previousTransform, std::shared_ptr<COLLADAFW::Transformation> nextTransform, double ratio) { COLLADAFW::Transformation::TransformationType transformationType = previousTransform->getTransformationType(); std::shared_ptr<COLLADAFW::Transformation> transform(previousTransform->clone()); switch (transformationType) { case COLLADAFW::Transformation::ROTATE: { COLLADAFW::Rotate* r1 = (COLLADAFW::Rotate*)previousTransform.get(); COLLADAFW::Rotate* r2 = (COLLADAFW::Rotate*)nextTransform.get(); COLLADAFW::Rotate* r = (COLLADAFW::Rotate*)transform.get(); r->setRotationAngle(_INTERPOLATE(r1->getRotationAngle(), r2->getRotationAngle(), ratio)); COLLADABU::Math::Vector3& rAxis1 = r1->getRotationAxis(); COLLADABU::Math::Vector3& rAxis2 = r2->getRotationAxis(); r->setRotationAxis(_INTERPOLATE(rAxis1.x, rAxis2.x, ratio), _INTERPOLATE(rAxis1.y, rAxis2.y, ratio), _INTERPOLATE(rAxis1.z, rAxis2.z, ratio)); break; } case COLLADAFW::Transformation::TRANSLATE: { COLLADAFW::Translate* t1 = (COLLADAFW::Translate*)previousTransform.get(); COLLADAFW::Translate* t2 = (COLLADAFW::Translate*)nextTransform.get(); COLLADAFW::Translate* t = (COLLADAFW::Translate*)transform.get(); COLLADABU::Math::Vector3& translation1 = t1->getTranslation(); COLLADABU::Math::Vector3& translation2 = t2->getTranslation(); t->setTranslation(_INTERPOLATE(translation1.x, translation2.x, ratio), _INTERPOLATE(translation1.y, translation2.y, ratio), _INTERPOLATE(translation1.z, translation2.z, ratio)); break; } case COLLADAFW::Transformation::SCALE: { COLLADAFW::Scale* s1 = (COLLADAFW::Scale*)previousTransform.get(); COLLADAFW::Scale* s2 = (COLLADAFW::Scale*)nextTransform.get(); COLLADAFW::Scale* t = (COLLADAFW::Scale*)transform.get(); COLLADABU::Math::Vector3& scale1 = s1->getScale(); COLLADABU::Math::Vector3& scale2 = s2->getScale(); t->setScale(_INTERPOLATE(scale1.x, scale2.x, ratio), _INTERPOLATE(scale1.y, scale2.y, ratio), _INTERPOLATE(scale1.z, scale2.z, ratio)); break; } default: { static bool printOnce = false; if (!printOnce) { printf("WARNING: unhandled interpolation in animation flattener\n"); printOnce = true; } } break; } return transform; } void getTransformationMatrixAtIndex(COLLADABU::Math::Matrix4& transformationMatrix, size_t index) { transformationMatrix = COLLADABU::Math::Matrix4::IDENTITY; for ( size_t i = 0, count = this->_originalTransforms.size(); i < count; ++i ) { COLLADAFW::Transformation* transform; int idIndex = _idIndex[i]; if (idIndex != -1) { std::string transformID = this->_transformsOrder->at(idIndex); std::shared_ptr <GLTFTransformKey> key = this->_transforms[index]; if ((*key->subTransforms()).count(transformID) == 0) { //so here we need to get a transform matching transformID for this key but it does not contain it, //we need to figure it out by interpolating the previous/next key containing this transform (this involves a search. std::shared_ptr<COLLADAFW::Transformation> previousTransform; std::shared_ptr<COLLADAFW::Transformation> nextTransform; std::shared_ptr <GLTFTransformKey> previousKey; std::shared_ptr <GLTFTransformKey> nextKey; double t1 = 0, t2 = 0; bool found = false; if (index > 0) { int previousIndex = (int)index - 1; do { previousKey = this->_transforms[previousIndex--]; if ((*previousKey->subTransforms()).count(transformID) != 0) { previousTransform = (*previousKey->subTransforms())[transformID]; t1 = previousKey->getTime(); found = true; break; } } while (previousIndex >= 0); } if (found == false) { previousTransform = _idToTransform[transformID]; t1 = 0; } found = false; if (index + 1 < this->_transforms.size()) { size_t nextIndex = index + 1; do { nextKey = this->_transforms[nextIndex++]; if ((*nextKey->subTransforms()).count(transformID) != 0) { nextTransform = (*nextKey->subTransforms())[transformID]; t2 = nextKey->getTime(); found = true; break; } } while (nextIndex < this->_transforms.size()); } if (found == false) { std::shared_ptr <GLTFTransformKey> lastKey = this->_transforms[this->_transforms.size() - 1]; nextTransform = _idToTransform[transformID]; t2 = lastKey->getTime(); } if (previousTransform->getTransformationType() == nextTransform->getTransformationType()) { double ratio = key->getTime() / (t2 - t1); (*key->subTransforms())[transformID] = _interpolateTransforms(previousTransform, nextTransform, ratio); } else { printf("inconsistent state: cannot interpolate keys of different types\n"); } } transform = (*key->subTransforms())[transformID].get(); if (!transform) { printf("warning:can't find id\n"); } } else { transform = this->_originalTransforms[i].get(); } switch ( transform->getTransformationType() ) { case COLLADAFW::Transformation::ROTATE: { COLLADAFW::Rotate* rotate = (COLLADAFW::Rotate*)transform; COLLADABU::Math::Vector3 axis = rotate->getRotationAxis(); axis.normalise(); double angle = rotate->getRotationAngle(); transformationMatrix = transformationMatrix * COLLADABU::Math::Matrix4(COLLADABU::Math::Quaternion(COLLADABU::Math::Utils::degToRad(angle), axis)); break; } case COLLADAFW::Transformation::TRANSLATE: { COLLADAFW::Translate* translate = (COLLADAFW::Translate*)transform; const COLLADABU::Math::Vector3& translation = translate->getTranslation(); COLLADABU::Math::Matrix4 translationMatrix; translationMatrix.makeTrans(translation); transformationMatrix = transformationMatrix * translationMatrix; break; } case COLLADAFW::Transformation::SCALE: { COLLADAFW::Scale* scale = (COLLADAFW::Scale*)transform; const COLLADABU::Math::Vector3& scaleVector = scale->getScale(); COLLADABU::Math::Matrix4 scaleMatrix; scaleMatrix.makeScale(scaleVector); transformationMatrix = transformationMatrix * scaleMatrix; break; } case COLLADAFW::Transformation::MATRIX: { COLLADAFW::Matrix* matrix = (COLLADAFW::Matrix*)transform; transformationMatrix = transformationMatrix * matrix->getMatrix(); break; } case COLLADAFW::Transformation::LOOKAT: break; case COLLADAFW::Transformation::SKEW: break; } } } private: bool _hasAnimatedScale, _hasAnimatedTranslation, _hasAnimatedRotation; std::string _targetUID; int *_idIndex; std::vector<std::shared_ptr<COLLADAFW::Transformation> > _originalTransforms; std::vector<std::shared_ptr<GLTFTransformKey> > _transforms; std::map<std::string , std::shared_ptr<COLLADAFW::Transformation> > _idToTransform; std::shared_ptr<std::vector<std::string> > _transformsOrder; }; std::shared_ptr <GLTFAnimation> convertOpenCOLLADAAnimationToGLTFAnimation(const COLLADAFW::Animation* animation, GLTF::GLTFAsset *asset); bool writeAnimation(std::shared_ptr <GLTFAnimation> cvtAnimation, const COLLADAFW::AnimationList::AnimationClass animationClass, AnimatedTargetsSharedPtr animatedTargets, GLTF::GLTFAsset *asset); //------- } #endif
47.651667
210
0.476828
d40272ab913d69697afdc02e65e3b4a6f64ce87e
7,513
h
C
include/SGB_Screen.h
ManoShu/SGB
4590910743ad1e8bbcf9209325393059587592cd
[ "BSD-2-Clause" ]
5
2017-05-21T08:46:08.000Z
2020-04-22T13:21:39.000Z
include/SGB_Screen.h
ManoShu/SGB
4590910743ad1e8bbcf9209325393059587592cd
[ "BSD-2-Clause" ]
null
null
null
include/SGB_Screen.h
ManoShu/SGB
4590910743ad1e8bbcf9209325393059587592cd
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "SGB_SDL.h" #include "SGB_Display.h" #include "SGB_LoadingQueue.h" class SGB_Display; /*! \brief Class to manage a screen flow, with loading, updating and unloading. * * The SGB_Screen class aims to reduce the effort needed to setup the rendering process * and focus on the specific purpose of said screen. * * <b>Example usage</b>: * In this example, the screen loading process is simulated with a loop of SDL_Delay's, * a grid of boxes equal to the average FPS is drawn and, after 10 seconds elapsed, * the next screen is set (in this case is the same class, but can be any other SGB_Screen * inherited class). If the user press ESC while the screen is running, * `SGB_Display::StopRunning()` is called signalling the end of the main loop. TestScreen.h \includelineno TestScreen.h TestScreen.cpp \includelineno TestScreen.cpp */ class SGB_Screen { public: /*! \brief Creates an instance of SGB_Screen. */ SGB_Screen(); /*! \brief Destroys the SGB_Screen instance. */ virtual ~SGB_Screen(); /*! \brief Indicate to the SGB_Screen instance what instance of * SGB_Display will handle it. * * \param display The SGB_Display that will handle the SGB_Screen * instance. * * The SGB_Screen::_display and SGB_Screen::_renderer are set at * this moment, making any other methods being able to access those * intances resources. */ void SetDisplay(SGB_Display* display); /*! \brief Loads any resouces needed by the SGB_Screen. * * This method should be used to load all resource-heavy, * time-consuming data, as this method and UnloadScreen() will be * called in a separate thread, while a loading screen (if set) is * shown during this process. */ virtual void LoadScreen() {}; /*! \brief Prepare the SGB_Screen to be displayed. * * Unlike LoadScreen(), this method is executed in the main thread, * so it's recommended to keep it's processing load light and fast. */ virtual void ScreenShow() {}; /*! \brief Process a delta-time iteration. * * The SGB_Screen's logic calculations will usually be done here. */ virtual void Update() = 0; /*! \brief Draws the SGB_Screen visual content. */ virtual void Draw() {}; /*! \brief Prepare the screen to be changed to another one. * * Use this method to stop any immediate processing the SGB_Screen * might be doing, like a network request or thread execution. * * This method is also run on the main thread, so it's wise to keep * it light and return fast. */ virtual void ScreenFinish() {}; /*! \brief Unloads any resources used by the SGB_Screen. * * Any heavy resource release process, such as flushing logs, save * and closing file streams, should be done in this method, as, like * LoadScreen(), it runs on a separate thread from the caller one. */ virtual void UnloadScreen() {}; /*! \brief Connects a SGB_LoadingScreen's SGB_LoadingQueue to this * SGB_Screen. * * \param loadingScreen The SGB_LoadingScreen being used while this * SGB_Screen intance is loading. * * This method is not intended to be called manually, as it is * executed when the SGB_Display is preparing to load a new * SGB_Screen. */ void SetLoadingQueue(SGB_Screen* loadingScreen); protected: /*! \brief Signals the SGB_Display to change SGB_Screen's. * * \param screen The next SGB_Screen to be shown. * * A shortcut that calls SGB_Display::SetScreen(). * * <b>WARNING:</b> When calling SetNextScreen(), make sure * that there will be no more resources used until this screen's * current update loop ends, as ScreenFinish() and * UnloadScreen() will be called by the parent SGB_Display will * be called and there's no guarantee of the current loop * finishing before those calls. */ void SetNextScreen(SGB_Screen* screen); /*! \brief Builds a SDL_Color struct with the informed RGBA values. * \param r Red value (0-255) * \param g Green value (0-255) * \param b Blue value (0-255) * \param a Alpha value (0-255) * * \returns A SDL_Color structure with the given fields filled. * * The alpha parameter defaults to SDL_ALPHA_OPAQUE ( 0xff , 255 ). */ SDL_Color GetColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a = SDL_ALPHA_OPAQUE); /*! \brief Sets the render color. * * \param color The SDL_Color to be set as render color. * * A shortcut that calls SGB_Display::SetDrawColor(). */ void SetColor(SDL_Color color); /*! \brief Renders a filled rectangle with the given color and * position/dimension. * * \param rect The SDL_Rect position\\dimension where the rectangle * will be rendered. * \param color The SDL_Color to be used to render the rectangle. * * Uses SGB_Display::GetDrawColor and SGB_Display::SetDrawColor to * temporarily set the render color and draw a "full" rectangle, * going back to the previous render color when done. */ void FillRect(SDL_Rect rect, SDL_Color color); /*! \brief Renders a non-filled rectangle, using the current draw * color. * * \param rect The positions and size on where the rectangle will * be drawn. */ void DrawRect(SDL_Rect rect); /*! \brief Renders a non-filled rectangle, using the given draw * color. * * \param rect The positions and size on where the rectangle will * be drawn. * \param color The color to be used to draw the rectangle. */ void DrawRect(SDL_Rect rect, SDL_Color color); /*! \brief Renders a filled rectangle with the current render * color and given position/dimension. * * \param rect The SDL_Rect position\\dimension where the rectangle * will be rendered. */ void FillRect(SDL_Rect rect); /*! \brief Gets the current renderer's width and height. * * \param[out] width The current renderer width. * \param[out] height The current renderer height. * * \returns <b>0</b> on success or a negative error code on failure; * call SDL_GetError() for more information. * [extracted from SDL's SDL_GetRendererOutputSize page] * * A shortcut that calls and returns * `SDL_GetRendererOutputSize(_renderer, width, height)`. */ int GetRendererSize(int* width, int* height); /*! \brief Set x, y, width and height of a SDL_Rect. * * \param[in,out] rect The SDL_Rect to be set. * \param x The X position. * \param y The Y position. * \param width The rectangle width. * \param height The rectangle height. */ void SetRect(SDL_Rect* rect, int x, int y, int width, int height); /*! \brief Gets a SDL_Rect structure with then given x, y, width * and height. * * \param x The X position. * \param y The Y position. * \param width The rectangle width. * \param height The rectangle height. * * \returns A SDL_Rect structure with the given fields filled. */ SDL_Rect GetRect(int x, int y, int width, int height); /*! \brief Send a loading status update to the status queue. * * \param status The message status to be sent. * * If SGB_Screen::_statusQueue is not NULL, the `status` message * will be put at the end of the queue, being accessed * by a SGB_LoadingScreen instance's * SGB_LoadingScreen::PullLoadingStatus method. */ void PushLoadingStatus(SGB_LoadingScreenStatus status); /*! \brief Holds the SGB_Display instance set by SetDisplay() */ SGB_Display* _display; /*! \brief Holds the SDL_Renderer instance created by the * SGB_Display set by SetDisplay() */ SDL_Renderer* _renderer; /*! \brief Holds the SGB_LoadingQueue instance set by * SetLoadingQueue(). * * The value is NULL if there is no SGB_LoadingScreen associated * with this SGB_Screen instance. */ SGB_LoadingQueue* _statusQueue; };
30.790984
89
0.724877
5f95cda354d035b82194a25e5e552fc97bb1cd8f
1,192
c
C
engine/dc/timer.c
christianhaitian/openbor
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
[ "BSD-3-Clause" ]
600
2017-04-05T07:52:07.000Z
2022-03-31T07:56:47.000Z
engine/dc/timer.c
christianhaitian/openbor
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
[ "BSD-3-Clause" ]
166
2017-04-16T12:16:11.000Z
2022-03-02T21:42:48.000Z
engine/dc/timer.c
christianhaitian/openbor
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
[ "BSD-3-Clause" ]
105
2017-04-05T08:18:08.000Z
2022-03-31T06:44:04.000Z
/* * OpenBOR - http://www.LavaLit.com * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in OpenBOR root for details. * * Copyright (c) 2004 - 2011 OpenBOR Team */ #include "kos.h" #include "timer.h" static unsigned lastinterval = 0; static unsigned tickinit = 0; unsigned newticks = 0; unsigned getTicks() { uint32 milis=0, secs=0; timer_ms_gettime(&secs, &milis); return (((secs*1000)+milis)-tickinit); } void borTimerInit() { uint32 milis=0, secs=0; timer_ms_gettime(&secs, &milis); tickinit = (secs*1000)+milis; } void borTimerExit() { } unsigned timer_getinterval(unsigned freq) { unsigned tickspassed,ebx,blocksize,now; now=timer_gettick()-newticks; ebx=now-lastinterval; blocksize=1000/freq; ebx+=1000%freq; tickspassed=ebx/blocksize; ebx-=ebx%blocksize; lastinterval+=ebx; return tickspassed; } unsigned timer_gettick() { return getTicks(); } u64 timer_uticks() { return timer_gettick() * 1000LL; } unsigned get_last_interval() { return lastinterval; } void set_last_interval(unsigned value) { lastinterval = value; } void set_ticks(unsigned value) { newticks = value; }
16.788732
75
0.672819
271370e5cb284588df966ef4f9cb31e0325665ca
3,644
h
C
Dump/Lobby_classes.h
patrickcjk/RogueCompanyDump
fc83446500e8713f12e9f6a95cfa07f756a6b5c3
[ "MIT" ]
null
null
null
Dump/Lobby_classes.h
patrickcjk/RogueCompanyDump
fc83446500e8713f12e9f6a95cfa07f756a6b5c3
[ "MIT" ]
null
null
null
Dump/Lobby_classes.h
patrickcjk/RogueCompanyDump
fc83446500e8713f12e9f6a95cfa07f756a6b5c3
[ "MIT" ]
1
2021-02-25T00:48:25.000Z
2021-02-25T00:48:25.000Z
// Class Lobby.LobbyBeaconClient // Size: 0x338 (Inherited: 0x2b0) struct ALobbyBeaconClient : public AOnlineBeaconClient { struct ALobbyBeaconState* LobbyState; // 0x2b0(0x08) struct ALobbyBeaconPlayerState* PlayerState; // 0x2b8(0x08) char UnknownData_2C0[0x1]; // 0x2c0(0x01) enum class ELobbyBeaconJoinState LobbyJoinServerState; // 0x2c1(0x01) char UnknownData_2C2[0x76]; // 0x2c2(0x76) void ServerSetPartyOwner(struct FUniqueNetIdRepl InUniqueId, struct FUniqueNetIdRepl InPartyOwnerId); // Function Lobby.LobbyBeaconClient.ServerSetPartyOwner void ServerNotifyJoiningServer(); // Function Lobby.LobbyBeaconClient.ServerNotifyJoiningServer void ServerLoginPlayer(struct FString InSessionId, struct FUniqueNetIdRepl InUniqueId, struct FString UrlString); // Function Lobby.LobbyBeaconClient.ServerLoginPlayer void ServerKickPlayer(struct FUniqueNetIdRepl PlayerToKick, struct FText Reason); // Function Lobby.LobbyBeaconClient.ServerKickPlayer void ServerDisconnectFromLobby(); // Function Lobby.LobbyBeaconClient.ServerDisconnectFromLobby void ServerCheat(struct FString Msg); // Function Lobby.LobbyBeaconClient.ServerCheat void ClientWasKicked(struct FText KickReason); // Function Lobby.LobbyBeaconClient.ClientWasKicked void ClientSetInviteFlags(struct FJoinabilitySettings Settings); // Function Lobby.LobbyBeaconClient.ClientSetInviteFlags void ClientPlayerLeft(struct FUniqueNetIdRepl InUniqueId); // Function Lobby.LobbyBeaconClient.ClientPlayerLeft void ClientPlayerJoined(struct FText NewPlayerName, struct FUniqueNetIdRepl InUniqueId); // Function Lobby.LobbyBeaconClient.ClientPlayerJoined void ClientLoginComplete(struct FUniqueNetIdRepl InUniqueId, bool bWasSuccessful); // Function Lobby.LobbyBeaconClient.ClientLoginComplete void ClientJoinGame(); // Function Lobby.LobbyBeaconClient.ClientJoinGame void ClientAckJoiningServer(); // Function Lobby.LobbyBeaconClient.ClientAckJoiningServer }; // Class Lobby.LobbyBeaconHost // Size: 0x280 (Inherited: 0x248) struct ALobbyBeaconHost : public AOnlineBeaconHostObject { char UnknownData_248[0x8]; // 0x248(0x08) SoftClassProperty LobbyStateClass; // 0x250(0x28) struct ALobbyBeaconState* LobbyState; // 0x278(0x08) }; // Class Lobby.LobbyBeaconPlayerState // Size: 0x2e0 (Inherited: 0x220) struct ALobbyBeaconPlayerState : public AInfo { struct FText DisplayName; // 0x220(0x18) struct FUniqueNetIdRepl UniqueId; // 0x238(0x28) struct FUniqueNetIdRepl PartyOwnerUniqueId; // 0x260(0x28) bool bInLobby; // 0x288(0x01) char UnknownData_289[0x7]; // 0x289(0x07) struct AOnlineBeaconClient* ClientActor; // 0x290(0x08) char UnknownData_298[0x48]; // 0x298(0x48) void OnRep_UniqueId(); // Function Lobby.LobbyBeaconPlayerState.OnRep_UniqueId void OnRep_PartyOwner(); // Function Lobby.LobbyBeaconPlayerState.OnRep_PartyOwner void OnRep_InLobby(); // Function Lobby.LobbyBeaconPlayerState.OnRep_InLobby }; // Class Lobby.LobbyBeaconState // Size: 0x3c8 (Inherited: 0x220) struct ALobbyBeaconState : public AInfo { int32_t MaxPlayers; // 0x220(0x04) char UnknownData_224[0x4]; // 0x224(0x04) struct ALobbyBeaconPlayerState* LobbyBeaconPlayerStateClass; // 0x228(0x08) char UnknownData_230[0x8]; // 0x230(0x08) bool bLobbyStarted; // 0x238(0x01) char UnknownData_239[0x3]; // 0x239(0x03) float WaitForPlayersTimeRemaining; // 0x23c(0x04) struct FLobbyPlayerStateInfoArray Players; // 0x240(0x120) char UnknownData_360[0x68]; // 0x360(0x68) void OnRep_WaitForPlayersTimeRemaining(); // Function Lobby.LobbyBeaconState.OnRep_WaitForPlayersTimeRemaining void OnRep_LobbyStarted(); // Function Lobby.LobbyBeaconState.OnRep_LobbyStarted };
55.212121
168
0.816685
16ade8cb14874f5ad7a003370b268ba9b2aac0cf
3,399
h
C
core/arch/arm/tee/replay/wr_8.h
zaxguo/optee-os
da22949de86eedeba56cd3ba9bcdb3b0b11c26b2
[ "BSD-2-Clause" ]
null
null
null
core/arch/arm/tee/replay/wr_8.h
zaxguo/optee-os
da22949de86eedeba56cd3ba9bcdb3b0b11c26b2
[ "BSD-2-Clause" ]
null
null
null
core/arch/arm/tee/replay/wr_8.h
zaxguo/optee-os
da22949de86eedeba56cd3ba9bcdb3b0b11c26b2
[ "BSD-2-Clause" ]
null
null
null
#include "common.h" static void wr_template(int addr, int count, void *replay_dma_chan, void *host) { printk("write[%d:%d]\n", addr, count); u32 **cbs, **pgs; if (replay_dma_chan == NULL || host == NULL) { EMSG("dma: %p or host: %p, invalid!\n", replay_dma_chan, host); return; } dma_addr_t cb = prepare_cb(TO_DEV, count, &cbs, &pgs); req_read(host, SDEDM, 0x00010801); req_read(host, SDCMD, 0x0000000d); req_read(host, SDHSTS, 0x00000000); req_write(host, SDHCFG, 0x0000040e); req_write(host, SDHBCT, 0x00000200); /* blk count parameterize */ req_write(host, SDHBLC, count); /*lwg: below sector number, parameterized */ req_write(host, SDARG, addr); req_write(host, SDCMD, 0x00008099); req_write(replay_dma_chan, BCM2835_DMA_ADDR, cb); printk("%d:start... (debug = %08x, src = %08x)\n", __LINE__, readl(replay_dma_chan + BCM2835_DMA_DEBUG), readl(replay_dma_chan + BCM2835_DMA_SOURCE_AD)); req_write(replay_dma_chan, BCM2835_DMA_CS, 0x00000001); req_read(replay_dma_chan, BCM2835_DMA_CS, 0x0000000b); req_read(host, SDCMD, 0x00000099); req_read(host, SDRSP0, 0x00000900); u32 val; do { cpu_relax(); val = readl(replay_dma_chan + BCM2835_DMA_CS); printk("%d:poll... (val = %08x, debug = %08x, src = %08x)\n", __LINE__, val, readl(replay_dma_chan + BCM2835_DMA_DEBUG), readl(replay_dma_chan + BCM2835_DMA_SOURCE_AD)); //udelay(1); } while ((val &= 0x00000004) == 0); /* ack */ reply_write(replay_dma_chan, BCM2835_DMA_CS, 0x00000004); printk("%d:ack ... (debug = %08x, src = %08x)\n", __LINE__, readl(replay_dma_chan + BCM2835_DMA_DEBUG), readl(replay_dma_chan + BCM2835_DMA_SOURCE_AD)); /* > 8 sectors busy flag will be on */ if (count > 8) { reply_read(host, SDHSTS, 0x00000001); } else { reply_read(host, SDHSTS, 0x00000000); } reply_read(host, SDCMD, 0x00000099); if (count > 8) { reply_read(host, SDEDM, 0x00010807); /* again?? */ reply_read(host, SDEDM, 0x00010807); reply_read(host, SDEDM, 0x00010807); } else { reply_read(host, SDEDM, 0x00010801); } reply_write(host, SDHCFG, 0x0000040e); reply_read(host, SDCMD, 0x00000099); if (count > 8) { reply_read(host, SDHSTS, 0x00000001); } else { reply_read(host, SDHSTS, 0x00000000); } reply_write(host, SDARG, 0x00000000); reply_write(host, SDCMD, 0x0000880c); /* poll */ #if 1 do { val = readl(host + SDHSTS); /*printk("%d:poll... (val = %08x\n", __LINE__, val);*/ } while (val != 0x00000400); #endif /*reply_read(host, SDHSTS, 0x00000400);*/ reply_write(host, SDHSTS, 0x00000701); reply_read(host, SDCMD, 0x0000080c); reply_read(host, SDRSP0, 0x00000c00); reply_read(host, SDHSTS, 0x00000000); req_read(host, SDEDM, 0x00010801); req_read(host, SDCMD, 0x0000080c); req_read(host, SDHSTS, 0x00000000); req_write(host, SDARG, 0x59b40000); req_write(host, SDCMD, 0x0000800d); //req_read(host, SDCMD, 0x0000800d); //req_read(host, SDCMD, 0x0000800d); //req_read(host, SDCMD, 0x0000000d); // summarize while(readl(host + SDCMD) != 0x0000000d); req_read(host, SDRSP0, 0x00000900); cleanup_mem(count, cbs, pgs); } static void wr_256(int sec, void *replay_dma_chan, void *host) { wr_template(sec, 256, replay_dma_chan, host); } static void wr_32(int sec, void *replay_dma_chan, void *host) { wr_template(sec, 32, replay_dma_chan, host); } static void wr_8(int sec, void *replay_dma_chan, void *host) { wr_template(sec, 8, replay_dma_chan, host); }
33.653465
171
0.705207
1d046810e3e46e3ffab144f257139358d5d7f3cd
154
c
C
src/network/listen.c
PacBrew/ps4-openorbis-musl
091e9f0d5d9ab5a5535ddb9cfbb85ea665d5afcc
[ "MIT" ]
25
2020-05-22T08:51:02.000Z
2022-03-28T08:05:27.000Z
src/network/listen.c
PacBrew/ps4-openorbis-musl
091e9f0d5d9ab5a5535ddb9cfbb85ea665d5afcc
[ "MIT" ]
16
2020-05-24T22:30:51.000Z
2022-02-02T22:26:23.000Z
src/network/listen.c
PacBrew/ps4-openorbis-musl
091e9f0d5d9ab5a5535ddb9cfbb85ea665d5afcc
[ "MIT" ]
9
2020-05-24T21:51:18.000Z
2022-03-01T06:36:57.000Z
#include <sys/socket.h> #include "syscall.h" #ifndef PS4 int listen(int fd, int backlog) { return socketcall(listen, fd, backlog, 0, 0, 0, 0); } #endif
15.4
52
0.681818
1d06da8779d0087a16bbbe0966c7fd9c6751aad1
4,678
h
C
uboot/include/ppc4xx.h
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
null
null
null
uboot/include/ppc4xx.h
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
null
null
null
uboot/include/ppc4xx.h
LoongPenguin/Linux_210
d941ed620798fb9c96b5d06764fb1dcb68057513
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------------+ | | This source code has been made available to you by IBM on an AS-IS | basis. Anyone receiving this source is licensed under IBM | copyrights to use it in any way he or she deems fit, including | copying it, modifying it, compiling it, and redistributing it either | with or without modifications. No license under IBM patents or | patent applications is to be implied by the copyright license. | | Any user of this software should understand that IBM cannot provide | technical support for this software and will not be responsible for | any consequences resulting from the use of this software. | | Any person who transfers this source code or any derivative work | must include the IBM copyright notice, this paragraph, and the | preceding two paragraphs in the transferred software. | | COPYRIGHT I B M CORPORATION 1999 | LICENSED MATERIAL - PROGRAM PROPERTY OF I B M +----------------------------------------------------------------------------*/ #ifndef __PPC4XX_H__ #define __PPC4XX_H__ /* * Configure which SDRAM/DDR/DDR2 controller is equipped */ #if defined(CONFIG_405GP) || defined(CONFIG_405CR) || defined(CONFIG_405EP) || \ defined(CONFIG_AP1000) || defined(CONFIG_ML2) #define CONFIG_SDRAM_PPC4xx_IBM_SDRAM /* IBM SDRAM controller */ #endif #if defined(CONFIG_440GP) || defined(CONFIG_440GX) || \ defined(CONFIG_440EP) || defined(CONFIG_440GR) #define CONFIG_SDRAM_PPC4xx_IBM_DDR /* IBM DDR controller */ #endif #if defined(CONFIG_440EPX) || defined(CONFIG_440GRX) #define CONFIG_SDRAM_PPC4xx_DENALI_DDR2 /* Denali DDR(2) controller */ #endif #if defined(CONFIG_405EX) || \ defined(CONFIG_440SP) || defined(CONFIG_440SPE) || \ defined(CONFIG_460EX) || defined(CONFIG_460GT) #define CONFIG_SDRAM_PPC4xx_IBM_DDR2 /* IBM DDR(2) controller */ #endif #if defined(CONFIG_440) /* * Enable long long (%ll ...) printf format on 440 PPC's since most of * them support 36bit physical addressing */ #define CFG_64BIT_VSPRINTF #define CFG_64BIT_STRTOUL #include <ppc440.h> #else #include <ppc405.h> #endif #include <asm/ppc4xx-sdram.h> /* * Macro for generating register field mnemonics */ #define PPC_REG_BITS 32 #define PPC_REG_VAL(bit, value) ((value) << ((PPC_REG_BITS - 1) - (bit))) /* * Elide casts when assembling register mnemonics */ #ifndef __ASSEMBLY__ #define static_cast(type, val) (type)(val) #else #define static_cast(type, val) (val) #endif /* * Common stuff for 4xx (405 and 440) */ #define EXC_OFF_SYS_RESET 0x0100 /* System reset */ #define _START_OFFSET (EXC_OFF_SYS_RESET + 0x2000) #define RESET_VECTOR 0xfffffffc #define CACHELINE_MASK (CFG_CACHELINE_SIZE - 1) /* Address mask for cache line aligned data. */ #define CPR0_DCR_BASE 0x0C #define cprcfga (CPR0_DCR_BASE+0x0) #define cprcfgd (CPR0_DCR_BASE+0x1) #define SDR_DCR_BASE 0x0E #define sdrcfga (SDR_DCR_BASE+0x0) #define sdrcfgd (SDR_DCR_BASE+0x1) #define SDRAM_DCR_BASE 0x10 #define memcfga (SDRAM_DCR_BASE+0x0) #define memcfgd (SDRAM_DCR_BASE+0x1) #define EBC_DCR_BASE 0x12 #define ebccfga (EBC_DCR_BASE+0x0) #define ebccfgd (EBC_DCR_BASE+0x1) /* * Macros for indirect DCR access */ #define mtcpr(reg, d) do { mtdcr(cprcfga,reg);mtdcr(cprcfgd,d); } while (0) #define mfcpr(reg, d) do { mtdcr(cprcfga,reg);d = mfdcr(cprcfgd); } while (0) #define mtebc(reg, d) do { mtdcr(ebccfga,reg);mtdcr(ebccfgd,d); } while (0) #define mfebc(reg, d) do { mtdcr(ebccfga,reg);d = mfdcr(ebccfgd); } while (0) #define mtsdram(reg, d) do { mtdcr(memcfga,reg);mtdcr(memcfgd,d); } while (0) #define mfsdram(reg, d) do { mtdcr(memcfga,reg);d = mfdcr(memcfgd); } while (0) #define mtsdr(reg, d) do { mtdcr(sdrcfga,reg);mtdcr(sdrcfgd,d); } while (0) #define mfsdr(reg, d) do { mtdcr(sdrcfga,reg);d = mfdcr(sdrcfgd); } while (0) #ifndef __ASSEMBLY__ typedef struct { unsigned long freqDDR; unsigned long freqEBC; unsigned long freqOPB; unsigned long freqPCI; unsigned long freqPLB; unsigned long freqTmrClk; unsigned long freqUART; unsigned long freqProcessor; unsigned long freqVCOHz; unsigned long freqVCOMhz; /* in MHz */ unsigned long pciClkSync; /* PCI clock is synchronous */ unsigned long pciIntArbEn; /* Internal PCI arbiter is enabled */ unsigned long pllExtBusDiv; unsigned long pllFbkDiv; unsigned long pllFwdDiv; unsigned long pllFwdDivA; unsigned long pllFwdDivB; unsigned long pllOpbDiv; unsigned long pllPciDiv; unsigned long pllPlbDiv; } PPC4xx_SYS_INFO; #endif /* __ASSEMBLY__ */ #endif /* __PPC4XX_H__ */
31.608108
80
0.699872
0eb731f6e2ea92530297cc12220246c39d793492
1,394
h
C
Plugins/UnrealDotNet/Source/UnrealDotNetRuntime/Public/Generate/Export/UPawnAction_BlueprintBase.h
mrkriv/UnrealDotNet
55f6982727d8f24ba08bfaca73109bd8140428ab
[ "Apache-2.0" ]
36
2018-04-09T09:40:53.000Z
2022-02-11T09:10:38.000Z
Plugins/UnrealDotNet/Source/UnrealDotNetRuntime/Public/Generate/Export/UPawnAction_BlueprintBase.h
mrkriv/UnrealDotNet
55f6982727d8f24ba08bfaca73109bd8140428ab
[ "Apache-2.0" ]
1
2019-03-12T10:16:13.000Z
2019-03-14T10:56:15.000Z
Plugins/UnrealDotNet/Source/UnrealDotNetRuntime/Public/Generate/Export/UPawnAction_BlueprintBase.h
mrkriv/UnrealDotNet
55f6982727d8f24ba08bfaca73109bd8140428ab
[ "Apache-2.0" ]
11
2018-04-09T09:41:02.000Z
2022-03-31T08:04:51.000Z
#pragma once // This file was created automatically, do not modify the contents of this file. PRAGMA_DISABLE_DEPRECATION_WARNINGS #include "CoreMinimal.h" #include "ManageEventSender.h" #include "Runtime/AIModule/Classes/Actions/PawnAction_BlueprintBase.h" // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Actions\PawnAction_BlueprintBase.h:13 extern "C" { DOTNET_EXPORT INT_PTR E_NewObject_UPawnAction_BlueprintBase(UObject* Parent, char* Name) { return (INT_PTR)NewObject<UPawnAction_BlueprintBase>(Parent, FName(UTF8_TO_TCHAR(Name))); } DOTNET_EXPORT auto E_UPawnAction_BlueprintBase_ActionPause(UPawnAction_BlueprintBase* Self, APawn* ControlledPawn) { auto _p0 = ControlledPawn; Self->ActionPause(_p0); } DOTNET_EXPORT auto E_UPawnAction_BlueprintBase_ActionResume(UPawnAction_BlueprintBase* Self, APawn* ControlledPawn) { auto _p0 = ControlledPawn; Self->ActionResume(_p0); } DOTNET_EXPORT auto E_UPawnAction_BlueprintBase_ActionStart(UPawnAction_BlueprintBase* Self, APawn* ControlledPawn) { auto _p0 = ControlledPawn; Self->ActionStart(_p0); } DOTNET_EXPORT auto E_UPawnAction_BlueprintBase_ActionTick(UPawnAction_BlueprintBase* Self, APawn* ControlledPawn, float DeltaSeconds) { auto _p0 = ControlledPawn; auto _p1 = DeltaSeconds; Self->ActionTick(_p0, _p1); } } PRAGMA_ENABLE_DEPRECATION_WARNINGS
29.659574
134
0.806313
cde2ae68f5728f8e2b960047ed0304721ce1053e
738
h
C
utils/file_utils.h
fletcherjiang/ssm-alipay
d7cd911c72c2538859597b9ed3c96d02693febf2
[ "Apache-2.0" ]
169
2021-10-07T03:50:42.000Z
2021-12-20T01:55:51.000Z
utils/file_utils.h
fletcherjiang/ssm-alipay
d7cd911c72c2538859597b9ed3c96d02693febf2
[ "Apache-2.0" ]
11
2021-10-09T01:53:49.000Z
2021-10-09T01:53:49.000Z
utils/file_utils.h
JoeAnimation/ssm-alipay
d7cd911c72c2538859597b9ed3c96d02693febf2
[ "Apache-2.0" ]
56
2021-10-07T03:50:53.000Z
2021-10-12T00:41:59.000Z
/** * @file file_utils.h * * Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved. * * 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. */ #ifndef ACL_UTILS_FILE_UTILS_H #define ACL_UTILS_FILE_UTILS_H #include <string> #include <vector> #include "acl/acl_base.h" namespace acl { namespace file_utils { using FileNameFilterFn = bool(const std::string &fileName); aclError ListFiles(const std::string &dirName, FileNameFilterFn filter, std::vector<std::string> &names, int32_t maxDepth); } // namespace file_utils } // namespace acl #endif // ACL_UTILS_FILE_UTILS_H
24.6
77
0.753388
077e476d0c18a498189b6f8ab2737bb8e31f0993
1,301
h
C
gui/qimageview/QImageFileEditor.h
amyznikov/SerStacker
6657240210af0b35fff1c5adc1d6f9d51b469e80
[ "CC0-1.0" ]
1
2021-09-03T06:02:59.000Z
2021-09-03T06:02:59.000Z
gui/qimageview/QImageFileEditor.h
amyznikov/SerStacker
6657240210af0b35fff1c5adc1d6f9d51b469e80
[ "CC0-1.0" ]
1
2021-09-03T03:43:54.000Z
2021-09-10T01:30:46.000Z
gui/qimageview/QImageFileEditor.h
amyznikov/SerStacker
6657240210af0b35fff1c5adc1d6f9d51b469e80
[ "CC0-1.0" ]
null
null
null
/* * QImageFileEditor.h * * Created on: Feb 24, 2021 * Author: amyznikov */ #ifndef __QImageFileEditor_h__ #define __QImageFileEditor_h__ #include "QImageEditor.h" #include "QPlaySequenceControl.h" #include <core/io/c_input_sequence.h> class QImageFileEditor : public QImageEditor { Q_OBJECT; public: typedef QImageFileEditor ThisClass; typedef QImageEditor Base; QImageFileEditor(QWidget * parent = Q_NULLPTR); void openImage(const std::string & pathfilename); void openImage(const QString & pathfilename); void openImages(const std::vector<std::string> & pathfilenames); void openImages(const QStringList & pathfilenames); void setImage(cv::InputArray image, cv::InputArray mask, cv::InputArray imageData /*= cv::noArray()*/, bool make_copy /*= true*/) override; void editImage(cv::InputArray image, cv::InputArray mask) override; void closeCurrentSequence(); const c_input_sequence::ptr & input_sequence() const; protected slots: void startDisplay(); void loadNextFrame(); void onSeek(int pos); protected: //void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; protected: c_input_sequence::ptr input_sequence_; QPlaySequenceControl * playControls = Q_NULLPTR; }; #endif /* __QImageFileEditor_h__ */
25.509804
141
0.749424
e0556e840256331f1e8ecfd422eb4a2d2512f853
529
h
C
swift/Problem 81/Problem 81/Problem_81.h
SebastienFCT/daily-coding-problem
209eeb24c24ad5450ce2f7dbf9678281f9c6895e
[ "MIT" ]
10
2020-04-04T14:57:43.000Z
2022-02-02T13:48:15.000Z
swift/Problem 81/Problem 81/Problem_81.h
SebastienFCT/daily-coding-problem
209eeb24c24ad5450ce2f7dbf9678281f9c6895e
[ "MIT" ]
null
null
null
swift/Problem 81/Problem 81/Problem_81.h
SebastienFCT/daily-coding-problem
209eeb24c24ad5450ce2f7dbf9678281f9c6895e
[ "MIT" ]
3
2019-12-06T03:54:25.000Z
2020-01-10T16:19:15.000Z
// // Problem_81.h // Problem 81 // // Created by sebastien FOCK CHOW THO on 2019-08-14. // Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for Problem_81. FOUNDATION_EXPORT double Problem_81VersionNumber; //! Project version string for Problem_81. FOUNDATION_EXPORT const unsigned char Problem_81VersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Problem_81/PublicHeader.h>
26.45
135
0.763705
b8e73a74cbd86e7189740ba2e8e4f4ebd333e487
658
h
C
BaseUtility/Classes/BaseUtility/BaseTools/ToolsClass/CustomSectionColorLayout.h
XueYangLee/BaseUtility
474a3ef3de1cf40b8c615e07123cc810e13573e9
[ "MIT" ]
null
null
null
BaseUtility/Classes/BaseUtility/BaseTools/ToolsClass/CustomSectionColorLayout.h
XueYangLee/BaseUtility
474a3ef3de1cf40b8c615e07123cc810e13573e9
[ "MIT" ]
null
null
null
BaseUtility/Classes/BaseUtility/BaseTools/ToolsClass/CustomSectionColorLayout.h
XueYangLee/BaseUtility
474a3ef3de1cf40b8c615e07123cc810e13573e9
[ "MIT" ]
null
null
null
// // CustomSectionColorLayout.h // BaseTools // // Created by Singularity on 2020/8/12. // Copyright © 2020 Singularity. All rights reserved. // UICollectionView section背景色原始方法 @interface ViewController ()<CustomSectionColorLayout> #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN //@protocol CustomSectionColorLayout <UICollectionViewDelegateFlowLayout> // //@optional //- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section; // //@end // //@interface CustomSectionColorLayout : UICollectionViewFlowLayout // //@end NS_ASSUME_NONNULL_END
26.32
164
0.791793
897da4d1e0b09bb25f46140c250811cc1d0ae331
2,270
h
C
src/main/include/RobotContainer.h
ericwetzel7/2022-core-mentor
0591b537ba602ec5d44220541cddb42e88d811c2
[ "BSD-3-Clause" ]
null
null
null
src/main/include/RobotContainer.h
ericwetzel7/2022-core-mentor
0591b537ba602ec5d44220541cddb42e88d811c2
[ "BSD-3-Clause" ]
null
null
null
src/main/include/RobotContainer.h
ericwetzel7/2022-core-mentor
0591b537ba602ec5d44220541cddb42e88d811c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #pragma once #include "Constants.h" #include <frc2/command/Command.h> #include <frc2/command/SequentialCommandGroup.h> #include <frc2/command/InstantCommand.h> #include <frc2/command/RunCommand.h> #include <frc2/command/WaitCommand.h> #include "commands/DriveToLineCommand.h" #include "commands/DriveUntilCommand.h" #include <units/time.h> #ifdef USE_XBOX_CONTROLS #include <frc/XboxController.h> #else #include <frc/Joystick.h> #endif #include <frc/Timer.h> #include "subsystems/ClimberSubsystem.h" #include "subsystems/DriveSubsytem.h" #include "subsystems/IntakeSubsystem.h" #include "subsystems/ShooterSubsystem.h" #include "subsystems/TransportSubsystem.h" /** * This class is where the bulk of the robot should be declared. Since * Command-based is a "declarative" paradigm, very little robot logic should * actually be handled in the {@link Robot} periodic methods (other than the * scheduler calls). Instead, the structure of the robot (including subsystems, * commands, and button mappings) should be declared here. */ class RobotContainer { public: RobotContainer(); frc2::Command* autonomousCommand(); private: // The robot's subsystems and commands are defined here... DriveSubsystem driveSubsystem; ClimberSubsystem climberSubsystem; IntakeSubsystem intakeSubsystem; ShooterSubsystem shooterSubsystem; TransportSubsystem transportSubsystem; #ifdef USE_XBOX_CONTROLS frc::XboxController controller{constants::XBOX_CONTROL}; #else frc::Joystick control1{constants::CONTROL1}; frc::Joystick control2{constants::CONTROL2}; #endif frc::Timer innerTimer; void ConfigureButtonBindings(); frc2::SequentialCommandGroup autocmd{ frc2::InstantCommand([this]{transportSubsystem.disableInnerBelt();}), DriveToLineCommand(&driveSubsystem, false), frc2::InstantCommand([this]{driveSubsystem.resetDistance();}), DriveUntilCommand(&driveSubsystem, false, [this] { return driveSubsystem.distance() <= -33; }), frc2::RunCommand([this] { transportSubsystem.enableInnerBelt(); }) }; };
30.675676
80
0.761233
32c183d0268845cbaa460e6fcc186edd151e22f6
2,451
c
C
fw/blink.c
svarvel/battor
1c79bb0f7d2a5773f5971c9df8b5fd6f815ade35
[ "Apache-2.0" ]
15
2015-05-29T14:40:27.000Z
2021-01-10T06:20:15.000Z
fw/blink.c
svarvel/battor
1c79bb0f7d2a5773f5971c9df8b5fd6f815ade35
[ "Apache-2.0" ]
65
2015-02-28T23:23:51.000Z
2021-08-17T19:52:55.000Z
fw/blink.c
svarvel/battor
1c79bb0f7d2a5773f5971c9df8b5fd6f815ade35
[ "Apache-2.0" ]
6
2015-02-07T01:47:02.000Z
2021-07-01T22:55:32.000Z
#include "common.h" #include "blink.h" static uint16_t blink_ms, blink_strobe_ms; static uint16_t blink_interval_ms, blink_strobe_count, blink_strobe_idx; static uint32_t blink_prev_ms_ticks, blink_strobe_prev_ms_ticks; static uint8_t blink_led; static uint8_t first_blink; static uint8_t strobe_state; typedef enum STROBE_STATE_enum { STROBE_STATE_FIRST, STROBE_STATE_WAIT_FOR_LED_ON, STROBE_STATE_LED_ON, STROBE_STATE_LED_OFF, } STROBE_STATE_t; void blink_init(uint16_t interval_ms, uint8_t led) { blink_led = led; blink_interval_ms = interval_ms; blink_ms = 0; blink_strobe_ms = 0; blink_strobe_count = 1; blink_strobe_idx = 0; blink_prev_ms_ticks = 0; blink_strobe_prev_ms_ticks = 0; first_blink = 1; led_off(led); } void blink_ms_timer_update() { if (first_blink) { blink_ms = blink_interval_ms; blink_prev_ms_ticks = g_timer_ms_ticks; blink_strobe_ms = 0; strobe_state = STROBE_STATE_FIRST; first_blink = 0; } blink_ms += timer_elapsed_ms(blink_prev_ms_ticks, g_timer_ms_ticks); blink_prev_ms_ticks = g_timer_ms_ticks; if (blink_ms >= blink_interval_ms) { if (strobe_state == STROBE_STATE_FIRST) { blink_strobe_prev_ms_ticks = g_timer_ms_ticks; blink_strobe_idx = 0; strobe_state = STROBE_STATE_WAIT_FOR_LED_ON; } blink_strobe_ms += timer_elapsed_ms(blink_strobe_prev_ms_ticks, g_timer_ms_ticks); blink_strobe_prev_ms_ticks = g_timer_ms_ticks; if (blink_strobe_idx < blink_strobe_count) { switch (strobe_state) { case STROBE_STATE_WAIT_FOR_LED_ON: led_on(blink_led); blink_strobe_ms = 0; strobe_state = STROBE_STATE_LED_ON; break; case STROBE_STATE_LED_ON: if (blink_strobe_ms >= BLINK_STROBE_ON_TIME_MS) { led_off(blink_led); blink_strobe_ms = 0; strobe_state = STROBE_STATE_LED_OFF; } break; case STROBE_STATE_LED_OFF: if (blink_strobe_ms >= BLINK_STROBE_OFF_TIME_MS) { strobe_state = STROBE_STATE_WAIT_FOR_LED_ON; blink_strobe_idx++; } break; } } else { blink_ms = 0; strobe_state = STROBE_STATE_FIRST; } } } void blink_set_led(uint8_t led) { // turn of old blink led led_off(blink_led); blink_led = led; first_blink = 1; } void blink_set_interval_ms(uint16_t interval_ms) { blink_interval_ms = interval_ms; first_blink = 1; } void blink_set_strobe_count(uint16_t count) { if (count > 0) { blink_strobe_count = count; first_blink = 1; } }
21.883929
84
0.745002
9be8198a92da4ee6ebff112c4840350dabb37302
338
c
C
src/php-src/auto/php3_get_browser.c
cuhk-seclab/XSym
6e4f0a3d8cc78e8f4e85045bac2e0eb80511c193
[ "MIT" ]
3
2021-10-11T11:21:03.000Z
2021-11-24T03:49:19.000Z
src/php-src/auto/php3_get_browser.c
cuhk-seclab/XSym
6e4f0a3d8cc78e8f4e85045bac2e0eb80511c193
[ "MIT" ]
null
null
null
src/php-src/auto/php3_get_browser.c
cuhk-seclab/XSym
6e4f0a3d8cc78e8f4e85045bac2e0eb80511c193
[ "MIT" ]
null
null
null
#include "stdio.h" #include "phli.h" void php3_get_browser(INTERNAL_FUNCTION_PARAMETERS); int main(int argc, char* argv[]) { char *result_dir="/data/phli/results/php3_get_browser/"; HashTable *ht; HashTable *list; HashTable *plist; pval *return_value=phli_construct_pval_string("arg_1"); php3_get_browser(ht, return_value, list, plist); }
30.727273
56
0.781065
7472feae59ab8c567402be2b95a418bf026fe7a6
1,762
c
C
os/sys/hash-map.c
Chiburator/master-scheduler
857ad6a7dd4d6413517d0191e23883c3938a15e4
[ "BSD-3-Clause" ]
null
null
null
os/sys/hash-map.c
Chiburator/master-scheduler
857ad6a7dd4d6413517d0191e23883c3938a15e4
[ "BSD-3-Clause" ]
null
null
null
os/sys/hash-map.c
Chiburator/master-scheduler
857ad6a7dd4d6413517d0191e23883c3938a15e4
[ "BSD-3-Clause" ]
1
2021-09-14T15:47:35.000Z
2021-09-14T15:47:35.000Z
/** * \file * Simple fixed Hash map * \author * Oliver Harms <harms@chalmers.se> * */ #include "contiki.h" #include "hash-map.h" void hash_map_clear_table(hash_table_t *table){ uint8_t pos; hash_node_t *node; table->number_entries = 0; for (pos = 0; pos < HASH_MAP_SIZE; ++pos){ node = &(table->list[pos]); node->key = 0; node->val = 0; node->next = NULL; } } static uint8_t hash_code(uint8_t key){ return (key % HASH_MAP_SIZE); } uint8_t hash_map_insert(hash_table_t *table, uint16_t key, uint16_t val){ uint8_t pos = hash_code(key); hash_node_t *node = &(table->list[pos]); if (node->key == 0){ node->key = key; node->val = val; ++(table->number_entries); return 1; } hash_node_t *prev_node; do { if (node->key == key){ node->val = val; return 1; } prev_node = node; node = node->next; } while (node); if (table->number_entries >= HASH_MAP_SIZE){ return 0; } uint8_t pos2; for (pos2 = pos; pos2 < HASH_MAP_SIZE; ++pos2){ if (table->list[pos2].key == 0){ node = &(table->list[pos2]); node->key = key; node->val = val; prev_node->next = node; ++(table->number_entries); return 1; } } for (pos2 = 0; pos2 < pos; ++pos2){ if (table->list[pos2].key == 0){ node = &(table->list[pos2]); node->key = key; node->val = val; prev_node->next = node; ++(table->number_entries); return 1; } } return 0; } uint16_t hash_map_lookup(hash_table_t *table, uint16_t key){ uint8_t pos = hash_code(key); hash_node_t *node = &(table->list[pos]); while (node){ if (node->key == key){ return node->val; } node = node->next; } return 0; }
21.487805
73
0.570375
92dbf9142fb78b36af7927d8d21da1bf9615ea66
138
h
C
SwiftEmptyDataSet/Pods/Target Support Files/SwiftHUD/SwiftHUD-umbrella.h
15038777234/SwiftEmptyDataSet
9102a654c790db12d899edc4706f729b9e530ace
[ "MIT" ]
3
2016-08-13T09:56:42.000Z
2016-10-13T14:14:10.000Z
SwiftEmptyDataSet/Pods/Target Support Files/SwiftHUD/SwiftHUD-umbrella.h
15038777234/SwiftEmptyDataSet
9102a654c790db12d899edc4706f729b9e530ace
[ "MIT" ]
null
null
null
SwiftEmptyDataSet/Pods/Target Support Files/SwiftHUD/SwiftHUD-umbrella.h
15038777234/SwiftEmptyDataSet
9102a654c790db12d899edc4706f729b9e530ace
[ "MIT" ]
2
2016-08-17T03:47:01.000Z
2016-08-17T03:54:44.000Z
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double SwiftHUDVersionNumber; FOUNDATION_EXPORT const unsigned char SwiftHUDVersionString[];
19.714286
62
0.84058
20d0013266c819804a1b8b075bd11a72a5e659b6
19
c
C
OCaml/mini-c/tests/syntax/bad/testfile-expr6-1.c
LouisProffitX/INF564-Projet
daf78f04d7a760a773cc46a6c3c44632b5776a9c
[ "MIT" ]
null
null
null
OCaml/mini-c/tests/syntax/bad/testfile-expr6-1.c
LouisProffitX/INF564-Projet
daf78f04d7a760a773cc46a6c3c44632b5776a9c
[ "MIT" ]
null
null
null
OCaml/mini-c/tests/syntax/bad/testfile-expr6-1.c
LouisProffitX/INF564-Projet
daf78f04d7a760a773cc46a6c3c44632b5776a9c
[ "MIT" ]
null
null
null
void f() { (0)0; }
9.5
18
0.368421
dd5e86f5ccff451cb4d06ccb693313c8cd8b1cab
1,077
h
C
src/render/OGLBase/CRendererOGLBase.h
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
4
2015-08-13T08:25:36.000Z
2017-04-07T21:33:10.000Z
src/render/OGLBase/CRendererOGLBase.h
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
src/render/OGLBase/CRendererOGLBase.h
opengamejam/OpenJam
565dd19fa7f1a727966b4274b810424e5395600b
[ "MIT" ]
null
null
null
// // CRendererOGLBase.h // OpenJam // // Created by Yevgeniy Logachev // Copyright (c) 2014 Yevgeniy Logachev. All rights reserved. // #if defined(RENDER_OGL1_3) || defined(RENDER_OGLES1_0) || \ defined(RENDER_OGL1_5) || defined(RENDER_OGLES1_1) || \ defined(RENDER_OGL2_0) || defined(RENDER_OGLES2_0) #ifndef CRENDEREROGLBASE_H #define CRENDEREROGLBASE_H #include "IRenderer.h" #include "IMaterial.h" namespace jam { class CRendererOGLBase : public IRenderer { public: CRendererOGLBase(IRenderViewPtr renderView); virtual ~CRendererOGLBase(); /* * Returns render view */ virtual IRenderViewPtr RenderView() const override; /* * OpenGL specific */ virtual GLenum ConvertPrimitiveType(IMaterial::PrimitiveTypes type); private: IRenderViewPtr m_RenderView; }; }; // namespace jam #endif /* CRENDEREROGLBASE_H */ #endif /* defined(RENDER_OGL1_3) || defined(RENDER_OGLES1_0) || \ defined(RENDER_OGL1_5) || defined(RENDER_OGLES1_1) || \ defined(RENDER_OGL2_0) || defined(RENDER_OGLES2_0) */
23.413043
72
0.702878
ee4b22577f85e78393f077a34926ea3ccf94841b
4,012
h
C
kernel/drivers/net/stack/xenomai-3.0.5/kernel/cobalt/posix/process.h
oPiZiL/xenomai-deb
2d0ba1c0b19e482c3f77a80d08d7e34ff4a2f604
[ "Apache-2.0" ]
1
2019-10-12T01:38:30.000Z
2019-10-12T01:38:30.000Z
kernel/drivers/net/stack/xenomai-3.0.5/kernel/cobalt/posix/process.h
oPiZiL/xenomai-deb
2d0ba1c0b19e482c3f77a80d08d7e34ff4a2f604
[ "Apache-2.0" ]
null
null
null
kernel/drivers/net/stack/xenomai-3.0.5/kernel/cobalt/posix/process.h
oPiZiL/xenomai-deb
2d0ba1c0b19e482c3f77a80d08d7e34ff4a2f604
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 Philippe Gerum <rpm@xenomai.org>. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _COBALT_POSIX_PROCESS_H #define _COBALT_POSIX_PROCESS_H #include <linux/list.h> #include <linux/bitmap.h> #include <cobalt/kernel/ppd.h> #define KEVENT_PROPAGATE 0 #define KEVENT_STOP 1 #define NR_PERSONALITIES 4 #if BITS_PER_LONG < NR_PERSONALITIES #error "NR_PERSONALITIES overflows internal bitmap" #endif struct mm_struct; struct xnthread_personality; struct cobalt_timer; struct cobalt_resources { struct list_head condq; struct list_head mutexq; struct list_head semq; struct list_head monitorq; struct list_head eventq; struct list_head schedq; }; struct cobalt_process { struct mm_struct *mm; struct hlist_node hlink; struct cobalt_ppd sys_ppd; unsigned long permap; struct rb_root usems; struct list_head sigwaiters; struct cobalt_resources resources; DECLARE_BITMAP(timers_map, CONFIG_XENO_OPT_NRTIMERS); struct cobalt_timer *timers[CONFIG_XENO_OPT_NRTIMERS]; void *priv[NR_PERSONALITIES]; }; struct cobalt_resnode { struct cobalt_resources *scope; struct cobalt_process *owner; struct list_head next; xnhandle_t handle; }; int cobalt_register_personality(struct xnthread_personality *personality); int cobalt_unregister_personality(int xid); struct xnthread_personality *cobalt_push_personality(int xid); void cobalt_pop_personality(struct xnthread_personality *prev); int cobalt_bind_core(void); int cobalt_bind_personality(unsigned int magic); struct cobalt_process *cobalt_search_process(struct mm_struct *mm); int cobalt_map_user(struct xnthread *thread, __u32 __user *u_winoff); void *cobalt_get_context(int xid); int cobalt_yield(xnticks_t min, xnticks_t max); int cobalt_process_init(void); extern struct list_head cobalt_thread_list; extern struct cobalt_resources cobalt_global_resources; static inline struct cobalt_process *cobalt_current_process(void) { return ipipe_current_threadinfo()->process; } static inline struct cobalt_process * cobalt_set_process(struct cobalt_process *process) { struct ipipe_threadinfo *p = ipipe_current_threadinfo(); struct cobalt_process *old; old = p->process; p->process = process; return old; } static inline struct cobalt_ppd *cobalt_ppd_get(int global) { struct cobalt_process *process; if (global || (process = cobalt_current_process()) == NULL) return &cobalt_kernel_ppd; return &process->sys_ppd; } static inline struct cobalt_resources *cobalt_current_resources(int pshared) { struct cobalt_process *process; if (pshared || (process = cobalt_current_process()) == NULL) return &cobalt_global_resources; return &process->resources; } static inline void __cobalt_add_resource(struct cobalt_resnode *node, int pshared) { node->owner = cobalt_current_process(); node->scope = cobalt_current_resources(pshared); } #define cobalt_add_resource(__node, __type, __pshared) \ do { \ __cobalt_add_resource(__node, __pshared); \ list_add_tail(&(__node)->next, \ &((__node)->scope)->__type ## q); \ } while (0) static inline void cobalt_del_resource(struct cobalt_resnode *node) { list_del(&node->next); } extern struct xnthread_personality *cobalt_personalities[]; extern struct xnthread_personality cobalt_personality; #endif /* !_COBALT_POSIX_PROCESS_H */
26.051948
77
0.77991
6ed9d91407082cf47118ff092d11862c9d2c4d94
787
h
C
solver/sparse.h
naruto2/ConjugateGradient
965791f23b990a70a5cd8e5978596e6d8fa185c7
[ "MIT" ]
null
null
null
solver/sparse.h
naruto2/ConjugateGradient
965791f23b990a70a5cd8e5978596e6d8fa185c7
[ "MIT" ]
null
null
null
solver/sparse.h
naruto2/ConjugateGradient
965791f23b990a70a5cd8e5978596e6d8fa185c7
[ "MIT" ]
null
null
null
#ifndef SPARSE_H #define SPARSE_H #include <map> #include <vector> namespace sparse { using namespace std; template<typename Real> class customap { map<long, Real> mp; public: auto& operator []( const long i ) { for ( auto it : mp ) if (it.second == 0.0) mp.erase(it.first); return mp[i]; } auto begin() { return mp.begin();} auto end() { return mp.end();} }; template<typename Real> class matrix : public vector< customap<Real> > { public: matrix() : vector< customap<Real> >(){} matrix(long n) : vector< customap<Real> >(n){} }; template<typename Real> class device_matrix : public matrix<Real> { public: device_matrix() : matrix<Real>(){} device_matrix(long n) : matrix<Real>(n){} }; } #endif
21.861111
74
0.603558
6ee16c3ddca38414507c3fa2ab22cdc237746c1b
683
h
C
Lighthouse/LHDriverFeedbackUpdateTask.h
pixty/Lighthouse
144a1c934952028c6a644538edef05cf12260e67
[ "MIT" ]
4
2016-02-04T12:46:15.000Z
2016-02-05T02:55:24.000Z
Lighthouse/LHDriverFeedbackUpdateTask.h
pixty/Router
144a1c934952028c6a644538edef05cf12260e67
[ "MIT" ]
null
null
null
Lighthouse/LHDriverFeedbackUpdateTask.h
pixty/Router
144a1c934952028c6a644538edef05cf12260e67
[ "MIT" ]
null
null
null
// // LHDriverFeedbackUpdateTask.h // Lighthouse // // Created by Nick Tymchenko on 29/09/15. // Copyright © 2015 Pixty. All rights reserved. // #import "LHNodeUpdateTask.h" NS_ASSUME_NONNULL_BEGIN @interface LHDriverFeedbackUpdateTask : LHNodeUpdateTask - (instancetype)initWithComponents:(LHComponents *)components animated:(BOOL)animated sourceNode:(id<LHNode>)node nodeUpdateBlock:(void (^)(void))block NS_DESIGNATED_INITIALIZER; - (instancetype)initWithComponents:(LHComponents *)components animated:(BOOL)animated NS_UNAVAILABLE; - (void)sourceDriverUpdateDidFinish; @end NS_ASSUME_NONNULL_END
23.551724
101
0.713031
7b5f30f56c8f0914b5d0ce0f0c68f61f3717de8e
16,225
c
C
src/core/morphos/SDL_library.c
BeWorld2018/SDL
326f1e30c5a470575eb586c0b1d7a5ffecac90fd
[ "Zlib" ]
1
2022-03-10T19:36:53.000Z
2022-03-10T19:36:53.000Z
src/core/morphos/SDL_library.c
BeWorld2018/SDL
326f1e30c5a470575eb586c0b1d7a5ffecac90fd
[ "Zlib" ]
1
2021-05-26T16:21:58.000Z
2021-05-27T18:40:32.000Z
src/core/morphos/SDL_library.c
BeWorld2018/SDL
326f1e30c5a470575eb586c0b1d7a5ffecac90fd
[ "Zlib" ]
1
2021-05-16T12:03:29.000Z
2021-05-16T12:03:29.000Z
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stddef.h> #include <stdlib.h> #include <libraries/gadtools.h> #include <proto/intuition.h> #include <devices/timer.h> #include <exec/execbase.h> #include <exec/resident.h> #include <exec/system.h> #include <proto/exec.h> #include <proto/gadtools.h> #include "SDL_amigaversion.h" #include "SDL_library.h" #include "SDL_startup.h" STATIC CONST TEXT __TEXTSEGMENT__ verstring[] = VERSTAG; STATIC CONST TEXT libname[] = "sdl2.library"; struct SDL_Library *GlobalBase = NULL; struct ExecBase *SysBase = NULL; struct DosLibrary *DOSBase = NULL; struct IntuitionBase *IntuitionBase = NULL; struct GfxBase *GfxBase = NULL; struct Library *UtilityBase = NULL; struct Library *CyberGfxBase = NULL; struct Library *KeymapBase = NULL; struct Library *WorkbenchBase = NULL; struct Library *IconBase = NULL; struct Library *MUIMasterBase = NULL; struct Library *CxBase = NULL; struct Library *ScreenNotifyBase = NULL; struct Library *TimerBase = NULL; struct Library *LocaleBase = NULL; struct Library *SensorsBase = NULL; struct Library *IFFParseBase = NULL; struct Library *CharsetsBase = NULL; struct Library *IConvBase = NULL; struct Library *ThreadPoolBase = NULL; struct Library *DynLoadBase = NULL; struct Library *OpenURLBase = NULL; struct Library *GadToolsBase = NULL; //SDL_JOYSTICK_AMIGA // struct Library *LowLevelBase = NULL; struct NewMenu SDL_NewMenu[] = { { NM_TITLE, (char *)"Project", 0, 0, 0, (APTR)MID_PROJECT }, { NM_ITEM , (char *)"About...", (const STRPTR)"A", 0, 0, (APTR)MID_ABOUT }, { NM_ITEM, NM_BARLABEL, NULL, 0, 0, NULL }, { NM_ITEM , (char *)"Hide", (const STRPTR)"H", 0, 0, (APTR)MID_HIDE }, { NM_ITEM, NM_BARLABEL, NULL, 0, 0, NULL }, { NM_ITEM , (char *)"Quit", (const STRPTR)"Q", 0, 0, (APTR)MID_QUIT}, { NM_TITLE, (char *)"Misc", 0, 0, 0, (APTR)MID_MISC }, { NM_ITEM , (char *)"Mute Sound", (const STRPTR)"M", (CHECKIT | MENUTOGGLE), 0, (APTR)MID_MUTE}, { NM_ITEM , (char *)"Low CPU Priority", (const STRPTR)"P", (CHECKIT | MENUTOGGLE), 0, (APTR)MID_PRIORITY}, { NM_ITEM, NM_BARLABEL, NULL, 0, 0, NULL }, { NM_ITEM , (char *)"About Joystick", (const STRPTR)"J", 0, 0, (APTR)MID_JOYSTICK}, { NM_ITEM , (char *)"About System", (const STRPTR)"S", 0, 0, (APTR)MID_ABOUTSYS}, { NM_END , NULL, NULL, 0, 0, NULL } }; struct timerequest GlobalTimeReq; u_int32_t DataL1LineSize = 0; BYTE HasAltiVec = 0; /********************************************************************** LIB_Reserved **********************************************************************/ STATIC ULONG LIB_Reserved(void) { return 0; } /********************************************************************** comp_ctdt Sort constructors/destructors **********************************************************************/ STATIC int comp_ctdt(struct CTDT *a, struct CTDT *b) { if (a->priority == b->priority) return (0); if ((unsigned long)a->priority < (unsigned long) b->priority) return (-1); return (1); } STATIC VOID sort_ctdt(struct SDL_Library *LibBase) { extern struct CTDT __ctdtlist; struct CTDT *ctdtlist = &__ctdtlist; struct HunkSegment *seg = (struct HunkSegment *)(((unsigned int)ctdtlist) - sizeof(struct HunkSegment)); struct CTDT *_last_ctdt = (struct CTDT *)(((unsigned int)seg) + seg->Size); qsort((struct CTDT *)ctdtlist, _last_ctdt - ctdtlist, sizeof(*ctdtlist), (int (*)(const void *, const void *))comp_ctdt); LibBase->ctdtlist = ctdtlist; LibBase->last_ctdt = _last_ctdt; } /********************************************************************** init_system **********************************************************************/ STATIC void init_system(struct SDL_Library *LibBase, struct ExecBase *SysBase) { u_int32_t value; NewGetSystemAttrsA(&value, sizeof(value), SYSTEMINFOTYPE_PPC_DCACHEL1LINESIZE, NULL); if (value < 32) value = 32; DataL1LineSize = value; ULONG Altivec = 0; if (NewGetSystemAttrsA(&Altivec,sizeof(Altivec),SYSTEMINFOTYPE_PPC_ALTIVEC,NULL)) { if (Altivec) { HasAltiVec = 1; } } } /********************************************************************** init_libs **********************************************************************/ static int init_libs(struct SDL_Library *base, struct ExecBase *SysBase) { if ((GfxBase = base->MyGfxBase = (APTR)OpenLibrary("graphics.library", 39)) != NULL) if ((DOSBase = base->MyDOSBase = (APTR)OpenLibrary("dos.library", 36)) != NULL) if ((IntuitionBase = base->MyIntuiBase = (APTR)OpenLibrary("intuition.library", 39)) != NULL) if ((UtilityBase = OpenLibrary("utility.library", 36)) != NULL) if (OpenDevice("timer.device", UNIT_MICROHZ, &GlobalTimeReq.tr_node, 0) == 0) { TimerBase = (struct Library *)GlobalTimeReq.tr_node.io_Device; sort_ctdt(base); init_system(base, SysBase); return 1; } return 0; } /********************************************************************** data relocs **********************************************************************/ #define R13_OFFSET 0x8000 extern int __datadata_relocs(void); STATIC __inline int __dbsize(void) { extern APTR __sdata_size, __sbss_size; STATIC CONST ULONG size[] = { (ULONG)&__sdata_size, (ULONG)&__sbss_size }; return size[0] + size[1]; } /********************************************************************** LIB_Init **********************************************************************/ struct Library *LIB_Init(struct SDL_Library *LibBase, BPTR SegList, struct ExecBase *sysBase) { register char *r13; GlobalBase = LibBase; SysBase = sysBase; LibBase->Library.lib_Node.ln_Pri = -5; #ifndef __MORPHOS__ LibBase->Library.lib_Revision = COMPILE_REVISION; #endif asm volatile ("lis %0,__r13_init@ha; addi %0,%0,__r13_init@l" : "=r" (r13)); LibBase->SegList = SegList; LibBase->DataSeg = r13 - R13_OFFSET; LibBase->DataSize = __dbsize(); LibBase->Parent = NULL; LibBase->MySysBase = sysBase; NEWLIST(&LibBase->TaskContext.TaskList); InitSemaphore(&LibBase->Semaphore); if (init_libs(LibBase, sysBase) == 0) { FreeMem((APTR)((ULONG)(LibBase) - (ULONG)(LibBase->Library.lib_NegSize)), LibBase->Library.lib_NegSize + LibBase->Library.lib_PosSize); LibBase = NULL; } return (struct Library *)LibBase; } /********************************************************************** DeleteLib **********************************************************************/ static BPTR DeleteLib(struct SDL_Library *LibBase, struct ExecBase *SysBase) { BPTR SegList = 0; if (LibBase->Library.lib_OpenCnt == 0) { CloseLibrary((struct Library *)LibBase->MyGfxBase); CloseLibrary((struct Library *)LibBase->MyDOSBase); CloseLibrary((struct Library *)LibBase->MyIntuiBase); CloseLibrary(UtilityBase); CloseDevice(&GlobalTimeReq.tr_node); SegList = LibBase->SegList; REMOVE(&LibBase->Library.lib_Node); FreeMem((APTR)((ULONG)(LibBase) - (ULONG)(LibBase->Library.lib_NegSize)), LibBase->Library.lib_NegSize + LibBase->Library.lib_PosSize); } return SegList; } /********************************************************************** UserLibClose **********************************************************************/ static void UserLibClose(struct SDL_Library *LibBase, struct ExecBase *SysBase) { CloseLibrary(LibBase->MyCyberGfxBase); CloseLibrary(LibBase->MyKeymapBase); CloseLibrary(LibBase->MyWorkbenchBase); CloseLibrary(LibBase->MyIconBase); CloseLibrary(LibBase->MyMUIMasterBase); CloseLibrary(LibBase->MyCxBase); CloseLibrary(LibBase->MyScreenNotifyBase); CloseLibrary(LocaleBase); CloseLibrary(SensorsBase); CloseLibrary(IFFParseBase); CloseLibrary(CharsetsBase); CloseLibrary(IConvBase); CloseLibrary(ThreadPoolBase); CloseLibrary(DynLoadBase); CloseLibrary(OpenURLBase); CloseLibrary(GadToolsBase); CyberGfxBase = LibBase->MyCyberGfxBase = NULL; KeymapBase = LibBase->MyKeymapBase = NULL; WorkbenchBase = LibBase->MyWorkbenchBase = NULL; IconBase = LibBase->MyIconBase = NULL; MUIMasterBase = LibBase->MyMUIMasterBase = NULL; CxBase = LibBase->MyCxBase = NULL; ScreenNotifyBase = LibBase->MyScreenNotifyBase = NULL; LocaleBase = NULL; SensorsBase = NULL; IFFParseBase = NULL; CharsetsBase = NULL; IConvBase = NULL; ThreadPoolBase = NULL; DynLoadBase = NULL; OpenURLBase = NULL; GadToolsBase = NULL; } /********************************************************************** LIB_Expunge **********************************************************************/ BPTR LIB_Expunge(void) { struct SDL_Library *LibBase = (struct SDL_Library *)REG_A6; LibBase->Library.lib_Flags |= LIBF_DELEXP; return DeleteLib(LibBase, LibBase->MySysBase); } /********************************************************************** LIB_Close *********************************************************************/ BPTR LIB_Close(void) { struct SDL_Library *LibBase = (struct SDL_Library *)REG_A6; struct ExecBase *SysBase = LibBase->MySysBase; BPTR SegList = 0; if (LibBase->Parent) { struct SDL_Library *ChildBase = LibBase; if ((--ChildBase->Library.lib_OpenCnt) > 0) return 0; LibBase = ChildBase->Parent; REMOVE(&ChildBase->TaskContext.TaskNode.Node); AMIGA_Cleanup(ChildBase); FreeVecTaskPooled((APTR)((ULONG)(ChildBase) - (ULONG)(ChildBase->Library.lib_NegSize))); } ObtainSemaphore(&LibBase->Semaphore); LibBase->Library.lib_OpenCnt--; if (LibBase->Library.lib_OpenCnt == 0) { LibBase->Alloc = 0; UserLibClose(LibBase, SysBase); } ReleaseSemaphore(&LibBase->Semaphore); if (LibBase->Library.lib_Flags & LIBF_DELEXP) SegList = DeleteLib(LibBase, SysBase); return SegList; } /********************************************************************** LIB_Open **********************************************************************/ struct Library *LIB_Open(void) { struct SDL_Library *LibBase = (struct SDL_Library *)REG_A6; struct SDL_Library *newbase, *childbase; struct ExecBase *SysBase = LibBase->MySysBase; struct Task *MyTask = SysBase->ThisTask; struct TaskNode *ChildNode; ULONG MyBaseSize; /* Has this task already opened a child? */ ForeachNode(&LibBase->TaskContext.TaskList, ChildNode) { if (ChildNode->Task == MyTask) { /* Yep, return it */ childbase = (APTR)(((ULONG)ChildNode) - offsetof(struct SDL_Library, TaskContext.TaskNode.Node)); childbase->Library.lib_Flags &= ~LIBF_DELEXP; childbase->Library.lib_OpenCnt++; return(&childbase->Library); } } childbase = NULL; MyBaseSize = LibBase->Library.lib_NegSize + LibBase->Library.lib_PosSize; LibBase->Library.lib_Flags &= ~LIBF_DELEXP; LibBase->Library.lib_OpenCnt++; ObtainSemaphore(&LibBase->Semaphore); if (LibBase->Alloc == 0) { if (((IntuitionBase = LibBase->MyIntuiBase = (APTR)OpenLibrary("intuition.library" , 39)) != NULL) && ((CyberGfxBase = LibBase->MyCyberGfxBase = (APTR)OpenLibrary("cybergraphics.library", 40)) != NULL) && ((KeymapBase = LibBase->MyKeymapBase = (APTR)OpenLibrary("keymap.library" , 36)) != NULL) && ((WorkbenchBase = LibBase->MyWorkbenchBase = (APTR)OpenLibrary("workbench.library" , 0)) != NULL) && ((IconBase = LibBase->MyIconBase = (APTR)OpenLibrary("icon.library" , 0)) != NULL) && ((MUIMasterBase = LibBase->MyMUIMasterBase = (APTR)OpenLibrary("muimaster.library" , 19)) != NULL) && ((CxBase = LibBase->MyCxBase = (APTR)OpenLibrary("commodities.library" , 37)) != NULL) && ((ScreenNotifyBase = LibBase->MyScreenNotifyBase = (APTR)OpenLibrary("screennotify.library" , 0)) != NULL) && ((LocaleBase = OpenLibrary("locale.library" , 0)) != NULL) && ((SensorsBase = OpenLibrary("sensors.library" , 53)) != NULL) && ((IFFParseBase = OpenLibrary("iffparse.library" , 0)) != NULL) && ((CharsetsBase = OpenLibrary("charsets.library" , 53)) != NULL) && ((IConvBase = OpenLibrary("iconv.library" , 0)) != NULL) && ((ThreadPoolBase = OpenLibrary("threadpool.library" , 53)) != NULL) && ((DynLoadBase = OpenLibrary("dynload.library" , 0)) != NULL) && ((GadToolsBase = OpenLibrary("gadtools.library" , 0)) != NULL) && ((OpenURLBase = OpenLibrary("openurl.library" , 0)) != NULL)) { LibBase->Alloc = 1; } else { goto error; } } if ((newbase = AllocVecTaskPooled(MyBaseSize + LibBase->DataSize + 15)) != NULL) { CopyMem((APTR)((ULONG)LibBase - (ULONG)LibBase->Library.lib_NegSize), newbase, MyBaseSize); childbase = (APTR)((ULONG)newbase + (ULONG)LibBase->Library.lib_NegSize); if (LibBase->DataSize) { char *orig = LibBase->DataSeg; LONG *relocs = (LONG *) __datadata_relocs; int mem = ((int)newbase + MyBaseSize + 15) & (unsigned int) ~15; CopyMem(orig, (char *)mem, LibBase->DataSize); if (relocs[0] > 0) { int i, num_relocs = relocs[0]; for (i = 0, relocs++; i < num_relocs; ++i, ++relocs) { *(long *)(mem + *relocs) -= (int)orig - mem; } } childbase->DataSeg = (char *)mem + R13_OFFSET; if (AMIGA_Startup(childbase) == 0) { AMIGA_Cleanup(childbase); FreeVecTaskPooled(newbase); childbase = 0; goto error; } } childbase->Parent = LibBase; childbase->Library.lib_OpenCnt = 1; /* Register which task opened this child */ childbase->TaskContext.TaskNode.Task = MyTask; ADDTAIL(&LibBase->TaskContext.TaskList, &childbase->TaskContext.TaskNode.Node); } else { error: LibBase->Library.lib_OpenCnt--; if (LibBase->Library.lib_OpenCnt == 0) { LibBase->Alloc = 0; UserLibClose(LibBase, SysBase); } } ReleaseSemaphore(&LibBase->Semaphore); return (struct Library *)childbase; } /********************************************************************** Library data **********************************************************************/ #include "SDL_stubs.h" extern void LIB_InitTGL(); extern void LIB_SetExitPointer(); extern void LIB_SDL_VSetError(); static const APTR FuncTable[] = { (APTR)FUNCARRAY_BEGIN, (APTR)FUNCARRAY_32BIT_NATIVE, (APTR)LIB_Open, (APTR)LIB_Close, (APTR)LIB_Expunge, (APTR)LIB_Reserved, (APTR)-1, (APTR)FUNCARRAY_32BIT_SYSTEMV, (APTR)LIB_InitTGL, (APTR)LIB_SetExitPointer, (APTR)LIB_SDL_VSetError, #define GENERATE_POINTERS #include "SDL_stubs.h" (APTR)-1, (APTR)FUNCARRAY_END }; static const size_t InitTable[] = { sizeof(struct SDL_Library), (size_t)FuncTable, 0, (size_t)LIB_Init }; const struct Resident __TEXTSEGMENT__ RomTag = { RTC_MATCHWORD, (struct Resident *)&RomTag, (struct Resident *)&RomTag+1, RTF_AUTOINIT | RTF_PPC | RTF_EXTENDED, VERSION, NT_LIBRARY, 0, (char *)libname, (char *)&verstring[7], (APTR)&InitTable[0], REVISION, NULL }; CONST ULONG __abox__ = 1; __asm("\n.section \".ctdt\",\"a\",@progbits\n__ctdtlist:\n.long -1,-1\n");
30.383895
137
0.604314
7b750c015e8abb6e298527a9556ef08651204a7c
6,579
c
C
src/C/libgcrypt/libgcrypt-1.6.1/cipher/ecc-misc.c
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/libgcrypt/libgcrypt-1.6.1/cipher/ecc-misc.c
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/libgcrypt/libgcrypt-1.6.1/cipher/ecc-misc.c
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* ecc-misc.c - Elliptic Curve miscellaneous functions * Copyright (C) 2007, 2008, 2010, 2011 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "g10lib.h" #include "mpi.h" #include "cipher.h" #include "context.h" #include "ec-context.h" #include "ecc-common.h" /* * Release a curve object. */ void _gcry_ecc_curve_free (elliptic_curve_t *E) { mpi_free (E->p); E->p = NULL; mpi_free (E->a); E->a = NULL; mpi_free (E->b); E->b = NULL; _gcry_mpi_point_free_parts (&E->G); mpi_free (E->n); E->n = NULL; } /* * Return a copy of a curve object. */ elliptic_curve_t _gcry_ecc_curve_copy (elliptic_curve_t E) { elliptic_curve_t R; R.model = E.model; R.dialect = E.dialect; R.name = E.name; R.p = mpi_copy (E.p); R.a = mpi_copy (E.a); R.b = mpi_copy (E.b); _gcry_mpi_point_init (&R.G); point_set (&R.G, &E.G); R.n = mpi_copy (E.n); return R; } /* * Return a description of the curve model. */ const char * _gcry_ecc_model2str (enum gcry_mpi_ec_models model) { const char *str = "?"; switch (model) { case MPI_EC_WEIERSTRASS: str = "Weierstrass"; break; case MPI_EC_MONTGOMERY: str = "Montgomery"; break; case MPI_EC_TWISTEDEDWARDS: str = "Twisted Edwards"; break; } return str; } /* * Return a description of the curve dialect. */ const char * _gcry_ecc_dialect2str (enum ecc_dialects dialect) { const char *str = "?"; switch (dialect) { case ECC_DIALECT_STANDARD: str = "Standard"; break; case ECC_DIALECT_ED25519: str = "Ed25519"; break; } return str; } gcry_mpi_t _gcry_ecc_ec2os (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t p) { gpg_err_code_t rc; int pbytes = (mpi_get_nbits (p)+7)/8; size_t n; unsigned char *buf, *ptr; gcry_mpi_t result; buf = xmalloc ( 1 + 2*pbytes ); *buf = 04; /* Uncompressed point. */ ptr = buf+1; rc = _gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, x); if (rc) log_fatal ("mpi_print failed: %s\n", gpg_strerror (rc)); if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } ptr += pbytes; rc = _gcry_mpi_print (GCRYMPI_FMT_USG, ptr, pbytes, &n, y); if (rc) log_fatal ("mpi_print failed: %s\n", gpg_strerror (rc)); if (n < pbytes) { memmove (ptr+(pbytes-n), ptr, n); memset (ptr, 0, (pbytes-n)); } rc = _gcry_mpi_scan (&result, GCRYMPI_FMT_USG, buf, 1+2*pbytes, NULL); if (rc) log_fatal ("mpi_scan failed: %s\n", gpg_strerror (rc)); xfree (buf); return result; } /* Convert POINT into affine coordinates using the context CTX and return a newly allocated MPI. If the conversion is not possible NULL is returned. This function won't print an error message. */ gcry_mpi_t _gcry_mpi_ec_ec2os (gcry_mpi_point_t point, mpi_ec_t ectx) { gcry_mpi_t g_x, g_y, result; g_x = mpi_new (0); g_y = mpi_new (0); if (_gcry_mpi_ec_get_affine (g_x, g_y, point, ectx)) result = NULL; else result = _gcry_ecc_ec2os (g_x, g_y, ectx->p); mpi_free (g_x); mpi_free (g_y); return result; } /* RESULT must have been initialized and is set on success to the point given by VALUE. */ gcry_err_code_t _gcry_ecc_os2ec (mpi_point_t result, gcry_mpi_t value) { gcry_err_code_t rc; size_t n; const unsigned char *buf; unsigned char *buf_memory; gcry_mpi_t x, y; if (mpi_is_opaque (value)) { unsigned int nbits; buf = mpi_get_opaque (value, &nbits); if (!buf) return GPG_ERR_INV_OBJ; n = (nbits + 7)/8; buf_memory = NULL; } else { n = (mpi_get_nbits (value)+7)/8; buf_memory = xmalloc (n); rc = _gcry_mpi_print (GCRYMPI_FMT_USG, buf_memory, n, &n, value); if (rc) { xfree (buf_memory); return rc; } buf = buf_memory; } if (n < 1) { xfree (buf_memory); return GPG_ERR_INV_OBJ; } if (*buf != 4) { xfree (buf_memory); return GPG_ERR_NOT_IMPLEMENTED; /* No support for point compression. */ } if ( ((n-1)%2) ) { xfree (buf_memory); return GPG_ERR_INV_OBJ; } n = (n-1)/2; rc = _gcry_mpi_scan (&x, GCRYMPI_FMT_USG, buf+1, n, NULL); if (rc) { xfree (buf_memory); return rc; } rc = _gcry_mpi_scan (&y, GCRYMPI_FMT_USG, buf+1+n, n, NULL); xfree (buf_memory); if (rc) { mpi_free (x); return rc; } mpi_set (result->x, x); mpi_set (result->y, y); mpi_set_ui (result->z, 1); mpi_free (x); mpi_free (y); return 0; } /* Compute the public key from the the context EC. Obviously a requirement is that the secret key is available in EC. On success Q is returned; on error NULL. If Q is NULL a newly allocated point is returned. If G or D are given they override the values taken from EC. */ mpi_point_t _gcry_ecc_compute_public (mpi_point_t Q, mpi_ec_t ec, mpi_point_t G, gcry_mpi_t d) { if (!G) G = ec->G; if (!d) d = ec->d; if (!d || !G || !ec->p || !ec->a) return NULL; if (ec->model == MPI_EC_TWISTEDEDWARDS && !ec->b) return NULL; if (ec->dialect == ECC_DIALECT_ED25519 && (ec->flags & PUBKEY_FLAG_EDDSA)) { gcry_mpi_t a; unsigned char *digest; if (_gcry_ecc_eddsa_compute_h_d (&digest, d, ec)) return NULL; a = mpi_snew (0); _gcry_mpi_set_buffer (a, digest, 32, 0); xfree (digest); /* And finally the public key. */ if (!Q) Q = mpi_point_new (0); if (Q) _gcry_mpi_ec_mul_point (Q, a, G, ec); mpi_free (a); } else { if (!Q) Q = mpi_point_new (0); if (Q) _gcry_mpi_ec_mul_point (Q, d, G, ec); } return Q; }
22.84375
79
0.623195
294d868a4615c209d46b4b806d8c91391666131c
1,388
h
C
tr3_embedded/tr.libs/rosserial_esp32/include/ESP32Hardware.h
SlateRobotics/tr3_essentials
c8608f04a83a5ca53f25ce0e5f6bce217e378c6f
[ "MIT" ]
2
2021-01-22T05:52:10.000Z
2021-02-09T18:11:20.000Z
tr3_embedded/tr.libs/rosserial_esp32/include/ESP32Hardware.h
SlateRobotics/tr3_essentials
c8608f04a83a5ca53f25ce0e5f6bce217e378c6f
[ "MIT" ]
1
2020-08-07T08:47:52.000Z
2020-08-07T08:47:52.000Z
tr3_embedded/tr.libs/rosserial_esp32/include/ESP32Hardware.h
SlateRobotics/tr3_essentials
c8608f04a83a5ca53f25ce0e5f6bce217e378c6f
[ "MIT" ]
3
2020-08-03T17:42:18.000Z
2021-04-06T14:23:35.000Z
#ifndef ROS_ESP32_HARDWARE_H_ #define ROS_ESP32_HARDWARE_H_ #include "Config.h" extern "C" { #include "sdkconfig.h" #include "stdio.h" #include "esp_err.h" #include "esp_timer.h" #include <driver/uart.h> #include "esp_ros_wifi.h" } #define UART_PORT UART_NUM_0 #define UART_TX_PIN GPIO_NUM_1 #define UART_RX_PIN GPIO_NUM_3 class ESP32Hardware { protected: uint8_t rx_buf[8192]; public: ESP32Hardware() { } // Initialization code for ESP32 void init() { Serial.print("Connecting to SSID: "); Serial.println(CONFIG_ROSSERVER_SSID); esp_ros_wifi_init(CONFIG_ROSSERVER_SSID, CONFIG_ROSSERVER_PASS); ros_tcp_connect(CONFIG_ROSSERVER_IP, CONFIG_ROSSERVER_PORT); } // read a byte from the serial port. -1 = failure int read() { int read_len = ros_tcp_read(rx_buf, 1); if (read_len == 1) { return rx_buf[0]; } else { return -1; } } // write data to the connection to ROS int write(uint8_t* data, int length) { return ros_tcp_send(data, length); } // returns milliseconds since start of program unsigned long time() { return esp_timer_get_time() / 1000; } }; #endif
25.236364
76
0.579251
ada77bcc00ac633491e0e0a387ec1722225a02df
784
h
C
move-semantics/move-lambda-as-param/test5.h
gusenov/examples-cpp
2cd0abe15bf534c917bcfbca70694daaa19c4612
[ "MIT" ]
12
2019-08-18T19:28:55.000Z
2022-03-29T12:55:20.000Z
move-semantics/move-lambda-as-param/test5.h
gusenov/examples-cpp
2cd0abe15bf534c917bcfbca70694daaa19c4612
[ "MIT" ]
null
null
null
move-semantics/move-lambda-as-param/test5.h
gusenov/examples-cpp
2cd0abe15bf534c917bcfbca70694daaa19c4612
[ "MIT" ]
null
null
null
#pragma once namespace test5 { class Bar { public: Bar() { std::cout << "Bar()" << std::endl; } ~Bar() {} Bar(Bar const&) { std::cout << "Bar(Bar const&)" << std::endl; } Bar(Bar&&) noexcept { std::cout << "Bar(Bar&&)" << std::endl; } void operator()() const { std::cout << "void operator()()" << std::endl; } }; // Если эту функцию закомментировать, то будет: // No matching function for call to 'Foo' void Foo(Bar const&) { std::cout << "void Foo(std::function<void()> const&)" << std::endl; } void Foo(Bar&&) { std::cout << "void Foo(std::function<void()>&&)" << std::endl; } void Run() { Bar b; // Bar() Foo(b); // void Foo(std::function<void()> const&) } }
14.518519
71
0.494898
9532cf8ee0d42554cb8cb2aa4a4cedf970246b7e
156
h
C
Source/ModelTexture.h
jetspiking/Blockworld
be452d31563f33924ba3e03ee6beb5b9e7058cc5
[ "MIT" ]
null
null
null
Source/ModelTexture.h
jetspiking/Blockworld
be452d31563f33924ba3e03ee6beb5b9e7058cc5
[ "MIT" ]
null
null
null
Source/ModelTexture.h
jetspiking/Blockworld
be452d31563f33924ba3e03ee6beb5b9e7058cc5
[ "MIT" ]
null
null
null
#pragma once #include <gl/glew.h> #include <string> class Texture { GLuint id; public: Texture(const std::string& fileName); void bind(); };
13
39
0.641026
4ebf79a4dab10b185bc2d5aa830260fee7d16e4a
3,171
h
C
Core/FileLoader.h
simul/Platform
5825b3ce8540c6996ba6ab59a55581e44c68e7ad
[ "MIT" ]
5
2020-07-20T15:47:46.000Z
2021-12-23T20:54:22.000Z
Core/FileLoader.h
simul/Platform
5825b3ce8540c6996ba6ab59a55581e44c68e7ad
[ "MIT" ]
1
2021-07-12T09:53:30.000Z
2021-07-12T09:53:30.000Z
Core/FileLoader.h
simul/Platform
5825b3ce8540c6996ba6ab59a55581e44c68e7ad
[ "MIT" ]
3
2020-10-01T14:02:28.000Z
2021-05-27T14:15:35.000Z
#ifndef SIMUL_BASE_FILEINTERFACE_H #define SIMUL_BASE_FILEINTERFACE_H #include <vector> #include <string> #include "Platform/Core/Export.h" namespace platform { namespace core { //! An interface to derive from so you can provide your own file load/save functions. //! Use SetFileLoader to define the object that Simul will use for file handling. //! The default is simul::base::DefaultFileLoader, which uses standard file handling. class PLATFORM_CORE_EXPORT FileLoader { public: //! Returns a pointer to the current file handler. static FileLoader *GetFileLoader(); //! Returns true if and only if the named file exists. If it has a relative path, it is relative to the current directory. virtual bool FileExists(const char *filename_utf8) const=0; //! Set the file handling object: call this before any file operations, if at all. static void SetFileLoader(FileLoader *f); //! Put the file's entire contents into memory, by allocating sufficiently many bytes, and setting the pointer. //! The memory should later be freed by a call to ReleaseFileContents. //! The filename should be unicode UTF8-encoded. virtual void AcquireFileContents(void*& pointer, unsigned int& bytes, const char* filename_utf8,bool open_as_text)=0; //! Get the file date as a julian day number. Return zero if the file doesn't exist. virtual double GetFileDate(const char* filename_utf8) const=0; //! Free the memory allocated by AcquireFileContents. virtual void ReleaseFileContents(void* pointer)=0; //! Save the chunk of memory to storage. virtual bool Save(void* pointer, unsigned int bytes, const char* filename_utf8,bool save_as_text)=0; virtual std::vector<std::string> ListDirectory(const std::string &path) const; void AcquireFileContents(void*& pointer, unsigned int& bytes, const char* filename_utf8, const std::vector<std::string>& paths, bool open_as_text); static std::string FindParentFolder(const char *folder_utf8); //! Find the named file relative to one of a given list of paths. Searches from the top of the stack. std::string FindFileInPathStack(const char *filename_utf8,const std::vector<std::string> &path_stack_utf8) const; //! Find the named file relative to one of a given list of paths, and return the index in the list, -1 if the file was found on the general search path, or -2 if it was not found. Searches from the top of the stack. // If more than one exists, the newest file is used. int FindIndexInPathStack(const char *filename_utf8,const std::vector<std::string> &path_stack_utf8) const; protected: //! Find the named file relative to one of a given list of paths. Searches from the top of the stack. std::string FindFileInPathStack(const char *filename_utf8,const char * const* path_stack_utf8) const; //! Find the named file relative to one of a given list of paths, and return the index in the list, -1 if the file was found on the general search path, or path_stack_utf8.size() if it was not found. Searches from the top of the stack. int FindIndexInPathStack(const char *filename_utf8,const char * const* path_stack_utf8) const; }; } } #endif
58.722222
238
0.753075
ab7305c9d6600101aba0f0bcf2e1f8a249f8ab8b
411
h
C
ITMLKit.framework/IKDataProperty.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
ITMLKit.framework/IKDataProperty.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
ITMLKit.framework/IKDataProperty.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
1
2021-10-08T07:40:53.000Z
2021-10-08T07:40:53.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/ITMLKit.framework/ITMLKit */ @interface IKDataProperty : IKDataAccessor { NSString * _property; } @property (nonatomic, readonly) NSString *property; - (void).cxx_destruct; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (unsigned long long)hash; - (id)initWithProperty:(id)arg1; - (bool)isEqual:(id)arg1; - (id)property; @end
21.631579
69
0.727494
61839fe188366a4289dd6bffdcd20eff84aaec0d
7,154
h
C
low_level_simulation/devel/include/costum_msgs/SegmentMetadataMsg.h
abiantorres/autonomous-vehicles-system-simulation
3f0112036b2b270f5055729c648a1310976df933
[ "Apache-2.0" ]
null
null
null
low_level_simulation/devel/include/costum_msgs/SegmentMetadataMsg.h
abiantorres/autonomous-vehicles-system-simulation
3f0112036b2b270f5055729c648a1310976df933
[ "Apache-2.0" ]
null
null
null
low_level_simulation/devel/include/costum_msgs/SegmentMetadataMsg.h
abiantorres/autonomous-vehicles-system-simulation
3f0112036b2b270f5055729c648a1310976df933
[ "Apache-2.0" ]
null
null
null
// Generated by gencpp from file costum_msgs/SegmentMetadataMsg.msg // DO NOT EDIT! #ifndef COSTUM_MSGS_MESSAGE_SEGMENTMETADATAMSG_H #define COSTUM_MSGS_MESSAGE_SEGMENTMETADATAMSG_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Point.h> namespace costum_msgs { template <class ContainerAllocator> struct SegmentMetadataMsg_ { typedef SegmentMetadataMsg_<ContainerAllocator> Type; SegmentMetadataMsg_() : segment_index(0) , initial_point() , end_point() , distance_between_obstacles(0.0) , segment_simulation_timeout(0) { } SegmentMetadataMsg_(const ContainerAllocator& _alloc) : segment_index(0) , initial_point(_alloc) , end_point(_alloc) , distance_between_obstacles(0.0) , segment_simulation_timeout(0) { (void)_alloc; } typedef int64_t _segment_index_type; _segment_index_type segment_index; typedef ::geometry_msgs::Point_<ContainerAllocator> _initial_point_type; _initial_point_type initial_point; typedef ::geometry_msgs::Point_<ContainerAllocator> _end_point_type; _end_point_type end_point; typedef double _distance_between_obstacles_type; _distance_between_obstacles_type distance_between_obstacles; typedef int64_t _segment_simulation_timeout_type; _segment_simulation_timeout_type segment_simulation_timeout; typedef boost::shared_ptr< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> const> ConstPtr; }; // struct SegmentMetadataMsg_ typedef ::costum_msgs::SegmentMetadataMsg_<std::allocator<void> > SegmentMetadataMsg; typedef boost::shared_ptr< ::costum_msgs::SegmentMetadataMsg > SegmentMetadataMsgPtr; typedef boost::shared_ptr< ::costum_msgs::SegmentMetadataMsg const> SegmentMetadataMsgConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> & v) { ros::message_operations::Printer< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace costum_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'costum_msgs': ['/home/abiantorres/Documentos/tfg/autonomous-vehicles-system-simulation/low_level_simulation/src/costum_msgs/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > { static const char* value() { return "b238c42fedf53903e2cf5776ff7562f0"; } static const char* value(const ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xb238c42fedf53903ULL; static const uint64_t static_value2 = 0xe2cf5776ff7562f0ULL; }; template<class ContainerAllocator> struct DataType< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > { static const char* value() { return "costum_msgs/SegmentMetadataMsg"; } static const char* value(const ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > { static const char* value() { return "int64 segment_index\n\ geometry_msgs/Point initial_point\n\ geometry_msgs/Point end_point\n\ float64 distance_between_obstacles\n\ int64 segment_simulation_timeout\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ "; } static const char* value(const ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.segment_index); stream.next(m.initial_point); stream.next(m.end_point); stream.next(m.distance_between_obstacles); stream.next(m.segment_simulation_timeout); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct SegmentMetadataMsg_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::costum_msgs::SegmentMetadataMsg_<ContainerAllocator>& v) { s << indent << "segment_index: "; Printer<int64_t>::stream(s, indent + " ", v.segment_index); s << indent << "initial_point: "; s << std::endl; Printer< ::geometry_msgs::Point_<ContainerAllocator> >::stream(s, indent + " ", v.initial_point); s << indent << "end_point: "; s << std::endl; Printer< ::geometry_msgs::Point_<ContainerAllocator> >::stream(s, indent + " ", v.end_point); s << indent << "distance_between_obstacles: "; Printer<double>::stream(s, indent + " ", v.distance_between_obstacles); s << indent << "segment_simulation_timeout: "; Printer<int64_t>::stream(s, indent + " ", v.segment_simulation_timeout); } }; } // namespace message_operations } // namespace ros #endif // COSTUM_MSGS_MESSAGE_SEGMENTMETADATAMSG_H
30.442553
441
0.744199
61549d60f26675c2095691828647b6b4db6da784
757
h
C
ApptentiveConnect/source/Custom Views/ApptentiveNetworkImageView.h
hibu/apptentive-ios
6b6741878758c3c8e58d90172b41cf5bb3835846
[ "BSD-3-Clause" ]
null
null
null
ApptentiveConnect/source/Custom Views/ApptentiveNetworkImageView.h
hibu/apptentive-ios
6b6741878758c3c8e58d90172b41cf5bb3835846
[ "BSD-3-Clause" ]
null
null
null
ApptentiveConnect/source/Custom Views/ApptentiveNetworkImageView.h
hibu/apptentive-ios
6b6741878758c3c8e58d90172b41cf5bb3835846
[ "BSD-3-Clause" ]
null
null
null
// // ApptentiveNetworkImageView.h // ApptentiveConnect // // Created by Andrew Wooster on 4/17/13. // Copyright (c) 2013 Apptentive, Inc. All rights reserved. // #import <UIKit/UIKit.h> @protocol ApptentiveNetworkImageViewDelegate; @interface ApptentiveNetworkImageView : UIImageView <NSURLConnectionDelegate, NSURLConnectionDataDelegate> @property (copy, nonatomic) NSURL *imageURL; @property (assign, nonatomic) BOOL useCache; @property (weak, nonatomic) id<ApptentiveNetworkImageViewDelegate> delegate; @end @protocol ApptentiveNetworkImageViewDelegate <NSObject> - (void)networkImageViewDidLoad:(ApptentiveNetworkImageView *)imageView; - (void)networkImageView:(ApptentiveNetworkImageView *)imageView didFailWithError:(NSError *)error; @end
29.115385
106
0.801849
b20c82720a70925ed484d5f66f440a6ba57e9c67
404
h
C
ClothProject/ClothProject/clock.h
crunchthebunch/ClothPhysics
fed83f4aac834605ca6565851a1febd558c03d5a
[ "MIT" ]
null
null
null
ClothProject/ClothProject/clock.h
crunchthebunch/ClothPhysics
fed83f4aac834605ca6565851a1febd558c03d5a
[ "MIT" ]
null
null
null
ClothProject/ClothProject/clock.h
crunchthebunch/ClothPhysics
fed83f4aac834605ca6565851a1febd558c03d5a
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <Windows.h> #include <ctime> #include <cstdlib> class Clock { public: Clock(); ~Clock(); bool Initialise(); void Process(); double GetDeltaTick(); int GetMsPassed() const; protected: double timeElapsed; double deltaTime; double lastTime; double currentTime; double secondsPerCount; int frameCount = 0; clock_t startTime; double msPassed; };
12.625
25
0.720297
95b99aea92f9bdf01c81099ae30999ff36ff4d48
1,630
h
C
src/ofp_ctrl2sw.h
w180112/ofagent
2ce9a43685049950dc43b2429bfb03c79b54db93
[ "BSD-3-Clause" ]
null
null
null
src/ofp_ctrl2sw.h
w180112/ofagent
2ce9a43685049950dc43b2429bfb03c79b54db93
[ "BSD-3-Clause" ]
null
null
null
src/ofp_ctrl2sw.h
w180112/ofagent
2ce9a43685049950dc43b2429bfb03c79b54db93
[ "BSD-3-Clause" ]
null
null
null
#ifndef _OFP_CTRL2SW_H_ #define _OFP_CTRL2SW_H_ #include "ofp_common.h" typedef struct ofp_multipart { struct ofp_header ofp_header; uint16_t type; uint16_t flags; uint8_t pad[4]; uint8_t body[0]; }ofp_multipart_t; OFP_ASSERT(sizeof(struct ofp_multipart) == 16); /* Send packet (controller -> datapath). */ typedef struct ofp_packet_out { struct ofp_header header; uint32_t buffer_id; /* ID assigned by datapath (OFP_NO_BUFFER if none). */ uint32_t in_port; /* Packet's input port or OFPP_CONTROLLER. */ uint16_t actions_len; /* Size of action array in bytes. */ uint8_t pad[6]; struct ofp_action_header actions[0]; /* Action list. */ /* uint8_t data[0]; */ /* Packet data. The length is inferred from the length field in the header. (Only meaningful if buffer_id == -1.) */ }ofp_packet_out_t; OFP_ASSERT(sizeof(struct ofp_packet_out) == 24); /* Switch features. */ typedef struct ofp_switch_features { struct ofp_header ofp_header; uint64_t datapath_id; /* Datapath unique ID. The lower 48-bits are for a MAC address, while the upper 16-bits are implementer-defined. */ uint32_t n_buffers; /* Max packets buffered at once. */ uint8_t n_tables; /* Number of tables supported by datapath. */ uint8_t auxiliary_id; /* Identify auxiliary connections */ uint8_t pad[2]; /* Align to 64-bits. */ /* Features. */ uint32_t capabilities; /* Bitmap of support "ofp_capabilities". */ uint32_t reserved; }ofp_switch_features_t; OFP_ASSERT(sizeof(struct ofp_switch_features) == 32); #endif
37.045455
81
0.687117
f9685ada02db129a000e7a4ed36fa3935a20bd6b
78
h
C
cps_pp/include/util/defines.h
RBC-UKQCD/CPS
329cd411d01dce8e3409335f55e478dac3c3bca4
[ "BSD-3-Clause" ]
7
2017-06-24T02:20:36.000Z
2021-12-02T20:41:00.000Z
cps_pp/include/util/defines.h
RBC-UKQCD/CPS
329cd411d01dce8e3409335f55e478dac3c3bca4
[ "BSD-3-Clause" ]
null
null
null
cps_pp/include/util/defines.h
RBC-UKQCD/CPS
329cd411d01dce8e3409335f55e478dac3c3bca4
[ "BSD-3-Clause" ]
3
2020-03-16T05:55:57.000Z
2021-12-02T20:41:09.000Z
#ifndef _DEFINES_H_ #define _DEFINES_H_ #define MAX_FUZZING_C_NUM 10 #endif
11.142857
28
0.820513
d71fd40c1c8f65e0e527761994841ab67a0a8e84
769
h
C
example-persistentNodes/src/staticTestModule.h
PlaymodesStudio/ofxOceanode
400df6d49c4b29bc6916e4a045145e935beff4e0
[ "MIT" ]
31
2018-04-20T13:47:38.000Z
2021-12-26T04:32:24.000Z
example-persistentNodes/src/staticTestModule.h
PlaymodesStudio/ofxOceanode
400df6d49c4b29bc6916e4a045145e935beff4e0
[ "MIT" ]
25
2018-02-19T17:15:32.000Z
2020-01-05T01:51:00.000Z
example-persistentNodes/src/staticTestModule.h
PlaymodesStudio/ofxOceanode
400df6d49c4b29bc6916e4a045145e935beff4e0
[ "MIT" ]
5
2018-09-25T18:37:23.000Z
2021-01-21T16:26:16.000Z
// // staticTestModule.h // example-persistentNodes // // Created by Eduard Frigola Bagué on 16/08/2018. // #ifndef staticTestModule_h #define staticTestModule_h #include "ofxOceanodeNodeModel.h" class staticTestModule : public ofxOceanodeNodeModel{ public: staticTestModule() : ofxOceanodeNodeModel("Static Test Module"){}; ~staticTestModule(){}; void setup() override{ parameters->add(intParam.set("Int", 5, 0, 24)); parameters->add(floatParam.set("Float", 0, 0, 1)); addParameterToGroupAndInfo(stringParam.set("String", "I'm a Static")).isSavePreset = false; } private: ofParameter<int> intParam; ofParameter<float> floatParam; ofParameter<string> stringParam; }; #endif /* staticTestModule_h */
24.03125
99
0.693108
ba2285e5184d6ea7ddc5393bdeabda309737e65c
994
h
C
huffman.h
shixiongfei/huffman
e9e34957815390cbaeb11087404318342b6feab2
[ "Apache-2.0" ]
1
2022-03-22T10:23:24.000Z
2022-03-22T10:23:24.000Z
huffman.h
shixiongfei/huffman
e9e34957815390cbaeb11087404318342b6feab2
[ "Apache-2.0" ]
null
null
null
huffman.h
shixiongfei/huffman
e9e34957815390cbaeb11087404318342b6feab2
[ "Apache-2.0" ]
null
null
null
/* * huffman.h * * copyright (c) 2019 Xiongfei Shi * * author: Xiongfei Shi <jenson.shixf(a)gmail.com> * license: Apache2.0 * * https://github.com/shixiongfei/huffman */ #ifndef ___HUFFMAN_H__ #define ___HUFFMAN_H__ #include <stddef.h> #ifdef __cplusplus extern "C" { #endif #define HUFFMAN_TABLESIZE 256 typedef struct huffman_s huffman_t; void huffman_setalloc(void * (*alloc)(size_t), void (*release)(void *)); void huffman_table(unsigned short *table, const unsigned char *data, int len); huffman_t *huffman_create(unsigned short *table); void huffman_destroy(huffman_t *huffm); int huffman_rebuild(huffman_t *huffm, unsigned short *table); int huffman_enclen(huffman_t *huffm, int bytelen); int huffman_declen(huffman_t *huffm, int bitlen); int huffman_encode(huffman_t *huffm, void *outbuf, const void *data, int bytelen); int huffman_decode(huffman_t *huffm, void *outbuf, const void *data, int bitlen); #ifdef __cplusplus }; #endif #endif /* ___HUFFMAN_H__ */
22.590909
82
0.744467
9c92b4c0f875fc51e10faa8d4acf8660575dcc9c
1,499
h
C
Content/C++/graph/coloring/ChromaticNumber.h
GoatGirl98/Resources
429c0ff357365dfff0b7df0c52346466d828ce93
[ "CC0-1.0" ]
36
2017-05-10T08:00:56.000Z
2022-03-18T15:21:57.000Z
Content/C++/graph/coloring/ChromaticNumber.h
GoatGirl98/Resources
429c0ff357365dfff0b7df0c52346466d828ce93
[ "CC0-1.0" ]
90
2017-04-15T03:51:15.000Z
2020-06-16T00:39:33.000Z
Content/C++/graph/coloring/ChromaticNumber.h
GoatGirl98/Resources
429c0ff357365dfff0b7df0c52346466d828ce93
[ "CC0-1.0" ]
17
2020-02-19T01:02:32.000Z
2021-12-21T06:28:34.000Z
#pragma once #include <bits/stdc++.h> using namespace std; // Computes the minimum number of colors required to color a simple graph such // that no two adjacent vertices share the same color // Vertices are 0-indexed // Function Arguments: // V: the number of vertices in the simple graph // edges: a vector of pairs in the form (v, w) representing // an undirected edge in the simple graph (no self loops or parallel edges) // between vertices v and w // Return Value: the chromatic number (minimum number of colors) // In practice, has a small constant // Time Complexity: O(V 2^V) // Memory Complexity: O(2^V) // Tested: // https://judge.yosupo.jp/problem/chromatic_number int chromaticNumber(int V, const vector<pair<int, int>> &edges) { int ans = V, PV = 1 << V; vector<int> mask(V, 0), ind(PV), aux(PV); for (auto &&e : edges) { mask[e.first] |= 1 << e.second; mask[e.second] |= 1 << e.first; } for (int d : {7, 9, 21, 33, 87, 93, 97}) { long long mod = 1e9 + d; fill(ind.begin(), ind.end(), 0); ind[0] = 1; fill(aux.begin(), aux.end(), 1); for (int i = 0; i < PV; i++) { int v = __builtin_ctz(i); ind[i] = ind[i ^ (1 << v)] + ind[(i ^ (1 << v)) & ~mask[v]]; } for (int k = 1; k < ans; k++) { long long chi = 0; for (int i = 0; i < PV; i++) { int j = i ^ (i >> 1); aux[j] = (long long) aux[j] * ind[j] % mod; chi += (i & 1) ? aux[j] : -aux[j]; } if (chi % mod != 0) ans = k; } } return ans; }
37.475
79
0.576384
b91274bbf3358fc21ca132a1a934aa9cff151361
2,785
h
C
usr/libexec/demod/MSDContentServerLocator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
usr/libexec/demod/MSDContentServerLocator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
usr/libexec/demod/MSDContentServerLocator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> #import "MSDContentServerLocatorDelegate-Protocol.h" #import "NSNetServiceBrowserDelegate-Protocol.h" #import "NSNetServiceDelegate-Protocol.h" @class MSDTargetDevice, NSMutableSet, NSNetServiceBrowser, NSString; @interface MSDContentServerLocator : NSObject <NSNetServiceBrowserDelegate, NSNetServiceDelegate, MSDContentServerLocatorDelegate> { MSDTargetDevice *_device; // 8 = 0x8 NSMutableSet *_delegates; // 16 = 0x10 NSMutableSet *_netServices; // 24 = 0x18 NSNetServiceBrowser *_browser; // 32 = 0x20 NSString *_bonjourName; // 40 = 0x28 unsigned long long _pingFailCount; // 48 = 0x30 } + (id)sharedInstance; // IMP=0x0000000100045850 - (void).cxx_destruct; // IMP=0x0000000100047ad4 @property unsigned long long pingFailCount; // @synthesize pingFailCount=_pingFailCount; @property(retain) NSString *bonjourName; // @synthesize bonjourName=_bonjourName; @property(retain) NSNetServiceBrowser *browser; // @synthesize browser=_browser; @property(retain) NSMutableSet *netServices; // @synthesize netServices=_netServices; @property(retain) NSMutableSet *delegates; // @synthesize delegates=_delegates; @property(retain) MSDTargetDevice *device; // @synthesize device=_device; - (void)netServiceDidResolveAddress:(id)arg1; // IMP=0x00000001000478f0 - (void)netServiceBrowser:(id)arg1 didRemoveService:(id)arg2 moreComing:(_Bool)arg3; // IMP=0x0000000100047750 - (void)netServiceBrowser:(id)arg1 didFindService:(id)arg2 moreComing:(_Bool)arg3; // IMP=0x0000000100047674 - (void)contentServerDidDisappear; // IMP=0x00000001000475a8 - (void)contentServerDidAppear:(id)arg1 port:(id)arg2; // IMP=0x00000001000473a0 - (void)updateHubHostNameFromNetService:(id)arg1; // IMP=0x0000000100046d94 - (void)triggerLogicSyncingWithDemoUnit; // IMP=0x00000001000469cc - (_Bool)tryAlternativeHubHostNameToRecoverConnection; // IMP=0x0000000100046814 - (void)startLogicSyncingIfTimeIsUp; // IMP=0x00000001000466e8 - (void)incrementPingFailCountAndScheduleLogicSyncIfNeeded; // IMP=0x0000000100046428 - (void)resetPingFailCountAndSaveHubLastOnlineTime; // IMP=0x0000000100046358 - (void)startLocatingContentServerIfNeeded; // IMP=0x0000000100045e94 - (void)unregisterContentServerLocatorDelegate:(id)arg1; // IMP=0x0000000100045c78 - (void)registerContentServerLocatorDelegate:(id)arg1; // IMP=0x00000001000459e8 - (id)init; // IMP=0x00000001000458bc // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
48.859649
130
0.792819
3bc0a61016064399193f2d689b010106811339ae
1,241
h
C
app/src/main/cpp/MissionFlag.h
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
app/src/main/cpp/MissionFlag.h
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
app/src/main/cpp/MissionFlag.h
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
/******************************************************************************/ /*! @file MissionFlag.h @brief ミッションフラグクラス定義ファイル *******************************************************************************/ #ifndef MISSIONFLAG_H #define MISSIONFLAG_H #include <memory> #include "Common.h" namespace Shooting2D { /******************************************************************************/ /*! @class IMissionFlag @brief ミッションフラグクラス *******************************************************************************/ class IMissionFlag { public: /******************************************************************************/ /*! デストラクタ *******************************************************************************/ virtual ~IMissionFlag() = default; /******************************************************************************/ /*! 有効フラグの取得 @return 有効フラグ *******************************************************************************/ virtual MyBool IsValid() const noexcept = 0; }; /*! ポインタ置き換え */ using MissionFlagPtr = std::shared_ptr<IMissionFlag>; } #endif //MISSIONFLAG_H
31.820513
88
0.268332
befb9f202585bde1a3ea1d9732a849b8962a9606
3,183
h
C
System/Library/PrivateFrameworks/CameraUI.framework/CAMFeedbackContoller.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
12
2019-06-02T02:42:41.000Z
2021-04-13T07:22:20.000Z
System/Library/PrivateFrameworks/CameraUI.framework/CAMFeedbackContoller.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/CameraUI.framework/CAMFeedbackContoller.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
3
2019-06-11T02:46:10.000Z
2019-12-21T14:58:16.000Z
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:49:17 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/CameraUI.framework/CameraUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @class UISelectionFeedbackGenerator, _UIButtonFeedbackGenerator, NSMutableSet; @interface CAMFeedbackContoller : NSObject { UISelectionFeedbackGenerator* __modeSelectionFeedbackGenerator; UISelectionFeedbackGenerator* __burstCountFeedbackGenerator; _UIButtonFeedbackGenerator* __shutterButtonLatchingOnFeedbackGenerator; _UIButtonFeedbackGenerator* __shutterButtonLatchingOffFeedbackGenerator; _UIButtonFeedbackGenerator* __shutterButtonMomentaryFeedbackGenerator; NSMutableSet* __activePairedFeedbackGenerators; } @property (nonatomic,readonly) UISelectionFeedbackGenerator * _modeSelectionFeedbackGenerator; //@synthesize _modeSelectionFeedbackGenerator=__modeSelectionFeedbackGenerator - In the implementation block @property (nonatomic,readonly) UISelectionFeedbackGenerator * _burstCountFeedbackGenerator; //@synthesize _burstCountFeedbackGenerator=__burstCountFeedbackGenerator - In the implementation block @property (nonatomic,readonly) _UIButtonFeedbackGenerator * _shutterButtonLatchingOnFeedbackGenerator; //@synthesize _shutterButtonLatchingOnFeedbackGenerator=__shutterButtonLatchingOnFeedbackGenerator - In the implementation block @property (nonatomic,readonly) _UIButtonFeedbackGenerator * _shutterButtonLatchingOffFeedbackGenerator; //@synthesize _shutterButtonLatchingOffFeedbackGenerator=__shutterButtonLatchingOffFeedbackGenerator - In the implementation block @property (nonatomic,readonly) _UIButtonFeedbackGenerator * _shutterButtonMomentaryFeedbackGenerator; //@synthesize _shutterButtonMomentaryFeedbackGenerator=__shutterButtonMomentaryFeedbackGenerator - In the implementation block @property (nonatomic,readonly) NSMutableSet * _activePairedFeedbackGenerators; //@synthesize _activePairedFeedbackGenerators=__activePairedFeedbackGenerators - In the implementation block -(id)_feedbackGeneratorForDiscreteFeedback:(unsigned long long)arg1 ; -(id)_feedbackGeneratorForPairedFeedback:(unsigned long long)arg1 ; -(NSMutableSet *)_activePairedFeedbackGenerators; -(id)_debugStringForPairedFeedback:(unsigned long long)arg1 ; -(UISelectionFeedbackGenerator *)_modeSelectionFeedbackGenerator; -(UISelectionFeedbackGenerator *)_burstCountFeedbackGenerator; -(_UIButtonFeedbackGenerator *)_shutterButtonMomentaryFeedbackGenerator; -(_UIButtonFeedbackGenerator *)_shutterButtonLatchingOnFeedbackGenerator; -(_UIButtonFeedbackGenerator *)_shutterButtonLatchingOffFeedbackGenerator; -(void)prepareDiscreteFeedback:(unsigned long long)arg1 ; -(void)performDiscreteFeedback:(unsigned long long)arg1 ; -(void)prepareButtonFeedback:(unsigned long long)arg1 ; -(void)performPressButtonFeedback:(unsigned long long)arg1 ; -(void)performReleaseButtonFeedback:(unsigned long long)arg1 ; -(id)init; @end
69.195652
247
0.832234
475eca553b5d4f5646a711a5bbb8fd6bfb23eb2f
624
h
C
include/gf2d_scene.h
lahoising78/gf2d
54dc92817e8a45a02698aa0bad41c6b78ee0d2d3
[ "MIT" ]
null
null
null
include/gf2d_scene.h
lahoising78/gf2d
54dc92817e8a45a02698aa0bad41c6b78ee0d2d3
[ "MIT" ]
null
null
null
include/gf2d_scene.h
lahoising78/gf2d
54dc92817e8a45a02698aa0bad41c6b78ee0d2d3
[ "MIT" ]
null
null
null
#ifndef _GF2D_SCENE_H_ #define _GF2D_SCENE_H_ #include "gfc_list.h" #include "gf2d_physics_entity.h" typedef struct { char name[GFCLINELEN]; PhysicsEntity **physics_entities; uint32_t physics_entities_count; Entity **entities; uint32_t entities_count; List *render_list; } Scene; void gf2d_scene_load( uint32_t physics_entities_count, uint32_t entities, void (*scene_awake)() ); void gf2d_scene_close(); void gf2d_scene_render(); int gf2d_scene_add_entity( Entity *ent ); void gf2d_scene_remove_entity( Entity *e ); #endif
24
98
0.677885
cc33c8cae0437cc0a6e9e38f4a8dd9e4e7bdc6e8
1,075
h
C
plugin_sa/game_sa/CNodeAddress.h
gta-chaos-mod/plugin-sdk
e3bf176337774a2afc797a47825f81adde78e899
[ "Zlib" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
plugin_sa/game_sa/CNodeAddress.h
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
89
2016-05-08T06:42:36.000Z
2022-03-29T06:49:09.000Z
plugin_sa/game_sa/CNodeAddress.h
SteepCheat/plugin-sdk
a17c5d933cb8b06e4959b370092828a6a7aa00ef
[ "Zlib" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" class PLUGIN_API CNodeAddress { public: short m_nAreaId; short m_nNodeId; inline CNodeAddress() { Clear(); } inline CNodeAddress(short areaId, short nodeId) { Set(areaId, nodeId); } inline void Set(short areaId, short nodeId) { m_nAreaId = areaId; m_nNodeId = nodeId; } inline bool IsEmpty() const { return m_nAreaId == -1 || m_nNodeId == -1; } inline void Clear() { m_nAreaId = -1; m_nNodeId = -1; } inline bool operator==(CNodeAddress const &rhs) const { return m_nAreaId == rhs.m_nAreaId && m_nNodeId == rhs.m_nNodeId; } inline bool operator!=(CNodeAddress const &rhs) const { return m_nAreaId != rhs.m_nAreaId || m_nNodeId != rhs.m_nNodeId; } }; VALIDATE_SIZE(CNodeAddress, 0x4);
22.395833
72
0.625116
cc68bf39169e6fc8223cf15f2d729ee956f45280
214
h
C
cx/utils.h
Number5ix/cx
f77bcbf0a30a9873b449ddcfc2ae523d29084317
[ "BSD-3-Clause" ]
null
null
null
cx/utils.h
Number5ix/cx
f77bcbf0a30a9873b449ddcfc2ae523d29084317
[ "BSD-3-Clause" ]
null
null
null
cx/utils.h
Number5ix/cx
f77bcbf0a30a9873b449ddcfc2ae523d29084317
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cx/cx.h> #include <cx/utils/cbhandle.h> #include <cx/utils/compare.h> #include <cx/utils/lazyinit.h> #include <cx/utils/macros.h> #include <cx/utils/murmur.h> #include <cx/utils/scratch.h>
19.454545
30
0.719626
6225c6ce3c9add552a83e4f0e35c82e4ab2a3c10
31,794
h
C
source/code/providers/SCX_MemoryStatisticalInformation.h
pigera/scxcore
7cb5b2c81521d0f984b4a1c8c1f80cea5c9ca9b9
[ "MS-PL" ]
18
2016-04-25T18:24:40.000Z
2019-04-12T01:39:46.000Z
source/code/providers/SCX_MemoryStatisticalInformation.h
pigera/scxcore
7cb5b2c81521d0f984b4a1c8c1f80cea5c9ca9b9
[ "MS-PL" ]
58
2016-03-11T20:46:18.000Z
2019-04-01T09:19:41.000Z
source/code/providers/SCX_MemoryStatisticalInformation.h
pigera/scxcore
7cb5b2c81521d0f984b4a1c8c1f80cea5c9ca9b9
[ "MS-PL" ]
18
2019-05-07T06:41:41.000Z
2021-11-10T10:05:47.000Z
/* @migen@ */ /* **============================================================================== ** ** WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. PLEASE DO NOT EDIT. ** **============================================================================== */ #ifndef _SCX_MemoryStatisticalInformation_h #define _SCX_MemoryStatisticalInformation_h #include <MI.h> #include "SCX_StatisticalInformation.h" /* **============================================================================== ** ** SCX_MemoryStatisticalInformation [SCX_MemoryStatisticalInformation] ** ** Keys: ** Name ** **============================================================================== */ typedef struct _SCX_MemoryStatisticalInformation /* extends SCX_StatisticalInformation */ { MI_Instance __instance; /* CIM_ManagedElement properties */ MI_ConstStringField InstanceID; MI_ConstStringField Caption; MI_ConstStringField Description; MI_ConstStringField ElementName; /* CIM_StatisticalInformation properties */ /*KEY*/ MI_ConstStringField Name; /* SCX_StatisticalInformation properties */ MI_ConstBooleanField IsAggregate; /* SCX_MemoryStatisticalInformation properties */ MI_ConstUint64Field AvailableMemory; MI_ConstUint8Field PercentAvailableMemory; MI_ConstUint64Field UsedMemory; MI_ConstUint8Field PercentUsedMemory; MI_ConstUint8Field PercentUsedByCache; MI_ConstUint64Field PagesPerSec; MI_ConstUint64Field PagesReadPerSec; MI_ConstUint64Field PagesWrittenPerSec; MI_ConstUint64Field AvailableSwap; MI_ConstUint8Field PercentAvailableSwap; MI_ConstUint64Field UsedSwap; MI_ConstUint8Field PercentUsedSwap; } SCX_MemoryStatisticalInformation; typedef struct _SCX_MemoryStatisticalInformation_Ref { SCX_MemoryStatisticalInformation* value; MI_Boolean exists; MI_Uint8 flags; } SCX_MemoryStatisticalInformation_Ref; typedef struct _SCX_MemoryStatisticalInformation_ConstRef { MI_CONST SCX_MemoryStatisticalInformation* value; MI_Boolean exists; MI_Uint8 flags; } SCX_MemoryStatisticalInformation_ConstRef; typedef struct _SCX_MemoryStatisticalInformation_Array { struct _SCX_MemoryStatisticalInformation** data; MI_Uint32 size; } SCX_MemoryStatisticalInformation_Array; typedef struct _SCX_MemoryStatisticalInformation_ConstArray { struct _SCX_MemoryStatisticalInformation MI_CONST* MI_CONST* data; MI_Uint32 size; } SCX_MemoryStatisticalInformation_ConstArray; typedef struct _SCX_MemoryStatisticalInformation_ArrayRef { SCX_MemoryStatisticalInformation_Array value; MI_Boolean exists; MI_Uint8 flags; } SCX_MemoryStatisticalInformation_ArrayRef; typedef struct _SCX_MemoryStatisticalInformation_ConstArrayRef { SCX_MemoryStatisticalInformation_ConstArray value; MI_Boolean exists; MI_Uint8 flags; } SCX_MemoryStatisticalInformation_ConstArrayRef; MI_EXTERN_C MI_CONST MI_ClassDecl SCX_MemoryStatisticalInformation_rtti; MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Construct( SCX_MemoryStatisticalInformation* self, MI_Context* context) { return MI_ConstructInstance(context, &SCX_MemoryStatisticalInformation_rtti, (MI_Instance*)&self->__instance); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clone( const SCX_MemoryStatisticalInformation* self, SCX_MemoryStatisticalInformation** newInstance) { return MI_Instance_Clone( &self->__instance, (MI_Instance**)newInstance); } MI_INLINE MI_Boolean MI_CALL SCX_MemoryStatisticalInformation_IsA( const MI_Instance* self) { MI_Boolean res = MI_FALSE; return MI_Instance_IsA(self, &SCX_MemoryStatisticalInformation_rtti, &res) == MI_RESULT_OK && res; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Destruct(SCX_MemoryStatisticalInformation* self) { return MI_Instance_Destruct(&self->__instance); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Delete(SCX_MemoryStatisticalInformation* self) { return MI_Instance_Delete(&self->__instance); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Post( const SCX_MemoryStatisticalInformation* self, MI_Context* context) { return MI_PostInstance(context, &self->__instance); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_InstanceID( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 0, (MI_Value*)&str, MI_STRING, 0); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_SetPtr_InstanceID( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 0, (MI_Value*)&str, MI_STRING, MI_FLAG_BORROW); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_InstanceID( SCX_MemoryStatisticalInformation* self) { return self->__instance.ft->ClearElementAt( (MI_Instance*)&self->__instance, 0); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_Caption( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 1, (MI_Value*)&str, MI_STRING, 0); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_SetPtr_Caption( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 1, (MI_Value*)&str, MI_STRING, MI_FLAG_BORROW); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_Caption( SCX_MemoryStatisticalInformation* self) { return self->__instance.ft->ClearElementAt( (MI_Instance*)&self->__instance, 1); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_Description( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 2, (MI_Value*)&str, MI_STRING, 0); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_SetPtr_Description( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 2, (MI_Value*)&str, MI_STRING, MI_FLAG_BORROW); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_Description( SCX_MemoryStatisticalInformation* self) { return self->__instance.ft->ClearElementAt( (MI_Instance*)&self->__instance, 2); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_ElementName( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 3, (MI_Value*)&str, MI_STRING, 0); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_SetPtr_ElementName( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 3, (MI_Value*)&str, MI_STRING, MI_FLAG_BORROW); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_ElementName( SCX_MemoryStatisticalInformation* self) { return self->__instance.ft->ClearElementAt( (MI_Instance*)&self->__instance, 3); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_Name( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 4, (MI_Value*)&str, MI_STRING, 0); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_SetPtr_Name( SCX_MemoryStatisticalInformation* self, const MI_Char* str) { return self->__instance.ft->SetElementAt( (MI_Instance*)&self->__instance, 4, (MI_Value*)&str, MI_STRING, MI_FLAG_BORROW); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_Name( SCX_MemoryStatisticalInformation* self) { return self->__instance.ft->ClearElementAt( (MI_Instance*)&self->__instance, 4); } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_IsAggregate( SCX_MemoryStatisticalInformation* self, MI_Boolean x) { ((MI_BooleanField*)&self->IsAggregate)->value = x; ((MI_BooleanField*)&self->IsAggregate)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_IsAggregate( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->IsAggregate, 0, sizeof(self->IsAggregate)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_AvailableMemory( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->AvailableMemory)->value = x; ((MI_Uint64Field*)&self->AvailableMemory)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_AvailableMemory( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->AvailableMemory, 0, sizeof(self->AvailableMemory)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PercentAvailableMemory( SCX_MemoryStatisticalInformation* self, MI_Uint8 x) { ((MI_Uint8Field*)&self->PercentAvailableMemory)->value = x; ((MI_Uint8Field*)&self->PercentAvailableMemory)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PercentAvailableMemory( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PercentAvailableMemory, 0, sizeof(self->PercentAvailableMemory)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_UsedMemory( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->UsedMemory)->value = x; ((MI_Uint64Field*)&self->UsedMemory)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_UsedMemory( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->UsedMemory, 0, sizeof(self->UsedMemory)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PercentUsedMemory( SCX_MemoryStatisticalInformation* self, MI_Uint8 x) { ((MI_Uint8Field*)&self->PercentUsedMemory)->value = x; ((MI_Uint8Field*)&self->PercentUsedMemory)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PercentUsedMemory( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PercentUsedMemory, 0, sizeof(self->PercentUsedMemory)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PercentUsedByCache( SCX_MemoryStatisticalInformation* self, MI_Uint8 x) { ((MI_Uint8Field*)&self->PercentUsedByCache)->value = x; ((MI_Uint8Field*)&self->PercentUsedByCache)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PercentUsedByCache( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PercentUsedByCache, 0, sizeof(self->PercentUsedByCache)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PagesPerSec( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->PagesPerSec)->value = x; ((MI_Uint64Field*)&self->PagesPerSec)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PagesPerSec( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PagesPerSec, 0, sizeof(self->PagesPerSec)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PagesReadPerSec( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->PagesReadPerSec)->value = x; ((MI_Uint64Field*)&self->PagesReadPerSec)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PagesReadPerSec( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PagesReadPerSec, 0, sizeof(self->PagesReadPerSec)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PagesWrittenPerSec( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->PagesWrittenPerSec)->value = x; ((MI_Uint64Field*)&self->PagesWrittenPerSec)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PagesWrittenPerSec( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PagesWrittenPerSec, 0, sizeof(self->PagesWrittenPerSec)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_AvailableSwap( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->AvailableSwap)->value = x; ((MI_Uint64Field*)&self->AvailableSwap)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_AvailableSwap( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->AvailableSwap, 0, sizeof(self->AvailableSwap)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PercentAvailableSwap( SCX_MemoryStatisticalInformation* self, MI_Uint8 x) { ((MI_Uint8Field*)&self->PercentAvailableSwap)->value = x; ((MI_Uint8Field*)&self->PercentAvailableSwap)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PercentAvailableSwap( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PercentAvailableSwap, 0, sizeof(self->PercentAvailableSwap)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_UsedSwap( SCX_MemoryStatisticalInformation* self, MI_Uint64 x) { ((MI_Uint64Field*)&self->UsedSwap)->value = x; ((MI_Uint64Field*)&self->UsedSwap)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_UsedSwap( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->UsedSwap, 0, sizeof(self->UsedSwap)); return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Set_PercentUsedSwap( SCX_MemoryStatisticalInformation* self, MI_Uint8 x) { ((MI_Uint8Field*)&self->PercentUsedSwap)->value = x; ((MI_Uint8Field*)&self->PercentUsedSwap)->exists = 1; return MI_RESULT_OK; } MI_INLINE MI_Result MI_CALL SCX_MemoryStatisticalInformation_Clear_PercentUsedSwap( SCX_MemoryStatisticalInformation* self) { memset((void*)&self->PercentUsedSwap, 0, sizeof(self->PercentUsedSwap)); return MI_RESULT_OK; } /* **============================================================================== ** ** SCX_MemoryStatisticalInformation provider function prototypes ** **============================================================================== */ /* The developer may optionally define this structure */ typedef struct _SCX_MemoryStatisticalInformation_Self SCX_MemoryStatisticalInformation_Self; MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_Load( SCX_MemoryStatisticalInformation_Self** self, MI_Module_Self* selfModule, MI_Context* context); MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_Unload( SCX_MemoryStatisticalInformation_Self* self, MI_Context* context); MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_EnumerateInstances( SCX_MemoryStatisticalInformation_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const MI_PropertySet* propertySet, MI_Boolean keysOnly, const MI_Filter* filter); MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_GetInstance( SCX_MemoryStatisticalInformation_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const SCX_MemoryStatisticalInformation* instanceName, const MI_PropertySet* propertySet); MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_CreateInstance( SCX_MemoryStatisticalInformation_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const SCX_MemoryStatisticalInformation* newInstance); MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_ModifyInstance( SCX_MemoryStatisticalInformation_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const SCX_MemoryStatisticalInformation* modifiedInstance, const MI_PropertySet* propertySet); MI_EXTERN_C void MI_CALL SCX_MemoryStatisticalInformation_DeleteInstance( SCX_MemoryStatisticalInformation_Self* self, MI_Context* context, const MI_Char* nameSpace, const MI_Char* className, const SCX_MemoryStatisticalInformation* instanceName); /* **============================================================================== ** ** SCX_MemoryStatisticalInformation_Class ** **============================================================================== */ #ifdef __cplusplus # include <micxx/micxx.h> MI_BEGIN_NAMESPACE class SCX_MemoryStatisticalInformation_Class : public SCX_StatisticalInformation_Class { public: typedef SCX_MemoryStatisticalInformation Self; SCX_MemoryStatisticalInformation_Class() : SCX_StatisticalInformation_Class(&SCX_MemoryStatisticalInformation_rtti) { } SCX_MemoryStatisticalInformation_Class( const SCX_MemoryStatisticalInformation* instanceName, bool keysOnly) : SCX_StatisticalInformation_Class( &SCX_MemoryStatisticalInformation_rtti, &instanceName->__instance, keysOnly) { } SCX_MemoryStatisticalInformation_Class( const MI_ClassDecl* clDecl, const MI_Instance* instance, bool keysOnly) : SCX_StatisticalInformation_Class(clDecl, instance, keysOnly) { } SCX_MemoryStatisticalInformation_Class( const MI_ClassDecl* clDecl) : SCX_StatisticalInformation_Class(clDecl) { } SCX_MemoryStatisticalInformation_Class& operator=( const SCX_MemoryStatisticalInformation_Class& x) { CopyRef(x); return *this; } SCX_MemoryStatisticalInformation_Class( const SCX_MemoryStatisticalInformation_Class& x) : SCX_StatisticalInformation_Class(x) { } static const MI_ClassDecl* GetClassDecl() { return &SCX_MemoryStatisticalInformation_rtti; } // // SCX_MemoryStatisticalInformation_Class.AvailableMemory // const Field<Uint64>& AvailableMemory() const { const size_t n = offsetof(Self, AvailableMemory); return GetField<Uint64>(n); } void AvailableMemory(const Field<Uint64>& x) { const size_t n = offsetof(Self, AvailableMemory); GetField<Uint64>(n) = x; } const Uint64& AvailableMemory_value() const { const size_t n = offsetof(Self, AvailableMemory); return GetField<Uint64>(n).value; } void AvailableMemory_value(const Uint64& x) { const size_t n = offsetof(Self, AvailableMemory); GetField<Uint64>(n).Set(x); } bool AvailableMemory_exists() const { const size_t n = offsetof(Self, AvailableMemory); return GetField<Uint64>(n).exists ? true : false; } void AvailableMemory_clear() { const size_t n = offsetof(Self, AvailableMemory); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PercentAvailableMemory // const Field<Uint8>& PercentAvailableMemory() const { const size_t n = offsetof(Self, PercentAvailableMemory); return GetField<Uint8>(n); } void PercentAvailableMemory(const Field<Uint8>& x) { const size_t n = offsetof(Self, PercentAvailableMemory); GetField<Uint8>(n) = x; } const Uint8& PercentAvailableMemory_value() const { const size_t n = offsetof(Self, PercentAvailableMemory); return GetField<Uint8>(n).value; } void PercentAvailableMemory_value(const Uint8& x) { const size_t n = offsetof(Self, PercentAvailableMemory); GetField<Uint8>(n).Set(x); } bool PercentAvailableMemory_exists() const { const size_t n = offsetof(Self, PercentAvailableMemory); return GetField<Uint8>(n).exists ? true : false; } void PercentAvailableMemory_clear() { const size_t n = offsetof(Self, PercentAvailableMemory); GetField<Uint8>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.UsedMemory // const Field<Uint64>& UsedMemory() const { const size_t n = offsetof(Self, UsedMemory); return GetField<Uint64>(n); } void UsedMemory(const Field<Uint64>& x) { const size_t n = offsetof(Self, UsedMemory); GetField<Uint64>(n) = x; } const Uint64& UsedMemory_value() const { const size_t n = offsetof(Self, UsedMemory); return GetField<Uint64>(n).value; } void UsedMemory_value(const Uint64& x) { const size_t n = offsetof(Self, UsedMemory); GetField<Uint64>(n).Set(x); } bool UsedMemory_exists() const { const size_t n = offsetof(Self, UsedMemory); return GetField<Uint64>(n).exists ? true : false; } void UsedMemory_clear() { const size_t n = offsetof(Self, UsedMemory); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PercentUsedMemory // const Field<Uint8>& PercentUsedMemory() const { const size_t n = offsetof(Self, PercentUsedMemory); return GetField<Uint8>(n); } void PercentUsedMemory(const Field<Uint8>& x) { const size_t n = offsetof(Self, PercentUsedMemory); GetField<Uint8>(n) = x; } const Uint8& PercentUsedMemory_value() const { const size_t n = offsetof(Self, PercentUsedMemory); return GetField<Uint8>(n).value; } void PercentUsedMemory_value(const Uint8& x) { const size_t n = offsetof(Self, PercentUsedMemory); GetField<Uint8>(n).Set(x); } bool PercentUsedMemory_exists() const { const size_t n = offsetof(Self, PercentUsedMemory); return GetField<Uint8>(n).exists ? true : false; } void PercentUsedMemory_clear() { const size_t n = offsetof(Self, PercentUsedMemory); GetField<Uint8>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PercentUsedByCache // const Field<Uint8>& PercentUsedByCache() const { const size_t n = offsetof(Self, PercentUsedByCache); return GetField<Uint8>(n); } void PercentUsedByCache(const Field<Uint8>& x) { const size_t n = offsetof(Self, PercentUsedByCache); GetField<Uint8>(n) = x; } const Uint8& PercentUsedByCache_value() const { const size_t n = offsetof(Self, PercentUsedByCache); return GetField<Uint8>(n).value; } void PercentUsedByCache_value(const Uint8& x) { const size_t n = offsetof(Self, PercentUsedByCache); GetField<Uint8>(n).Set(x); } bool PercentUsedByCache_exists() const { const size_t n = offsetof(Self, PercentUsedByCache); return GetField<Uint8>(n).exists ? true : false; } void PercentUsedByCache_clear() { const size_t n = offsetof(Self, PercentUsedByCache); GetField<Uint8>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PagesPerSec // const Field<Uint64>& PagesPerSec() const { const size_t n = offsetof(Self, PagesPerSec); return GetField<Uint64>(n); } void PagesPerSec(const Field<Uint64>& x) { const size_t n = offsetof(Self, PagesPerSec); GetField<Uint64>(n) = x; } const Uint64& PagesPerSec_value() const { const size_t n = offsetof(Self, PagesPerSec); return GetField<Uint64>(n).value; } void PagesPerSec_value(const Uint64& x) { const size_t n = offsetof(Self, PagesPerSec); GetField<Uint64>(n).Set(x); } bool PagesPerSec_exists() const { const size_t n = offsetof(Self, PagesPerSec); return GetField<Uint64>(n).exists ? true : false; } void PagesPerSec_clear() { const size_t n = offsetof(Self, PagesPerSec); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PagesReadPerSec // const Field<Uint64>& PagesReadPerSec() const { const size_t n = offsetof(Self, PagesReadPerSec); return GetField<Uint64>(n); } void PagesReadPerSec(const Field<Uint64>& x) { const size_t n = offsetof(Self, PagesReadPerSec); GetField<Uint64>(n) = x; } const Uint64& PagesReadPerSec_value() const { const size_t n = offsetof(Self, PagesReadPerSec); return GetField<Uint64>(n).value; } void PagesReadPerSec_value(const Uint64& x) { const size_t n = offsetof(Self, PagesReadPerSec); GetField<Uint64>(n).Set(x); } bool PagesReadPerSec_exists() const { const size_t n = offsetof(Self, PagesReadPerSec); return GetField<Uint64>(n).exists ? true : false; } void PagesReadPerSec_clear() { const size_t n = offsetof(Self, PagesReadPerSec); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PagesWrittenPerSec // const Field<Uint64>& PagesWrittenPerSec() const { const size_t n = offsetof(Self, PagesWrittenPerSec); return GetField<Uint64>(n); } void PagesWrittenPerSec(const Field<Uint64>& x) { const size_t n = offsetof(Self, PagesWrittenPerSec); GetField<Uint64>(n) = x; } const Uint64& PagesWrittenPerSec_value() const { const size_t n = offsetof(Self, PagesWrittenPerSec); return GetField<Uint64>(n).value; } void PagesWrittenPerSec_value(const Uint64& x) { const size_t n = offsetof(Self, PagesWrittenPerSec); GetField<Uint64>(n).Set(x); } bool PagesWrittenPerSec_exists() const { const size_t n = offsetof(Self, PagesWrittenPerSec); return GetField<Uint64>(n).exists ? true : false; } void PagesWrittenPerSec_clear() { const size_t n = offsetof(Self, PagesWrittenPerSec); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.AvailableSwap // const Field<Uint64>& AvailableSwap() const { const size_t n = offsetof(Self, AvailableSwap); return GetField<Uint64>(n); } void AvailableSwap(const Field<Uint64>& x) { const size_t n = offsetof(Self, AvailableSwap); GetField<Uint64>(n) = x; } const Uint64& AvailableSwap_value() const { const size_t n = offsetof(Self, AvailableSwap); return GetField<Uint64>(n).value; } void AvailableSwap_value(const Uint64& x) { const size_t n = offsetof(Self, AvailableSwap); GetField<Uint64>(n).Set(x); } bool AvailableSwap_exists() const { const size_t n = offsetof(Self, AvailableSwap); return GetField<Uint64>(n).exists ? true : false; } void AvailableSwap_clear() { const size_t n = offsetof(Self, AvailableSwap); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PercentAvailableSwap // const Field<Uint8>& PercentAvailableSwap() const { const size_t n = offsetof(Self, PercentAvailableSwap); return GetField<Uint8>(n); } void PercentAvailableSwap(const Field<Uint8>& x) { const size_t n = offsetof(Self, PercentAvailableSwap); GetField<Uint8>(n) = x; } const Uint8& PercentAvailableSwap_value() const { const size_t n = offsetof(Self, PercentAvailableSwap); return GetField<Uint8>(n).value; } void PercentAvailableSwap_value(const Uint8& x) { const size_t n = offsetof(Self, PercentAvailableSwap); GetField<Uint8>(n).Set(x); } bool PercentAvailableSwap_exists() const { const size_t n = offsetof(Self, PercentAvailableSwap); return GetField<Uint8>(n).exists ? true : false; } void PercentAvailableSwap_clear() { const size_t n = offsetof(Self, PercentAvailableSwap); GetField<Uint8>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.UsedSwap // const Field<Uint64>& UsedSwap() const { const size_t n = offsetof(Self, UsedSwap); return GetField<Uint64>(n); } void UsedSwap(const Field<Uint64>& x) { const size_t n = offsetof(Self, UsedSwap); GetField<Uint64>(n) = x; } const Uint64& UsedSwap_value() const { const size_t n = offsetof(Self, UsedSwap); return GetField<Uint64>(n).value; } void UsedSwap_value(const Uint64& x) { const size_t n = offsetof(Self, UsedSwap); GetField<Uint64>(n).Set(x); } bool UsedSwap_exists() const { const size_t n = offsetof(Self, UsedSwap); return GetField<Uint64>(n).exists ? true : false; } void UsedSwap_clear() { const size_t n = offsetof(Self, UsedSwap); GetField<Uint64>(n).Clear(); } // // SCX_MemoryStatisticalInformation_Class.PercentUsedSwap // const Field<Uint8>& PercentUsedSwap() const { const size_t n = offsetof(Self, PercentUsedSwap); return GetField<Uint8>(n); } void PercentUsedSwap(const Field<Uint8>& x) { const size_t n = offsetof(Self, PercentUsedSwap); GetField<Uint8>(n) = x; } const Uint8& PercentUsedSwap_value() const { const size_t n = offsetof(Self, PercentUsedSwap); return GetField<Uint8>(n).value; } void PercentUsedSwap_value(const Uint8& x) { const size_t n = offsetof(Self, PercentUsedSwap); GetField<Uint8>(n).Set(x); } bool PercentUsedSwap_exists() const { const size_t n = offsetof(Self, PercentUsedSwap); return GetField<Uint8>(n).exists ? true : false; } void PercentUsedSwap_clear() { const size_t n = offsetof(Self, PercentUsedSwap); GetField<Uint8>(n).Clear(); } }; typedef Array<SCX_MemoryStatisticalInformation_Class> SCX_MemoryStatisticalInformation_ClassA; MI_END_NAMESPACE #endif /* __cplusplus */ #endif /* _SCX_MemoryStatisticalInformation_h */
28.286477
109
0.686073
4ade42248f066e3c9589af0e0fd0775085a15056
161
h
C
Rearrengine/Engine/UI/About.h
jcarlos0305/Game-Engine
a64116e42f81283af6724643863f271891fe9848
[ "MIT" ]
null
null
null
Rearrengine/Engine/UI/About.h
jcarlos0305/Game-Engine
a64116e42f81283af6724643863f271891fe9848
[ "MIT" ]
null
null
null
Rearrengine/Engine/UI/About.h
jcarlos0305/Game-Engine
a64116e42f81283af6724643863f271891fe9848
[ "MIT" ]
null
null
null
#pragma once #include "Utils/Globals.h" #include "UIWindow.h" class About : public UIWindow { public: About(); ~About(); void Draw(); bool CleanUp(); };
10.733333
31
0.652174
d1db657da4565723ecd321f594962b819fcf786b
345
c
C
CProgramming/series demo3.c
Th3At0nic/Cprograms
0ed84c7cb86310106d2f4fe13b96664874510680
[ "MIT" ]
null
null
null
CProgramming/series demo3.c
Th3At0nic/Cprograms
0ed84c7cb86310106d2f4fe13b96664874510680
[ "MIT" ]
null
null
null
CProgramming/series demo3.c
Th3At0nic/Cprograms
0ed84c7cb86310106d2f4fe13b96664874510680
[ "MIT" ]
null
null
null
//write a program that displays the sum of float n numbers\ // 1.5 + 2.5 + 3.5 + ......... + n #include<stdio.h> int main() { float i, sum=0, n; printf("Enter N number: "); scanf("%f", &n); for(i=1.5; i<=n; i++) { sum = sum+i; } printf("Sum of numbers: %f\n", sum); return 0; }
15.681818
60
0.449275
9e8256780b7be53fde00864a3b6416cbb4420002
8,370
c
C
src/uclibc/uClibc-0.9.28.3/libm/float_wrappers.c
aps337/unum-sdk
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
[ "Apache-2.0" ]
31
2018-08-01T21:25:24.000Z
2022-02-14T07:52:34.000Z
src/uclibc/uClibc-0.9.28.3/libm/float_wrappers.c
aps337/unum-sdk
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
[ "Apache-2.0" ]
40
2018-12-03T19:48:52.000Z
2021-03-10T06:34:26.000Z
src/uclibc/uClibc-0.9.28.3/libm/float_wrappers.c
aps337/unum-sdk
2de3ae625e474c5064f6a88b720ec2ffdcdefad9
[ "Apache-2.0" ]
20
2018-11-16T21:19:22.000Z
2021-10-18T23:08:24.000Z
/* vi: set sw=4 ts=4: */ /* * Wrapper functions implementing all the float math functions * defined by SuSv3 by actually calling the double version of * each function and then casting the result back to a float * to return to the user. * * Copyright (C) 2005 by Erik Andersen <andersen@uclibc.org> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Library General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This 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 Library General Public License * for more details. * * You should have received a copy of the GNU Library General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "math.h" /* For the time being, do _NOT_ implement these functions * that are defined by SuSv3 */ #if 0 float exp2f(float); float fmaf(float, float, float); float fmaxf(float, float); float fminf(float, float); float fdimf(float, float); long long llrintf(float); long long llroundf(float); long lroundf(float); float log2f(float); long lrintf(float); float nexttowardf(float, long double); float remquof(float, float, int *); float roundf(float); float scalblnf(float, long); float truncf(float); float tgammaf(float); #endif /* Implement the following, as defined by SuSv3 */ #if 0 float acosf(float); float acoshf(float); float asinf(float); float asinhf(float); float atan2f(float, float); float atanf(float); float atanhf(float); float cbrtf(float); float ceilf(float); float copysignf(float, float); float cosf(float); float coshf(float); float erfcf(float); float erff(float); float expf(float); float expm1f(float); float fabsf(float); float floorf(float); float fmodf(float, float); float frexpf(float value, int *); float hypotf(float, float); int ilogbf(float); float ldexpf(float, int); float lgammaf(float); float log10f(float); float log1pf(float); float logbf(float); float logf(float); float modff(float, float *); float nearbyintf(float); float nextafterf(float, float); float powf(float, float); float remainderf(float, float); float rintf(float); float scalbnf(float, int); float sinf(float); float sinhf(float); float sqrtf(float); float tanf(float); float tanhf(float); #endif #ifdef L_acosf float acosf (float x) { return (float) acos( (double)x ); } #endif #ifdef L_acoshf float acoshf (float x) { return (float) acosh( (double)x ); } #endif #ifdef L_asinf float asinf (float x) { return (float) asin( (double)x ); } #endif #ifdef L_asinhf float asinhf (float x) { return (float) asinh( (double)x ); } #endif #ifdef L_atan2f float atan2f (float x, float y) { return (float) atan2( (double)x, (double)y ); } #endif #ifdef L_atanf float atanf (float x) { return (float) atan( (double)x ); } #endif #ifdef L_atanhf float atanhf (float x) { return (float) atanh( (double)x ); } #endif #ifdef L_cbrtf float cbrtf (float x) { return (float) cbrt( (double)x ); } #endif #ifdef L_ceilf float ceilf (float x) { return (float) ceil( (double)x ); } #endif #ifdef L_copysignf float copysignf (float x, float y) { return (float) copysign( (double)x, (double)y ); } #endif #ifdef L_cosf float cosf (float x) { return (float) cos( (double)x ); } #endif #ifdef L_coshf float coshf (float x) { return (float) cosh( (double)x ); } #endif #ifdef L_erfcf float erfcf (float x) { return (float) erfc( (double)x ); } #endif #ifdef L_erff float erff (float x) { return (float) erf( (double)x ); } #endif #if 0 #ifdef L_exp2f float exp2f (float x) { return (float) exp2( (double)x ); } #endif #endif #ifdef L_expf float expf (float x) { return (float) exp( (double)x ); } #endif #ifdef L_expm1f float expm1f (float x) { return (float) expm1( (double)x ); } #endif #ifdef L_fabsf float fabsf (float x) { return (float) fabs( (double)x ); } #endif #if 0 #ifdef L_fdimf float fdimf (float x, float y) { return (float) fdim( (double)x, (double)y ); } #endif #endif #ifdef L_floorf float floorf (float x) { return (float) floor( (double)x ); } #endif #if 0 #ifdef L_fmaf float fmaf (float x, float y, float z) { return (float) fma( (double)x, (double)y, (double)z ); } #endif #ifdef L_fmaxf float fmaxf (float x, float y) { return (float) fmax( (double)x, (double)y ); } #endif #ifdef L_fminf float fminf (float x, float y) { return (float) fmin( (double)x, (double)y ); } #endif #endif #ifdef L_fmodf float fmodf (float x, float y) { return (float) fmod( (double)x, (double)y ); } #endif #ifdef L_frexpf float frexpf (float x, int *exp) { return (float) frexp( (double)x, exp ); } #endif #ifdef L_hypotf float hypotf (float x, float y) { return (float) hypot( (double)x, (double)y ); } #endif #ifdef L_ilogbf int ilogbf (float x) { return (float) ilogb( (double)x ); } #endif #ifdef L_ldexpf float ldexpf (float x, int exp) { return (float) ldexp( (double)x, exp ); } #endif #ifdef L_lgammaf float lgammaf (float x) { return (float) lgamma( (double)x ); } #endif #if 0 #ifdef L_llrintf long long llrintf (float x) { return (float) llrint( (double)x ); } #endif #ifdef L_llroundf long long llroundf (float x) { return (float) llround( (double)x ); } #endif #endif #ifdef L_log10f float log10f (float x) { return (float) log10( (double)x ); } #endif #ifdef L_log1pf float log1pf (float x) { return (float) log1p( (double)x ); } #endif #if 0 #ifdef L_log2f float log2f (float x) { return (float) log2( (double)x ); } #endif #endif #ifdef L_logbf float logbf (float x) { return (float) logb( (double)x ); } #endif #ifdef L_logf float logf (float x) { return (float) log( (double)x ); } #endif #if 0 #ifdef L_lrintf long lrintf (float x) { return (float) lrint( (double)x ); } #endif #ifdef L_lroundf long lroundf (float x) { return (float) lround( (double)x ); } #endif #endif #ifdef L_modff float modff (float x, float *iptr) { double y, result; result = modf ( x, &y ); *iptr = (float)y; return (float) result; } #endif #if 0 #ifdef L_nearbyintf float nearbyintf (float x) { return (float) nearbyint( (double)x ); } #endif #endif #ifdef L_nextafterf float nextafterf (float x, float y) { return (float) nextafter( (double)x, (double)y ); } #endif #if 0 #ifdef L_nexttowardf float nexttowardf (float x, long double y) { return (float) nexttoward( (double)x, (double)y ); } #endif #endif #ifdef L_powf float powf (float x, float y) { return (float) pow( (double)x, (double)y ); } #endif #ifdef L_remainderf float remainderf (float x, float y) { return (float) remainder( (double)x, (double)y ); } #endif #if 0 #ifdef L_remquof float remquof (float x, float y, int *quo) { return (float) remquo( (double)x, (double)y, quo ); } #endif #endif #ifdef L_rintf float rintf (float x) { return (float) rint( (double)x ); } #endif #if 0 #ifdef L_roundf float roundf (float x) { return (float) round( (double)x ); } #endif #ifdef L_scalblnf float scalblnf (float x, long exp) { return (float) scalbln( (double)x, exp ); } #endif #endif #ifdef L_scalbnf float scalbnf (float x, int exp) { return (float) scalbn( (double)x, exp ); } #endif #ifdef L_sinf float sinf (float x) { return (float) sin( (double)x ); } #endif #ifdef L_sinhf float sinhf (float x) { return (float) sinh( (double)x ); } #endif #ifdef L_sqrtf float sqrtf (float x) { return (float) sqrt( (double)x ); } #endif #ifdef L_tanf float tanf (float x) { return (float) tan( (double)x ); } #endif #ifdef L_tanhf float tanhf (float x) { return (float) tanh( (double)x ); } #endif #if 0 #ifdef L_tgammaf float tgammaf (float x) { return (float) tgamma( (double)x ); } #endif #ifdef L_truncf float truncf (float x) { return (float) trunc( (double)x ); } #endif #endif
14.840426
79
0.656631
9ecaf0efc1015c9cd3057b0741bce577e2bcab9c
464,910
h
C
modules/lwjgl/vma/src/main/c/vk_mem_alloc.h
Dico200/lwjgl3
7ef51d1054aa4647bc8aafcfd3d93c6a6ad1410f
[ "BSD-3-Clause" ]
null
null
null
modules/lwjgl/vma/src/main/c/vk_mem_alloc.h
Dico200/lwjgl3
7ef51d1054aa4647bc8aafcfd3d93c6a6ad1410f
[ "BSD-3-Clause" ]
null
null
null
modules/lwjgl/vma/src/main/c/vk_mem_alloc.h
Dico200/lwjgl3
7ef51d1054aa4647bc8aafcfd3d93c6a6ad1410f
[ "BSD-3-Clause" ]
1
2019-12-19T22:57:15.000Z
2019-12-19T22:57:15.000Z
// // 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. // #ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H #define AMD_VULKAN_MEMORY_ALLOCATOR_H #ifdef __cplusplus extern "C" { #endif /** \mainpage Vulkan Memory Allocator <b>Version 2.1.0</b> (2018-09-10) Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved. \n License: MIT Documentation of all members: vk_mem_alloc.h \section main_table_of_contents Table of contents - <b>User guide</b> - \subpage quick_start - [Project setup](@ref quick_start_project_setup) - [Initialization](@ref quick_start_initialization) - [Resource allocation](@ref quick_start_resource_allocation) - \subpage choosing_memory_type - [Usage](@ref choosing_memory_type_usage) - [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags) - [Explicit memory types](@ref choosing_memory_type_explicit_memory_types) - [Custom memory pools](@ref choosing_memory_type_custom_memory_pools) - \subpage memory_mapping - [Mapping functions](@ref memory_mapping_mapping_functions) - [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory) - [Cache control](@ref memory_mapping_cache_control) - [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable) - \subpage custom_memory_pools - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex) - [Linear allocation algorithm](@ref linear_algorithm) - [Free-at-once](@ref linear_algorithm_free_at_once) - [Stack](@ref linear_algorithm_stack) - [Double stack](@ref linear_algorithm_double_stack) - [Ring buffer](@ref linear_algorithm_ring_buffer) - \subpage defragmentation - \subpage lost_allocations - \subpage statistics - [Numeric statistics](@ref statistics_numeric_statistics) - [JSON dump](@ref statistics_json_dump) - \subpage allocation_annotation - [Allocation user data](@ref allocation_user_data) - [Allocation names](@ref allocation_names) - \subpage debugging_memory_usage - [Memory initialization](@ref debugging_memory_usage_initialization) - [Margins](@ref debugging_memory_usage_margins) - [Corruption detection](@ref debugging_memory_usage_corruption_detection) - \subpage record_and_replay - \subpage usage_patterns - [Simple patterns](@ref usage_patterns_simple) - [Advanced patterns](@ref usage_patterns_advanced) - \subpage configuration - [Pointers to Vulkan functions](@ref config_Vulkan_functions) - [Custom host memory allocator](@ref custom_memory_allocator) - [Device memory allocation callbacks](@ref allocation_callbacks) - [Device heap memory limit](@ref heap_memory_limit) - \subpage vk_khr_dedicated_allocation - \subpage general_considerations - [Thread safety](@ref general_considerations_thread_safety) - [Validation layer warnings](@ref general_considerations_validation_layer_warnings) - [Allocation algorithm](@ref general_considerations_allocation_algorithm) - [Features not supported](@ref general_considerations_features_not_supported) \section main_see_also See also - [Product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/) - [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator) \page quick_start Quick start \section quick_start_project_setup Project setup Vulkan Memory Allocator comes in form of a single header file. You don't need to build it as a separate library project. You can add this file directly to your project and submit it to code repository next to your other source files. "Single header" doesn't mean that everything is contained in C/C++ declarations, like it tends to be in case of inline functions or C++ templates. It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro. If you don't do it properly, you will get linker errors. To do it properly: -# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library. This includes declarations of all members of the library. -# In exacly one CPP file define following macro before this include. It enables also internal definitions. \code #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" \endcode It may be a good idea to create dedicated CPP file just for this purpose. Please note that this library includes header `<vulkan/vulkan.h>`, which in turn includes `<windows.h>` on Windows. If you need some specific macros defined before including these headers (like `WIN32_LEAN_AND_MEAN` or `WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define them before every `#include` of this library. \section quick_start_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 quick_start_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(). For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory(). -# 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 more details, see description of this enum. 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 To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`, to be able to read from it or write to it in CPU code. Mapping is possible only of memory allocated from a memory type that has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag. Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose. You can use them directly with memory allocated by this library, but it is not recommended because of following issue: Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed. This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan. Because of this, Vulkan Memory Allocator provides following facilities: \section memory_mapping_mapping_functions Mapping functions The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory(). They are safer and more convenient to use than standard Vulkan functions. You can map an allocation multiple times simultaneously - mapping is reference-counted internally. You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block. The way it's implemented is that the library always maps entire memory block, not just region of the allocation. For further details, see description of vmaMapMemory() function. Example: \code // Having these objects initialized: struct ConstantBuffer { ... }; ConstantBuffer constantBufferData; VmaAllocator allocator; VkBuffer constantBuffer; VmaAllocation constantBufferAllocation; // You can map and fill your buffer using following code: void* mappedData; vmaMapMemory(allocator, constantBufferAllocation, &mappedData); memcpy(mappedData, &constantBufferData, sizeof(constantBufferData)); vmaUnmapMemory(allocator, constantBufferAllocation); \endcode When mapping, you may see a warning from Vulkan validation layer similar to this one: <i>Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.</i> It happens because the library maps entire `VkDeviceMemory` block, where different types of images and buffers may end up together, especially on GPUs with unified memory like Intel. You can safely ignore it if you are sure you access only memory of the intended object that you wanted to map. \section memory_mapping_persistently_mapped_memory Persistently mapped memory Kepping your memory persistently mapped is generally OK in Vulkan. You don't need to unmap it before using its data on the GPU. The library provides a special feature designed for that: Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in VmaAllocationCreateInfo::flags stay mapped all the time, so you can just access CPU pointer to it any time without a need to call any "map" or "unmap" function. Example: \code VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = sizeof(ConstantBuffer); 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 already mapped. You can access its memory. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData)); \endcode There are some exceptions though, when you should consider mapping memory only for a short period of time: - When operating system is Windows 7 or 8.x (Windows 10 is not affected because it uses WDDM2), device is discrete AMD GPU, and memory type is the special 256 MiB pool of `DEVICE_LOCAL + HOST_VISIBLE` memory (selected when you use #VMA_MEMORY_USAGE_CPU_TO_GPU), then whenever a memory block allocated from this memory type stays 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. - Keeping many large memory blocks mapped may impact performance or stability of some debugging tools. \section memory_mapping_cache_control Cache control Memory in Vulkan doesn't need to be unmapped before using it on GPU, but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set, you need to manually invalidate cache before reading of mapped pointer and flush cache after writing to mapped pointer. Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`, `vkInvalidateMappedMemoryRanges()`, but this library provides more convenient functions that refer to given allocation object: vmaFlushAllocation(), vmaInvalidateAllocation(). Regions of memory specified for flush/invalidate must be aligned to `VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library. In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations within blocks are aligned to this value, so their offsets are always multiply of `nonCoherentAtomSize` and two different allocations never share same "line" of this size. Please note that memory allocated with #VMA_MEMORY_USAGE_CPU_ONLY is guaranteed to be `HOST_COHERENT`. Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA) currently provide `HOST_COHERENT` flag on all memory types that are `HOST_VISIBLE`, so on this platform you may not need to bother. \section memory_mapping_finding_if_memory_mappable Finding out if memory is mappable It may happen that your allocation ends up in memory that is `HOST_VISIBLE` (available for mapping) despite it wasn't explicitly requested. For example, application may work on integrated graphics with unified memory (like Intel) or allocation from video memory might have failed, so the library chose system memory as fallback. You can detect this case and map such allocation to access its memory on CPU directly, instead of launching a transfer operation. In order to do that: inspect `allocInfo.memoryType`, call vmaGetMemoryTypeProperties(), and look for `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag in properties of that memory type. \code VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = sizeof(ConstantBuffer); bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; VkBuffer buf; VmaAllocation alloc; VmaAllocationInfo allocInfo; vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); VkMemoryPropertyFlags memFlags; vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags); if((memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { // Allocation ended up in mappable memory. You can map it and access it directly. void* mappedData; vmaMapMemory(allocator, alloc, &mappedData); memcpy(mappedData, &constantBufferData, sizeof(constantBufferData)); vmaUnmapMemory(allocator, alloc); } else { // Allocation ended up in non-mappable memory. // You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer. } \endcode You can even use #VMA_ALLOCATION_CREATE_MAPPED_BIT flag while creating allocations that are not necessarily `HOST_VISIBLE` (e.g. using #VMA_MEMORY_USAGE_GPU_ONLY). If the allocation ends up in memory type that is `HOST_VISIBLE`, it will be persistently mapped and you can use it directly. If not, the flag is just ignored. Example: \code VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = sizeof(ConstantBuffer); 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_MAPPED_BIT; VkBuffer buf; VmaAllocation alloc; VmaAllocationInfo allocInfo; vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); if(allocInfo.pUserData != nullptr) { // Allocation ended up in mappable memory. // It's persistently mapped. You can access it directly. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData)); } else { // Allocation ended up in non-mappable memory. // You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer. } \endcode \page custom_memory_pools Custom memory pools A memory pool contains a number of `VkDeviceMemory` blocks. The library automatically creates and manages default pool for each memory type available on the device. Default memory pool automatically grows in size. Size of allocated blocks is also variable and managed automatically. 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, fixed size of Vulkan memory blocks. - Limit maximum amount of Vulkan memory allocated for that pool. - Reserve minimum or fixed amount of Vulkan memory always preallocated 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 can 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 helper functions vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo(). You need to provide structures with example parameters of buffers or images that you are going to create in that pool. \code VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; exampleBufCreateInfo.size = 1024; // Whatever. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Change if needed. VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; // Change if needed. uint32_t memTypeIndex; vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex); VmaPoolCreateInfo poolCreateInfo = {}; poolCreateInfo.memoryTypeIndex = memTypeIndex; // ... \endcode When creating buffers/images allocated in that pool, provide following parameters: - `VkBufferCreateInfo`: Prefer to pass same parameters as above. Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior. Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers or the other way around. - VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member. Other members are ignored anyway. \section linear_algorithm Linear allocation algorithm Each Vulkan memory block managed by this library has accompanying metadata that keeps track of used and unused regions. By default, the metadata structure and algorithm tries to find best place for new allocations among free regions to optimize memory usage. This way you can allocate and free objects in any order. ![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png) Sometimes there is a need to use simpler, linear allocation algorithm. You can create custom pool that uses such algorithm by adding flag #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating #VmaPool object. Then an alternative metadata management is used. It always creates new allocations after last one and doesn't reuse free regions after allocations freed in the middle. It results in better allocation performance and less memory consumed by metadata. ![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png) With this one flag, you can create a custom pool that can be used in many ways: free-at-once, stack, double stack, and ring buffer. See below for details. \subsection linear_algorithm_free_at_once Free-at-once In a pool that uses linear algorithm, you still need to free all the allocations individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free them in any order. New allocations are always made after last one - free space in the middle is not reused. However, when you release all the allocation and the pool becomes empty, allocation starts from the beginning again. This way you can use linear algorithm to speed up creation of allocations that you are going to release all at once. ![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png) This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount value that allows multiple memory blocks. \subsection linear_algorithm_stack Stack When you free an allocation that was created last, its space can be reused. Thanks to this, if you always release allocations in the order opposite to their creation (LIFO - Last In First Out), you can achieve behavior of a stack. ![Stack](../gfx/Linear_allocator_4_stack.png) This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount value that allows multiple memory blocks. \subsection linear_algorithm_double_stack Double stack The space reserved by a custom pool with linear algorithm may be used by two stacks: - First, default one, growing up from offset 0. - Second, "upper" one, growing down from the end towards lower offsets. To make allocation from upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT to VmaAllocationCreateInfo::flags. ![Double stack](../gfx/Linear_allocator_7_double_stack.png) Double stack is available only in pools with one memory block - VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined. When the two stacks' ends meet so there is not enough space between them for a new allocation, such allocation fails with usual `VK_ERROR_OUT_OF_DEVICE_MEMORY` error. \subsection linear_algorithm_ring_buffer Ring buffer When you free some allocations from the beginning and there is not enough free space for a new one at the end of a pool, allocator's "cursor" wraps around to the beginning and starts allocation there. Thanks to this, if you always release allocations in the same order as you created them (FIFO - First In First Out), you can achieve behavior of a ring buffer / queue. ![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png) Pools with linear algorithm support [lost allocations](@ref lost_allocations) when used as ring buffer. If there is not enough free space for a new allocation, but existing allocations from the front of the queue can become lost, they become lost and the allocation succeeds. ![Ring buffer with lost allocations](../gfx/Linear_allocator_6_ring_buffer_lost.png) Ring buffer is available only in pools with one memory block - VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined. \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 vmaTouchAllocation(). 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. vmaGetAllocationInfo() can also be used for checking status of the allocation. Allocation is lost when returned VmaAllocationInfo::deviceMemory == `VK_NULL_HANDLE`. 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>Q: 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 vmaTouchAllocation() / vmaGetAllocationInfo() not only returns allocation status/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>Q: 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 vmaTouchAllocation() / 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>Q: 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. if(vmaTouchAllocation(allocator, m_Alloc)) { // 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. You can create an allocation that is already in lost state from the beginning using function vmaCreateLostAllocation(). It may be useful if you need a "dummy" allocation that is not null. You can call function vmaMakePoolAllocationsLost() to set all eligible allocations in a specified custom pool to lost state. Allocations that have been "touched" in current frame or VmaPoolCreateInfo::frameInUseCount frames back cannot become lost. <b>Q: Can I touch allocation that cannot become lost?</b> Yes, although it has no visible effect. Calls to vmaGetAllocationInfo() and vmaTouchAllocation() update last use frame index also for allocations that cannot become lost, but the only way to observe it is to dump internal allocator state using vmaBuildStatsString(). You can use this feature for debugging purposes to explicitly mark allocations that you use in current frame and then analyze JSON dump to see for how long each allocation stays unused. \page statistics Statistics This library contains functions that return information about its internal state, especially the amount of memory allocated from Vulkan. Please keep in mind that these functions need to traverse all internal data structures to gather these information, so they may be quite time-consuming. Don't call them too often. \section statistics_numeric_statistics Numeric statistics You can query for overall statistics of the allocator using function vmaCalculateStats(). Information are returned using structure #VmaStats. It contains #VmaStatInfo - number of allocated blocks, number of allocations (occupied ranges in these blocks), number of unused (free) ranges in these blocks, number of bytes used and unused (but still allocated from Vulkan) and other information. They are summed across memory heaps, memory types and total for whole allocator. You can query for statistics of a custom pool using function vmaGetPoolStats(). Information are returned using structure #VmaPoolStats. You can query for information about specific allocation using function vmaGetAllocationInfo(). It fill structure #VmaAllocationInfo. \section statistics_json_dump JSON dump You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString(). The result is guaranteed to be correct JSON. It uses ANSI encoding. Any strings provided by user (see [Allocation names](@ref allocation_names)) are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding, this JSON string can be treated as using this encoding. It must be freed using function vmaFreeStatsString(). The format of this JSON string is not part of official documentation of the library, but it will not change in backward-incompatible way without increasing library major version number and appropriate mention in changelog. The JSON string contains all the data that can be obtained using vmaCalculateStats(). It can also contain detailed map of allocated memory blocks and their regions - free and occupied by allocations. This allows e.g. to visualize the memory or assess fragmentation. \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 debugging_memory_usage Debugging incorrect memory usage If you suspect a bug with memory usage, like usage of uninitialized memory or memory being overwritten out of bounds of an allocation, you can use debug features of this library to verify this. \section debugging_memory_usage_initialization Memory initialization If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used, you can enable automatic memory initialization to verify this. To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1. \code #define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1 #include "vk_mem_alloc.h" \endcode It makes memory of all new allocations initialized to bit pattern `0xDCDCDCDC`. Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`. Memory is automatically mapped and unmapped if necessary. If you find these values while debugging your program, good chances are that you incorrectly read Vulkan memory that is allocated but not initialized, or already freed, respectively. Memory initialization works only with memory types that are `HOST_VISIBLE`. It works also with dedicated allocations. It doesn't work with allocations created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag, as they cannot be mapped. \section debugging_memory_usage_margins Margins By default, allocations are laid out in memory blocks next to each other if possible (considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`). ![Allocations without margin](../gfx/Margins_1.png) Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified number of bytes as a margin before and after every allocation. \code #define VMA_DEBUG_MARGIN 16 #include "vk_mem_alloc.h" \endcode ![Allocations with margin](../gfx/Margins_2.png) If your bug goes away after enabling margins, it means it may be caused by memory being overwritten outside of allocation boundaries. It is not 100% certain though. Change in application behavior may also be caused by different order and distribution of allocations across memory blocks after margins are applied. The margin is applied also before first and after last allocation in a block. It may occur only once between two adjacent allocations. Margins work with all types of memory. Margin is applied only to allocations made out of memory blocks and not to dedicated allocations, which have their own memory block of specific size. It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag or those automatically decided to put into dedicated allocations, e.g. due to its large size or recommended by VK_KHR_dedicated_allocation extension. Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space. Note that enabling margins increases memory usage and fragmentation. \section debugging_memory_usage_corruption_detection Corruption detection You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation of contents of the margins. \code #define VMA_DEBUG_MARGIN 16 #define VMA_DEBUG_DETECT_CORRUPTION 1 #include "vk_mem_alloc.h" \endcode When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN` (it must be multiply of 4) before and after every allocation is filled with a magic number. This idea is also know as "canary". Memory is automatically mapped and unmapped if necessary. This number is validated automatically when the allocation is destroyed. If it's not equal to the expected value, `VMA_ASSERT()` is executed. It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation, which indicates a serious bug. You can also explicitly request checking margins of all allocations in all memory blocks that belong to specified memory types by using function vmaCheckCorruption(), or in memory blocks that belong to specified custom pool, by using function vmaCheckPoolCorruption(). Margin validation (corruption detection) works only for memory types that are `HOST_VISIBLE` and `HOST_COHERENT`. \page record_and_replay Record and replay \section record_and_replay_introduction Introduction While using the library, sequence of calls to its functions together with their parameters can be recorded to a file and later replayed using standalone player application. It can be useful to: - Test correctness - check if same sequence of calls will not cause crash or failures on a target platform. - Gather statistics - see number of allocations, peak memory usage, number of calls etc. - Benchmark performance - see how much time it takes to replay the whole sequence. \section record_and_replay_usage Usage <b>To record sequence of calls to a file:</b> Fill in VmaAllocatorCreateInfo::pRecordSettings member while creating #VmaAllocator object. File is opened and written during whole lifetime of the allocator. <b>To replay file:</b> Use VmaReplay - standalone command-line program. Precompiled binary can be found in "bin" directory. Its source can be found in "src/VmaReplay" directory. Its project is generated by Premake. Command line syntax is printed when the program is launched without parameters. Basic usage: VmaReplay.exe MyRecording.csv <b>Documentation of file format</b> can be found in file: "docs/Recording file format.md". It's a human-readable, text file in CSV format (Comma Separated Values). \section record_and_replay_additional_considerations Additional considerations - Replaying file that was recorded on a different GPU (with different parameters like `bufferImageGranularity`, `nonCoherentAtomSize`, and especially different set of memory heaps and types) may give different performance and memory usage results, as well as issue some warnings and errors. - Current implementation of recording in VMA, as well as VmaReplay application, is coded and tested only on Windows. Inclusion of recording code is driven by `VMA_RECORDING_ENABLED` macro. Support for other platforms should be easy to add. Contributions are welcomed. - Currently calls to vmaDefragment() function are not recorded. \page usage_patterns Recommended usage patterns See also slides from talk: [Sawicki, Adam. Advanced Graphics Techniques Tutorial: Memory management in Vulkan and DX12. Game Developers Conference, 2018](https://www.gdcvault.com/play/1025458/Advanced-Graphics-Techniques-Tutorial-New) \section usage_patterns_simple Simple patterns \subsection usage_patterns_simple_render_targets Render targets <b>When:</b> Any resources that you frequently write and read on GPU, e.g. images used as color attachments (aka "render targets"), depth-stencil attachments, images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)"). <b>What to do:</b> Create them in video memory that is fastest to access from GPU using #VMA_MEMORY_USAGE_GPU_ONLY. Consider using [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension and/or manually creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, especially if they are large or if you plan to destroy and recreate them e.g. when display resolution changes. Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later. \subsection usage_patterns_simple_immutable_resources Immutable resources <b>When:</b> Any resources that you fill on CPU only once (aka "immutable") or infrequently and then read frequently on GPU, e.g. textures, vertex and index buffers, constant buffers that don't change often. <b>What to do:</b> Create them in video memory that is fastest to access from GPU using #VMA_MEMORY_USAGE_GPU_ONLY. To initialize content of such resource, create a CPU-side (aka "staging") copy of it in system memory - #VMA_MEMORY_USAGE_CPU_ONLY, map it, fill it, and submit a transfer from it to the GPU resource. You can keep the staging copy if you need it for another upload transfer in the future. If you don't, you can destroy it or reuse this buffer for uploading different resource after the transfer finishes. Prefer to create just buffers in system memory rather than images, even for uploading textures. Use `vkCmdCopyBufferToImage()`. Dont use images with `VK_IMAGE_TILING_LINEAR`. \subsection usage_patterns_dynamic_resources Dynamic resources <b>When:</b> Any resources that change frequently (aka "dynamic"), e.g. every frame or every draw call, written on CPU, read on GPU. <b>What to do:</b> Create them using #VMA_MEMORY_USAGE_CPU_TO_GPU. You can map it and write to it directly on CPU, as well as read from it on GPU. This is a more complex situation. Different solutions are possible, and the best one depends on specific GPU type, but you can use this simple approach for the start. Prefer to write to such resource sequentially (e.g. using `memcpy`). Don't perform random access or any reads from it on CPU, as it may be very slow. \subsection usage_patterns_readback Readback <b>When:</b> Resources that contain data written by GPU that you want to read back on CPU, e.g. results of some computations. <b>What to do:</b> Create them using #VMA_MEMORY_USAGE_GPU_TO_CPU. You can write to them directly on GPU, as well as map and read them on CPU. \section usage_patterns_advanced Advanced patterns \subsection usage_patterns_integrated_graphics Detecting integrated graphics You can support integrated graphics (like Intel HD Graphics, AMD APU) better by detecting it in Vulkan. To do it, call `vkGetPhysicalDeviceProperties()`, inspect `VkPhysicalDeviceProperties::deviceType` and look for `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`. When you find it, you can assume that memory is unified and all memory types are comparably fast to access from GPU, regardless of `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. You can then sum up sizes of all available memory heaps and treat them as useful for your GPU resources, instead of only `DEVICE_LOCAL` ones. You can also prefer to create your resources in memory types that are `HOST_VISIBLE` to map them directly instead of submitting explicit transfer (see below). \subsection usage_patterns_direct_vs_transfer Direct access versus transfer For resources that you frequently write on CPU and read on GPU, many solutions are possible: -# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY, second copy in system memory using #VMA_MEMORY_USAGE_CPU_ONLY and submit explicit tranfer each time. -# Create just single copy using #VMA_MEMORY_USAGE_CPU_TO_GPU, map it and fill it on CPU, read it directly on GPU. -# Create just single copy using #VMA_MEMORY_USAGE_CPU_ONLY, map it and fill it on CPU, read it directly on GPU. Which solution is the most efficient depends on your resource and especially on the GPU. It is best to measure it and then make the decision. Some general recommendations: - On integrated graphics use (2) or (3) to avoid unnecesary time and memory overhead related to using a second copy and making transfer. - For small resources (e.g. constant buffers) use (2). Discrete AMD cards have special 256 MiB pool of video memory that is directly mappable. Even if the resource ends up in system memory, its data may be cached on GPU after first fetch over PCIe bus. - For larger resources (e.g. textures), decide between (1) and (2). You may want to differentiate NVIDIA and AMD, e.g. by looking for memory type that is both `DEVICE_LOCAL` and `HOST_VISIBLE`. When you find it, use (2), otherwise use (1). Similarly, for resources that you frequently write on GPU and read on CPU, multiple solutions are possible: -# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY, second copy in system memory using #VMA_MEMORY_USAGE_GPU_TO_CPU and submit explicit tranfer each time. -# Create just single copy using #VMA_MEMORY_USAGE_GPU_TO_CPU, write to it directly on GPU, map it and read it on CPU. You should take some measurements to decide which option is faster in case of your specific resource. If you don't want to specialize your code for specific types of GPUs, you can still make an simple optimization for cases when your resource ends up in mappable memory to use it directly in this case instead of creating CPU-side staging copy. For details see [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable). \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, atomic etc. The library uses its own implementation of containers by default, but you can switch to using STL containers instead. \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 general_considerations General considerations \section general_considerations_thread_safety Thread safety - The library has no global state, so separate #VmaAllocator objects can be used independently. There should be no need to create multiple such objects though - one per `VkDevice` is enough. - 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. \section general_considerations_validation_layer_warnings Validation layer warnings When using this library, you can meet following types of warnings issued by Vulkan validation layer. They don't necessarily indicate a bug, so you may need to just ignore them. - *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.* - It happens when VK_KHR_dedicated_allocation extension is enabled. `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it. - *Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.* - It happens when you map a buffer or image, because the library maps entire `VkDeviceMemory` block, where different types of images and buffers may end up together, especially on GPUs with unified memory like Intel. - *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.* - It happens when you use lost allocations, and a new image or buffer is created in place of an existing object that bacame lost. \section general_considerations_allocation_algorithm Allocation algorithm 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, size/4, size/8. -# 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`. \section general_considerations_features_not_supported Features not supported Features deliberately excluded from the scope of this library: - Sparse resources. - Data transfer - issuing commands that transfer data between buffers or images, any usage of `VkCommandList` or `VkQueue` and related synchronization is responsibility of the user. - Allocations for imported/exported external memory. They tend to require explicit memory type index and dedicated allocation anyway, so they don't interact with main features of this library. Such special purpose allocations should be made manually, using `vkCreateBuffer()` and `vkAllocateMemory()`. - Support for any programming languages other than C/C++. Bindings to other languages are welcomed as external projects. */ /* Define this macro to 0/1 to disable/enable support for recording functionality, available through VmaAllocatorCreateInfo::pRecordSettings. */ #ifndef VMA_RECORDING_ENABLED #ifdef _WIN32 #define VMA_RECORDING_ENABLED 1 #else #define VMA_RECORDING_ENABLED 0 #endif #endif #define NOMINMAX // For Windows.h #include <vulkan/vulkan.h> #if VMA_RECORDING_ENABLED #include <Windows.h> #endif #if !defined(VMA_DEDICATED_ALLOCATION) #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation #define VMA_DEDICATED_ALLOCATION 1 #else #define VMA_DEDICATED_ALLOCATION 0 #endif #endif /** \struct VmaAllocator \brief Represents main object of this library initialized. Fill structure VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it. Call function vmaDestroyAllocator() to destroy it. It is recommended to create just one object of this type per `VkDevice` object, right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed. */ 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_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; PFN_vkBindBufferMemory vkBindBufferMemory; PFN_vkBindImageMemory vkBindImageMemory; PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; PFN_vkCreateBuffer vkCreateBuffer; PFN_vkDestroyBuffer vkDestroyBuffer; PFN_vkCreateImage vkCreateImage; PFN_vkDestroyImage vkDestroyImage; #if VMA_DEDICATED_ALLOCATION PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR; PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR; #endif } VmaVulkanFunctions; /// Flags to be used in VmaRecordSettings::flags. typedef enum VmaRecordFlagBits { /** \brief Enables flush after recording every function call. Enable it if you expect your application to crash, which may leave recording file truncated. It may degrade performance though. */ VMA_RECORD_FLUSH_AFTER_CALL_BIT = 0x00000001, VMA_RECORD_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } VmaRecordFlagBits; typedef VkFlags VmaRecordFlags; /// Parameters for recording calls to VMA functions. To be used in VmaAllocatorCreateInfo::pRecordSettings. typedef struct VmaRecordSettings { /// Flags for recording. Use #VmaRecordFlagBits enum. VmaRecordFlags flags; /** \brief Path to the file that should be written by the recording. Suggested extension: "csv". If the file already exists, it will be overwritten. It will be opened for the whole time #VmaAllocator object is alive. If opening this file fails, creation of the whole allocator object fails. */ const char* pFilePath; } VmaRecordSettings; /// 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. Optional. /** Set to 0 to use default, which is currently 256 MiB. */ VkDeviceSize preferredLargeHeapBlockSize; /// Custom CPU memory allocation callbacks. Optional. /** 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. /** 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; /** \brief Parameters for recording of VMA calls. Can be null. If not null, it enables recording of calls to VMA functions to a file. If support for recording is not enabled using `VMA_RECORDING_ENABLED` macro, creation of the allocator object fails with `VK_ERROR_FEATURE_NOT_PRESENT`. */ const VmaRecordSettings* pRecordSettings; } 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 /** \struct VmaPool \brief Represents custom memory pool Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it. Call function vmaDestroyPool() to destroy it. For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools). */ 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 on GPU. 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. Guarantees to be `HOST_VISIBLE` and `HOST_COHERENT`. CPU access is typically uncached. Writes may be write-combined. Resources created in this pool may still be accessible to the device, but access to them can be slow. 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 access is typically uncached. Writes may be write-combined. 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 or accessed randomly 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, /** Allocation will be created from upper stack in a double stack pool. This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag. */ VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040, 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; /** \brief Helps to find memoryTypeIndex, given memoryTypeBits and 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); /** \brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex. It internally creates a temporary, dummy buffer that never has memory bound. It is just a convenience function, equivalent to calling: - `vkCreateBuffer` - `vkGetBufferMemoryRequirements` - `vmaFindMemoryTypeIndex` - `vkDestroyBuffer` */ VkResult vmaFindMemoryTypeIndexForBufferInfo( VmaAllocator allocator, const VkBufferCreateInfo* pBufferCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, uint32_t* pMemoryTypeIndex); /** \brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex. It internally creates a temporary, dummy image that never has memory bound. It is just a convenience function, equivalent to calling: - `vkCreateImage` - `vkGetImageMemoryRequirements` - `vmaFindMemoryTypeIndex` - `vkDestroyImage` */ VkResult vmaFindMemoryTypeIndexForImageInfo( VmaAllocator allocator, const VkImageCreateInfo* pImageCreateInfo, 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 an 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, /** \brief Enables alternative, linear allocation algorithm in this pool. Specify this flag to enable linear allocation algorithm, which always creates new allocations after last one and doesn't reuse space from allocations freed in between. It trades memory consumption for simplified algorithm and data structure, which has better performance and uses less memory for metadata. By using this flag, you can achieve behavior of free-at-once, stack, ring buffer, and double stack. For details, see documentation chapter \ref linear_algorithm. When using this flag, you must specify VmaPoolCreateInfo::maxBlockCount == 1 (or 0 for default). */ VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004, 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. Specify nonzero to set explicit, constant size of memory blocks used by this pool. Leave 0 to use default and let the library manage block sizes automatically. Sizes of particular blocks may vary. */ 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 allow 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 default, which is `SIZE_MAX`, which means no limit. Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated throughout 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 available for new allocation. 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; /** \brief Number of `VkDeviceMemory` blocks allocated for this pool. */ size_t blockCount; } 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); /** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero, `VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection). Possible return values: - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool. - `VK_SUCCESS` - corruption detection has been performed and succeeded. - `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations. `VMA_ASSERT` is also fired in that case. - Other value: Error returned by Vulkan, e.g. memory mapping failure. */ VkResult vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool); /** \struct VmaAllocation \brief Represents single memory allocation. It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type plus unique offset. There are multiple ways to create such object. You need to fill structure VmaAllocationCreateInfo. For more information see [Choosing memory type](@ref choosing_memory_type). Although the library provides convenience functions that create Vulkan buffer or image, allocate memory for it and bind them together, binding of the allocation to a buffer or an image is out of scope of the allocation itself. Allocation object can exist without buffer/image bound, binding can be done manually by the user, and destruction of it can be done independently of destruction of the allocation. The object also remembers its size and some other information. To retrieve this information, use function vmaGetAllocationInfo() and inspect returned structure VmaAllocationInfo. Some kinds allocations can be in lost state. For more information, see [Lost allocations](@ref lost_allocations). */ 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); /** \brief Returns current information about specified allocation and atomically marks it as used in current frame. Current paramters of given allocation are returned in `pAllocationInfo`. This function also atomically "touches" allocation - marks it as used in current frame, just like vmaTouchAllocation(). If the allocation is in lost state, `pAllocationInfo->deviceMemory == VK_NULL_HANDLE`. Although this function uses atomics and doesn't lock any mutex, so it should be quite efficient, you can avoid calling it too often. - You can retrieve same VmaAllocationInfo structure while creating your resource, from function vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change (e.g. due to defragmentation or allocation becoming lost). - If you just want to check if allocation is not lost, vmaTouchAllocation() will work faster. */ void vmaGetAllocationInfo( VmaAllocator allocator, VmaAllocation allocation, VmaAllocationInfo* pAllocationInfo); /** \brief Returns `VK_TRUE` if allocation is not lost and atomically marks it as used in current frame. If the allocation has been created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag, this function returns `VK_TRUE` if it's not in lost state, so it can still be used. It then also atomically "touches" the allocation - marks it as used in current frame, so that you can be sure it won't become lost in current frame or next `frameInUseCount` frames. If the allocation is in lost state, the function returns `VK_FALSE`. Memory of such allocation, as well as buffer or image bound to it, should not be used. Lost allocation and the buffer/image still need to be destroyed. If the allocation has been created without #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag, this function always returns `VK_TRUE`. */ VkBool32 vmaTouchAllocation( VmaAllocator allocator, VmaAllocation allocation); /** \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 Flushes memory of given allocation. Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation. - `offset` must be relative to the beginning of allocation. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation. - `offset` and `size` don't have to be aligned. They are internally rounded down/up to multiply of `nonCoherentAtomSize`. - If `size` is 0, this call is ignored. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`, this call is ignored. */ void vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size); /** \brief Invalidates memory of given allocation. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation. - `offset` must be relative to the beginning of allocation. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation. - `offset` and `size` don't have to be aligned. They are internally rounded down/up to multiply of `nonCoherentAtomSize`. - If `size` is 0, this call is ignored. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`, this call is ignored. */ void vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size); /** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions. @param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero, `VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection). Possible return values: - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types. - `VK_SUCCESS` - corruption detection has been performed and succeeded. - `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations. `VMA_ASSERT` is also fired in that case. - Other value: Error returned by Vulkan, e.g. memory mapping failure. */ VkResult vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits); /** \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` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flags can be compacted. You may pass other allocations but it makes no sense - these will never be moved. - Custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag are not defragmented. Allocations passed to this function that come from such pools are ignored. - Allocations created with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT or created as dedicated allocations for any other reason are also ignored. - 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 Note: Please don't expect memory to be fully compacted after this call. Algorithms inside are based on some heuristics that try to maximize number of Vulkan memory blocks to make totally empty to release them, as well as to maximimze continuous empty space inside remaining blocks, while minimizing the number and size of data that needs to be moved. Some fragmentation still remains after this call. This is normal. Warning: This function is not 100% correct according to Vulkan specification. Use it at your own risk. That's because 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. Warning: This function may be time-consuming, so you shouldn't call it too often (like every frame or after every resource creation/destruction). You can call it on special occasions (like when reloading a game level or when you just destroyed a lot of objects). */ VkResult vmaDefragment( VmaAllocator allocator, VmaAllocation* pAllocations, size_t allocationCount, VkBool32* pAllocationsChanged, const VmaDefragmentationInfo *pDefragmentationInfo, VmaDefragmentationStats* pDefragmentationStats); /** \brief Binds buffer to allocation. Binds specified buffer to region of memory represented by specified allocation. Gets `VkDeviceMemory` handle and offset from the allocation. If you want to create a buffer, allocate memory for it and bind them together separately, you should use this function for binding instead of standard `vkBindBufferMemory()`, because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously (which is illegal in Vulkan). It is recommended to use function vmaCreateBuffer() instead of this one. */ VkResult vmaBindBufferMemory( VmaAllocator allocator, VmaAllocation allocation, VkBuffer buffer); /** \brief Binds image to allocation. Binds specified image to region of memory represented by specified allocation. Gets `VkDeviceMemory` handle and offset from the allocation. If you want to create an image, allocate memory for it and bind them together separately, you should use this function for binding instead of standard `vkBindImageMemory()`, because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously (which is illegal in Vulkan). It is recommended to use function vmaCreateImage() instead of this one. */ VkResult vmaBindImageMemory( VmaAllocator allocator, VmaAllocation allocation, VkImage image); /** @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. #if defined(__cplusplus) && defined(__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 #ifndef VMA_NULL // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0. #define VMA_NULL nullptr #endif #if defined(__APPLE__) || defined(__ANDROID__) #include <cstdlib> void *aligned_alloc(size_t alignment, size_t size) { // alignment must be >= sizeof(void*) if(alignment < sizeof(void*)) { alignment = sizeof(void*); } void *pointer; if(posix_memalign(&pointer, alignment, size) == 0) return pointer; return VMA_NULL; } #endif // If your compiler is not compatible with C++11 and definition of // aligned_alloc() function is missing, uncommeting following line may help: //#include <malloc.h> // 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_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 allocations, 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 before and after every allocation, in bytes. Set nonzero for debugging purposes only. */ #define VMA_DEBUG_MARGIN (0) #endif #ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS /** Define this macro to 1 to automatically fill new allocations and destroyed allocations with some bit pattern. */ #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0) #endif #ifndef VMA_DEBUG_DETECT_CORRUPTION /** Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to enable writing magic value to the margin before and after every allocation and validating it, so that memory corruptions (out-of-bounds writes) are detected. */ #define VMA_DEBUG_DETECT_CORRUPTION (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 #ifndef VMA_CLASS_NO_COPY #define VMA_CLASS_NO_COPY(className) \ private: \ className(const className&) = delete; \ className& operator=(const className&) = delete; #endif static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX; // Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F. static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666; static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC; static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF; /******************************************************************************* 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; } // Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8. // Use types like uint32_t, uint64_t as T. template <typename T> static inline T VmaAlignDown(T val, T align) { return val / 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; } static inline bool VmaStrIsEmpty(const char* pStr) { return pStr == VMA_NULL || *pStr == '\0'; } #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; } } static void VmaWriteMagicValue(void* pData, VkDeviceSize offset) { uint32_t* pDst = (uint32_t*)((char*)pData + offset); const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); for(size_t i = 0; i < numberCount; ++i, ++pDst) { *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE; } } static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset) { const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset); const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); for(size_t i = 0; i < numberCount; ++i, ++pSrc) { if(*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE) { return false; } } return true; } // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope). struct VmaMutexLock { VMA_CLASS_NO_COPY(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 CmpLess, typename IterT, typename KeyT> static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, CmpLess 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 IterT, typename KeyT> IterT VmaVectorFindSorted(const IterT& beg, const IterT& end, const KeyT& value) { CmpLess comparator; IterT it = VmaBinaryFindFirstNotLess<CmpLess, IterT, KeyT>( beg, end, value, comparator); if(it == end || (!comparator(*it, value) && !comparator(value, *it))) { return it; } return end; } //////////////////////////////////////////////////////////////////////////////// // 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 { VMA_CLASS_NO_COPY(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 { VMA_CLASS_NO_COPY(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; }; 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 { VMA_CLASS_NO_COPY(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; enum VMA_CACHE_OPERATION { VMA_CACHE_FLUSH, VMA_CACHE_INVALIDATE }; struct VmaAllocation_T { VMA_CLASS_NO_COPY(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) { #if VMA_STATS_STRING_ENABLED m_CreationFrameIndex = currentFrameIndex; m_BufferImageUsage = 0; #endif } ~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); #if VMA_STATS_STRING_ENABLED uint32_t GetCreationFrameIndex() const { return m_CreationFrameIndex; } uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; } void InitBufferImageUsage(uint32_t bufferImageUsage) { VMA_ASSERT(m_BufferImageUsage == 0); m_BufferImageUsage = bufferImageUsage; } void PrintParameters(class VmaJsonWriter& json) const; #endif 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; }; #if VMA_STATS_STRING_ENABLED uint32_t m_CreationFrameIndex; uint32_t m_BufferImageUsage; // 0 if unknown. #endif 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; }; // Comparator for offsets. struct VmaSuballocationOffsetLess { bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const { return lhs.offset < rhs.offset; } }; struct VmaSuballocationOffsetGreater { bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const { return lhs.offset > rhs.offset; } }; 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() : m_Size(0) { } virtual ~VmaBlockMetadata() { } virtual void Init(VkDeviceSize size) { m_Size = size; } // Validates all data structures inside this object. If not valid, returns false. virtual bool Validate() const = 0; VkDeviceSize GetSize() const { return m_Size; } virtual size_t GetAllocationCount() const = 0; virtual VkDeviceSize GetSumFreeSize() const = 0; virtual VkDeviceSize GetUnusedRangeSizeMax() const = 0; // Returns true if this block is empty - contains only single free suballocation. virtual bool IsEmpty() const = 0; virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const = 0; // Shouldn't modify blockCount. virtual void AddPoolStats(VmaPoolStats& inoutStats) const = 0; #if VMA_STATS_STRING_ENABLED virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0; #endif // Tries to find a place for suballocation with given parameters inside this block. // If succeeded, fills pAllocationRequest and returns true. // If failed, returns false. virtual bool CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, bool upperAddress, VmaSuballocationType allocType, bool canMakeOtherLost, VmaAllocationRequest* pAllocationRequest) = 0; virtual bool MakeRequestedAllocationsLost( uint32_t currentFrameIndex, uint32_t frameInUseCount, VmaAllocationRequest* pAllocationRequest) = 0; virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) = 0; virtual VkResult CheckCorruption(const void* pBlockData) = 0; // Makes actual allocation based on request. Request must already be checked and valid. virtual void Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, bool upperAddress, VmaAllocation hAllocation) = 0; // Frees suballocation assigned to given memory region. virtual void Free(const VmaAllocation allocation) = 0; virtual void FreeAtOffset(VkDeviceSize offset) = 0; protected: #if VMA_STATS_STRING_ENABLED void PrintDetailedMap_Begin(class VmaJsonWriter& json, VkDeviceSize unusedBytes, size_t allocationCount, size_t unusedRangeCount) const; void PrintDetailedMap_Allocation(class VmaJsonWriter& json, VkDeviceSize offset, VmaAllocation hAllocation) const; void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json, VkDeviceSize offset, VkDeviceSize size) const; void PrintDetailedMap_End(class VmaJsonWriter& json) const; #endif private: VkDeviceSize m_Size; }; class VmaBlockMetadata_Generic : public VmaBlockMetadata { VMA_CLASS_NO_COPY(VmaBlockMetadata_Generic) public: VmaBlockMetadata_Generic(VmaAllocator hAllocator); virtual ~VmaBlockMetadata_Generic(); virtual void Init(VkDeviceSize size); virtual bool Validate() const; virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; } virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; } virtual VkDeviceSize GetUnusedRangeSizeMax() const; virtual bool IsEmpty() const; virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const; virtual void AddPoolStats(VmaPoolStats& inoutStats) const; #if VMA_STATS_STRING_ENABLED virtual void PrintDetailedMap(class VmaJsonWriter& json) const; #endif virtual bool CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, bool upperAddress, VmaSuballocationType allocType, bool canMakeOtherLost, VmaAllocationRequest* pAllocationRequest); virtual bool MakeRequestedAllocationsLost( uint32_t currentFrameIndex, uint32_t frameInUseCount, VmaAllocationRequest* pAllocationRequest); virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); virtual VkResult CheckCorruption(const void* pBlockData); virtual void Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, bool upperAddress, VmaAllocation hAllocation); virtual void Free(const VmaAllocation allocation); virtual void FreeAtOffset(VkDeviceSize offset); private: 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); }; /* Allocations and their references in internal data structure look like this: if(m_2ndVectorMode == SECOND_VECTOR_EMPTY): 0 +-------+ | | | | | | +-------+ | Alloc | 1st[m_1stNullItemsBeginCount] +-------+ | Alloc | 1st[m_1stNullItemsBeginCount + 1] +-------+ | ... | +-------+ | Alloc | 1st[1st.size() - 1] +-------+ | | | | | | GetSize() +-------+ if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER): 0 +-------+ | Alloc | 2nd[0] +-------+ | Alloc | 2nd[1] +-------+ | ... | +-------+ | Alloc | 2nd[2nd.size() - 1] +-------+ | | | | | | +-------+ | Alloc | 1st[m_1stNullItemsBeginCount] +-------+ | Alloc | 1st[m_1stNullItemsBeginCount + 1] +-------+ | ... | +-------+ | Alloc | 1st[1st.size() - 1] +-------+ | | GetSize() +-------+ if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK): 0 +-------+ | | | | | | +-------+ | Alloc | 1st[m_1stNullItemsBeginCount] +-------+ | Alloc | 1st[m_1stNullItemsBeginCount + 1] +-------+ | ... | +-------+ | Alloc | 1st[1st.size() - 1] +-------+ | | | | | | +-------+ | Alloc | 2nd[2nd.size() - 1] +-------+ | ... | +-------+ | Alloc | 2nd[1] +-------+ | Alloc | 2nd[0] GetSize() +-------+ */ class VmaBlockMetadata_Linear : public VmaBlockMetadata { VMA_CLASS_NO_COPY(VmaBlockMetadata_Linear) public: VmaBlockMetadata_Linear(VmaAllocator hAllocator); virtual ~VmaBlockMetadata_Linear(); virtual void Init(VkDeviceSize size); virtual bool Validate() const; virtual size_t GetAllocationCount() const; virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; } virtual VkDeviceSize GetUnusedRangeSizeMax() const; virtual bool IsEmpty() const { return GetAllocationCount() == 0; } virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const; virtual void AddPoolStats(VmaPoolStats& inoutStats) const; #if VMA_STATS_STRING_ENABLED virtual void PrintDetailedMap(class VmaJsonWriter& json) const; #endif virtual bool CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, bool upperAddress, VmaSuballocationType allocType, bool canMakeOtherLost, VmaAllocationRequest* pAllocationRequest); virtual bool MakeRequestedAllocationsLost( uint32_t currentFrameIndex, uint32_t frameInUseCount, VmaAllocationRequest* pAllocationRequest); virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount); virtual VkResult CheckCorruption(const void* pBlockData); virtual void Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, bool upperAddress, VmaAllocation hAllocation); virtual void Free(const VmaAllocation allocation); virtual void FreeAtOffset(VkDeviceSize offset); private: /* There are two suballocation vectors, used in ping-pong way. The one with index m_1stVectorIndex is called 1st. The one with index (m_1stVectorIndex ^ 1) is called 2nd. 2nd can be non-empty only when 1st is not empty. When 2nd is not empty, m_2ndVectorMode indicates its mode of operation. */ typedef VmaVector< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > SuballocationVectorType; enum SECOND_VECTOR_MODE { SECOND_VECTOR_EMPTY, /* Suballocations in 2nd vector are created later than the ones in 1st, but they all have smaller offset. */ SECOND_VECTOR_RING_BUFFER, /* Suballocations in 2nd vector are upper side of double stack. They all have offsets higher than those in 1st vector. Top of this stack means smaller offsets, but higher indices in this vector. */ SECOND_VECTOR_DOUBLE_STACK, }; VkDeviceSize m_SumFreeSize; SuballocationVectorType m_Suballocations0, m_Suballocations1; uint32_t m_1stVectorIndex; SECOND_VECTOR_MODE m_2ndVectorMode; SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } // Number of items in 1st vector with hAllocation = null at the beginning. size_t m_1stNullItemsBeginCount; // Number of other items in 1st vector with hAllocation = null somewhere in the middle. size_t m_1stNullItemsMiddleCount; // Number of items in 2nd vector with hAllocation = null. size_t m_2ndNullItemsCount; bool ShouldCompact1st() const; void CleanupAfterFree(); }; /* 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 { VMA_CLASS_NO_COPY(VmaDeviceMemoryBlock) public: VmaBlockMetadata* m_pMetadata; VmaDeviceMemoryBlock(VmaAllocator hAllocator); ~VmaDeviceMemoryBlock() { VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped."); VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); } // Always call after construction. void Init( VmaAllocator hAllocator, uint32_t newMemoryTypeIndex, VkDeviceMemory newMemory, VkDeviceSize newSize, uint32_t id, bool linearAlgorithm); // Always call before destruction. void Destroy(VmaAllocator allocator); VkDeviceMemory GetDeviceMemory() const { return m_hMemory; } uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } uint32_t GetId() const { return m_Id; } void* GetMappedData() const { return m_pMappedData; } // Validates all data structures inside this object. If not valid, returns false. bool Validate() const; VkResult CheckCorruption(VmaAllocator hAllocator); // ppData can be null. VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData); void Unmap(VmaAllocator hAllocator, uint32_t count); VkResult WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); VkResult ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); VkResult BindBufferMemory( const VmaAllocator hAllocator, const VmaAllocation hAllocation, VkBuffer hBuffer); VkResult BindImageMemory( const VmaAllocator hAllocator, const VmaAllocation hAllocation, VkImage hImage); private: uint32_t m_MemoryTypeIndex; uint32_t m_Id; VkDeviceMemory m_hMemory; // Protects access to m_hMemory so it's not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory. // Also protects m_MapCount, m_pMappedData. VMA_MUTEX m_Mutex; uint32_t m_MapCount; void* m_pMappedData; }; 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 { VMA_CLASS_NO_COPY(VmaBlockVector) public: VmaBlockVector( VmaAllocator hAllocator, uint32_t memoryTypeIndex, VkDeviceSize preferredBlockSize, size_t minBlockCount, size_t maxBlockCount, VkDeviceSize bufferImageGranularity, uint32_t frameInUseCount, bool isCustomPool, bool explicitBlockSize, bool linearAlgorithm); ~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; } bool UsesLinearAlgorithm() const { return m_LinearAlgorithm; } void GetPoolStats(VmaPoolStats* pStats); bool IsEmpty() const { return m_Blocks.empty(); } bool IsCorruptionDetectionEnabled() const; VkResult Allocate( VmaPool hCurrentPool, uint32_t currentFrameIndex, VkDeviceSize size, VkDeviceSize alignment, 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); VkResult CheckCorruption(); 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; const bool m_ExplicitBlockSize; const bool m_LinearAlgorithm; bool m_HasEmptyBlock; 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. */ VmaDefragmentator* m_pDefragmentator; uint32_t m_NextBlockId; VkDeviceSize 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(); // To be used only without CAN_MAKE_OTHER_LOST flag. VkResult AllocateFromBlock( VmaDeviceMemoryBlock* pBlock, VmaPool hCurrentPool, uint32_t currentFrameIndex, VkDeviceSize size, VkDeviceSize alignment, VmaAllocationCreateFlags allocFlags, void* pUserData, VmaSuballocationType suballocType, VmaAllocation* pAllocation); VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex); }; struct VmaPool_T { VMA_CLASS_NO_COPY(VmaPool_T) public: VmaBlockVector m_BlockVector; VmaPool_T( VmaAllocator hAllocator, const VmaPoolCreateInfo& createInfo, VkDeviceSize preferredBlockSize); ~VmaPool_T(); uint32_t GetId() const { return m_Id; } void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; } #if VMA_STATS_STRING_ENABLED //void PrintDetailedMap(class VmaStringBuilder& sb); #endif private: uint32_t m_Id; }; class VmaDefragmentator { VMA_CLASS_NO_COPY(VmaDefragmentator) private: 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_pMetadata->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_pMetadata->GetSumFreeSize() < pRhsBlockInfo->m_pBlock->m_pMetadata->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); }; #if VMA_RECORDING_ENABLED class VmaRecorder { public: VmaRecorder(); VkResult Init(const VmaRecordSettings& settings, bool useMutex); void WriteConfiguration( const VkPhysicalDeviceProperties& devProps, const VkPhysicalDeviceMemoryProperties& memProps, bool dedicatedAllocationExtensionEnabled); ~VmaRecorder(); void RecordCreateAllocator(uint32_t frameIndex); void RecordDestroyAllocator(uint32_t frameIndex); void RecordCreatePool(uint32_t frameIndex, const VmaPoolCreateInfo& createInfo, VmaPool pool); void RecordDestroyPool(uint32_t frameIndex, VmaPool pool); void RecordAllocateMemory(uint32_t frameIndex, const VkMemoryRequirements& vkMemReq, const VmaAllocationCreateInfo& createInfo, VmaAllocation allocation); void RecordAllocateMemoryForBuffer(uint32_t frameIndex, const VkMemoryRequirements& vkMemReq, bool requiresDedicatedAllocation, bool prefersDedicatedAllocation, const VmaAllocationCreateInfo& createInfo, VmaAllocation allocation); void RecordAllocateMemoryForImage(uint32_t frameIndex, const VkMemoryRequirements& vkMemReq, bool requiresDedicatedAllocation, bool prefersDedicatedAllocation, const VmaAllocationCreateInfo& createInfo, VmaAllocation allocation); void RecordFreeMemory(uint32_t frameIndex, VmaAllocation allocation); void RecordSetAllocationUserData(uint32_t frameIndex, VmaAllocation allocation, const void* pUserData); void RecordCreateLostAllocation(uint32_t frameIndex, VmaAllocation allocation); void RecordMapMemory(uint32_t frameIndex, VmaAllocation allocation); void RecordUnmapMemory(uint32_t frameIndex, VmaAllocation allocation); void RecordFlushAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size); void RecordInvalidateAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size); void RecordCreateBuffer(uint32_t frameIndex, const VkBufferCreateInfo& bufCreateInfo, const VmaAllocationCreateInfo& allocCreateInfo, VmaAllocation allocation); void RecordCreateImage(uint32_t frameIndex, const VkImageCreateInfo& imageCreateInfo, const VmaAllocationCreateInfo& allocCreateInfo, VmaAllocation allocation); void RecordDestroyBuffer(uint32_t frameIndex, VmaAllocation allocation); void RecordDestroyImage(uint32_t frameIndex, VmaAllocation allocation); void RecordTouchAllocation(uint32_t frameIndex, VmaAllocation allocation); void RecordGetAllocationInfo(uint32_t frameIndex, VmaAllocation allocation); void RecordMakePoolAllocationsLost(uint32_t frameIndex, VmaPool pool); private: struct CallParams { uint32_t threadId; double time; }; class UserDataString { public: UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData); const char* GetString() const { return m_Str; } private: char m_PtrStr[17]; const char* m_Str; }; bool m_UseMutex; VmaRecordFlags m_Flags; FILE* m_File; VMA_MUTEX m_FileMutex; int64_t m_Freq; int64_t m_StartCounter; void GetBasicParams(CallParams& outParams); void Flush(); }; #endif // #if VMA_RECORDING_ENABLED // Main allocator object. struct VmaAllocator_T { VMA_CLASS_NO_COPY(VmaAllocator_T) public: 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); VkResult Init(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; } // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT. bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const { return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; } // Minimum alignment for all allocations in specific memory type. VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const { return IsMemoryTypeNonCoherent(memTypeIndex) ? VMA_MAX((VkDeviceSize)VMA_DEBUG_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) : (VkDeviceSize)VMA_DEBUG_ALIGNMENT; } bool IsIntegratedGpu() const { return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; } #if VMA_RECORDING_ENABLED VmaRecorder* GetRecorder() const { return m_pRecorder; } #endif 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); bool TouchAllocation(VmaAllocation hAllocation); VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool); void DestroyPool(VmaPool pool); void GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats); void SetCurrentFrameIndex(uint32_t frameIndex); uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); } void MakePoolAllocationsLost( VmaPool hPool, size_t* pLostAllocationCount); VkResult CheckPoolCorruption(VmaPool hPool); VkResult CheckCorruption(uint32_t memoryTypeBits); 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); VkResult BindBufferMemory(VmaAllocation hAllocation, VkBuffer hBuffer); VkResult BindImageMemory(VmaAllocation hAllocation, VkImage hImage); void FlushOrInvalidateAllocation( VmaAllocation hAllocation, VkDeviceSize offset, VkDeviceSize size, VMA_CACHE_OPERATION op); void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern); 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; uint32_t m_NextPoolId; VmaVulkanFunctions m_VulkanFunctions; #if VMA_RECORDING_ENABLED VmaRecorder* m_pRecorder; #endif void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions); VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex); VkResult AllocateMemoryOfType( VkDeviceSize size, VkDeviceSize alignment, 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 { VMA_CLASS_NO_COPY(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->GetDeviceMemory(); 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->GetMemoryTypeIndex(); 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->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; } } } } #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", }; void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const { json.WriteString("Type"); json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]); json.WriteString("Size"); json.WriteNumber(m_Size); if(m_pUserData != VMA_NULL) { json.WriteString("UserData"); if(IsUserDataString()) { json.WriteString((const char*)m_pUserData); } else { json.BeginString(); json.ContinueString_Pointer(m_pUserData); json.EndString(); } } json.WriteString("CreationFrameIndex"); json.WriteNumber(m_CreationFrameIndex); json.WriteString("LastUseFrameIndex"); json.WriteNumber(GetLastUseFrameIndex()); if(m_BufferImageUsage != 0) { json.WriteString("Usage"); json.WriteNumber(m_BufferImageUsage); } } #endif 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 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 #if VMA_STATS_STRING_ENABLED void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json, VkDeviceSize unusedBytes, size_t allocationCount, size_t unusedRangeCount) const { json.BeginObject(); json.WriteString("TotalBytes"); json.WriteNumber(GetSize()); json.WriteString("UnusedBytes"); json.WriteNumber(unusedBytes); json.WriteString("Allocations"); json.WriteNumber((uint64_t)allocationCount); json.WriteString("UnusedRanges"); json.WriteNumber((uint64_t)unusedRangeCount); json.WriteString("Suballocations"); json.BeginArray(); } void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json, VkDeviceSize offset, VmaAllocation hAllocation) const { json.BeginObject(true); json.WriteString("Offset"); json.WriteNumber(offset); hAllocation->PrintParameters(json); json.EndObject(); } void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json, VkDeviceSize offset, VkDeviceSize size) const { json.BeginObject(true); json.WriteString("Offset"); json.WriteNumber(offset); json.WriteString("Type"); json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]); json.WriteString("Size"); json.WriteNumber(size); json.EndObject(); } void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const { json.EndArray(); json.EndObject(); } #endif // #if VMA_STATS_STRING_ENABLED //////////////////////////////////////////////////////////////////////////////// // class VmaBlockMetadata_Generic VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(VmaAllocator hAllocator) : m_FreeCount(0), m_SumFreeSize(0), m_Suballocations(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())), m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(hAllocator->GetAllocationCallbacks())) { } VmaBlockMetadata_Generic::~VmaBlockMetadata_Generic() { } void VmaBlockMetadata_Generic::Init(VkDeviceSize size) { VmaBlockMetadata::Init(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_Generic::Validate() const { if(m_Suballocations.empty()) { return false; } // Expected offset of new suballocation as calculated 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 visited 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; } // Margin required between allocations - every free space must be at least that large. if(subAlloc.size < VMA_DEBUG_MARGIN) { return false; } } else { if(subAlloc.hAllocation->GetOffset() != subAlloc.offset) { return false; } if(subAlloc.hAllocation->GetSize() != subAlloc.size) { return false; } // Margin required between allocations - previous allocation must be free. if(VMA_DEBUG_MARGIN > 0 && !prevFree) { 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 != GetSize()) || (calculatedSumFreeSize != m_SumFreeSize) || (calculatedFreeCount != m_FreeCount)) { return false; } return true; } VkDeviceSize VmaBlockMetadata_Generic::GetUnusedRangeSizeMax() const { if(!m_FreeSuballocationsBySize.empty()) { return m_FreeSuballocationsBySize.back()->size; } else { return 0; } } bool VmaBlockMetadata_Generic::IsEmpty() const { return (m_Suballocations.size() == 1) && (m_FreeCount == 1); } void VmaBlockMetadata_Generic::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 = GetSize() - 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_Generic::AddPoolStats(VmaPoolStats& inoutStats) const { const uint32_t rangeCount = (uint32_t)m_Suballocations.size(); inoutStats.size += GetSize(); 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_Generic::PrintDetailedMap(class VmaJsonWriter& json) const { PrintDetailedMap_Begin(json, m_SumFreeSize, // unusedBytes m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount m_FreeCount); // unusedRangeCount size_t i = 0; for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin(); suballocItem != m_Suballocations.cend(); ++suballocItem, ++i) { if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE) { PrintDetailedMap_UnusedRange(json, suballocItem->offset, suballocItem->size); } else { PrintDetailedMap_Allocation(json, suballocItem->offset, suballocItem->hAllocation); } } PrintDetailedMap_End(json); } #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; bool VmaBlockMetadata_Generic::CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, bool upperAddress, VmaSuballocationType allocType, bool canMakeOtherLost, VmaAllocationRequest* pAllocationRequest) { VMA_ASSERT(allocSize > 0); VMA_ASSERT(!upperAddress); 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 + 2 * VMA_DEBUG_MARGIN) { 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 + 2 * VMA_DEBUG_MARGIN. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess( m_FreeSuballocationsBySize.data(), m_FreeSuballocationsBySize.data() + freeSuballocCount, allocSize + 2 * VMA_DEBUG_MARGIN, 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_Generic::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_Generic::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; } VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData) { for(VmaSuballocationList::iterator it = m_Suballocations.begin(); it != m_Suballocations.end(); ++it) { if(it->type != VMA_SUBALLOCATION_TYPE_FREE) { if(!VmaValidateMagicValue(pBlockData, it->offset - VMA_DEBUG_MARGIN)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!"); return VK_ERROR_VALIDATION_FAILED_EXT; } if(!VmaValidateMagicValue(pBlockData, it->offset + it->size)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); return VK_ERROR_VALIDATION_FAILED_EXT; } } } return VK_SUCCESS; } void VmaBlockMetadata_Generic::Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, bool upperAddress, VmaAllocation hAllocation) { VMA_ASSERT(!upperAddress); 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_Generic::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_Generic::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_Generic::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_Generic::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(GetSize() - 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) { *pOffset += VMA_DEBUG_MARGIN; } // Apply alignment. *pOffset = VmaAlignUp(*pOffset, allocAlignment); // 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. const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN; const VkDeviceSize totalSize = paddingBegin + allocSize + requiredEndMargin; // Another early return check. if(suballocItem->offset + totalSize > GetSize()) { 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) { *pOffset += VMA_DEBUG_MARGIN; } // Apply alignment. *pOffset = VmaAlignUp(*pOffset, allocAlignment); // 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. const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN; // 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_Generic::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_Generic::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_Generic::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_Generic::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 VmaBlockMetadata_Linear VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(VmaAllocator hAllocator) : m_SumFreeSize(0), m_Suballocations0(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())), m_Suballocations1(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())), m_1stVectorIndex(0), m_2ndVectorMode(SECOND_VECTOR_EMPTY), m_1stNullItemsBeginCount(0), m_1stNullItemsMiddleCount(0), m_2ndNullItemsCount(0) { } VmaBlockMetadata_Linear::~VmaBlockMetadata_Linear() { } void VmaBlockMetadata_Linear::Init(VkDeviceSize size) { VmaBlockMetadata::Init(size); m_SumFreeSize = size; } bool VmaBlockMetadata_Linear::Validate() const { const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); if(suballocations2nd.empty() != (m_2ndVectorMode == SECOND_VECTOR_EMPTY)) { return false; } if(suballocations1st.empty() && !suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { return false; } if(!suballocations1st.empty()) { // Null item at the beginning should be accounted into m_1stNullItemsBeginCount. if(suballocations1st[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE) { return false; } // Null item at the end should be just pop_back(). if(suballocations1st.back().hAllocation == VK_NULL_HANDLE) { return false; } } if(!suballocations2nd.empty()) { // Null item at the end should be just pop_back(). if(suballocations2nd.back().hAllocation == VK_NULL_HANDLE) { return false; } } if(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount > suballocations1st.size()) { return false; } if(m_2ndNullItemsCount > suballocations2nd.size()) { return false; } VkDeviceSize sumUsedSize = 0; const size_t suballoc1stCount = suballocations1st.size(); VkDeviceSize offset = VMA_DEBUG_MARGIN; if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const size_t suballoc2ndCount = suballocations2nd.size(); size_t nullItem2ndCount = 0; for(size_t i = 0; i < suballoc2ndCount; ++i) { const VmaSuballocation& suballoc = suballocations2nd[i]; const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); if(currFree != (suballoc.hAllocation == VK_NULL_HANDLE)) { return false; } if(suballoc.offset < offset) { return false; } if(!currFree) { if(suballoc.hAllocation->GetOffset() != suballoc.offset) { return false; } if(suballoc.hAllocation->GetSize() != suballoc.size) { return false; } sumUsedSize += suballoc.size; } else { ++nullItem2ndCount; } offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN; } if(nullItem2ndCount != m_2ndNullItemsCount) { return false; } } for(size_t i = 0; i < m_1stNullItemsBeginCount; ++i) { const VmaSuballocation& suballoc = suballocations1st[i]; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE || suballoc.hAllocation != VK_NULL_HANDLE) { return false; } } size_t nullItem1stCount = m_1stNullItemsBeginCount; for(size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i) { const VmaSuballocation& suballoc = suballocations1st[i]; const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); if(currFree != (suballoc.hAllocation == VK_NULL_HANDLE)) { return false; } if(suballoc.offset < offset) { return false; } if(i < m_1stNullItemsBeginCount && !currFree) { return false; } if(!currFree) { if(suballoc.hAllocation->GetOffset() != suballoc.offset) { return false; } if(suballoc.hAllocation->GetSize() != suballoc.size) { return false; } sumUsedSize += suballoc.size; } else { ++nullItem1stCount; } offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN; } if(nullItem1stCount != m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount) { return false; } if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { const size_t suballoc2ndCount = suballocations2nd.size(); size_t nullItem2ndCount = 0; for(size_t i = suballoc2ndCount; i--; ) { const VmaSuballocation& suballoc = suballocations2nd[i]; const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); if(currFree != (suballoc.hAllocation == VK_NULL_HANDLE)) { return false; } if(suballoc.offset < offset) { return false; } if(!currFree) { if(suballoc.hAllocation->GetOffset() != suballoc.offset) { return false; } if(suballoc.hAllocation->GetSize() != suballoc.size) { return false; } sumUsedSize += suballoc.size; } else { ++nullItem2ndCount; } offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN; } if(nullItem2ndCount != m_2ndNullItemsCount) { return false; } } if(offset > GetSize()) { return false; } if(m_SumFreeSize != GetSize() - sumUsedSize) { return false; } return true; } size_t VmaBlockMetadata_Linear::GetAllocationCount() const { return AccessSuballocations1st().size() - (m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount) + AccessSuballocations2nd().size() - m_2ndNullItemsCount; } VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const { const VkDeviceSize size = GetSize(); /* We don't consider gaps inside allocation vectors with freed allocations because they are not suitable for reuse in linear allocator. We consider only space that is available for new allocations. */ if(IsEmpty()) { return size; } const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); switch(m_2ndVectorMode) { case SECOND_VECTOR_EMPTY: /* Available space is after end of 1st, as well as before beginning of 1st (which whould make it a ring buffer). */ { const size_t suballocations1stCount = suballocations1st.size(); VMA_ASSERT(suballocations1stCount > m_1stNullItemsBeginCount); const VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount]; const VmaSuballocation& lastSuballoc = suballocations1st[suballocations1stCount - 1]; return VMA_MAX( firstSuballoc.offset, size - (lastSuballoc.offset + lastSuballoc.size)); } break; case SECOND_VECTOR_RING_BUFFER: /* Available space is only between end of 2nd and beginning of 1st. */ { const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); const VmaSuballocation& lastSuballoc2nd = suballocations2nd.back(); const VmaSuballocation& firstSuballoc1st = suballocations1st[m_1stNullItemsBeginCount]; return firstSuballoc1st.offset - (lastSuballoc2nd.offset + lastSuballoc2nd.size); } break; case SECOND_VECTOR_DOUBLE_STACK: /* Available space is only between end of 1st and top of 2nd. */ { const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); const VmaSuballocation& topSuballoc2nd = suballocations2nd.back(); const VmaSuballocation& lastSuballoc1st = suballocations1st.back(); return topSuballoc2nd.offset - (lastSuballoc1st.offset + lastSuballoc1st.size); } break; default: VMA_ASSERT(0); return 0; } } void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo& outInfo) const { const VkDeviceSize size = GetSize(); const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); const size_t suballoc1stCount = suballocations1st.size(); const size_t suballoc2ndCount = suballocations2nd.size(); outInfo.blockCount = 1; outInfo.allocationCount = (uint32_t)GetAllocationCount(); outInfo.unusedRangeCount = 0; outInfo.usedBytes = 0; outInfo.allocationSizeMin = UINT64_MAX; outInfo.allocationSizeMax = 0; outInfo.unusedRangeSizeMin = UINT64_MAX; outInfo.unusedRangeSizeMax = 0; VkDeviceSize lastOffset = 0; if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; size_t nextAlloc2ndIndex = 0; while(lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAllocIndex to the end. while(nextAlloc2ndIndex < suballoc2ndCount && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex < suballoc2ndCount) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; ++outInfo.unusedRangeCount; outInfo.unusedBytes += unusedRangeSize; outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize); outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. outInfo.usedBytes += suballoc.size; outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size); outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size); // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc2ndIndex; } // We are at the end. else { // There is free space from lastOffset to freeSpace2ndTo1stEnd. if(lastOffset < freeSpace2ndTo1stEnd) { const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; ++outInfo.unusedRangeCount; outInfo.unusedBytes += unusedRangeSize; outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize); outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize); } // End of loop. lastOffset = freeSpace2ndTo1stEnd; } } } size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; const VkDeviceSize freeSpace1stTo2ndEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; while(lastOffset < freeSpace1stTo2ndEnd) { // Find next non-null allocation or move nextAllocIndex to the end. while(nextAlloc1stIndex < suballoc1stCount && suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc1stIndex; } // Found non-null allocation. if(nextAlloc1stIndex < suballoc1stCount) { const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; ++outInfo.unusedRangeCount; outInfo.unusedBytes += unusedRangeSize; outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize); outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. outInfo.usedBytes += suballoc.size; outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size); outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size); // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc1stIndex; } // We are at the end. else { // There is free space from lastOffset to freeSpace1stTo2ndEnd. if(lastOffset < freeSpace1stTo2ndEnd) { const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; ++outInfo.unusedRangeCount; outInfo.unusedBytes += unusedRangeSize; outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize); outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize); } // End of loop. lastOffset = freeSpace1stTo2ndEnd; } } if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; while(lastOffset < size) { // Find next non-null allocation or move nextAllocIndex to the end. while(nextAlloc2ndIndex != SIZE_MAX && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { --nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex != SIZE_MAX) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; ++outInfo.unusedRangeCount; outInfo.unusedBytes += unusedRangeSize; outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize); outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. outInfo.usedBytes += suballoc.size; outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size); outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size); // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; --nextAlloc2ndIndex; } // We are at the end. else { // There is free space from lastOffset to size. if(lastOffset < size) { const VkDeviceSize unusedRangeSize = size - lastOffset; ++outInfo.unusedRangeCount; outInfo.unusedBytes += unusedRangeSize; outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize); outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize); } // End of loop. lastOffset = size; } } } outInfo.unusedBytes = size - outInfo.usedBytes; } void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats& inoutStats) const { const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); const VkDeviceSize size = GetSize(); const size_t suballoc1stCount = suballocations1st.size(); const size_t suballoc2ndCount = suballocations2nd.size(); inoutStats.size += size; VkDeviceSize lastOffset = 0; if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount; while(lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while(nextAlloc2ndIndex < suballoc2ndCount && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex < suballoc2ndCount) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; inoutStats.unusedSize += unusedRangeSize; ++inoutStats.unusedRangeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. ++inoutStats.allocationCount; // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc2ndIndex; } // We are at the end. else { if(lastOffset < freeSpace2ndTo1stEnd) { // There is free space from lastOffset to freeSpace2ndTo1stEnd. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; inoutStats.unusedSize += unusedRangeSize; ++inoutStats.unusedRangeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize); } // End of loop. lastOffset = freeSpace2ndTo1stEnd; } } } size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; const VkDeviceSize freeSpace1stTo2ndEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; while(lastOffset < freeSpace1stTo2ndEnd) { // Find next non-null allocation or move nextAllocIndex to the end. while(nextAlloc1stIndex < suballoc1stCount && suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc1stIndex; } // Found non-null allocation. if(nextAlloc1stIndex < suballoc1stCount) { const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; inoutStats.unusedSize += unusedRangeSize; ++inoutStats.unusedRangeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. ++inoutStats.allocationCount; // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc1stIndex; } // We are at the end. else { if(lastOffset < freeSpace1stTo2ndEnd) { // There is free space from lastOffset to freeSpace1stTo2ndEnd. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; inoutStats.unusedSize += unusedRangeSize; ++inoutStats.unusedRangeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize); } // End of loop. lastOffset = freeSpace1stTo2ndEnd; } } if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; while(lastOffset < size) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while(nextAlloc2ndIndex != SIZE_MAX && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { --nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex != SIZE_MAX) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; inoutStats.unusedSize += unusedRangeSize; ++inoutStats.unusedRangeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. ++inoutStats.allocationCount; // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; --nextAlloc2ndIndex; } // We are at the end. else { if(lastOffset < size) { // There is free space from lastOffset to size. const VkDeviceSize unusedRangeSize = size - lastOffset; inoutStats.unusedSize += unusedRangeSize; ++inoutStats.unusedRangeCount; inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize); } // End of loop. lastOffset = size; } } } } #if VMA_STATS_STRING_ENABLED void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const { const VkDeviceSize size = GetSize(); const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); const size_t suballoc1stCount = suballocations1st.size(); const size_t suballoc2ndCount = suballocations2nd.size(); // FIRST PASS size_t unusedRangeCount = 0; VkDeviceSize usedBytes = 0; VkDeviceSize lastOffset = 0; size_t alloc2ndCount = 0; if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; size_t nextAlloc2ndIndex = 0; while(lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while(nextAlloc2ndIndex < suballoc2ndCount && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex < suballoc2ndCount) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. ++unusedRangeCount; } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. ++alloc2ndCount; usedBytes += suballoc.size; // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc2ndIndex; } // We are at the end. else { if(lastOffset < freeSpace2ndTo1stEnd) { // There is free space from lastOffset to freeSpace2ndTo1stEnd. ++unusedRangeCount; } // End of loop. lastOffset = freeSpace2ndTo1stEnd; } } } size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; size_t alloc1stCount = 0; const VkDeviceSize freeSpace1stTo2ndEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; while(lastOffset < freeSpace1stTo2ndEnd) { // Find next non-null allocation or move nextAllocIndex to the end. while(nextAlloc1stIndex < suballoc1stCount && suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc1stIndex; } // Found non-null allocation. if(nextAlloc1stIndex < suballoc1stCount) { const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. ++unusedRangeCount; } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. ++alloc1stCount; usedBytes += suballoc.size; // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc1stIndex; } // We are at the end. else { if(lastOffset < size) { // There is free space from lastOffset to freeSpace1stTo2ndEnd. ++unusedRangeCount; } // End of loop. lastOffset = freeSpace1stTo2ndEnd; } } if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; while(lastOffset < size) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while(nextAlloc2ndIndex != SIZE_MAX && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { --nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex != SIZE_MAX) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. ++unusedRangeCount; } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. ++alloc2ndCount; usedBytes += suballoc.size; // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; --nextAlloc2ndIndex; } // We are at the end. else { if(lastOffset < size) { // There is free space from lastOffset to size. ++unusedRangeCount; } // End of loop. lastOffset = size; } } } const VkDeviceSize unusedBytes = size - usedBytes; PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount); // SECOND PASS lastOffset = 0; if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; size_t nextAlloc2ndIndex = 0; while(lastOffset < freeSpace2ndTo1stEnd) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while(nextAlloc2ndIndex < suballoc2ndCount && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex < suballoc2ndCount) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation); // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc2ndIndex; } // We are at the end. else { if(lastOffset < freeSpace2ndTo1stEnd) { // There is free space from lastOffset to freeSpace2ndTo1stEnd. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); } // End of loop. lastOffset = freeSpace2ndTo1stEnd; } } } nextAlloc1stIndex = m_1stNullItemsBeginCount; while(lastOffset < freeSpace1stTo2ndEnd) { // Find next non-null allocation or move nextAllocIndex to the end. while(nextAlloc1stIndex < suballoc1stCount && suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE) { ++nextAlloc1stIndex; } // Found non-null allocation. if(nextAlloc1stIndex < suballoc1stCount) { const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation); // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; ++nextAlloc1stIndex; } // We are at the end. else { if(lastOffset < freeSpace1stTo2ndEnd) { // There is free space from lastOffset to freeSpace1stTo2ndEnd. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); } // End of loop. lastOffset = freeSpace1stTo2ndEnd; } } if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; while(lastOffset < size) { // Find next non-null allocation or move nextAlloc2ndIndex to the end. while(nextAlloc2ndIndex != SIZE_MAX && suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE) { --nextAlloc2ndIndex; } // Found non-null allocation. if(nextAlloc2ndIndex != SIZE_MAX) { const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; // 1. Process free space before this allocation. if(lastOffset < suballoc.offset) { // There is free space from lastOffset to suballoc.offset. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); } // 2. Process this allocation. // There is allocation with suballoc.offset, suballoc.size. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation); // 3. Prepare for next iteration. lastOffset = suballoc.offset + suballoc.size; --nextAlloc2ndIndex; } // We are at the end. else { if(lastOffset < size) { // There is free space from lastOffset to size. const VkDeviceSize unusedRangeSize = size - lastOffset; PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); } // End of loop. lastOffset = size; } } } PrintDetailedMap_End(json); } #endif // #if VMA_STATS_STRING_ENABLED bool VmaBlockMetadata_Linear::CreateAllocationRequest( uint32_t currentFrameIndex, uint32_t frameInUseCount, VkDeviceSize bufferImageGranularity, VkDeviceSize allocSize, VkDeviceSize allocAlignment, bool upperAddress, 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()); const VkDeviceSize size = GetSize(); SuballocationVectorType& suballocations1st = AccessSuballocations1st(); SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); if(upperAddress) { if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer."); return false; } // Try to allocate before 2nd.back(), or end of block if 2nd.empty(). if(allocSize > size) { return false; } VkDeviceSize resultBaseOffset = size - allocSize; if(!suballocations2nd.empty()) { const VmaSuballocation& lastSuballoc = suballocations2nd.back(); resultBaseOffset = lastSuballoc.offset - allocSize; if(allocSize > lastSuballoc.offset) { return false; } } // Start from offset equal to end of free space. VkDeviceSize resultOffset = resultBaseOffset; // Apply VMA_DEBUG_MARGIN at the end. if(VMA_DEBUG_MARGIN > 0) { if(resultOffset < VMA_DEBUG_MARGIN) { return false; } resultOffset -= VMA_DEBUG_MARGIN; } // Apply alignment. resultOffset = VmaAlignDown(resultOffset, allocAlignment); // Check next suballocations from 2nd for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if(bufferImageGranularity > 1 && !suballocations2nd.empty()) { bool bufferImageGranularityConflict = false; for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; ) { const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex]; if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType)) { bufferImageGranularityConflict = true; break; } } else // Already on previous page. break; } if(bufferImageGranularityConflict) { resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity); } } // There is enough free space. const VkDeviceSize endOf1st = !suballocations1st.empty() ? suballocations1st.back().offset + suballocations1st.back().size : 0; if(endOf1st + VMA_DEBUG_MARGIN <= resultOffset) { // Check previous suballocations for BufferImageGranularity conflicts. // If conflict exists, allocation cannot be made here. if(bufferImageGranularity > 1) { for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; ) { const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex]; if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type)) { return false; } } else { // Already on next page. break; } } } // All tests passed: Success. pAllocationRequest->offset = resultOffset; pAllocationRequest->sumFreeSize = resultBaseOffset + allocSize - endOf1st; pAllocationRequest->sumItemSize = 0; // pAllocationRequest->item unused. pAllocationRequest->itemsToMakeLostCount = 0; return true; } } else // !upperAddress { if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { // Try to allocate at the end of 1st vector. VkDeviceSize resultBaseOffset = 0; if(!suballocations1st.empty()) { const VmaSuballocation& lastSuballoc = suballocations1st.back(); resultBaseOffset = lastSuballoc.offset + lastSuballoc.size; } // Start from offset equal to beginning of free space. VkDeviceSize resultOffset = resultBaseOffset; // Apply VMA_DEBUG_MARGIN at the beginning. if(VMA_DEBUG_MARGIN > 0) { resultOffset += VMA_DEBUG_MARGIN; } // Apply alignment. resultOffset = VmaAlignUp(resultOffset, allocAlignment); // Check previous suballocations for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if(bufferImageGranularity > 1 && !suballocations1st.empty()) { bool bufferImageGranularityConflict = false; for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; ) { const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex]; if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) { bufferImageGranularityConflict = true; break; } } else // Already on previous page. break; } if(bufferImageGranularityConflict) { resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity); } } const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; // There is enough free space at the end after alignment. if(resultOffset + allocSize + VMA_DEBUG_MARGIN <= freeSpaceEnd) { // Check next suballocations for BufferImageGranularity conflicts. // If conflict exists, allocation cannot be made here. if(bufferImageGranularity > 1 && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; ) { const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex]; if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) { return false; } } else { // Already on previous page. break; } } } // All tests passed: Success. pAllocationRequest->offset = resultOffset; pAllocationRequest->sumFreeSize = freeSpaceEnd - resultBaseOffset; pAllocationRequest->sumItemSize = 0; // pAllocationRequest->item unused. pAllocationRequest->itemsToMakeLostCount = 0; return true; } } // Wrap-around to end of 2nd vector. Try to allocate there, watching for the // beginning of 1st vector as the end of free space. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { VMA_ASSERT(!suballocations1st.empty()); VkDeviceSize resultBaseOffset = 0; if(!suballocations2nd.empty()) { const VmaSuballocation& lastSuballoc = suballocations2nd.back(); resultBaseOffset = lastSuballoc.offset + lastSuballoc.size; } // Start from offset equal to beginning of free space. VkDeviceSize resultOffset = resultBaseOffset; // Apply VMA_DEBUG_MARGIN at the beginning. if(VMA_DEBUG_MARGIN > 0) { resultOffset += VMA_DEBUG_MARGIN; } // Apply alignment. resultOffset = VmaAlignUp(resultOffset, allocAlignment); // Check previous suballocations for BufferImageGranularity conflicts. // Make bigger alignment if necessary. if(bufferImageGranularity > 1 && !suballocations2nd.empty()) { bool bufferImageGranularityConflict = false; for(size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; ) { const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex]; if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) { bufferImageGranularityConflict = true; break; } } else // Already on previous page. break; } if(bufferImageGranularityConflict) { resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity); } } pAllocationRequest->itemsToMakeLostCount = 0; pAllocationRequest->sumItemSize = 0; size_t index1st = m_1stNullItemsBeginCount; if(canMakeOtherLost) { while(index1st < suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN > suballocations1st[index1st].offset) { // Next colliding allocation at the beginning of 1st vector found. Try to make it lost. const VmaSuballocation& suballoc = suballocations1st[index1st]; if(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE) { // No problem. } else { VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE); if(suballoc.hAllocation->CanBecomeLost() && suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex) { ++pAllocationRequest->itemsToMakeLostCount; pAllocationRequest->sumItemSize += suballoc.size; } else { return false; } } ++index1st; } // Check next suballocations for BufferImageGranularity conflicts. // If conflict exists, we must mark more allocations lost or fail. if(bufferImageGranularity > 1) { while(index1st < suballocations1st.size()) { const VmaSuballocation& suballoc = suballocations1st[index1st]; if(VmaBlocksOnSamePage(resultOffset, allocSize, suballoc.offset, bufferImageGranularity)) { if(suballoc.hAllocation != VK_NULL_HANDLE) { // Not checking actual VmaIsBufferImageGranularityConflict(allocType, suballoc.type). if(suballoc.hAllocation->CanBecomeLost() && suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex) { ++pAllocationRequest->itemsToMakeLostCount; pAllocationRequest->sumItemSize += suballoc.size; } else { return false; } } } else { // Already on next page. break; } ++index1st; } } } // There is enough free space at the end after alignment. if((index1st == suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN < size) || (index1st < suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN <= suballocations1st[index1st].offset)) { // Check next suballocations for BufferImageGranularity conflicts. // If conflict exists, allocation cannot be made here. if(bufferImageGranularity > 1) { for(size_t nextSuballocIndex = index1st; nextSuballocIndex < suballocations1st.size(); nextSuballocIndex++) { const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex]; if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) { if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) { return false; } } else { // Already on next page. break; } } } // All tests passed: Success. pAllocationRequest->offset = resultOffset; pAllocationRequest->sumFreeSize = (index1st < suballocations1st.size() ? suballocations1st[index1st].offset : size) - resultBaseOffset - pAllocationRequest->sumItemSize; // pAllocationRequest->item unused. return true; } } } return false; } bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost( uint32_t currentFrameIndex, uint32_t frameInUseCount, VmaAllocationRequest* pAllocationRequest) { if(pAllocationRequest->itemsToMakeLostCount == 0) { return true; } VMA_ASSERT(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER); SuballocationVectorType& suballocations1st = AccessSuballocations1st(); size_t index1st = m_1stNullItemsBeginCount; size_t madeLostCount = 0; while(madeLostCount < pAllocationRequest->itemsToMakeLostCount) { VMA_ASSERT(index1st < suballocations1st.size()); VmaSuballocation& suballoc = suballocations1st[index1st]; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) { VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE); VMA_ASSERT(suballoc.hAllocation->CanBecomeLost()); if(suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; m_SumFreeSize += suballoc.size; ++m_1stNullItemsMiddleCount; ++madeLostCount; } else { return false; } } ++index1st; } CleanupAfterFree(); //VMA_HEAVY_ASSERT(Validate()); // Already called by ClanupAfterFree(). return true; } uint32_t VmaBlockMetadata_Linear::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) { uint32_t lostAllocationCount = 0; SuballocationVectorType& suballocations1st = AccessSuballocations1st(); for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i) { VmaSuballocation& suballoc = suballocations1st[i]; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE && suballoc.hAllocation->CanBecomeLost() && suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; ++m_1stNullItemsMiddleCount; m_SumFreeSize += suballoc.size; ++lostAllocationCount; } } SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i) { VmaSuballocation& suballoc = suballocations2nd[i]; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE && suballoc.hAllocation->CanBecomeLost() && suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount)) { suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; suballoc.hAllocation = VK_NULL_HANDLE; ++m_2ndNullItemsCount; ++lostAllocationCount; } } if(lostAllocationCount) { CleanupAfterFree(); } return lostAllocationCount; } VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData) { SuballocationVectorType& suballocations1st = AccessSuballocations1st(); for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i) { const VmaSuballocation& suballoc = suballocations1st[i]; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) { if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!"); return VK_ERROR_VALIDATION_FAILED_EXT; } if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); return VK_ERROR_VALIDATION_FAILED_EXT; } } } SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i) { const VmaSuballocation& suballoc = suballocations2nd[i]; if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) { if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!"); return VK_ERROR_VALIDATION_FAILED_EXT; } if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); return VK_ERROR_VALIDATION_FAILED_EXT; } } } return VK_SUCCESS; } void VmaBlockMetadata_Linear::Alloc( const VmaAllocationRequest& request, VmaSuballocationType type, VkDeviceSize allocSize, bool upperAddress, VmaAllocation hAllocation) { const VmaSuballocation newSuballoc = { request.offset, allocSize, hAllocation, type }; if(upperAddress) { VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER && "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer."); SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); suballocations2nd.push_back(newSuballoc); m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK; } else { SuballocationVectorType& suballocations1st = AccessSuballocations1st(); // First allocation. if(suballocations1st.empty()) { suballocations1st.push_back(newSuballoc); } else { // New allocation at the end of 1st vector. if(request.offset >= suballocations1st.back().offset + suballocations1st.back().size) { // Check if it fits before the end of the block. VMA_ASSERT(request.offset + allocSize <= GetSize()); suballocations1st.push_back(newSuballoc); } // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector. else if(request.offset + allocSize <= suballocations1st[m_1stNullItemsBeginCount].offset) { SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); switch(m_2ndVectorMode) { case SECOND_VECTOR_EMPTY: // First allocation from second part ring buffer. VMA_ASSERT(suballocations2nd.empty()); m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER; break; case SECOND_VECTOR_RING_BUFFER: // 2-part ring buffer is already started. VMA_ASSERT(!suballocations2nd.empty()); break; case SECOND_VECTOR_DOUBLE_STACK: VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack."); break; default: VMA_ASSERT(0); } suballocations2nd.push_back(newSuballoc); } else { VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR."); } } } m_SumFreeSize -= newSuballoc.size; } void VmaBlockMetadata_Linear::Free(const VmaAllocation allocation) { FreeAtOffset(allocation->GetOffset()); } void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset) { SuballocationVectorType& suballocations1st = AccessSuballocations1st(); SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); if(!suballocations1st.empty()) { // First allocation: Mark it as next empty at the beginning. VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount]; if(firstSuballoc.offset == offset) { firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; firstSuballoc.hAllocation = VK_NULL_HANDLE; m_SumFreeSize += firstSuballoc.size; ++m_1stNullItemsBeginCount; CleanupAfterFree(); return; } } // Last allocation in 2-part ring buffer or top of upper stack (same logic). if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) { VmaSuballocation& lastSuballoc = suballocations2nd.back(); if(lastSuballoc.offset == offset) { m_SumFreeSize += lastSuballoc.size; suballocations2nd.pop_back(); CleanupAfterFree(); return; } } // Last allocation in 1st vector. else if(m_2ndVectorMode == SECOND_VECTOR_EMPTY) { VmaSuballocation& lastSuballoc = suballocations1st.back(); if(lastSuballoc.offset == offset) { m_SumFreeSize += lastSuballoc.size; suballocations1st.pop_back(); CleanupAfterFree(); return; } } // Item from the middle of 1st vector. { VmaSuballocation refSuballoc; refSuballoc.offset = offset; // Rest of members stays uninitialized intentionally for better performance. SuballocationVectorType::iterator it = VmaVectorFindSorted<VmaSuballocationOffsetLess>( suballocations1st.begin() + m_1stNullItemsBeginCount, suballocations1st.end(), refSuballoc); if(it != suballocations1st.end()) { it->type = VMA_SUBALLOCATION_TYPE_FREE; it->hAllocation = VK_NULL_HANDLE; ++m_1stNullItemsMiddleCount; m_SumFreeSize += it->size; CleanupAfterFree(); return; } } if(m_2ndVectorMode != SECOND_VECTOR_EMPTY) { // Item from the middle of 2nd vector. VmaSuballocation refSuballoc; refSuballoc.offset = offset; // Rest of members stays uninitialized intentionally for better performance. SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ? VmaVectorFindSorted<VmaSuballocationOffsetLess>(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc) : VmaVectorFindSorted<VmaSuballocationOffsetGreater>(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc); if(it != suballocations2nd.end()) { it->type = VMA_SUBALLOCATION_TYPE_FREE; it->hAllocation = VK_NULL_HANDLE; ++m_2ndNullItemsCount; m_SumFreeSize += it->size; CleanupAfterFree(); return; } } VMA_ASSERT(0 && "Allocation to free not found in linear allocator!"); } bool VmaBlockMetadata_Linear::ShouldCompact1st() const { const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; const size_t suballocCount = AccessSuballocations1st().size(); return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3; } void VmaBlockMetadata_Linear::CleanupAfterFree() { SuballocationVectorType& suballocations1st = AccessSuballocations1st(); SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); if(IsEmpty()) { suballocations1st.clear(); suballocations2nd.clear(); m_1stNullItemsBeginCount = 0; m_1stNullItemsMiddleCount = 0; m_2ndNullItemsCount = 0; m_2ndVectorMode = SECOND_VECTOR_EMPTY; } else { const size_t suballoc1stCount = suballocations1st.size(); const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; VMA_ASSERT(nullItem1stCount <= suballoc1stCount); // Find more null items at the beginning of 1st vector. while(m_1stNullItemsBeginCount < suballoc1stCount && suballocations1st[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE) { ++m_1stNullItemsBeginCount; --m_1stNullItemsMiddleCount; } // Find more null items at the end of 1st vector. while(m_1stNullItemsMiddleCount > 0 && suballocations1st.back().hAllocation == VK_NULL_HANDLE) { --m_1stNullItemsMiddleCount; suballocations1st.pop_back(); } // Find more null items at the end of 2nd vector. while(m_2ndNullItemsCount > 0 && suballocations2nd.back().hAllocation == VK_NULL_HANDLE) { --m_2ndNullItemsCount; suballocations2nd.pop_back(); } if(ShouldCompact1st()) { const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount; size_t srcIndex = m_1stNullItemsBeginCount; for(size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex) { while(suballocations1st[srcIndex].hAllocation == VK_NULL_HANDLE) { ++srcIndex; } if(dstIndex != srcIndex) { suballocations1st[dstIndex] = suballocations1st[srcIndex]; } ++srcIndex; } suballocations1st.resize(nonNullItemCount); m_1stNullItemsBeginCount = 0; m_1stNullItemsMiddleCount = 0; } // 2nd vector became empty. if(suballocations2nd.empty()) { m_2ndVectorMode = SECOND_VECTOR_EMPTY; } // 1st vector became empty. if(suballocations1st.size() - m_1stNullItemsBeginCount == 0) { suballocations1st.clear(); m_1stNullItemsBeginCount = 0; if(!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) { // Swap 1st with 2nd. Now 2nd is empty. m_2ndVectorMode = SECOND_VECTOR_EMPTY; m_1stNullItemsMiddleCount = m_2ndNullItemsCount; while(m_1stNullItemsBeginCount < suballocations2nd.size() && suballocations2nd[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE) { ++m_1stNullItemsBeginCount; --m_1stNullItemsMiddleCount; } m_2ndNullItemsCount = 0; m_1stVectorIndex ^= 1; } } } VMA_HEAVY_ASSERT(Validate()); } //////////////////////////////////////////////////////////////////////////////// // class VmaDeviceMemoryBlock VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) : m_pMetadata(VMA_NULL), m_MemoryTypeIndex(UINT32_MAX), m_Id(0), m_hMemory(VK_NULL_HANDLE), m_MapCount(0), m_pMappedData(VMA_NULL) { } void VmaDeviceMemoryBlock::Init( VmaAllocator hAllocator, uint32_t newMemoryTypeIndex, VkDeviceMemory newMemory, VkDeviceSize newSize, uint32_t id, bool linearAlgorithm) { VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); m_MemoryTypeIndex = newMemoryTypeIndex; m_Id = id; m_hMemory = newMemory; if(linearAlgorithm) { m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator); } else { m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Generic)(hAllocator); } m_pMetadata->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_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!"); VMA_ASSERT(m_hMemory != VK_NULL_HANDLE); allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory); m_hMemory = VK_NULL_HANDLE; vma_delete(allocator, m_pMetadata); m_pMetadata = VMA_NULL; } bool VmaDeviceMemoryBlock::Validate() const { if((m_hMemory == VK_NULL_HANDLE) || (m_pMetadata->GetSize() == 0)) { return false; } return m_pMetadata->Validate(); } VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator) { void* pData = nullptr; VkResult res = Map(hAllocator, 1, &pData); if(res != VK_SUCCESS) { return res; } res = m_pMetadata->CheckCorruption(pData); Unmap(hAllocator, 1); return res; } VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, 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, m_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 VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, 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, m_hMemory); } } else { VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped."); } } VkResult VmaDeviceMemoryBlock::WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize) { VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN); void* pData; VkResult res = Map(hAllocator, 1, &pData); if(res != VK_SUCCESS) { return res; } VmaWriteMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN); VmaWriteMagicValue(pData, allocOffset + allocSize); Unmap(hAllocator, 1); return VK_SUCCESS; } VkResult VmaDeviceMemoryBlock::ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize) { VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN); void* pData; VkResult res = Map(hAllocator, 1, &pData); if(res != VK_SUCCESS) { return res; } if(!VmaValidateMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE FREED ALLOCATION!"); } else if(!VmaValidateMagicValue(pData, allocOffset + allocSize)) { VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!"); } Unmap(hAllocator, 1); return VK_SUCCESS; } VkResult VmaDeviceMemoryBlock::BindBufferMemory( const VmaAllocator hAllocator, const VmaAllocation hAllocation, VkBuffer hBuffer) { VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && hAllocation->GetBlock() == this); // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex); return hAllocator->GetVulkanFunctions().vkBindBufferMemory( hAllocator->m_hDevice, hBuffer, m_hMemory, hAllocation->GetOffset()); } VkResult VmaDeviceMemoryBlock::BindImageMemory( const VmaAllocator hAllocator, const VmaAllocation hAllocation, VkImage hImage) { VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && hAllocation->GetBlock() == this); // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex); return hAllocator->GetVulkanFunctions().vkBindImageMemory( hAllocator->m_hDevice, hImage, m_hMemory, hAllocation->GetOffset()); } 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, VkDeviceSize preferredBlockSize) : m_BlockVector( hAllocator, createInfo.memoryTypeIndex, createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize, createInfo.minBlockCount, createInfo.maxBlockCount, (createInfo.flags & VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(), createInfo.frameInUseCount, true, // isCustomPool createInfo.blockSize != 0, // explicitBlockSize (createInfo.flags & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) != 0), // linearAlgorithm m_Id(0) { } 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, bool explicitBlockSize, bool linearAlgorithm) : 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_ExplicitBlockSize(explicitBlockSize), m_LinearAlgorithm(linearAlgorithm), m_HasEmptyBlock(false), m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())), m_pDefragmentator(VMA_NULL), m_NextBlockId(0) { } 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) { VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); const size_t blockCount = m_Blocks.size(); pStats->size = 0; pStats->unusedSize = 0; pStats->allocationCount = 0; pStats->unusedRangeCount = 0; pStats->unusedRangeSizeMax = 0; pStats->blockCount = blockCount; for(uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) { const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; VMA_ASSERT(pBlock); VMA_HEAVY_ASSERT(pBlock->Validate()); pBlock->m_pMetadata->AddPoolStats(*pStats); } } bool VmaBlockVector::IsCorruptionDetectionEnabled() const { const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; return (VMA_DEBUG_DETECT_CORRUPTION != 0) && (VMA_DEBUG_MARGIN > 0) && (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags; } static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32; VkResult VmaBlockVector::Allocate( VmaPool hCurrentPool, uint32_t currentFrameIndex, VkDeviceSize size, VkDeviceSize alignment, const VmaAllocationCreateInfo& createInfo, VmaSuballocationType suballocType, VmaAllocation* pAllocation) { const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0; 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; const bool canCreateNewBlock = ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) && (m_Blocks.size() < m_MaxBlockCount); // If linearAlgorithm is used, canMakeOtherLost is available only when used as ring buffer. // Which in turn is available only when maxBlockCount = 1. if(m_LinearAlgorithm && m_MaxBlockCount > 1) { canMakeOtherLost = false; } // Upper address can only be used with linear allocator and within single memory block. if(isUpperAddress && (!m_LinearAlgorithm || m_MaxBlockCount > 1)) { return VK_ERROR_FEATURE_NOT_PRESENT; } // Early reject: requested allocation size is larger that maximum block size for this block vector. if(size + 2 * VMA_DEBUG_MARGIN > m_PreferredBlockSize) { return VK_ERROR_OUT_OF_DEVICE_MEMORY; } VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); /* Under certain condition, this whole section can be skipped for optimization, so we move on directly to trying to allocate with canMakeOtherLost. That's the case e.g. for custom pools with linear algorithm. */ if(!canMakeOtherLost || canCreateNewBlock) { // 1. Search existing allocations. Try to allocate without making other allocations lost. VmaAllocationCreateFlags allocFlagsCopy = createInfo.flags; allocFlagsCopy &= ~VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT; if(m_LinearAlgorithm) { // Use only last block. if(!m_Blocks.empty()) { VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back(); VMA_ASSERT(pCurrBlock); VkResult res = AllocateFromBlock( pCurrBlock, hCurrentPool, currentFrameIndex, size, alignment, allocFlagsCopy, createInfo.pUserData, suballocType, pAllocation); if(res == VK_SUCCESS) { VMA_DEBUG_LOG(" Returned from last block #%u", (uint32_t)(m_Blocks.size() - 1)); return VK_SUCCESS; } } } else { // 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); VkResult res = AllocateFromBlock( pCurrBlock, hCurrentPool, currentFrameIndex, size, alignment, allocFlagsCopy, createInfo.pUserData, suballocType, pAllocation); if(res == VK_SUCCESS) { VMA_DEBUG_LOG(" Returned from existing block #%u", (uint32_t)blockIndex); return VK_SUCCESS; } } } // 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; if(!m_ExplicitBlockSize) { // 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 >= 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_ExplicitBlockSize) { while(res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX) { const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; if(smallerNewBlockSize >= size) { newBlockSize = smallerNewBlockSize; ++newBlockSizeShift; res = CreateBlock(newBlockSize, &newBlockIndex); } else { break; } } } if(res == VK_SUCCESS) { VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex]; VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size); res = AllocateFromBlock( pBlock, hCurrentPool, currentFrameIndex, size, alignment, allocFlagsCopy, createInfo.pUserData, suballocType, pAllocation); if(res == VK_SUCCESS) { VMA_DEBUG_LOG(" Created new block Size=%llu", newBlockSize); return VK_SUCCESS; } else { // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment. return VK_ERROR_OUT_OF_DEVICE_MEMORY; } } } } // 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_pMetadata->CreateAllocationRequest( currentFrameIndex, m_FrameInUseCount, m_BufferImageGranularity, size, alignment, (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0, 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_pMetadata->MakeRequestedAllocationsLost( currentFrameIndex, m_FrameInUseCount, &bestRequest)) { // We no longer have an empty Allocation. if(pBestRequestBlock->m_pMetadata->IsEmpty()) { m_HasEmptyBlock = false; } // Allocate from this pBlock. *pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString); pBestRequestBlock->m_pMetadata->Alloc(bestRequest, suballocType, size, isUpperAddress, *pAllocation); (*pAllocation)->InitBlockAllocation( hCurrentPool, pBestRequestBlock, bestRequest.offset, alignment, 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); if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) { m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); } if(IsCorruptionDetectionEnabled()) { VkResult res = pBestRequestBlock->WriteMagicValueAroundAllocation(m_hAllocator, bestRequest.offset, size); VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value."); } 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(IsCorruptionDetectionEnabled()) { VkResult res = pBlock->ValidateMagicValueAroundAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize()); VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value."); } if(hAllocation->IsPersistentMap()) { pBlock->Unmap(m_hAllocator, 1); } pBlock->m_pMetadata->Free(hAllocation); VMA_HEAVY_ASSERT(pBlock->Validate()); VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", memTypeIndex); // pBlock became empty after this deallocation. if(pBlock->m_pMetadata->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 block. 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_pMetadata->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); } } VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const { VkDeviceSize result = 0; for(size_t i = m_Blocks.size(); i--; ) { result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->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() { if(!m_LinearAlgorithm) { // Bubble sort only until first swap. for(size_t i = 1; i < m_Blocks.size(); ++i) { if(m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize()) { VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]); return; } } } } VkResult VmaBlockVector::AllocateFromBlock( VmaDeviceMemoryBlock* pBlock, VmaPool hCurrentPool, uint32_t currentFrameIndex, VkDeviceSize size, VkDeviceSize alignment, VmaAllocationCreateFlags allocFlags, void* pUserData, VmaSuballocationType suballocType, VmaAllocation* pAllocation) { VMA_ASSERT((allocFlags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) == 0); const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0; VmaAllocationRequest currRequest = {}; if(pBlock->m_pMetadata->CreateAllocationRequest( currentFrameIndex, m_FrameInUseCount, m_BufferImageGranularity, size, alignment, isUpperAddress, suballocType, false, // canMakeOtherLost &currRequest)) { // Allocate from pCurrBlock. VMA_ASSERT(currRequest.itemsToMakeLostCount == 0); if(mapped) { VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL); if(res != VK_SUCCESS) { return res; } } // We no longer have an empty Allocation. if(pBlock->m_pMetadata->IsEmpty()) { m_HasEmptyBlock = false; } *pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString); pBlock->m_pMetadata->Alloc(currRequest, suballocType, size, isUpperAddress, *pAllocation); (*pAllocation)->InitBlockAllocation( hCurrentPool, pBlock, currRequest.offset, alignment, size, suballocType, mapped, (allocFlags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0); VMA_HEAVY_ASSERT(pBlock->Validate()); (*pAllocation)->SetUserData(m_hAllocator, pUserData); if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) { m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); } if(IsCorruptionDetectionEnabled()) { VkResult res = pBlock->WriteMagicValueAroundAllocation(m_hAllocator, currRequest.offset, size); VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value."); } return VK_SUCCESS; } return VK_ERROR_OUT_OF_DEVICE_MEMORY; } 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_hAllocator, m_MemoryTypeIndex, mem, allocInfo.allocationSize, m_NextBlockId++, m_LinearAlgorithm); 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); } if(m_LinearAlgorithm) { json.WriteString("LinearAlgorithm"); json.WriteBool(true); } } else { json.WriteString("PreferredBlockSize"); json.WriteNumber(m_PreferredBlockSize); } json.WriteString("Blocks"); json.BeginObject(); for(size_t i = 0; i < m_Blocks.size(); ++i) { json.BeginString(); json.ContinueString(m_Blocks[i]->GetId()); json.EndString(); m_Blocks[i]->m_pMetadata->PrintDetailedMap(json); } json.EndObject(); 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_pMetadata->IsEmpty()) { if(m_Blocks.size() > m_MinBlockCount) { if(pDefragmentationStats != VMA_NULL) { ++pDefragmentationStats->deviceMemoryBlocksFreed; pDefragmentationStats->bytesFreed += pBlock->m_pMetadata->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_pMetadata->MakeAllocationsLost(currentFrameIndex, m_FrameInUseCount); } if(pLostAllocationCount != VMA_NULL) { *pLostAllocationCount = lostAllocationCount; } } VkResult VmaBlockVector::CheckCorruption() { if(!IsCorruptionDetectionEnabled()) { return VK_ERROR_FEATURE_NOT_PRESENT; } VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex); for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) { VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; VMA_ASSERT(pBlock); VkResult res = pBlock->CheckCorruption(m_hAllocator); if(res != VK_SUCCESS) { return res; } } return VK_SUCCESS; } 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_pMetadata->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())) { VMA_ASSERT(!pBlockVector->UsesLinearAlgorithm()); } 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->GetMappedData()) { *ppMappedData = m_pBlock->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_pMetadata->CreateAllocationRequest( m_CurrentFrameIndex, m_pBlockVector->GetFrameInUseCount(), m_pBlockVector->GetBufferImageGranularity(), size, alignment, false, // upperAddress 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)); if(VMA_DEBUG_MARGIN > 0) { VmaWriteMagicValue(pDstMappedData, dstAllocRequest.offset - VMA_DEBUG_MARGIN); VmaWriteMagicValue(pDstMappedData, dstAllocRequest.offset + size); } pDstBlockInfo->m_pBlock->m_pMetadata->Alloc( dstAllocRequest, suballocType, size, false, // upperAddress allocInfo.m_hAllocation); pSrcBlockInfo->m_pBlock->m_pMetadata->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; } //////////////////////////////////////////////////////////////////////////////// // VmaRecorder #if VMA_RECORDING_ENABLED VmaRecorder::VmaRecorder() : m_UseMutex(true), m_Flags(0), m_File(VMA_NULL), m_Freq(INT64_MAX), m_StartCounter(INT64_MAX) { } VkResult VmaRecorder::Init(const VmaRecordSettings& settings, bool useMutex) { m_UseMutex = useMutex; m_Flags = settings.flags; QueryPerformanceFrequency((LARGE_INTEGER*)&m_Freq); QueryPerformanceCounter((LARGE_INTEGER*)&m_StartCounter); // Open file for writing. errno_t err = fopen_s(&m_File, settings.pFilePath, "wb"); if(err != 0) { return VK_ERROR_INITIALIZATION_FAILED; } // Write header. fprintf(m_File, "%s\n", "Vulkan Memory Allocator,Calls recording"); fprintf(m_File, "%s\n", "1,3"); return VK_SUCCESS; } VmaRecorder::~VmaRecorder() { if(m_File != VMA_NULL) { fclose(m_File); } } void VmaRecorder::RecordCreateAllocator(uint32_t frameIndex) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaCreateAllocator\n", callParams.threadId, callParams.time, frameIndex); Flush(); } void VmaRecorder::RecordDestroyAllocator(uint32_t frameIndex) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaDestroyAllocator\n", callParams.threadId, callParams.time, frameIndex); Flush(); } void VmaRecorder::RecordCreatePool(uint32_t frameIndex, const VmaPoolCreateInfo& createInfo, VmaPool pool) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaCreatePool,%u,%u,%llu,%llu,%llu,%u,%p\n", callParams.threadId, callParams.time, frameIndex, createInfo.memoryTypeIndex, createInfo.flags, createInfo.blockSize, createInfo.minBlockCount, createInfo.maxBlockCount, createInfo.frameInUseCount, pool); Flush(); } void VmaRecorder::RecordDestroyPool(uint32_t frameIndex, VmaPool pool) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaDestroyPool,%p\n", callParams.threadId, callParams.time, frameIndex, pool); Flush(); } void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex, const VkMemoryRequirements& vkMemReq, const VmaAllocationCreateInfo& createInfo, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemory,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, vkMemReq.alignment, vkMemReq.memoryTypeBits, createInfo.flags, createInfo.usage, createInfo.requiredFlags, createInfo.preferredFlags, createInfo.memoryTypeBits, createInfo.pool, allocation, userDataStr.GetString()); Flush(); } void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t frameIndex, const VkMemoryRequirements& vkMemReq, bool requiresDedicatedAllocation, bool prefersDedicatedAllocation, const VmaAllocationCreateInfo& createInfo, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForBuffer,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, vkMemReq.alignment, vkMemReq.memoryTypeBits, requiresDedicatedAllocation ? 1 : 0, prefersDedicatedAllocation ? 1 : 0, createInfo.flags, createInfo.usage, createInfo.requiredFlags, createInfo.preferredFlags, createInfo.memoryTypeBits, createInfo.pool, allocation, userDataStr.GetString()); Flush(); } void VmaRecorder::RecordAllocateMemoryForImage(uint32_t frameIndex, const VkMemoryRequirements& vkMemReq, bool requiresDedicatedAllocation, bool prefersDedicatedAllocation, const VmaAllocationCreateInfo& createInfo, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(createInfo.flags, createInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForImage,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, vkMemReq.size, vkMemReq.alignment, vkMemReq.memoryTypeBits, requiresDedicatedAllocation ? 1 : 0, prefersDedicatedAllocation ? 1 : 0, createInfo.flags, createInfo.usage, createInfo.requiredFlags, createInfo.preferredFlags, createInfo.memoryTypeBits, createInfo.pool, allocation, userDataStr.GetString()); Flush(); } void VmaRecorder::RecordFreeMemory(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaFreeMemory,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex, VmaAllocation allocation, const void* pUserData) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr( allocation->IsUserDataString() ? VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT : 0, pUserData); fprintf(m_File, "%u,%.3f,%u,vmaSetAllocationUserData,%p,%s\n", callParams.threadId, callParams.time, frameIndex, allocation, userDataStr.GetString()); Flush(); } void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaCreateLostAllocation,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordMapMemory(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaMapMemory,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaUnmapMemory,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaFlushAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex, allocation, offset, size); Flush(); } void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaInvalidateAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex, allocation, offset, size); Flush(); } void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex, const VkBufferCreateInfo& bufCreateInfo, const VmaAllocationCreateInfo& allocCreateInfo, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaCreateBuffer,%u,%llu,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, bufCreateInfo.flags, bufCreateInfo.size, bufCreateInfo.usage, bufCreateInfo.sharingMode, allocCreateInfo.flags, allocCreateInfo.usage, allocCreateInfo.requiredFlags, allocCreateInfo.preferredFlags, allocCreateInfo.memoryTypeBits, allocCreateInfo.pool, allocation, userDataStr.GetString()); Flush(); } void VmaRecorder::RecordCreateImage(uint32_t frameIndex, const VkImageCreateInfo& imageCreateInfo, const VmaAllocationCreateInfo& allocCreateInfo, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData); fprintf(m_File, "%u,%.3f,%u,vmaCreateImage,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex, imageCreateInfo.flags, imageCreateInfo.imageType, imageCreateInfo.format, imageCreateInfo.extent.width, imageCreateInfo.extent.height, imageCreateInfo.extent.depth, imageCreateInfo.mipLevels, imageCreateInfo.arrayLayers, imageCreateInfo.samples, imageCreateInfo.tiling, imageCreateInfo.usage, imageCreateInfo.sharingMode, imageCreateInfo.initialLayout, allocCreateInfo.flags, allocCreateInfo.usage, allocCreateInfo.requiredFlags, allocCreateInfo.preferredFlags, allocCreateInfo.memoryTypeBits, allocCreateInfo.pool, allocation, userDataStr.GetString()); Flush(); } void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaDestroyBuffer,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordDestroyImage(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaDestroyImage,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaTouchAllocation,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex, VmaAllocation allocation) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaGetAllocationInfo,%p\n", callParams.threadId, callParams.time, frameIndex, allocation); Flush(); } void VmaRecorder::RecordMakePoolAllocationsLost(uint32_t frameIndex, VmaPool pool) { CallParams callParams; GetBasicParams(callParams); VmaMutexLock lock(m_FileMutex, m_UseMutex); fprintf(m_File, "%u,%.3f,%u,vmaMakePoolAllocationsLost,%p\n", callParams.threadId, callParams.time, frameIndex, pool); Flush(); } VmaRecorder::UserDataString::UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData) { if(pUserData != VMA_NULL) { if((allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0) { m_Str = (const char*)pUserData; } else { sprintf_s(m_PtrStr, "%p", pUserData); m_Str = m_PtrStr; } } else { m_Str = ""; } } void VmaRecorder::WriteConfiguration( const VkPhysicalDeviceProperties& devProps, const VkPhysicalDeviceMemoryProperties& memProps, bool dedicatedAllocationExtensionEnabled) { fprintf(m_File, "Config,Begin\n"); fprintf(m_File, "PhysicalDevice,apiVersion,%u\n", devProps.apiVersion); fprintf(m_File, "PhysicalDevice,driverVersion,%u\n", devProps.driverVersion); fprintf(m_File, "PhysicalDevice,vendorID,%u\n", devProps.vendorID); fprintf(m_File, "PhysicalDevice,deviceID,%u\n", devProps.deviceID); fprintf(m_File, "PhysicalDevice,deviceType,%u\n", devProps.deviceType); fprintf(m_File, "PhysicalDevice,deviceName,%s\n", devProps.deviceName); fprintf(m_File, "PhysicalDeviceLimits,maxMemoryAllocationCount,%u\n", devProps.limits.maxMemoryAllocationCount); fprintf(m_File, "PhysicalDeviceLimits,bufferImageGranularity,%llu\n", devProps.limits.bufferImageGranularity); fprintf(m_File, "PhysicalDeviceLimits,nonCoherentAtomSize,%llu\n", devProps.limits.nonCoherentAtomSize); fprintf(m_File, "PhysicalDeviceMemory,HeapCount,%u\n", memProps.memoryHeapCount); for(uint32_t i = 0; i < memProps.memoryHeapCount; ++i) { fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,size,%llu\n", i, memProps.memoryHeaps[i].size); fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,flags,%u\n", i, memProps.memoryHeaps[i].flags); } fprintf(m_File, "PhysicalDeviceMemory,TypeCount,%u\n", memProps.memoryTypeCount); for(uint32_t i = 0; i < memProps.memoryTypeCount; ++i) { fprintf(m_File, "PhysicalDeviceMemory,Type,%u,heapIndex,%u\n", i, memProps.memoryTypes[i].heapIndex); fprintf(m_File, "PhysicalDeviceMemory,Type,%u,propertyFlags,%u\n", i, memProps.memoryTypes[i].propertyFlags); } fprintf(m_File, "Extension,VK_KHR_dedicated_allocation,%u\n", dedicatedAllocationExtensionEnabled ? 1 : 0); fprintf(m_File, "Macro,VMA_DEBUG_ALWAYS_DEDICATED_MEMORY,%u\n", VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ? 1 : 0); fprintf(m_File, "Macro,VMA_DEBUG_ALIGNMENT,%llu\n", (VkDeviceSize)VMA_DEBUG_ALIGNMENT); fprintf(m_File, "Macro,VMA_DEBUG_MARGIN,%llu\n", (VkDeviceSize)VMA_DEBUG_MARGIN); fprintf(m_File, "Macro,VMA_DEBUG_INITIALIZE_ALLOCATIONS,%u\n", VMA_DEBUG_INITIALIZE_ALLOCATIONS ? 1 : 0); fprintf(m_File, "Macro,VMA_DEBUG_DETECT_CORRUPTION,%u\n", VMA_DEBUG_DETECT_CORRUPTION ? 1 : 0); fprintf(m_File, "Macro,VMA_DEBUG_GLOBAL_MUTEX,%u\n", VMA_DEBUG_GLOBAL_MUTEX ? 1 : 0); fprintf(m_File, "Macro,VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY,%llu\n", (VkDeviceSize)VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY); fprintf(m_File, "Macro,VMA_SMALL_HEAP_MAX_SIZE,%llu\n", (VkDeviceSize)VMA_SMALL_HEAP_MAX_SIZE); fprintf(m_File, "Macro,VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE,%llu\n", (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE); fprintf(m_File, "Config,End\n"); } void VmaRecorder::GetBasicParams(CallParams& outParams) { outParams.threadId = GetCurrentThreadId(); LARGE_INTEGER counter; QueryPerformanceCounter(&counter); outParams.time = (double)(counter.QuadPart - m_StartCounter) / (double)m_Freq; } void VmaRecorder::Flush() { if((m_Flags & VMA_RECORD_FLUSH_AFTER_CALL_BIT) != 0) { fflush(m_File); } } #endif // #if VMA_RECORDING_ENABLED //////////////////////////////////////////////////////////////////////////////// // 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())), m_NextPoolId(0) #if VMA_RECORDING_ENABLED ,m_pRecorder(VMA_NULL) #endif { if(VMA_DEBUG_DETECT_CORRUPTION) { // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it. VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0); } VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device); #if !(VMA_DEDICATED_ALLOCATION) if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0) { VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros."); } #endif memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks)); memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties)); memset(&m_MemProps, 0, sizeof(m_MemProps)); 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 false, // explicitBlockSize false); // linearAlgorithm // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here, // becase minBlockCount is 0. m_pDedicatedAllocations[memTypeIndex] = vma_new(this, AllocationVectorType)(VmaStlAllocator<VmaAllocation>(GetAllocationCallbacks())); } } VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo) { VkResult res = VK_SUCCESS; if(pCreateInfo->pRecordSettings != VMA_NULL && !VmaStrIsEmpty(pCreateInfo->pRecordSettings->pFilePath)) { #if VMA_RECORDING_ENABLED m_pRecorder = vma_new(this, VmaRecorder)(); res = m_pRecorder->Init(*pCreateInfo->pRecordSettings, m_UseMutex); if(res != VK_SUCCESS) { return res; } m_pRecorder->WriteConfiguration( m_PhysicalDeviceProperties, m_MemProps, m_UseKhrDedicatedAllocation); m_pRecorder->RecordCreateAllocator(GetCurrentFrameIndex()); #else VMA_ASSERT(0 && "VmaAllocatorCreateInfo::pRecordSettings used, but not supported due to VMA_RECORDING_ENABLED not defined to 1."); return VK_ERROR_FEATURE_NOT_PRESENT; #endif } return res; } VmaAllocator_T::~VmaAllocator_T() { #if VMA_RECORDING_ENABLED if(m_pRecorder != VMA_NULL) { m_pRecorder->RecordDestroyAllocator(GetCurrentFrameIndex()); vma_delete(this, m_pRecorder); } #endif 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) { memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions)); #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.vkFlushMappedMemoryRanges = &vkFlushMappedMemoryRanges; m_VulkanFunctions.vkInvalidateMappedMemoryRanges = &vkInvalidateMappedMemoryRanges; 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 VMA_DEDICATED_ALLOCATION if(m_UseKhrDedicatedAllocation) { m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetBufferMemoryRequirements2KHR"); m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetImageMemoryRequirements2KHR"); } #endif // #if VMA_DEDICATED_ALLOCATION #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(vkFlushMappedMemoryRanges); VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges); 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); #if VMA_DEDICATED_ALLOCATION VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR); VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR); #endif } #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.vkFlushMappedMemoryRanges != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != 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 VMA_DEDICATED_ALLOCATION if(m_UseKhrDedicatedAllocation) { VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL); VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL); } #endif } 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( VkDeviceSize size, VkDeviceSize alignment, 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. 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( 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(), size, alignment, 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( 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; #if VMA_DEDICATED_ALLOCATION 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; } } #endif // #if VMA_DEDICATED_ALLOCATION // 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); if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) { FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); } // 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 VMA_DEDICATED_ALLOCATION 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 #endif // #if VMA_DEDICATED_ALLOCATION { (*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 VMA_DEDICATED_ALLOCATION 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 #endif // #if VMA_DEDICATED_ALLOCATION { (*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) { const VkDeviceSize alignmentForPool = VMA_MAX( vkMemReq.alignment, GetMemoryTypeMinAlignment(createInfo.pool->m_BlockVector.GetMemoryTypeIndex())); return createInfo.pool->m_BlockVector.Allocate( createInfo.pool, m_CurrentFrameIndex.load(), vkMemReq.size, alignmentForPool, 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) { VkDeviceSize alignmentForMemType = VMA_MAX( vkMemReq.alignment, GetMemoryTypeMinAlignment(memTypeIndex)); res = AllocateMemoryOfType( vkMemReq.size, alignmentForMemType, 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) { alignmentForMemType = VMA_MAX( vkMemReq.alignment, GetMemoryTypeMinAlignment(memTypeIndex)); res = AllocateMemoryOfType( vkMemReq.size, alignmentForMemType, 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(TouchAllocation(allocation)) { if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) { FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED); } 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]->m_BlockVector.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. const VkMemoryPropertyFlags requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; if((hAlloc->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK) && // Only HOST_VISIBLE and HOST_COHERENT memory types can be defragmented. ((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags) && // 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) { // Pools with linear algorithm are not defragmented. if(!hAllocPool->m_BlockVector.UsesLinearAlgorithm()) { pAllocBlockVector = &hAllocPool->m_BlockVector; } } // This allocation belongs to general pool. else { pAllocBlockVector = m_pBlockVectors[memTypeIndex]; } if(pAllocBlockVector != VMA_NULL) { 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]->m_BlockVector.Defragment( pDefragmentationStats, maxBytesToMove, maxAllocationsToMove); } // ======== Destroy defragmentators. // Process custom pools. for(size_t poolIndex = poolCount; poolIndex--; ) { m_Pools[poolIndex]->m_BlockVector.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 :) */ const 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 { #if VMA_STATS_STRING_ENABLED uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for(;;) { VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST); if(localLastUseFrameIndex == localCurrFrameIndex) { break; } else // Last use time earlier than current time. { if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex)) { localLastUseFrameIndex = localCurrFrameIndex; } } } #endif pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); pAllocationInfo->deviceMemory = hAllocation->GetMemory(); pAllocationInfo->offset = hAllocation->GetOffset(); pAllocationInfo->size = hAllocation->GetSize(); pAllocationInfo->pMappedData = hAllocation->GetMappedData(); pAllocationInfo->pUserData = hAllocation->GetUserData(); } } bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation) { // This is a stripped-down version of VmaAllocator_T::GetAllocationInfo. if(hAllocation->CanBecomeLost()) { uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for(;;) { if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST) { return false; } else if(localLastUseFrameIndex == localCurrFrameIndex) { return true; } else // Last use time earlier than current time. { if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex)) { localLastUseFrameIndex = localCurrFrameIndex; } } } } else { #if VMA_STATS_STRING_ENABLED uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load(); uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex(); for(;;) { VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST); if(localLastUseFrameIndex == localCurrFrameIndex) { break; } else // Last use time earlier than current time. { if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex)) { localLastUseFrameIndex = localCurrFrameIndex; } } } #endif return true; } } VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool) { VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags); const bool isLinearAlgorithm = (pCreateInfo->flags & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) != 0; VmaPoolCreateInfo newCreateInfo = *pCreateInfo; if(newCreateInfo.maxBlockCount == 0) { newCreateInfo.maxBlockCount = SIZE_MAX; } if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount) { return VK_ERROR_INITIALIZATION_FAILED; } const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex); *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize); 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); (*pPool)->SetId(m_NextPoolId++); 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); } VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool) { return hPool->m_BlockVector.CheckCorruption(); } VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits) { VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT; // Process default pools. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) { if(((1u << memTypeIndex) & memoryTypeBits) != 0) { VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex]; VMA_ASSERT(pBlockVector); VkResult localRes = pBlockVector->CheckCorruption(); switch(localRes) { case VK_ERROR_FEATURE_NOT_PRESENT: break; case VK_SUCCESS: finalRes = VK_SUCCESS; break; default: return localRes; } } } // Process custom pools. { VmaMutexLock lock(m_PoolsMutex, m_UseMutex); for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex) { if(((1u << m_Pools[poolIndex]->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0) { VkResult localRes = m_Pools[poolIndex]->m_BlockVector.CheckCorruption(); switch(localRes) { case VK_ERROR_FEATURE_NOT_PRESENT: break; case VK_SUCCESS: finalRes = VK_SUCCESS; break; default: return localRes; } } } } return finalRes; } 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); } } VkResult VmaAllocator_T::BindBufferMemory(VmaAllocation hAllocation, VkBuffer hBuffer) { VkResult res = VK_SUCCESS; switch(hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: res = GetVulkanFunctions().vkBindBufferMemory( m_hDevice, hBuffer, hAllocation->GetMemory(), 0); //memoryOffset break; case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block. Is the allocation lost?"); res = pBlock->BindBufferMemory(this, hAllocation, hBuffer); break; } default: VMA_ASSERT(0); } return res; } VkResult VmaAllocator_T::BindImageMemory(VmaAllocation hAllocation, VkImage hImage) { VkResult res = VK_SUCCESS; switch(hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: res = GetVulkanFunctions().vkBindImageMemory( m_hDevice, hImage, hAllocation->GetMemory(), 0); //memoryOffset break; case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block. Is the allocation lost?"); res = pBlock->BindImageMemory(this, hAllocation, hImage); break; } default: VMA_ASSERT(0); } return res; } void VmaAllocator_T::FlushOrInvalidateAllocation( VmaAllocation hAllocation, VkDeviceSize offset, VkDeviceSize size, VMA_CACHE_OPERATION op) { const uint32_t memTypeIndex = hAllocation->GetMemoryTypeIndex(); if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex)) { const VkDeviceSize allocationSize = hAllocation->GetSize(); VMA_ASSERT(offset <= allocationSize); const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize; VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE }; memRange.memory = hAllocation->GetMemory(); switch(hAllocation->GetType()) { case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: memRange.offset = VmaAlignDown(offset, nonCoherentAtomSize); if(size == VK_WHOLE_SIZE) { memRange.size = allocationSize - memRange.offset; } else { VMA_ASSERT(offset + size <= allocationSize); memRange.size = VMA_MIN( VmaAlignUp(size + (offset - memRange.offset), nonCoherentAtomSize), allocationSize - memRange.offset); } break; case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: { // 1. Still within this allocation. memRange.offset = VmaAlignDown(offset, nonCoherentAtomSize); if(size == VK_WHOLE_SIZE) { size = allocationSize - offset; } else { VMA_ASSERT(offset + size <= allocationSize); } memRange.size = VmaAlignUp(size + (offset - memRange.offset), nonCoherentAtomSize); // 2. Adjust to whole block. const VkDeviceSize allocationOffset = hAllocation->GetOffset(); VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0); const VkDeviceSize blockSize = hAllocation->GetBlock()->m_pMetadata->GetSize(); memRange.offset += allocationOffset; memRange.size = VMA_MIN(memRange.size, blockSize - memRange.offset); break; } default: VMA_ASSERT(0); } switch(op) { case VMA_CACHE_FLUSH: (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange); break; case VMA_CACHE_INVALIDATE: (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange); break; default: VMA_ASSERT(0); } } // else: Just ignore this call. } 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); } void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern) { if(VMA_DEBUG_INITIALIZE_ALLOCATIONS && !hAllocation->CanBecomeLost() && (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { void* pData = VMA_NULL; VkResult res = Map(hAllocation, &pData); if(res == VK_SUCCESS) { memset(pData, (int)pattern, (size_t)hAllocation->GetSize()); FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH); Unmap(hAllocation); } else { VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation."); } } } #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) { json.BeginObject(true); const VmaAllocation hAlloc = (*pDedicatedAllocVector)[i]; hAlloc->PrintParameters(json); 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(); } } // Custom pools { VmaMutexLock lock(m_PoolsMutex, m_UseMutex); const size_t poolCount = m_Pools.size(); if(poolCount > 0) { json.WriteString("Pools"); json.BeginObject(); for(size_t poolIndex = 0; poolIndex < poolCount; ++poolIndex) { json.BeginString(); json.ContinueString(m_Pools[poolIndex]->GetId()); json.EndString(); m_Pools[poolIndex]->m_BlockVector.PrintDetailedMap(json); } json.EndObject(); } } } #endif // #if VMA_STATS_STRING_ENABLED //////////////////////////////////////////////////////////////////////////////// // 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 (*pAllocator)->Init(pCreateInfo); } 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; const bool mapped = (pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; if(mapped) { preferredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; } // Convert usage to requiredFlags and preferredFlags. switch(pAllocationCreateInfo->usage) { case VMA_MEMORY_USAGE_UNKNOWN: break; case VMA_MEMORY_USAGE_GPU_ONLY: if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { 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; if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { 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 vmaFindMemoryTypeIndexForBufferInfo( VmaAllocator allocator, const VkBufferCreateInfo* pBufferCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, uint32_t* pMemoryTypeIndex) { VMA_ASSERT(allocator != VK_NULL_HANDLE); VMA_ASSERT(pBufferCreateInfo != VMA_NULL); VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); const VkDevice hDev = allocator->m_hDevice; VkBuffer hBuffer = VK_NULL_HANDLE; VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer( hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer); if(res == VK_SUCCESS) { VkMemoryRequirements memReq = {}; allocator->GetVulkanFunctions().vkGetBufferMemoryRequirements( hDev, hBuffer, &memReq); res = vmaFindMemoryTypeIndex( allocator, memReq.memoryTypeBits, pAllocationCreateInfo, pMemoryTypeIndex); allocator->GetVulkanFunctions().vkDestroyBuffer( hDev, hBuffer, allocator->GetAllocationCallbacks()); } return res; } VkResult vmaFindMemoryTypeIndexForImageInfo( VmaAllocator allocator, const VkImageCreateInfo* pImageCreateInfo, const VmaAllocationCreateInfo* pAllocationCreateInfo, uint32_t* pMemoryTypeIndex) { VMA_ASSERT(allocator != VK_NULL_HANDLE); VMA_ASSERT(pImageCreateInfo != VMA_NULL); VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); const VkDevice hDev = allocator->m_hDevice; VkImage hImage = VK_NULL_HANDLE; VkResult res = allocator->GetVulkanFunctions().vkCreateImage( hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage); if(res == VK_SUCCESS) { VkMemoryRequirements memReq = {}; allocator->GetVulkanFunctions().vkGetImageMemoryRequirements( hDev, hImage, &memReq); res = vmaFindMemoryTypeIndex( allocator, memReq.memoryTypeBits, pAllocationCreateInfo, pMemoryTypeIndex); allocator->GetVulkanFunctions().vkDestroyImage( hDev, hImage, allocator->GetAllocationCallbacks()); } return res; } VkResult vmaCreatePool( VmaAllocator allocator, const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool) { VMA_ASSERT(allocator && pCreateInfo && pPool); VMA_DEBUG_LOG("vmaCreatePool"); VMA_DEBUG_GLOBAL_MUTEX_LOCK VkResult res = allocator->CreatePool(pCreateInfo, pPool); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordCreatePool(allocator->GetCurrentFrameIndex(), *pCreateInfo, *pPool); } #endif return res; } void vmaDestroyPool( VmaAllocator allocator, VmaPool pool) { VMA_ASSERT(allocator); if(pool == VK_NULL_HANDLE) { return; } VMA_DEBUG_LOG("vmaDestroyPool"); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordDestroyPool(allocator->GetCurrentFrameIndex(), pool); } #endif 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 #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordMakePoolAllocationsLost(allocator->GetCurrentFrameIndex(), pool); } #endif allocator->MakePoolAllocationsLost(pool, pLostAllocationCount); } VkResult vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool) { VMA_ASSERT(allocator && pool); VMA_DEBUG_GLOBAL_MUTEX_LOCK VMA_DEBUG_LOG("vmaCheckPoolCorruption"); return allocator->CheckPoolCorruption(pool); } 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 VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordAllocateMemory( allocator->GetCurrentFrameIndex(), *pVkMemoryRequirements, *pCreateInfo, *pAllocation); } #endif if(pAllocationInfo != VMA_NULL && 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 VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordAllocateMemoryForBuffer( allocator->GetCurrentFrameIndex(), vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, *pCreateInfo, *pAllocation); } #endif 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 VkMemoryRequirements vkMemReq = {}; bool requiresDedicatedAllocation = false; bool prefersDedicatedAllocation = false; allocator->GetImageMemoryRequirements(image, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); VkResult result = allocator->AllocateMemory( vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, VK_NULL_HANDLE, // dedicatedBuffer image, // dedicatedImage *pCreateInfo, VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN, pAllocation); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordAllocateMemoryForImage( allocator->GetCurrentFrameIndex(), vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, *pCreateInfo, *pAllocation); } #endif if(pAllocationInfo && result == VK_SUCCESS) { allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); } return result; } void vmaFreeMemory( VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator); if(allocation == VK_NULL_HANDLE) { return; } VMA_DEBUG_LOG("vmaFreeMemory"); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordFreeMemory( allocator->GetCurrentFrameIndex(), allocation); } #endif allocator->FreeMemory(allocation); } void vmaGetAllocationInfo( VmaAllocator allocator, VmaAllocation allocation, VmaAllocationInfo* pAllocationInfo) { VMA_ASSERT(allocator && allocation && pAllocationInfo); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordGetAllocationInfo( allocator->GetCurrentFrameIndex(), allocation); } #endif allocator->GetAllocationInfo(allocation, pAllocationInfo); } VkBool32 vmaTouchAllocation( VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordTouchAllocation( allocator->GetCurrentFrameIndex(), allocation); } #endif return allocator->TouchAllocation(allocation); } void vmaSetAllocationUserData( VmaAllocator allocator, VmaAllocation allocation, void* pUserData) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocation->SetUserData(allocator, pUserData); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordSetAllocationUserData( allocator->GetCurrentFrameIndex(), allocation, pUserData); } #endif } void vmaCreateLostAllocation( VmaAllocator allocator, VmaAllocation* pAllocation) { VMA_ASSERT(allocator && pAllocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK; allocator->CreateLostAllocation(pAllocation); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordCreateLostAllocation( allocator->GetCurrentFrameIndex(), *pAllocation); } #endif } VkResult vmaMapMemory( VmaAllocator allocator, VmaAllocation allocation, void** ppData) { VMA_ASSERT(allocator && allocation && ppData); VMA_DEBUG_GLOBAL_MUTEX_LOCK VkResult res = allocator->Map(allocation, ppData); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordMapMemory( allocator->GetCurrentFrameIndex(), allocation); } #endif return res; } void vmaUnmapMemory( VmaAllocator allocator, VmaAllocation allocation) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordUnmapMemory( allocator->GetCurrentFrameIndex(), allocation); } #endif allocator->Unmap(allocation); } void vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_LOG("vmaFlushAllocation"); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordFlushAllocation( allocator->GetCurrentFrameIndex(), allocation, offset, size); } #endif } void vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size) { VMA_ASSERT(allocator && allocation); VMA_DEBUG_LOG("vmaInvalidateAllocation"); VMA_DEBUG_GLOBAL_MUTEX_LOCK allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordInvalidateAllocation( allocator->GetCurrentFrameIndex(), allocation, offset, size); } #endif } VkResult vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits) { VMA_ASSERT(allocator); VMA_DEBUG_LOG("vmaCheckCorruption"); VMA_DEBUG_GLOBAL_MUTEX_LOCK return allocator->CheckCorruption(memoryTypeBits); } 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 vmaBindBufferMemory( VmaAllocator allocator, VmaAllocation allocation, VkBuffer buffer) { VMA_ASSERT(allocator && allocation && buffer); VMA_DEBUG_LOG("vmaBindBufferMemory"); VMA_DEBUG_GLOBAL_MUTEX_LOCK return allocator->BindBufferMemory(allocation, buffer); } VkResult vmaBindImageMemory( VmaAllocator allocator, VmaAllocation allocation, VkImage image) { VMA_ASSERT(allocator && allocation && image); VMA_DEBUG_LOG("vmaBindImageMemory"); VMA_DEBUG_GLOBAL_MUTEX_LOCK return allocator->BindImageMemory(allocation, image); } 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 VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordCreateBuffer( allocator->GetCurrentFrameIndex(), *pBufferCreateInfo, *pAllocationCreateInfo, *pAllocation); } #endif if(res >= 0) { // 3. Bind buffer with memory. res = allocator->BindBufferMemory(*pAllocation, *pBuffer); if(res >= 0) { // All steps succeeded. #if VMA_STATS_STRING_ENABLED (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage); #endif 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) { VMA_ASSERT(allocator); if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE) { return; } VMA_DEBUG_LOG("vmaDestroyBuffer"); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordDestroyBuffer( allocator->GetCurrentFrameIndex(), allocation); } #endif if(buffer != VK_NULL_HANDLE) { (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks()); } if(allocation != VK_NULL_HANDLE) { 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. VkMemoryRequirements vkMemReq = {}; bool requiresDedicatedAllocation = false; bool prefersDedicatedAllocation = false; allocator->GetImageMemoryRequirements(*pImage, vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation); res = allocator->AllocateMemory( vkMemReq, requiresDedicatedAllocation, prefersDedicatedAllocation, VK_NULL_HANDLE, // dedicatedBuffer *pImage, // dedicatedImage *pAllocationCreateInfo, suballocType, pAllocation); #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordCreateImage( allocator->GetCurrentFrameIndex(), *pImageCreateInfo, *pAllocationCreateInfo, *pAllocation); } #endif if(res >= 0) { // 3. Bind image with memory. res = allocator->BindImageMemory(*pAllocation, *pImage); if(res >= 0) { // All steps succeeded. #if VMA_STATS_STRING_ENABLED (*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage); #endif 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) { VMA_ASSERT(allocator); if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE) { return; } VMA_DEBUG_LOG("vmaDestroyImage"); VMA_DEBUG_GLOBAL_MUTEX_LOCK #if VMA_RECORDING_ENABLED if(allocator->GetRecorder() != VMA_NULL) { allocator->GetRecorder()->RecordDestroyImage( allocator->GetCurrentFrameIndex(), allocation); } #endif if(image != VK_NULL_HANDLE) { (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks()); } if(allocation != VK_NULL_HANDLE) { allocator->FreeMemory(allocation); } } #endif // #ifdef VMA_IMPLEMENTATION
34.506791
214
0.673406
9af34a7e6e13e1ba17e660a3b1f0fb767b484b89
3,589
h
C
release/src-rt-6.x.4708/linux/linux-2.6.36/fs/nilfs2/alloc.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
10
2015-02-28T21:05:37.000Z
2021-09-16T04:57:27.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/fs/nilfs2/alloc.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
1
2018-08-21T03:43:09.000Z
2018-08-21T03:43:09.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/fs/nilfs2/alloc.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
5
2017-10-11T08:09:11.000Z
2020-10-14T04:10:13.000Z
/* * alloc.h - persistent object (dat entry/disk inode) allocator/deallocator * * Copyright (C) 2006-2008 Nippon Telegraph and Telephone Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Original code was written by Koji Sato <koji@osrg.net>. * Two allocators were unified by Ryusuke Konishi <ryusuke@osrg.net>, * Amagai Yoshiji <amagai@osrg.net>. */ #ifndef _NILFS_ALLOC_H #define _NILFS_ALLOC_H #include <linux/types.h> #include <linux/buffer_head.h> #include <linux/fs.h> /** * nilfs_palloc_entries_per_group - get the number of entries per group * @inode: inode of metadata file using this allocator * * The number of entries per group is defined by the number of bits * that a bitmap block can maintain. */ static inline unsigned long nilfs_palloc_entries_per_group(const struct inode *inode) { return 1UL << (inode->i_blkbits + 3 /* log2(8 = CHAR_BITS) */); } int nilfs_palloc_init_blockgroup(struct inode *, unsigned); int nilfs_palloc_get_entry_block(struct inode *, __u64, int, struct buffer_head **); void *nilfs_palloc_block_get_entry(const struct inode *, __u64, const struct buffer_head *, void *); /** * nilfs_palloc_req - persistent allocator request and reply * @pr_entry_nr: entry number (vblocknr or inode number) * @pr_desc_bh: buffer head of the buffer containing block group descriptors * @pr_bitmap_bh: buffer head of the buffer containing a block group bitmap * @pr_entry_bh: buffer head of the buffer containing translation entries */ struct nilfs_palloc_req { __u64 pr_entry_nr; struct buffer_head *pr_desc_bh; struct buffer_head *pr_bitmap_bh; struct buffer_head *pr_entry_bh; }; int nilfs_palloc_prepare_alloc_entry(struct inode *, struct nilfs_palloc_req *); void nilfs_palloc_commit_alloc_entry(struct inode *, struct nilfs_palloc_req *); void nilfs_palloc_abort_alloc_entry(struct inode *, struct nilfs_palloc_req *); void nilfs_palloc_commit_free_entry(struct inode *, struct nilfs_palloc_req *); int nilfs_palloc_prepare_free_entry(struct inode *, struct nilfs_palloc_req *); void nilfs_palloc_abort_free_entry(struct inode *, struct nilfs_palloc_req *); int nilfs_palloc_freev(struct inode *, __u64 *, size_t); #define nilfs_set_bit_atomic ext2_set_bit_atomic #define nilfs_clear_bit_atomic ext2_clear_bit_atomic #define nilfs_find_next_zero_bit ext2_find_next_zero_bit /* * persistent object allocator cache */ struct nilfs_bh_assoc { unsigned long blkoff; struct buffer_head *bh; }; struct nilfs_palloc_cache { spinlock_t lock; struct nilfs_bh_assoc prev_desc; struct nilfs_bh_assoc prev_bitmap; struct nilfs_bh_assoc prev_entry; }; void nilfs_palloc_setup_cache(struct inode *inode, struct nilfs_palloc_cache *cache); void nilfs_palloc_clear_cache(struct inode *inode); void nilfs_palloc_destroy_cache(struct inode *inode); #endif /* _NILFS_ALLOC_H */
35.534653
79
0.76623
d21dc0244bcaf6021e0370d3adf67a11c9f454de
771
c
C
main.c
before25tofree/Coroutine
2a34c38a96183bdb328fa7317979553d32507dda
[ "MIT" ]
5
2019-05-20T11:35:49.000Z
2019-06-03T02:51:48.000Z
main.c
before25tofree/Coroutine
2a34c38a96183bdb328fa7317979553d32507dda
[ "MIT" ]
null
null
null
main.c
before25tofree/Coroutine
2a34c38a96183bdb328fa7317979553d32507dda
[ "MIT" ]
null
null
null
#include "coroutine.h" #include <stdio.h> struct args { int n; }; static void //测试使用的协程执行函数 foo(struct schedule * S, void *ud) { struct args * args = ud; int start = args->n; int i; for(i=0; i<5; i++){ printf("coroutine %d : %d\n", coroutine_running(S), start + i); coroutine_yield(S); } } static void //关于两个打印协程的测试用例 test(struct schedule * S) { struct args args1 = { 0 }; struct args args2 = { 100 }; int co1 = coroutine_new(S, foo, &args1); int co2 = coroutine_new(S, foo, &args2); printf("main start\n"); while(coroutine_status(S,co1) && coroutine_status(S,co2)) { coroutine_resume(S,co1); coroutine_resume(S,co2); } printf("main end\n"); } int main() { struct schedule * S = coroutine_open(); test(S); coroutine_close(S); return 0; }
19.275
65
0.647211
191111782401c07aa0a96fb7af8f87b6f7a620ea
59,102
h
C
lib/RandomHash_Snefru_8_256.h
pascgodev/go-randomhash
28db9de6dc0b93f9a4d413f05fc17ee4f27923f2
[ "CC0-1.0" ]
1
2019-03-13T03:14:46.000Z
2019-03-13T03:14:46.000Z
lib/Pascal/RandomHash_Snefru_8_256.h
PascalCoinPool/node-randomhash
b70fea265e71c1e02cffe03ed442ce5ba55bef5b
[ "CC0-1.0" ]
null
null
null
lib/Pascal/RandomHash_Snefru_8_256.h
PascalCoinPool/node-randomhash
b70fea265e71c1e02cffe03ed442ce5ba55bef5b
[ "CC0-1.0" ]
1
2019-06-02T11:14:47.000Z
2019-06-02T11:14:47.000Z
/** * * Copyright 2018 Polyminer1 <https://github.com/polyminer1> * * To the extent possible under law, the author(s) have dedicated all copyright * and related and neighboring rights to this software to the public domain * worldwide. This software is distributed without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication along with * this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ /// /// @file /// @copyright Polyminer1, QualiaLibre #include "RandomHash_core.h" #define SNEFRU_SecurityLevel 8 #define SNEFRU_HashSize 32 #define SNEFRU_BlockSize (64 - 32) #define SNEFRU_size (SNEFRU_HashSize >> 2) //8 const uint32_t RH_ALIGN(64) Snefru_shifts[4] = { 16, 8, 16, 24 }; const uint32_t RH_ALIGN(64) Snefru_boxes[16][256] = { { 0x64F9001B, 0xFEDDCDF6, 0x7C8FF1E2, 0x11D71514, 0x8B8C18D3, 0xDDDF881E, 0x6EAB5056, 0x88CED8E1, 0x49148959, 0x69C56FD5, 0xB7994F03, 0x0FBCEE3E, 0x3C264940, 0x21557E58, 0xE14B3FC2, 0x2E5CF591, 0xDCEFF8CE, 0x092A1648, 0xBE812936, 0xFF7B0C6A, 0xD5251037, 0xAFA448F1, 0x7DAFC95A, 0x1EA69C3F, 0xA417ABE7, 0x5890E423, 0xB0CB70C0, 0xC85025F7, 0x244D97E3, 0x1FF3595F, 0xC4EC6396, 0x59181E17, 0xE635B477, 0x354E7DBF, 0x796F7753, 0x66EB52CC, 0x77C3F995, 0x32E3A927, 0x80CCAED6, 0x4E2BE89D, 0x375BBD28, 0xAD1A3D05, 0x2B1B42B3, 0x16C44C71, 0x4D54BFA8, 0xE57DDC7A, 0xEC6D8144, 0x5A71046B, 0xD8229650, 0x87FC8F24, 0xCBC60E09, 0xB6390366, 0xD9F76092, 0xD393A70B, 0x1D31A08A, 0x9CD971C9, 0x5C1EF445, 0x86FAB694, 0xFDB44165, 0x8EAAFCBE, 0x4BCAC6EB, 0xFB7A94E5, 0x5789D04E, 0xFA13CF35, 0x236B8DA9, 0x4133F000, 0x6224261C, 0xF412F23B, 0xE75E56A4, 0x30022116, 0xBAF17F1F, 0xD09872F9, 0xC1A3699C, 0xF1E802AA, 0x0DD145DC, 0x4FDCE093, 0x8D8412F0, 0x6CD0F376, 0x3DE6B73D, 0x84BA737F, 0xB43A30F2, 0x44569F69, 0x00E4EACA, 0xB58DE3B0, 0x959113C8, 0xD62EFEE9, 0x90861F83, 0xCED69874, 0x2F793CEE, 0xE8571C30, 0x483665D1, 0xAB07B031, 0x914C844F, 0x15BF3BE8, 0x2C3F2A9A, 0x9EB95FD4, 0x92E7472D, 0x2297CC5B, 0xEE5F2782, 0x5377B562, 0xDB8EBBCF, 0xF961DEDD, 0xC59B5C60, 0x1BD3910D, 0x26D206AD, 0xB28514D8, 0x5ECF6B52, 0x7FEA78BB, 0x504879AC, 0xED34A884, 0x36E51D3C, 0x1753741D, 0x8C47CAED, 0x9D0A40EF, 0x3145E221, 0xDA27EB70, 0xDF730BA3, 0x183C8789, 0x739AC0A6, 0x9A58DFC6, 0x54B134C1, 0xAC3E242E, 0xCC493902, 0x7B2DDA99, 0x8F15BC01, 0x29FD38C7, 0x27D5318F, 0x604AAFF5, 0xF29C6818, 0xC38AA2EC, 0x1019D4C3, 0xA8FB936E, 0x20ED7B39, 0x0B686119, 0x89A0906F, 0x1CC7829E, 0x9952EF4B, 0x850E9E8C, 0xCD063A90, 0x67002F8E, 0xCFAC8CB7, 0xEAA24B11, 0x988B4E6C, 0x46F066DF, 0xCA7EEC08, 0xC7BBA664, 0x831D17BD, 0x63F575E6, 0x9764350E, 0x47870D42, 0x026CA4A2, 0x8167D587, 0x61B6ADAB, 0xAA6564D2, 0x70DA237B, 0x25E1C74A, 0xA1C901A0, 0x0EB0A5DA, 0x7670F741, 0x51C05AEA, 0x933DFA32, 0x0759FF1A, 0x56010AB8, 0x5FDECB78, 0x3F32EDF8, 0xAEBEDBB9, 0x39F8326D, 0xD20858C5, 0x9B638BE4, 0xA572C80A, 0x28E0A19F, 0x432099FC, 0x3A37C3CD, 0xBF95C585, 0xB392C12A, 0x6AA707D7, 0x52F66A61, 0x12D483B1, 0x96435B5E, 0x3E75802B, 0x3BA52B33, 0xA99F51A5, 0xBDA1E157, 0x78C2E70C, 0xFCAE7CE0, 0xD1602267, 0x2AFFAC4D, 0x4A510947, 0x0AB2B83A, 0x7A04E579, 0x340DFD80, 0xB916E922, 0xE29D5E9B, 0xF5624AF4, 0x4CA9D9AF, 0x6BBD2CFE, 0xE3B7F620, 0xC2746E07, 0x5B42B9B6, 0xA06919BC, 0xF0F2C40F, 0x72217AB5, 0x14C19DF3, 0xF3802DAE, 0xE094BEB4, 0xA2101AFF, 0x0529575D, 0x55CDB27C, 0xA33BDDB2, 0x6528B37D, 0x740C05DB, 0xE96A62C4, 0x40782846, 0x6D30D706, 0xBBF48E2C, 0xBCE2D3DE, 0x049E37FA, 0x01B5E634, 0x2D886D8D, 0x7E5A2E7E, 0xD7412013, 0x06E90F97, 0xE45D3EBA, 0xB8AD3386, 0x13051B25, 0x0C035354, 0x71C89B75, 0xC638FBD0, 0x197F11A1, 0xEF0F08FB, 0xF8448651, 0x38409563, 0x452F4443, 0x5D464D55, 0x03D8764C, 0xB1B8D638, 0xA70BBA2F, 0x94B3D210, 0xEB6692A7, 0xD409C2D9, 0x68838526, 0xA6DB8A15, 0x751F6C98, 0xDE769A88, 0xC9EE4668, 0x1A82A373, 0x0896AA49, 0x42233681, 0xF62C55CB, 0x9F1C5404, 0xF74FB15C, 0xC06E4312, 0x6FFE5D72, 0x8AA8678B, 0x337CD129, 0x8211CEFD }, { 0x074A1D09, 0x52A10E5A, 0x9275A3F8, 0x4B82506C, 0x37DF7E1B, 0x4C78B3C5, 0xCEFAB1DA, 0xF472267E, 0xB63045F6, 0xD66A1FC0, 0x400298E3, 0x27E60C94, 0x87D2F1B8, 0xDF9E56CC, 0x45CD1803, 0x1D35E098, 0xCCE7C736, 0x03483BF1, 0x1F7307D7, 0xC6E8F948, 0xE613C111, 0x3955C6FF, 0x1170ED7C, 0x8E95DA41, 0x99C31BF4, 0xA4DA8021, 0x7B5F94FB, 0xDD0DA51F, 0x6562AA77, 0x556BCB23, 0xDB1BACC6, 0x798040B9, 0xBFE5378F, 0x731D55E6, 0xDAA5BFEE, 0x389BBC60, 0x1B33FBA4, 0x9C567204, 0x36C26C68, 0x77EE9D69, 0x8AEB3E88, 0x2D50B5CE, 0x9579E790, 0x42B13CFC, 0x33FBD32B, 0xEE0503A7, 0xB5862824, 0x15E41EAD, 0xC8412EF7, 0x9D441275, 0x2FCEC582, 0x5FF483B7, 0x8F3931DF, 0x2E5D2A7B, 0x49467BF9, 0x0653DEA9, 0x2684CE35, 0x7E655E5C, 0xF12771D8, 0xBB15CC67, 0xAB097CA1, 0x983DCF52, 0x10DDF026, 0x21267F57, 0x2C58F6B4, 0x31043265, 0x0BAB8C01, 0xD5492099, 0xACAAE619, 0x944CE54A, 0xF2D13D39, 0xADD3FC32, 0xCDA08A40, 0xE2B0D451, 0x9EFE08AE, 0xB9D50FD2, 0xEA5CD7FD, 0xC9A749DD, 0x13EA2253, 0x832DEBAA, 0x24BE640F, 0xE03E926A, 0x29E01CDE, 0x8BF59F18, 0x0F9D00B6, 0xE1238B46, 0x1E7D8E34, 0x93619ADB, 0x76B32F9F, 0xBD972CEC, 0xE31FA976, 0xA68FBB10, 0xFB3BA49D, 0x8587C41D, 0xA5ADD1D0, 0xF3CF84BF, 0xD4E11150, 0xD9FFA6BC, 0xC3F6018C, 0xAEF10572, 0x74A64B2F, 0xE7DC9559, 0x2AAE35D5, 0x5B6F587F, 0xA9E353FE, 0xCA4FB674, 0x04BA24A8, 0xE5C6875F, 0xDCBC6266, 0x6BC5C03F, 0x661EEF02, 0xED740BAB, 0x058E34E4, 0xB7E946CF, 0x88698125, 0x72EC48ED, 0xB11073A3, 0xA13485EB, 0xA2A2429C, 0xFA407547, 0x50B76713, 0x5418C37D, 0x96192DA5, 0x170BB04B, 0x518A021E, 0xB0AC13D1, 0x0963FA2A, 0x4A6E10E1, 0x58472BDC, 0xF7F8D962, 0x979139EA, 0x8D856538, 0xC0997042, 0x48324D7A, 0x447623CB, 0x8CBBE364, 0x6E0C6B0E, 0xD36D63B0, 0x3F244C84, 0x3542C971, 0x2B228DC1, 0xCB0325BB, 0xF8C0D6E9, 0xDE11066B, 0xA8649327, 0xFC31F83E, 0x7DD80406, 0xF916DD61, 0xD89F79D3, 0x615144C2, 0xEBB45D31, 0x28002958, 0x56890A37, 0xF05B3808, 0x123AE844, 0x86839E16, 0x914B0D83, 0xC506B43C, 0xCF3CBA5E, 0x7C60F5C9, 0x22DEB2A0, 0x5D9C2715, 0xC77BA0EF, 0x4F45360B, 0xC1017D8B, 0xE45ADC29, 0xA759909B, 0x412CD293, 0xD7D796B1, 0x00C8FF30, 0x23A34A80, 0x4EC15C91, 0x714E78B5, 0x47B9E42E, 0x78F3EA4D, 0x7F078F5B, 0x346C593A, 0xA3A87A1A, 0x9BCBFE12, 0x3D439963, 0xB2EF6D8E, 0xB8D46028, 0x6C2FD5CA, 0x62675256, 0x01F2A2F3, 0xBC96AE0A, 0x709A8920, 0xB4146E87, 0x6308B9E2, 0x64BDA7BA, 0xAFED6892, 0x6037F2A2, 0xF52969E0, 0x0ADB43A6, 0x82811400, 0x90D0BDF0, 0x19C9549E, 0x203F6A73, 0x1ACCAF4F, 0x89714E6D, 0x164D4705, 0x67665F07, 0xEC206170, 0x0C2182B2, 0xA02B9C81, 0x53289722, 0xF6A97686, 0x140E4179, 0x9F778849, 0x9A88E15D, 0x25CADB54, 0xD157F36F, 0x32A421C3, 0xB368E98A, 0x5A92CD0D, 0x757AA8D4, 0xC20AC278, 0x08B551C7, 0x849491E8, 0x4DC75AD6, 0x697C33BE, 0xBAF0CA33, 0x46125B4E, 0x59D677B3, 0x30D9C8F2, 0xD0AF860C, 0x1C7FD0FA, 0xFE0FF72C, 0x5C8D6F43, 0x57FDEC3B, 0x6AB6AD97, 0xD22ADF89, 0x18171785, 0x02BFE22D, 0x6DB80917, 0x80B216AF, 0xE85E4F9A, 0x7A1C306E, 0x6FC49BF5, 0x3AF7A11C, 0x81E215E7, 0x68363FCD, 0x3E9357C8, 0xEF52FD55, 0x3B8BAB4C, 0x3C8CF495, 0xBEFCEEBD, 0xFD25B714, 0xC498D83D, 0x0D2E1A8D, 0xE9F966AC, 0x0E387445, 0x435419E5, 0x5E7EBEC4, 0xAA90B8D9, 0xFF1A3A96 }, { 0x4A8FE4E3, 0xF27D99CD, 0xD04A40CA, 0xCB5FF194, 0x3668275A, 0xFF4816BE, 0xA78B394C, 0x4C6BE9DB, 0x4EEC38D2, 0x4296EC80, 0xCDCE96F8, 0x888C2F38, 0xE75508F5, 0x7B916414, 0x060AA14A, 0xA214F327, 0xBE608DAF, 0x1EBBDEC2, 0x61F98CE9, 0xE92156FE, 0x4F22D7A3, 0x3F76A8D9, 0x559A4B33, 0x38AD2959, 0xF3F17E9E, 0x85E1BA91, 0xE5EBA6FB, 0x73DCD48C, 0xF5C3FF78, 0x481B6058, 0x8A3297F7, 0x8F1F3BF4, 0x93785AB2, 0x477A4A5B, 0x6334EB5D, 0x6D251B2E, 0x74A9102D, 0x07E38FFA, 0x915C9C62, 0xCCC275EA, 0x6BE273EC, 0x3EBDDD70, 0xD895796C, 0xDC54A91B, 0xC9AFDF81, 0x23633F73, 0x275119B4, 0xB19F6B67, 0x50756E22, 0x2BB152E2, 0x76EA46A2, 0xA353E232, 0x2F596AD6, 0x0B1EDB0B, 0x02D3D9A4, 0x78B47843, 0x64893E90, 0x40F0CAAD, 0xF68D3AD7, 0x46FD1707, 0x1C9C67EF, 0xB5E086DE, 0x96EE6CA6, 0x9AA34774, 0x1BA4F48A, 0x8D01ABFD, 0x183EE1F6, 0x5FF8AA7A, 0x17E4FAAE, 0x303983B0, 0x6C08668B, 0xD4AC4382, 0xE6C5849F, 0x92FEFB53, 0xC1CAC4CE, 0x43501388, 0x441118CF, 0xEC4FB308, 0x53A08E86, 0x9E0FE0C5, 0xF91C1525, 0xAC45BE05, 0xD7987CB5, 0x49BA1487, 0x57938940, 0xD5877648, 0xA958727F, 0x58DFE3C3, 0xF436CF77, 0x399E4D11, 0xF0A5BFA9, 0xEF61A33B, 0xA64CAC60, 0x04A8D0BA, 0x030DD572, 0xB83D320F, 0xCAB23045, 0xE366F2F0, 0x815D008D, 0xC897A43A, 0x1D352DF3, 0xB9CC571D, 0x8BF38744, 0x72209092, 0xEBA124EB, 0xFB99CE5E, 0x3BB94293, 0x28DA549C, 0xAAB8A228, 0xA4197785, 0x33C70296, 0x25F6259B, 0x5C85DA21, 0xDF15BDEE, 0x15B7C7E8, 0xE2ABEF75, 0xFCC19BC1, 0x417FF868, 0x14884434, 0x62825179, 0xC6D5C11C, 0x0E4705DC, 0x22700DE0, 0xD3D2AF18, 0x9BE822A0, 0x35B669F1, 0xC42BB55C, 0x0A801252, 0x115BF0FC, 0x3CD7D856, 0xB43F5F9D, 0xC2306516, 0xA1231C47, 0xF149207E, 0x5209A795, 0x34B3CCD8, 0x67AEFE54, 0x2C83924E, 0x6662CBAC, 0x5EEDD161, 0x84E681AA, 0x5D57D26B, 0xFA465CC4, 0x7E3AC3A8, 0xBF7C0CC6, 0xE18A9AA1, 0xC32F0A6F, 0xB22CC00D, 0x3D280369, 0x994E554F, 0x68F480D3, 0xADCFF5E6, 0x3A8EB265, 0x83269831, 0xBD568A09, 0x4BC8AE6A, 0x69F56D2B, 0x0F17EAC8, 0x772EB6C7, 0x9F41343C, 0xAB1D0742, 0x826A6F50, 0xFEA2097C, 0x1912C283, 0xCE185899, 0xE4444839, 0x2D8635D5, 0x65D0B1FF, 0x865A7F17, 0x326D9FB1, 0x59E52820, 0x0090ADE1, 0x753C7149, 0x9DDD8B98, 0xA5A691DA, 0x0D0382BB, 0x8904C930, 0x086CB000, 0x6E69D3BD, 0x24D4E7A7, 0x05244FD0, 0x101A5E0C, 0x6A947DCB, 0xE840F77B, 0x7D0C5003, 0x7C370F1F, 0x805245ED, 0xE05E3D3F, 0x7906880E, 0xBABFCD35, 0x1A7EC697, 0x8C052324, 0x0C6EC8DF, 0xD129A589, 0xC7A75B02, 0x12D81DE7, 0xD9BE2A66, 0x1F4263AB, 0xDE73FDB6, 0x2A00680A, 0x56649E36, 0x3133ED55, 0x90FA0BF2, 0x2910A02A, 0x949D9D46, 0xA0D1DCDD, 0xCFC9B7D4, 0xD2677BE5, 0x95CB36B3, 0x13CD9410, 0xDBF73313, 0xB7C6E8C0, 0xF781414B, 0x510B016D, 0xB0DE1157, 0xD6B0F62C, 0xBB074ECC, 0x7F1395B7, 0xEE792CF9, 0xEA6FD63E, 0x5BD6938E, 0xAF02FC64, 0xDAB57AB8, 0x8EDB3784, 0x8716318F, 0x164D1A01, 0x26F26141, 0xB372E6B9, 0xF8FC2B06, 0x7AC00E04, 0x3727B89A, 0x97E9BCA5, 0x9C2A742F, 0xBC3B1F7D, 0x7165B471, 0x609B4C29, 0x20925351, 0x5AE72112, 0x454BE5D1, 0xC0FFB95F, 0xDD0EF919, 0x6F2D70C9, 0x0974C5BF, 0x98AA6263, 0x01D91E4D, 0x2184BB6E, 0x70C43C1E, 0x4D435915, 0xAE7B8523, 0xB6FB06BC, 0x5431EE76, 0xFDBC5D26, 0xED77493D, 0xC5712EE4, 0xA8380437, 0x2EEF261A }, { 0x5A79392B, 0xB8AF32C2, 0x41F7720A, 0x833A61EC, 0x13DFEDAC, 0xC4990BC4, 0xDC0F54BC, 0xFEDD5E88, 0x80DA1881, 0x4DEA1AFD, 0xFD402CC6, 0xAE67CC7A, 0xC5238525, 0x8EA01254, 0xB56B9BD5, 0x862FBD6D, 0xAC8575D3, 0x6FBA3714, 0xDA7EBF46, 0x59CD5238, 0x8AC9DBFE, 0x353729FC, 0xE497D7F2, 0xC3AB84E0, 0xF05A114B, 0x7B887A75, 0xEDC603DD, 0x5E6FE680, 0x2C84B399, 0x884EB1DA, 0x1CB8C8BF, 0xAA51098A, 0xC862231C, 0x8BAC2221, 0x21B387E5, 0x208A430D, 0x2A3F0F8B, 0xA5FF9CD2, 0x6012A2EA, 0x147A9EE7, 0xF62A501D, 0xB4B2E51A, 0x3EF3484C, 0xC0253C59, 0x2B82B536, 0x0AA9696B, 0xBE0C109B, 0xC70B7929, 0xCE3E8A19, 0x2F66950E, 0x459F1C2C, 0xE68FB93D, 0xA3C3FF3E, 0x62B45C62, 0x300991CB, 0x01914C57, 0x7F7BC06A, 0x182831F5, 0xE7B74BCA, 0xFA50F6D0, 0x523CAA61, 0xE3A7CF05, 0xE9E41311, 0x280A21D1, 0x6A4297E1, 0xF24DC67E, 0xFC3189E6, 0xB72BF34F, 0x4B1E67AF, 0x543402CE, 0x79A59867, 0x0648E02A, 0x00A3AC17, 0xC6208D35, 0x6E7F5F76, 0xA45BB4BE, 0xF168FA63, 0x3F4125F3, 0xF311406F, 0x02706565, 0xBFE58022, 0x0CFCFDD9, 0x0735A7F7, 0x8F049092, 0xD98EDC27, 0xF5C5D55C, 0xE0F201DB, 0x0DCAFC9A, 0x7727FB79, 0xAF43ABF4, 0x26E938C1, 0x401B26A6, 0x900720FA, 0x2752D97B, 0xCFF1D1B3, 0xA9D9E424, 0x42DB99AB, 0x6CF8BE5F, 0xE82CEBE3, 0x3AFB733B, 0x6B734EB6, 0x1036414A, 0x975F667C, 0x049D6377, 0xBA587C60, 0xB1D10483, 0xDE1AEFCC, 0x1129D055, 0x72051E91, 0x6946D623, 0xF9E86EA7, 0x48768C00, 0xB0166C93, 0x9956BBF0, 0x1F1F6D84, 0xFB15E18E, 0x033B495D, 0x56E3362E, 0x4F44C53C, 0x747CBA51, 0x89D37872, 0x5D9C331B, 0xD2EF9FA8, 0x254917F8, 0x1B106F47, 0x37D75553, 0xB3F053B0, 0x7DCCD8EF, 0xD30EB802, 0x5889F42D, 0x610206D7, 0x1A7D34A1, 0x92D87DD8, 0xE5F4A315, 0xD1CF0E71, 0xB22DFE45, 0xB901E8EB, 0x0FC0CE5E, 0x2EFA60C9, 0x2DE74290, 0x36D0C906, 0x381C70E4, 0x4C6DA5B5, 0x3D81A682, 0x7E381F34, 0x396C4F52, 0x95AD5901, 0x1DB50C5A, 0x29982E9E, 0x1557689F, 0x3471EE42, 0xD7E2F7C0, 0x8795A1E2, 0xBC324D8D, 0xE224C3C8, 0x12837E39, 0xCDEE3D74, 0x7AD2143F, 0x0E13D40C, 0x78BD4A68, 0xA2EB194D, 0xDB9451F9, 0x859B71DC, 0x5C4F5B89, 0xCA14A8A4, 0xEF92F003, 0x16741D98, 0x33AA4444, 0x9E967FBB, 0x092E3020, 0xD86A35B8, 0x8CC17B10, 0xE1BF08AE, 0x55693FC5, 0x7680AD13, 0x1E6546E8, 0x23B6E7B9, 0xEE77A4B2, 0x08ED0533, 0x44FD2895, 0xB6393B69, 0x05D6CACF, 0x9819B209, 0xECBBB72F, 0x9A75779C, 0xEAEC0749, 0x94A65AEE, 0xBDF52DC3, 0xD6A25D04, 0x82008E4E, 0xA6DE160F, 0x9B036AFB, 0x228B3A66, 0x5FB10A70, 0xCC338B58, 0x5378A9DF, 0xC908BCA9, 0x4959E25B, 0x46909A97, 0x66AE8F6E, 0xDD0683E9, 0x65F994B4, 0x6426CDA5, 0xC24B8840, 0x32539DA0, 0x63175650, 0xD0C815FF, 0x50CBC41E, 0xF7C774A3, 0x31B0C231, 0x8D0D8116, 0x24BEF16C, 0xD555D256, 0xDF47EA8C, 0x6D21ECCD, 0xA887A012, 0x84542AED, 0xA7B9C1BD, 0x914C1BB1, 0xA0D5B67D, 0x438CE937, 0x7030F873, 0x71F6B0C7, 0x574576BA, 0xF8BC4541, 0x9C61D348, 0x1960579D, 0x17C4DAAD, 0x96A4CB0B, 0xC193F2F6, 0x756EAFA2, 0x7C1D2F94, 0xF4FE2B43, 0xCB86E33A, 0xEBD4C728, 0x9D18AE64, 0x9FE13E30, 0x3CE0F5DE, 0xABA1F985, 0xADDC2718, 0x68CE6278, 0xD45E241F, 0xA15C82B7, 0x3B2293D4, 0x739EDD32, 0x674A6BF1, 0x5B5D587F, 0x4772DEAA, 0x4A63968F, 0x0BE68686, 0x513D6426, 0x939A4787, 0xBBA89296, 0x4EC20007, 0x818D0D08, 0xFF64DFD6 }, { 0xCB2297CB, 0xDB48A144, 0xA16CBE4B, 0xBBEA1D6C, 0x5AF6B6B7, 0x8A8110B6, 0xF9236EF9, 0xC98F83E6, 0x0F9C65B8, 0x252D4A89, 0xA497F068, 0xA5D7ED2D, 0x94C22845, 0x9DA1C8C4, 0xE27C2E2E, 0x6E8BA2B4, 0xC3DD17FB, 0x498CD482, 0x0DFE6A9F, 0xB0705829, 0x9A1E6DC1, 0xF829717C, 0x07BB8E3A, 0xDA3C0B02, 0x1AF82FC7, 0x73B70955, 0x7A04379C, 0x5EE20A28, 0x83712AE5, 0xF4C47C6D, 0xDF72BA56, 0xD794858D, 0x8C0CF709, 0x18F0F390, 0xB6C69B35, 0xBF2F01DB, 0x2FA74DCA, 0xD0CD9127, 0xBDE66CEC, 0x3DEEBD46, 0x57C88FC3, 0xCEE1406F, 0x0066385A, 0xF3C3444F, 0x3A79D5D5, 0x75751EB9, 0x3E7F8185, 0x521C2605, 0xE1AAAB6E, 0x38EBB80F, 0xBEE7E904, 0x61CB9647, 0xEA54904E, 0x05AE00E4, 0x2D7AC65F, 0x087751A1, 0xDCD82915, 0x0921EE16, 0xDD86D33B, 0xD6BD491A, 0x40FBADF0, 0x4232CBD2, 0x33808D10, 0x39098C42, 0x193F3199, 0x0BC1E47A, 0x4A82B149, 0x02B65A8A, 0x104CDC8E, 0x24A8F52C, 0x685C6077, 0xC79F95C9, 0x1D11FE50, 0xC08DAFCD, 0x7B1A9A03, 0x1C1F11D8, 0x84250E7F, 0x979DB248, 0xEBDC0501, 0xB9553395, 0xE3C05EA8, 0xB1E51C4C, 0x13B0E681, 0x3B407766, 0x36DB3087, 0xEE17C9FC, 0x6C53ECF2, 0xADCCC58F, 0xC427660B, 0xEFD5867D, 0x9B6D54A5, 0x6FF1AEFF, 0x8E787952, 0x9E2BFFE0, 0x8761D034, 0xE00BDBAD, 0xAE99A8D3, 0xCC03F6E2, 0xFD0ED807, 0x0E508AE3, 0xB74182AB, 0x4349245D, 0xD120A465, 0xB246A641, 0xAF3B7AB0, 0x2A6488BB, 0x4B3A0D1F, 0xE7C7E58C, 0x3FAFF2EB, 0x90445FFD, 0xCF38C393, 0x995D07E7, 0xF24F1B36, 0x356F6891, 0x6D6EBCBE, 0x8DA9E262, 0x50FD520E, 0x5BCA9E1E, 0x37472CF3, 0x69075057, 0x7EC5FDED, 0x0CAB892A, 0xFB2412BA, 0x1728DEBF, 0xA000A988, 0xD843CE79, 0x042E20DD, 0x4FE8F853, 0x56659C3C, 0x2739D119, 0xA78A6120, 0x80960375, 0x70420611, 0x85E09F78, 0xABD17E96, 0x1B513EAF, 0x1E01EB63, 0x26AD2133, 0xA890C094, 0x7613CF60, 0x817E781B, 0xA39113D7, 0xE957FA58, 0x4131B99E, 0x28B1EFDA, 0x66ACFBA7, 0xFF68944A, 0x77A44FD1, 0x7F331522, 0x59FFB3FA, 0xA6DF935B, 0xFA12D9DF, 0xC6BF6F3F, 0x89520CF6, 0x659EDD6A, 0x544DA739, 0x8B052538, 0x7C30EA21, 0xC2345525, 0x15927FB2, 0x144A436B, 0xBA107B8B, 0x1219AC97, 0x06730432, 0x31831AB3, 0xC55A5C24, 0xAA0FCD3E, 0xE5606BE8, 0x5C88F19B, 0x4C0841EE, 0x1FE37267, 0x11F9C4F4, 0x9F1B9DAE, 0x864E76D0, 0xE637C731, 0xD97D23A6, 0x32F53D5C, 0xB8161980, 0x93FA0F84, 0xCAEF0870, 0x8874487E, 0x98F2CC73, 0x645FB5C6, 0xCD853659, 0x2062470D, 0x16EDE8E9, 0x6B06DAB5, 0x78B43900, 0xFC95B786, 0x5D8E7DE1, 0x465B5954, 0xFE7BA014, 0xF7D23F7B, 0x92BC8B18, 0x03593592, 0x55CEF4F7, 0x74B27317, 0x79DE1FC2, 0xC8A0BFBD, 0x229398CC, 0x62A602CE, 0xBCB94661, 0x5336D206, 0xD2A375FE, 0x6A6AB483, 0x4702A5A4, 0xA2E9D73D, 0x23A2E0F1, 0x9189140A, 0x581D18DC, 0xB39A922B, 0x82356212, 0xD5F432A9, 0xD356C2A3, 0x5F765B4D, 0x450AFCC8, 0x4415E137, 0xE8ECDFBC, 0xED0DE3EA, 0x60D42B13, 0xF13DF971, 0x71FC5DA2, 0xC1455340, 0xF087742F, 0xF55E5751, 0x67B3C1F8, 0xAC6B8774, 0x7DCFAAAC, 0x95983BC0, 0x489BB0B1, 0x2C184223, 0x964B6726, 0x2BD3271C, 0x72266472, 0xDED64530, 0x0A2AA343, 0xD4F716A0, 0xB4DAD6D9, 0x2184345E, 0x512C990C, 0x29D92D08, 0x2EBE709A, 0x01144C69, 0x34584B9D, 0xE4634ED6, 0xECC963CF, 0x3C6984AA, 0x4ED056EF, 0x9CA56976, 0x8F3E80D4, 0xB5BAE7C5, 0x30B5CAF5, 0x63F33A64, 0xA9E4BBDE, 0xF6B82298, 0x4D673C1D }, { 0x4B4F1121, 0xBA183081, 0xC784F41F, 0xD17D0BAC, 0x083D2267, 0x37B1361E, 0x3581AD05, 0xFDA2F6BC, 0x1E892CDD, 0xB56D3C3A, 0x32140E46, 0x138D8AAB, 0xE14773D4, 0x5B0E71DF, 0x5D1FE055, 0x3FB991D3, 0xF1F46C71, 0xA325988C, 0x10F66E80, 0xB1006348, 0x726A9F60, 0x3B67F8BA, 0x4E114EF4, 0x05C52115, 0x4C5CA11C, 0x99E1EFD8, 0x471B83B3, 0xCBF7E524, 0x43AD82F5, 0x690CA93B, 0xFAA61BB2, 0x12A832B5, 0xB734F943, 0xBD22AEA7, 0x88FEC626, 0x5E80C3E7, 0xBE3EAF5E, 0x44617652, 0xA5724475, 0xBB3B9695, 0x7F3FEE8F, 0x964E7DEB, 0x518C052D, 0x2A0BBC2B, 0xC2175F5C, 0x9A7B3889, 0xA70D8D0C, 0xEACCDD29, 0xCCCD6658, 0x34BB25E6, 0xB8391090, 0xF651356F, 0x52987C9E, 0x0C16C1CD, 0x8E372D3C, 0x2FC6EBBD, 0x6E5DA3E3, 0xB0E27239, 0x5F685738, 0x45411786, 0x067F65F8, 0x61778B40, 0x81AB2E65, 0x14C8F0F9, 0xA6B7B4CE, 0x4036EAEC, 0xBF62B00A, 0xECFD5E02, 0x045449A6, 0xB20AFD28, 0x2166D273, 0x0D13A863, 0x89508756, 0xD51A7530, 0x2D653F7A, 0x3CDBDBC3, 0x80C9DF4F, 0x3D5812D9, 0x53FBB1F3, 0xC0F185C0, 0x7A3C3D7E, 0x68646410, 0x857607A0, 0x1D12622E, 0x97F33466, 0xDB4C9917, 0x6469607C, 0x566E043D, 0x79EF1EDB, 0x2C05898D, 0xC9578E25, 0xCD380101, 0x46E04377, 0x7D1CC7A9, 0x6552B837, 0x20192608, 0xB97500C5, 0xED296B44, 0x368648B4, 0x62995CD5, 0x82731400, 0xF9AEBD8B, 0x3844C0C7, 0x7C2DE794, 0x33A1A770, 0x8AE528C2, 0x5A2BE812, 0x1F8F4A07, 0x2B5ED7CA, 0x937EB564, 0x6FDA7E11, 0xE49B5D6C, 0xB4B3244E, 0x18AA53A4, 0x3A061334, 0x4D6067A3, 0x83BA5868, 0x9BDF4DFE, 0x7449F261, 0x709F8450, 0xCAD133CB, 0xDE941C3F, 0xF52AE484, 0x781D77ED, 0x7E4395F0, 0xAE103B59, 0x922331BB, 0x42CE50C8, 0xE6F08153, 0xE7D941D0, 0x5028ED6B, 0xB3D2C49B, 0xAD4D9C3E, 0xD201FB6E, 0xA45BD5BE, 0xFFCB7F4B, 0x579D7806, 0xF821BB5B, 0x59D592AD, 0xD0BE0C31, 0xD4E3B676, 0x0107165A, 0x0FE939D2, 0x49BCAAFD, 0x55FFCFE5, 0x2EC1F783, 0xF39A09A5, 0x3EB42772, 0x19B55A5D, 0x024A0679, 0x8C83B3F7, 0x8642BA1D, 0xACACD9EA, 0x87D352C4, 0x60931F45, 0xA05F97D7, 0x1CECD42C, 0xE2FCC87B, 0xB60F94E2, 0x67A34B0B, 0xFCDD40C9, 0x0B150A27, 0xD3EE9E04, 0x582E29E9, 0x4AC22B41, 0x6AC4E1B8, 0xBCCAA51A, 0x237AF30E, 0xEBC3B709, 0xC4A59D19, 0x284BC98A, 0xE9D41A93, 0x6BFA2018, 0x73B2D651, 0x11F9A2FA, 0xCE09BFF1, 0x41A470AA, 0x25888F22, 0x77E754E8, 0xF7330D8E, 0x158EAB16, 0xC5D68842, 0xC685A6F6, 0xE5B82FDE, 0x09EA3A96, 0x6DDE1536, 0x4FA919DA, 0x26C0BE9F, 0x9EED6F69, 0xF05555F2, 0xE06FC285, 0x9CD76D23, 0xAF452A92, 0xEFC74CB7, 0x9D6B4732, 0x8BE408EE, 0x22401D0D, 0xEE6C459D, 0x7587CB82, 0xE8746862, 0x5CBDDE87, 0x98794278, 0x31AFB94D, 0xC11E0F2F, 0x30E8FC2A, 0xCF3261EF, 0x1A3023E1, 0xAA2F86CF, 0xF202E24A, 0x8D08DCFF, 0x764837C6, 0xA26374CC, 0x9F7C3E88, 0x949CC57D, 0xDD26A07F, 0xC39EFAB0, 0xC8F879A1, 0xDCE67BB9, 0xF4B0A435, 0x912C9AE0, 0xD85603E4, 0x953A9BBF, 0xFB8290D6, 0x0AEBCD5F, 0x16206A9A, 0x6C787A14, 0xD9A0F16A, 0x29BF4F74, 0x8F8BCE91, 0x0E5A9354, 0xAB038CB1, 0x1B8AD11B, 0xE327FF49, 0x0053DA20, 0x90CF51DC, 0xDA92FE6D, 0x0390CA47, 0xA8958097, 0xA9DC5BAF, 0x3931E3C1, 0x840446B6, 0x63D069FB, 0xD7460299, 0x7124ECD1, 0x0791E613, 0x485918FC, 0xD635D04C, 0xDF96AC33, 0x66F2D303, 0x247056AE, 0xA1A7B2A8, 0x27D8CC9C, 0x17B6E998, 0x7BF5590F, 0xFE97F557, 0x5471D8A2 }, { 0x83A327A1, 0x9F379F51, 0x40A7D007, 0x11307423, 0x224587C1, 0xAC27D63B, 0x3B7E64EA, 0x2E1CBFA6, 0x09996000, 0x03BC0E2C, 0xD4C4478A, 0x4542E0AB, 0xFEDA26D4, 0xC1D10FCB, 0x8252F596, 0x4494EB5C, 0xA362F314, 0xF5BA81FD, 0x75C3A376, 0x4CA214CA, 0xE164DEDD, 0x5088FA97, 0x4B0930E0, 0x2FCFB7E8, 0x33A6F4B2, 0xC7E94211, 0x2D66C774, 0x43BE8BAE, 0xC663D445, 0x908EB130, 0xF4E3BE15, 0x63B9D566, 0x529396B5, 0x1E1BE743, 0x4D5FF63F, 0x985E4A83, 0x71AB9DF7, 0xC516C6F5, 0x85C19AB4, 0x1F4DAEE4, 0xF2973431, 0xB713DC5E, 0x3F2E159A, 0xC824DA16, 0x06BF376A, 0xB2FE23EC, 0xE39B1C22, 0xF1EECB5F, 0x08E82D52, 0x565686C2, 0xAB0AEA93, 0xFD47219F, 0xEBDBABD7, 0x2404A185, 0x8C7312B9, 0xA8F2D828, 0x0C8902DA, 0x65B42B63, 0xC0BBEF62, 0x4E3E4CEF, 0x788F8018, 0xEE1EBAB7, 0x93928F9D, 0x683D2903, 0xD3B60689, 0xAFCB0DDC, 0x88A4C47A, 0xF6DD9C3D, 0x7EA5FCA0, 0x8A6D7244, 0xBE11F120, 0x04FF91B8, 0x8D2DC8C0, 0x27F97FDB, 0x7F9E1F47, 0x1734F0C7, 0x26F3ED8E, 0x0DF8F2BF, 0xB0833D9E, 0xE420A4E5, 0xA423CAE6, 0x95616772, 0x9AE6C049, 0x075941F2, 0xD8E12812, 0x000F6F4F, 0x3C0D6B05, 0x6CEF921C, 0xB82BC264, 0x396CB008, 0x5D608A6F, 0x6D7782C8, 0x186550AA, 0x6B6FEC09, 0x28E70B13, 0x57CE5688, 0xECD3AF84, 0x23335A95, 0x91F40CD2, 0x7B6A3B26, 0xBD32B3B6, 0x3754A6FB, 0x8ED088F0, 0xF867E87C, 0x20851746, 0x6410F9C6, 0x35380442, 0xC2CA10A7, 0x1ADEA27F, 0x76BDDD79, 0x92742CF4, 0x0E98F7EE, 0x164E931D, 0xB9C835B3, 0x69060A99, 0xB44C531E, 0xFA7B66FE, 0xC98A5B53, 0x7D95AAE9, 0x302F467B, 0x74B811DE, 0xF3866ABD, 0xB5B3D32D, 0xFC3157A4, 0xD251FE19, 0x0B5D8EAC, 0xDA71FFD5, 0x47EA05A3, 0x05C6A9E1, 0xCA0EE958, 0x9939034D, 0x25DC5EDF, 0x79083CB1, 0x86768450, 0xCF757D6D, 0x5972B6BC, 0xA78D59C9, 0xC4AD8D41, 0x2A362AD3, 0xD1179991, 0x601407FF, 0xDCF50917, 0x587069D0, 0xE0821ED6, 0xDBB59427, 0x73911A4B, 0x7C904FC3, 0x844AFB92, 0x6F8C955D, 0xE8C0C5BB, 0xB67AB987, 0xA529D96C, 0xF91F7181, 0x618B1B06, 0xE718BB0C, 0x8BD7615B, 0xD5A93A59, 0x54AEF81B, 0x772136E3, 0xCE44FD9C, 0x10CDA57E, 0x87D66E0B, 0x3D798967, 0x1B2C1804, 0x3EDFBD68, 0x15F6E62B, 0xEF68B854, 0x3896DB35, 0x12B7B5E2, 0xCB489029, 0x9E4F98A5, 0x62EB77A8, 0x217C24A2, 0x964152F6, 0x49B2080A, 0x53D23EE7, 0x48FB6D69, 0x1903D190, 0x9449E494, 0xBF6E7886, 0xFB356CFA, 0x3A261365, 0x424BC1EB, 0xA1192570, 0x019CA782, 0x9D3F7E0E, 0x9C127575, 0xEDF02039, 0xAD57BCCE, 0x5C153277, 0x81A84540, 0xBCAA7356, 0xCCD59B60, 0xA62A629B, 0xA25CCD10, 0x2B5B65CF, 0x1C535832, 0x55FD4E3A, 0x31D9790D, 0xF06BC37D, 0x4AFC1D71, 0xAEED5533, 0xBA461634, 0xBB694B78, 0x5F3A5C73, 0x6A3C764A, 0x8FB0CCA9, 0xF725684C, 0x4FE5382F, 0x1D0163AF, 0x5AA07A8F, 0xE205A8ED, 0xC30BAD38, 0xFF22CF1F, 0x72432E2E, 0x32C2518B, 0x3487CE4E, 0x7AE0AC02, 0x709FA098, 0x0A3B395A, 0x5B4043F8, 0xA9E48C36, 0x149A8521, 0xD07DEE6B, 0x46ACD2F3, 0x8958DFFC, 0xB3A1223C, 0xB11D31C4, 0xCD7F4D3E, 0x0F28E3AD, 0xE5B100BE, 0xAAC54824, 0xE9C9D7BA, 0x9BD47001, 0x80F149B0, 0x66022F0F, 0x020C4048, 0x6EFA192A, 0x67073F8D, 0x13EC7BF9, 0x3655011A, 0xE6AFE157, 0xD9845F6E, 0xDECC4425, 0x511AE2CC, 0xDF81B4D8, 0xD7809E55, 0xD6D883D9, 0x2CC7978C, 0x5E787CC5, 0xDD0033D1, 0xA050C937, 0x97F75DCD, 0x299DE580, 0x41E2B261, 0xEA5A54F1 }, { 0x7E672590, 0xBEA513BB, 0x2C906FE6, 0x86029C2B, 0x55DC4F74, 0x0553398E, 0x63E09647, 0xCAFD0BAB, 0x264C37DF, 0x8272210F, 0x67AFA669, 0x12D98A5F, 0x8CAB23C4, 0x75C68BD1, 0xC3370470, 0x33F37F4E, 0x283992FF, 0xE73A3A67, 0x1032F283, 0xF5AD9FC2, 0x963F0C5D, 0x664FBC45, 0x202BA41C, 0xC7C02D80, 0x54731E84, 0x8A1085F5, 0x601D80FB, 0x2F968E55, 0x35E96812, 0xE45A8F78, 0xBD7DE662, 0x3B6E6EAD, 0x8097C5EF, 0x070B6781, 0xB1E508F3, 0x24E4FAE3, 0xB81A7805, 0xEC0FC918, 0x43C8774B, 0x9B2512A9, 0x2B05AD04, 0x32C2536F, 0xEDF236E0, 0x8BC4B0CF, 0xBACEB837, 0x4535B289, 0x0D0E94C3, 0xA5A371D0, 0xAD695A58, 0x39E3437D, 0x9186BFFC, 0x21038C3B, 0x0AA9DFF9, 0x5D1F06CE, 0x62DEF8A4, 0xF740A2B4, 0xA2575868, 0x682683C1, 0xDBB30FAC, 0x61FE1928, 0x468A6511, 0xC61CD5F4, 0xE54D9800, 0x6B98D7F7, 0x8418B6A5, 0x5F09A5D2, 0x90B4E80B, 0x49B2C852, 0x69F11C77, 0x17412B7E, 0x7F6FC0ED, 0x56838DCC, 0x6E9546A2, 0xD0758619, 0x087B9B9A, 0xD231A01D, 0xAF46D415, 0x097060FD, 0xD920F657, 0x882D3F9F, 0x3AE7C3C9, 0xE8A00D9B, 0x4FE67EBE, 0x2EF80EB2, 0xC1916B0C, 0xF4DFFEA0, 0xB97EB3EB, 0xFDFF84DD, 0xFF8B14F1, 0xE96B0572, 0xF64B508C, 0xAE220A6E, 0x4423AE5A, 0xC2BECE5E, 0xDE27567C, 0xFC935C63, 0x47075573, 0xE65B27F0, 0xE121FD22, 0xF2668753, 0x2DEBF5D7, 0x8347E08D, 0xAC5EDA03, 0x2A7CEBE9, 0x3FE8D92E, 0x23542FE4, 0x1FA7BD50, 0xCF9B4102, 0x9D0DBA39, 0x9CB8902A, 0xA7249D8B, 0x0F6D667A, 0x5EBFA9EC, 0x6A594DF2, 0x79600938, 0x023B7591, 0xEA2C79C8, 0xC99D07EA, 0x64CB5EE1, 0x1A9CAB3D, 0x76DB9527, 0xC08E012F, 0x3DFB481A, 0x872F22E7, 0x2948D15C, 0xA4782C79, 0x6F50D232, 0x78F0728A, 0x5A87AAB1, 0xC4E2C19C, 0xEE767387, 0x1B2A1864, 0x7B8D10D3, 0xD1713161, 0x0EEAC456, 0xD8799E06, 0xB645B548, 0x4043CB65, 0xA874FB29, 0x4B12D030, 0x7D687413, 0x18EF9A1F, 0xD7631D4C, 0x5829C7DA, 0xCDFA30FA, 0xC5084BB0, 0x92CD20E2, 0xD4C16940, 0x03283EC0, 0xA917813F, 0x9A587D01, 0x70041F8F, 0xDC6AB1DC, 0xDDAEE3D5, 0x31829742, 0x198C022D, 0x1C9EAFCB, 0x5BBC6C49, 0xD3D3293A, 0x16D50007, 0x04BB8820, 0x3C5C2A41, 0x37EE7AF8, 0x8EB04025, 0x9313ECBA, 0xBFFC4799, 0x8955A744, 0xEF85D633, 0x504499A7, 0xA6CA6A86, 0xBB3D3297, 0xB34A8236, 0x6DCCBE4F, 0x06143394, 0xCE19FC7B, 0xCCC3C6C6, 0xE36254AE, 0x77B7EDA1, 0xA133DD9E, 0xEBF9356A, 0x513CCF88, 0xE2A1B417, 0x972EE5BD, 0x853824CD, 0x5752F4EE, 0x6C1142E8, 0x3EA4F309, 0xB2B5934A, 0xDFD628AA, 0x59ACEA3E, 0xA01EB92C, 0x389964BC, 0xDA305DD4, 0x019A59B7, 0x11D2CA93, 0xFAA6D3B9, 0x4E772ECA, 0x72651776, 0xFB4E5B0E, 0xA38F91A8, 0x1D0663B5, 0x30F4F192, 0xB50051B6, 0xB716CCB3, 0x4ABD1B59, 0x146C5F26, 0xF134E2DE, 0x00F67C6C, 0xB0E1B795, 0x98AA4EC7, 0x0CC73B34, 0x654276A3, 0x8D1BA871, 0x740A5216, 0xE0D01A23, 0x9ED161D6, 0x9F36A324, 0x993EBB7F, 0xFEB9491B, 0x365DDCDB, 0x810CFFC5, 0x71EC0382, 0x2249E7BF, 0x48817046, 0xF3A24A5B, 0x4288E4D9, 0x0BF5C243, 0x257FE151, 0x95B64C0D, 0x4164F066, 0xAAF7DB08, 0x73B1119D, 0x8F9F7BB8, 0xD6844596, 0xF07A34A6, 0x53943D0A, 0xF9DD166D, 0x7A8957AF, 0xF8BA3CE5, 0x27C9621E, 0x5CDAE910, 0xC8518998, 0x941538FE, 0x136115D8, 0xABA8443C, 0x4D01F931, 0x34EDF760, 0xB45F266B, 0xD5D4DE14, 0x52D8AC35, 0x15CFD885, 0xCBC5CD21, 0x4CD76D4D, 0x7C80EF54, 0xBC92EE75, 0x1E56A1F6 }, { 0xBAA20B6C, 0x9FFBAD26, 0xE1F7D738, 0x794AEC8D, 0xC9E9CF3C, 0x8A9A7846, 0xC57C4685, 0xB9A92FED, 0x29CB141F, 0x52F9DDB7, 0xF68BA6BC, 0x19CCC020, 0x4F584AAA, 0x3BF6A596, 0x003B7CF7, 0x54F0CE9A, 0xA7EC4303, 0x46CF0077, 0x78D33AA1, 0x215247D9, 0x74BCDF91, 0x08381D30, 0xDAC43E40, 0x64872531, 0x0BEFFE5F, 0xB317F457, 0xAEBB12DA, 0xD5D0D67B, 0x7D75C6B4, 0x42A6D241, 0x1502D0A9, 0x3FD97FFF, 0xC6C3ED28, 0x81868D0A, 0x92628BC5, 0x86679544, 0xFD1867AF, 0x5CA3EA61, 0x568D5578, 0x4A2D71F4, 0x43C9D549, 0x8D95DE2B, 0x6E5C74A0, 0x9120FFC7, 0x0D05D14A, 0xA93049D3, 0xBFA80E17, 0xF4096810, 0x043F5EF5, 0xA673B4F1, 0x6D780298, 0xA4847783, 0x5EE726FB, 0x9934C281, 0x220A588C, 0x384E240F, 0x933D5C69, 0x39E5EF47, 0x26E8B8F3, 0x4C1C6212, 0x8040F75D, 0x074B7093, 0x6625A8D7, 0x36298945, 0x76285088, 0x651D37C3, 0x24F5274D, 0xDBCA3DAB, 0x186B7EE1, 0xD80F8182, 0x14210C89, 0x943A3075, 0x4E6E11C4, 0x4D7E6BAD, 0xF05064C8, 0x025DCD97, 0x4BC10302, 0x7CEDE572, 0x8F90A970, 0xAB88EEBA, 0xB5998029, 0x5124D839, 0xB0EEB6A3, 0x89DDABDC, 0xE8074D76, 0xA1465223, 0x32518CF2, 0x9D39D4EB, 0xC0D84524, 0xE35E6EA8, 0x7ABF3804, 0x113E2348, 0x9AE6069D, 0xB4DFDABB, 0xA8C5313F, 0x23EA3F79, 0x530E36A2, 0xA5FD228B, 0x95D1D350, 0x2B14CC09, 0x40042956, 0x879D05CC, 0x2064B9CA, 0xACACA40E, 0xB29C846E, 0x9676C9E3, 0x752B7B8A, 0x7BE2BCC2, 0x6BD58F5E, 0xD48F4C32, 0x606835E4, 0x9CD7C364, 0x2C269B7A, 0x3A0D079C, 0x73B683FE, 0x45374F1E, 0x10AFA242, 0x577F8666, 0xDDAA10F6, 0xF34F561C, 0x3D355D6B, 0xE47048AE, 0xAA13C492, 0x050344FD, 0x2AAB5151, 0xF5B26AE5, 0xED919A59, 0x5AC67900, 0xF1CDE380, 0x0C79A11B, 0x351533FC, 0xCD4D8E36, 0x1F856005, 0x690B9FDD, 0xE736DCCF, 0x1D47BF6A, 0x7F66C72A, 0x85F21B7F, 0x983CBDB6, 0x01EBBEBF, 0x035F3B99, 0xEB111F34, 0x28CEFDC6, 0x5BFC9ECD, 0xF22EACB0, 0x9E41CBB2, 0xE0F8327C, 0x82E3E26F, 0xFC43FC86, 0xD0BA66DF, 0x489EF2A7, 0xD9E0C81D, 0x68690D52, 0xCC451367, 0xC2232E16, 0xE95A7335, 0x0FDAE19B, 0xFF5B962C, 0x97596527, 0xC46DB333, 0x3ED4C562, 0xC14C9D9E, 0x5D6FAA21, 0x638E940D, 0xF9316D58, 0x47B3B0EA, 0x30FFCAD2, 0xCE1BBA7D, 0x1E6108E6, 0x2E1EA33D, 0x507BF05B, 0xFAFEF94B, 0xD17DE8E2, 0x5598B214, 0x1663F813, 0x17D25A2D, 0xEEFA5FF9, 0x582F4E37, 0x12128773, 0xFEF17AB8, 0x06005322, 0xBB32BBC9, 0x8C898508, 0x592C15F0, 0xD38A4054, 0x4957B7D6, 0xD2B891DB, 0x37BD2D3E, 0x34AD20CB, 0x622288E9, 0x2DC7345A, 0xAFB416C0, 0x1CF459B1, 0xDC7739FA, 0x0A711A25, 0x13E18A0C, 0x5F72AF4C, 0x6AC8DB11, 0xBE53C18E, 0x1AA569B9, 0xEF551EA4, 0xA02A429F, 0xBD16E790, 0x7EB9171A, 0x77D693D8, 0x8E06993A, 0x9BDE7560, 0xE5801987, 0xC37A09BE, 0xB8DB76AC, 0xE2087294, 0x6C81616D, 0xB7F30FE7, 0xBC9B82BD, 0xFBA4E4D4, 0xC7B1012F, 0xA20C043B, 0xDE9FEBD0, 0x2F9297CE, 0xE610AEF8, 0x70B06F19, 0xC86AE00B, 0x0E01988F, 0x41192AE0, 0x448C1CB5, 0xADBE92EE, 0x7293A007, 0x1B54B5B3, 0xD61F63D1, 0xEAE40A74, 0x61A72B55, 0xEC83A7D5, 0x88942806, 0x90A07DA5, 0xD7424B95, 0x67745B4E, 0xA31A1853, 0xCA6021EF, 0xDFB56C4F, 0xCBC2D915, 0x3C48E918, 0x8BAE3C63, 0x6F659C71, 0xF8B754C1, 0x2782F3DE, 0xF796F168, 0x71492C84, 0x33C0F5A6, 0x3144F6EC, 0x25DC412E, 0xB16C5743, 0x83A1FA7E, 0x0997B101, 0xB627E6E8, 0xCF33905C, 0x8456FB65 }, { 0xB29BEA74, 0xC35DA605, 0x305C1CA3, 0xD2E9F5BC, 0x6FD5BFF4, 0xFF347703, 0xFC45B163, 0xF498E068, 0xB71229FC, 0x81ACC3FB, 0x78538A8B, 0x984ECF81, 0xA5DA47A4, 0x8F259EEF, 0x6475DC65, 0x081865B9, 0x49E14A3C, 0x19E66079, 0xD382E91B, 0x5B109794, 0x3F9F81E1, 0x4470A388, 0x41601ABE, 0xAAF9F407, 0x8E175EF6, 0xED842297, 0x893A4271, 0x1790839A, 0xD566A99E, 0x6B417DEE, 0x75C90D23, 0x715EDB31, 0x723553F7, 0x9AFB50C9, 0xFBC5F600, 0xCD3B6A4E, 0x97ED0FBA, 0x29689AEC, 0x63135C8E, 0xF0E26C7E, 0x0692AE7F, 0xDBB208FF, 0x2EDE3E9B, 0x6A65BEBD, 0xD40867E9, 0xC954AFC5, 0x73B08201, 0x7FFDF809, 0x1195C24F, 0x1CA5ADCA, 0x74BD6D1F, 0xB393C455, 0xCADFD3FA, 0x99F13011, 0x0EBCA813, 0x60E791B8, 0x6597AC7A, 0x18A7E46B, 0x09CB49D3, 0x0B27DF6D, 0xCFE52F87, 0xCEF66837, 0xE6328035, 0xFA87C592, 0x37BAFF93, 0xD71FCC99, 0xDCAB205C, 0x4D7A5638, 0x48012510, 0x62797558, 0xB6CF1FE5, 0xBC311834, 0x9C2373AC, 0x14EC6175, 0xA439CBDF, 0x54AFB0EA, 0xD686960B, 0xFDD0D47B, 0x7B063902, 0x8B78BAC3, 0x26C6A4D5, 0x5C0055B6, 0x2376102E, 0x0411783E, 0x2AA3F1CD, 0x51FC6EA8, 0x701CE243, 0x9B2A0ABB, 0x0AD93733, 0x6E80D03D, 0xAF6295D1, 0xF629896F, 0xA30B0648, 0x463D8DD4, 0x963F84CB, 0x01FF94F8, 0x8D7FEFDC, 0x553611C0, 0xA97C1719, 0xB96AF759, 0xE0E3C95E, 0x0528335B, 0x21FE5925, 0x821A5245, 0x807238B1, 0x67F23DB5, 0xEA6B4EAB, 0x0DA6F985, 0xAB1BC85A, 0xEF8C90E4, 0x4526230E, 0x38EB8B1C, 0x1B91CD91, 0x9FCE5F0C, 0xF72CC72B, 0xC64F2617, 0xDAF7857D, 0x7D373CF1, 0x28EAEDD7, 0x203887D0, 0xC49A155F, 0xA251B3B0, 0xF2D47AE3, 0x3D9EF267, 0x4A94AB2F, 0x7755A222, 0x0205E329, 0xC28FA7A7, 0xAEC1FE51, 0x270F164C, 0x8C6D01BF, 0x53B5BC98, 0xC09D3FEB, 0x834986CC, 0x4309A12C, 0x578B2A96, 0x3BB74B86, 0x69561B4A, 0x037E32F3, 0xDE335B08, 0xC5156BE0, 0xE7EF09AD, 0x93B834C7, 0xA7719352, 0x59302821, 0xE3529D26, 0xF961DA76, 0xCB142C44, 0xA0F3B98D, 0x76502457, 0x945A414B, 0x078EEB12, 0xDFF8DE69, 0xEB6C8C2D, 0xBDA90C4D, 0xE9C44D16, 0x168DFD66, 0xAD64763B, 0xA65FD764, 0x95A29C06, 0x32D7713F, 0x40F0B277, 0x224AF08F, 0x004CB5E8, 0x92574814, 0x8877D827, 0x3E5B2D04, 0x68C2D5F2, 0x86966273, 0x1D433ADA, 0x8774988A, 0x3C0E0BFE, 0xDDAD581D, 0x2FD654ED, 0x0F4769FD, 0xC181EE9D, 0x5FD88F61, 0x341DBB3A, 0x528543F9, 0xD92235CF, 0x1EA82EB4, 0xB5CD790F, 0x91D24F1E, 0xA869E6C2, 0x61F474D2, 0xCC205ADD, 0x0C7BFBA9, 0xBF2B0489, 0xB02D72D8, 0x2B46ECE6, 0xE4DCD90A, 0xB8A11440, 0xEE8A63B7, 0x854DD1A1, 0xD1E00583, 0x42B40E24, 0x9E8964DE, 0xB4B35D78, 0xBEC76F6E, 0x24B9C620, 0xD8D399A6, 0x5ADB2190, 0x2DB12730, 0x3A5866AF, 0x58C8FADB, 0x5D8844E7, 0x8A4BF380, 0x15A01D70, 0x79F5C028, 0x66BE3B8C, 0xF3E42B53, 0x56990039, 0x2C0C3182, 0x5E16407C, 0xECC04515, 0x6C440284, 0x4CB6701A, 0x13BFC142, 0x9D039F6A, 0x4F6E92C8, 0xA1407C62, 0x8483A095, 0xC70AE1C4, 0xE20213A2, 0xBACAFC41, 0x4ECC12B3, 0x4BEE3646, 0x1FE807AE, 0x25217F9C, 0x35DDE5F5, 0x7A7DD6CE, 0xF89CCE50, 0xAC07B718, 0x7E73D2C6, 0xE563E76C, 0x123CA536, 0x3948CA56, 0x9019DD49, 0x10AA88D9, 0xC82451E2, 0x473EB6D6, 0x506FE854, 0xE8BB03A5, 0x332F4C32, 0xFE1E1E72, 0xB1AE572A, 0x7C0D7BC1, 0xE1C37EB2, 0xF542AA60, 0xF1A48EA0, 0xD067B89F, 0xBBFA195D, 0x1A049B0D, 0x315946AA, 0x36D1B447, 0x6D2EBDF0 }, { 0x0D188A6D, 0x12CEA0DB, 0x7E63740E, 0x6A444821, 0x253D234F, 0x6FFC6597, 0x94A6BDEF, 0x33EE1B2F, 0x0A6C00C0, 0x3AA336B1, 0x5AF55D17, 0x265FB3DC, 0x0E89CF4D, 0x0786B008, 0xC80055B8, 0x6B17C3CE, 0x72B05A74, 0xD21A8D78, 0xA6B70840, 0xFE8EAE77, 0xED69565C, 0x55E1BCF4, 0x585C2F60, 0xE06F1A62, 0xAD67C0CD, 0x7712AF88, 0x9CC26ACA, 0x1888053D, 0x37EB853E, 0x9215ABD7, 0xDE30ADFC, 0x1F1038E6, 0x70C51C8A, 0x8D586C26, 0xF72BDD90, 0x4DC3CE15, 0x68EAEEFA, 0xD0E9C8B9, 0x200F9C44, 0xDDD141BA, 0x024BF1D3, 0x0F64C9D4, 0xC421E9E9, 0x9D11C14C, 0x9A0DD9E4, 0x5F92EC19, 0x1B980DF0, 0x1DCC4542, 0xB8FE8C56, 0x0C9C9167, 0x4E81EB49, 0xCA368F27, 0xE3603B37, 0xEA08ACCC, 0xAC516992, 0xC34F513B, 0x804D100D, 0x6EDCA4C4, 0xFC912939, 0x29D219B0, 0x278AAA3C, 0x4868DA7D, 0x54E890B7, 0xB46D735A, 0x514589AA, 0xD6C630AF, 0x4980DFE8, 0xBE3CCC55, 0x59D41202, 0x650C078B, 0xAF3A9E7B, 0x3ED9827A, 0x9E79FC6E, 0xAADBFBAE, 0xC5F7D803, 0x3DAF7F50, 0x67B4F465, 0x73406E11, 0x39313F8C, 0x8A6E6686, 0xD8075F1F, 0xD3CBFED1, 0x69C7E49C, 0x930581E0, 0xE4B1A5A8, 0xBBC45472, 0x09DDBF58, 0xC91D687E, 0xBDBFFDA5, 0x88C08735, 0xE9E36BF9, 0xDB5EA9B6, 0x95559404, 0x08F432FB, 0xE24EA281, 0x64663579, 0x000B8010, 0x7914E7D5, 0x32FD0473, 0xD1A7F0A4, 0x445AB98E, 0xEC72993F, 0xA29A4D32, 0xB77306D8, 0xC7C97CF6, 0x7B6AB645, 0xF5EF7ADF, 0xFB2E15F7, 0xE747F757, 0x5E944354, 0x234A2669, 0x47E46359, 0x9B9D11A9, 0x40762CED, 0x56F1DE98, 0x11334668, 0x890A9A70, 0x1A296113, 0xB3BD4AF5, 0x163B7548, 0xD51B4F84, 0xB99B2ABC, 0x3CC1DC30, 0xA9F0B56C, 0x812272B2, 0x0B233A5F, 0xB650DBF2, 0xF1A0771B, 0x36562B76, 0xDC037B0F, 0x104C97FF, 0xC2EC98D2, 0x90596F22, 0x28B6620B, 0xDF42B212, 0xFDBC4243, 0xF3FB175E, 0x4A2D8B00, 0xE8F3869B, 0x30D69BC3, 0x853714C8, 0xA7751D2E, 0x31E56DEA, 0xD4840B0C, 0x9685D783, 0x068C9333, 0x8FBA032C, 0x76D7BB47, 0x6D0EE22B, 0xB546794B, 0xD971B894, 0x8B09D253, 0xA0AD5761, 0xEE77BA06, 0x46359F31, 0x577CC7EC, 0x52825EFD, 0xA4BEED95, 0x9825C52A, 0xEB48029A, 0xBAAE59F8, 0xCF490EE1, 0xBC990164, 0x8CA49DFE, 0x4F38A6E7, 0x2BA98389, 0x8228F538, 0x199F64AC, 0x01A1CAC5, 0xA8B51641, 0x5CE72D01, 0x8E5DF26B, 0x60F28E1E, 0xCD5BE125, 0xE5B376BF, 0x1C8D3116, 0x7132CBB3, 0xCB7AE320, 0xC0FA5366, 0xD7653E34, 0x971C88C2, 0xC62C7DD0, 0x34D0A3DA, 0x868F6709, 0x7AE6FA8F, 0x22BBD523, 0x66CD3D5B, 0x1EF9288D, 0xF9CF58C1, 0x5B784E80, 0x7439A191, 0xAE134C36, 0x9116C463, 0x2E9E1396, 0xF8611F3A, 0x2D2F3307, 0x247F37DD, 0xC1E2FF9D, 0x43C821E5, 0x05ED5CAB, 0xEF74E80A, 0x4CCA6028, 0xF0AC3CBD, 0x5D874B29, 0x6C62F6A6, 0x4B2A2EF3, 0xB1AA2087, 0x62A5D0A3, 0x0327221C, 0xB096B4C6, 0x417EC693, 0xABA840D6, 0x789725EB, 0xF4B9E02D, 0xE6E00975, 0xCC04961A, 0x63F624BB, 0x7FA21ECB, 0x2C01EA7F, 0xB2415005, 0x2A8BBEB5, 0x83B2B14E, 0xA383D1A7, 0x5352F96A, 0x043ECDAD, 0xCE1918A1, 0xFA6BE6C9, 0x50DEF36F, 0xF6B80CE2, 0x4543EF7C, 0x9953D651, 0xF257955D, 0x87244914, 0xDA1E0A24, 0xFFDA4785, 0x14D327A2, 0x3B93C29F, 0x840684B4, 0x61AB71A0, 0x9F7B784A, 0x2FD570CF, 0x15955BDE, 0x38F8D471, 0x3534A718, 0x133FB71D, 0x3FD80F52, 0x4290A8BE, 0x75FF44C7, 0xA554E546, 0xE1023499, 0xBF2652E3, 0x7D20399E, 0xA1DF7E82, 0x177092EE, 0x217DD3F1, 0x7C1FF8D9 }, { 0x12113F2E, 0xBFBD0785, 0xF11793FB, 0xA5BFF566, 0x83C7B0E5, 0x72FB316B, 0x75526A9A, 0x41E0E612, 0x7156BA09, 0x53CE7DEE, 0x0AA26881, 0xA43E0D7D, 0x3DA73CA3, 0x182761ED, 0xBD5077FF, 0x56DB4AA0, 0xE792711C, 0xF0A4EB1D, 0x7F878237, 0xEC65C4E8, 0x08DC8D43, 0x0F8CE142, 0x8258ABDA, 0xF4154E16, 0x49DEC2FD, 0xCD8D5705, 0x6C2C3A0F, 0x5C12BB88, 0xEFF3CDB6, 0x2C89ED8C, 0x7BEBA967, 0x2A142157, 0xC6D0836F, 0xB4F97E96, 0x6931E969, 0x514E6C7C, 0xA7792600, 0x0BBBF780, 0x59671BBD, 0x0707B676, 0x37482D93, 0x80AF1479, 0x3805A60D, 0xE1F4CAC1, 0x580B3074, 0x30B8D6CE, 0x05A304BE, 0xD176626D, 0xEBCA97F3, 0xBB201F11, 0x6A1AFE23, 0xFFAA86E4, 0x62B4DA49, 0x1B6629F5, 0xF5D9E092, 0xF37F3DD1, 0x619BD45B, 0xA6EC8E4F, 0x29C80939, 0x0C7C0C34, 0x9CFE6E48, 0xE65FD3AC, 0x73613B65, 0xB3C669F9, 0xBE2E8A9E, 0x286F9678, 0x5797FD13, 0x99805D75, 0xCFB641C5, 0xA91074BA, 0x6343AF47, 0x6403CB46, 0x8894C8DB, 0x2663034C, 0x3C40DC5E, 0x00995231, 0x96789AA2, 0x2EFDE4B9, 0x7DC195E1, 0x547DADD5, 0x06A8EA04, 0xF2347A63, 0x5E0DC6F7, 0x8462DFC2, 0x1E6B2C3C, 0x9BD275B3, 0x91D419E2, 0xBCEFD17E, 0xB9003924, 0xD07E7320, 0xDEF0495C, 0xC36AD00E, 0x1785B1AB, 0x92E20BCF, 0xB139F0E9, 0x675BB9A1, 0xAECFA4AF, 0x132376CB, 0xE84589D3, 0x79A05456, 0xA2F860BC, 0x1AE4F8B5, 0x20DF4DB4, 0xA1E1428B, 0x3BF60A1A, 0x27FF7BF1, 0xCB44C0E7, 0xF7F587C4, 0x1F3B9B21, 0x94368F01, 0x856E23A4, 0x6F93DE3F, 0x773F5BBF, 0x8B22056E, 0xDF41F654, 0xB8246FF4, 0x8D57BFF2, 0xD57167EA, 0xC5699F22, 0x40734BA7, 0x5D5C2772, 0x033020A8, 0xE30A7C4D, 0xADC40FD6, 0x76353441, 0x5AA5229B, 0x81516590, 0xDA49F14E, 0x4FA672A5, 0x4D9FAC5F, 0x154BE230, 0x8A7A5CC0, 0xCE3D2F84, 0xCCA15514, 0x5221360C, 0xAF0FB81E, 0x5BDD5873, 0xF6825F8F, 0x1113D228, 0x70AD996C, 0x93320051, 0x60471C53, 0xE9BA567B, 0x3A462AE3, 0x5F55E72D, 0x1D3C5AD7, 0xDCFC45EC, 0x34D812EF, 0xFA96EE1B, 0x369D1EF8, 0xC9B1A189, 0x7C1D3555, 0x50845EDC, 0x4BB31877, 0x8764A060, 0x8C9A9415, 0x230E1A3A, 0xB05E9133, 0x242B9E03, 0xA3B99DB7, 0xC2D7FB0A, 0x3333849D, 0xD27278D4, 0xB5D3EFA6, 0x78AC28AD, 0xC7B2C135, 0x0926ECF0, 0xC1374C91, 0x74F16D98, 0x2274084A, 0x3F6D9CFA, 0x7AC0A383, 0xB73AFF1F, 0x3909A23D, 0x9F1653AE, 0x4E2F3E71, 0xCA5AB22A, 0xE01E3858, 0x90C5A7EB, 0x3E4A17DF, 0xAA987FB0, 0x488BBD62, 0xB625062B, 0x2D776BB8, 0x43B5FC08, 0x1490D532, 0xD6D12495, 0x44E89845, 0x2FE60118, 0x9D9EF950, 0xAC38133E, 0xD3864329, 0x017B255A, 0xFDC2DD26, 0x256851E6, 0x318E7086, 0x2BFA4861, 0x89EAC706, 0xEE5940C6, 0x68C3BC2F, 0xE260334B, 0x98DA90BB, 0xF818F270, 0x4706D897, 0x212D3799, 0x4CF7E5D0, 0xD9C9649F, 0xA85DB5CD, 0x35E90E82, 0x6B881152, 0xAB1C02C7, 0x46752B02, 0x664F598E, 0x45AB2E64, 0xC4CDB4B2, 0xBA42107F, 0xEA2A808A, 0x971BF3DE, 0x4A54A836, 0x4253AECC, 0x1029BE68, 0x6DCC9225, 0xE4BCA56A, 0xC0AE50B1, 0x7E011D94, 0xE59C162C, 0xD8E5C340, 0xD470FA0B, 0xB2BE79DD, 0xD783889C, 0x1CEDE8F6, 0x8F4C817A, 0xDDB785C9, 0x860232D8, 0x198AAAD9, 0xA0814738, 0x3219CFFC, 0x169546D2, 0xFC0CB759, 0x55911510, 0x04D5CEC3, 0xED08CC3B, 0x0D6CF427, 0xC8E38CCA, 0x0EEEE3FE, 0x9EE7D7C8, 0xF9F24FA9, 0xDB04B35D, 0x9AB0C9E0, 0x651F4417, 0x028F8B07, 0x6E28D9AA, 0xFBA96319, 0x8ED66687, 0xFECBC58D, 0x954DDB44 }, { 0x7B0BDFFE, 0x865D16B1, 0x49A058C0, 0x97ABAA3F, 0xCAACC75D, 0xABA6C17D, 0xF8746F92, 0x6F48AEED, 0x8841D4B5, 0xF36A146A, 0x73C390AB, 0xE6FB558F, 0x87B1019E, 0x26970252, 0x246377B2, 0xCBF676AE, 0xF923DB06, 0xF7389116, 0x14C81A90, 0x83114EB4, 0x8B137559, 0x95A86A7A, 0xD5B8DA8C, 0xC4DF780E, 0x5A9CB3E2, 0xE44D4062, 0xE8DC8EF6, 0x9D180845, 0x817AD18B, 0xC286C85B, 0x251F20DE, 0xEE6D5933, 0xF6EDEF81, 0xD4D16C1E, 0xC94A0C32, 0x8437FD22, 0x3271EE43, 0x42572AEE, 0x5F91962A, 0x1C522D98, 0x59B23F0C, 0xD86B8804, 0x08C63531, 0x2C0D7A40, 0xB97C4729, 0x04964DF9, 0x13C74A17, 0x5878362F, 0x4C808CD6, 0x092CB1E0, 0x6DF02885, 0xA0C2105E, 0x8ABA9E68, 0x64E03057, 0xE5D61325, 0x0E43A628, 0x16DBD62B, 0x2733D90B, 0x3AE57283, 0xC0C1052C, 0x4B6FB620, 0x37513953, 0xFC898BB3, 0x471B179F, 0xDF6E66B8, 0xD32142F5, 0x9B30FAFC, 0x4ED92549, 0x105C6D99, 0x4ACD69FF, 0x2B1A27D3, 0x6BFCC067, 0x6301A278, 0xAD36E6F2, 0xEF3FF64E, 0x56B3CADB, 0x0184BB61, 0x17BEB9FD, 0xFAEC6109, 0xA2E1FFA1, 0x2FD224F8, 0x238F5BE6, 0x8F8570CF, 0xAEB5F25A, 0x4F1D3E64, 0x4377EB24, 0x1FA45346, 0xB2056386, 0x52095E76, 0xBB7B5ADC, 0x3514E472, 0xDDE81E6E, 0x7ACEA9C4, 0xAC15CC48, 0x71C97D93, 0x767F941C, 0x911052A2, 0xFFEA09BF, 0xFE3DDCF0, 0x15EBF3AA, 0x9235B8BC, 0x75408615, 0x9A723437, 0xE1A1BD38, 0x33541B7E, 0x1BDD6856, 0xB307E13E, 0x90814BB0, 0x51D7217B, 0x0BB92219, 0x689F4500, 0xC568B01F, 0x5DF3D2D7, 0x3C0ECD0D, 0x2A0244C8, 0x852574E8, 0xE72F23A9, 0x8E26ED02, 0x2D92CBDD, 0xDABC0458, 0xCDF5FEB6, 0x9E4E8DCC, 0xF4F1E344, 0x0D8C436D, 0x4427603B, 0xBDD37FDA, 0x80505F26, 0x8C7D2B8E, 0xB73273C5, 0x397362EA, 0x618A3811, 0x608BFB88, 0x06F7D714, 0x212E4677, 0x28EFCEAD, 0x076C0371, 0x36A3A4D9, 0x5487B455, 0x3429A365, 0x65D467AC, 0x78EE7EEB, 0x99BF12B7, 0x4D129896, 0x772A5601, 0xCCE284C7, 0x2ED85C21, 0xD099E8A4, 0xA179158A, 0x6AC0AB1A, 0x299A4807, 0xBE67A58D, 0xDC19544A, 0xB8949B54, 0x8D315779, 0xB6F849C1, 0x53C5AC34, 0x66DE92A5, 0xF195DD13, 0x318D3A73, 0x301EC542, 0x0CC40DA6, 0xF253ADE4, 0x467EE566, 0xEA5585EC, 0x3BAF19BB, 0x7DE9F480, 0x79006E7C, 0xA9B7A197, 0xA44BD8F1, 0xFB2BA739, 0xEC342FD4, 0xED4FD32D, 0x3D1789BA, 0x400F5D7F, 0xC798F594, 0x4506A847, 0x034C0A95, 0xE2162C9D, 0x55A9CFD0, 0x692D832E, 0xCF9DB2CA, 0x5E2287E9, 0xD2610EF3, 0x1AE7ECC2, 0x48399CA0, 0xA7E4269B, 0x6EE3A0AF, 0x7065BFE1, 0xA6FFE708, 0x2256804C, 0x7476E21B, 0x41B0796C, 0x7C243B05, 0x000A950F, 0x1858416B, 0xF5A53C89, 0xE9FEF823, 0x3F443275, 0xE0CBF091, 0x0AF27B84, 0x3EBB0F27, 0x1DE6F7F4, 0xC31C29F7, 0xB166DE3D, 0x12932EC3, 0x9C0C0674, 0x5CDA81B9, 0xD1BD9D12, 0xAFFD7C82, 0x8962BCA7, 0xA342C4A8, 0x62457151, 0x82089F03, 0xEB49C670, 0x5B5F6530, 0x7E28BAD2, 0x20880BA3, 0xF0FAAFCD, 0xCE82B56F, 0x0275335C, 0xC18E8AFB, 0xDE601D69, 0xBA9B820A, 0xC8A2BE4F, 0xD7CAC335, 0xD9A73741, 0x115E974D, 0x7F5AC21D, 0x383BF9C6, 0xBCAEB75F, 0xFD0350CE, 0xB5D06B87, 0x9820E03C, 0x72D5F163, 0xE3644FC9, 0xA5464C4B, 0x57048FCB, 0x9690C9DF, 0xDBF9EAFA, 0xBFF4649A, 0x053C00E3, 0xB4B61136, 0x67593DD1, 0x503EE960, 0x9FB4993A, 0x19831810, 0xC670D518, 0xB05B51D8, 0x0F3A1CE5, 0x6CAA1F9C, 0xAACC31BE, 0x949ED050, 0x1EAD07E7, 0xA8479ABD, 0xD6CFFCD5, 0x936993EF }, { 0x472E91CB, 0x5444B5B6, 0x62BE5861, 0x1BE102C7, 0x63E4B31E, 0xE81F71B7, 0x9E2317C9, 0x39A408AE, 0x518024F4, 0x1731C66F, 0x68CBC918, 0x71FB0C9E, 0xD03B7FDD, 0x7D6222EB, 0x9057EDA3, 0x1A34A407, 0x8CC2253D, 0xB6F6979D, 0x835675DC, 0xF319BE9F, 0xBE1CD743, 0x4D32FEE4, 0x77E7D887, 0x37E9EBFD, 0x15F851E8, 0x23DC3706, 0x19D78385, 0xBD506933, 0xA13AD4A6, 0x913F1A0E, 0xDDE560B9, 0x9A5F0996, 0xA65A0435, 0x48D34C4D, 0xE90839A7, 0x8ABBA54E, 0x6FD13CE1, 0xC7EEBD3C, 0x0E297602, 0x58B9BBB4, 0xEF7901E6, 0x64A28A62, 0xA509875A, 0xF8834442, 0x2702C709, 0x07353F31, 0x3B39F665, 0xF5B18B49, 0x4010AE37, 0x784DE00B, 0x7A1121E9, 0xDE918ED3, 0xC8529DCD, 0x816A5D05, 0x02ED8298, 0x04E3DD84, 0xFD2BC3E2, 0xAF167089, 0x96AF367E, 0xA4DA6232, 0x18FF7325, 0x05F9A9F1, 0x4FEFB9F9, 0xCD94EAA5, 0xBFAA5069, 0xA0B8C077, 0x60D86F57, 0xFE71C813, 0x29EBD2C8, 0x4CA86538, 0x6BF1A030, 0xA237B88A, 0xAA8AF41D, 0xE1F7B6EC, 0xE214D953, 0x33057879, 0x49CAA736, 0xFA45CFF3, 0xC063B411, 0xBA7E27D0, 0x31533819, 0x2A004AC1, 0x210EFC3F, 0x2646885E, 0x66727DCF, 0x9D7FBF54, 0xA8DD0EA8, 0x3447CACE, 0x3F0C14DB, 0xB8382AAC, 0x4ACE3539, 0x0A518D51, 0x95178981, 0x35AEE2CA, 0x73F0F7E3, 0x94281140, 0x59D0E523, 0xD292CB88, 0x565D1B27, 0x7EC8FBAF, 0x069AF08D, 0xC127FD24, 0x0BC77B10, 0x5F03E7EF, 0x453E99BA, 0xEED9FF7F, 0x87B55215, 0x7915AB4C, 0xD389A358, 0x5E75CE6D, 0x28D655C0, 0xDAD26C73, 0x2E2510FF, 0x9FA7EECC, 0x1D0629C3, 0xDC9C9C46, 0x2D67ECD7, 0xE75E94BD, 0x3D649E2A, 0x6C413A2B, 0x706F0D7C, 0xDFB0127B, 0x4E366B55, 0x2C825650, 0x24205720, 0xB5C998F7, 0x3E95462C, 0x756E5C72, 0x3259488F, 0x11E8771A, 0xA7C0A617, 0x577663E5, 0x089B6401, 0x8EAB1941, 0xAE55EF8C, 0x3AAC5460, 0xD4E6262F, 0x5D979A47, 0xB19823B0, 0x7F8D6A0C, 0xFFA08683, 0x0170CD0F, 0x858CD5D8, 0x53961C90, 0xC4C61556, 0x41F2F226, 0xCFCD062D, 0xF24C03B8, 0xEA81DF5B, 0x7BE2FA52, 0xB361F98B, 0xC2901316, 0x55BA4BBC, 0x93B234A9, 0x0FBC6603, 0x80A96822, 0x6D60491F, 0x22BD00F8, 0xBCAD5AAD, 0x52F3F13B, 0x42FD2B28, 0xB41DD01C, 0xC52C93BF, 0xFC663094, 0x8F58D100, 0x43FECC08, 0xC6331E5D, 0xE6480F66, 0xCA847204, 0x4BDF1DA0, 0x30CC2EFB, 0x13E02DEA, 0xFB49AC45, 0xF9D4434F, 0xF47C5B9C, 0x148879C2, 0x039FC234, 0xA3DB9BFC, 0xD1A1DC5C, 0x763D7CD4, 0xED6D2F93, 0xAB13AF6E, 0x1E8E054A, 0xD68F4F9A, 0xC30484B3, 0xD7D50AFA, 0x6930855F, 0xCC07DB95, 0xCE746DB1, 0x744E967D, 0xF16CF575, 0x8643E8B5, 0xF0EAE38E, 0xE52DE1D1, 0x6587DAE0, 0x0C4B8121, 0x1C7AC567, 0xAC0DB20A, 0x36C3A812, 0x5B1A4514, 0xA9A3F868, 0xB9263BAA, 0xCB3CE9D2, 0xE44FB1A4, 0x9221BC82, 0xB29390FE, 0x6AB41863, 0x974A3E2E, 0x89F531C5, 0x255CA13E, 0x8B65D348, 0xEC248F78, 0xD8FC16F0, 0x50ECDEEE, 0x09010792, 0x3C7D1FB2, 0xEBA5426B, 0x847B417A, 0x468B40D9, 0x8DC4E680, 0x7CC1F391, 0x2F1EB086, 0x6E5BAA6A, 0xE0B395DA, 0xE31B2CF6, 0xD9690B0D, 0x729EC464, 0x38403DDE, 0x610B80A2, 0x5CF433AB, 0xB0785FC4, 0xD512E4C6, 0xBBB7D699, 0x5A86591B, 0x10CF5376, 0x12BF9F4B, 0x980FBAA1, 0x992A4E70, 0x20FA7AE7, 0xF7996EBB, 0xC918A2BE, 0x82DE74F2, 0xAD54209B, 0xF66B4D74, 0x1FC5B771, 0x169D9229, 0x887761DF, 0x00B667D5, 0xDB425E59, 0xB72F2844, 0x9B0AC1F5, 0x9C737E3A, 0x2B85476C, 0x6722ADD6, 0x44A63297, 0x0D688CED }, { 0xABC59484, 0x4107778A, 0x8AD94C6F, 0xFE83DF90, 0x0F64053F, 0xD1292E9D, 0xC5744356, 0x8DD1ABB4, 0x4C4E7667, 0xFB4A7FC1, 0x74F402CB, 0x70F06AFD, 0xA82286F2, 0x918DD076, 0x7A97C5CE, 0x48F7BDE3, 0x6A04D11D, 0xAC243EF7, 0x33AC10CA, 0x2F7A341E, 0x5F75157A, 0xF4773381, 0x591C870E, 0x78DF8CC8, 0x22F3ADB0, 0x251A5993, 0x09FBEF66, 0x796942A8, 0x97541D2E, 0x2373DAA9, 0x1BD2F142, 0xB57E8EB2, 0xE1A5BFDB, 0x7D0EFA92, 0xB3442C94, 0xD2CB6447, 0x386AC97E, 0x66D61805, 0xBDADA15E, 0x11BC1AA7, 0x14E9F6EA, 0xE533A0C0, 0xF935EE0A, 0x8FEE8A04, 0x810D6D85, 0x7C68B6D6, 0x4EDC9AA2, 0x956E897D, 0xED87581A, 0x264BE9D7, 0xFF4DDB29, 0x823857C2, 0xE005A9A0, 0xF1CC2450, 0x6F9951E1, 0xAADE2310, 0xE70C75F5, 0x83E1A31F, 0x4F7DDE8E, 0xF723B563, 0x368E0928, 0x86362B71, 0x21E8982D, 0xDFB3F92B, 0x44676352, 0x99EFBA31, 0x2EAB4E1C, 0xFC6CA5E7, 0x0EBE5D4E, 0xA0717D0C, 0xB64F8199, 0x946B31A1, 0x5656CBC6, 0xCFFEC3EF, 0x622766C9, 0xFA211E35, 0x52F98B89, 0x6D01674B, 0x4978A802, 0xF651F701, 0x15B0D43D, 0xD6FF4683, 0x3463855F, 0x672BA29C, 0xBC128312, 0x4626A70D, 0xC8927A5A, 0xB8481CF9, 0x1C962262, 0xA21196BA, 0xBABA5EE9, 0x5BB162D0, 0x69943BD1, 0x0C47E35C, 0x8CC9619A, 0xE284D948, 0x271BF264, 0xC27FB398, 0x4BC70897, 0x60CF202C, 0x7F42D6AA, 0xA5A13506, 0x5D3E8860, 0xCEA63D3C, 0x63BF0A8F, 0xF02E9EFA, 0xB17B0674, 0xB072B1D3, 0x06E5723B, 0x3737E436, 0x24AA49C7, 0x0DED0D18, 0xDB256B14, 0x58B27877, 0xECB49F54, 0x6C40256A, 0x6EA92FFB, 0x3906AA4C, 0xC9866FD5, 0x4549323E, 0xA7B85FAB, 0x1918CC27, 0x7308D7B5, 0x1E16C7AD, 0x71850B37, 0x3095FD78, 0xA63B70E6, 0xD880E2AE, 0x3E282769, 0xA39BA6BC, 0x98700FA3, 0xF34C53E8, 0x288AF426, 0xB99D930F, 0xF5B99DF1, 0xE9D0C8CF, 0x5AC8405D, 0x50E7217B, 0x511FBBBE, 0x2CA2E639, 0xC020301B, 0x356DBC00, 0x8E43DDB9, 0x4D327B4A, 0xF20FF3ED, 0x1DBB29BD, 0x43D44779, 0xA1B68F70, 0x6114455B, 0xE63D280B, 0x6BF6FF65, 0x10FC39E5, 0x3DAE126E, 0xC1D7CF11, 0xCB60B795, 0x1789D5B3, 0x9BCA36B7, 0x08306075, 0x84615608, 0x8B3A0186, 0xE88FBECD, 0x7BA47C4D, 0x2DE44DAC, 0x653FE58D, 0xCCA0B968, 0xD7FA0E72, 0x93901780, 0x1F2C26CC, 0xAE595B6B, 0xA9ECEA9B, 0xE3DBF8C4, 0x319CC130, 0x12981196, 0x01A3A4DE, 0x32C454B6, 0x755BD817, 0x3CD871E4, 0xA48BB8DA, 0x02FDEC09, 0xFD2DC2E2, 0x9E578088, 0x9A9F916D, 0x4065FE6C, 0x1853999E, 0xC7793F23, 0xDC1016BB, 0x969355FF, 0x7EF292F6, 0xCDCE4ADC, 0x05E24416, 0x85C16C46, 0xD441D37F, 0x57BD6855, 0x8746F54F, 0x9CA773DF, 0x770BAE22, 0x54828413, 0xB75E4B19, 0x04C35C03, 0xBF7CCA07, 0x2955C4DD, 0x721DB041, 0xB2394F33, 0x03F51387, 0x89B73C9F, 0x0B1737F3, 0x07E69024, 0x9231D245, 0x76193861, 0x88159C15, 0xDEB552D9, 0xD9767E40, 0x20C6C0C3, 0x4281977C, 0xF8AFE1E0, 0xD32A0751, 0x3FC27432, 0xDDF1DCC5, 0x68581F34, 0x3BCD5025, 0x0091B2EE, 0x4AEB6944, 0x1602E743, 0xEA09EB58, 0xEF0A2A8B, 0x641E03A5, 0xEB50E021, 0x5C8CCEF8, 0x802FF0B8, 0xD5E3EDFE, 0xC4DD1B49, 0x5334CD2A, 0x13F82D2F, 0x47450C20, 0x55DAFBD2, 0xBEC0C6F4, 0xB45D7959, 0x3AD36E8C, 0x0AA8AC57, 0x1A3C8D73, 0xE45AAFB1, 0x9F664838, 0xC6880053, 0xD0039BBF, 0xEE5F19EB, 0xCA0041D8, 0xBBEA3AAF, 0xDA628291, 0x9D5C95D4, 0xADD504A6, 0xC39AB482, 0x5E9E14A4, 0x2BE065F0, 0x2A13FC3A, 0x9052E8EC, 0xAF6F5AFC }, { 0x519AA8B5, 0xBB303DA9, 0xE00E2B10, 0xDFA6C1DB, 0x2E6B952E, 0xEE10DC23, 0x37936D09, 0x1FC42E92, 0x39B25A9F, 0x13FF89F4, 0xC8F53FEA, 0x18500BC7, 0x95A0379D, 0x98F751C2, 0x2289C42F, 0xA21E4098, 0x6F391F41, 0xF27E7E58, 0x0D0DF887, 0x4B79D540, 0x8E8409AA, 0x71FE46F8, 0x688A9B29, 0x3F08B548, 0x84ABE03A, 0x5E91B6C1, 0xFDE4C2AE, 0x251D0E72, 0x92D4FEE5, 0xF9371967, 0x9175108F, 0xE6E81835, 0x8C8CB8EE, 0xB55A67B3, 0xCEF138CC, 0x8B256268, 0x00D815F5, 0xE8810812, 0x77826189, 0xEA73267D, 0x19B90F8D, 0x45C33BB4, 0x82477056, 0xE1770075, 0x09467AA6, 0xA7C6F54A, 0x79768742, 0x61B86BCA, 0xD6644A44, 0xE33F0171, 0xC229FBCD, 0x41B08FEB, 0xD1903E30, 0x65EC9080, 0x563D6FBD, 0xF56DA488, 0xEBF64CD8, 0x4934426B, 0x7C8592FC, 0x6ACA8CF2, 0x1CEA111B, 0x3A57EE7A, 0xACE11C0D, 0x9942D85E, 0xC4613407, 0xFA8E643B, 0x327FC701, 0x4CA9BE82, 0x3352526D, 0x2C047F63, 0xF3A8F7DD, 0x1A4A98A8, 0x762ED4D1, 0x27C75008, 0xBDF497C0, 0x7A7B84DF, 0x315C28AB, 0x801F93E3, 0xF19B0CA1, 0x8F14E46A, 0xE48BA333, 0x9605E625, 0xF03ECB60, 0x60385F2D, 0x902845BA, 0x7F96D66F, 0x24BFF05C, 0x2820730B, 0x947133CB, 0xD444828A, 0xB343F6F1, 0x0BEF4705, 0x8DA574F9, 0x01E25D6C, 0x1732793E, 0x4F0F7B27, 0x364B7117, 0xB2D1DA77, 0xA6C5F1E9, 0x574CA5B1, 0x386A3076, 0xAD6894D6, 0x1156D7FA, 0xA48D1D9A, 0x4794C0AF, 0x150C0AA0, 0x26D348AC, 0x29FDEABE, 0xA5DEDE53, 0x81671E8E, 0x594EE3BF, 0xA96C56E6, 0x3426A726, 0xC5976579, 0xBC22E5E4, 0xC1006319, 0xDAAFDD2A, 0xA1A1AA83, 0x3BADD0E7, 0xC3B14981, 0xD770B155, 0xCCD7C693, 0x42E944C5, 0x03E0064F, 0xCA95B4EF, 0x3DEE81C3, 0xFBBCD98C, 0x1E07E15B, 0x667CE949, 0xE7D6773F, 0x21B6124B, 0x6B2A6EF7, 0xD3278A9C, 0x9A988304, 0x75D2AE9B, 0xFE49E2FF, 0x9BC24F46, 0x74CC2CF6, 0xA3139F36, 0x6C9EF35A, 0x9FC1DFFE, 0x9E5FACDC, 0xAADC8BBB, 0x5ABDBC5F, 0x44B3B390, 0xF754EFA7, 0x5FE3BDB7, 0x4E59C886, 0x06A4C984, 0xA0338878, 0xCD513CD7, 0x63EBD27E, 0x8ABA80AD, 0x50DA144E, 0x5D9F4E97, 0x025B751C, 0x2D580200, 0xB6C05837, 0x580AA15D, 0x54022A6E, 0xB41A5415, 0x4863FAB6, 0xB0B79957, 0x46D0D159, 0xDC2B8650, 0x20A7BB0C, 0x4A032974, 0xEC8636A2, 0x8548F24C, 0xF6A2BF16, 0x1088F4B0, 0x0C2F3A94, 0x525DC396, 0x14065785, 0x2B4DCA52, 0x08AEED39, 0xABEDFC99, 0xB1DBCF18, 0x87F85BBC, 0xAE3AFF61, 0x433CCD70, 0x5B23CC64, 0x7B453213, 0x5355C545, 0x9318EC0A, 0x78692D31, 0x0A21693D, 0xD5666814, 0x05FB59D9, 0xC71985B2, 0x2ABB8E0E, 0xCF6E6C91, 0xD9CFE7C6, 0xEFE7132C, 0x9711AB28, 0x3CE52732, 0x12D516D2, 0x7209A0D0, 0xD278D306, 0x70FA4B7B, 0x1D407DD3, 0xDB0BEBA4, 0xBFD97621, 0xA8BE21E1, 0x1B6F1B66, 0x30650DDA, 0xBA7DDBB9, 0x7DF953FB, 0x9D1C3902, 0xEDF0E8D5, 0xB8741AE0, 0x0F240565, 0x62CD438B, 0xC616A924, 0xAF7A96A3, 0x35365538, 0xE583AF4D, 0x73415EB8, 0x23176A47, 0xFC9CCEE8, 0x7EFC9DE2, 0x695E03CF, 0xF8CE66D4, 0x88B4781D, 0x67DD9C03, 0x3E8F9E73, 0xC0C95C51, 0xBE314D22, 0x55AA0795, 0xCB1BB011, 0xE980FDC8, 0x9C62B7CE, 0xDE2D239E, 0x042CADF3, 0xFFDF04DE, 0x5CE6A60F, 0xD8C831ED, 0xB7B5B9EC, 0xB9CBF962, 0xE253B254, 0x0735BA1F, 0x16AC917F, 0xDD607C2B, 0x64A335C4, 0x40159A7C, 0x869222F0, 0x6EF21769, 0x839D20A5, 0xD03B24C9, 0xF412601E, 0x6D72A243, 0x0E018DFD, 0x89F3721A, 0xC94F4134, 0x2F992F20, 0x4D87253C }}; void Snefru_8_256_Transform(uint32_t* data, uint32_t* state) { uint32_t i, j, k, shift; RH_ALIGN(64) uint32_t work[16]; //beData //uint32_t *ptr_work = &work[0]; memcpy(&work[0], &state[0], SNEFRU_size * sizeof(uint32_t)); //scratch buffer 64 uint32 uint32_t* part2 = &work[8]; copy8_op(part2, data, ReverseBytesUInt32); i = 0; while (i < (uint32_t)SNEFRU_SecurityLevel) { const uint32_t* sbox0 = &Snefru_boxes[i * 2 + 0][0]; const uint32_t* sbox1 = &Snefru_boxes[i * 2 + 1][0]; j = 0; while (j < 4) { work[15] = work[15] ^ (sbox0)[uint8_t(work[0])]; work[1] = work[1] ^ (sbox0)[uint8_t(work[0])]; work[0] = work[0] ^ (sbox0)[uint8_t(work[1])]; work[2] = work[2] ^ (sbox0)[uint8_t(work[1])]; work[1] = work[1] ^ (sbox1)[uint8_t(work[2])]; work[3] = work[3] ^ (sbox1)[uint8_t(work[2])]; work[2] = work[2] ^ (sbox1)[uint8_t(work[3])]; work[4] = work[4] ^ (sbox1)[uint8_t(work[3])]; work[3] = work[3] ^ (sbox0)[uint8_t(work[4])]; work[5] = work[5] ^ (sbox0)[uint8_t(work[4])]; work[4] = work[4] ^ (sbox0)[uint8_t(work[5])]; work[6] = work[6] ^ (sbox0)[uint8_t(work[5])]; work[5] = work[5] ^ (sbox1)[uint8_t(work[6])]; work[7] = work[7] ^ (sbox1)[uint8_t(work[6])]; work[6] = work[6] ^ (sbox1)[uint8_t(work[7])]; work[8] = work[8] ^ (sbox1)[uint8_t(work[7])]; work[7] = work[7] ^ (sbox0)[uint8_t(work[8])]; work[9] = work[9] ^ (sbox0)[uint8_t(work[8])]; work[8] = work[8] ^ (sbox0)[uint8_t(work[9])]; work[10] = work[10] ^ (sbox0)[uint8_t(work[9])]; work[9] = work[9] ^ (sbox1)[uint8_t(work[10])]; work[11] = work[11] ^ (sbox1)[uint8_t(work[10])]; work[10] = work[10] ^ (sbox1)[uint8_t(work[11])]; work[12] = work[12] ^ (sbox1)[uint8_t(work[11])]; work[11] = work[11] ^ (sbox0)[uint8_t(work[12])]; work[13] = work[13] ^ (sbox0)[uint8_t(work[12])]; work[12] = work[12] ^ (sbox0)[uint8_t(work[13])]; work[14] = work[14] ^ (sbox0)[uint8_t(work[13])]; work[13] = work[13] ^ (sbox1)[uint8_t(work[14])]; work[15] = work[15] ^ (sbox1)[uint8_t(work[14])]; work[14] = work[14] ^ (sbox1)[uint8_t(work[15])]; work[0] = work[0] ^ (sbox1)[uint8_t(work[15])]; shift = Snefru_shifts[j]; k = 0; while (k < 16) { work[k] = ROTR32(work[k], shift); k++; } j++; } i++; } state[0] = state[0] ^ work[15]; state[1] = state[1] ^ work[14]; state[2] = state[2] ^ work[13]; state[3] = state[3] ^ work[12]; state[4] = state[4] ^ work[11]; state[5] = state[5] ^ work[10]; state[6] = state[6] ^ work[9]; state[7] = state[7] ^ work[8]; } void RandomHash_Snefru_8_256(RH_StridePtr roundInput, RH_StridePtr output) { // init RH_ALIGN(64) uint32_t state[SNEFRU_size]; RH_memzero_32(state, sizeof(state)); int32_t len = (int32_t)RH_STRIDE_GET_SIZE(roundInput); uint64_t bits = len * 8; uint32_t blockCount = len / SNEFRU_BlockSize; uint32_t *dataPtr = (uint32_t *)RH_STRIDE_GET_DATA(roundInput); while(blockCount > 0) { Snefru_8_256_Transform(dataPtr, state); len -= SNEFRU_BlockSize; dataPtr += SNEFRU_BlockSize / 4; blockCount--; } //finish int32_t padindex; uint32_t pos = len % SNEFRU_BlockSize; if (pos > 0) padindex = 2 * SNEFRU_BlockSize - pos - 8; else padindex = SNEFRU_BlockSize - pos - 8; RH_ALIGN(64) uint32_t pad[SNEFRU_BlockSize*2]; RH_memzero_of16(pad, sizeof(pad)); bits = ReverseBytesUInt64(bits); ReadUInt64AsBytesLE(bits, ((uint8_t*)pad)+padindex); padindex = padindex + 8; memcpy(((uint8_t*)dataPtr) + len, pad, padindex); RH_ASSERT(((padindex + len) % SNEFRU_BlockSize)==0); Snefru_8_256_Transform(dataPtr, state); padindex -= SNEFRU_BlockSize; if (padindex > 0) Snefru_8_256_Transform(dataPtr+(SNEFRU_BlockSize/4), state); //output state dataPtr = (uint32_t*)RH_STRIDE_GET_DATA(output); RH_STRIDE_SET_SIZE(output, SNEFRU_size * 4); copy8_op(dataPtr, state, ReverseBytesUInt32); }
78.593085
103
0.743934
30368c8560ea67f7e431c1367114e8c0a0cc71b5
4,110
h
C
samples-cpp/datalayer.provider.all-data/providerNodeAllData.h
bracoe/ctrlx-automation-sdk
6b2e61e146c557488125baf941e4d64c6fa6d0fb
[ "MIT" ]
16
2021-08-23T13:07:12.000Z
2022-02-21T13:29:21.000Z
samples-cpp/datalayer.provider.all-data/providerNodeAllData.h
bracoe/ctrlx-automation-sdk
6b2e61e146c557488125baf941e4d64c6fa6d0fb
[ "MIT" ]
null
null
null
samples-cpp/datalayer.provider.all-data/providerNodeAllData.h
bracoe/ctrlx-automation-sdk
6b2e61e146c557488125baf941e4d64c6fa6d0fb
[ "MIT" ]
10
2021-09-29T09:58:33.000Z
2022-01-13T07:20:00.000Z
#ifndef PROVIDER_NODE_ALL_DATA_H #define PROVIDER_NODE_ALL_DATA_H #include <iostream> #include <vector> #include <cfloat> #include "comm/datalayer/datalayer.h" #include "comm/datalayer/datalayer_system.h" #include "comm/datalayer/variant.h" #include "comm/datalayer/metadata_generated.h" #include "sampleSchema_generated.h" #include "dataContainer.h" /* ProviderNodeAllData This class implements the IProviderNode interface and provides an 'all-data' Data Layer sub branch. The branch and it's nodes are virtual - Data Layer clients will see normal Data Layer nodes but they are all 'simulated' by an instance of this class. For each virtual node a DataContainer instance is used. The branch can be dynamic. In this case the branch itself and it's nodes can be manipulated (write, remove,..) by clients. If the branch is declared as static now changes can be made. This is useful for integration test and so on. */ class ProviderNodeAllData : public comm::datalayer::IProviderNode { protected: // List of DataContainer instances ('virtual nodes') std::vector<DataContainer *> _dataContainers; // The Data Layer Provider instance comm::datalayer::IProvider *_provider; // Data Layer root path std::string _addressRoot; // Flag: True branch is dynamic (can be changed by clients) bool _dynamic; // Root path combined with 'static' or 'dynamic' std::string _addressBase; //metadata for the providerNode comm::datalayer::Variant _metadata; // Search an existing DataContainer instance for this address DataContainer *getDataContainer(const std::string &address); // Create a DataContainer instance for this address with that data comm::datalayer::DlResult createDataContainer(const std::string &address, const comm::datalayer::Variant &data); // Create a DataContainer instance for this address with that data if setValueResult is DL_OK void createDataContainer(comm::datalayer::DlResult setValueResult, const std::string &addressNode, const comm::datalayer::Variant &data); // Create Metadata instance for the address with the data comm::datalayer::Variant createMetadata(const comm::datalayer::Variant &data, const std::string &address); public: // Constructor ProviderNodeAllData(comm::datalayer::IProvider *provider, const std::string &addressRoot, bool dynamic); // Create virtual nodes and register them in the Data Layer void RegisterNodes(); // Will be called by the Data Layer broker whenever a sub node should be created. virtual void onCreate( const std::string &address, const comm::datalayer::Variant *data, const comm::datalayer::IProviderNode::ResponseCallback &callback); // Will be called by the Data Layer broker whenever a sub node should be read. virtual void onRead( const std::string &address, const comm::datalayer::Variant *data, const comm::datalayer::IProviderNode::ResponseCallback &callback); // Will be called by the Data Layer broker whenever a sub node should be written. virtual void onWrite( const std::string &address, const comm::datalayer::Variant *data, const comm::datalayer::IProviderNode::ResponseCallback &callback); // Will be called by the Data Layer broker whenever a sub node should be removed. virtual void onRemove( const std::string &address, const comm::datalayer::IProviderNode::ResponseCallback &callback); // Will be called by the Data Layer broker to list sub nodes. // The returned list is merged with the list of nodes known by the broker himself. // So normally we return nothing. virtual void onBrowse( const std::string &address, const comm::datalayer::IProviderNode::ResponseCallback &callback); // Will be called by the Data Layer broker when he needs the properties (meta data) of the node. virtual void onMetadata( const std::string &address, const comm::datalayer::IProviderNode::ResponseCallback &callback); }; static const char *snap_path() { return std::getenv("SNAP"); } static bool is_snap() { return snap_path() != nullptr; } #endif
35.73913
139
0.745742
6806100fb81a4d71a9e577667f6d2f5327eb838c
839
h
C
content/public/browser/android/java_interfaces.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/public/browser/android/java_interfaces.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/public/browser/android/java_interfaces.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 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 CONTENT_PUBLIC_BROWSER_ANDROID_JAVA_INTERFACES_H_ #define CONTENT_PUBLIC_BROWSER_ANDROID_JAVA_INTERFACES_H_ #include "content/common/content_export.h" namespace service_manager { class InterfaceProvider; } namespace content { // Returns an InterfaceProvider for global Java-implemented interfaces. // This provides access to interfaces implemented in Java in the browser process // to C++ code in the browser process. This and the returned InterfaceProvider // may only be used on the UI thread. CONTENT_EXPORT service_manager::InterfaceProvider* GetGlobalJavaInterfaces(); } // namespace content #endif // CONTENT_PUBLIC_BROWSER_ANDROID_JAVA_INTERFACES_H_
33.56
80
0.815256
a93538f08b94886163dec1851b081a257542eff5
6,880
h
C
whisperstreamlib/base/media_info.h
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/base/media_info.h
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/base/media_info.h
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009, Whispersoft s.r.l. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Whispersoft s.r.l. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: Cosmin Tudorache #ifndef __MEDIA_SOURCE_MEDIA_INFO_H__ #define __MEDIA_SOURCE_MEDIA_INFO_H__ #include <string> #include <vector> #include <whisperlib/common/base/types.h> #include <whisperlib/common/io/buffer/memory_stream.h> #include <whisperstreamlib/f4v/frames/header.h> #include <whisperstreamlib/rtmp/objects/rtmp_objects.h> namespace streaming { namespace f4v { class MoovAtom; } class MediaInfo { public: struct Audio { enum Format { FORMAT_AAC, FORMAT_MP3, }; static const char* FormatName(Format format); Audio(); ~Audio(); const char* format_name() const; string ToString(const char* glue = ", ") const; Format format_; uint8 channels_; // 1 or 2 uint32 sample_rate_; // e.g. 44100 uint32 sample_size_; // e.g. 16 uint32 bps_; // e.g. 96000 ( = 96 kbps) // MP4 specific string mp4_language_; // e.g. "eng" // AAC specific uint8 aac_level_; uint8 aac_profile_; uint8 aac_config_[2]; // 2 bytes AAC configuration // AAC Frame format inside FLV container: <2 bytes unknown> <aac frame> // AAC Frame format inside MP4/regular container: <aac frame> bool aac_flv_container_; // MP3 specific // MP3 Frame format inside FLV container: // <0x2e> <4 bytes mp3 header> <mp3 data> .. // MP3 Frame format inside MP3/regular container: // <4 bytes mp3 header> <mp3 data> .. bool mp3_flv_container_; }; struct Video { enum Format { FORMAT_H263, FORMAT_H264, FORMAT_ON_VP6, }; static const char* FormatName(Format format); Video(); ~Video(); const char* format_name() const; string ToString(const char* glue = ", ") const; Format format_; uint32 width_; // in pixels uint32 height_; // in pixels uint32 clock_rate_; // e.g. 90000 for H264/AVC float frame_rate_; // fps uint32 bps_; // e.g. 512000 ( = 512 kbps) uint32 timescale_; // clock ticks / second // MP4 specific uint32 mp4_moov_position_; // H264 specific uint8 h264_configuration_version_; uint8 h264_profile_; uint8 h264_profile_compatibility_; uint8 h264_level_; uint8 h264_nalu_length_size_; vector<string> h264_sps_; // sequence parameter set, binary format vector<string> h264_pps_; // picture parameter set, binary format // In FLV container we have: // <7 unknown bytes> <2 bytes NALU size> <NALU body> <2 bytes NALU size> .. // In MP4 container we have: // <4 bytes NALU size> <NALU body> <4 bytes NALU size> ... bool h264_flv_container_; // If true: <NALU start code> <NALU body> <NALU start code> <NALU body> ... // false: <2/4 bytes NALU size> <NALU body> ... // The <NALU start code> can be 3 bytes: 0x000001, or 4 bytes: 0x00000001 bool h264_nalu_start_code_; // the complete AVCC atom body (without the header type & size: 8 bytes) string h264_avcc_; }; struct Frame { // true = audio frame // false = video frame bool is_audio_; // frame size in bytes uint32 size_; // decoding timestamp int64 decoding_ts_; // Composition Time = Decoding Time + Composition Offset Ms uint32 composition_offset_ms_; // valid on Video frames only. Marks a keyframe. bool is_keyframe_; Frame(bool is_audio, uint32 size, int64 decoding_ts, uint32 composition_offset_ms, bool is_keyframe) : is_audio_(is_audio), size_(size), decoding_ts_(decoding_ts), composition_offset_ms_(composition_offset_ms), is_keyframe_(is_keyframe) {} string ToString() const; }; public: MediaInfo(); MediaInfo(const MediaInfo& other); virtual ~MediaInfo(); bool has_audio() const; bool has_video() const; const Audio& audio() const; Audio* mutable_audio(); const Video& video() const; Video* mutable_video(); uint32 duration_ms() const; void set_duration_ms(uint32 duration_ms); uint64 file_size() const; void set_file_size(uint64 file_size); bool seekable() const; void set_seekable(bool seekable); bool pausable() const; void set_pausable(bool pausable); const vector<Frame>& frames() const; vector<Frame>* mutable_frames(); void set_frames(const vector<f4v::FrameHeader*>& frames); const rtmp::CMixedMap& flv_extra_metadata() const; rtmp::CMixedMap* mutable_flv_extra_metadata(); const f4v::MoovAtom* mp4_moov() const; f4v::MoovAtom* mutable_mp4_moov(); void set_mp4_moov(const f4v::MoovAtom& moov); string ToString() const; private: // audio attributes Audio audio_; // video attributes Video video_; // media duration uint32 duration_ms_; // in bytes; useful if media is a file, otherwise 0 uint64 file_size_; // is media seekable bool seekable_; // is media pausable (more like a stream controller attribute) bool pausable_; // stream frames. Some formats have them: mp4. // For other formats this is empty: flv, mp3, aac. vector<Frame> frames_; // extra metadata values that are not extracted into audio/video/duration.. rtmp::CMixedMap flv_extra_metadata_; // TODO(cosmin): the whole MOOV, because I don't have a solution for storing // the extra atoms MOOV may contain. f4v::MoovAtom* mp4_moov_; }; } #endif // __MEDIA_SOURCE_MEDIA_INFO_H__
30.852018
80
0.701744
04fa73f9fd2262092ea7e84abbbaf1632a212be9
693
h
C
deps/sock/tcp.h
jwerle/libhttp
64eba2de745f4f56035db8c18dd12b72787845f2
[ "MIT" ]
6
2018-01-16T11:53:47.000Z
2022-02-27T20:47:35.000Z
include/sock/tcp.h
jwerle/libsock
3ebcd6030729f9aa4969c2be038231b36a59cb8c
[ "MIT" ]
null
null
null
include/sock/tcp.h
jwerle/libsock
3ebcd6030729f9aa4969c2be038231b36a59cb8c
[ "MIT" ]
null
null
null
/** * `tcp.h' - libsock * * copyright (c) 2014 joseph werle <joseph.werle@gmail.com> */ #ifndef SOCK_TCP_H #define SOCK_TCP_H 1 #include "common.h" #include "socket.h" typedef struct socket_tcp_s { SOCK_SOCKET_FIELDS int backlog; } socket_tcp_t; /** * Create a new tcp socket */ SOCK_EXTERN socket_t * sock_tcp_new (); /** * Listens for connections on socket */ SOCK_EXTERN int sock_tcp_listen (socket_t *); /** * Closes socket with `SHUT_RDWR' * using `shutdown(int, int)' */ SOCK_EXTERN int sock_tcp_close (socket_t *); /** * Creates a new tcp socket client * for a given host and port */ SOCK_EXTERN socket_t * sock_tcp_client_new (const char *, int); #endif
13.86
59
0.689755
a9d2ac05d903371fcad50281e214e71bd7c5eba2
6,395
h
C
src/session/sip_call.h
lichao2014/rtc_call
3084df96c4986d0fa37f476f72e4c2cdc05857ca
[ "Apache-2.0" ]
3
2018-07-24T08:16:38.000Z
2018-08-03T02:16:11.000Z
src/session/sip_call.h
lichao2014/rtc_call
3084df96c4986d0fa37f476f72e4c2cdc05857ca
[ "Apache-2.0" ]
null
null
null
src/session/sip_call.h
lichao2014/rtc_call
3084df96c4986d0fa37f476f72e4c2cdc05857ca
[ "Apache-2.0" ]
1
2018-07-24T08:16:44.000Z
2018-07-24T08:16:44.000Z
#ifndef _RTC_SIP_SESSION_CALL_H_INCLUDED #define _RTC_SIP_SESSION_CALL_H_INCLUDED #include "resip/dum/AppDialogSet.hxx" #include "resip/dum/ClientInviteSession.hxx" #include "resip/dum/ServerInviteSession.hxx" #include "resip/dum/AppDialogSetFactory.hxx" #include "session/sip_user.h" #include "session/resip_util.h" namespace rtc_session { template<typename Handle = resip::InviteSessionHandle> class SipCallContext { public: SipCallContext(std::shared_ptr<SipUserContext> user_ctx, const UserId& user_id) : user_ctx_(user_ctx) , user_id_(user_id) { //std::clog << "call ctx new\t" << this << std::endl; } ~SipCallContext() { //std::clog << "call ctx release\t" << this << std::endl; } auto& user_context() { return user_ctx_; } const UserId& peer() const { return user_id_; } void SetCallback(std::shared_ptr<CallCallback> callback) { callback_ = callback; } bool GetLocalSdp(std::string *out) { return user_ctx_->Invoke([this, out] { if (!h_.isValid()) { return false; } if (!h_->hasLocalSdp()) { return false; } auto& body = h_->getLocalSdp().getBodyData(); out->assign(body.data(), body.size()); return true; }); } void Message(const Contents& msg) { user_ctx_->Dispatch([h = h_, msg]() mutable { if (h.isValid()) { h->message(*MakeContents(msg)); } }); } void AcceptNIT(int code, const Contents *msg) { if (msg) { user_ctx_->Dispatch([h = h_, code, msg = *msg]() mutable { if (h.isValid()) { h->acceptNIT(code, MakeContents(msg).get()); } }); } else { user_ctx_->Dispatch([h = h_, code]() mutable { if (h.isValid()) { h->acceptNIT(code); } }); } } void RejectNIT(int code) { user_ctx_->Dispatch([h = h_, code]() mutable { if (h.isValid()) { h->rejectNIT(code); } }); } void End() { user_ctx_->Dispatch([h = h_]() mutable { if (h.isValid()) { h->end(); } }); } void Init(Handle h) { h_ = h; callback_(&CallCallback::OnInit); } void OnFailure() { callback_(&CallCallback::OnFailure); } void OnOffer(const std::string& offer) { callback_(&CallCallback::OnOffer, offer); } void OnAnswer(const std::string& answer) { callback_(&CallCallback::OnAnswer, answer); } void OnMessage(const Contents& msg) { callback_(&CallCallback::OnMessage, msg); } void OnMessageResult(bool success) { callback_(&CallCallback::OnMessageResult, success); } void OnConnected() { callback_(&CallCallback::OnConnected); } void OnTerminated() { callback_(&CallCallback::OnTerminated); } protected: Handle h_; UserId user_id_; std::shared_ptr<SipUserContext> user_ctx_; util::CallbackWrapper<CallCallback> callback_; }; class SipCallerContext : public SipCallContext<resip::ClientInviteSessionHandle> , public std::enable_shared_from_this<SipCallerContext> { public: using SipCallContext<resip::ClientInviteSessionHandle>::SipCallContext; void Invite(const std::string *offer); void End(); private: void DoInvite(const std::string *offer); resip::SharedPtr<resip::SipMessage> invite_request_msg_; }; class SipCalleeContext : public SipCallContext<resip::ServerInviteSessionHandle> , public std::enable_shared_from_this<SipCalleeContext> { public: using SipCallContext<resip::ServerInviteSessionHandle>::SipCallContext; void Accept(const std::string& answer, int code); void Reject(int code); }; template<typename T = SessionCallInterface, typename Context = SipCallContext<>> class SipCall : public T { public: explicit SipCall(std::shared_ptr<Context> ctx) : ctx_(ctx) {} ~SipCall() override { ctx_->End(); } const UserId& peer() const override { return ctx_->peer(); } bool GetLocalSdp(std::string *out) override { return ctx_->GetLocalSdp(out); } void Message(const Contents& msg) override { ctx_->Message(msg); } void AcceptNIT(int code, const Contents *msg) override { ctx_->AcceptNIT(code, msg); } void RejectNIT(int code) override { ctx_->RejectNIT(code); } void SetCallback(std::shared_ptr<CallCallback> callback) override { ctx_->SetCallback(callback); } protected: std::shared_ptr<Context> ctx_; }; class SipCaller : public SipCall<CallerInterface, SipCallerContext> { public: using SipCall<CallerInterface, SipCallerContext>::SipCall; void Invite(const std::string *offer) override { ctx_->Invite(offer); } }; class SipCallee : public SipCall<CalleeInterface, SipCalleeContext> { public: using SipCall<CalleeInterface, SipCalleeContext>::SipCall; void Accept(const std::string& answer, int code) override { ctx_->Accept(answer, code); } void Reject(int code) override { ctx_->Reject(code); } }; template<typename Context> class SipCallDialogSet : public resip::AppDialogSet { public: explicit SipCallDialogSet(std::shared_ptr<Context> ctx) : resip::AppDialogSet(*ctx->user_context()) , ctx_(ctx) {} const std::shared_ptr<Context>& context() const { return ctx_; } private: std::shared_ptr<Context> ctx_; }; class SipDialogSetFactory : public resip::AppDialogSetFactory { public: explicit SipDialogSetFactory(std::shared_ptr<SipUserContext> user_ctx) : user_ctx_(user_ctx) {} private: resip::AppDialogSet* createAppDialogSet(resip::DialogUsageManager&, const resip::SipMessage&) override; std::shared_ptr<SipUserContext> user_ctx_; }; } #endif // !_RTC_SIP_SESSION_CALL_H_INCLUDED
27.212766
84
0.592025
e702f5d47b00a7780c0df45f6154e4619195e6a2
3,425
h
C
MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
MagneticField/GeomBuilder/src/MagGeoBuilderFromDDD.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef MagGeoBuilderFromDDD_H #define MagGeoBuilderFromDDD_H /** \class MagGeoBuilderFromDDD * Parse the XML magnetic geometry, build individual volumes and match their * shared surfaces. Build MagVolume6Faces and organise them in a hierarchical * structure. Build MagGeometry out of it. * * \author N. Amapane - INFN Torino */ #include "MagneticField/Interpolation/interface/MagProviderInterpol.h" #include "DetectorDescription/Core/interface/DDCompactView.h" #include "CondFormats/MFObjects/interface/MagFieldConfig.h" #include <string> #include <vector> #include <map> #include <memory> class Surface; class MagBLayer; class MagESector; class MagVolume6Faces; namespace magneticfield { class VolumeBasedMagneticFieldESProducer; class VolumeBasedMagneticFieldESProducerFromDB; class BaseVolumeHandle; // Needs to be public to share code with DD4hep using handles = std::vector<BaseVolumeHandle*>; } // namespace magneticfield class MagGeoBuilderFromDDD { public: /// Constructor. MagGeoBuilderFromDDD(std::string tableSet_, int geometryVersion, bool debug = false); /// Destructor virtual ~MagGeoBuilderFromDDD(); /// Set scaling factors for individual volumes. /// "keys" is a vector of 100*volume number + sector (sector 0 = all sectors) /// "values" are the corresponding scaling factors void setScaling(const std::vector<int>& keys, const std::vector<double>& values); void setGridFiles(const magneticfield::TableFileMap& gridFiles); /// Get barrel layers std::vector<MagBLayer*> barrelLayers() const; /// Get endcap layers std::vector<MagESector*> endcapSectors() const; float maxR() const; float maxZ() const; // Temporary container to manipulate volumes and their surfaces. class volumeHandle; // Needs to be public to share code with DD4hep private: // Build the geometry. //virtual void build(); virtual void build(const DDCompactView& cpv); // FIXME: only for temporary tests and debug, to be removed friend class TestMagVolume; friend class MagGeometry; friend class magneticfield::VolumeBasedMagneticFieldESProducer; friend class magneticfield::VolumeBasedMagneticFieldESProducerFromDB; std::vector<MagVolume6Faces*> barrelVolumes() const; std::vector<MagVolume6Faces*> endcapVolumes() const; // Build interpolator for the volume with "correct" rotation void buildInterpolator(const volumeHandle* vol, std::map<std::string, MagProviderInterpol*>& interpolators); // Build all MagVolumes setting the MagProviderInterpol void buildMagVolumes(const magneticfield::handles& volumes, std::map<std::string, MagProviderInterpol*>& interpolators); // Print checksums for surfaces. void summary(magneticfield::handles& volumes); // Perform simple sanity checks void testInside(magneticfield::handles& volumes); magneticfield::handles bVolumes; // the barrel volumes. magneticfield::handles eVolumes; // the endcap volumes. std::vector<MagBLayer*> mBLayers; // Finally built barrel geometry std::vector<MagESector*> mESectors; // Finally built barrel geometry std::string tableSet; // Version of the data files to be used int geometryVersion; // Version of MF geometry std::map<int, double> theScalingFactors; const magneticfield::TableFileMap* theGridFiles; // Non-owned pointer assumed to be valid until build() is called const bool debug; }; #endif
33.578431
116
0.75708
34368a4ac1fa1690b3f216cd8cc5b8f88e8371b4
1,349
h
C
include/RE/S/StatsNode.h
r-neal-kelly/CommonLibSSE
aefeb91d38cad750bc9f36f6260a05e7b1b094fd
[ "MIT" ]
null
null
null
include/RE/S/StatsNode.h
r-neal-kelly/CommonLibSSE
aefeb91d38cad750bc9f36f6260a05e7b1b094fd
[ "MIT" ]
null
null
null
include/RE/S/StatsNode.h
r-neal-kelly/CommonLibSSE
aefeb91d38cad750bc9f36f6260a05e7b1b094fd
[ "MIT" ]
null
null
null
#pragma once #include "RE/B/BSIntrusiveRefCounted.h" #include "RE/B/BSTArray.h" #include "RE/B/BSTEvent.h" #include "RE/S/SimpleAnimationGraphManagerHolder.h" namespace RE { struct BSAnimationGraphEvent; class StatsNode : public SimpleAnimationGraphManagerHolder, // 00 public BSIntrusiveRefCounted, // 20 public BSTEventSink<BSAnimationGraphEvent> // 18 { public: inline static constexpr auto RTTI = RTTI_StatsNode; virtual ~StatsNode(); // 00 // override (SimpleAnimationGraphManagerHolder) virtual bool SetupAnimEventSinks(const BSTSmartPointer<BShkbAnimationGraph>& a_animGraph) override; // 08 virtual void Unk_0C(void) override; // 0C // override (BSTEventSink<BSAnimationGraphEvent>) virtual BSEventNotifyControl ProcessEvent(const BSAnimationGraphEvent* a_event, BSTEventSource<BSAnimationGraphEvent>* a_eventSource) override; // 01 - runs PlaySound on BSAnimationGraphEvent::optionalStr // members std::uint32_t unk24; // 24 BSTArray<BSTSmartPointer<BSIntrusiveRefCounted>> unk28; // 28 std::uint64_t unk40; // 40 std::uint64_t unk48; // 48 BSTSmartPointer<BSIntrusiveRefCounted> unk50; // 50 BSTSmartPointer<BSIntrusiveRefCounted> unk58; // 58 std::uint64_t unk60; // 60 }; static_assert(sizeof(StatsNode) == 0x68); }
33.725
207
0.727947
2eda5bfd1b8d995f86b1d8f7c1b2f8241c6597c9
1,904
h
C
NmeaAnalysisTool/src/NmeaDecode/NmeaDecodeRing.h
summerquiet/NmeaAnalysisTool
73d10e421a5face988444fb04d7d61d3f30333f7
[ "Apache-2.0" ]
1
2019-01-08T02:42:48.000Z
2019-01-08T02:42:48.000Z
NmeaAnalysisTool/src/NmeaDecode/NmeaDecodeRing.h
summerquiet/NmeaAnalysisTool
73d10e421a5face988444fb04d7d61d3f30333f7
[ "Apache-2.0" ]
null
null
null
NmeaAnalysisTool/src/NmeaDecode/NmeaDecodeRing.h
summerquiet/NmeaAnalysisTool
73d10e421a5face988444fb04d7d61d3f30333f7
[ "Apache-2.0" ]
1
2020-11-10T11:10:28.000Z
2020-11-10T11:10:28.000Z
/** * Copyright @ 2017 - 2018 * All Rights Reserved. * */ #ifndef CXX_NMEADECODERING_H #define CXX_NMEADECODERING_H #ifndef __cplusplus # error ERROR: This file requires C++ compilation (use a .cpp suffix) #endif /*---------------------------------------------------------------------------*/ // Included files /*---------------------------------------------------------------------------*/ // Class define class CNmeaDecode; /** * CNmeaDecodeRing class * * NMEA decode ring buffer */ class CNmeaDecodeRing { public: /** * Constructor * * @param NONE * * @return NONE */ CNmeaDecodeRing(CNmeaDecode* pcDecode); /** * Destructor * * @param NONE * * @return NONE */ virtual ~CNmeaDecodeRing(); /** * Receive NMEA information * * @param pData [IN]: input NMEA information * dwSize [IN]: input data size * * @return BOOL : Decode result */ BOOL ReceiveNmeaInfo(const VOID* pData, DWORD dwSize); private: static const DWORD NMEA_DECODE_SEARCH_BUF_SIZE = 2048; // NMEA decode search buffer size static const DWORD NMEA_DECODE_SEND_BUF_SIZE = 256 + 1; // NMEA decode send buffer size CNmeaDecode* m_pcDecode; // decode parent pointer CHAR m_pSearchBuffer[NMEA_DECODE_SEARCH_BUF_SIZE]; // NMEA decode search buffer DWORD m_dwUsingBufSize; // using buffer size CHAR m_pSendBuffer[NMEA_DECODE_SEND_BUF_SIZE]; // NMEA decode send buffer }; /*---------------------------------------------------------------------------*/ #endif // CXX_NMEADECODERING_H /*---------------------------------------------------------------------------*/ /* EOF */
25.72973
109
0.47479
a2ed2c1756a15c57b396f58421893e6b0b22c7cc
561
h
C
include/Game.h
aidan-clyens/2DGameEngine
ec92cf75ae443b6642b6d6dc526db44766907b79
[ "MIT" ]
null
null
null
include/Game.h
aidan-clyens/2DGameEngine
ec92cf75ae443b6642b6d6dc526db44766907b79
[ "MIT" ]
null
null
null
include/Game.h
aidan-clyens/2DGameEngine
ec92cf75ae443b6642b6d6dc526db44766907b79
[ "MIT" ]
null
null
null
#ifndef GAME_H #define GAME_H #include <SFML/Graphics.hpp> #include "global.h" #include "TileMap.h" #include "Player.h" #include "State.h" #include "MainMenuState.h" #include "GameState.h" class Game { public: Game(); ~Game(); void init_window(); void init_states(); void run(); void update(); void render(); void poll_events(); private: sf::RenderWindow *m_main_window; sf::ContextSettings m_window_settings; std::stack<State*> m_states; }; #endif // GAME_H
17.53125
46
0.597148
08aa06a06e48f218bb6535ed2ab86a92450dd26d
11,875
c
C
C/PocketSphinxTrigger/phone_loop_search.c
lostromb/pocketsphinx-kws
c0c34f0d884e7f3b2de1bb290fbb0b5f093edab2
[ "BSD-3-Clause" ]
11
2018-07-09T19:45:46.000Z
2021-07-05T18:05:47.000Z
C/PocketSphinxTrigger/phone_loop_search.c
lostromb/pocketsphinx-kws
c0c34f0d884e7f3b2de1bb290fbb0b5f093edab2
[ "BSD-3-Clause" ]
2
2019-10-14T12:39:31.000Z
2020-09-26T12:51:10.000Z
C/PocketSphinxTrigger/phone_loop_search.c
lostromb/pocketsphinx-kws
c0c34f0d884e7f3b2de1bb290fbb0b5f093edab2
[ "BSD-3-Clause" ]
4
2018-07-09T20:43:08.000Z
2019-11-07T07:13:01.000Z
/* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* ==================================================================== * Copyright (c) 2008 Carnegie Mellon University. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * This work was supported in part by funding from the Defense Advanced * Research Projects Agency and the National Science Foundation of the * United States of America, and the CMU Sphinx Speech Consortium. * * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ==================================================================== * */ /** * @file phone_loop_search.h Fast and rough context-independent phoneme loop search. */ #include "err.h" #include "phone_loop_search.h" static int phone_loop_search_start(ps_search_t *search); static int phone_loop_search_step(ps_search_t *search, int frame_idx); static int phone_loop_search_finish(ps_search_t *search); static int phone_loop_search_reinit(ps_search_t *search, dict_t *dict, dict2pid_t *d2p); static void phone_loop_search_free(ps_search_t *search); static char const *phone_loop_search_hyp(ps_search_t *search, int32 *out_score); static int32 phone_loop_search_prob(ps_search_t *search); static ps_seg_t *phone_loop_search_seg_iter(ps_search_t *search); static ps_searchfuncs_t phone_loop_search_funcs = { /* start: */ phone_loop_search_start, /* step: */ phone_loop_search_step, /* finish: */ phone_loop_search_finish, /* reinit: */ phone_loop_search_reinit, /* free: */ phone_loop_search_free, /* lattice: */ NULL, /* hyp: */ phone_loop_search_hyp, /* prob: */ phone_loop_search_prob, /* seg_iter: */ phone_loop_search_seg_iter, }; static int phone_loop_search_reinit(ps_search_t *search, dict_t *dict, dict2pid_t *d2p) { phone_loop_search_t *pls = (phone_loop_search_t *)search; cmd_ln_t *config = ps_search_config(search); acmod_t *acmod = ps_search_acmod(search); int i; /* Free old dict2pid, dict, if necessary. */ ps_search_base_reinit(search, dict, d2p); /* Initialize HMM context. */ if (pls->hmmctx) hmm_context_free(pls->hmmctx); pls->hmmctx = hmm_context_init(bin_mdef_n_emit_state(acmod->mdef), acmod->tmat->tp, NULL, acmod->mdef->sseq); if (pls->hmmctx == NULL) return -1; /* Initialize penalty storage */ pls->n_phones = bin_mdef_n_ciphone(acmod->mdef); pls->window = cmd_ln_int32_r(config, "-pl_window"); if (pls->penalties) ckd_free(pls->penalties); pls->penalties = (int32 *)ckd_calloc(pls->n_phones, sizeof(*pls->penalties)); if (pls->pen_buf) ckd_free_2d(pls->pen_buf); pls->pen_buf = (int32 **)ckd_calloc_2d(pls->window, pls->n_phones, sizeof(**pls->pen_buf)); /* Initialize phone HMMs. */ if (pls->hmms) { for (i = 0; i < pls->n_phones; ++i) hmm_deinit((hmm_t *)&pls->hmms[i]); ckd_free(pls->hmms); } pls->hmms = (hmm_t *)ckd_calloc(pls->n_phones, sizeof(*pls->hmms)); for (i = 0; i < pls->n_phones; ++i) { hmm_init(pls->hmmctx, (hmm_t *)&pls->hmms[i], FALSE, bin_mdef_pid2ssid(acmod->mdef, i), bin_mdef_pid2tmatid(acmod->mdef, i)); } pls->penalty_weight = cmd_ln_float64_r(config, "-pl_weight"); pls->beam = logmath_log(acmod->lmath, cmd_ln_float64_r(config, "-pl_beam")) >> SENSCR_SHIFT; pls->pbeam = logmath_log(acmod->lmath, cmd_ln_float64_r(config, "-pl_pbeam")) >> SENSCR_SHIFT; pls->pip = logmath_log(acmod->lmath, cmd_ln_float32_r(config, "-pl_pip")) >> SENSCR_SHIFT; E_INFO("State beam %d Phone exit beam %d Insertion penalty %d\n", pls->beam, pls->pbeam, pls->pip); return 0; } ps_search_t * phone_loop_search_init(cmd_ln_t *config, acmod_t *acmod, dict_t *dict) { phone_loop_search_t *pls; /* Allocate and initialize. */ pls = (phone_loop_search_t *)ckd_calloc(1, sizeof(*pls)); ps_search_init(ps_search_base(pls), &phone_loop_search_funcs, PS_SEARCH_TYPE_PHONE_LOOP, PS_DEFAULT_PL_SEARCH, config, acmod, dict, NULL); phone_loop_search_reinit(ps_search_base(pls), ps_search_dict(pls), ps_search_dict2pid(pls)); return ps_search_base(pls); } static void phone_loop_search_free_renorm(phone_loop_search_t *pls) { gnode_t *gn; for (gn = pls->renorm; gn; gn = gnode_next(gn)) ckd_free(gnode_ptr(gn)); glist_free(pls->renorm); pls->renorm = NULL; } static void phone_loop_search_free(ps_search_t *search) { phone_loop_search_t *pls = (phone_loop_search_t *)search; int i; ps_search_base_free(search); for (i = 0; i < pls->n_phones; ++i) hmm_deinit((hmm_t *)&pls->hmms[i]); phone_loop_search_free_renorm(pls); ckd_free_2d(pls->pen_buf); ckd_free(pls->hmms); ckd_free(pls->penalties); hmm_context_free(pls->hmmctx); ckd_free(pls); } static int phone_loop_search_start(ps_search_t *search) { phone_loop_search_t *pls = (phone_loop_search_t *)search; int i; /* Reset and enter all phone HMMs. */ for (i = 0; i < pls->n_phones; ++i) { hmm_t *hmm = (hmm_t *)&pls->hmms[i]; hmm_clear(hmm); hmm_enter(hmm, 0, -1, 0); } memset(pls->penalties, 0, pls->n_phones * sizeof(*pls->penalties)); for (i = 0; i < pls->window; i++) memset(pls->pen_buf[i], 0, pls->n_phones * sizeof(*pls->pen_buf[i])); phone_loop_search_free_renorm(pls); pls->best_score = 0; pls->pen_buf_ptr = 0; return 0; } static void renormalize_hmms(phone_loop_search_t *pls, int frame_idx, int32 norm) { phone_loop_renorm_t *rn = (phone_loop_renorm_t *)ckd_calloc(1, sizeof(*rn)); int i; pls->renorm = glist_add_ptr(pls->renorm, rn); rn->frame_idx = frame_idx; rn->norm = norm; for (i = 0; i < pls->n_phones; ++i) { hmm_normalize((hmm_t *)&pls->hmms[i], norm); } } static void evaluate_hmms(phone_loop_search_t *pls, int16 const *senscr, int frame_idx) { int32 bs = WORST_SCORE; int i; hmm_context_set_senscore(pls->hmmctx, senscr); for (i = 0; i < pls->n_phones; ++i) { hmm_t *hmm = (hmm_t *)&pls->hmms[i]; int32 score; if (hmm_frame(hmm) < frame_idx) continue; score = hmm_vit_eval(hmm); if (score BETTER_THAN bs) { bs = score; } } pls->best_score = bs; } static void store_scores(phone_loop_search_t *pls, int frame_idx) { int i, j, itr; for (i = 0; i < pls->n_phones; ++i) { hmm_t *hmm = (hmm_t *)&pls->hmms[i]; pls->pen_buf[pls->pen_buf_ptr][i] = (hmm_bestscore(hmm) - pls->best_score) * pls->penalty_weight; } pls->pen_buf_ptr++; pls->pen_buf_ptr = pls->pen_buf_ptr % pls->window; /* update penalties */ for (i = 0; i < pls->n_phones; ++i) { pls->penalties[i] = WORST_SCORE; for (j = 0, itr = pls->pen_buf_ptr + 1; j < pls->window; j++, itr++) { itr = itr % pls->window; if (pls->pen_buf[itr][i] > pls->penalties[i]) pls->penalties[i] = pls->pen_buf[itr][i]; } } } static void prune_hmms(phone_loop_search_t *pls, int frame_idx) { int32 thresh = pls->best_score + pls->beam; int nf = frame_idx + 1; int i; /* Check all phones to see if they remain active in the next frame. */ for (i = 0; i < pls->n_phones; ++i) { hmm_t *hmm = (hmm_t *)&pls->hmms[i]; if (hmm_frame(hmm) < frame_idx) continue; /* Retain if score better than threshold. */ if (hmm_bestscore(hmm) BETTER_THAN thresh) { hmm_frame(hmm) = nf; } else hmm_clear_scores(hmm); } } static void phone_transition(phone_loop_search_t *pls, int frame_idx) { int32 thresh = pls->best_score + pls->pbeam; int nf = frame_idx + 1; int i; /* Now transition out of phones whose last states are inside the * phone transition beam. */ for (i = 0; i < pls->n_phones; ++i) { hmm_t *hmm = (hmm_t *)&pls->hmms[i]; int32 newphone_score; int j; if (hmm_frame(hmm) != nf) continue; newphone_score = hmm_out_score(hmm) + pls->pip; if (newphone_score BETTER_THAN thresh) { /* Transition into all phones using the usual Viterbi rule. */ for (j = 0; j < pls->n_phones; ++j) { hmm_t *nhmm = (hmm_t *)&pls->hmms[j]; if (hmm_frame(nhmm) < frame_idx || newphone_score BETTER_THAN hmm_in_score(nhmm)) { hmm_enter(nhmm, newphone_score, hmm_out_history(hmm), nf); } } } } } static int phone_loop_search_step(ps_search_t *search, int frame_idx) { phone_loop_search_t *pls = (phone_loop_search_t *)search; acmod_t *acmod = ps_search_acmod(search); int16 const *senscr; int i; /* All CI senones are active all the time. */ if (!ps_search_acmod(pls)->compallsen) { acmod_clear_active(ps_search_acmod(pls)); for (i = 0; i < pls->n_phones; ++i) acmod_activate_hmm(acmod, (hmm_t *)&pls->hmms[i]); } /* Calculate senone scores for current frame. */ senscr = acmod_score(acmod, &frame_idx); /* Renormalize, if necessary. */ if (pls->best_score + (2 * pls->beam) WORSE_THAN WORST_SCORE) { E_INFO("Renormalizing Scores at frame %d, best score %d\n", frame_idx, pls->best_score); renormalize_hmms(pls, frame_idx, pls->best_score); } /* Evaluate phone HMMs for current frame. */ evaluate_hmms(pls, senscr, frame_idx); /* Store hmm scores for senone penaly calculation */ store_scores(pls, frame_idx); /* Prune phone HMMs. */ prune_hmms(pls, frame_idx); /* Do phone transitions. */ phone_transition(pls, frame_idx); return 0; } static int phone_loop_search_finish(ps_search_t *search) { /* Actually nothing to do here really. */ return 0; } static char const * phone_loop_search_hyp(ps_search_t *search, int32 *out_score) { E_WARN("Hypotheses are not returned from phone loop search"); return NULL; } static int32 phone_loop_search_prob(ps_search_t *search) { /* FIXME: Actually... they ought to be. */ E_WARN("Posterior probabilities are not returned from phone loop search"); return 0; } static ps_seg_t * phone_loop_search_seg_iter(ps_search_t *search) { E_WARN("Hypotheses are not returned from phone loop search"); return NULL; }
32.269022
105
0.637811
08b910e897044d1d411116e18b16244bafc3144b
177
h
C
examples/courses/v1th04/timer/timer.h
FStoeltie/themaopdracht04
d1c3a9d29fac778d7675b48b14b51c3d7498d228
[ "BSL-1.0" ]
null
null
null
examples/courses/v1th04/timer/timer.h
FStoeltie/themaopdracht04
d1c3a9d29fac778d7675b48b14b51c3d7498d228
[ "BSL-1.0" ]
null
null
null
examples/courses/v1th04/timer/timer.h
FStoeltie/themaopdracht04
d1c3a9d29fac778d7675b48b14b51c3d7498d228
[ "BSL-1.0" ]
null
null
null
// header file for the timer functions // #ifndef NINCLUDE_TIMER_H #define NINCLUDE_TIMER_H void timer_init( void ); unsigned int now(); void await( unsigned int t ); #endif
14.75
38
0.745763
839a04909b1d48940f2b18511c387aadbb321cfe
1,005
c
C
mediaTool/exCh.c
liuyang1/test
a4560e0c9ffd0bc054d55bbcf12a894ab5b7d417
[ "MIT" ]
8
2015-06-07T13:25:48.000Z
2022-03-22T23:14:50.000Z
mediaTool/exCh.c
liuyang1/test
a4560e0c9ffd0bc054d55bbcf12a894ab5b7d417
[ "MIT" ]
30
2016-01-29T01:36:41.000Z
2018-09-19T07:01:22.000Z
mediaTool/exCh.c
liuyang1/test
a4560e0c9ffd0bc054d55bbcf12a894ab5b7d417
[ "MIT" ]
null
null
null
/** extract audiod data as channels 32bit only*/ #include <stdio.h> #include <stdlib.h> #include <stdint.h> void usage(char *name) { printf("%s file chn-all chn-begin chn-number\n", name); } int main(int argc, char **argv) { char *name = argv[0]; if (argc < 5) { usage(name); return -1; } char *fn = argv[1]; int chn = atoi(argv[2]); int bgn = atoi(argv[3]); int num = atoi(argv[4]); if (chn == 0 || num == 0) { usage(name); return -1; } FILE *in = fopen(fn, "ro"); char out_fn[128] = {0}; sprintf(out_fn, "%s.%d.%d.%d", fn, chn, bgn, num); FILE *out = fopen(out_fn, "w"); int32_t i; for (i = 0; ; i++) { int x; int ret = fread(&x, sizeof(int32_t), 1, in); if (ret != 1) { break; } int r = i % chn; if (bgn <= r && r < bgn + num) { fwrite(&x, sizeof(int32_t), 1, out); } } fclose(in); fclose(out); return 0; }
22.840909
59
0.472637
262460d3c8bb7d596e6b22a19325d7f330818a46
5,682
c
C
demo1/axissphere.c
nompelis/INXLib
ba675e029a62bc3fd6f63b88b15bf262e71a00ca
[ "BSD-4-Clause" ]
null
null
null
demo1/axissphere.c
nompelis/INXLib
ba675e029a62bc3fd6f63b88b15bf262e71a00ca
[ "BSD-4-Clause" ]
null
null
null
demo1/axissphere.c
nompelis/INXLib
ba675e029a62bc3fd6f63b88b15bf262e71a00ca
[ "BSD-4-Clause" ]
1
2019-01-26T20:12:35.000Z
2019-01-26T20:12:35.000Z
/* * A utility to make a map-style sphere with normals and texels * Ioannis Nompelis 2016/09/10 */ /****************************************************************************** Copyright (c) 2016, Ioannis Nompelis All rights reserved. Redistribution and use in source and binary forms, with or without any modification, are permitted provided that the following conditions are met: 1. Redistribution of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistribution in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: "This product includes software developed by Ioannis Nompelis." 4. Neither the name of Ioannis Nompelis and his partners/affiliates nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. 5. Redistribution or use of source code and binary forms for profit must have written permission of the copyright holder. THIS SOFTWARE IS PROVIDED BY IOANNIS NOMPELIS ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IOANNIS NOMPELIS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> /* * Function that makes a spherical shell surface of structured quadrilaterals * with a degenerate axis singularity at jmin and jmax. It also generates the * texels for appropriate texture-mapping. */ int inMakeAxisSphereshell(int im, int jm, double **x, double **y, double **z, double **u, double **v, double **w, float **p, float **q) { int i,j,n; size_t isize; double pi,angle,azimuth; double ksi,eta; pi = acos(-1.0); isize = im*jm; *x = (double *) malloc(isize*sizeof(double)); *y = (double *) malloc(isize*sizeof(double)); *z = (double *) malloc(isize*sizeof(double)); *u = (double *) malloc(isize*sizeof(double)); *v = (double *) malloc(isize*sizeof(double)); *w = (double *) malloc(isize*sizeof(double)); *p = (float *) malloc(isize*sizeof(float)); *q = (float *) malloc(isize*sizeof(float)); if(*x == NULL || *y == NULL || *z == NULL || *u == NULL || *v == NULL || *w == NULL || *p == NULL || *q == NULL) { fprintf(stdout," e [inAxisSphereshell] Could not allocate arrays \n"); if(*x != NULL) free(*x); if(*y != NULL) free(*y); if(*z != NULL) free(*z); if(*u != NULL) free(*u); if(*v != NULL) free(*v); if(*w != NULL) free(*w); if(*p != NULL) free(*p); if(*q != NULL) free(*q); return(1); } for(i=0;i<im;++i) { ksi = ((double) i)/ ((double) (im-1)); angle = 2.0*pi * ksi; for(j=0;j<jm;++j) { eta = ((double) j)/ ((double) (jm-1)); azimuth = pi * (1.0 - eta); n = i*jm + j; (*x)[n] = cos(angle)*sin(azimuth); (*y)[n] = cos(azimuth); (*z)[n] = sin(angle)*sin(azimuth); // normals (*u)[n] = (*x)[n]; (*v)[n] = (*y)[n]; (*w)[n] = (*z)[n]; // texels (*p)[n] = (float) ksi; (*q)[n] = (float) eta; /* // sheet (*x)[n] = ((double) i)/((double) im); (*y)[n] = ((double) j)/((double) im); (*z)[n] = 0.0; // sheet normals (*u)[n] = 0.0; (*v)[n] = 0.0; (*w)[n] = 1.0; */ // scale all vertices by a factor (*x)[n] = (*x)[n] * 0.1; (*y)[n] = (*y)[n] * 0.1; (*z)[n] = (*z)[n] * 0.1; } } return(0); } /* * Function to plot the geometry in TecPlot or ParaView */ int inDumpTecplotShell(char *fname, int im, int jm, double *x, double *y, double *z, double *u, double *v, double *w, float *p, float *q) { int i,j; FILE *fp; fp = fopen(fname,"w"); if(fp == NULL) { fprintf(stdout," e Could not create file \"%s\" \n",fname); return(1); } fprintf(fp,"variables = x y z u v w p q \n"); fprintf(fp,"zone T=\"sphere shell\", i=%d, j=%d,k=1, f=point \n",im,jm); for(j=0;j<jm;++j) { for(i=0;i<im;++i) { int n = i*jm + j; fprintf(fp," %lf %lf %lf \n",x[n],y[n],z[n]); fprintf(fp," %lf %lf %lf \n",u[n],v[n],w[n]); fprintf(fp," %f %f \n",p[n],q[n]); } } fclose(fp); return(0); } // Compile this file with "-DMAIN" to run it standalone #ifdef MAIN int main() { int im = 40,jm = 20; double *x,*y,*z; double *u,*v,*w; float *p,*q; (void) inMakeAxisSphereshell(im,jm,&x,&y,&z,&u,&v,&w,&p,&q); (void) inDumpTecplotShell("shell.dat",im,jm,x,y,z, u,v,w, p,q); return(0); } #endif
31.04918
80
0.561246
267851d082c545795a101576713249bcfb663fad
295
h
C
search/Person.h
shuaiAdmin/learnDemo
be5913e520a25e87f59313f0b32cfb7ba728da1f
[ "MIT" ]
1
2016-09-07T08:05:00.000Z
2016-09-07T08:05:00.000Z
search/Person.h
shuaiAdmin/learnDemo
be5913e520a25e87f59313f0b32cfb7ba728da1f
[ "MIT" ]
null
null
null
search/Person.h
shuaiAdmin/learnDemo
be5913e520a25e87f59313f0b32cfb7ba728da1f
[ "MIT" ]
null
null
null
// // Person.h // search // // Created by 王帅 on 16/9/2. // Copyright © 2016年 shuai. All rights reserved. // #import <Foundation/Foundation.h> @interface Person : NSObject @property(nonatomic, copy)NSString * age; @property(nonatomic, assign)double money; + (void)run; + (void)study; @end
16.388889
49
0.681356
03b05c54722dd5cee090501697550d8e20cd621c
3,721
h
C
linux-5.4.67/drivers/gpu/drm/vkms/vkms_drv.h
d0lim/linux-class
4947e6915f0534648c7d0d9a3ef28b29165f0f6a
[ "MIT" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
linux-5.4.67/drivers/gpu/drm/vkms/vkms_drv.h
d0lim/linux-class
4947e6915f0534648c7d0d9a3ef28b29165f0f6a
[ "MIT" ]
null
null
null
linux-5.4.67/drivers/gpu/drm/vkms/vkms_drv.h
d0lim/linux-class
4947e6915f0534648c7d0d9a3ef28b29165f0f6a
[ "MIT" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
/* SPDX-License-Identifier: GPL-2.0+ */ #ifndef _VKMS_DRV_H_ #define _VKMS_DRV_H_ #include <linux/hrtimer.h> #include <drm/drm.h> #include <drm/drm_gem.h> #include <drm/drm_encoder.h> #define XRES_MIN 20 #define YRES_MIN 20 #define XRES_DEF 1024 #define YRES_DEF 768 #define XRES_MAX 8192 #define YRES_MAX 8192 extern bool enable_cursor; struct vkms_composer { struct drm_framebuffer fb; struct drm_rect src, dst; unsigned int offset; unsigned int pitch; unsigned int cpp; }; /** * vkms_plane_state - Driver specific plane state * @base: base plane state * @composer: data required for composing computation */ struct vkms_plane_state { struct drm_plane_state base; struct vkms_composer *composer; }; /** * vkms_crtc_state - Driver specific CRTC state * @base: base CRTC state * @composer_work: work struct to compose and add CRC entries * @n_frame_start: start frame number for computed CRC * @n_frame_end: end frame number for computed CRC */ struct vkms_crtc_state { struct drm_crtc_state base; struct work_struct composer_work; int num_active_planes; /* stack of active planes for crc computation, should be in z order */ struct vkms_plane_state **active_planes; /* below three are protected by vkms_output.composer_lock */ bool crc_pending; u64 frame_start; u64 frame_end; }; struct vkms_output { struct drm_crtc crtc; struct drm_encoder encoder; struct drm_connector connector; struct hrtimer vblank_hrtimer; ktime_t period_ns; struct drm_pending_vblank_event *event; /* ordered wq for composer_work */ struct workqueue_struct *composer_workq; /* protects concurrent access to composer */ spinlock_t lock; /* protected by @lock */ bool composer_enabled; struct vkms_crtc_state *composer_state; spinlock_t composer_lock; }; struct vkms_device { struct drm_device drm; struct platform_device *platform; struct vkms_output output; }; struct vkms_gem_object { struct drm_gem_object gem; struct mutex pages_lock; /* Page lock used in page fault handler */ struct page **pages; unsigned int vmap_count; void *vaddr; }; #define drm_crtc_to_vkms_output(target) \ container_of(target, struct vkms_output, crtc) #define drm_device_to_vkms_device(target) \ container_of(target, struct vkms_device, drm) #define drm_gem_to_vkms_gem(target)\ container_of(target, struct vkms_gem_object, gem) #define to_vkms_crtc_state(target)\ container_of(target, struct vkms_crtc_state, base) #define to_vkms_plane_state(target)\ container_of(target, struct vkms_plane_state, base) /* CRTC */ int vkms_crtc_init(struct drm_device *dev, struct drm_crtc *crtc, struct drm_plane *primary, struct drm_plane *cursor); bool vkms_get_vblank_timestamp(struct drm_device *dev, unsigned int pipe, int *max_error, ktime_t *vblank_time, bool in_vblank_irq); int vkms_output_init(struct vkms_device *vkmsdev, int index); struct drm_plane *vkms_plane_init(struct vkms_device *vkmsdev, enum drm_plane_type type, int index); /* Gem stuff */ vm_fault_t vkms_gem_fault(struct vm_fault *vmf); int vkms_dumb_create(struct drm_file *file, struct drm_device *dev, struct drm_mode_create_dumb *args); void vkms_gem_free_object(struct drm_gem_object *obj); int vkms_gem_vmap(struct drm_gem_object *obj); void vkms_gem_vunmap(struct drm_gem_object *obj); /* CRC Support */ const char *const *vkms_get_crc_sources(struct drm_crtc *crtc, size_t *count); int vkms_set_crc_source(struct drm_crtc *crtc, const char *src_name); int vkms_verify_crc_source(struct drm_crtc *crtc, const char *source_name, size_t *values_cnt); /* Composer Support */ void vkms_composer_worker(struct work_struct *work); #endif /* _VKMS_DRV_H_ */
25.486301
74
0.769148
c13324d86a802ce1373024b31a5eda62c219925c
393
h
C
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Elements.Perspec-cd6b1b54.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Elements.Perspec-cd6b1b54.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Elements.Perspec-cd6b1b54.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Controls/1.9.0/Viewport.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace Fuse{ namespace Elements{ // public enum PerspectiveRelativeToMode :21 uEnumType* PerspectiveRelativeToMode_typeof(); }}} // ::g::Fuse::Elements
26.2
120
0.765903
6c473fa96ec79d79f19f0c91c2a057ec8fe12ac6
4,203
h
C
tcmalloc/src/stacktrace_win32-inl.h
johnzhd/learnandtraining
31cc0595cded675c3c860920dfb57b0e49727a52
[ "MIT" ]
null
null
null
tcmalloc/src/stacktrace_win32-inl.h
johnzhd/learnandtraining
31cc0595cded675c3c860920dfb57b0e49727a52
[ "MIT" ]
null
null
null
tcmalloc/src/stacktrace_win32-inl.h
johnzhd/learnandtraining
31cc0595cded675c3c860920dfb57b0e49727a52
[ "MIT" ]
1
2019-04-30T18:56:59.000Z
2019-04-30T18:56:59.000Z
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // --- // Produces a stack trace for Windows. Normally, one could use // stacktrace_x86-inl.h or stacktrace_x86_64-inl.h -- and indeed, that // should work for binaries compiled using MSVC in "debug" mode. // However, in "release" mode, Windows uses frame-pointer // optimization, which makes getting a stack trace very difficult. // // There are several approaches one can take. One is to use Windows // intrinsics like StackWalk64. These can work, but have restrictions // on how successful they can be. Another attempt is to write a // version of stacktrace_x86-inl.h that has heuristic support for // dealing with FPO, similar to what WinDbg does (see // http://www.nynaeve.net/?p=97). // // The solution we've ended up doing is to call the undocumented // windows function RtlCaptureStackBackTrace, which probably doesn't // work with FPO but at least is fast, and doesn't require a symbol // server. // // This code is inspired by a patch from David Vitek: // http://code.google.com/p/gperftools/issues/detail?id=83 #ifndef BASE_STACKTRACE_WIN32_INL_H_ #define BASE_STACKTRACE_WIN32_INL_H_ // Note: this file is included into stacktrace.cc more than once. // Anything that should only be defined once should be here: #include "config.h" #include <windows.h> // for GetProcAddress and GetModuleHandle #include <assert.h> typedef USHORT NTAPI RtlCaptureStackBackTrace_Function( IN ULONG frames_to_skip, IN ULONG frames_to_capture, OUT PVOID *backtrace, OUT PULONG backtrace_hash); // Load the function we need at static init time, where we don't have // to worry about someone else holding the loader's lock. static RtlCaptureStackBackTrace_Function* const RtlCaptureStackBackTrace_fn = (RtlCaptureStackBackTrace_Function*) GetProcAddress(GetModuleHandleA("ntdll.dll"), "RtlCaptureStackBackTrace"); PERFTOOLS_DLL_DECL int GetStackTrace(void** result, int max_depth, int skip_count) { if (!RtlCaptureStackBackTrace_fn) { // TODO(csilvers): should we log an error here? return 0; // can't find a stacktrace with no function to call } return (int)RtlCaptureStackBackTrace_fn(skip_count + 2, max_depth, result, 0); } PERFTOOLS_DLL_DECL int GetStackFrames(void** /* pcs */, int* /* sizes */, int /* max_depth */, int /* skip_count */) { assert(0 == "Not yet implemented"); return 0; } #endif // BASE_STACKTRACE_WIN32_INL_H_
45.193548
77
0.717821
887bdc5e9bac05e22c0564e50daba26639238846
2,695
h
C
platform/shared/tcmalloc/rhomem.h
malayap47/dummy
4e5987c4cd60332c297f36e4ad95fd5649943880
[ "MIT" ]
null
null
null
platform/shared/tcmalloc/rhomem.h
malayap47/dummy
4e5987c4cd60332c297f36e4ad95fd5649943880
[ "MIT" ]
null
null
null
platform/shared/tcmalloc/rhomem.h
malayap47/dummy
4e5987c4cd60332c297f36e4ad95fd5649943880
[ "MIT" ]
null
null
null
#ifndef RHO_MEMORY__ #define RHO_MEMORY__ #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif //_CRT_SECURE_NO_DEPRECATE //#ifndef __APPLE__ #if 0 //defined( _WIN32_WCE ) && !defined(WCE_PLATFORM_MC3000C50B) && !defined (WCE_PLATFORM_WT41N0) #include <stdlib.h> #ifndef _RHO_NO_MEMDEFINES #undef _CRTDBG_MAP_ALLOC #if (defined( _WIN32_WCE ) || defined( WIN32 )) && !defined( _SIZE_T_DEFINED) typedef unsigned int size_t; #define _SIZE_T_DEFINED 1 #endif #if defined(__SYMBIAN32__) && !defined( _SIZE_T_DECLARED) typedef unsigned int size_t; #define _SIZE_T_DECLARED 1 #endif #if defined(__APPLE__) && !defined( _SIZE_T) typedef unsigned int size_t; #define _SIZE_T 1 #endif #ifdef __cplusplus extern "C" { #endif void rho_free(void *); void * rho_malloc(size_t); void * rho_calloc(size_t num, size_t size); size_t rho_msize(void *); void * rho_realloc(void *, size_t); char * rho_strdup(const char *); wchar_t * rho_wcsdup(const wchar_t * str); void sys_free(void *); #ifdef __cplusplus } #endif #undef free #undef malloc #undef calloc #undef _msize #undef realloc #undef strdup #undef _strdup #undef _wcsdup //#define _recalloc(p, n, s) rho_realloc(p, n*s) #define free(p) rho_free(p) #define malloc(s) rho_malloc(s) #define calloc(num, size) rho_calloc(num,size) #define _msize( p) rho_msize(p) #define realloc(p, s) rho_realloc(p,s) #define strdup(s) rho_strdup(s) #define _strdup(s) rho_strdup(s) #define _wcsdup(s) rho_wcsdup(s) #ifndef __SYMBIAN32__ #ifdef __cplusplus void* cpp_alloc(size_t size, bool nothrow); #include <new> #ifndef __THROW #define __THROW throw() #endif inline void* operator new(size_t size) { void* p = cpp_alloc(size, false); return p; } inline void operator delete(void* p) __THROW { rho_free(p); } inline void* operator new[](size_t size) { void* p = cpp_alloc(size, false); return p; } inline void operator delete[](void* p) __THROW { rho_free(p); } /* #ifndef __NOTHROW_T_DEFINED #define __NOTHROW_T_DEFINED namespace std { struct nothrow_t {}; extern const nothrow_t nothrow; }; #endif //__NOTHROW_T_DEFINED */ inline void operator delete(void* p, const std::nothrow_t&) __THROW { rho_free(p); } inline void* operator new[](size_t size, const std::nothrow_t&) __THROW { void* p = cpp_alloc(size, true); return p; } inline void operator delete[](void* p, const std::nothrow_t&) __THROW { rho_free(p); } inline void* operator new(size_t size, const std::nothrow_t&) __THROW { void* p = cpp_alloc(size, true); return p; } #endif// __cplusplus #endif #endif //_RHO_NO_MEMDEFINES #else #define sys_free free //#endif// _WIN32_WCE #endif #endif // RHO_MEMORY__
20.572519
100
0.728015
b719df6c70ccefefab6b198d07215fa7bb8f0429
1,153
c
C
d/dagger/phederia/rooms/keep/k16.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/dagger/phederia/rooms/keep/k16.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/dagger/phederia/rooms/keep/k16.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> #include "/d/dagger/phederia/phedefs.h" inherit ROOM; void create(){ ::create(); set_property("light",2); set_property("no teleport",1); set_short( "At the bottom of the Dismal walls of the Rose Keep." ); set_long( "At the bottom of the Dismal walls of the Rose Keep.\n" " The walls of the rose keep rise above you here blocking even the grey light that permeates the whole area." " A dim building is faintly visible to the east and the walls fade away to grey to the west and the steep walls of the inner keep rise up to the south." "\n" ); set_smell("default", "The smell of blood lays faint in the air." ); set_listen("default", "Echoing footsteps ring from contacts on stone somewhere above you." ); set_items(([ "building":"A dim stone building set into the base of the corner of the outer wall. Not much can be seen of it.", "walls":"The walls seem to fill you with dread and imposing menace towering over you.", ({"keep","inner keep"}):"All you can see are the walls fading into the greyness above you.", ])); set_exits(([ "east":KEEP"k15.c", "west":KEEP"k17.c", ])); }
32.942857
155
0.685169
8d83acb3cbd9b53a867a5d4aed006b4ded63c8c1
3,092
h
C
similarity_search/include/report_intr_dim.h
GuilhemN/nmslib
9c464c077a9dd7e3d453b44e9a1b39829034d68e
[ "Apache-2.0" ]
2,031
2018-03-29T00:59:55.000Z
2022-03-31T23:54:33.000Z
similarity_search/include/report_intr_dim.h
GuilhemN/nmslib
9c464c077a9dd7e3d453b44e9a1b39829034d68e
[ "Apache-2.0" ]
262
2018-03-29T17:44:53.000Z
2022-03-31T02:56:40.000Z
similarity_search/include/report_intr_dim.h
GuilhemN/nmslib
9c464c077a9dd7e3d453b44e9a1b39829034d68e
[ "Apache-2.0" ]
281
2018-03-29T13:12:50.000Z
2022-03-28T15:18:31.000Z
/** * Non-metric Space Library * * Main developers: Bilegsaikhan Naidan, Leonid Boytsov, Yury Malkov, Ben Frederickson, David Novak * * For the complete list of contributors and further details see: * https://github.com/nmslib/nmslib * * Copyright (c) 2013-2018 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #ifndef REPORT_INTR_DIM_H #define REPORT_INTR_DIM_H #include <string> #include "object.h" #include "my_isnan_isinf.h" namespace similarity { /* * This version of intrinsic dimensionality is defined in * E. Chavez, G. Navarro, R. Baeza-Yates, and J. L. Marroquin, 2001, Searching in metric spaces. * * Note that this measure may be irrelevant in non-metric spaces. */ template <typename dist_t> void ComputeIntrinsicDimensionality(const Space<dist_t>& space, const ObjectVector& dataset, double& IntrDim, double& DistMean, double& DistSigma, std::vector<double>& dist, size_t SampleQty = 1000000) { DistMean = 0; dist.clear(); for (size_t n = 0; n < SampleQty; ++n) { size_t r1 = RandomInt() % dataset.size(); size_t r2 = RandomInt() % dataset.size(); CHECK(r1 < dataset.size()); CHECK(r2 < dataset.size()); const Object* obj1 = dataset[r1]; const Object* obj2 = dataset[r2]; dist_t d = space.IndexTimeDistance(obj1, obj2); dist.push_back(d); if (my_isnan(d)) { /* * TODO: @leo Dump object contents here. To this end, * we need to subclass objects, so that sparse * vectors, dense vectors and other objects * can implement their own dump function. */ throw runtime_error("!!! Bug: a distance returned NAN!"); } DistMean += d; } DistMean /= double(SampleQty); DistSigma = 0; for (size_t i = 0; i < SampleQty; ++i) { DistSigma += (dist[i] - DistMean) * (dist[i] - DistMean); } DistSigma /= double(SampleQty); IntrDim = DistMean * DistMean / (2 * DistSigma); DistSigma = sqrt(DistSigma); } template <typename dist_t> void ReportIntrinsicDimensionality(const string& reportName, const Space<dist_t>& space, const ObjectVector& dataset, std::vector<double>& dist, size_t SampleQty = 1000000) { double DistMean, DistSigma, IntrDim; ComputeIntrinsicDimensionality(space, dataset, IntrDim, DistMean, DistSigma, dist, SampleQty); LOG(LIB_INFO) << "### " << reportName; LOG(LIB_INFO) << "### intrinsic dim: " << IntrDim; LOG(LIB_INFO) << "### distance mean: " << DistMean; LOG(LIB_INFO) << "### distance sigma: " << DistSigma; } } #endif
32.893617
99
0.557245
9d641180b145c4ea926d2fab047acd6715c68d42
1,648
h
C
jack/macosx/coremidi/JackCoreMidiPhysicalOutputPort.h
KimJeongYeon/jack2_android
4a8787be4306558cb52e5379466c0ed4cc67e788
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
47
2015-01-04T21:47:07.000Z
2022-03-23T16:27:16.000Z
vendor/samsung/external/jack/macosx/coremidi/JackCoreMidiPhysicalOutputPort.h
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
3
2015-02-04T21:40:11.000Z
2019-09-16T19:53:51.000Z
jack/macosx/coremidi/JackCoreMidiPhysicalOutputPort.h
KimJeongYeon/jack2_android
4a8787be4306558cb52e5379466c0ed4cc67e788
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
7
2015-05-17T08:22:52.000Z
2021-08-07T22:36:17.000Z
/* Copyright (C) 2011 Devin Anderson This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __JackCoreMidiPhysicalOutputPort__ #define __JackCoreMidiPhysicalOutputPort__ #include "JackCoreMidiOutputPort.h" namespace Jack { class JackCoreMidiPhysicalOutputPort: public JackCoreMidiOutputPort { private: MIDIPortRef internal_output; protected: bool SendPacketList(MIDIPacketList *packet_list); public: JackCoreMidiPhysicalOutputPort(const char *alias_name, const char *client_name, const char *driver_name, int index, MIDIClientRef client, MIDIPortRef internal_output, double time_ratio, size_t max_bytes=4096, size_t max_messages=1024); ~JackCoreMidiPhysicalOutputPort(); }; } #endif
29.428571
74
0.645631
f200aad93ed0698dffd92c3320fc5403cb64b77e
40,762
c
C
patch/c/micropython/ports/esp32/modcamera.c
remibert/pycameresp
cdb2bddadfbd3627c653663ede4e37a63f48f788
[ "MIT" ]
28
2021-01-19T10:53:20.000Z
2022-03-24T13:57:09.000Z
patch/c/micropython/ports/esp32/modcamera.c
remibert/pycameresp
cdb2bddadfbd3627c653663ede4e37a63f48f788
[ "MIT" ]
5
2021-02-28T23:00:23.000Z
2022-03-30T07:36:21.000Z
patch/c/micropython/ports/esp32/modcamera.c
remibert/pycameresp
cdb2bddadfbd3627c653663ede4e37a63f48f788
[ "MIT" ]
9
2021-02-28T23:01:37.000Z
2022-03-24T13:57:18.000Z
// Code adapted from https://github.com/espressif/esp32-camera #include "string.h" #include "esp_log.h" #include "esp_jpg_decode.h" #include "esp_system.h" #include "esp_spi_flash.h" #include "py/nlr.h" #include "py/obj.h" #include "py/runtime.h" #include "py/binary.h" #include "py/objstr.h" #ifdef CONFIG_ESP32CAM #include "esp_camera.h" #endif #define TAG "camera" #define _ ESP_LOGE(TAG, "%s:%d:%s",__FILE__,__LINE__,__FUNCTION__); #define min(a,b) ((a)<(b) ?(a):(b)) #define max(a,b) ((a)>(b) ?(a):(b)) #ifdef CONFIG_ESP32CAM #define CAMERA_SETTING(type, field, method, min, max) \ STATIC mp_obj_t camera_##method(size_t n_args, const mp_obj_t *args)\ {\ if (n_args == 0) \ {\ sensor_t *s = esp_camera_sensor_get();\ if (s)\ {\ return mp_obj_new_int((int)s->status.field);\ }\ else\ {\ mp_raise_ValueError(MP_ERROR_TEXT("Camera sensor get " #method " not possible : driver not opened"));\ }\ }\ else\ {\ type value = (type)mp_obj_get_int(args[0]);\ if (value >= min && value <= max)\ {\ sensor_t *s = esp_camera_sensor_get();\ if (s)\ {\ s->set_ ## method(s,(type)value);\ }\ else\ {\ mp_raise_ValueError(MP_ERROR_TEXT("Camera sensor set " #method " not possible : driver not opened"));\ }\ }\ else\ {\ mp_raise_ValueError(MP_ERROR_TEXT("Camera sensor set " #method " : value out of limits [" #min "-" #max "]"));\ }\ }\ return mp_const_none;\ }\ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(camera_##method##_obj, 0, 1, camera_##method); //WROVER-KIT PIN Map #define CAM_PIN_PWDN 32 //power down is not used #define CAM_PIN_RESET -1 //software reset will be performed #define CAM_PIN_XCLK 0 #define CAM_PIN_SIOD 26 // SDA #define CAM_PIN_SIOC 27 // SCL #define CAM_PIN_D7 35 #define CAM_PIN_D6 34 #define CAM_PIN_D5 39 #define CAM_PIN_D4 36 #define CAM_PIN_D3 21 #define CAM_PIN_D2 19 #define CAM_PIN_D1 18 #define CAM_PIN_D0 5 #define CAM_PIN_VSYNC 25 #define CAM_PIN_HREF 23 #define CAM_PIN_PCLK 22 static camera_config_t camera_config = { .pin_pwdn = CAM_PIN_PWDN, .pin_reset = CAM_PIN_RESET, .pin_xclk = CAM_PIN_XCLK, .pin_sscb_sda = CAM_PIN_SIOD, .pin_sscb_scl = CAM_PIN_SIOC, .pin_d7 = CAM_PIN_D7, .pin_d6 = CAM_PIN_D6, .pin_d5 = CAM_PIN_D5, .pin_d4 = CAM_PIN_D4, .pin_d3 = CAM_PIN_D3, .pin_d2 = CAM_PIN_D2, .pin_d1 = CAM_PIN_D1, .pin_d0 = CAM_PIN_D0, .pin_vsync = CAM_PIN_VSYNC, .pin_href = CAM_PIN_HREF, .pin_pclk = CAM_PIN_PCLK, //XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental) .xclk_freq_hz = 20000000, .ledc_timer = LEDC_TIMER_0, .ledc_channel = LEDC_CHANNEL_0, .pixel_format = PIXFORMAT_JPEG,//YUV422,GRAYSCALE,RGB565,JPEG .frame_size = FRAMESIZE_UXGA,//QQVGA-UXGA Do not use sizes above QVGA when not JPEG .jpeg_quality = 12, //0-63 lower number means higher quality .fb_count = 1 //if more than one, i2s runs in continuous mode. Use only with JPEG }; #endif typedef struct Shape_t { uint16_t id; uint32_t x; uint32_t y; uint16_t minx; uint16_t maxx; uint16_t miny; uint16_t maxy; uint16_t size; } Shape_t; #define MAX_LINES 4 // Straight line portion typedef struct { int x; // First x point of line int y; // First y point of line int a; // a * x + b int b; } Line_t; typedef struct { mp_obj_base_t base; uint8_t *imageData; uint32_t imageLength; uint16_t height; uint16_t width; const uint8_t *input; uint16_t diffWidth; uint16_t diffHeight; uint16_t diffMax; uint16_t square_x; uint16_t square_y; uint16_t *lights; uint16_t *diffs; uint16_t *stack; #define MAX_HISTO 16 uint16_t histo[MAX_HISTO]; uint16_t stackpos; } Motion_t; const mp_obj_type_t Motion_type; typedef struct { uint8_t * mask_data; uint16_t mask_length; Line_t errorLights[MAX_LINES]; Line_t errorHistos[MAX_LINES]; } MotionConfiguration_t; MotionConfiguration_t motionConfiguration = {0,0}; // Create motion objet with an image static Motion_t * Motion_new(const uint8_t *imageData, size_t imageLength); #pragma GCC diagnostic ignored "-Wtype-limits" #ifdef CONFIG_ESP32CAM // type, get set , min, max // https://heyrick.eu/blog/index.php?diary=20210418 CAMERA_SETTING(uint16_t , aec_value , aec_value , 0, 1200) CAMERA_SETTING(framesize_t, framesize , framesize , FRAMESIZE_96X96, FRAMESIZE_QSXGA) CAMERA_SETTING(uint8_t , quality , quality , 0, 63 ) CAMERA_SETTING(uint8_t , special_effect, special_effect, 0, 6 ) CAMERA_SETTING(uint8_t , wb_mode , wb_mode , 0, 4 ) // White balance mode CAMERA_SETTING(uint8_t , agc_gain , agc_gain , 0, 30 ) // Automatic gain control CAMERA_SETTING(uint8_t , gainceiling , gainceiling , 0, 6 ) CAMERA_SETTING(int8_t , brightness , brightness , -2, 2 ) CAMERA_SETTING(int8_t , contrast , contrast , -2, 2 ) CAMERA_SETTING(int8_t , saturation , saturation , -2, 2 ) CAMERA_SETTING(int8_t , sharpness , sharpness , -2, 2 ) CAMERA_SETTING(int8_t , ae_level , ae_level , -2, 2 ) // Automatic exposure CAMERA_SETTING(uint8_t , denoise , denoise , 0, 255 ) CAMERA_SETTING(uint8_t , awb , whitebal , 0, 255 ) // Automatic white balance CAMERA_SETTING(uint8_t , awb_gain , awb_gain , 0, 255 ) // Automatic white balance gain CAMERA_SETTING(uint8_t , aec , exposure_ctrl , 0, 255 ) // Automatic exposure control CAMERA_SETTING(uint8_t , aec2 , aec2 , 0, 255 ) // Automatic exposure control 2 CAMERA_SETTING(uint8_t , agc , gain_ctrl , 0, 255 ) // Automatic gain control CAMERA_SETTING(uint8_t , bpc , bpc , 0, 255 ) // Black pixel correction CAMERA_SETTING(uint8_t , wpc , wpc , 0, 255 ) // White pixel correction CAMERA_SETTING(uint8_t , raw_gma , raw_gma , 0, 255 ) CAMERA_SETTING(uint8_t , lenc , lenc , 0, 255 ) CAMERA_SETTING(uint8_t , hmirror , hmirror , 0, 255 ) CAMERA_SETTING(uint8_t , vflip , vflip , 0, 255 ) CAMERA_SETTING(uint8_t , dcw , dcw , 0, 255 ) // Downsize EN CAMERA_SETTING(uint8_t , colorbar , colorbar , 0, 255 ) #endif #pragma GCC diagnostic pop static void *_malloc(size_t size) { void * result = heap_caps_calloc(1, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); if (result == 0) { ESP_LOGE(TAG, "Malloc failed !!!!!!"); } return result; } static void _free(void ** ptr) { if (ptr) { if (*ptr) { free(*ptr); *ptr = 0; } } } // Get list item at the index mp_obj_t list_get_item(mp_obj_t list, size_t index) { mp_obj_t result = mp_const_none; size_t length; mp_obj_t *items; mp_obj_list_get(list, &length, &items); if (index < length) { result = items[index]; } return result; } size_t list_get_size(mp_obj_t list) { size_t result = 0; mp_obj_t *items; mp_obj_list_get(list, &result, &items); return result; } #ifdef CONFIG_ESP32CAM STATIC mp_obj_t camera_pixformat(size_t n_args, const mp_obj_t *args) { if (n_args == 0) { sensor_t *s = esp_camera_sensor_get(); if (s) { return mp_obj_new_int((int)s->pixformat); } else { mp_raise_ValueError(MP_ERROR_TEXT("Camera get pixformat not possible : driver not opened")); } } else { pixformat_t value = (pixformat_t)mp_obj_get_int(args[0]); if (value >= PIXFORMAT_RGB565 && value <= PIXFORMAT_RGB555) { sensor_t *s = esp_camera_sensor_get(); if (s) { s->set_pixformat(s,(pixformat_t)value); } else { mp_raise_ValueError(MP_ERROR_TEXT("Camera set pixformat not possible : driver not opened")); } } else { mp_raise_ValueError(MP_ERROR_TEXT("Camera set pixformat : value out of limits [PIXFORMAT_RGB565-PIXFORMAT_RGB555]")); } } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(camera_pixformat_obj, 0, 1, camera_pixformat); #endif STATIC mp_obj_t camera_isavailable() { #ifdef CONFIG_ESP32CAM return mp_const_true; #else return mp_const_false; #endif } STATIC MP_DEFINE_CONST_FUN_OBJ_0(camera_isavailable_obj, camera_isavailable); #ifdef CONFIG_ESP32CAM STATIC mp_obj_t camera_init() { esp_err_t err = esp_camera_init(&camera_config); if (err != ESP_OK) { ESP_LOGE(TAG, "Camera init failed"); return mp_const_false; } return mp_const_true; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(camera_init_obj, camera_init); STATIC mp_obj_t camera_deinit() { esp_err_t err = esp_camera_deinit(); if (err != ESP_OK) { ESP_LOGE(TAG, "Camera deinit failed"); return mp_const_false; } return mp_const_true; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(camera_deinit_obj, camera_deinit); typedef struct { mp_obj_t writeCallback; uint16_t height; uint16_t width; const uint8_t *input; } Decoder_t; static uint32_t camera_decodeRead(void * arg, size_t index, uint8_t *buf, size_t len) { Decoder_t * decoder = (Decoder_t *)arg; if(buf) { memcpy(buf, decoder->input + index, len); } return len; } //output buffer and image width static bool camera_decodeImage(void * arg, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint8_t *data) { Decoder_t * decoder = (Decoder_t *)arg; // First access if(!data) { if(x == 0 && y == 0) { // Get the size of image decoder->width = w; decoder->height = h; } else { // Write end } } else { int Y, X; //unsigned int red; //unsigned int green; //unsigned int blue; //uint8_t * pdata; ESP_LOGE(TAG, "Decode x=%d, y=%d, w=%d, h=%d",x,y,w,h); for (Y = y; Y < (y + h); Y ++) { for (X = x; X < (x + w); X ++) { //pdata = &(data[(X-x)*3]); //blue = *pdata; pdata++; //green = *pdata; pdata++; //red = *pdata; pdata++; } data += (w * 3); } } return true; } // Decode image STATIC mp_obj_t camera_decode(mp_obj_t image_in, mp_obj_t write_callback_in) { if (mp_obj_is_str_or_bytes(image_in)) { Decoder_t decoder; GET_STR_DATA_LEN(image_in, imageData, imageLength); memset(&decoder, 0, sizeof(decoder)); decoder.input = imageData; if (write_callback_in != mp_const_none && !mp_obj_is_callable(write_callback_in)) { mp_raise_ValueError(MP_ERROR_TEXT("Invalid write_callback")); } else { decoder.writeCallback = write_callback_in; esp_err_t ret = esp_jpg_decode(imageLength, JPG_SCALE_8X, camera_decodeRead, camera_decodeImage, (void*)&decoder); if (ret != ESP_OK) { mp_raise_ValueError(MP_ERROR_TEXT("Decoder error failed"));\ } } } else { mp_raise_ValueError(MP_ERROR_TEXT("Invalid image buffer")); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(camera_decode_obj, camera_decode); STATIC mp_obj_t camera_capture() { camera_fb_t * fb; // Acquire a frame fb = esp_camera_fb_get(); if (!fb) { ESP_LOGE(TAG, "Camera capture Failed"); return mp_const_none; } mp_obj_t image = mp_obj_new_bytes(fb->buf, fb->len); // Return the frame buffer back to the driver for reuse esp_camera_fb_return(fb); return image; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(camera_capture_obj, camera_capture); // Get motion information STATIC mp_obj_t camera_motion_detect() { mp_obj_t res; camera_fb_t * fb; fb = esp_camera_fb_get(); if (!fb) { ESP_LOGE(TAG, "Camera capture Failed"); return mp_const_none; } res = Motion_new(fb->buf, fb->len); esp_camera_fb_return(fb); return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(camera_motion_detect_obj, camera_motion_detect); // Switch on or off the flash led STATIC mp_obj_t camera_flash(mp_obj_t level_in) { if (mp_obj_is_int(level_in)) { int level = mp_obj_get_int(level_in); periph_module_enable(PERIPH_LEDC_MODULE); // Set up timer ledc_timer_config_t flash_led_timer = { // Set timer resolution .duty_resolution = LEDC_TIMER_8_BIT, // Set timer frequency (high frequency to avoid whistling) .freq_hz = 40000, .speed_mode = LEDC_LOW_SPEED_MODE, .timer_num = LEDC_TIMER_3, }; ledc_timer_config(&flash_led_timer); // Set up GPIO PIN if (level > 256) { level = 256; } ledc_channel_config_t channel_config = { .channel = LEDC_CHANNEL_7, // Select available channel .duty = level/2, // Set the level of flash .gpio_num = 4, // Flash led gpio .speed_mode = LEDC_LOW_SPEED_MODE, .timer_sel = LEDC_TIMER_3 }; ledc_channel_config(&channel_config); } else { mp_raise_TypeError(MP_ERROR_TEXT("Bad flash level parameters")); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(camera_flash_obj, camera_flash); #endif // input buffer static uint32_t Motion_jpgRead(void * arg, size_t index, uint8_t *buf, size_t len) { Motion_t * motion = (Motion_t *)arg; if(buf) { memcpy(buf, motion->input + index, len); } return len; } //output buffer and image width static bool Motion_parseImage(void * arg, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint8_t *data) { Motion_t * motion = (Motion_t *)arg; // First access if(!data) { if(x == 0 && y == 0) { // Get the size of image motion->width = w; motion->height = h; if (((w/8) % 8) == 0) { motion->square_x = 8; } else { motion->square_x = 5; } if (((h/8) % 8) == 0) { motion->square_y = 8; } else { motion->square_y = 5; } motion->diffMax = (w/motion->square_x) * (h/motion->square_y); motion->diffWidth = (w/motion->square_x); motion->diffHeight = (h/motion->square_y); //ESP_LOGE(TAG, "motion %dx%d %dx%d %d",w,h, motion->square_x, motion->square_y, motion->diffMax); motion->lights = (uint16_t*)_malloc(sizeof(uint16_t) * motion->diffMax); motion->diffs = (uint16_t*)_malloc(sizeof(uint16_t) * motion->diffMax); motion->stack = (uint16_t*)_malloc(sizeof(uint16_t) * motion->diffMax*2*4); } else { // Write end } } else { int Y, X; unsigned int red; unsigned int green; unsigned int blue; unsigned int light; uint16_t *lights; unsigned int square_x = motion->square_x; unsigned int square_y = motion->square_y; int posY; uint8_t * pdata; lights = motion->lights; // Compute the motion in the square detection for (Y = y; Y < (y + h); Y ++) { posY = ((Y/square_y)*(motion->width/square_x)); for (X = x; X < (x + w); X ++) { pdata = &(data[(X-x)*3]); blue = *pdata; pdata++; green = *pdata; pdata++; red = *pdata; pdata++; light = ((max(max(red,green),blue) + min(min(red,green),blue)) >> 1); motion->histo[light/MAX_HISTO] ++; lights[posY + (X / square_x)] += light; } data += (w * 3); } } return true; } unsigned long computeCrc(const uint8_t *imageData, size_t imageLength) { unsigned long result =0; const unsigned long * ptrSrc = (unsigned long *)imageData; for (int i = 0; i < imageLength/4; i++) { result ^= *ptrSrc; ptrSrc ++; } return result; } // Create motion objet with an image static Motion_t * Motion_new(const uint8_t *imageData, size_t imageLength) { // Alloc class instance Motion_t *motion = m_new_obj_with_finaliser(Motion_t); if (motion) { memset(motion, 0, sizeof(Motion_t)); motion->base.type = &Motion_type; motion->input = imageData; // Compute motion detection esp_err_t ret = esp_jpg_decode(imageLength, JPG_SCALE_8X, Motion_jpgRead, Motion_parseImage, (void*)motion); if (ret == ESP_OK) { int square = motion->square_x * motion->square_y; int i; motion->imageData = _malloc(max(imageLength, 64*1024)); // Max size image is 65536 limited by system if (motion->imageData) { motion->imageLength = imageLength; memcpy(motion->imageData, imageData, max(imageLength, 64*1024)); // Max size image is 65536 limited by system } for (i = 0; i < motion->diffMax; i++) { // Calculate the average on the detection square motion->lights[i] /= square; } for (i = 0; i < MAX_HISTO; i++) { motion->histo[i] /= square; } } else { mp_raise_ValueError(MP_ERROR_TEXT("Camera esp_jpg_decode failed"));\ } } return motion; } // Constructor method STATIC mp_obj_t Motion_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { mp_obj_t result = mp_const_none; enum { ARG_image, }; // Constructor parameters static const mp_arg_t allowed_args[] = { { MP_QSTR_image, MP_ARG_REQUIRED | MP_ARG_OBJ }, }; // Parsing parameters mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // Check image if (args[ARG_image].u_obj == mp_const_none || ! mp_obj_is_str_or_bytes(args[ARG_image].u_obj)) { mp_raise_TypeError(MP_ERROR_TEXT("Bad image")); } else { GET_STR_DATA_LEN(args[ARG_image].u_obj, imageData, imageLength); Motion_t * self = Motion_new(imageData, imageLength); if (self) { result = self; } } return result; } // Delete method STATIC mp_obj_t Motion_deinit(mp_obj_t self_in) { Motion_t *motion = self_in; if (motion) { _free((void**)&motion->lights); _free((void**)&motion->diffs); _free((void**)&motion->imageData); _free((void**)&motion->stack); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(Motion_deinit_obj, Motion_deinit); // extract method STATIC mp_obj_t Motion_extract(mp_obj_t self_in) { Motion_t *motion = self_in; mp_obj_t res = mp_obj_new_list(0, NULL); if (motion) { int i; uint16_t * pLights = motion->lights; uint16_t * pDiffs = motion->diffs; // Build list of light pLights = motion->lights; pDiffs = motion->diffs; mp_obj_t objLights = mp_obj_new_list(0, NULL); mp_obj_t objDiffs = mp_obj_new_list(0, NULL); for (i = 0; i < motion->diffMax; i++) { mp_obj_list_append(objLights , mp_obj_new_int(*pLights)); mp_obj_list_append(objDiffs , mp_obj_new_int(*pDiffs)); pLights++; pDiffs++; } mp_obj_t objHisto = mp_obj_new_list(0,NULL); for (i = 0; i < MAX_HISTO; i++) { mp_obj_list_append(objHisto , mp_obj_new_int(motion->histo[i])); } // Add image buffer mp_obj_list_append(res,mp_obj_new_bytes(motion->imageData, motion->imageLength)); // Add list of lights mp_obj_list_append(res, objLights); // Add list with differences mp_obj_list_append(res, objDiffs); // Add list with histo mp_obj_list_append(res, objHisto); } return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(Motion_extract_obj, Motion_extract); // get_image method STATIC mp_obj_t Motion_get_image(mp_obj_t self_in) { Motion_t *motion = self_in; mp_obj_t res = mp_const_none; if (motion) { res = mp_obj_new_bytes(motion->imageData, motion->imageLength); } return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(Motion_get_image_obj, Motion_get_image); // get_size method STATIC mp_obj_t Motion_get_size(mp_obj_t self_in) { Motion_t *motion = self_in; mp_obj_t res = mp_const_none; if (motion) { res = mp_obj_new_int(motion->imageLength); } return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(Motion_get_size_obj, Motion_get_size); // get_light method STATIC mp_obj_t Motion_get_light(mp_obj_t self_in) { Motion_t *motion = self_in; mp_obj_t res = mp_const_none; if (motion) { long meanLight = 0; int i; for (i = 0; i < motion->diffMax; i++) { meanLight += motion->lights[i]; } meanLight /= motion->diffMax; res = mp_obj_new_int(meanLight); } return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(Motion_get_light_obj, Motion_get_light); // Push coordinates void Motion_push(Motion_t * motion, int x, int y) { motion->stack[motion->stackpos++] = x; motion->stack[motion->stackpos++] = y; } // Pop coordinates void Motion_pop(Motion_t * motion, int *x, int *y) { if (motion->stackpos > 0) { *y = motion->stack[--motion->stackpos]; *x = motion->stack[--motion->stackpos]; } } // Check if difference detected in the current pixel bool Motion_isDifference(Motion_t * motion, int x, int y) { bool result = false; // If position is in image if (x >= 0 && x < motion->width/motion->square_x && y >= 0 && y < motion->height/motion->square_y) { int i = y*(motion->width/motion->square_x) + x; uint16_t diff = motion->diffs[i]; // If difference detected not yet found if (((diff & 0xFF00) == 0) && ((diff & 0xFF) != 0)) { result = true; } } return result; } // Set the difference void Motion_setDifference(Motion_t * motion, int x, int y, Shape_t * shape) { int i = y*(motion->width/motion->square_x) + x; uint16_t diff = motion->diffs[i]; // If difference not yet parsed if ((diff & 0xFF00) == 0) { // Modify current difference to add shape identifier motion->diffs[i] = (diff &0xFF) | (shape->id << 8); // Compute the difference informations shape->size ++; shape->x += x; shape->y += y; if (x < shape->minx) shape->minx = x; if (x > shape->maxx) shape->maxx = x; if (y < shape->miny) shape->miny = y; if (y > shape->maxy) shape->maxy = y; } } // Search a shape in the differences bool Motion_searchShape(Motion_t * motion, int x, int y, Shape_t * shape) { bool result = false; // Push coordinates motion->stackpos = 0; if (Motion_isDifference(motion, x, y)) { Motion_push(motion, x, y); while(motion->stackpos > 0) { // Pop coordinates Motion_pop(motion, &x, &y); Motion_setDifference(motion, x, y, shape); // Search in contigous pixels if (Motion_isDifference(motion, x+1,y )) Motion_push(motion, x+1, y); if (Motion_isDifference(motion, x-1,y )) Motion_push(motion, x-1, y); if (Motion_isDifference(motion, x ,y+1)) Motion_push(motion, x , y+1); if (Motion_isDifference(motion, x ,y-1)) Motion_push(motion, x , y-1); //if (Motion_isDifference(motion, x+1,y+1)) Motion_push(motion, x+1, y+1); //if (Motion_isDifference(motion, x-1,y+1)) Motion_push(motion, x-1, y+1); //if (Motion_isDifference(motion, x+1,y-1)) Motion_push(motion, x+1, y-1); //if (Motion_isDifference(motion, x-1,y-1)) Motion_push(motion, x-1, y-1); } result = true; } // Compute the center of shape if (shape->size > 0) { shape->x = shape->x / shape->size; shape->y = shape->y / shape->size; result = true; } return result; } // Compute histogram int Motion_get_diff_histo(Motion_t *self, Motion_t *previous) { int i; int diff = 0; for (i = 0; i < MAX_HISTO; i++) { diff += abs(self->histo[i] - previous->histo[i]); } if (diff > self->diffMax) { return 0; } else { return (256 - ((diff<< 8)/self->diffMax)); } } /** Extract lines from the lists of points */ void Lines_configure(mp_obj_t points, Line_t * lines, int maxLines) { size_t size = list_get_size(points); if (maxLines == size) { Line_t point1, point2; // For all points defined for (size_t i = 0; i < size; i++) { mp_obj_t point = list_get_item (points, i); // If x and y defined if (list_get_size(point) == 2) { // Get point of line point1.x = mp_obj_get_int(list_get_item(point, 0)); point1.y = mp_obj_get_int(list_get_item(point, 1)); // If it is not the first point of line if (i > 0) { // Save the point in the previous point point2 = lines[i-1]; // If two points distincts if ((point1.x - point2.x) != 0) { // Compute the slope of line point1.a = (((point1.y - point2.y)<<8) / (point1.x - point2.x)); point1.b = (point1.y - ((point1.a*point1.x)>>8)); } else { mp_raise_TypeError(MP_ERROR_TEXT("Motions configure divide 0 for points")); } } else { point1.a = 0; point1.b = 0; } // ESP_LOGE(TAG,"x=%d y=%d a=%d b=%d",point1.x, point1.y, point1.a, point1.b); lines[i] = point1; } } } else { mp_raise_TypeError(MP_ERROR_TEXT("Motions bad configure size for points")); } } /** Compute Y value according to X */ int Lines_getY(Line_t * lines, int maxLines, int x) { int i; int y =0; // Search the error x according to the x level for (i = 1; i < maxLines; i++) { // If right straight line found if (x >= lines[i-1].x && x < lines[i].x) { // Compute the error light according its position in the straight line y =((lines[i].a * x)>>8) + lines[i].b; break; } } return y; } // Compute the difference between two motion detection STATIC int Motion_computeDiff(Motion_t *self, Motion_t *previous, mp_obj_t result) { int i; int diffDetected = 0; int diffHisto = Motion_get_diff_histo(self, previous); int errLight; int errHisto; uint16_t *pCurrentLights = self->lights; uint16_t *pPreviousLights = previous->lights; uint16_t *pDiffs = self->diffs; int light; // Compute the error histo according to the curves configured errHisto = Lines_getY(motionConfiguration.errorHistos, MAX_LINES, diffHisto); // For all square detection for (i = 0; i < self->diffMax; i++) { // Get the current max light of the selected square for two motion images light = max(*pCurrentLights, *pPreviousLights); // Compute the error light according to the curves configured errLight = Lines_getY(motionConfiguration.errorLights, MAX_LINES, light); // Mitigate the error according to the change in brightness if (((abs(*pCurrentLights - *pPreviousLights) * errHisto)>>8) > errLight) { *pDiffs = 0x01; diffDetected ++; } else { *pDiffs = 0x00; } pDiffs ++; pCurrentLights ++; pPreviousLights ++; } char * diffs = (char*)_malloc(sizeof(char) * self->diffMax + 1); if (motionConfiguration.mask_length > 0 && motionConfiguration.mask_length == self->diffMax) { int ignored = 0; uint8_t * pMask = motionConfiguration.mask_data; pDiffs = self->diffs; for (i = 0; i < self->diffMax; i++) { if (*pDiffs) { if (*pMask == '/') { diffs[i] = ' '; diffDetected --; ignored ++; *pDiffs = 0; // ESP_LOGE(TAG,"ignored = %d %c %d", i, *pMask, diffDetected); } else { diffs[i] = '#'; } } else { diffs[i] = ' '; } pDiffs++; pMask++; } //ESP_LOGE(TAG,"ignored=%d diff=%d", ignored, diffDetected); } else { int count = 0; pDiffs = self->diffs; for (i = 0; i < self->diffMax; i++) { if (*pDiffs) { diffs[i] = '#'; count ++; } else { diffs[i] = ' '; } pDiffs++; } } mp_obj_t diffdict = mp_obj_new_dict(0); mp_obj_dict_store(diffdict, mp_obj_new_str("count" , strlen("count")) , mp_obj_new_int(diffDetected)); mp_obj_dict_store(diffdict, mp_obj_new_str("max" , strlen("max")) , mp_obj_new_int(self->diffMax)); mp_obj_dict_store(diffdict, mp_obj_new_str("squarex" , strlen("squarex")) , mp_obj_new_int(self->square_x*8)); mp_obj_dict_store(diffdict, mp_obj_new_str("squarey" , strlen("squarey")) , mp_obj_new_int(self->square_y*8)); mp_obj_dict_store(diffdict, mp_obj_new_str("width" , strlen("width")) , mp_obj_new_int(self->diffWidth)); mp_obj_dict_store(diffdict, mp_obj_new_str("height" , strlen("height")) , mp_obj_new_int(self->diffHeight)); mp_obj_dict_store(diffdict, mp_obj_new_str("diffhisto" , strlen("diffhisto")) , mp_obj_new_int(diffHisto)); mp_obj_dict_store(diffdict, mp_obj_new_str("errhisto" , strlen("errhisto")) , mp_obj_new_int(errHisto)); mp_obj_dict_store(diffdict, mp_obj_new_str("diffs" , strlen("diffs")) , mp_obj_new_str(diffs , self->diffMax)); mp_obj_dict_store(result, mp_obj_new_str("diff" , strlen("diff")), diffdict); _free((void**)&diffs); return diffDetected; } STATIC void Motion_extractShape(Motion_t *self, mp_obj_t result, bool extractShape) { int x; int y; int width = self->width /self->square_x; int height = self->height/self->square_y; // Get the list of shapes detected mp_obj_t shapeslist = mp_obj_new_list(0, NULL); if (extractShape) { Shape_t shape; int shapeId = 1; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { memset(&shape, 0, sizeof(shape)); shape.minx = self->diffMax; shape.miny = self->diffMax; shape.id = shapeId; // If shape found if (Motion_searchShape(self, x, y,&shape)) { mp_obj_t shapedict = mp_obj_new_dict(0); mp_obj_dict_store(shapedict, mp_obj_new_str("size", strlen("size")), mp_obj_new_int(shape.size)); #if 1 mp_obj_dict_store(shapedict, mp_obj_new_str("centerx", strlen("centerx")), mp_obj_new_int(shape.x*self->square_x*8)); mp_obj_dict_store(shapedict, mp_obj_new_str("centery", strlen("centery")), mp_obj_new_int(shape.y*self->square_y*8)); mp_obj_dict_store(shapedict, mp_obj_new_str("x", strlen("x")), mp_obj_new_int(shape.minx*self->square_x*8)); mp_obj_dict_store(shapedict, mp_obj_new_str("y", strlen("y")), mp_obj_new_int(shape.miny*self->square_y*8)); mp_obj_dict_store(shapedict, mp_obj_new_str("width", strlen("width")), mp_obj_new_int((shape.maxx + 1 - shape.minx)*self->square_x*8)); mp_obj_dict_store(shapedict, mp_obj_new_str("height", strlen("height")), mp_obj_new_int((shape.maxy + 1 - shape.miny)*self->square_y*8)); #else mp_obj_dict_store(shapedict, mp_obj_new_str("centerx", strlen("centerx")), mp_obj_new_int(shape.x)); mp_obj_dict_store(shapedict, mp_obj_new_str("centery", strlen("centery")), mp_obj_new_int(shape.y)); mp_obj_dict_store(shapedict, mp_obj_new_str("minx", strlen("minx")), mp_obj_new_int(shape.minx)); mp_obj_dict_store(shapedict, mp_obj_new_str("miny", strlen("miny")), mp_obj_new_int(shape.miny)); mp_obj_dict_store(shapedict, mp_obj_new_str("maxx", strlen("maxx")), mp_obj_new_int(shape.maxx)); mp_obj_dict_store(shapedict, mp_obj_new_str("maxy", strlen("maxy")), mp_obj_new_int(shape.maxy)); #endif mp_obj_dict_store(shapedict, mp_obj_new_str("id", strlen("id")), mp_obj_new_int(shape.id)); mp_obj_list_append(shapeslist, shapedict); shapeId++; } } } #if 0 { char line[100]; int i; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { i = y * width + x; if (self->diffs[i]) { line[x] = ((self->diffs[i]&0xFF00)>>8) + 0x30; line[x+1] = '\0'; } else { line[x] = ' '; line[x+1] = '\0'; } } ESP_LOGE(TAG,"|%s|",line); } } #endif } mp_obj_dict_store(result, mp_obj_new_str("shapes" , strlen("shapes")) , shapeslist); } // compare method STATIC mp_obj_t Motion_compare(mp_obj_t self_in, mp_obj_t other_in, mp_obj_t extract_shape_in) { Motion_t *self = self_in; Motion_t *previous = other_in; if (previous->base.type != &Motion_type) { mp_raise_TypeError(MP_ERROR_TEXT("Not motion object")); } else if (self->diffMax != previous->diffMax) { mp_raise_TypeError(MP_ERROR_TEXT("Motions not same format")); } else if (!mp_obj_is_bool(extract_shape_in) && extract_shape_in != mp_const_none) { mp_raise_TypeError(MP_ERROR_TEXT("Motions bad parameters")); } else { int extractShape = mp_obj_is_true(extract_shape_in); mp_obj_t result = mp_obj_new_dict(0); if (Motion_computeDiff(self, previous, result) > 0) { Motion_extractShape(self, result, extractShape); } mp_obj_t geometrydict = mp_obj_new_dict(0); mp_obj_dict_store(geometrydict, mp_obj_new_str("width", strlen("width")), mp_obj_new_int(self->width * 8)); mp_obj_dict_store(geometrydict, mp_obj_new_str("height", strlen("height")), mp_obj_new_int(self->height * 8)); mp_obj_dict_store(result, mp_obj_new_str("geometry" , strlen("geometry")), geometrydict); return result; } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(Motion_compare_obj, Motion_compare); // configure method STATIC mp_obj_t Motion_configure(mp_obj_t self_in, mp_obj_t params_in) { Motion_t *self = self_in; if (self->base.type != &Motion_type) { mp_raise_TypeError(MP_ERROR_TEXT("Not motion object")); } else if (!mp_obj_is_dict_or_ordereddict(params_in) && params_in != mp_const_none) { mp_raise_TypeError(MP_ERROR_TEXT("Motions bad parameters")); } else { mp_obj_t errorLights = mp_obj_dict_get(params_in, MP_OBJ_NEW_QSTR(MP_QSTR_errorLights)); Lines_configure(errorLights, motionConfiguration.errorLights, MAX_LINES); mp_obj_t errorHistos = mp_obj_dict_get(params_in, MP_OBJ_NEW_QSTR(MP_QSTR_errorHistos)); Lines_configure(errorHistos, motionConfiguration.errorHistos, MAX_LINES); mp_obj_t mask_in = mp_obj_dict_get(params_in, MP_OBJ_NEW_QSTR(MP_QSTR_mask)); if (mp_obj_is_str_or_bytes(mask_in)) { GET_STR_DATA_LEN(mask_in, mask_data, mask_length); if (motionConfiguration.mask_data) { _free((void**)&motionConfiguration.mask_data); motionConfiguration.mask_data = 0; motionConfiguration.mask_length = 0; } if (mask_length > 0) { motionConfiguration.mask_data = _malloc(mask_length + 1); if (motionConfiguration.mask_data) { memcpy(motionConfiguration.mask_data, mask_data, mask_length); motionConfiguration.mask_length = mask_length; motionConfiguration.mask_data[mask_length] = '\0'; //ESP_LOGE(TAG,"|%s|",motionConfiguration.mask_data); } } } else { mp_raise_TypeError(MP_ERROR_TEXT("Bad mask type")); } } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(Motion_configure_obj, Motion_configure); // print method STATIC void Motion_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { ESP_LOGE(TAG, "Motion_print"); } // Methods STATIC const mp_rom_map_elem_t Motion_locals_dict_table[] = { // Delete method { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&Motion_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&Motion_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_extract), MP_ROM_PTR(&Motion_extract_obj) }, { MP_ROM_QSTR(MP_QSTR_compare), MP_ROM_PTR(&Motion_compare_obj) }, { MP_ROM_QSTR(MP_QSTR_configure), MP_ROM_PTR(&Motion_configure_obj) }, { MP_ROM_QSTR(MP_QSTR_get_image), MP_ROM_PTR(&Motion_get_image_obj) }, { MP_ROM_QSTR(MP_QSTR_get_size), MP_ROM_PTR(&Motion_get_size_obj) }, { MP_ROM_QSTR(MP_QSTR_get_light), MP_ROM_PTR(&Motion_get_light_obj) }, }; STATIC MP_DEFINE_CONST_DICT(Motion_locals_dict, Motion_locals_dict_table); // Class definition const mp_obj_type_t Motion_type = { { &mp_type_type }, .name = MP_QSTR_Motion, .print = Motion_print, .make_new = Motion_make_new, .locals_dict = (mp_obj_t)&Motion_locals_dict, }; STATIC const mp_rom_map_elem_t camera_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__ ), MP_ROM_QSTR(MP_QSTR_camera) }, { MP_ROM_QSTR(MP_QSTR_isavailable ), MP_ROM_PTR(&camera_isavailable_obj) }, #ifdef CONFIG_ESP32CAM { MP_ROM_QSTR(MP_QSTR_init ), MP_ROM_PTR(&camera_init_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit ), MP_ROM_PTR(&camera_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_capture ), MP_ROM_PTR(&camera_capture_obj) }, { MP_ROM_QSTR(MP_QSTR_motion ), MP_ROM_PTR(&camera_motion_detect_obj) }, { MP_ROM_QSTR(MP_QSTR_flash ), MP_ROM_PTR(&camera_flash_obj) }, { MP_ROM_QSTR(MP_QSTR_decode ), MP_ROM_PTR(&camera_decode_obj) }, { MP_ROM_QSTR(MP_QSTR_pixformat ), MP_ROM_PTR(&camera_pixformat_obj) }, { MP_ROM_QSTR(MP_QSTR_aec_value ), MP_ROM_PTR(&camera_aec_value_obj) }, { MP_ROM_QSTR(MP_QSTR_framesize ), MP_ROM_PTR(&camera_framesize_obj) }, { MP_ROM_QSTR(MP_QSTR_quality ), MP_ROM_PTR(&camera_quality_obj) }, { MP_ROM_QSTR(MP_QSTR_special_effect ), MP_ROM_PTR(&camera_special_effect_obj) }, { MP_ROM_QSTR(MP_QSTR_wb_mode ), MP_ROM_PTR(&camera_wb_mode_obj) }, { MP_ROM_QSTR(MP_QSTR_agc_gain ), MP_ROM_PTR(&camera_agc_gain_obj) }, { MP_ROM_QSTR(MP_QSTR_gainceiling ), MP_ROM_PTR(&camera_gainceiling_obj) }, { MP_ROM_QSTR(MP_QSTR_brightness ), MP_ROM_PTR(&camera_brightness_obj) }, { MP_ROM_QSTR(MP_QSTR_contrast ), MP_ROM_PTR(&camera_contrast_obj) }, { MP_ROM_QSTR(MP_QSTR_saturation ), MP_ROM_PTR(&camera_saturation_obj) }, { MP_ROM_QSTR(MP_QSTR_sharpness ), MP_ROM_PTR(&camera_sharpness_obj) }, { MP_ROM_QSTR(MP_QSTR_ae_level ), MP_ROM_PTR(&camera_ae_level_obj) }, { MP_ROM_QSTR(MP_QSTR_denoise ), MP_ROM_PTR(&camera_denoise_obj) }, { MP_ROM_QSTR(MP_QSTR_whitebal ), MP_ROM_PTR(&camera_whitebal_obj) }, { MP_ROM_QSTR(MP_QSTR_awb_gain ), MP_ROM_PTR(&camera_awb_gain_obj) }, { MP_ROM_QSTR(MP_QSTR_exposure_ctrl ), MP_ROM_PTR(&camera_exposure_ctrl_obj) }, { MP_ROM_QSTR(MP_QSTR_aec2 ), MP_ROM_PTR(&camera_aec2_obj) }, { MP_ROM_QSTR(MP_QSTR_gain_ctrl ), MP_ROM_PTR(&camera_gain_ctrl_obj) }, { MP_ROM_QSTR(MP_QSTR_bpc ), MP_ROM_PTR(&camera_bpc_obj) }, { MP_ROM_QSTR(MP_QSTR_wpc ), MP_ROM_PTR(&camera_wpc_obj) }, { MP_ROM_QSTR(MP_QSTR_raw_gma ), MP_ROM_PTR(&camera_raw_gma_obj) }, { MP_ROM_QSTR(MP_QSTR_lenc ), MP_ROM_PTR(&camera_lenc_obj) }, { MP_ROM_QSTR(MP_QSTR_hmirror ), MP_ROM_PTR(&camera_hmirror_obj) }, { MP_ROM_QSTR(MP_QSTR_vflip ), MP_ROM_PTR(&camera_vflip_obj) }, { MP_ROM_QSTR(MP_QSTR_dcw ), MP_ROM_PTR(&camera_dcw_obj) }, { MP_ROM_QSTR(MP_QSTR_colorbar ), MP_ROM_PTR(&camera_colorbar_obj) }, { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_96X96 ), MP_ROM_INT(FRAMESIZE_96X96 )}, // 96x96 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_QQVGA ), MP_ROM_INT(FRAMESIZE_QQVGA )}, // 160x120 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_QCIF ), MP_ROM_INT(FRAMESIZE_QCIF )}, // 176x144 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_HQVGA ), MP_ROM_INT(FRAMESIZE_HQVGA )}, // 240x176 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_240X240 ), MP_ROM_INT(FRAMESIZE_240X240 )}, // 240x240 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_QVGA ), MP_ROM_INT(FRAMESIZE_QVGA )}, // 320x240 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_CIF ), MP_ROM_INT(FRAMESIZE_CIF )}, // 400x296 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_HVGA ), MP_ROM_INT(FRAMESIZE_HVGA )}, // 480x320 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_VGA ), MP_ROM_INT(FRAMESIZE_VGA )}, // 640x480 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_SVGA ), MP_ROM_INT(FRAMESIZE_SVGA )}, // 800x600 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_XGA ), MP_ROM_INT(FRAMESIZE_XGA )}, // 1024x768 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_HD ), MP_ROM_INT(FRAMESIZE_HD )}, // 1280x720 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_SXGA ), MP_ROM_INT(FRAMESIZE_SXGA )}, // 1280x1024 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_UXGA ), MP_ROM_INT(FRAMESIZE_UXGA )}, // 1600x1200 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_FHD ), MP_ROM_INT(FRAMESIZE_FHD )}, // 1920x1080 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_P_HD ), MP_ROM_INT(FRAMESIZE_P_HD )}, // 720x1280 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_P_3MP ), MP_ROM_INT(FRAMESIZE_P_3MP )}, // 864x1536 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_QXGA ), MP_ROM_INT(FRAMESIZE_QXGA )}, // 2048x1536 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_QHD ), MP_ROM_INT(FRAMESIZE_QHD )}, // 2560x1440 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_WQXGA ), MP_ROM_INT(FRAMESIZE_WQXGA )}, // 2560x1600 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_P_FHD ), MP_ROM_INT(FRAMESIZE_P_FHD )}, // 1080x1920 { MP_ROM_QSTR(MP_QSTR_FRAMESIZE_QSXGA ), MP_ROM_INT(FRAMESIZE_QSXGA )}, // 2560x1920 { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_RGB565 ), MP_ROM_INT(PIXFORMAT_RGB565 )}, // 2BPP/RGB565 { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_YUV422 ), MP_ROM_INT(PIXFORMAT_YUV422 )}, // 2BPP/YUV422 { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_GRAYSCALE), MP_ROM_INT(PIXFORMAT_GRAYSCALE)}, // 1BPP/GRAYSCALE { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_JPEG ), MP_ROM_INT(PIXFORMAT_JPEG )}, // JPEG/COMPRESSED { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_RGB888 ), MP_ROM_INT(PIXFORMAT_RGB888 )}, // 3BPP/RGB888 { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_RAW ), MP_ROM_INT(PIXFORMAT_RAW )}, // RAW { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_RGB444 ), MP_ROM_INT(PIXFORMAT_RGB444 )}, // 3BP2P/RGB444 { MP_ROM_QSTR(MP_QSTR_PIXFORMAT_RGB555 ), MP_ROM_INT(PIXFORMAT_RGB555 )}, // 3BP2P/RGB555 #endif { MP_ROM_QSTR(MP_QSTR_Motion ), MP_ROM_PTR(&Motion_type) }, }; STATIC MP_DEFINE_CONST_DICT(camera_module_globals, camera_module_globals_table); const mp_obj_module_t mp_module_camera = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t*)&camera_module_globals, };
29.241033
146
0.671287
9974d320d12330fec3aec3dc2ac9ffaaad9369b2
701
c
C
src/kernel/timer.c
miklhh/os4
8fb7d926bb44a498ac50a4fd0dc2c1c8e0941d74
[ "MIT" ]
3
2017-08-23T12:56:09.000Z
2017-10-30T13:42:16.000Z
src/kernel/timer.c
miklhh/os4
8fb7d926bb44a498ac50a4fd0dc2c1c8e0941d74
[ "MIT" ]
null
null
null
src/kernel/timer.c
miklhh/os4
8fb7d926bb44a498ac50a4fd0dc2c1c8e0941d74
[ "MIT" ]
null
null
null
/* * Part of OS4, timer.c * Author: Mikael Henriksson, miklhh */ #include <stdint.h> #include <kernel/timer.h> #include <kernel/pit.h> #include <task/task.h> #include <stdint.h> /* Global tick variable. */ volatile uint64_t __sys_tick = 0; extern uint8_t tasking_initialized; /* * Timer interrupt service routine. * 2017-06-25: Called each millisecond. * Gate type: Interruptgate. * DPL: Ring 0. */ void timer_irq() { /* Increase the system tick variable. */ __sys_tick++; /* Call the task preempt function if tasking has been initialized. */ if (tasking_initialized) { task_preempt(); } } /* Timer init function. */ void timer_init() { pit_init(); }
17.974359
73
0.660485
8509c790e0ff7fab6f3e0212fa65a04df425c9cf
908
h
C
headers/TNDRAccountWarningsViewModel.h
Tatsh-archive/tynder
bbbf0a2b7480d1a1519483ddcead6736d9ba6501
[ "MIT" ]
1
2015-03-03T13:37:47.000Z
2015-03-03T13:37:47.000Z
headers/TNDRAccountWarningsViewModel.h
Tatsh/tynder
bbbf0a2b7480d1a1519483ddcead6736d9ba6501
[ "MIT" ]
null
null
null
headers/TNDRAccountWarningsViewModel.h
Tatsh/tynder
bbbf0a2b7480d1a1519483ddcead6736d9ba6501
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSArray, TNDRReportReasonsViewModel; @interface TNDRAccountWarningsViewModel : NSObject { NSArray *_accountWarnings; TNDRReportReasonsViewModel *_reportReasonsViewModel; } + (id)accountWarningsFromArray:(id)arg1; + (id)accountWarningsFromJSON:(id)arg1; - (void).cxx_destruct; @property(retain, nonatomic) NSArray *accountWarnings; // @synthesize accountWarnings=_accountWarnings; - (id)accountWarningsSummaryJoinedByString:(id)arg1 prefix:(id)arg2; - (id)initFromArray:(id)arg1; - (id)initFromJSON:(id)arg1; @property(retain, nonatomic) TNDRReportReasonsViewModel *reportReasonsViewModel; // @synthesize reportReasonsViewModel=_reportReasonsViewModel; - (void)requestAccountWarningsWithCompletion:(CDUnknownBlockType)arg1; @end
31.310345
143
0.779736
12ec6234527f93d2df58a70b69b0ebe47ac8bda7
2,824
h
C
include/ironbee/apidoc.h
b1v1r/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
148
2015-01-10T01:53:39.000Z
2022-03-20T20:48:12.000Z
include/ironbee/apidoc.h
ErikHendriks/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
8
2015-03-09T15:50:36.000Z
2020-10-10T19:23:06.000Z
include/ironbee/apidoc.h
ErikHendriks/ironbee
97b453afd9c3dc70342c6183a875bde22c9c4a76
[ "Apache-2.0" ]
46
2015-03-08T22:45:42.000Z
2022-01-15T13:47:59.000Z
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- Top level API documentation. * * This file contains no code, only API documentations. It functions as the * main page of the API documentation. * * @author Christopher Alfeld <calfeld@qualys.com> **/ /** * @mainpage IronBee Documentation * * Welcome to the API documentation for IronBee. * * If you are a module, rule, or server writer, you are probably interested in * the public API. See the Modules list and the files in include/ironbee. * * Some general documentation on IronBee and development from the codebase: * - https://github.com/ironbee/ironbee/blob/master/README.adoc * - https://github.com/ironbee/ironbee/blob/master/CHANGES.adoc * - https://github.com/ironbee/ironbee/blob/master/DEVELOPMENT.adoc * - https://github.com/ironbee/ironbee/blob/master/CODESTYLE.adoc * * Of particular interest: * - Module writers: module.h, module_sym.h, example_modules/ibmod_set_c.c, * example_modules/ibmod_set_cpp.cpp. * - Server writers: server.h, state_notify.h, example_servers/parsed_c.c, * example_modules/unparsed_cpp.cpp. * - Lua Rule and Module writers: @ref LuaAPI * - Everyone: types.h, mpool.h * * If you are interested in developing the above in C++, see @ref * ironbeepp page. * * if you are interested in IronAutomata, an automata creation and execution * framework that targets IronBee's needs but has minimal dependence on * IronBee, see @ref ironautomata. * * If you are an IronBee developer, you may be interested in the private API. * First, make sure you are viewing the internal version of this * documentation. That version includes all internal modules, functions, * files, etc. Run '@c make @c doxygen' in the docs directory and look at * @c doxygen_internal/html/index.html * * This page is defined in include/ironbee/apidoc.h. **/ /** * @defgroup IronBee IronBee WAF **/
40.927536
78
0.697592
8f08e84bf11ea1f30a530d1e5f6bb94dfe79cfce
403
h
C
Example/Pods/Target Support Files/ZZPopoverWindow/ZZPopoverWindow-umbrella.h
ACommonChinese/ZZPopoverWindow
12367daccbc89dcfe125d6541002cb53647ff2a6
[ "MIT" ]
12
2016-03-22T10:56:21.000Z
2020-03-03T08:48:13.000Z
Example/Pods/Target Support Files/ZZPopoverWindow/ZZPopoverWindow-umbrella.h
ACommonChinese/ZZPopoverWindow
12367daccbc89dcfe125d6541002cb53647ff2a6
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/ZZPopoverWindow/ZZPopoverWindow-umbrella.h
ACommonChinese/ZZPopoverWindow
12367daccbc89dcfe125d6541002cb53647ff2a6
[ "MIT" ]
5
2016-03-22T05:42:51.000Z
2016-09-28T07:55:02.000Z
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "ZZPopoverView.h" #import "ZZPopoverWindow.h" #import "ZZPositionList.h" FOUNDATION_EXPORT double ZZPopoverWindowVersionNumber; FOUNDATION_EXPORT const unsigned char ZZPopoverWindowVersionString[];
20.15
69
0.82134
6aa9da1afebb0fcd6807455dceee3c99793e7966
265
h
C
KLMRouterDemo/KLMHomeViewController.h
shsoul/KLMRouter
a71655bc71099ee68112d7fcd79585efc7db5129
[ "MIT" ]
1
2021-03-21T13:04:07.000Z
2021-03-21T13:04:07.000Z
KLMRouterDemo/KLMHomeViewController.h
shsoul/KLMRouter
a71655bc71099ee68112d7fcd79585efc7db5129
[ "MIT" ]
null
null
null
KLMRouterDemo/KLMHomeViewController.h
shsoul/KLMRouter
a71655bc71099ee68112d7fcd79585efc7db5129
[ "MIT" ]
null
null
null
// // ViewController.h // KLMRouter // // Created by zhangshuijie on 2017/5/23. // Copyright © 2017年 sjst.xgfe. All rights reserved. // #import <UIKit/UIKit.h> #import "KLMProvider.h" @interface KLMHomeViewController : UITabBarController<KLMProvider> @end
15.588235
66
0.716981
5c72619c187a7988fb00cfea2d3d7e0017d46401
2,201
h
C
Petris_Debugging.h
bendapootie/petris
92dfe5a80b1cc6e46ba0eef71e9d87667a71fc4b
[ "MIT" ]
3
2022-01-29T20:57:40.000Z
2022-02-05T20:25:57.000Z
Petris_Debugging.h
bendapootie/petris
92dfe5a80b1cc6e46ba0eef71e9d87667a71fc4b
[ "MIT" ]
20
2022-02-04T03:33:14.000Z
2022-03-22T02:45:23.000Z
Petris_Debugging.h
bendapootie/petris
92dfe5a80b1cc6e46ba0eef71e9d87667a71fc4b
[ "MIT" ]
null
null
null
// Define DEBUGGING_ENABLED to enable Asserts, Serial port output, and extra debugging // Note: If this is defined before the types, I get compiler errors?!? #ifdef DEBUGGING_ENABLED // TODO: Figure out how to use __FlashStringHelper* string here to avoid eating up dynamic memory static const char* s_stackTrace[10]; static short s_stackTraceLine[10]; static uint8 s_stackDepth = 0; class DebugStackTracker { public: DebugStackTracker(const char* func, short line) { s_stackTrace[s_stackDepth] = func; s_stackTraceLine[s_stackDepth] = line; s_stackDepth++; } ~DebugStackTracker() { s_stackDepth--; } static void PrintStack(); private: }; // static void DebugStackTracker::PrintStack() { for (uint8 i = 0; i < s_stackDepth; i++) { if (i != 0) { Serial.print(" - "); } Serial.print(s_stackTrace[i]); Serial.print("("); Serial.print(s_stackTraceLine[i]); Serial.print(")"); } } // Instrumentation for getting at least partial stack traces from failed asserts // Usage: Sprinkle these around at the top of functions to get better data from asserts #define DebugStack DebugStackTracker __debugStackTracker(__FUNCTION__, __LINE__) char g_debugStr[80]; void DebugPrint(const __FlashStringHelper* msg) { Serial.print(msg); } void DebugPrintLine(const __FlashStringHelper* msg) { Serial.println(msg); } void __AssertFunction(const char* func, int line, bool condition, const __FlashStringHelper* msg = nullptr) { if (!condition) { Serial.print(F("Assert Failed! ")); Serial.print(func); Serial.print(F("(")); Serial.print(line); Serial.print(F(") - ")); Serial.println(msg == nullptr ? F("") : msg); Serial.print(F("Stack: ")); DebugStackTracker::PrintStack(); Serial.println(); } } #define Assert(condition, ...) __AssertFunction(__FUNCTION__, __LINE__, (condition), ##__VA_ARGS__) #else // #ifdef DEBUGGING_ENABLED void DebugPrint(...) {} void DebugPrintLine(...) {} #define Assert(condition, ...) {} #define DebugStack {} #endif // #else // #ifdef DEBUGGING_ENABLED
30.150685
109
0.6597
582e1eac546f17822d4e0eb7d11e0a59b416bf5d
15,942
h
C
include/mrs_lib/geometry/shapes.h
ctu-mrs/mrs_lib
1df4282d71c2944904676adbb7289ce45004432a
[ "BSD-3-Clause" ]
1
2022-03-17T17:42:09.000Z
2022-03-17T17:42:09.000Z
include/mrs_lib/geometry/shapes.h
ctu-mrs/mrs_lib
1df4282d71c2944904676adbb7289ce45004432a
[ "BSD-3-Clause" ]
11
2020-10-20T09:36:36.000Z
2022-03-08T19:17:26.000Z
include/mrs_lib/geometry/shapes.h
ctu-mrs/mrs_lib
1df4282d71c2944904676adbb7289ce45004432a
[ "BSD-3-Clause" ]
2
2019-04-02T08:47:47.000Z
2021-08-05T12:54:05.000Z
// clang: MatousFormat /** \file \brief Defines various geometrical shapes and their relations. \author Petr Štibinger - stibipet@fel.cvut.cz \author Matouš Vrba - vrbamato@fel.cvut.cz */ #ifndef SHAPES_H #define SHAPES_H #include <boost/optional.hpp> #include <Eigen/Dense> namespace mrs_lib { namespace geometry { /* class Ray //{ */ /** * @brief geometric representation of a ray. Instantiate it by two input Vector3. Use static methods for from-to raycast, or a point-direction raycast. */ class Ray { public: /** * @brief constructor without initialization of internal variables */ Ray(); /** * @brief destructor */ ~Ray(); /** * @brief default constructor * * @param p1 origin of the ray * @param p2 endpoint of the ray */ Ray(Eigen::Vector3d p1, Eigen::Vector3d p2); private: Eigen::Vector3d point1; Eigen::Vector3d point2; public: /** * @brief get the origin point * * @return ray origin point */ const Eigen::Vector3d p1(); /** * @brief get the end point * * @return ray end point */ const Eigen::Vector3d p2(); /** * @brief get the direction of ray (normalized) * * @return direction (normalized) */ const Eigen::Vector3d direction(); public: /** * @brief static method for generating new rays by raycasting from-to * * @param pointFrom origin of the ray * @param pointTo endpoint of the ray * * @return new Ray instance created by raycasting */ static Ray twopointCast(Eigen::Vector3d pointFrom, Eigen::Vector3d pointTo); /** * @brief static method for generating new rays by raycasting origin-direction * * @param origin origin of the ray * @param direction of the ray * * @return new Ray instance created by raycasting */ static Ray directionCast(Eigen::Vector3d origin, Eigen::Vector3d direction); }; //} /* class Triangle //{ */ /** * @brief geometric representation of a triangle. Instantiate a new triangle by providing three vertices */ class Triangle { public: /** * @brief constructor for initialization with default values (points [0,0,0], [1,0,0] and [0,0,1] */ Triangle(); /** * @brief destructor */ ~Triangle(); /** * @brief default constructor for creating a new triangle from given vertices * * @param a * @param b * @param c */ Triangle(Eigen::Vector3d a, Eigen::Vector3d b, Eigen::Vector3d c); private: Eigen::Vector3d point1; Eigen::Vector3d point2; Eigen::Vector3d point3; public: const Eigen::Vector3d a(); const Eigen::Vector3d b(); const Eigen::Vector3d c(); /** * @brief get position on the triangle center * * @return vector3 */ const Eigen::Vector3d center(); /** * @brief get normal vector of this triangle. The vector origin is placed at triangle center, length is normalized and direction follows the right-hand * rule with respect to vertex order a-b-c * * @return vector3 */ const Eigen::Vector3d normal(); /** * @brief get a vector of all vertices * * @return std::vector<vector3> */ const std::vector<Eigen::Vector3d> vertices(); public: /** * @brief calculate an intersection of this triangle with a given ray with given tolerance * * @param r ray to calculate intersection with * @param epsilon calculation tolerance * * @return vector3 intersection if exists, boost::none if no intersection is found */ const boost::optional<Eigen::Vector3d> intersectionRay(Ray r, double epsilon = 1e-4); }; //} /* class Rectangle //{ */ /** * @brief geometric representation of a rectangle (can represent any quadrilateral) */ class Rectangle { public: /** * @brief constructor for initialization with points set to [0,0,0], [1,0,0], [1,1,0] and [0,1,0] */ Rectangle(); /** * @brief destructor */ ~Rectangle(); /** * @brief constructor using a std::vector of points (vector3). Provide points in a counter-clockwise order for correct behavior * * @param points std::vector of points in 3d */ Rectangle(std::vector<Eigen::Vector3d> points); /** * @brief constructor using four points (vector3). Provide points in a counter-clockwise order for correct behavior * * @param a * @param b * @param c * @param d */ Rectangle(Eigen::Vector3d a, Eigen::Vector3d b, Eigen::Vector3d c, Eigen::Vector3d d); private: Eigen::Vector3d point1; Eigen::Vector3d point2; Eigen::Vector3d point3; Eigen::Vector3d point4; public: /** * @brief getter for first point * * @return 1st point (vector3) */ const Eigen::Vector3d a(); /** * @brief getter for the second point * * @return 2nd point (vector3) */ const Eigen::Vector3d b(); /** * @brief getter for the third point * * @return 3rd point (vector3) */ const Eigen::Vector3d c(); /** * @brief getter for the fourth point * * @return 4th point (vector3) */ const Eigen::Vector3d d(); /** * @brief getter for center point * * @return center point (vector3) */ const Eigen::Vector3d center(); /** * @brief getter for the normal vector. It originates in the center of the Rectangle, length is normalized, orientation follows the right-hand rule, * assuiming the points are provided in counter-clockwise order * * @return normal vector3 */ const Eigen::Vector3d normal(); /** * @brief getter for all the points of this rectangle provided as std::vector * * @return std::vector of points (vector3) */ const std::vector<Eigen::Vector3d> vertices(); /** * @brief getter for the triangles forming this rectangle * * @return std::vector of triangles */ const std::vector<Triangle> triangles(); /** * @brief calculate an intersection of this rectangle with a given ray with given tolerance * * @param r ray to calculate intersection with * @param epsilon calculation tolerance * * @return vector3 intersection if exists, boost::none if no intersection is found */ const boost::optional<Eigen::Vector3d> intersectionRay(Ray r, double epsilon = 1e-4); /** * @brief check if the normal is facing a given point, i.e. if the point lies in the same half-space as the rectangle normal * * @param point vector3 to check against * * @return true if the normal is facing given point. Returns false for angle >= 90 degrees */ bool isFacing(Eigen::Vector3d point); /** * @brief compute the solid angle of this rectangle relative to a given sphere center * * @param point center of a sphere to compute the solid angle for * * @return solid angle in steradians */ double solidAngleRelativeTo(Eigen::Vector3d point); }; //} /* class Cuboid //{ */ /** * @brief geometric representation of a cuboid */ class Cuboid { public: /** * @brief constructor for initialization with all points set to [0,0,0] */ Cuboid(); /** * @brief virtual destructor */ ~Cuboid(); /** * @brief constructor from six provided points (vector3) * * @param p0 vector3 * @param p1 vector3 * @param p2 vector3 * @param p3 vector3 * @param p4 vector3 * @param p5 vector3 * @param p6 vector3 * @param p7 vector3 */ Cuboid(Eigen::Vector3d p0, Eigen::Vector3d p1, Eigen::Vector3d p2, Eigen::Vector3d p3, Eigen::Vector3d p4, Eigen::Vector3d p5, Eigen::Vector3d p6, Eigen::Vector3d p7); /** * @brief constructor from a std::vector of provided points * * @param points std::vector<vector3> */ Cuboid(std::vector<Eigen::Vector3d> points); /** * @brief constructor from a provided center point, size and orientation * * @param center vector3 * @param size vector3 * @param orientation quaternion */ Cuboid(Eigen::Vector3d center, Eigen::Vector3d size, Eigen::Quaterniond orientation); private: /** * @brief side indexing */ enum { FRONT = 0, BACK = 1, LEFT = 2, RIGHT = 3, BOTTOM = 4, TOP = 5, }; private: std::vector<Eigen::Vector3d> points; std::vector<Eigen::Vector3d> lookupPoints(int face_idx); public: /** * @brief getter for all vertices (vector3) of this cuboid * * @return std::vector<vector3> */ const std::vector<Eigen::Vector3d> vertices(); /** * @brief getter for the center point * * @return vector3 */ const Eigen::Vector3d center(); /** * @brief getter for one side corresponding to a provided index * * @param face_idx index of the side to lookup points for * * @return rectangle representing the cuboid side */ const Rectangle getRectangle(int face_idx); /** * @brief calculate the intersection between this cuboid and a provided ray within a given tolerance. Can result in 0, 1 or 2 intersection points * * @param r ray to check intersection with * @param epsilon tolerance for the calculation * * @return std::vector<vector3> list of intersection points (depending on the geometry, can yield 0, 1 or 2 points) */ const std::vector<Eigen::Vector3d> intersectionRay(Ray r, double epsilon = 1e-4); }; //} /* class Ellipse //{ */ /** * @brief geometric representation of an ellipse */ class Ellipse { public: /** * @brief constructor for initialization without setting internal variables */ Ellipse(); /** * @brief destructor */ ~Ellipse(); /** * @brief constructor using a provided center point, orientation, major semi-axis length and minor semi-axis length * * @param center vector3 * @param orientation quaternion * @param a major semi-axis length * @param b minor semi-axis length */ Ellipse(Eigen::Vector3d center, Eigen::Quaterniond orientation, double a, double b); private: double major_semi; double minor_semi; Eigen::Vector3d center_point; Eigen::Quaterniond absolute_orientation; public: /** * @brief getter for major semi-axis * * @return length of major semi-axis */ double a(); /** * @brief getter for minor semi-axis * * @return length of minor semi-axis */ double b(); /** * @brief getter for the center point * * @return vector3 */ const Eigen::Vector3d center(); /** * @brief getter for the orientation * * @return quaternion */ const Eigen::Quaterniond orientation(); }; //} /* class Cylinder //{ */ /** * @brief geometric representation of a cylinder */ class Cylinder { public: /** * @brief constructor without setting the internal variables */ Cylinder(); /** * @brief destructor */ ~Cylinder(); /** * @brief constructor using a given center point, radius, height and orietnation * * @param center geometric center in the middle of body height * @param radius radius of the cap * @param height distance between caps * @param orientation quaternion */ Cylinder(Eigen::Vector3d center, double radius, double height, Eigen::Quaterniond orientation); private: Eigen::Vector3d center_point; double radius; double height; Eigen::Quaterniond absolute_orientation; public: /** * @brief cap indexing */ enum { BOTTOM = 0, TOP = 1, }; public: /** * @brief getter for the center point * * @return vector3 */ const Eigen::Vector3d center(); /** * @brief getter for the orientation * * @return quaternion */ const Eigen::Quaterniond orientation(); /** * @brief getter for cap radius * * @return radius of the cap */ double r(); /** * @brief getter for the body height * * @return body height */ double h(); /** * @brief getter for a cap corresponding to a provided index * * @param index of the cap * * @return ellipse representing the cap */ const Ellipse getCap(int index); }; //} /* class Cone //{ */ /** * @brief geometric representaiton of a cone */ class Cone { public: /** * @brief constructor without setting the internal variables */ Cone(); /** * @brief destructor */ ~Cone(); /** * @brief constructor from a given origin point (tip of the cone), angle, height and orientation * * @param origin_point tip of the cone * @param angle angle between body height and side in radians * @param height distance between tip and base * @param orientation offset from the default orientation. Default orientation is with body height aligned with Z axis, standing on the tip */ Cone(Eigen::Vector3d origin_point, double angle, double height, Eigen::Vector3d orientation); private: Eigen::Vector3d origin_point; double angle; double height; Eigen::Vector3d absolute_direction; public: /** * @brief getter for the tip point * * @return vector3 */ const Eigen::Vector3d origin(); /** * @brief getter for the direction. Normalized direction from origin towards base * * @return vector3, normalized */ const Eigen::Vector3d direction(); /** * @brief getter for the center point. Center point lies in half of the body height * * @return vector3 */ const Eigen::Vector3d center(); /** * @brief getter for angle between body height and body side * * @return angle in radians */ double theta(); /** * @brief getter for body height * * @return */ double h(); /** * @brief getter for the cap of the cone * * @return ellipse representing the cap of the cone */ const Ellipse getCap(); /** * @brief Project a 3D point orthogonally onto the Cone surface * * @param point in 3D * * @return projected point */ const std::optional<Eigen::Vector3d> projectPoint(const Eigen::Vector3d& point); }; //} } // namespace geometry } // namespace mrs_lib #endif // SHAPES_H
25.14511
157
0.563731
1eb0d557b1123e1b26e7d1a4a335d6cd058a69ed
381
h
C
SHHaveFun/SHHaveFun/App/AppMain/Calendar/MonthTitleModel.h
FuthureCrane/SHHaveFun
f2731bf00c899e27bae51603401cbb10f4f8e275
[ "MIT" ]
null
null
null
SHHaveFun/SHHaveFun/App/AppMain/Calendar/MonthTitleModel.h
FuthureCrane/SHHaveFun
f2731bf00c899e27bae51603401cbb10f4f8e275
[ "MIT" ]
null
null
null
SHHaveFun/SHHaveFun/App/AppMain/Calendar/MonthTitleModel.h
FuthureCrane/SHHaveFun
f2731bf00c899e27bae51603401cbb10f4f8e275
[ "MIT" ]
null
null
null
// // MonthTitleModel.h // IGTest // // Created by Futhure on 2017/10/24. // Copyright © 2017年 Auto. All rights reserved. // #import "IGListKit.h" @interface MonthTitleModel : NSObject <IGListDiffable> @property (nonatomic, copy) NSString *name; - (instancetype)initWithName:(NSString *)name; - (instancetype)init NS_UNAVAILABLE; - (instancetype)new NS_UNAVAILABLE; @end
18.142857
54
0.724409
9b5a3c40c21e46dc479e36cebbc308ae6f1e63fc
341
h
C
src/cmdEx_exe/resource.h
sgraham/cmdEx
19add8a0411d84526faa0b392f190e33af0fc5d5
[ "MIT-0" ]
25
2015-05-22T21:45:44.000Z
2021-08-14T02:46:56.000Z
src/cmdEx_exe/resource.h
sgraham/cmdEx
19add8a0411d84526faa0b392f190e33af0fc5d5
[ "MIT-0" ]
1
2018-02-23T15:36:51.000Z
2018-02-24T06:00:05.000Z
src/cmdEx_exe/resource.h
sgraham/cmdEx
19add8a0411d84526faa0b392f190e33af0fc5d5
[ "MIT-0" ]
4
2015-10-27T03:00:16.000Z
2020-09-05T20:19:14.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define CMDEX_X86_EXE 10000 #define CMDEX_DLL_X86_DLL 10001 #define GIT2_X86_DLL 10002 #define DBGHELP_X86_DLL 10003 #define SYMSRV_X86_DLL 10004 #define ANSI32_DLL_X86 10005
31
73
0.809384
afd43cfbe34acf76986bb5ff207905a8bf47e8fc
565
h
C
Engine/Input/Input.h
PMFU/Vic2-Save-Analyzer
452d0c8aacdf75094586e4d79fb9ab29f743ef80
[ "MIT" ]
null
null
null
Engine/Input/Input.h
PMFU/Vic2-Save-Analyzer
452d0c8aacdf75094586e4d79fb9ab29f743ef80
[ "MIT" ]
null
null
null
Engine/Input/Input.h
PMFU/Vic2-Save-Analyzer
452d0c8aacdf75094586e4d79fb9ab29f743ef80
[ "MIT" ]
null
null
null
#ifndef INPUT_H #define INPUT_H #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> namespace Input { struct Inputs { int AD; int WS; float mouseLR; float mouseUD; bool mouse1; bool mouseMiddle; bool mouse2; bool space; bool shift; bool escape; bool lctrl; bool tilda; double zoom = 0.0f; //probably bot implement bool oneclick; // this is to not select provinces over and over again after the first click }; void setupInput(); Inputs getInput(float dt); void resetZoom(); extern GLFWwindow* window; }; #endif // INPUT_H
14.868421
93
0.700885
18c05b9a14eb7d82aaf1645577d2bf7a07b7f48a
694
h
C
usr/libexec/appstored/Environment.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
5
2021-04-29T04:31:43.000Z
2021-08-19T18:59:58.000Z
usr/libexec/appstored/Environment.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
null
null
null
usr/libexec/appstored/Environment.h
lechium/tvOS145Headers
9940da19adb0017f8037853e9cfccbe01b290dd5
[ "MIT" ]
1
2022-03-19T11:16:23.000Z
2022-03-19T11:16:23.000Z
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> @class SQLiteDatabase; @protocol OS_dispatch_queue; @interface Environment : NSObject { NSObject<OS_dispatch_queue> *_dispatchQueue; // 8 = 0x8 SQLiteDatabase *_userDatabase; // 16 = 0x10 SQLiteDatabase *_systemDatabase; // 24 = 0x18 } + (id)sharedInstance; // IMP=0x00000001000529bc - (void).cxx_destruct; // IMP=0x0000000100052e88 @property(readonly) SQLiteDatabase *userDatabase; @property(readonly) SQLiteDatabase *systemDatabase; - (id)init; // IMP=0x0000000100052a28 @end
25.703704
120
0.731988
495cb3a9100bfa8178b072a9e0ff1db0952609bc
2,041
h
C
firmware/uvc_controller/mbed-os/features/nfc/acore/acore/ac_stream.h
davewhiiite/uvc
fd45223097eed5a824294db975b3c74aa5f5cc8f
[ "MIT" ]
1
2021-06-12T14:54:07.000Z
2021-06-12T14:54:07.000Z
firmware/uvc_controller/mbed-os/features/nfc/acore/acore/ac_stream.h
davewhiiite/uvc
fd45223097eed5a824294db975b3c74aa5f5cc8f
[ "MIT" ]
null
null
null
firmware/uvc_controller/mbed-os/features/nfc/acore/acore/ac_stream.h
davewhiiite/uvc
fd45223097eed5a824294db975b3c74aa5f5cc8f
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * \file ac_stream.h * \copyright Copyright (c) ARM Ltd 2015 * \author Donatien Garnier */ #ifndef ACORE_STREAM_H_ #define ACORE_STREAM_H_ #ifdef __cplusplus extern "C" { #endif struct __ac_istream; struct __ac_ostream; typedef struct __ac_istream ac_istream_t; typedef struct __ac_ostream ac_ostream_t; #include "stddef.h" #include "stdbool.h" #include "stdint.h" #include "acore/ac_buffer.h" typedef void (*ac_istream_fn)(ac_buffer_t *pDataIn, bool *pClose, size_t maxLength, void *pUserParam); typedef void (*ac_ostream_fn)(ac_buffer_t *pDataOut, bool closed, void *pUserParam); //Input stream -- pulled by consumer struct __ac_istream { ac_istream_fn fn; void *pUserParam; }; //Output stream -- pushed by supplier struct __ac_ostream { ac_ostream_fn fn; void *pUserParam; }; //Called by supplier void ac_istream_init(ac_istream_t *pac_istream, ac_istream_fn fn, void *pUserParam); //Called by consumer void ac_istream_pull(ac_istream_t *pac_istream, ac_buffer_t *pDataIn, bool *pClose, size_t maxLength); //Called by consumer void ac_ostream_init(ac_ostream_t *pac_ostream, ac_ostream_fn fn, void *pUserParam); //Called by supplier void ac_ostream_push(ac_ostream_t *pac_ostream, ac_buffer_t *pDataOut, bool closed); #ifdef __cplusplus } #endif #endif /* ACORE_STREAM_H_ */
28.347222
103
0.732484
8d921dce32ab9c0665f2a8349b307c63cdfcc508
174
h
C
Example/Pods/Target Support Files/Pods-SuperTextView_Example/Pods-SuperTextView_Example-umbrella.h
enkaism/SuperTextView
d975577a7ee4d7edcd4a6e824c96a3b0adb6cc4c
[ "MIT" ]
2
2016-06-01T17:11:01.000Z
2016-06-10T07:51:41.000Z
Example/Pods/Target Support Files/Pods-SuperTextView_Example/Pods-SuperTextView_Example-umbrella.h
enkaism/SuperTextView
d975577a7ee4d7edcd4a6e824c96a3b0adb6cc4c
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/Pods-SuperTextView_Example/Pods-SuperTextView_Example-umbrella.h
enkaism/SuperTextView
d975577a7ee4d7edcd4a6e824c96a3b0adb6cc4c
[ "MIT" ]
null
null
null
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SuperTextView_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SuperTextView_ExampleVersionString[];
24.857143
80
0.873563
f20297e2aeef84bf4dcb5284ee8351d6993c1f2f
2,579
h
C
src/server/http/output.h
viyadb/viyadb
56d9b9836a57a36483bee98e6bc79f79e2f5c772
[ "Apache-2.0" ]
109
2017-10-03T06:52:30.000Z
2022-03-22T18:38:48.000Z
src/server/http/output.h
viyadb/viyadb
56d9b9836a57a36483bee98e6bc79f79e2f5c772
[ "Apache-2.0" ]
26
2017-10-15T19:45:18.000Z
2019-10-18T09:55:54.000Z
src/server/http/output.h
viyadb/viyadb
56d9b9836a57a36483bee98e6bc79f79e2f5c772
[ "Apache-2.0" ]
7
2017-10-03T09:37:36.000Z
2020-12-15T01:04:45.000Z
/* * Copyright (c) 2017-present ViyaDB Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef VIYA_SERVER_HTTP_OUTPUT_H_ #define VIYA_SERVER_HTTP_OUTPUT_H_ #include "query/output.h" #include "util/macros.h" #include <ostream> #include <unordered_map> namespace viya { namespace server { namespace http { namespace query = viya::query; class ChunkedTsvOutput : public query::RowOutput { public: ChunkedTsvOutput(std::ostream &stream, char col_sep = '\t', char row_sep = '\n') : stream_(stream), chunk_size_(16384), col_sep_(col_sep), row_sep_(row_sep) {} DISALLOW_COPY_AND_MOVE(ChunkedTsvOutput); ~ChunkedTsvOutput() {} void AddHeader(const std::string &name, const std::string &value) { headers_.emplace(name, value); } void Start() { stream_ << std::hex; stream_ << "HTTP/1.1 200 OK\r\nContent-Type: " "text/tab-separated-values\r\nTransfer-Encoding: " "chunked\r\n"; for (auto it = headers_.begin(); it != headers_.end(); ++it) { stream_ << it->first << ": " << it->second << "\r\n"; } stream_ << "\r\n"; } void SendAsCol(const Row &row) { col_sep_ = '\n'; Send(row); } void Send(const Row &row) { auto size = row.size(); for (size_t i = 0; i < size; ++i) { if (i > 0) { buf_ << col_sep_; } buf_ << row[i]; } buf_ << row_sep_; if (buf_.tellp() >= chunk_size_) { stream_ << buf_.tellp() << crlf_; stream_ << buf_.str() << crlf_; buf_.str(""); } } void Flush() { if (buf_.tellp() > 0) { stream_ << buf_.tellp() << crlf_; stream_ << buf_.str() << crlf_; } stream_ << 0; stream_ << crlf_ << crlf_; } private: static constexpr const char *crlf_ = "\r\n"; std::ostream &stream_; long long chunk_size_; char col_sep_; char row_sep_; std::ostringstream buf_; std::unordered_map<std::string, std::string> headers_; }; } // namespace http } // namespace server } // namespace viya #endif // VIYA_SERVER_HTTP_OUTPUT_H_
25.79
75
0.629314
538f5764cced5f2c61ce1cc21780e119cb92cd30
1,103
h
C
libs/ubuntu_arm/include/pointcloud-1.0.0/PointCloudExports.h
pointcloudAI/libDepthEye
d6a55be236d8b4a0451a7ec4cc3ef38a21fcbadc
[ "MIT" ]
1
2022-03-26T09:52:03.000Z
2022-03-26T09:52:03.000Z
libs/ubuntu_arm/include/pointcloud-1.0.0/PointCloudExports.h
pointcloudAI/libDepthEye
d6a55be236d8b4a0451a7ec4cc3ef38a21fcbadc
[ "MIT" ]
null
null
null
libs/ubuntu_arm/include/pointcloud-1.0.0/PointCloudExports.h
pointcloudAI/libDepthEye
d6a55be236d8b4a0451a7ec4cc3ef38a21fcbadc
[ "MIT" ]
null
null
null
#ifndef POINTCLOUD_EXPORT_H #define POINTCLOUD_EXPORT_H #ifdef POINTCLOUD_STATIC_DEFINE # define POINTCLOUD_EXPORT # define POINTCLOUD_NO_EXPORT #else # ifndef POINTCLOUD_EXPORT # ifdef pointcloud_EXPORTS /* We are building this library */ # define POINTCLOUD_EXPORT __attribute__((visibility("default"))) # else /* We are using this library */ # define POINTCLOUD_EXPORT __attribute__((visibility("default"))) # endif # endif # ifndef POINTCLOUD_NO_EXPORT # define POINTCLOUD_NO_EXPORT __attribute__((visibility("hidden"))) # endif #endif #ifndef POINTCLOUD_DEPRECATED # define POINTCLOUD_DEPRECATED __attribute__ ((__deprecated__)) #endif #ifndef POINTCLOUD_DEPRECATED_EXPORT # define POINTCLOUD_DEPRECATED_EXPORT POINTCLOUD_EXPORT POINTCLOUD_DEPRECATED #endif #ifndef POINTCLOUD_DEPRECATED_NO_EXPORT # define POINTCLOUD_DEPRECATED_NO_EXPORT POINTCLOUD_NO_EXPORT POINTCLOUD_DEPRECATED #endif #if 0 /* DEFINE_NO_DEPRECATED */ # ifndef POINTCLOUD_NO_DEPRECATED # define POINTCLOUD_NO_DEPRECATED # endif #endif #endif /* POINTCLOUD_EXPORT_H */
25.651163
84
0.786945
3e29fd80b1e775d244f120e1a47a3ab2b438cc86
2,974
h
C
Code/Framework/AzToolsFramework/AzToolsFramework/Physics/Material/Legacy/LegacyPhysicsPrefabConversionUtils.h
prophetl33t/o3de
eaeeb883eee1594b1b93327f6909eebd1a826caf
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/Physics/Material/Legacy/LegacyPhysicsPrefabConversionUtils.h
prophetl33t/o3de
eaeeb883eee1594b1b93327f6909eebd1a826caf
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/Physics/Material/Legacy/LegacyPhysicsPrefabConversionUtils.h
prophetl33t/o3de
eaeeb883eee1594b1b93327f6909eebd1a826caf
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzToolsFramework/Prefab/PrefabDomUtils.h> #include <AzToolsFramework/Prefab/PrefabLoaderInterface.h> #include <AzToolsFramework/Prefab/PrefabSystemComponentInterface.h> // O3DE_DEPRECATION_NOTICE(GHI-9840) // Utilities used for legacy material conversion. namespace Physics::Utils { struct PrefabInfo { AzToolsFramework::Prefab::TemplateId m_templateId; AzToolsFramework::Prefab::Template* m_template = nullptr; AZStd::string m_prefabFullPath; }; AZStd::vector<PrefabInfo> CollectPrefabs(); AZStd::vector<AzToolsFramework::Prefab::PrefabDomValue*> GetPrefabEntities(AzToolsFramework::Prefab::PrefabDom& prefab); AZStd::vector<AzToolsFramework::Prefab::PrefabDomValue*> GetEntityComponents(AzToolsFramework::Prefab::PrefabDomValue& entity); AZ::TypeId GetComponentTypeId(const AzToolsFramework::Prefab::PrefabDomValue& component); AzToolsFramework::Prefab::PrefabDomValue* FindMemberChainInPrefabComponent( const AZStd::vector<AZStd::string>& memberChain, AzToolsFramework::Prefab::PrefabDomValue& prefabComponent); const AzToolsFramework::Prefab::PrefabDomValue* FindMemberChainInPrefabComponent( const AZStd::vector<AZStd::string>& memberChain, const AzToolsFramework::Prefab::PrefabDomValue& prefabComponent); void RemoveMemberChainInPrefabComponent( const AZStd::vector<AZStd::string>& memberChain, AzToolsFramework::Prefab::PrefabDomValue& prefabComponent); template<class T> bool LoadObjectFromPrefabComponent( const AZStd::vector<AZStd::string>& memberChain, const AzToolsFramework::Prefab::PrefabDomValue& prefabComponent, T& object) { const auto* member = FindMemberChainInPrefabComponent(memberChain, prefabComponent); if (!member) { return false; } auto result = AZ::JsonSerialization::Load(&object, azrtti_typeid<T>(), *member); return result.GetProcessing() == AZ::JsonSerializationResult::Processing::Completed; } template<class T> bool StoreObjectToPrefabComponent( const AZStd::vector<AZStd::string>& memberChain, AzToolsFramework::Prefab::PrefabDom& prefabDom, AzToolsFramework::Prefab::PrefabDomValue& prefabComponent, const T& object) { auto* member = FindMemberChainInPrefabComponent(memberChain, prefabComponent); if (!member) { return false; } T defaultObject; auto result = AZ::JsonSerialization::Store(*member, prefabDom.GetAllocator(), &object, &defaultObject, azrtti_typeid<T>()); return result.GetProcessing() == AZ::JsonSerializationResult::Processing::Completed; } } // namespace Physics::Utils
38.128205
132
0.726967
3e6f554819e22896e38838b68fb2c16c6fb0e4fa
1,069
h
C
tiamoPCI/source/pci.device.h
godspeed1989/WDUtils
69057e92a5759487ef6bd62a85db24644759b42c
[ "BSD-2-Clause" ]
13
2015-05-29T14:18:53.000Z
2020-08-12T14:26:33.000Z
tiamoPCI/source/pci.device.h
godspeed1989/WDUtils
69057e92a5759487ef6bd62a85db24644759b42c
[ "BSD-2-Clause" ]
null
null
null
tiamoPCI/source/pci.device.h
godspeed1989/WDUtils
69057e92a5759487ef6bd62a85db24644759b42c
[ "BSD-2-Clause" ]
11
2015-06-10T19:27:28.000Z
2020-03-05T10:14:41.000Z
//******************************************************************** // created: 5:10:2008 7:32 // file: pci.device.h // author: tiamo // purpose: device //******************************************************************** #pragma once // // reset // NTSTATUS Device_ResetDevice(__in PPCI_PDO_EXTENSION PdoExt,__in PPCI_COMMON_HEADER Config); // // get additional resource descriptor // VOID Device_GetAdditionalResourceDescriptors(__in PPCI_PDO_EXTENSION PdoExt,__in PPCI_COMMON_HEADER Config,__in PIO_RESOURCE_DESCRIPTOR IoRes); // // massage header // VOID Device_MassageHeaderForLimitsDetermination(__in PPCI_CONFIGURATOR_PARAM Param); // // restore current config // VOID Device_RestoreCurrent(__in PPCI_CONFIGURATOR_PARAM Param); // // save limits // VOID Device_SaveLimits(__in PPCI_CONFIGURATOR_PARAM Param); // // save current config // VOID Device_SaveCurrentSettings(__in PPCI_CONFIGURATOR_PARAM Param); // // change resource config // VOID Device_ChangeResourceSettings(__in struct _PCI_PDO_EXTENSION* PdoExt,__in PPCI_COMMON_HEADER Config);
24.860465
143
0.6913
8bdb6fd93459f5767fa7fe7eb9ff900a5e0763f1
9,710
c
C
usermods/scard/protocols.c
hodlwave/f469-disco
f83f3fe096d02f76452eb48ba8a955d098591531
[ "MIT" ]
24
2019-10-22T14:31:10.000Z
2021-11-26T10:22:21.000Z
usermods/scard/protocols.c
stepansnigirev/f469-disco
38f3451d385d210c840867d65a4d561d5c6dcd40
[ "MIT" ]
12
2020-01-10T20:39:42.000Z
2021-01-14T04:55:38.000Z
usermods/scard/protocols.c
stepansnigirev/f469-disco
38f3451d385d210c840867d65a4d561d5c6dcd40
[ "MIT" ]
17
2019-11-03T14:34:41.000Z
2022-03-07T07:10:38.000Z
/** * @file protocols.c * @brief MicroPython uscard module: protocol wrappers * @author Mike Tolkachev <contact@miketolkachev.dev> * @copyright Copyright 2020 Crypto Advance GmbH. All rights reserved. */ #include <stdio.h> #include "scard.h" #include "protocols.h" #include "py/obj.h" /// Maximal number sequential of TX errors for T=1 protocol #define MAX_TX_ERRORS_T1 (2U) /// Error descriptor typedef struct error_dsc_ { int32_t id; ///< Identifier const char* text; ///< Error text } error_dsc_t; /// T=1 protocol errors static const error_dsc_t errors_t1[] = { { t1_ev_err_internal, "internal error" }, { t1_ev_err_serial_out, "serial output error" }, { t1_ev_err_comm_failure, "smart card connection failed" }, { t1_ev_err_atr_timeout, "ATR timeout" }, { t1_ev_err_bad_atr, "incorrect ATR format" }, { t1_ev_err_incompatible, "incompatible card" }, { t1_ev_err_oversized_apdu, "received APDU does not fit in buffer" }, { t1_ev_err_sc_abort, "operation aborted by smart card" }, { t1_ev_pps_failed, "PPS exchange failed" }, { .text = NULL } // Terminating record }; /// Unknown error const char* unknown_error = "unknown error"; /** * Searches for error text * * @param error_table error table * @param id error identifier * @return error text string */ static const char* error_text(const error_dsc_t* error_table, int32_t id) { const error_dsc_t* p_dsc = error_table; while(p_dsc->text) { if(p_dsc->id == id) { return p_dsc->text; } ++p_dsc; } return unknown_error; } /** * Calls error handler * * @param handle protocol handle * @param text error text */ static inline void emit_error(proto_handle_t handle, const char* text) { proto_ev_prm_t prm = { .error = text }; handle->cb_handle_event(handle->cb_self, proto_ev_error, prm); } /** * T=1 protocol: callback function that outputs bytes to serial port * * @param buf buffer containing data to transmit * @param len length of data block in bytes * @param p_user_prm user defined parameter */ static bool t1_cb_serial_out(const uint8_t* buf, size_t len, void* p_user_prm) { if(scard_module_debug) { scard_ansi_color(SCARD_ANSI_RED); for(size_t i = 0; i < len; ++i) { printf(scard_module_debug_ansi ? " %02X" : " t%02X", buf[i]); } scard_ansi_reset(); } proto_handle_t handle = (proto_handle_t)p_user_prm; bool status = handle->cb_serial_out(handle->cb_self, buf, len); // For T=1 we can skip some TX errors hoping that the block will be // retransmitted if(status) { handle->tx_errors = 0U; } else if(handle->tx_errors >= MAX_TX_ERRORS_T1) { return false; } else { ++handle->tx_errors; } return true; } /** * T=1 protocol: callback function that handles protocol events * * @param ev_code event code * @param ev_prm event parameter depending on event code, typically NULL * @param p_user_prm user defined parameter */ static void t1_cb_handle_event(t1_ev_code_t ev_code, const void* ev_prm, void* p_user_prm) { proto_handle_t handle = (proto_handle_t)p_user_prm; if(t1_is_error_event(ev_code) && t1_ev_err_incompatible != ev_code) { emit_error(handle, error_text(errors_t1, ev_code)); } else { switch(ev_code) { case t1_ev_atr_received: case t1_ev_err_incompatible: { // Forward ATR data t1_atr_decoded_t* p_atr = (t1_atr_decoded_t*)ev_prm; proto_atr_t atr = { .atr = p_atr->atr, .len = p_atr->atr_len }; proto_ev_prm_t prm = { .atr_received = &atr }; handle->cb_handle_event(handle->cb_self, proto_ev_atr_received, prm); // Emit error if the card is incompatible if(t1_ev_err_incompatible == ev_code) { emit_error(handle, error_text(errors_t1, ev_code)); } } break; case t1_ev_connect: { proto_ev_prm_t prm = { .connect = NULL }; handle->cb_handle_event(handle->cb_self, proto_ev_connect, prm); } break; case t1_ev_apdu_received: { t1_apdu_t* p_apdu = (t1_apdu_t*)ev_prm; proto_apdu_t apdu = { .apdu = p_apdu->apdu, .len = p_apdu->len }; proto_ev_prm_t prm = { .apdu_received = &apdu }; handle->cb_handle_event(handle->cb_self, proto_ev_apdu_received, prm); } break; default: break; // Ignore unknown event } } } /** * T=1: releases protocol context * * @param handle protocol handle */ static void deinit_t1(proto_handle_t handle) { if(handle) { if(handle->ctx.t1) { m_del(t1_inst_t, handle->ctx.t1, 1); handle->ctx.t1 = NULL; } m_del(proto_inst_t, handle, 1); } } /** * T=1: initializes protocol implementation * * @param cb_serial_out callback function outputting bytes to serial port * @param cb_handle_event callback function handling protocol events * @param cb_self self parameter for callback * @return protocol handle or NULL if failed */ static proto_handle_t init_t1(proto_cb_serial_out_t cb_serial_out, proto_cb_handle_event_t cb_handle_event, mp_obj_t cb_self) { // Allocate instance of wrap and of a protocol, save parameters proto_handle_t handle = m_new0(proto_inst_t, 1); handle->ctx.t1 = m_new0(t1_inst_t, 1); handle->cb_serial_out = cb_serial_out; handle->cb_handle_event = cb_handle_event; handle->cb_self = cb_self; handle->tx_errors = 0U; if(!t1_init(handle->ctx.t1, t1_cb_serial_out, t1_cb_handle_event, handle)) { deinit_t1(handle); return NULL; } return handle; } /** * T=1: re-initializes protocol instance cleaning receive and transmit buffers * * @param handle protocol handle * @param wait_atr if true sets protocol instance into "waiting for ATR" state */ static void reset_t1(proto_handle_t handle, bool wait_atr) { if(handle) { t1_reset(handle->ctx.t1, wait_atr); } } /** * T=1: timer task, called by host periodically to implement timeouts * * @param handle protocol handle * @param elapsed_ms time in milliseconds passed since previous call */ static void timer_task_t1(proto_handle_t handle, uint32_t elapsed_ms) { if(handle) { t1_timer_task(handle->ctx.t1, elapsed_ms); } } /** * T=1: handles received bytes from serial port * * @param handle protocol handle * @param buf buffer holding received bytes * @param len number of bytes received */ static void serial_in_t1(proto_handle_t handle, const uint8_t* buf, size_t len) { if(scard_module_debug) { scard_ansi_color(SCARD_ANSI_GREEN); for(size_t i = 0; i < len; ++i) { printf(scard_module_debug_ansi ? " %02X" : " r%02X", buf[i]); } scard_ansi_reset(); } if(handle) { t1_serial_in(handle->ctx.t1, buf, len); } } /** * T=1: transmits APDU * * @param handle protocol handle * @param apdu buffer containing APDU * @param len length of APDU in bytes * @return true - OK, false - error */ static void transmit_apdu_t1(proto_handle_t handle, const uint8_t* apdu, size_t len) { if(handle) { if(!t1_transmit_apdu(handle->ctx.t1, apdu, len)) { emit_error(handle, "error transmitting APDU"); } } } /** * Sets T=1 protocol parameter * * @param handle protocol handle * @param prm_id parameter identifier of T=1 protocol * @param value parameter value, accepts proto_prm_unchanged and * proto_prm_default * @return true if successful */ static bool set_t1_config(proto_handle_t handle, t1_config_prm_id_t prm_id, int32_t value) { if(proto_prm_default == value) { return t1_set_default_config(handle->ctx.t1, prm_id); } else if(proto_prm_unchanged != value) { return t1_set_config(handle->ctx.t1, prm_id, value); } return true; } /** * T=1: Configures protocol timeouts * * This function accept special values for timeout parameters: * proto_prm_unchanged, proto_prm_default. * * @param handle protocol handle * @param atr_timeout_ms ATR timeout in ms * @param rsp_timeout_ms response timeout in ms * @param max_timeout_ms maximal response timeout in ms * @return true - OK, false - error */ static void set_timeouts_t1(proto_handle_t handle, int32_t atr_timeout_ms, int32_t rsp_timeout_ms, int32_t max_timeout_ms) { if(handle) { bool ok = set_t1_config(handle, t1_cfg_tm_atr, atr_timeout_ms); ok = ok && set_t1_config(handle, t1_cfg_tm_response, rsp_timeout_ms); ok = ok && set_t1_config(handle, t1_cfg_tm_response_max, max_timeout_ms); if(!ok) { emit_error(handle, "error configuring timeouts"); } } } /// Implementations of protocols const proto_impl_t protocols[] = { { .id = T1_protocol, .name = "T=1", .init = init_t1, .deinit = deinit_t1, .reset = reset_t1, .timer_task = timer_task_t1, .serial_in = serial_in_t1, .transmit_apdu = transmit_apdu_t1, .set_timeouts = set_timeouts_t1 } }; const proto_impl_t* proto_get_implementation(mp_int_t protocol) { size_t arr_size = sizeof(protocols) / sizeof(protocols[0]); for(size_t i = 0; i < arr_size; ++i) { if( protocol & ((int)protocols[i].id) ) { return &protocols[i]; } } return NULL; }
30.15528
80
0.64655
8f743485e2023c42235586bdd97886a8ff9813b9
2,286
h
C
CBHCollectionKitTests/Primitive Collections/CBHSliceTestMacros.h
chris-huxtable/CBHCollectionKit
b6dbc6ad73a2a7a670034c741b79d706795e79c4
[ "0BSD" ]
null
null
null
CBHCollectionKitTests/Primitive Collections/CBHSliceTestMacros.h
chris-huxtable/CBHCollectionKit
b6dbc6ad73a2a7a670034c741b79d706795e79c4
[ "0BSD" ]
null
null
null
CBHCollectionKitTests/Primitive Collections/CBHSliceTestMacros.h
chris-huxtable/CBHCollectionKit
b6dbc6ad73a2a7a670034c741b79d706795e79c4
[ "0BSD" ]
null
null
null
// CBHSliceTestMacros.h // CBHCollectionKitTests // // Created by Christian Huxtable <chris@huxtable.ca>, December 2019. // Copyright (c) 2019 Christian Huxtable. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #pragma once #define CBHAssertSliceState(aBuffer, aCapacity, aType, anEmpty)\ {\ XCTAssertEqual([aBuffer capacity], (aCapacity), @"Incorrect capacity.");\ XCTAssertEqual([aBuffer count], (aCapacity), @"Incorrect count.");\ XCTAssertEqual([aBuffer entrySize], sizeof(aType), @"Incorrect entry size.");\ XCTAssertEqual([aBuffer isEmpty], anEmpty, @"Incorrect empty state.");\ } #define CBHSliceCreateDefault(aName, aType)\ CBHSlice *aName = nil; \ {\ const aType __list[] = {0, 1, 2, 3, 4, 5, 6, 7};\ aName = [CBHSlice sliceWithEntrySize:sizeof(aType) copying:8 entriesFromBytes:__list];\ CBHAssertSliceState(aName, 8, aType, NO);\ } #define CBHMutableSliceCreateDefault(aName, aType)\ CBHMutableSlice *aName = nil; \ {\ const aType __list[] = {0, 1, 2, 3, 4, 5, 6, 7};\ aName = [CBHMutableSlice sliceWithEntrySize:sizeof(aType) copying:8 entriesFromBytes:__list];\ CBHAssertSliceState(aName, 8, aType, NO);\ } #define CBHAssertSliceDefault(aSlice, aType, aWord)\ {\ for (NSUInteger i = 0; i < 8; ++i)\ {\ XCTAssertEqual([aSlice aWord ## AtIndex:i], (aType)i, @"Fails to return correct value at index %lu.", i);\ }\ XCTAssertThrows([aSlice aWord ## AtIndex:8], @"Fails to catch out-of-bounds on access to %u.", 8);\ XCTAssertThrows([aSlice aWord ## AtIndex:NSUIntegerMax], @"Fails to catch out-of-bounds on access to NSUIntegerMax.");\ }
41.563636
120
0.729659
e922b6c8ee053eff7f16d35f1c9ce29cbafc001a
1,034
c
C
src/buzerop.c
blakemcbride/PC-LISP
68633aed5b2c38425e4a4befc48f99a47a14d35d
[ "BSD-2-Clause" ]
43
2015-03-29T03:30:35.000Z
2022-03-08T14:27:18.000Z
src/buzerop.c
blakemcbride/PC-LISP
68633aed5b2c38425e4a4befc48f99a47a14d35d
[ "BSD-2-Clause" ]
4
2016-03-23T13:32:57.000Z
2020-12-15T18:13:45.000Z
src/buzerop.c
blakemcbride/PC-LISP
68633aed5b2c38425e4a4befc48f99a47a14d35d
[ "BSD-2-Clause" ]
8
2015-04-03T20:00:58.000Z
2020-07-29T10:53:17.000Z
/* | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith */ #include <stdio.h> #include <math.h> #include "lisp.h" /************************************************************************* ** buzerop:(zerip number) Return t if number is exactly zero. ** *************************************************************************/ struct conscell *buzerop(form) struct conscell *form; { struct conscell *temp; if ((form != NULL)&&(form->cdrp == NULL)) { if ((temp = form->carp) != NULL) { if (temp->celltype == FIXATOM) { if (FIX(temp)->atom == 0L) return(LIST(thold)); else return(NULL); }; if (temp->celltype == REALATOM) { if (REAL(temp)->atom == 0.0) return(LIST(thold)); else return(NULL); }; }; }; ierror("zerop"); /* doesn't return */ return NULL; /* keep compiler happy */ }
29.542857
75
0.38588
6bfe987ff435b8e17f878df25181dd0da1bea247
4,346
h
C
Eudora71/Eudora/PersParams.h
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Eudora71/Eudora/PersParams.h
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Eudora71/Eudora/PersParams.h
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
// PersParams.h: interface for the CPersParams class. // // Copyright (c) 1997-2001 by QUALCOMM, Incorporated /* Copyright (c) 2016, Computer History Museum All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Computer History Museum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // #if !defined(AFX_PERSPARAMS_H__E76A09A6_0572_11D2_94D2_00805F9BF4D7__INCLUDED_) #define AFX_PERSPARAMS_H__E76A09A6_0572_11D2_94D2_00805F9BF4D7__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 class CPersParams { public: typedef enum { IST_UNKNOWN, IST_POP, IST_IMAP } ServType; CPersParams(); CPersParams(const CPersParams &copy); virtual ~CPersParams(); bool SetInServType(const ServType &type); bool GetInServType(ServType &type) const; bool UpdatePopAccount(); bool GetDefaultParams(); CString PersName; CString RealName; // IDS_INI_REAL_NAME CString POPAccount; // IDS_INI_POP_ACCOUNT CString LoginName; // IDS_INI_LOGIN_NAME CString InServer; // IDS_INI_POP_SERVER CString OutServer; // IDS_INI_SMTP_SERVER CString ReturnAddress; // IDS_INI_RETURN_ADDRESS CString DefaultDomain; // IDS_INI_DOMAIN_QUALIFIER CString Stationery; // IDS_INI_STATIONERY CString Signature; // IDS_INI_SIGNATURE_NAME CString IMAPPrefix; // IDS_INI_IMAP_PREFIX CString LeaveOnServDays; // IDS_INI_LEAVE_ON_SERVER_DAYS CString BigMsgThreshold; // IDS_INI_BIG_MESSAGE_THRESHOLD CString IMAPMaxSize; // IDS_INI_IMAP_MAXSIZE CString IMAPTrashMailbox; // IDS_INI_IMAP_TRASH_MBOXNAME. CString strIMAPAutoExpPct; // IDS_INI_IMAP_AUTO_EXPUNGE_PCT BOOL bCheckMail; // IDS_INI_PERSONA_CHECK_MAIL BOOL bLMOS; // IDS_INI_PERSONA_LMOS BOOL bPOP; // IDS_INI_USES_POP BOOL bIMAP; // IDS_INI_USES_IMAP BOOL bPassword; // IDS_INI_AUTH_PASS BOOL bKerberos; // IDS_INI_AUTH_KERB BOOL bAPop; // IDS_INI_AUTH_APOP BOOL bRPA; // IDS_INI_AUTH_RPA BOOL bWinSock; // IDS_INI_CONNECT_WINSOCK BOOL bDelServerAfter; // IDS_INI_DELETE_MAIL_FROM_SERVER BOOL bDelWhenTrashed; // IDS_INI_SERVER_DELETE BOOL bSkipBigMsgs; // IDS_INI_SKIP_BIG_MESSAGES BOOL bIMAPMinDwnld; // IDS_INI_IMAP_MINDNLOAD BOOL bIMAPFullDwnld; // IDS_INI_IMAP_OMITATTACH BOOL bIMAPXferToTrash; // IDS_INI_IMAP_XFERTOTRASH. BOOL bIMAPMarkDeleted; // IDS_INI_IMAP_MARK_DELETED. BOOL bIMAPAutoExpNever; // IDS_INI_IMAP_AUTO_EXPUNGE_NEVER BOOL bIMAPAutoExpAlways; // IDS_INI_IMAP_AUTO_EXPUNGE_ALWAYS BOOL bIMAPAutoExpOnPct; // IDS_INI_IMAP_AUTO_EXPUNGE_ON_PCT BOOL bSMTPAuthAllowed; // IDS_INI_SMTP_AUTH_ALLOWED BOOL bUseSMTPRelay; // IDS_INI_PERSONA_USE_RELAY int m_SSLReceiveUsage; // IDS_INI_SSL_RECEIVE_USE int m_SSLSendUsage; // IDS_INI_SSL_SEND_USE BOOL bUseSubmissionPort; // IDS_INI_USE_SUBMISSION_PORT }; #endif // !defined(AFX_PERSPARAMS_H__E76A09A6_0572_11D2_94D2_00805F9BF4D7__INCLUDED_)
47.758242
129
0.800276
3a2006a4a3d278700c9e9232d570b6edb80306a1
1,535
h
C
R5Streaming.framework/Headers/R5MetalVideoViewController.h
aif-partners/R5Streaming-Swift
a2acadd1458d31199e9c4e206f9feb1516e2fc4d
[ "MIT" ]
null
null
null
R5Streaming.framework/Headers/R5MetalVideoViewController.h
aif-partners/R5Streaming-Swift
a2acadd1458d31199e9c4e206f9feb1516e2fc4d
[ "MIT" ]
null
null
null
R5Streaming.framework/Headers/R5MetalVideoViewController.h
aif-partners/R5Streaming-Swift
a2acadd1458d31199e9c4e206f9feb1516e2fc4d
[ "MIT" ]
null
null
null
// // R5MetalVideoViewController.h // R5Streaming // // Created by David Heimann on 1/10/19. // Copyright © 2019 Infrared5. All rights reserved. // #import "R5Stream.h" #import <UIKit/UIKit.h> /** * @brief The VideoView for all R5Streaming. This version isn't reliant on OpenGL for rendering. When publishing, it will contain the camera view. While subscribing it will render all incoming stream data. Streams will be cropped to fit the aspect ratio of the view. */ @interface R5MetalVideoViewController : UIViewController /** * Desired FPS to render the video at. FPS lower than the streaming FPS will result in dropped frames. */ @property int preferredFPS; /** * Set a stream to render using this View * * @param videoStream Stream to render */ -(void) attachStream:(R5Stream *)videoStream; /** * Reset the GLES context and setup rendering loop */ -(void) resetContext; /** * Show the publish camera preview. You can use this to show the preview before the Stream is publishing. * * @param visible Set the visibility */ -(void) showPreview:(BOOL)visible; /** * Overlay the view with a log of textual debugging information. * * @param debug Set the visibility of the debug panel */ -(void) showDebugInfo:(BOOL)debug; /** * Set the view render frame * * @param frame Set the frame */ -(void)setFrame:(CGRect) frame; -(void)pauseRender; -(void)resumeRender; /** * Scaling mode of the rendering view for subscribing streams */ @property (nonatomic) r5_scale_mode scaleMode; @end
23.615385
270
0.715961
5c3d4a47cf531434ab46f5ecbf552bc72651b59f
899
h
C
Headers/Frameworks/Flexo/FFInspectorModuleColorMasksChannels.h
CommandPost/FinalCutProFrameworks
d98b00ff0c84af80942d71514e9238d624aca50a
[ "MIT" ]
3
2020-11-19T10:04:02.000Z
2021-10-02T17:25:21.000Z
Headers/Frameworks/Flexo/FFInspectorModuleColorMasksChannels.h
CommandPost/FinalCutProFrameworks
d98b00ff0c84af80942d71514e9238d624aca50a
[ "MIT" ]
null
null
null
Headers/Frameworks/Flexo/FFInspectorModuleColorMasksChannels.h
CommandPost/FinalCutProFrameworks
d98b00ff0c84af80942d71514e9238d624aca50a
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 Steve Nygard. // #import <Flexo/FFInspectorModuleColorChannelsBase.h> __attribute__((visibility("hidden"))) @interface FFInspectorModuleColorMasksChannels : FFInspectorModuleColorChannelsBase { BOOL _optionsDisplayed; } - (void)updateChannelFooterForItems:(id)arg1; - (void)controller:(id)arg1 willChangeChannel:(struct OZChannelBase *)arg2; - (void)_rebuildInspectorWithChannelFolders:(id)arg1 currentItems:(id)arg2 buildContext:(id)arg3 shouldReadLock:(BOOL)arg4; - (BOOL)isHiddenOrAnyDecendent:(struct OZChannelBase *)arg1; - (id)newColorEffectsForStack:(id)arg1; - (void)moduleDidUnhide; - (BOOL)shouldEncloseInScrollView; - (id)_videoEffectsForItem:(id)arg1; - (id)moduleFooterAccessoryView; - (Class)_inspectorDelegateClass; - (void)dealloc; - (id)init; @end
29.966667
123
0.774194