diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..60a2e59 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +Binaries/Win64 +Intermediate +*.exp +*.ilk +ThirdParty/CubiquityC/Src/CMakeFiles +ThirdParty/CubiquityC/Src/_sqlite3.dir +ThirdParty/CubiquityC/Src/CubiquityC.dir +ThirdParty/CubiquityC/Src/Debug +ThirdParty/CubiquityC/Src/Release +ThirdParty/CubiquityC/Src/RelWithDebInfo +ThirdParty/CubiquityC/Src/x64 +/ThirdParty/CubiquityC/Src/*.vcxproj +/ThirdParty/CubiquityC/Src/*.filters +/ThirdParty/CubiquityC/Src/*.user +*.sdf +*.opensdf +*.sln diff --git a/Dependencies/Cubiquity-2015-06-14/bin/CubiquityC.dll b/Dependencies/Cubiquity-2015-06-14/bin/CubiquityC.dll new file mode 100644 index 0000000..895ade1 Binary files /dev/null and b/Dependencies/Cubiquity-2015-06-14/bin/CubiquityC.dll differ diff --git a/Dependencies/Cubiquity-2015-06-14/bin/CubiquityC.lib b/Dependencies/Cubiquity-2015-06-14/bin/CubiquityC.lib new file mode 100644 index 0000000..6c55d16 Binary files /dev/null and b/Dependencies/Cubiquity-2015-06-14/bin/CubiquityC.lib differ diff --git a/Dependencies/Cubiquity-2015-06-14/include/CubiquityC.h b/Dependencies/Cubiquity-2015-06-14/include/CubiquityC.h new file mode 100644 index 0000000..bb11aef --- /dev/null +++ b/Dependencies/Cubiquity-2015-06-14/include/CubiquityC.h @@ -0,0 +1,199 @@ +#ifndef CUBIQUITY_C_INTERFACE_H_ +#define CUBIQUITY_C_INTERFACE_H_ + +#include //C99 fixed size data types. + +// The following ifdef block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the CUBIQUITYC_EXPORTS +// symbol defined on the command line. This symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// CUBIQUITYC_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +#if defined _WIN32 || defined __CYGWIN__ + #ifdef CUBIQUITYC_EXPORTS + #define CUBIQUITYC_API __declspec(dllexport) + #else + #define CUBIQUITYC_API __declspec(dllimport) + #endif +#else + #define CUBIQUITYC_API __attribute__ ((visibility("default"))) +#endif + +extern "C" +{ + const int32_t CU_OK = 0; + + // Standard exceptions, based on list here: http://www.cplusplus.com/reference/exception/exception/ + const int32_t CU_EXCEPTION = 10; + const int32_t CU_BAD_ALLOC = 20; + const int32_t CU_BAD_CAST = 30; + const int32_t CU_BAD_EXCEPTION = 40; + const int32_t CU_BAD_FUNCTION_CALL = 50; + const int32_t CU_BAD_TYPEID = 60; + const int32_t CU_BAD_WEAK_PTR = 70; + //const int32_t ios_base::failure // Included below + const int32_t CU_LOGIC_ERROR = 80; + const int32_t CU_RUNTIME_ERROR = 90; + + const int32_t CU_DOMAIN_ERROR = 100; + const int32_t CU_FUTURE_ERROR = 110; + const int32_t CU_INVALID_ARGUMENT = 120; + const int32_t CU_LENGTH_ERROR = 130; + const int32_t CU_OUT_OF_RANGE = 140; + + const int32_t CU_OVERFLOW_ERROR = 150; + const int32_t CU_RANGE_ERROR = 160; + const int32_t CU_SYSTEM_ERROR = 170; + const int32_t CU_UNDERFLOW_ERROR = 180; + + const int32_t CU_BAD_ARRAY_NEW_LENGTH = 190; + + const int32_t CU_IOS_BASE_FAILURE = 200; + + // Non-standard exceptions + const int32_t CU_DATABASE_ERROR = 210; + const int32_t CU_COMPRESSION_ERROR = 220; + + // Unknown error (caught by ...) + const int32_t CU_UNKNOWN_ERROR = 1000; + + // C version of Cubiquity::WritePermissions + // Fixme - should this be a C enum? + const uint32_t CU_READONLY = 0; + const uint32_t CU_READWRITE = 1; + + // Fixme - should this be a C enum? + // Also, apped '_VOLUME_TYPE'? + const uint32_t CU_COLORED_CUBES = 0; + const uint32_t CU_TERRAIN = 1; + const uint32_t CU_UNKNOWN = 0xFFFFFFFF; + + struct CuColor_s + { + uint32_t data; + }; + typedef struct CuColor_s CuColor; + + struct CuMaterialSet_s + { + uint64_t data; + }; + typedef struct CuMaterialSet_s CuMaterialSet; + + struct CuTerrainVertex_s + { + public: + uint16_t encodedPosX; + uint16_t encodedPosY; + uint16_t encodedPosZ; + uint16_t encodedNormal; + uint8_t material0; + uint8_t material1; + uint8_t material2; + uint8_t material3; + uint8_t material4; + uint8_t material5; + uint8_t material6; + uint8_t material7; + }; + typedef struct CuTerrainVertex_s CuTerrainVertex; + + struct CuColoredCubesVertex_s + { + public: + uint8_t encodedPosX; + uint8_t encodedPosY; + uint8_t encodedPosZ; + uint8_t dummy; + uint32_t data; + }; + typedef struct CuColoredCubesVertex_s CuColoredCubesVertex; + + struct CuOctreeNode_s + { + public: + int32_t posX; + int32_t posY; + int32_t posZ; + + uint32_t structureLastChanged; + uint32_t propertiesLastChanged; + uint32_t meshLastChanged; + uint32_t nodeOrChildrenLastChanged; + + uint32_t childHandles[2][2][2]; + + uint8_t hasMesh; + uint8_t renderThisNode; + uint8_t height; + }; + typedef struct CuOctreeNode_s CuOctreeNode; + + // Version functions + CUBIQUITYC_API int32_t cuGetVersionNumber(uint32_t* majorVersion, uint32_t* minorVersion, uint32_t* patchVersion, uint32_t* buildVersion); + + // Logging functions - Doesn't return error code as it is too simple to fail. + CUBIQUITYC_API const char* cuGetLogFilePath(void); + + // Error handling functions - Don't return error code as they are too simple to fail. + CUBIQUITYC_API const char* cuGetErrorCodeAsString(int32_t errorCode); + CUBIQUITYC_API const char* cuGetLastErrorMessage(void); + + // Color functions - these don't return error codes because they are too simple to fail. + CUBIQUITYC_API uint8_t cuGetRed(CuColor color); + CUBIQUITYC_API uint8_t cuGetGreen(CuColor color); + CUBIQUITYC_API uint8_t cuGetBlue(CuColor color); + CUBIQUITYC_API uint8_t cuGetAlpha(CuColor color); + CUBIQUITYC_API void cuGetAllComponents(CuColor color, uint8_t* red, uint8_t* green, uint8_t* blue, uint8_t* alpha); + + CUBIQUITYC_API CuColor cuMakeColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha); + + // Volume functions + CUBIQUITYC_API int32_t cuNewEmptyColoredCubesVolume(int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ, const char* pathToNewVoxelDatabase, uint32_t baseNodeSize, uint32_t* result); + CUBIQUITYC_API int32_t cuNewColoredCubesVolumeFromVDB(const char* pathToExistingVoxelDatabase, uint32_t writePermissions, uint32_t baseNodeSize, uint32_t* result); + CUBIQUITYC_API int32_t cuUpdateVolume(uint32_t volumeHandle, float eyePosX, float eyePosY, float eyePosZ, float lodThreshold, uint32_t* isUpToDate); + CUBIQUITYC_API int32_t cuDeleteVolume(uint32_t volumeHandle); + + CUBIQUITYC_API int32_t cuGetEnclosingRegion(uint32_t volumeHandle, int32_t* lowerX, int32_t* lowerY, int32_t* lowerZ, int32_t* upperX, int32_t* upperY, int32_t* upperZ); + + CUBIQUITYC_API int32_t cuAcceptOverrideChunks(uint32_t volumeHandle); + CUBIQUITYC_API int32_t cuDiscardOverrideChunks(uint32_t volumeHandle); + + CUBIQUITYC_API int32_t cuNewEmptyTerrainVolume(int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ, const char* pathToNewVoxelDatabase, uint32_t baseNodeSize, uint32_t* result); + CUBIQUITYC_API int32_t cuNewTerrainVolumeFromVDB(const char* pathToExistingVoxelDatabase, uint32_t writePermissions, uint32_t baseNodeSize, uint32_t* result); + + CUBIQUITYC_API int32_t cuGetVolumeType(uint32_t volumeHandle, uint32_t* result); + + // Voxel functions + CUBIQUITYC_API int32_t cuGetVoxel(uint32_t volumeHandle, int32_t x, int32_t y, int32_t z, void* result); + CUBIQUITYC_API int32_t cuSetVoxel(uint32_t volumeHandle, int32_t x, int32_t y, int32_t z, void* value); + + // Octree functions + CUBIQUITYC_API int32_t cuHasRootOctreeNode(uint32_t volumeHandle, uint32_t* result); + CUBIQUITYC_API int32_t cuGetRootOctreeNode(uint32_t volumeHandle, uint32_t* result); + CUBIQUITYC_API int32_t cuGetOctreeNode(uint32_t nodeHandle, CuOctreeNode* result); + + // Mesh functions + CUBIQUITYC_API int32_t cuSetLodRange(uint32_t volumeHandle, int32_t minimumLOD, int32_t maximumLOD); + CUBIQUITYC_API int32_t cuGetMesh(uint32_t nodeHandle, uint16_t* noOfVertices, void** vertices, uint32_t* noOfIndices, uint16_t** indices); + + // Clock functions + CUBIQUITYC_API int32_t cuGetCurrentTime(uint32_t* result); + + // Raycasting functions + CUBIQUITYC_API int32_t cuPickFirstSolidVoxel(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, int32_t* resultX, int32_t* resultY, int32_t* resultZ, uint32_t* result); + CUBIQUITYC_API int32_t cuPickLastEmptyVoxel(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, int32_t* resultX, int32_t* resultY, int32_t* resultZ, uint32_t* result); + + CUBIQUITYC_API int32_t cuPickTerrainSurface(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, float* resultX, float* resultY, float* resultZ, uint32_t* result); + + // Editing functions + CUBIQUITYC_API int32_t cuSculptTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity); + CUBIQUITYC_API int32_t cuBlurTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity); + CUBIQUITYC_API int32_t cuBlurTerrainVolumeRegion(uint32_t volumeHandle, int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ); + CUBIQUITYC_API int32_t cuPaintTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity, uint32_t materialIndex); + + // Volume generation functions + CUBIQUITYC_API int32_t cuGenerateFloor(uint32_t volumeHandle, int32_t lowerLayerHeight, uint32_t lowerLayerMaterial, int32_t upperLayerHeight, uint32_t upperLayerMaterial); +} + +#endif //CUBIQUITY_C_INTERFACE_H_ diff --git a/Dependencies/CubiquityColoredCubesVertexFactory.usf b/Dependencies/CubiquityColoredCubesVertexFactory.usf new file mode 100644 index 0000000..fee5d35 --- /dev/null +++ b/Dependencies/CubiquityColoredCubesVertexFactory.usf @@ -0,0 +1,205 @@ +// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved... + +/*============================================================================= + LocalVertexFactory.usf: Local vertex factory shader code. +=============================================================================*/ + +#include "VertexFactoryCommon.usf" +#include "LocalVertexFactoryCommon.usf" + +float4x4 PreviousLocalToWorld; + +/* Defines what the vertex factory needs as input to the vertex shader. */ +struct FVertexFactoryInput +{ + float4 Position : ATTRIBUTE0; + half4 Color : ATTRIBUTE1; +}; + +struct FPositionOnlyVertexFactoryInput +{ + float4 Position : ATTRIBUTE0; +}; + +/* Used to store cached intermediate data that will be used in multiple vertex factory functions. A common example is the TangentToLocal matrix, which had to be computed from unpacked vertex inputs. */ +struct FVertexFactoryIntermediates +{ + half3x3 TangentToLocal; + half3x3 TangentToWorld; + half TangentToWorldSign; + + half4 Color; +}; + +half3x3 CalcTangentToLocal(FVertexFactoryInput Input) +{ + half3x3 Result; + /*half4 TangentZ = TangentBias(Input.TangentZ); + + // pass-thru the tangent + half3 TangentX = TangentBias(Input.TangentX); + // pass-thru the normal + + // derive the binormal by getting the cross product of the normal and tangent + half3 TangentY = cross(TangentZ.xyz, TangentX) * TangentZ.w; + // Recalculate TangentX off of the other two vectors + // This corrects quantization error since TangentX was passed in as a quantized vertex input + // The error shows up most in specular off of a mesh with a smoothed UV seam (normal is smooth, but tangents vary across the seam) + Result[0] = cross(TangentY, TangentZ.xyz) * TangentZ.w; + Result[1] = TangentY; + Result[2] = TangentZ.xyz;*/ + + Result[0] = half3(0,0,1); + Result[1] = half3(0,0,1); + Result[2] = half3(0,0,1); + + return Result; +} + +half3x3 CalcTangentToWorldNoScale(in half3x3 TangentToLocal) +{ + half3x3 LocalToWorld = GetLocalToWorld3x3(); + half3 InvScale = Primitive.InvNonUniformScale.xyz; + LocalToWorld[0] *= InvScale.x; + LocalToWorld[1] *= InvScale.y; + LocalToWorld[2] *= InvScale.z; + return mul(TangentToLocal, LocalToWorld); +} + +half3x3 CalcTangentToWorld(FVertexFactoryInput Input, half3x3 TangentToLocal) +{ + half3x3 TangentToWorld = CalcTangentToWorldNoScale(TangentToLocal); + return TangentToWorld; +} + +// This is called first in the vertex shader (in Main in BasePassVertexShader.usf but also other passes) to convert the input format to the Intermediates format +FVertexFactoryIntermediates GetVertexFactoryIntermediates(FVertexFactoryInput Input) +{ + FVertexFactoryIntermediates Intermediates; + + Intermediates.TangentToLocal = CalcTangentToLocal(Input); + Intermediates.TangentToWorld = CalcTangentToWorld(Input,Intermediates.TangentToLocal); + Intermediates.TangentToWorldSign = Primitive.LocalToWorldDeterminantSign; + + // Swizzle vertex color. + Intermediates.Color = Input.Color FCOLOR_COMPONENT_SWIZZLE; + return Intermediates; +} + +float4 CalcWorldPosition(float4 Position) +{ + return TransformLocalToTranslatedWorld(Position.xyz); +} + +// @return translated world position +float4 VertexFactoryGetWorldPosition(FVertexFactoryInput Input, FVertexFactoryIntermediates Intermediates) +{ + return CalcWorldPosition(Input.Position); +} + +/** +* Get the 3x3 tangent basis vectors for this vertex factory +* this vertex factory will calculate the binormal on-the-fly +* +* @param Input - vertex input stream structure +* @return 3x3 matrix +*/ +half3x3 VertexFactoryGetTangentToLocal( FVertexFactoryInput Input, FVertexFactoryIntermediates Intermediates ) +{ + //return Intermediates.TangentToLocal; + return half3x3(0,0,1, 0,0,1, 0,0,1); +} + +/** Converts from vertex factory specific input to a FMaterialVertexParameters, which is used by vertex shader material inputs. */ +FMaterialVertexParameters GetMaterialVertexParameters( FVertexFactoryInput Input, FVertexFactoryIntermediates Intermediates, float3 WorldPosition, half3x3 TangentToLocal ) +{ + FMaterialVertexParameters Result = (FMaterialVertexParameters)0; + Result.WorldPosition = WorldPosition - View.PreViewTranslation; + Result.VertexColor = Intermediates.Color; + + Result.TangentToWorld = Intermediates.TangentToWorld; + + return Result; +} + +float4 VertexFactoryGetRasterizedWorldPosition(FVertexFactoryInput Input, FVertexFactoryIntermediates Intermediates, float4 InWorldPosition) +{ + return InWorldPosition; +} + +//Make this empty as we need not interpolate anything (except position which is handled automatically) +//Hmm, we can't redefine it here +/*struct FVertexFactoryInterpolantsVSToPS +{ +};*/ + +FVertexFactoryInterpolantsVSToPS VertexFactoryGetInterpolantsVSToPS(FVertexFactoryInput Input, FVertexFactoryIntermediates Intermediates, FMaterialVertexParameters VertexParameters) +{ + FVertexFactoryInterpolantsVSToPS Interpolants; + // Initialize the whole struct to 0 + Interpolants = (FVertexFactoryInterpolantsVSToPS)0; + + SetColor(Interpolants, Intermediates.Color); + + SetTangents(Interpolants, Intermediates.TangentToWorld[0], Intermediates.TangentToWorld[2], Intermediates.TangentToWorldSign); + + return Interpolants; +} + +float3 TransformWorldPositionToLocal(float3 InWorldPosition) +{ + return mul(float4(InWorldPosition, 1), Primitive.WorldToLocal).xyz; +} + +/** Converts from vertex factory specific interpolants to a FMaterialPixelParameters, which is used by material inputs. */ +// This is called in the pixel shader and converts vertex factory specific interpolants (FVertexFactoryInterpolants) to the FMaterialPixelParameters structure which is used by the pass pixel shaders. +FMaterialPixelParameters GetMaterialPixelParameters(FVertexFactoryInterpolantsVSToPS Interpolants, float4 PixelPosition) +{ + // GetMaterialPixelParameters is responsible for fully initializing the result + FMaterialPixelParameters Result = MakeInitializedMaterialPixelParameters(); + + float3 localPosition = TransformWorldPositionToLocal(PixelPosition.xyz); //Assuming PixelPosition is in world-space + + Result.AbsoluteWorldPosition = PixelPosition; //TODO Is this right? + + float3 volumeNormal = normalize(cross(ddx(PixelPosition.xyz), ddy(PixelPosition.xyz))); + + // This fixes inaccuracies/rounding errors which can otherwise occur + volumeNormal = floor(volumeNormal + float3(0.5, 0.5, 0.5)); + + Result.WorldNormal = TransformLocalToTranslatedWorld(volumeNormal); + + // Because we know our normal is pointing along one of the three main axes we can trivially compute a tangent space. + float3 volumeTangent = volumeNormal.yzx; + float3 volumeBinormal = volumeNormal.zxy; + + // And from our tangent space we can now compute texture coordinates. + float2 texCoords = float2(dot(PixelPosition.xyz, volumeTangent), dot(PixelPosition.xyz, volumeBinormal)); + texCoords = texCoords - float2(0.5, 0.5); // Required because integer positions are at the center of the voxel. + +#if NUM_MATERIAL_TEXCOORDS + Result.TexCoords[0] = texCoords; +#endif + + //These are in volume space, should be in world space? + Result.TangentToWorld[ 0 ] = volumeTangent; + Result.TangentToWorld[ 1 ] = volumeBinormal; + Result.TangentToWorld[ 2 ] = volumeNormal; + + Result.VertexColor = GetColor(Interpolants); + + Result.TwoSidedSign = 1; + return Result; +} + +/** for depth-only pass */ +float4 VertexFactoryGetWorldPosition(FPositionOnlyVertexFactoryInput Input) +{ + return CalcWorldPosition(Input.Position); +} + +// @return previous translated world position +float4 VertexFactoryGetPreviousWorldPosition(FVertexFactoryInput Input, FVertexFactoryIntermediates Intermediates) +{ + return mul(Input.Position, PreviousLocalToWorld); +} \ No newline at end of file diff --git a/Dependencies/README.md b/Dependencies/README.md new file mode 100644 index 0000000..376b6c9 --- /dev/null +++ b/Dependencies/README.md @@ -0,0 +1,4 @@ + +[Forum Post](https://forums.unrealengine.com/showthread.php?29873-Cubiquity-for-UE4-Voxel-Terrain-Plugin&p=311218&viewfull=1#post311218) + + you need to put CubiquityColoredCubesVertexFactory.usf in UnrealEngine/Engine/Shaders in the main Unreal Engine folder (not in your project). diff --git a/Dependencies/example-vdb/ImportedCity.vdb b/Dependencies/example-vdb/ImportedCity.vdb new file mode 100644 index 0000000..74fb4b4 Binary files /dev/null and b/Dependencies/example-vdb/ImportedCity.vdb differ diff --git a/Dependencies/example-vdb/ImportedCityLicense.txt b/Dependencies/example-vdb/ImportedCityLicense.txt new file mode 100644 index 0000000..000509c --- /dev/null +++ b/Dependencies/example-vdb/ImportedCityLicense.txt @@ -0,0 +1,10 @@ +This work (ImportedCity) was created by William Rigby is licensed under a Creative Commons Attribution 4.0 International License. You are allowed: + • to Share - to download it, run it on your server, send it to friends etc. + • to Adapt - remix, transform, and build upon the material for any purpose, even commercially. + +Under the following conditions: + • Attribution - You must specify when releasing modified content that I was the original author and you adapted my work. + +The work has been adapted by David Williams to remove the logo which originally appeared on the water (this modification was explicitly permitted by the creator). + +The original work can be found here: http://buildandshoot.com/viewtopic.php?f=8&t=913 \ No newline at end of file diff --git a/Dependencies/example-vdb/SmoothVoxeliensTerrain.vdb b/Dependencies/example-vdb/SmoothVoxeliensTerrain.vdb new file mode 100644 index 0000000..6c716e3 Binary files /dev/null and b/Dependencies/example-vdb/SmoothVoxeliensTerrain.vdb differ diff --git a/Dependencies/example-vdb/VoxeliensTerrain.vdb b/Dependencies/example-vdb/VoxeliensTerrain.vdb new file mode 100644 index 0000000..555ed72 Binary files /dev/null and b/Dependencies/example-vdb/VoxeliensTerrain.vdb differ diff --git a/Source/Cubiquity/Classes/CubiquityColoredCubesVertexFactory.h b/Source/Cubiquity/Classes/CubiquityColoredCubesVertexFactory.h index a565714..9d7c9da 100644 --- a/Source/Cubiquity/Classes/CubiquityColoredCubesVertexFactory.h +++ b/Source/Cubiquity/Classes/CubiquityColoredCubesVertexFactory.h @@ -19,7 +19,7 @@ struct FColoredCubesVertex FColoredCubesVertex(const FDynamicMeshVertex& other) : Position(other.Position), - Color(other.Position) + Color(other.Color) {} FVector Position; @@ -125,7 +125,7 @@ class FColoredCubesSceneProxy : public FPrimitiveSceneProxy virtual void GetDynamicMeshElements(const TArray& Views, const FSceneViewFamily& ViewFamily, uint32 VisibilityMap, FMeshElementCollector& Collector) const override; - virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View); + virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View) const override; virtual bool CanBeOccluded() const override { return !MaterialRelevance.bDisableDepthTest; }; diff --git a/Source/Cubiquity/Classes/CubiquityColoredCubesVolume.h b/Source/Cubiquity/Classes/CubiquityColoredCubesVolume.h index dc9cd0b..19d5e3d 100644 --- a/Source/Cubiquity/Classes/CubiquityColoredCubesVolume.h +++ b/Source/Cubiquity/Classes/CubiquityColoredCubesVolume.h @@ -26,11 +26,11 @@ class ACubiquityColoredCubesVolume : public ACubiquityVolume //Along a raycast, get the position of the first non-empty voxel UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Cubiquity") - FVector pickFirstSolidVoxel(FVector localStartPosition, FVector localDirection) const; + void pickFirstSolidVoxel(const FVector& localStartPosition, const FVector& localDirection, bool& success, FVector& hitLocation) const; //Along a raycast, get the position of the last empty voxel UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Cubiquity") - FVector pickLastEmptyVoxel(FVector localStartPosition, FVector localDirection) const; + void pickLastEmptyVoxel(const FVector& localStartPosition, const FVector& localDirection, bool& success, FVector& hitLocation) const; //Set a voxel in the volume to a specific value UFUNCTION(BlueprintCallable, Category = "Cubiquity") diff --git a/Source/Cubiquity/Classes/CubiquityMaterialSet.h b/Source/Cubiquity/Classes/CubiquityMaterialSet.h index fa32e7e..d66261d 100644 --- a/Source/Cubiquity/Classes/CubiquityMaterialSet.h +++ b/Source/Cubiquity/Classes/CubiquityMaterialSet.h @@ -12,9 +12,7 @@ class UCubiquityMaterialSet : public UObject GENERATED_BODY() public: - - UCubiquityMaterialSet() = default; - UCubiquityMaterialSet(const Cubiquity::MaterialSet& materialSet) : m_materialSet(materialSet) {} + UCubiquityMaterialSet(); UFUNCTION(BlueprintCallable, Category = "Cubiquity") void setMaterial(uint8 index, uint8 value); @@ -28,5 +26,6 @@ class UCubiquityMaterialSet : public UObject operator Cubiquity::MaterialSet() const { return m_materialSet; } private: + friend class ACubiquityTerrainVolume; Cubiquity::MaterialSet m_materialSet; }; diff --git a/Source/Cubiquity/Classes/CubiquityTerrainVertexFactory.h b/Source/Cubiquity/Classes/CubiquityTerrainVertexFactory.h index 26c81ce..78b25ee 100644 --- a/Source/Cubiquity/Classes/CubiquityTerrainVertexFactory.h +++ b/Source/Cubiquity/Classes/CubiquityTerrainVertexFactory.h @@ -129,7 +129,7 @@ class FGeneratedMeshSceneProxy : public FPrimitiveSceneProxy } } - virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View) + virtual FPrimitiveViewRelevance GetViewRelevance(const FSceneView* View) const override { FPrimitiveViewRelevance Result; Result.bDrawRelevance = IsShown(View); diff --git a/Source/Cubiquity/Classes/CubiquityTerrainVolume.h b/Source/Cubiquity/Classes/CubiquityTerrainVolume.h index 0cd478c..147741b 100644 --- a/Source/Cubiquity/Classes/CubiquityTerrainVolume.h +++ b/Source/Cubiquity/Classes/CubiquityTerrainVolume.h @@ -15,44 +15,44 @@ class UCubiquityMaterialSet; UCLASS() class ACubiquityTerrainVolume : public ACubiquityVolume { - GENERATED_BODY() + GENERATED_BODY() public: - ACubiquityTerrainVolume(const FObjectInitializer& PCIP); - virtual void PostActorCreated() override; - virtual void PostLoad() override; - - virtual void Destroyed() override; - - /** - * \param localPosition the volume-space position of the position to sculpt - * \param innerRadius the volume-space size of the solid part of the brush - * \param outerRadius the volume-space radius of the fall-off region of the brush - * \param opacity - */ - UFUNCTION(BlueprintCallable, Category = "Cubiquity") - void sculptTerrain(FVector localPosition, float innerRadius = 0.5, float outerRadius = 2.0, float opacity = 0.8); - - /** - * \param localStartPosition the volume-space position of the start of the raycast - * \param localDirection the volume-space direction of the raycast - * \return the volume-space position of the raycast hit - */ - UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Cubiquity") - FVector pickSurface(FVector localStartPosition, FVector localDirection) const; - - //Set a voxel in the volume to a specific value - UFUNCTION(BlueprintCallable, Category = "Cubiquity") - void setVoxel(FVector localPosition, const UCubiquityMaterialSet* materialSet); - - //Get the value of a voxel in the terrain - UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Cubiquity") - UCubiquityMaterialSet* getVoxel(FVector localPosition) const; + ACubiquityTerrainVolume(const FObjectInitializer& PCIP); + virtual void PostActorCreated() override; + virtual void PostLoad() override; + + virtual void Destroyed() override; + + /** + * \param localPosition the volume-space position of the position to sculpt + * \param innerRadius the volume-space size of the solid part of the brush + * \param outerRadius the volume-space radius of the fall-off region of the brush + * \param opacity + */ + UFUNCTION(BlueprintCallable, Category = "Cubiquity") + void sculptTerrain(FVector localPosition, float innerRadius = 0.5, float outerRadius = 2.0, float opacity = 0.8); + + /** + * \param localStartPosition the volume-space position of the start of the raycast + * \param localDirection the volume-space direction of the raycast + * \return the volume-space position of the raycast hit + */ + UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Cubiquity") + FVector pickSurface(FVector localStartPosition, FVector localDirection, bool& success) const; + + //Set a voxel in the volume to a specific value + UFUNCTION(BlueprintCallable, Category = "Cubiquity") + void setVoxel(FVector localPosition, const UCubiquityMaterialSet* materialSet); + + //Get the value of a voxel in the terrain + UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Cubiquity") + UCubiquityMaterialSet* getVoxel(FVector localPosition) const; private: - std::unique_ptr m_volume = nullptr; - Cubiquity::Volume* volume() override { return m_volume.get(); } + std::unique_ptr m_volume = nullptr; + Cubiquity::Volume* volume() override { return m_volume.get(); } - void loadVolume() override; + void loadVolume() override; }; diff --git a/Source/Cubiquity/Cubiquity.Build.cs b/Source/Cubiquity/Cubiquity.Build.cs index d3bf321..0e41984 100644 --- a/Source/Cubiquity/Cubiquity.Build.cs +++ b/Source/Cubiquity/Cubiquity.Build.cs @@ -12,17 +12,17 @@ private string ModulePath private string ThirdPartyPath { - get { return Path.GetFullPath("C:/Program Files/Cubiquity-2015-06-14"); } //Edit this line to match where Cubiquity is installed + get { return Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/CubiquityC")); } //Edit this line to match where Cubiquity is installed } private string ThirdPartyLibraryPath { - get { return Path.Combine(ThirdPartyPath, "bin"); } + get { return Path.Combine(ThirdPartyPath, "Lib"); } } private string ThirdPartyIncludePath { - get { return Path.Combine(ThirdPartyPath, "include"); } + get { return Path.Combine(ThirdPartyPath, "Src"); } } public Cubiquity(TargetInfo Target) @@ -38,18 +38,30 @@ public bool LoadCubiquity(TargetInfo Target) { bool isLibrarySupported = false; - if((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32)) + if (Target.Platform == UnrealTargetPlatform.Win64) { isLibrarySupported = true; - string PlatformString = (Target.Platform == UnrealTargetPlatform.Win64) ? "Win64" : "Win32"; + string ConfigurationDirString; + if (Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT) + { + ConfigurationDirString = "Debug"; + } + else if (Target.Configuration == UnrealTargetConfiguration.Shipping) + { + ConfigurationDirString = "Release"; + } + else + { + ConfigurationDirString = "RelWithDebInfo"; + } //string remotePath = @"http://www.volumesoffun.com/downloads/Cubiquity/Cubiquity-2015-06-14.zip"; //System.IO.Compression.ZipFile.ExtractToDirectory(remotePath, extractPath); //Copy the Cubiquity DLL into the binaries directory locally - FileInfo file = new FileInfo(Path.Combine(ThirdPartyLibraryPath, "CubiquityC.dll")); - DirectoryInfo destDir = new DirectoryInfo(Path.Combine(ModulePath, "..", "..", "Binaries", PlatformString)); + FileInfo file = new FileInfo(Path.Combine(ThirdPartyLibraryPath, ConfigurationDirString, "CubiquityC.dll")); + DirectoryInfo destDir = new DirectoryInfo(Path.Combine(ModulePath, "..", "..", "Binaries/Win64")); destDir.Create(); FileInfo destFile = new FileInfo(Path.Combine(destDir.ToString(), "CubiquityC.dll")); if (destFile.Exists) @@ -65,7 +77,8 @@ public bool LoadCubiquity(TargetInfo Target) } //Make sure we can link against the .lib file - PublicAdditionalLibraries.Add(Path.Combine(ThirdPartyLibraryPath, "CubiquityC.lib")); + PublicLibraryPaths.Add(Path.Combine(ThirdPartyLibraryPath, ConfigurationDirString)); + PublicAdditionalLibraries.Add("CubiquityC.lib"); } if(isLibrarySupported) diff --git a/Source/Cubiquity/Private/CubiquityColoredCubesVertexFactory.cpp b/Source/Cubiquity/Private/CubiquityColoredCubesVertexFactory.cpp index 62f42f7..24d027f 100644 --- a/Source/Cubiquity/Private/CubiquityColoredCubesVertexFactory.cpp +++ b/Source/Cubiquity/Private/CubiquityColoredCubesVertexFactory.cpp @@ -180,7 +180,7 @@ void FColoredCubesSceneProxy::GetDynamicMeshElements(const TArray(); + m_volume = loadVolumeImpl(); } -FVector ACubiquityColoredCubesVolume::pickFirstSolidVoxel(FVector localStartPosition, FVector localDirection) const +void ACubiquityColoredCubesVolume::pickFirstSolidVoxel(const FVector& localStartPosition, const FVector& localDirection, bool& success, FVector& hitLocation) const { - bool success; - auto hitLocation = m_volume->pickFirstSolidVoxel({ localStartPosition.X, localStartPosition.Y, localStartPosition.Z }, { localDirection.X, localDirection.Y, localDirection.Z }, &success); - - if (!success) - { - UE_LOG(CubiquityLog, Log, TEXT("Surface pick found nothing")); - return FVector::ZeroVector; - } - - return FVector(hitLocation.x, hitLocation.y, hitLocation.z); + auto ex_hitLocation = m_volume->pickFirstSolidVoxel({ localStartPosition.X, localStartPosition.Y, localStartPosition.Z }, { localDirection.X, localDirection.Y, localDirection.Z }, &success); + + if (!success) + { + UE_LOG(CubiquityLog, Log, TEXT("Surface pick found nothing")); + hitLocation = FVector::ZeroVector; + } + else + { + hitLocation = FVector(ex_hitLocation.x, ex_hitLocation.y, ex_hitLocation.z); + } } -FVector ACubiquityColoredCubesVolume::pickLastEmptyVoxel(FVector localStartPosition, FVector localDirection) const +void ACubiquityColoredCubesVolume::pickLastEmptyVoxel(const FVector& localStartPosition, const FVector& localDirection, bool& success, FVector& hitLocation) const { - bool success; - auto hitLocation = m_volume->pickLastEmptyVoxel({ localStartPosition.X, localStartPosition.Y, localStartPosition.Z }, { localDirection.X, localDirection.Y, localDirection.Z }, &success); - - if (!success) - { - UE_LOG(CubiquityLog, Log, TEXT("Surface pick found nothing")); - return FVector::ZeroVector; - } - - return FVector(hitLocation.x, hitLocation.y, hitLocation.z); + auto ex_hitLocation = m_volume->pickLastEmptyVoxel({ localStartPosition.X, localStartPosition.Y, localStartPosition.Z }, { localDirection.X, localDirection.Y, localDirection.Z }, &success); + + if (!success) + { + UE_LOG(CubiquityLog, Log, TEXT("Surface pick found nothing")); + hitLocation = FVector::ZeroVector; + } + else + { + hitLocation = FVector(ex_hitLocation.x, ex_hitLocation.y, ex_hitLocation.z); + } } void ACubiquityColoredCubesVolume::setVoxel(FVector position, FColor newColor) { - m_volume->setVoxel({ position.X, position.Y, position.Z }, { newColor.R, newColor.G, newColor.B, newColor.A }); + m_volume->setVoxel({ position.X, position.Y, position.Z }, { newColor.R, newColor.G, newColor.B, newColor.A }); } FColor ACubiquityColoredCubesVolume::getVoxel(FVector position) const { - const auto& voxel = m_volume->getVoxel({ position.X, position.Y, position.Z }); - return {voxel.red(), voxel.green(), voxel.blue(), voxel.alpha()}; + const auto& voxel = m_volume->getVoxel({ position.X, position.Y, position.Z }); + return {voxel.red(), voxel.green(), voxel.blue(), voxel.alpha()}; } diff --git a/Source/Cubiquity/Private/CubiquityMaterialSet.cpp b/Source/Cubiquity/Private/CubiquityMaterialSet.cpp index d9f6354..f11c05d 100644 --- a/Source/Cubiquity/Private/CubiquityMaterialSet.cpp +++ b/Source/Cubiquity/Private/CubiquityMaterialSet.cpp @@ -4,6 +4,10 @@ #include "CubiquityMaterialSet.h" +UCubiquityMaterialSet::UCubiquityMaterialSet() : Super() +{ +} + void UCubiquityMaterialSet::setMaterial(uint8 index, uint8 value) { m_materialSet.setMaterial(index, value); diff --git a/Source/Cubiquity/Private/CubiquityMeshComponent.cpp b/Source/Cubiquity/Private/CubiquityMeshComponent.cpp index ef406a8..fde9757 100644 --- a/Source/Cubiquity/Private/CubiquityMeshComponent.cpp +++ b/Source/Cubiquity/Private/CubiquityMeshComponent.cpp @@ -6,6 +6,8 @@ #include "CubiquityTerrainVolume.h" #include "CubiquityColoredCubesVolume.h" +#include "PhysicsEngine/BodySetup.h" + UCubiquityMeshComponent::UCubiquityMeshComponent(const FObjectInitializer& PCIP) : Super(PCIP) { diff --git a/Source/Cubiquity/Private/CubiquityOctreeNode.cpp b/Source/Cubiquity/Private/CubiquityOctreeNode.cpp index fb1d8da..f5f03d2 100644 --- a/Source/Cubiquity/Private/CubiquityOctreeNode.cpp +++ b/Source/Cubiquity/Private/CubiquityOctreeNode.cpp @@ -52,8 +52,8 @@ void ACubiquityOctreeNode::Destroyed() void ACubiquityOctreeNode::initialiseOctreeNode(const Cubiquity::OctreeNode& newOctreeNode, UMaterialInterface* material) { - AttachRootComponentToActor(GetOwner()); - + AttachToActor(GetOwner(), FAttachmentTransformRules::KeepRelativeTransform); + //UE_LOG(CubiquityLog, Log, TEXT("%d My absolute: %d %d %d Parent absolute: %d %d %d Relative: %d %d %d"), depth, nodeX, nodeY, nodeZ, parentX, parentY, parentZ, nodeX - parentX, nodeY - parentY, nodeZ - parentZ); structureLastSynced = 0; diff --git a/Source/Cubiquity/Private/CubiquityTerrainVolume.cpp b/Source/Cubiquity/Private/CubiquityTerrainVolume.cpp index 13d74bb..4bba613 100644 --- a/Source/Cubiquity/Private/CubiquityTerrainVolume.cpp +++ b/Source/Cubiquity/Private/CubiquityTerrainVolume.cpp @@ -9,63 +9,64 @@ #include "CubiquityMaterialSet.h" ACubiquityTerrainVolume::ACubiquityTerrainVolume(const FObjectInitializer& PCIP) - : Super(PCIP) + : Super(PCIP) { - volumeFileName = TEXT("G:/cubiquity/Data/VoxelDatabases/Version 0/SmoothVoxeliensTerrain.vdb"); + volumeFileName = FPaths::ConvertRelativePathToFull(FPaths::GamePluginsDir() + "Cubiquity/Dependencies/example-vdb/SmoothVoxeliensTerrain.vdb"); } void ACubiquityTerrainVolume::PostActorCreated() { - UE_LOG(CubiquityLog, Log, TEXT("ACubiquityTerrainVolume::PostActorCreated")); - - Super::PostActorCreated(); + UE_LOG(CubiquityLog, Log, TEXT("ACubiquityTerrainVolume::PostActorCreated")); + + Super::PostActorCreated(); } void ACubiquityTerrainVolume::PostLoad() { - UE_LOG(CubiquityLog, Log, TEXT("ACubiquityTerrainVolume::PostLoad")); + UE_LOG(CubiquityLog, Log, TEXT("ACubiquityTerrainVolume::PostLoad")); - Super::PostLoad(); + Super::PostLoad(); } void ACubiquityTerrainVolume::Destroyed() { - Super::Destroyed(); + Super::Destroyed(); - m_volume.reset(nullptr); + m_volume.reset(nullptr); } void ACubiquityTerrainVolume::loadVolume() { - m_volume = loadVolumeImpl(); + m_volume = loadVolumeImpl(); } void ACubiquityTerrainVolume::sculptTerrain(FVector localPosition, float innerRadius, float outerRadius, float opacity) { - m_volume->sculpt({ localPosition.X, localPosition.Y, localPosition.Z }, innerRadius, outerRadius, opacity); + m_volume->sculpt({ localPosition.X, localPosition.Y, localPosition.Z }, innerRadius, outerRadius, opacity); } -FVector ACubiquityTerrainVolume::pickSurface(FVector localStartPosition, FVector localDirection) const +FVector ACubiquityTerrainVolume::pickSurface(FVector localStartPosition, FVector localDirection, bool& success) const { - bool success; - auto hitLocation = m_volume->pickSurface({ localStartPosition.X, localStartPosition.Y, localStartPosition.Z }, { localDirection.X, localDirection.Y, localDirection.Z }, &success); + auto hitLocation = m_volume->pickSurface({ localStartPosition.X, localStartPosition.Y, localStartPosition.Z }, { localDirection.X, localDirection.Y, localDirection.Z }, &success); - if (!success) - { - UE_LOG(CubiquityLog, Log, TEXT("Surface pick found nothing")); - return FVector::ZeroVector; - } + if (!success) + { + UE_LOG(CubiquityLog, Log, TEXT("Surface pick found nothing")); + return FVector::ZeroVector; + } - return { hitLocation.x, hitLocation.y, hitLocation.z }; + return { hitLocation.x, hitLocation.y, hitLocation.z }; } void ACubiquityTerrainVolume::setVoxel(FVector position, const UCubiquityMaterialSet* materialSet) { - m_volume->setVoxel({ position.X, position.Y, position.Z }, *materialSet); + m_volume->setVoxel({ position.X, position.Y, position.Z }, *materialSet); } UCubiquityMaterialSet* ACubiquityTerrainVolume::getVoxel(FVector position) const { - const auto& voxel = m_volume->getVoxel({ position.X, position.Y, position.Z }); - return new UCubiquityMaterialSet(voxel); + const auto& voxel = m_volume->getVoxel({ position.X, position.Y, position.Z }); + auto materialSet = NewObject(); + materialSet->m_materialSet = voxel; + return materialSet; } diff --git a/ThirdParty/CubiquityC/CubiquityC.Build.cs b/ThirdParty/CubiquityC/CubiquityC.Build.cs new file mode 100644 index 0000000..d219329 --- /dev/null +++ b/ThirdParty/CubiquityC/CubiquityC.Build.cs @@ -0,0 +1,54 @@ +// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. + +using UnrealBuildTool; + +public class CubiquityC : ModuleRules +{ + public CubiquityC(TargetInfo Target) + { + Type = ModuleType.External; + + PublicIncludePaths.Add("CubiquityC/Src/"); + PrivateIncludePaths.Add("CubiquityC/Src/Dependancies/"); + + string CubiquityCLibPath = "CubiquityC/Lib/"; + + if (Target.Platform == UnrealTargetPlatform.Win64) + { + CubiquityCLibPath += "Win64/VS" + WindowsPlatform.GetVisualStudioCompilerVersionName(); + PublicLibraryPaths.Add(CubiquityCLibPath); + + if (Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT) + { + PublicAdditionalLibraries.Add("CubiquityCD_64.lib"); + } + else + { + PublicAdditionalLibraries.Add("CubiquityC_64.lib"); + } + } + else if (Target.Platform == UnrealTargetPlatform.Win32) + { + CubiquityCLibPath += "Win32/VS" + WindowsPlatform.GetVisualStudioCompilerVersionName(); + PublicLibraryPaths.Add(CubiquityCLibPath); + if (Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT) + { + PublicAdditionalLibraries.Add("CubiquityCD.lib"); + } + else + { + PublicAdditionalLibraries.Add("CubiquityC.lib"); + } + } + else if (Target.Platform == UnrealTargetPlatform.Mac) + { + string Postfix = (Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT) ? "d" : ""; + PublicAdditionalLibraries.Add(CubiquityCLibPath + "Mac/libCubiquityC" + Postfix + ".a"); + } + else if (Target.Platform == UnrealTargetPlatform.Linux) + { + string Postfix = (Target.Configuration == UnrealTargetConfiguration.Debug && BuildConfiguration.bDebugBuildsActuallyUseDebugCRT) ? "d" : ""; + PublicAdditionalLibraries.Add(CubiquityCLibPath + "Linux/" + Target.Architecture + "/libCubiquityC" + Postfix + ".a"); + } + } +} diff --git a/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.dll b/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.dll new file mode 100644 index 0000000..bc7c767 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.dll differ diff --git a/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.lib b/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.lib new file mode 100644 index 0000000..7090e44 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.lib differ diff --git a/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.pdb b/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.pdb new file mode 100644 index 0000000..e21e1f4 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Debug/CubiquityC.pdb differ diff --git a/ThirdParty/CubiquityC/Lib/Debug/_sqlite3.lib b/ThirdParty/CubiquityC/Lib/Debug/_sqlite3.lib new file mode 100644 index 0000000..bd7b0a5 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Debug/_sqlite3.lib differ diff --git a/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.dll b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.dll new file mode 100644 index 0000000..28545f9 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.dll differ diff --git a/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.lib b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.lib new file mode 100644 index 0000000..72eb07d Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.lib differ diff --git a/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.pdb b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.pdb new file mode 100644 index 0000000..db09f45 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/CubiquityC.pdb differ diff --git a/ThirdParty/CubiquityC/Lib/RelWithDebInfo/_sqlite3.lib b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/_sqlite3.lib new file mode 100644 index 0000000..6dfde09 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/RelWithDebInfo/_sqlite3.lib differ diff --git a/ThirdParty/CubiquityC/Lib/Release/CubiquityC.dll b/ThirdParty/CubiquityC/Lib/Release/CubiquityC.dll new file mode 100644 index 0000000..418632a Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Release/CubiquityC.dll differ diff --git a/ThirdParty/CubiquityC/Lib/Release/CubiquityC.lib b/ThirdParty/CubiquityC/Lib/Release/CubiquityC.lib new file mode 100644 index 0000000..33549e3 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Release/CubiquityC.lib differ diff --git a/ThirdParty/CubiquityC/Lib/Release/_sqlite3.lib b/ThirdParty/CubiquityC/Lib/Release/_sqlite3.lib new file mode 100644 index 0000000..1eec019 Binary files /dev/null and b/ThirdParty/CubiquityC/Lib/Release/_sqlite3.lib differ diff --git a/ThirdParty/CubiquityC/Src/BackgroundTaskProcessor.cpp b/ThirdParty/CubiquityC/Src/BackgroundTaskProcessor.cpp new file mode 100644 index 0000000..9064be7 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/BackgroundTaskProcessor.cpp @@ -0,0 +1,114 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "BackgroundTaskProcessor.h" + +/*#include "boost/bind.hpp" + +namespace Cubiquity +{ + BackgroundTaskProcessor gBackgroundTaskProcessor(1); //Our global instance + + BackgroundTaskProcessor::BackgroundTaskProcessor(uint32_t noOfThreads) + :TaskProcessor() + { + for(uint32_t ct = 0; ct < noOfThreads; ct++) + { + boost::thread* taskProcessingThread = new boost::thread(boost::bind(&BackgroundTaskProcessor::processTasks, this)); + mThreads.push_back(taskProcessingThread); + } + } + + BackgroundTaskProcessor::~BackgroundTaskProcessor() + { + for(std::list::iterator threadIter = mThreads.begin(); threadIter != mThreads.end(); threadIter++) + { + (*threadIter)->interrupt(); + (*threadIter)->join(); + delete *threadIter; + } + } + + void BackgroundTaskProcessor::addTask(Task* task) + { + mPendingTasks.push(task); + } + + void BackgroundTaskProcessor::processTasks(void) + { + // This is commented out becaue we're not currently using this class, and having this running + // causes problems on application shutdown. We probably need a way to stop this background processor. + //while(true) + //{ + // Task* task = 0; + // mPendingTasks.wait_and_pop(task); + // task->process(); + //} + } +}*/ + +namespace Cubiquity +{ + BackgroundTaskProcessor gBackgroundTaskProcessor; //Our global instance + + BackgroundTaskProcessor::BackgroundTaskProcessor() + :TaskProcessor() + { + } + + BackgroundTaskProcessor::~BackgroundTaskProcessor() + { + mPendingTasks.clear(); + } + + void BackgroundTaskProcessor::addTask(Task* task) + { + mPendingTasks.push_back(task); + } + + bool BackgroundTaskProcessor::hasTasks(void) + { + return mPendingTasks.size() > 0; + } + + void BackgroundTaskProcessor::processOneTask(void) + { + if (mPendingTasks.size() > 0) + { + Task* task = mPendingTasks.front(); + mPendingTasks.pop_front(); + task->process(); + } + } + + void BackgroundTaskProcessor::processAllTasks(void) + { + while (mPendingTasks.size() > 0) + { + Task* task = mPendingTasks.front(); + mPendingTasks.pop_front(); + task->process(); + } + } +} diff --git a/ThirdParty/CubiquityC/Src/BackgroundTaskProcessor.h b/ThirdParty/CubiquityC/Src/BackgroundTaskProcessor.h new file mode 100644 index 0000000..273cb32 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/BackgroundTaskProcessor.h @@ -0,0 +1,75 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_BACKGROUNDTASKPROCESSOR_H_ +#define CUBIQUITY_BACKGROUNDTASKPROCESSOR_H_ + +#include "ConcurrentQueue.h" +#include "TaskProcessor.h" + +//#include "boost/thread.hpp" + +#include + +namespace Cubiquity +{ + /*class BackgroundTaskProcessor : public TaskProcessor + { + public: + BackgroundTaskProcessor(uint32_t noOfThreads); + virtual ~BackgroundTaskProcessor(); + + void addTask(Task* task); + + bool hasAnyFinishedTasks(void); + Task* removeFirstFinishedTask(void); + + void processTasks(void); + + concurrent_queue mPendingTasks; + + std::list mThreads; + }; + + extern BackgroundTaskProcessor gBackgroundTaskProcessor;*/ + + class BackgroundTaskProcessor : public TaskProcessor + { + public: + BackgroundTaskProcessor(); + virtual ~BackgroundTaskProcessor(); + + void addTask(Task* task); + bool hasTasks(void); + + virtual void processOneTask(void)/* = 0*/; + virtual void processAllTasks(void)/* = 0*/; + + std::list mPendingTasks; + }; + + //extern BackgroundTaskProcessor gBackgroundTaskProcessor; +} + +#endif //CUBIQUITY_BACKGROUNDTASKPROCESSOR_H_ diff --git a/ThirdParty/CubiquityC/Src/BitField.h b/ThirdParty/CubiquityC/Src/BitField.h new file mode 100644 index 0000000..a3332fa --- /dev/null +++ b/ThirdParty/CubiquityC/Src/BitField.h @@ -0,0 +1,95 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_BITFIELD_H +#define CUBIQUITY_BITFIELD_H + +#include + +namespace Cubiquity +{ + template + class BitField + { + public: + BitField(StorageType initialValue = 0) + :mBits(initialValue) + { + } + + bool operator==(const BitField& rhs) const throw() + { + return mBits == rhs.mBits; + }; + + bool operator!=(const BitField& rhs) const throw() + { + return !(*this == rhs); + } + + StorageType getBits(size_t MSB, size_t LSB) const + { + const size_t noOfBitsToGet = (MSB - LSB) + 1; + + // Build a mask containing all '0's except for the least significant bits (which are '1's). + StorageType mask = (std::numeric_limits::max)(); //Set to all '1's + mask = mask << noOfBitsToGet; // Insert the required number of '0's for the lower bits + mask = ~mask; // And invert + + // Move the desired bits into the LSBs and mask them off + StorageType result = (mBits >> LSB) & mask; + + return result; + } + + void setBits(size_t MSB, size_t LSB, StorageType bitsToSet) + { + const size_t noOfBitsToSet = (MSB - LSB) + 1; + + StorageType mask = (std::numeric_limits::max)(); //Set to all '1's + mask = mask << noOfBitsToSet; // Insert the required number of '0's for the lower bits + mask = ~mask; // And invert + mask = mask << LSB; + + bitsToSet = (bitsToSet << LSB) & mask; + + mBits = (mBits & ~mask) | bitsToSet; + } + + StorageType allBits(void) + { + return mBits; + } + + void clearAllBits(void) + { + mBits = 0; + } + + private: + StorageType mBits; + }; +} + +#endif //CUBIQUITY_BITFIELD_H diff --git a/ThirdParty/CubiquityC/Src/Brush.cpp b/ThirdParty/CubiquityC/Src/Brush.cpp new file mode 100644 index 0000000..1f7c1b0 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Brush.cpp @@ -0,0 +1,65 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Brush.h" + +namespace Cubiquity +{ + Brush::Brush(float innerRadius, float outerRadius, float opacity) + :mInnerRadius(innerRadius) + ,mOuterRadius(outerRadius) + ,mOpacity(opacity) + { + } + + float Brush::innerRadius(void) const + { + return mInnerRadius; + } + + float Brush::outerRadius(void) const + { + return mOuterRadius; + } + + float Brush::opacity(void) const + { + return mOpacity; + } + + void Brush::setInnerRadius(float value) + { + mInnerRadius = value; + } + + void Brush::setOuterRadius(float value) + { + mOuterRadius = value; + } + + void Brush::setOpacity(float value) + { + mOpacity = value; + } +} diff --git a/ThirdParty/CubiquityC/Src/Brush.h b/ThirdParty/CubiquityC/Src/Brush.h new file mode 100644 index 0000000..dca0644 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Brush.h @@ -0,0 +1,50 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_BRUSH_H +#define CUBIQUITY_BRUSH_H + +namespace Cubiquity +{ + class Brush + { + public: + Brush(float innerRadius, float outerRadius, float opacity); + + float innerRadius(void) const; + float outerRadius(void) const; + float opacity(void) const; + + void setInnerRadius(float value); + void setOuterRadius(float value); + void setOpacity(float value); + + private: + float mInnerRadius; + float mOuterRadius; + float mOpacity; + }; +} + +#endif //CUBIQUITY_BRUSH_H diff --git a/ThirdParty/CubiquityC/Src/CMakeCache.txt b/ThirdParty/CubiquityC/Src/CMakeCache.txt new file mode 100644 index 0000000..8113e60 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/CMakeCache.txt @@ -0,0 +1,311 @@ +# This is the CMakeCache file. +# For build in directory: d:/VRSculptor/Cubiquity-UE4-Test/Plugins/Cubiquity/ThirdParty/CubiquityC/Src +# It was generated by CMake: C:/Program Files (x86)/CMake/bin/cmake.exe +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//For backwards compatibility, what version of CMake commands and +// syntax should this version of CMake try to support. +CMAKE_BACKWARDS_COMPATIBILITY:STRING=2.4 + +//Semicolon separated list of supported configuration types, only +// supports Debug, Release, MinSizeRel, and RelWithDebInfo, anything +// else will be ignored. +CMAKE_CONFIGURATION_TYPES:STRING=Debug;Release;MinSizeRel;RelWithDebInfo + +//Flags used by the compiler during all build types. +CMAKE_CXX_FLAGS:STRING= /DWIN32 /D_WINDOWS /W3 /GR /EHsc + +//Flags used by the compiler during debug builds. +CMAKE_CXX_FLAGS_DEBUG:STRING=/D_DEBUG /MDd /Zi /Ob0 /Od /RTC1 + +//Flags used by the compiler during release builds for minimum +// size. +CMAKE_CXX_FLAGS_MINSIZEREL:STRING=/MD /O1 /Ob1 /D NDEBUG + +//Flags used by the compiler during release builds. +CMAKE_CXX_FLAGS_RELEASE:STRING=/MD /O2 /Ob2 /D NDEBUG + +//Flags used by the compiler during release builds with debug info. +CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=/MD /Zi /O2 /Ob1 /D NDEBUG + +//Libraries linked by default with all C++ applications. +CMAKE_CXX_STANDARD_LIBRARIES:STRING=kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib + +//Flags used by the compiler during all build types. +CMAKE_C_FLAGS:STRING= /DWIN32 /D_WINDOWS /W3 + +//Flags used by the compiler during debug builds. +CMAKE_C_FLAGS_DEBUG:STRING=/D_DEBUG /MDd /Zi /Ob0 /Od /RTC1 + +//Flags used by the compiler during release builds for minimum +// size. +CMAKE_C_FLAGS_MINSIZEREL:STRING=/MD /O1 /Ob1 /D NDEBUG + +//Flags used by the compiler during release builds. +CMAKE_C_FLAGS_RELEASE:STRING=/MD /O2 /Ob2 /D NDEBUG + +//Flags used by the compiler during release builds with debug info. +CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=/MD /Zi /O2 /Ob1 /D NDEBUG + +//Libraries linked by default with all C applications. +CMAKE_C_STANDARD_LIBRARIES:STRING=kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib + +//Flags used by the linker. +CMAKE_EXE_LINKER_FLAGS:STRING= /machine:x64 + +//Flags used by the linker during debug builds. +CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING=/debug /INCREMENTAL + +//Flags used by the linker during release minsize builds. +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING=/INCREMENTAL:NO + +//Flags used by the linker during release builds. +CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING=/INCREMENTAL:NO + +//Flags used by the linker during Release with Debug Info builds. +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING=/debug /INCREMENTAL + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=C:/Program Files/CubiquityC + +//Path to a program. +CMAKE_LINKER:FILEPATH=C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin/x86_amd64/link.exe + +//Flags used by the linker during the creation of modules. +CMAKE_MODULE_LINKER_FLAGS:STRING= /machine:x64 + +//Flags used by the linker during debug builds. +CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING=/debug /INCREMENTAL + +//Flags used by the linker during release minsize builds. +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING=/INCREMENTAL:NO + +//Flags used by the linker during release builds. +CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING=/INCREMENTAL:NO + +//Flags used by the linker during Release with Debug Info builds. +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING=/debug /INCREMENTAL + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=CubiquityC + +//RC compiler +CMAKE_RC_COMPILER:FILEPATH=rc + +//Flags for Windows Resource Compiler. +CMAKE_RC_FLAGS:STRING=' ' + +//Flags used by the linker during the creation of dll's. +CMAKE_SHARED_LINKER_FLAGS:STRING= /machine:x64 + +//Flags used by the linker during debug builds. +CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING=/debug /INCREMENTAL + +//Flags used by the linker during release minsize builds. +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING=/INCREMENTAL:NO + +//Flags used by the linker during release builds. +CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING=/INCREMENTAL:NO + +//Flags used by the linker during Release with Debug Info builds. +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING=/debug /INCREMENTAL + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=OFF + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=OFF + +//Flags used by the linker during the creation of static libraries. +CMAKE_STATIC_LINKER_FLAGS:STRING= + +//Flags used by the linker during debug builds. +CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during release minsize builds. +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during release builds. +CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during Release with Debug Info builds. +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//If true, cmake will use relative paths in makefiles and projects. +CMAKE_USE_RELATIVE_PATHS:BOOL=OFF + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=OFF + +//Value Computed by CMake +CubiquityC_BINARY_DIR:STATIC=D:/VRSculptor/Cubiquity-UE4-Test/Plugins/Cubiquity/ThirdParty/CubiquityC/Src + +//Dependencies for the target +CubiquityC_LIB_DEPENDS:STATIC=general;_sqlite3; + +//Value Computed by CMake +CubiquityC_SOURCE_DIR:STATIC=D:/VRSculptor/Cubiquity-UE4-Test/Plugins/Cubiquity/ThirdParty/CubiquityC/Src + +//Single output directory for building all executables. +EXECUTABLE_OUTPUT_PATH:PATH=../Lib + +//Single output directory for building all libraries. +LIBRARY_OUTPUT_PATH:PATH=../Lib + +//Dependencies for target +_sqlite3_LIB_DEPENDS:STATIC= + + +######################## +# INTERNAL cache entries +######################## + +//Stored GUID +ALL_BUILD_GUID_CMAKE:INTERNAL=29151205-A2C3-40F7-BFB1-6ABC9EE97BED +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=d:/VRSculptor/Cubiquity-UE4-Test/Plugins/Cubiquity/ThirdParty/CubiquityC/Src +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=2 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=3 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=C:/Program Files (x86)/CMake/bin/cmake.exe +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=C:/Program Files (x86)/CMake/bin/cpack.exe +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=C:/Program Files (x86)/CMake/bin/ctest.exe +//ADVANCED property for variable: CMAKE_CXX_FLAGS +CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG +CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL +CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE +CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO +CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_STANDARD_LIBRARIES +CMAKE_CXX_STANDARD_LIBRARIES-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS +CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG +CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL +CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE +CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO +CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_STANDARD_LIBRARIES +CMAKE_C_STANDARD_LIBRARIES-ADVANCED:INTERNAL=1 +//Executable file format +CMAKE_EXECUTABLE_FORMAT:INTERNAL=Unknown +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS +CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG +CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE +CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Visual Studio 12 2013 Win64 +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Start directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=D:/VRSculptor/Cubiquity-UE4-Test/Plugins/Cubiquity/ThirdParty/CubiquityC/Src +//ADVANCED property for variable: CMAKE_LINKER +CMAKE_LINKER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS +CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG +CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE +CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_LOCAL_GENERATORS:INTERNAL=1 +//ADVANCED property for variable: CMAKE_RC_COMPILER +CMAKE_RC_COMPILER-ADVANCED:INTERNAL=1 +CMAKE_RC_COMPILER_WORKS:INTERNAL=1 +//ADVANCED property for variable: CMAKE_RC_FLAGS +CMAKE_RC_FLAGS-ADVANCED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=C:/Program Files (x86)/CMake/share/cmake-3.2 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS +CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG +CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE +CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS +CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG +CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE +CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//Suppress Warnings that are meant for the author of the CMakeLists.txt +// files. +CMAKE_SUPPRESS_DEVELOPER_WARNINGS:INTERNAL=FALSE +//ADVANCED property for variable: CMAKE_USE_RELATIVE_PATHS +CMAKE_USE_RELATIVE_PATHS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 +//Stored GUID +CubiquityC_GUID_CMAKE:INTERNAL=E41923CE-5EF8-4DB3-9CA8-880D2B56B1A1 +//Stored GUID +INSTALL_GUID_CMAKE:INTERNAL=5720BCB9-ED57-4CFF-A9F5-B9027AFBFA05 +//Stored GUID +SG_Filter_CMake Rules_GUID_CMAKE:INTERNAL=B822E017-DB7D-4356-92FD-8ADF22CC5922 +//Stored GUID +SG_Filter_Header Files_GUID_CMAKE:INTERNAL=551ACACA-A6A7-476F-850B-D5E5762A021C +//Stored GUID +SG_Filter_Object Files_GUID_CMAKE:INTERNAL=8F1CD0DA-5BE0-4D66-9DF7-CCA180C88B97 +//Stored GUID +SG_Filter_Resources_GUID_CMAKE:INTERNAL=39E2046D-CE93-4C22-BEDC-33AC1DD9AC39 +//Stored GUID +SG_Filter_Source Files_GUID_CMAKE:INTERNAL=A22A02F3-A1A8-44A9-813E-8D7DDC1124F5 +//Stored GUID +ZERO_CHECK_GUID_CMAKE:INTERNAL=F3628D2C-218F-47C7-B17E-E507D24739AA +//Stored GUID +_sqlite3_GUID_CMAKE:INTERNAL=720F3C02-CF10-4F38-B004-88A68722BE51 + diff --git a/ThirdParty/CubiquityC/Src/CMakeLists.txt b/ThirdParty/CubiquityC/Src/CMakeLists.txt new file mode 100644 index 0000000..6cf3a74 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/CMakeLists.txt @@ -0,0 +1,161 @@ +################################################################################ +# The MIT License (MIT) +# +# Copyright (c) 2016 David Williams and Matthew Williams +# +# 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. +################################################################################ + +project(CubiquityC) + +################################################################################ +# Build SQLite - Leading underscore to avoid conflict with system version? +################################################################################ +add_library(_sqlite3 STATIC Dependancies/SQLite/sqlite3.c) +set_target_properties(_sqlite3 PROPERTIES COMPILE_FLAGS "-fPIC") +add_definitions( -DSQLITE_OMIT_LOAD_EXTENSION ) # Avoids needing 'dl' on Linux + +# Organise the Visual Studio folders. +SET_PROPERTY(TARGET _sqlite3 PROPERTY FOLDER "Core/Dependancies") + +################################################################################ +# Build PolyVox - Leading underscore to avoid conflict with system version? +################################################################################ +set(POLYVOX_SRCS + # PolyVox code + #Dependancies/polyvox/library/PolyVox/source/AStarPathfinder.cpp + #Dependancies/polyvox/library/PolyVox/source/Region.cpp + + #Dependancies/polyvox/library/PolyVox/source/Impl/ErrorHandling.cpp + #Dependancies/polyvox/library/PolyVox/source/Impl/Logging.cpp + #Dependancies/polyvox/library/PolyVox/source/Impl/MarchingCubesTables.cpp + #Dependancies/polyvox/library/PolyVox/source/Impl/RandomUnitVectors.cpp + #Dependancies/polyvox/library/PolyVox/source/Impl/RandomVectors.cpp + #Dependancies/polyvox/library/PolyVox/source/Impl/Timer.cpp + #Dependancies/polyvox/library/PolyVox/source/Impl/Utility.cpp +) + +#add_library(_PolyVox STATIC ${POLYVOX_SRCS}) + +# Organise the Visual Studio folders. +#SET_PROPERTY(TARGET _PolyVox PROPERTY FOLDER "Core/Dependancies") + +################################################################################ +# Build Cubiquity +################################################################################ +include_directories( + Dependancies/ + Dependancies/polyvox/include/ +) + +set(SRCS + # Main Cubiquity code + BackgroundTaskProcessor.cpp + Brush.cpp + Clock.cpp + Color.cpp + ColoredCubesVolume.cpp + ColoredCubicSurfaceExtractionTask.cpp + Logging.cpp + MainThreadTaskProcessor.cpp + MaterialSet.cpp + Raycasting.cpp + SmoothSurfaceExtractionTask.cpp + TerrainVolume.cpp + TerrainVolumeEditor.cpp + Task.cpp + TerrainVolumeGenerator.cpp + VoxelDatabase.cpp + + # Cubiquity 'C' interface + CubiquityC.cpp +) + +set(HEADERS + # Main Cubiquity code + BackgroundTaskProcessor.h + BitField.h + Brush.h + Clock.h + Color.h + ColoredCubesVolume.h + ColoredCubicSurfaceExtractionTask.h + ConcurrentQueue.h + Cubiquity.h + CubiquityForwardDeclarations.h + Exceptions.h + Logging.h + MainThreadTaskProcessor.h + MaterialSet.h + Octree.h + Octree.inl + OctreeNode.h + OctreeNode.inl + Raycasting.h + Region.h + SmoothSurfaceExtractionTask.h + SQLiteUtils.h + Task.h + TaskProcessor.h + TerrainVolume.h + TerrainVolumeEditor.h + TerrainVolumeGenerator.h + Vector.h + Volume.h + Volume.inl + VoxelDatabase.h + VoxelDatabase.inl + VoxelTraits.h + WritePermissions.h + + # Cubiquity 'C' interface + CubiquityC.h +) + +add_library(CubiquityC SHARED ${SRCS} ${HEADERS}) + +# Organise the Visual Studio folders. +SET_PROPERTY(TARGET CubiquityC PROPERTY FOLDER "Core") + +# Shared library must export symbols +add_definitions( -DCUBIQUITYC_EXPORTS ) + +# Set LINK_FLAGS +if(CMAKE_CXX_COMPILER_ID MATCHES "GNU") + set_target_properties(CubiquityC PROPERTIES LINK_FLAGS "-static-libstdc++ -static-libgcc") +endif() + +# Set target_link_libraries +if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") + target_link_libraries(CubiquityC _sqlite3) +else() + target_link_libraries(CubiquityC _sqlite3 pthread) +endif() + +# The code below was copied from the old separate 'C' wrapper. I'm not sure we need it but it's here for safe keeping. +#if(CMAKE_SYSTEM_NAME MATCHES "Linux") + # +#elseif(CMAKE_SYSTEM_NAME MATCHES "Darwin") +# target_link_libraries(CubiquityC /home/matt/osxcross/build/libcxx-3.4/build/lib/libc++.a /home/matt/osxcross/target/SDK/MacOSX10.8.sdk/usr/lib/libc++abi.dylib) +#elseif(CMAKE_SYSTEM_NAME MATCHES "Windows") + # +#endif() + +install(TARGETS CubiquityC DESTINATION bin) +install(FILES CubiquityC.h DESTINATION include) diff --git a/ThirdParty/CubiquityC/Src/Clock.cpp b/ThirdParty/CubiquityC/Src/Clock.cpp new file mode 100644 index 0000000..8d09a00 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Clock.cpp @@ -0,0 +1,44 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Clock.h" + +#include "PolyVox/Impl/ErrorHandling.h" + +#include + +namespace Cubiquity +{ + // We initialise the clock to a reasonably sized value, so that we can initialise + // timestamps to small values and be sure that they will immediatly be out-of-date. + Timestamp Clock::mTimestamp = 100; + + Timestamp Clock::getTimestamp(void) + { + // I don't think we need to protect this operation with a mutex. Potentially two threads could enter this function and then + // leave in a different order to which they entered, but I don't think that matters as long as the timestamps are unique? + POLYVOX_ASSERT(mTimestamp < (std::numeric_limits::max)(), "Time stamp is wrapping around."); + return ++mTimestamp; + } +} diff --git a/ThirdParty/CubiquityC/Src/Clock.h b/ThirdParty/CubiquityC/Src/Clock.h new file mode 100644 index 0000000..ed130fd --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Clock.h @@ -0,0 +1,46 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_CLOCK_H +#define CUBIQUITY_CLOCK_H + +#include + +namespace Cubiquity +{ + typedef uint32_t Timestamp; + + class Clock + { + public: + static Timestamp getTimestamp(void); + + private: + // This should be atomic but I don't have a recent enough version of boost. + // This will be addressed in the future with a new boost version or C++11. + static Timestamp mTimestamp; + }; +} + +#endif //CUBIQUITY_CLOCK_H diff --git a/ThirdParty/CubiquityC/Src/Color.cpp b/ThirdParty/CubiquityC/Src/Color.cpp new file mode 100644 index 0000000..5e9376b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Color.cpp @@ -0,0 +1,56 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Color.h" + +namespace Cubiquity +{ + Color operator+(const Color& lhs, const Color& rhs) throw() + { + // This is a dummy function - see header. + assert(false); + return lhs; + } + + Color operator-(const Color& lhs, const Color& rhs) throw() + { + // This is a dummy function - see header. + assert(false); + return lhs; + } + + Color operator*(const Color& lhs, float rhs) throw() + { + // This is a dummy function - see header. + assert(false); + return lhs; + } + + Color operator/(const Color& lhs, float rhs) throw() + { + // This is a dummy function - see header. + assert(false); + return lhs; + } +} diff --git a/ThirdParty/CubiquityC/Src/Color.h b/ThirdParty/CubiquityC/Src/Color.h new file mode 100644 index 0000000..61958ed --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Color.h @@ -0,0 +1,165 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 __COLOUR_H__ +#define __COLOUR_H__ + +#include "PolyVox/CubicSurfaceExtractor.h" +#include "PolyVox/Vertex.h" + +#include "BitField.h" + +#include + +namespace Cubiquity +{ + class Color + { + public: + + static const uint32_t MaxInOutValue = 255; + + static const uint32_t RedMSB = 31; + static const uint32_t RedLSB = 27; + static const uint32_t GreenMSB = 26; + static const uint32_t GreenLSB = 21; + static const uint32_t BlueMSB = 20; + static const uint32_t BlueLSB = 16; + static const uint32_t AlphaMSB = 15; + static const uint32_t AlphaLSB = 12; + + static const uint32_t NoOfRedBits = RedMSB - RedLSB + 1; + static const uint32_t NoOfGreenBits = GreenMSB - GreenLSB + 1; + static const uint32_t NoOfBlueBits = BlueMSB - BlueLSB + 1; + static const uint32_t NoOfAlphaBits = AlphaMSB - AlphaLSB + 1; + + static const uint32_t RedScaleFactor = MaxInOutValue / ((0x01 << NoOfRedBits) - 1); + static const uint32_t GreenScaleFactor = MaxInOutValue / ((0x01 << NoOfGreenBits) - 1); + static const uint32_t BlueScaleFactor = MaxInOutValue / ((0x01 << NoOfBlueBits) - 1); + static const uint32_t AlphaScaleFactor = MaxInOutValue / ((0x01 << NoOfAlphaBits) - 1); + + Color() + { + mChannels.clearAllBits(); + } + + Color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = MaxInOutValue) + { + mChannels.clearAllBits(); + setColor(red, green, blue, alpha); + } + + bool operator==(const Color& rhs) const throw() + { + return mChannels == rhs.mChannels; + } + + bool operator!=(const Color& rhs) const throw() + { + return !(*this == rhs); + } + + uint8_t getRed(void) + { + return static_cast(mChannels.getBits(RedMSB, RedLSB) * RedScaleFactor); + } + + uint8_t getGreen(void) + { + return static_cast(mChannels.getBits(GreenMSB, GreenLSB) * GreenScaleFactor); + } + + uint8_t getBlue(void) + { + return static_cast(mChannels.getBits(BlueMSB, BlueLSB) * BlueScaleFactor); + } + + uint8_t getAlpha(void) + { + return static_cast(mChannels.getBits(AlphaMSB, AlphaLSB) * AlphaScaleFactor); + } + + void setRed(uint8_t value) + { + mChannels.setBits(RedMSB, RedLSB, value / RedScaleFactor); + } + + void setGreen(uint8_t value) + { + mChannels.setBits(GreenMSB, GreenLSB, value / GreenScaleFactor); + } + + void setBlue(uint8_t value) + { + mChannels.setBits(BlueMSB, BlueLSB, value / BlueScaleFactor); + } + + void setAlpha(uint8_t value) + { + mChannels.setBits(AlphaMSB, AlphaLSB, value / AlphaScaleFactor); + } + + void setColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) + { + setRed(red); + setGreen(green); + setBlue(blue); + setAlpha(alpha); + } + + private: + BitField mChannels; + }; + + // These operations are used by the smooth raycast to perform trilinear interpolation. + // We never actually do that on this type (because colors are used for cubic surfaces + // not smooth ones) but our use of templates means that this code path still gets compiled. + // The actual implementations simply assert if they are ever called by mistake. + Color operator+(const Color& lhs, const Color& rhs) throw(); + Color operator-(const Color& lhs, const Color& rhs) throw(); + Color operator*(const Color& lhs, float rhs) throw(); + Color operator/(const Color& lhs, float rhs) throw(); + + class ColoredCubesIsQuadNeeded + { + public: + bool operator()(Color back, Color front, Color& materialToUse) + { + if((back.getAlpha() > 0) && (front.getAlpha() == 0)) + { + materialToUse = back; + return true; + } + else + { + return false; + } + } + }; + + typedef ::PolyVox::CubicVertex ColoredCubesVertex; + typedef ::PolyVox::Mesh ColoredCubesMesh; +} + +#endif //__COLOUR_H__ diff --git a/ThirdParty/CubiquityC/Src/ColoredCubesVolume.cpp b/ThirdParty/CubiquityC/Src/ColoredCubesVolume.cpp new file mode 100644 index 0000000..ef5de70 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/ColoredCubesVolume.cpp @@ -0,0 +1,36 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "ColoredCubesVolume.h" + +#include "Clock.h" +#include "Color.h" +#include "ColoredCubicSurfaceExtractionTask.h" +#include "MainThreadTaskProcessor.h" + +using namespace PolyVox; + +namespace Cubiquity +{ +} diff --git a/ThirdParty/CubiquityC/Src/ColoredCubesVolume.h b/ThirdParty/CubiquityC/Src/ColoredCubesVolume.h new file mode 100644 index 0000000..c61f2c8 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/ColoredCubesVolume.h @@ -0,0 +1,64 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 COLOUREDCUBESVOLUME_H_ +#define COLOUREDCUBESVOLUME_H_ + +#include "Color.h" +#include "Cubiquity.h" +#include "CubiquityForwardDeclarations.h" +#include "Volume.h" + +namespace Cubiquity +{ + class ColoredCubesVolume : public Volume + { + public: + typedef Color VoxelType; + + ColoredCubesVolume(const Region& region, const std::string& pathToNewVoxelDatabase, unsigned int baseNodeSize) + :Volume(region, pathToNewVoxelDatabase, baseNodeSize) + { + m_pVoxelDatabase->setProperty("VoxelType", "Color"); + + mOctree = new Octree(this, OctreeConstructionModes::BoundVoxels, baseNodeSize); + } + + ColoredCubesVolume(const std::string& pathToExistingVoxelDatabase, WritePermission writePermission, unsigned int baseNodeSize) + :Volume(pathToExistingVoxelDatabase, writePermission, baseNodeSize) + { + std::string voxelType = m_pVoxelDatabase->getPropertyAsString("VoxelType", ""); + POLYVOX_THROW_IF(voxelType != "Color", std::runtime_error, "VoxelDatabase does not have the expected VoxelType of 'Color'"); + + mOctree = new Octree(this, OctreeConstructionModes::BoundVoxels, baseNodeSize); + } + + virtual ~ColoredCubesVolume() + { + delete mOctree; + } + }; +} + +#endif //COLOUREDCUBESVOLUME_H_ diff --git a/ThirdParty/CubiquityC/Src/ColoredCubicSurfaceExtractionTask.cpp b/ThirdParty/CubiquityC/Src/ColoredCubicSurfaceExtractionTask.cpp new file mode 100644 index 0000000..efa8722 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/ColoredCubicSurfaceExtractionTask.cpp @@ -0,0 +1,172 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "ColoredCubicSurfaceExtractionTask.h" + +#include "Color.h" +#include "OctreeNode.h" + +#include "PolyVox/CubicSurfaceExtractor.h" +#include "PolyVox/RawVolume.h" +#include "PolyVox/PagedVolume.h" + +#include + +using namespace PolyVox; + +namespace Cubiquity +{ + // Eliminate this + void scaleVertices(ColoredCubesMesh* mesh, uint32_t amount) + { + for (uint32_t ct = 0; ct < mesh->getNoOfVertices(); ct++) + { + ColoredCubesVertex& vertex = const_cast(mesh->getVertex(ct)); + vertex.encodedPosition *= amount; + } + } + + // Eliminate this + /*void translateVertices(ColoredCubesMesh* mesh, const Vector3DUint8& amount) + { + for (uint32_t ct = 0; ct < mesh->m_vecVertices.size(); ct++) + { + //TODO: Should rethink accessors here to provide faster access + Vector3DUint8 position = mesh->m_vecVertices[ct].position; + position += amount; + mesh->m_vecVertices[ct].position = position; + } + }*/ + + ColoredCubicSurfaceExtractionTask::ColoredCubicSurfaceExtractionTask(OctreeNode< Color >* octreeNode, ::PolyVox::PagedVolume* polyVoxVolume) + :Task() + ,mOctreeNode(octreeNode) + ,mPolyVoxVolume(polyVoxVolume) + ,mPolyVoxMesh(0) + ,mProcessingStartedTimestamp((std::numeric_limits::max)()) + ,mOwnMesh(false) + { + } + + ColoredCubicSurfaceExtractionTask::~ColoredCubicSurfaceExtractionTask() + { + if(mOwnMesh) + { + delete mPolyVoxMesh; + mPolyVoxMesh = 0; + mOwnMesh = false; + } + } + + void ColoredCubicSurfaceExtractionTask::process(void) + { + mProcessingStartedTimestamp = Clock::getTimestamp(); + + Region lod0Region = mOctreeNode->mRegion; + + //Extract the surface + mPolyVoxMesh = new ColoredCubesMesh; + mOwnMesh = true; + + uint32_t downScaleFactor = 0x0001 << mOctreeNode->mHeight; + + ColoredCubesIsQuadNeeded isQuadNeeded; + + if(downScaleFactor == 1) + { + extractCubicMeshCustom(mPolyVoxVolume, mOctreeNode->mRegion, mPolyVoxMesh, isQuadNeeded, true); + } + else if(downScaleFactor == 2) + { + + Region srcRegion = mOctreeNode->mRegion; + + srcRegion.grow(2); + + Vector3I lowerCorner = srcRegion.getLowerCorner(); + Vector3I upperCorner = srcRegion.getUpperCorner(); + + upperCorner = upperCorner - lowerCorner; + upperCorner = upperCorner / static_cast(downScaleFactor); + upperCorner = upperCorner + lowerCorner; + + Region dstRegion(lowerCorner, upperCorner); + + ::PolyVox::RawVolume resampledVolume(dstRegion); + rescaleCubicVolume(mPolyVoxVolume, srcRegion, &resampledVolume, dstRegion); + + dstRegion.shrink(1); + + //dstRegion.shiftLowerCorner(-1, -1, -1); + + extractCubicMeshCustom(&resampledVolume, dstRegion, mPolyVoxMesh, isQuadNeeded, true); + + scaleVertices(mPolyVoxMesh, downScaleFactor); + //translateVertices(mPolyVoxMesh, Vector3DFloat(0.5f, 0.5f, 0.5f)); // Removed when going from float positions to uin8_t. Do we need this? + } + else if(downScaleFactor == 4) + { + Region srcRegion = mOctreeNode->mRegion; + + srcRegion.grow(4); + + Vector3I lowerCorner = srcRegion.getLowerCorner(); + Vector3I upperCorner = srcRegion.getUpperCorner(); + + upperCorner = upperCorner - lowerCorner; + upperCorner = upperCorner / static_cast(2); + upperCorner = upperCorner + lowerCorner; + + Region dstRegion(lowerCorner, upperCorner); + + ::PolyVox::RawVolume resampledVolume(dstRegion); + rescaleCubicVolume(mPolyVoxVolume, srcRegion, &resampledVolume, dstRegion); + + + + lowerCorner = dstRegion.getLowerCorner(); + upperCorner = dstRegion.getUpperCorner(); + + upperCorner = upperCorner - lowerCorner; + upperCorner = upperCorner / static_cast(2); + upperCorner = upperCorner + lowerCorner; + + Region dstRegion2(lowerCorner, upperCorner); + + ::PolyVox::RawVolume resampledVolume2(dstRegion2); + rescaleCubicVolume(&resampledVolume, dstRegion, &resampledVolume2, dstRegion2); + + dstRegion2.shrink(1); + + //dstRegion.shiftLowerCorner(-1, -1, -1); + + extractCubicMeshCustom(&resampledVolume2, dstRegion2, mPolyVoxMesh, isQuadNeeded, true); + + scaleVertices(mPolyVoxMesh, downScaleFactor); + //translateVertices(mPolyVoxMesh, Vector3DFloat(1.5f, 1.5f, 1.5f)); // Removed when going from float positions to uin8_t. Do we need this? + } + + mOctreeNode->mOctree->mFinishedSurfaceExtractionTasks.push(this); + } +} diff --git a/ThirdParty/CubiquityC/Src/ColoredCubicSurfaceExtractionTask.h b/ThirdParty/CubiquityC/Src/ColoredCubicSurfaceExtractionTask.h new file mode 100644 index 0000000..15108fe --- /dev/null +++ b/ThirdParty/CubiquityC/Src/ColoredCubicSurfaceExtractionTask.h @@ -0,0 +1,204 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_COLOUREDCUBICSURFACEEXTRACTIONTASK_H_ +#define CUBIQUITY_COLOUREDCUBICSURFACEEXTRACTIONTASK_H_ + +#include "Clock.h" +#include "Color.h" +#include "CubiquityForwardDeclarations.h" +#include "Region.h" +#include "Task.h" +#include "Vector.h" +#include "VoxelTraits.h" + +#include "PolyVox/PagedVolume.h" + +namespace Cubiquity +{ + class ColoredCubicSurfaceExtractionTask : public Task + { + public: + ColoredCubicSurfaceExtractionTask(OctreeNode< Color >* octreeNode, ::PolyVox::PagedVolume* polyVoxVolume); + ~ColoredCubicSurfaceExtractionTask(); + + void process(void); + + public: + OctreeNode< Color >* mOctreeNode; + ::PolyVox::PagedVolume* mPolyVoxVolume; + ColoredCubesMesh* mPolyVoxMesh; + Timestamp mProcessingStartedTimestamp; + + // Whether the task owns the mesh, or whether it has been passed to + // the OctreeNode. Should probably switch this to use a smart pointer. + bool mOwnMesh; + }; + + template< typename SrcPolyVoxVolumeType, typename DstPolyVoxVolumeType> + void rescaleCubicVolume(SrcPolyVoxVolumeType* pVolSrc, const Region& regSrc, DstPolyVoxVolumeType* pVolDst, const Region& regDst) + { + POLYVOX_ASSERT(regSrc.getWidthInVoxels() == regDst.getWidthInVoxels() * 2, "Wrong size!"); + POLYVOX_ASSERT(regSrc.getHeightInVoxels() == regDst.getHeightInVoxels() * 2, "Wrong size!"); + POLYVOX_ASSERT(regSrc.getDepthInVoxels() == regDst.getDepthInVoxels() * 2, "Wrong size!"); + + typename SrcPolyVoxVolumeType::Sampler srcSampler(pVolSrc); + typename DstPolyVoxVolumeType::Sampler dstSampler(pVolDst); + + // First of all we iterate over all destination voxels and compute their color as the + // average of the colors of the eight corresponding voxels in the higher resolution version. + for(int32_t z = 0; z < regDst.getDepthInVoxels(); z++) + { + for(int32_t y = 0; y < regDst.getHeightInVoxels(); y++) + { + for(int32_t x = 0; x < regDst.getWidthInVoxels(); x++) + { + Vector3I srcPos = regSrc.getLowerCorner() + (Vector3I(x, y, z) * 2); + Vector3I dstPos = regDst.getLowerCorner() + Vector3I(x, y, z); + + uint32_t noOfSolidVoxels = 0; + uint32_t averageOf8Red = 0; + uint32_t averageOf8Green = 0; + uint32_t averageOf8Blue = 0; + for(int32_t childZ = 0; childZ < 2; childZ++) + { + for(int32_t childY = 0; childY < 2; childY++) + { + for(int32_t childX = 0; childX < 2; childX++) + { + srcSampler.setPosition(srcPos + Vector3I(childX, childY, childZ)); + + Color child = srcSampler.getVoxel(); + + if(child.getAlpha () > 0) + { + noOfSolidVoxels++; + averageOf8Red += child.getRed(); + averageOf8Green += child.getGreen(); + averageOf8Blue += child.getBlue(); + } + } + } + } + + // We only make a voxel solid if the eight corresponding voxels are also all solid. This + // means that higher LOD meshes actually shrink away which ensures cracks aren't visible. + if(noOfSolidVoxels > 7) + { + Color color; + color.setColor(averageOf8Red / noOfSolidVoxels, averageOf8Green / noOfSolidVoxels, averageOf8Blue / noOfSolidVoxels, 255); + pVolDst->setVoxel(dstPos, color); + } + else + { + Color color; + color.setColor(0,0,0,0); + pVolDst->setVoxel(dstPos, color); + } + } + } + } + + // At this point the results are usable, but we have a problem with thin structures disappearing. + // For example, if we have a solid blue sphere with a one voxel thick layer of red voxels on it, + // then we don't care that the shape changes then the red voxels are lost but we do care that the + // color changes, as this is very noticable. Our solution is o process again only those voxels + // which lie on a material-air boundary, and to recompute their color using a larger naighbourhood + // while also accounting for how visible the child voxels are. + for(int32_t z = 0; z < regDst.getDepthInVoxels(); z++) + { + for(int32_t y = 0; y < regDst.getHeightInVoxels(); y++) + { + for(int32_t x = 0; x < regDst.getWidthInVoxels(); x++) + { + Vector3I dstPos = regDst.getLowerCorner() + Vector3I(x, y, z); + + dstSampler.setPosition(dstPos); + + //Skip empty voxels + if(dstSampler.getVoxel().getAlpha() > 0) + { + //Only process voxels on a material-air boundary. + if((dstSampler.peekVoxel0px0py1nz().getAlpha() == 0) || + (dstSampler.peekVoxel0px0py1pz().getAlpha() == 0) || + (dstSampler.peekVoxel0px1ny0pz().getAlpha() == 0) || + (dstSampler.peekVoxel0px1py0pz().getAlpha() == 0) || + (dstSampler.peekVoxel1nx0py0pz().getAlpha() == 0) || + (dstSampler.peekVoxel1px0py0pz().getAlpha() == 0)) + { + Vector3I srcPos = regSrc.getLowerCorner() + (Vector3I(x, y, z) * 2); + + uint32_t totalRed = 0; + uint32_t totalGreen = 0; + uint32_t totalBlue = 0; + uint32_t totalExposedFaces = 0; + + // Look ate the 64 (4x4x4) children + for(int32_t childZ = -1; childZ < 3; childZ++) + { + for(int32_t childY = -1; childY < 3; childY++) + { + for(int32_t childX = -1; childX < 3; childX++) + { + srcSampler.setPosition(srcPos + Vector3I(childX, childY, childZ)); + + Color child = srcSampler.getVoxel(); + + if(child.getAlpha () > 0) + { + // For each small voxel, count the exposed faces and use this + // to determine the importance of the color contribution. + uint32_t exposedFaces = 0; + if(srcSampler.peekVoxel0px0py1nz().getAlpha() == 0) exposedFaces++; + if(srcSampler.peekVoxel0px0py1pz().getAlpha() == 0) exposedFaces++; + if(srcSampler.peekVoxel0px1ny0pz().getAlpha() == 0) exposedFaces++; + if(srcSampler.peekVoxel0px1py0pz().getAlpha() == 0) exposedFaces++; + if(srcSampler.peekVoxel1nx0py0pz().getAlpha() == 0) exposedFaces++; + if(srcSampler.peekVoxel1px0py0pz().getAlpha() == 0) exposedFaces++; + + totalRed += child.getRed() * exposedFaces; + totalGreen += child.getGreen() * exposedFaces; + totalBlue += child.getBlue() * exposedFaces; + + totalExposedFaces += exposedFaces; + } + } + } + } + + // Avoid divide by zero if there were no exposed faces. + if(totalExposedFaces == 0) totalExposedFaces++; + + Color color; + color.setColor(totalRed / totalExposedFaces, totalGreen / totalExposedFaces, totalBlue / totalExposedFaces, 255); + pVolDst->setVoxel(dstPos, color); + } + } + } + } + } + } +} + +#endif //CUBIQUITY_COLOUREDCUBICSURFACEEXTRACTIONTASK_H_ diff --git a/ThirdParty/CubiquityC/Src/ConcurrentQueue.h b/ThirdParty/CubiquityC/Src/ConcurrentQueue.h new file mode 100644 index 0000000..3c44c22 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/ConcurrentQueue.h @@ -0,0 +1,73 @@ +// Based on http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html +// +// Note from the comments on licensing: "Yes, you can just copy the code presented here and use +// it for whatever you like. There won't be any licensing issues. I'm glad you find it helpful." + +#ifndef CUBIQUITY_CONCURRENTQUEUE_H +#define CUBIQUITY_CONCURRENTQUEUE_H + +#include +#include + +namespace Cubiquity +{ + // FIXME: THIS QUEUE IS CURRENTLY NOT THREAD SAFE DESPITE IT'S NAME. THE THREADING CODE WAS BASED ON BOOST AND IS COMMENTED OUT + // PENDING A STD C++ VERSION. THE STD FUNCTIONS/TYPES DO NOT HAVE A ONE-TO-ONE CORRESPONDANCE TO THE BOOST FUNCTIONS/TYPES SO + // I WANT TO TAKE SOME CARE OVER THIS. + template + class concurrent_queue + { + private: + std::priority_queue, Compare> the_queue; + //mutable boost::mutex the_mutex; + //boost::condition_variable the_condition_variable; + public: + void push(Data const& data) + { + //boost::mutex::scoped_lock lock(the_mutex); + the_queue.push(data); + //lock.unlock(); + //the_condition_variable.notify_one(); + } + + bool empty() const + { + //boost::mutex::scoped_lock lock(the_mutex); + return the_queue.empty(); + } + + uint32_t size() const + { + //boost::mutex::scoped_lock lock(the_mutex); + return the_queue.size(); + } + + bool try_pop(Data& popped_value) + { + //boost::mutex::scoped_lock lock(the_mutex); + if(the_queue.empty()) + { + return false; + } + + popped_value=the_queue.top(); + the_queue.pop(); + return true; + } + + void wait_and_pop(Data& popped_value) + { + //boost::mutex::scoped_lock lock(the_mutex); + //while(the_queue.empty()) + //{ + // the_condition_variable.wait(lock); + //} + + popped_value=the_queue.top(); + the_queue.pop(); + } + + }; +} + +#endif //CUBIQUITY_CONCURRENTQUEUE_H diff --git a/ThirdParty/CubiquityC/Src/Cubiquity.h b/ThirdParty/CubiquityC/Src/Cubiquity.h new file mode 100644 index 0000000..513bd05 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Cubiquity.h @@ -0,0 +1,38 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_MAIN_HEADER_H_ +#define CUBIQUITY_MAIN_HEADER_H_ + +#include "Color.h" +#include "CubiquityForwardDeclarations.h" +#include "Region.h" +#include "Vector.h" + +namespace Cubiquity +{ + +} + +#endif diff --git a/ThirdParty/CubiquityC/Src/CubiquityC.cpp b/ThirdParty/CubiquityC/Src/CubiquityC.cpp new file mode 100644 index 0000000..ee45acc --- /dev/null +++ b/ThirdParty/CubiquityC/Src/CubiquityC.cpp @@ -0,0 +1,1050 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +// CubiquityC.cpp : Defines the exported functions for the DLL application. +// + +#include "CubiquityC.h" + +#include "Brush.h" +#include "ColoredCubesVolume.h" +#include "Logging.h" +#include "OctreeNode.h" +#include "Raycasting.h" +#include "TerrainVolume.h" +#include "TerrainVolumeEditor.h" +#include "TerrainVolumeGenerator.h" + +#if defined (_MSC_VER) || defined(__APPLE__) + #include //For std::future_error, but causes chrono-related compile errors on Linux/GCC. +#endif +#include +#include +#include + +using namespace std; + +// In principle we try to use semantic versioning (http://semver.org/), though in practice it's more complex and we +// the addition of a build number. The reason is that we want to keep the Cubiquity for Unity3D/Unreal version numbers +// matching the main Cubiquity ones. For example, if we release version 1.0.0 of Cubiquity for Unity3D and then we want +// to release a simple bugfix then users expect this to have version 1.0.1. However, implementing the bugfix may require +// changes to the native library interface, which would in theory require a minor version increase. For users of Cubiquity +// for Unity the C API is some implementation detail which is not important, but for direct users of Cubiquity it is +// very important. +// +// We therefore add the build number, which can be updated any time for any reason. I *think* it should be reset when the +// patch number is incremented. It's really for our internal use with Unity3D/Unreal so probably we tell C/C++ users not +// to use it. +// +// Longer term we can hope the native code API stabilizes, and we can just leave the build number at zero or something. +// I still think the Unity/Unreal wrapper version numbers should follow the Cubiquity ones, and this will be less +// disruptive once the Cubiquity ones are more settled. +const uint32_t CuMajorVersion = 1; +const uint32_t CuMinorVersion = 3; +const uint32_t CuPatchVersion = 0; +const uint32_t CuBuildVersion = 0; + +char gLastErrorMessage[4096]; + +#define CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(exception, errorCode) \ +catch (const exception& ex) \ +{ \ + POLYVOX_LOG_ERROR("Caught \'" #exception "\' at C interface. Message reads: \"", ex.what(), "\""); \ + strcpy(gLastErrorMessage, ex.what()); \ + return errorCode; \ +} + +#define OPEN_C_INTERFACE \ + try \ + { + +#define CLOSE_C_INTERFACE \ + return CU_OK; \ + } \ + /* Note - Exceptions are ordered from most to least specific */ \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(DatabaseError, CU_DATABASE_ERROR) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(CompressionError, CU_COMPRESSION_ERROR) \ + \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(ios_base::failure, CU_IOS_BASE_FAILURE) \ + \ + /*CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_array_new_length, CU_BAD_ARRAY_NEW_LENGTH) *Causing compile errors on Linux/GCC* */ \ + \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(underflow_error, CU_UNDERFLOW_ERROR) \ + /*CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(system_error, CU_SYSTEM_ERROR) *Causing compile errors on Linux/GCC* */ \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(range_error, CU_RANGE_ERROR) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(overflow_error, CU_OVERFLOW_ERROR) \ + \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(out_of_range, CU_OUT_OF_RANGE) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(length_error, CU_LENGTH_ERROR) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(invalid_argument, CU_INVALID_ARGUMENT) \ + /*CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(future_error, CU_FUTURE_ERROR) *Requires header (problematic on Linux/GCC)* */ \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(domain_error, CU_DOMAIN_ERROR) \ + \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(runtime_error, CU_RUNTIME_ERROR) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(logic_error, CU_LOGIC_ERROR) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_weak_ptr, CU_BAD_WEAK_PTR) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_typeid, CU_BAD_TYPEID) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_function_call, CU_BAD_FUNCTION_CALL) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_exception, CU_BAD_EXCEPTION) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_cast, CU_BAD_CAST) \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(bad_alloc, CU_BAD_ALLOC) \ + \ + CATCH_EXCEPTION_AND_MAP_TO_ERROR_CODE(exception, CU_EXCEPTION) \ + \ + catch (...) \ + { \ + POLYVOX_LOG_ERROR("Caught unknown exception at C interface."); \ + strcpy(gLastErrorMessage, "No error message due to unknown exception type."); \ + return CU_UNKNOWN_ERROR; \ + } \ + +using namespace Cubiquity; + +const int MaxNoOfVolumes = 256; +const int TotalHandleBits = 32; +const int VolumeHandleBits = 8; +const int MaxVolumeHandle = (0x01 << VolumeHandleBits) - 1; + +const int NodeHandleBits = 16; // Set this properly later. +const int NodeHandleMask = (0x01 << NodeHandleBits) - 1; +const int MaxNodeHandle = (0x01 << NodeHandleBits) - 1; + +void* gVolumes[MaxNoOfVolumes]; + +// This class (via it's single global instance) allows code to be executed when the library is loaded and unloaded. +// I do have some concerns about how robust this is - in particular see here: http://stackoverflow.com/a/1229542 +class EntryAndExitPoints +{ +public: + EntryAndExitPoints() + :mFileLogger() + { + PolyVox::setLoggerInstance(&mFileLogger); + + // HACK - Should have a seperate init function for this? + for (int ct = 0; ct < MaxNoOfVolumes; ct++) + { + gVolumes[ct] = 0; + } + } + + ~EntryAndExitPoints() + { + PolyVox::setLoggerInstance(0); + } + +public: + FileLogger mFileLogger; +}; + +// The single global instance of the above class. +EntryAndExitPoints gEntryAndExitPoints; + +void* getVolumeFromIndex(uint32_t volumeIndex) +{ + void* volume = gVolumes[volumeIndex]; + POLYVOX_THROW_IF(volume == 0, std::runtime_error, "Handle represents a null volume"); + return volume; +} + +ColoredCubesVolume* getColoredCubesVolumeFromHandle(uint32_t volumeIndex) +{ + ColoredCubesVolume* volume = reinterpret_cast(getVolumeFromIndex(volumeIndex)); + return volume; +} + +TerrainVolume* getTerrainVolumeFromHandle(uint32_t volumeIndex) +{ + TerrainVolume* volume = reinterpret_cast(getVolumeFromIndex(volumeIndex)); + return volume; +} + +uint32_t encodeHandle(uint32_t volumeType, uint32_t volumeIndex, uint32_t nodeIndex) +{ + uint32_t handle = volumeType << (TotalHandleBits - 1); + handle |= (volumeIndex << NodeHandleBits); + handle |= nodeIndex; + return handle; +} + +void decodeHandle(uint32_t handle, uint32_t* volumeType, uint32_t* volumeIndex, uint32_t* nodeIndex) +{ + *volumeType = handle >> (TotalHandleBits - 1); + *volumeIndex = (handle >> NodeHandleBits) & 0xFF; + *nodeIndex = handle & NodeHandleMask; +} + +void* getNode(uint32_t volumeType, uint32_t volumeIndex, uint32_t nodeIndex) +{ + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + OctreeNode* node = volume->getOctree()->getNodeFromIndex(nodeIndex); + return node; + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + OctreeNode* node = volume->getOctree()->getNodeFromIndex(nodeIndex); + return node; + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Version functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuGetVersionNumber(uint32_t* majorVersion, uint32_t* minorVersion, uint32_t* patchVersion, uint32_t* buildVersion) +{ + OPEN_C_INTERFACE + + *majorVersion = CuMajorVersion; + *minorVersion = CuMinorVersion; + *patchVersion = CuPatchVersion; + *buildVersion = CuBuildVersion; + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Logging functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API const char* cuGetLogFilePath(void) +{ + // Use of buffer is a bit of a hack! But otherwise the string doesn't come through. To be investigated. + static char buffer[1024]; + strcpy(buffer, gEntryAndExitPoints.mFileLogger.getLogFilePath().c_str()); + return buffer; +} + +#define ERROR_CODE_TO_STRING(errorCode) case errorCode: strcpy(buffer, #errorCode); break; + +//////////////////////////////////////////////////////////////////////////////// +// Logging functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API const char* cuGetErrorCodeAsString(int32_t errorCode) +{ + static char buffer[1024]; // Can't return a pointer to a local variableso we make it static. + + switch (errorCode) + { + ERROR_CODE_TO_STRING(CU_OK) + + ERROR_CODE_TO_STRING(CU_EXCEPTION) + ERROR_CODE_TO_STRING(CU_BAD_ALLOC) + ERROR_CODE_TO_STRING(CU_BAD_CAST) + ERROR_CODE_TO_STRING(CU_BAD_EXCEPTION) + ERROR_CODE_TO_STRING(CU_BAD_FUNCTION_CALL) + ERROR_CODE_TO_STRING(CU_BAD_TYPEID) + ERROR_CODE_TO_STRING(CU_BAD_WEAK_PTR) + ERROR_CODE_TO_STRING(CU_LOGIC_ERROR) + ERROR_CODE_TO_STRING(CU_RUNTIME_ERROR) + + ERROR_CODE_TO_STRING(CU_DOMAIN_ERROR) + ERROR_CODE_TO_STRING(CU_FUTURE_ERROR) + ERROR_CODE_TO_STRING(CU_INVALID_ARGUMENT) + ERROR_CODE_TO_STRING(CU_LENGTH_ERROR) + ERROR_CODE_TO_STRING(CU_OUT_OF_RANGE) + + ERROR_CODE_TO_STRING(CU_OVERFLOW_ERROR) + ERROR_CODE_TO_STRING(CU_RANGE_ERROR) + ERROR_CODE_TO_STRING(CU_SYSTEM_ERROR) + ERROR_CODE_TO_STRING(CU_UNDERFLOW_ERROR) + + ERROR_CODE_TO_STRING(CU_BAD_ARRAY_NEW_LENGTH) + + ERROR_CODE_TO_STRING(CU_IOS_BASE_FAILURE) + + ERROR_CODE_TO_STRING(CU_DATABASE_ERROR) + ERROR_CODE_TO_STRING(CU_COMPRESSION_ERROR) + + ERROR_CODE_TO_STRING(CU_UNKNOWN_ERROR) + + default: + strcpy(buffer, "Unrecognised error code"); + break; + } + + return buffer; +} + +CUBIQUITYC_API const char* cuGetLastErrorMessage(void) +{ + return gLastErrorMessage; +} + +//////////////////////////////////////////////////////////////////////////////// +// Color functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API uint8_t cuGetRed(CuColor color) +{ + BitField bits(color.data); + return static_cast(bits.getBits(Color::RedMSB, Color::RedLSB) * Color::RedScaleFactor); +} + +CUBIQUITYC_API uint8_t cuGetGreen(CuColor color) +{ + BitField bits(color.data); + return static_cast(bits.getBits(Color::GreenMSB, Color::GreenLSB) * Color::GreenScaleFactor); +} + +CUBIQUITYC_API uint8_t cuGetBlue(CuColor color) +{ + BitField bits(color.data); + return static_cast(bits.getBits(Color::BlueMSB, Color::BlueLSB) * Color::BlueScaleFactor); +} + +CUBIQUITYC_API uint8_t cuGetAlpha(CuColor color) +{ + BitField bits(color.data); + return static_cast(bits.getBits(Color::AlphaMSB, Color::AlphaLSB) * Color::AlphaScaleFactor); +} + +CUBIQUITYC_API void cuGetAllComponents(CuColor color, uint8_t* red, uint8_t* green, uint8_t* blue, uint8_t* alpha) +{ + BitField bits(color.data); + *red = static_cast(bits.getBits(Color::RedMSB, Color::RedLSB) * Color::RedScaleFactor); + *green = static_cast(bits.getBits(Color::GreenMSB, Color::GreenLSB) * Color::GreenScaleFactor); + *blue = static_cast(bits.getBits(Color::BlueMSB, Color::BlueLSB) * Color::BlueScaleFactor); + *alpha = static_cast(bits.getBits(Color::AlphaMSB, Color::AlphaLSB) * Color::AlphaScaleFactor); +} + +CUBIQUITYC_API CuColor cuMakeColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) +{ + BitField bits; + bits.setBits(Color::RedMSB, Color::RedLSB, red / Color::RedScaleFactor); + bits.setBits(Color::GreenMSB, Color::GreenLSB, green / Color::GreenScaleFactor); + bits.setBits(Color::BlueMSB, Color::BlueLSB, blue / Color::BlueScaleFactor); + bits.setBits(Color::AlphaMSB, Color::AlphaLSB, alpha / Color::AlphaScaleFactor); + + CuColor color; + color.data = bits.allBits(); + return color; +} + +//////////////////////////////////////////////////////////////////////////////// +// Volume functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuNewEmptyColoredCubesVolume(int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ, const char* pathToNewVoxelDatabase, uint32_t baseNodeSize, uint32_t* result) +{ + OPEN_C_INTERFACE + + ColoredCubesVolume* volume = new ColoredCubesVolume(Region(lowerX, lowerY, lowerZ, upperX, upperY, upperZ), pathToNewVoxelDatabase, baseNodeSize); + volume->markAsModified(volume->getEnclosingRegion()); + + // Replace an existing entry if it has been deleted. + bool foundEmptySlot = false; + uint32_t ct = 0; + for (; ct < MaxNoOfVolumes; ct++) + { + if(gVolumes[ct] == 0) + { + gVolumes[ct] = volume; + foundEmptySlot = true; + break; + } + } + + POLYVOX_THROW_IF(!foundEmptySlot, std::invalid_argument, "Cannot create new volume as there is a limit of " + MaxNoOfVolumes); + + POLYVOX_LOG_DEBUG("Created new colored cubes volume in slot ", ct); + + // Build the handle + *result = encodeHandle(CU_COLORED_CUBES, ct, 0); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuNewColoredCubesVolumeFromVDB(const char* pathToExistingVoxelDatabase, uint32_t writePermissions, uint32_t baseNodeSize, uint32_t* result) +{ + OPEN_C_INTERFACE + + // Fixme - Find out how to pass this write permissions enum properly. + WritePermission cubiquityWritePermissions = (writePermissions == CU_READONLY) ? WritePermissions::ReadOnly : WritePermissions::ReadWrite; + ColoredCubesVolume* volume = new ColoredCubesVolume(pathToExistingVoxelDatabase, cubiquityWritePermissions, baseNodeSize); + volume->markAsModified(volume->getEnclosingRegion()); + + // Replace an existing entry if it has been deleted. + bool foundEmptySlot = false; + uint32_t ct = 0; + for (; ct < MaxNoOfVolumes; ct++) + { + if(gVolumes[ct] == 0) + { + gVolumes[ct] = volume; + foundEmptySlot = true; + break; + } + } + + POLYVOX_THROW_IF(!foundEmptySlot, std::invalid_argument, "Cannot create new volume as there is a limit of " + MaxNoOfVolumes); + + POLYVOX_LOG_DEBUG("Created new colored cubes volume in slot ", ct); + + // Build the handle + *result = encodeHandle(CU_COLORED_CUBES, ct, 0); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuUpdateVolume(uint32_t volumeHandle, float eyePosX, float eyePosY, float eyePosZ, float lodThreshold, uint32_t* isUpToDate) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + *isUpToDate = volume->update(Vector3F(eyePosX, eyePosY, eyePosZ), lodThreshold); + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + *isUpToDate = volume->update(Vector3F(eyePosX, eyePosY, eyePosZ), lodThreshold); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuDeleteVolume(uint32_t volumeHandle) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + POLYVOX_LOG_DEBUG("Deleting volume with index ", volumeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + delete volume; + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + delete volume; + } + + // Set the slot to zero so that it can be reused. + gVolumes[volumeIndex] = 0; + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuGetEnclosingRegion(uint32_t volumeHandle, int32_t* lowerX, int32_t* lowerY, int32_t* lowerZ, int32_t* upperX, int32_t* upperY, int32_t* upperZ) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* coloredCubesVolume = getColoredCubesVolumeFromHandle(volumeIndex); + const Region& region = coloredCubesVolume->getEnclosingRegion(); + + *lowerX = region.getLowerCorner().getX(); + *lowerY = region.getLowerCorner().getY(); + *lowerZ = region.getLowerCorner().getZ(); + *upperX = region.getUpperCorner().getX(); + *upperY = region.getUpperCorner().getY(); + *upperZ = region.getUpperCorner().getZ(); + } + else + { + TerrainVolume* terrainVolume = getTerrainVolumeFromHandle(volumeIndex); + const Region& region = terrainVolume->getEnclosingRegion(); + + *lowerX = region.getLowerCorner().getX(); + *lowerY = region.getLowerCorner().getY(); + *lowerZ = region.getLowerCorner().getZ(); + *upperX = region.getUpperCorner().getX(); + *upperY = region.getUpperCorner().getY(); + *upperZ = region.getUpperCorner().getZ(); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuGetVoxel(uint32_t volumeHandle, int32_t x, int32_t y, int32_t z, void* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + Color temp = volume->getVoxel(x, y, z); + CuColor* ptr = (CuColor*)&temp; + CuColor* resultAsColor = (CuColor*)result; + *resultAsColor = *ptr; + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + MaterialSet material = volume->getVoxel(x, y, z); + CuMaterialSet* resultAsMaterialSet = (CuMaterialSet*)result; + resultAsMaterialSet->data = material.mWeights.allBits(); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuSetVoxel(uint32_t volumeHandle, int32_t x, int32_t y, int32_t z, void* value) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + Color* pColor = (Color*)value; + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + volume->setVoxel(x, y, z, *pColor, true); + } + else + { + MaterialSet* pMat = (MaterialSet*)value; + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + volume->setVoxel(x, y, z, *pMat, true); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuAcceptOverrideChunks(uint32_t volumeHandle) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + volume->acceptOverrideChunks(); + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + volume->acceptOverrideChunks(); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuDiscardOverrideChunks(uint32_t volumeHandle) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + volume->discardOverrideChunks(); + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + volume->discardOverrideChunks(); + } + + CLOSE_C_INTERFACE +} + +//-------------------------------------------------------------------------------- + +CUBIQUITYC_API int32_t cuNewEmptyTerrainVolume(int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ, const char* pathToNewVoxelDatabase, uint32_t baseNodeSize, uint32_t* result) +{ + OPEN_C_INTERFACE + + TerrainVolume* volume = new TerrainVolume(Region(lowerX, lowerY, lowerZ, upperX, upperY, upperZ), pathToNewVoxelDatabase, baseNodeSize); + volume->markAsModified(volume->getEnclosingRegion()); + + // Replace an existing entry if it has been deleted. + bool foundEmptySlot = false; + uint32_t ct = 0; + for (; ct < MaxNoOfVolumes; ct++) + { + if(gVolumes[ct] == 0) + { + gVolumes[ct] = volume; + foundEmptySlot = true; + break; + } + } + + POLYVOX_THROW_IF(!foundEmptySlot, std::invalid_argument, "Cannot create new volume as there is a limit of " + MaxNoOfVolumes); + + POLYVOX_LOG_DEBUG("Created new smooth volume in slot ", ct); + + // Build the handle + *result = encodeHandle(CU_TERRAIN, ct, 0); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuNewTerrainVolumeFromVDB(const char* pathToExistingVoxelDatabase, uint32_t writePermissions, uint32_t baseNodeSize, uint32_t* result) +{ + OPEN_C_INTERFACE + + // Fixme - Find out how to pass this write permissions enum properly. + WritePermission cubiquityWritePermissions = (writePermissions == CU_READONLY) ? WritePermissions::ReadOnly : WritePermissions::ReadWrite; + TerrainVolume* volume = new TerrainVolume(pathToExistingVoxelDatabase, cubiquityWritePermissions, baseNodeSize); + volume->markAsModified(volume->getEnclosingRegion()); + + // Replace an existing entry if it has been deleted. + bool foundEmptySlot = false; + uint32_t ct = 0; + for (; ct < MaxNoOfVolumes; ct++) + { + if(gVolumes[ct] == 0) + { + gVolumes[ct] = volume; + foundEmptySlot = true; + break; + } + } + + POLYVOX_THROW_IF(!foundEmptySlot, std::invalid_argument, "Cannot create new volume as there is a limit of " + MaxNoOfVolumes); + + POLYVOX_LOG_DEBUG("Created new smooth volume in slot ", ct); + + // Build the handle + *result = encodeHandle(CU_TERRAIN, ct, 0); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuGetVolumeType(uint32_t volumeHandle, uint32_t* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeIndex, nodeIndex; + decodeHandle(volumeHandle, result, &volumeIndex, &nodeIndex); + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Octree functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuHasRootOctreeNode(uint32_t volumeHandle, uint32_t* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + OctreeNode* node = volume->getRootOctreeNode(); + *result = node ? 1 : 0; + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + OctreeNode* node = volume->getRootOctreeNode(); + *result = node ? 1 : 0; + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuGetRootOctreeNode(uint32_t volumeHandle, uint32_t* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + OctreeNode* node = volume->getRootOctreeNode(); + + if (!node) + { + POLYVOX_THROW(PolyVox::invalid_operation, "No root node exists! Please check this with cuHasRootOctreeNode() first"); + } + + uint32_t nodeIndex = node->mSelf; + + *result = encodeHandle(CU_COLORED_CUBES, volumeIndex, nodeIndex); + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + OctreeNode* node = volume->getRootOctreeNode(); + + if (!node) + { + POLYVOX_THROW(PolyVox::invalid_operation, "No root node exists! Please check this with cuHasRootOctreeNode() first"); + } + + uint32_t nodeIndex = node->mSelf; + + *result = encodeHandle(CU_TERRAIN, volumeIndex, nodeIndex); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuGetOctreeNode(uint32_t nodeHandle, CuOctreeNode* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(nodeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + OctreeNode* node = reinterpret_cast*>(getNode(volumeType, volumeIndex, nodeIndex)); + const Vector3I& lowerCorner = node->mRegion.getLowerCorner(); + result->posX = lowerCorner.getX(); + result->posY = lowerCorner.getY(); + result->posZ = lowerCorner.getZ(); + + result->structureLastChanged = node->mStructureLastChanged; + result->propertiesLastChanged = node->mPropertiesLastChanged; + result->meshLastChanged = node->mMeshLastChanged; + result->nodeOrChildrenLastChanged = node->mNodeOrChildrenLastChanged; + + for (int childZ = 0; childZ < 2; childZ++) + { + for (int childY = 0; childY < 2; childY++) + { + for (int childX = 0; childX < 2; childX++) + { + OctreeNode* child = node->getChildNode(childX, childY, childZ); + + if (child && child->isActive()) + { + uint32_t nodeIndex = child->mSelf; + + uint32_t volumeHandle; + uint32_t dummy; + decodeHandle(nodeHandle, &volumeType, &volumeHandle, &dummy); + + result->childHandles[childX][childY][childZ] = encodeHandle(CU_COLORED_CUBES, volumeHandle, nodeIndex); + } + else + { + result->childHandles[childX][childY][childZ] = 0xFFFFFFFF; // Should be CU_INVALID_HANLDE + } + } + } + } + + result->hasMesh = (node->getMesh() != 0) && (node->getMesh()->getNoOfVertices() > 0) && (node->getMesh()->getNoOfIndices() > 0) ? 1 : 0; + result->height = node->mHeight; + result->renderThisNode = node->renderThisNode(); + } + else + { + OctreeNode* node = reinterpret_cast*>(getNode(volumeType, volumeIndex, nodeIndex)); + const Vector3I& lowerCorner = node->mRegion.getLowerCorner(); + result->posX = lowerCorner.getX(); + result->posY = lowerCorner.getY(); + result->posZ = lowerCorner.getZ(); + + result->structureLastChanged = node->mStructureLastChanged; + result->propertiesLastChanged = node->mPropertiesLastChanged; + result->meshLastChanged = node->mMeshLastChanged; + result->nodeOrChildrenLastChanged = node->mNodeOrChildrenLastChanged; + + for (int childZ = 0; childZ < 2; childZ++) + { + for (int childY = 0; childY < 2; childY++) + { + for (int childX = 0; childX < 2; childX++) + { + OctreeNode* child = node->getChildNode(childX, childY, childZ); + + if (child && child->isActive()) + { + uint32_t nodeIndex = child->mSelf; + + uint32_t volumeHandle; + uint32_t dummy; + decodeHandle(nodeHandle, &volumeType, &volumeHandle, &dummy); + + result->childHandles[childX][childY][childZ] = encodeHandle(CU_TERRAIN, volumeHandle, nodeIndex); + } + else + { + result->childHandles[childX][childY][childZ] = 0xFFFFFFFF; // Should be CU_INVALID_HANLDE + } + } + } + } + + result->hasMesh = (node->getMesh() != 0) && (node->getMesh()->getNoOfVertices() > 0) && (node->getMesh()->getNoOfIndices() > 0) ? 1 : 0; + result->height = node->mHeight; + result->renderThisNode = node->renderThisNode(); + } + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Mesh functions +//////////////////////////////////////////////////////////////////////////////// + +// This isn't really a mesh function... more of an Octree one? +CUBIQUITYC_API int32_t cuSetLodRange(uint32_t volumeHandle, int32_t minimumLOD, int32_t maximumLOD) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + volume->getOctree()->setLodRange(minimumLOD, maximumLOD); + } + else + { + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + volume->getOctree()->setLodRange(minimumLOD, maximumLOD); + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuGetMesh(uint32_t nodeHandle, uint16_t* noOfVertices, void** vertices, uint32_t* noOfIndices, uint16_t** indices) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(nodeHandle, &volumeType, &volumeIndex, &nodeIndex); + + if (volumeType == CU_COLORED_CUBES) + { + // Get the node + OctreeNode* node = reinterpret_cast*>(getNode(volumeType, volumeIndex, nodeIndex)); + + // Get the mesh + const ::PolyVox::Mesh< typename VoxelTraits::VertexType, uint16_t >* polyVoxMesh = node->getMesh(); + + // Get no of vertices + *noOfVertices = polyVoxMesh->getNoOfVertices(); + + // Get the vertices + const VoxelTraits::VertexType* vertexPointer = polyVoxMesh->getRawVertexData(); + const void* constVoidPointer = reinterpret_cast(vertexPointer); + void* voidPointer = const_cast(constVoidPointer); + *vertices = voidPointer; + + // Get no of indices + *noOfIndices = polyVoxMesh->getNoOfIndices(); + + // Get the indices + const uint16_t* constUInt16Pointer = polyVoxMesh->getRawIndexData(); + uint16_t* uintPointer = const_cast(constUInt16Pointer); + *indices = uintPointer; + } + else + { + // Get the node + OctreeNode* node = reinterpret_cast*>(getNode(volumeType, volumeIndex, nodeIndex)); + + // Get the mesh + const ::PolyVox::Mesh< typename VoxelTraits::VertexType, uint16_t >* polyVoxMesh = node->getMesh(); + + // Get no of vertices + *noOfVertices = polyVoxMesh->getNoOfVertices(); + + // Get the vertices + const VoxelTraits::VertexType* vertexPointer = polyVoxMesh->getRawVertexData(); + const void* constVoidPointer = reinterpret_cast(vertexPointer); + void* voidPointer = const_cast(constVoidPointer); + *vertices = voidPointer; + + // Get no of indices + *noOfIndices = polyVoxMesh->getNoOfIndices(); + + // Get the indices + const uint16_t* constUIntPointer = polyVoxMesh->getRawIndexData(); + uint16_t* uintPointer = const_cast(constUIntPointer); + *indices = uintPointer; + } + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Clock functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuGetCurrentTime(uint32_t* result) +{ + OPEN_C_INTERFACE + + *result = Clock::getTimestamp(); + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Raycasting functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuPickFirstSolidVoxel(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, int32_t* resultX, int32_t* resultY, int32_t* resultZ, uint32_t* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + + if(pickFirstSolidVoxel(volume, rayStartX, rayStartY, rayStartZ, rayDirX, rayDirY, rayDirZ, resultX, resultY, resultZ)) + { + *result = 1; + } + else + { + *result = 0; + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuPickLastEmptyVoxel(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, int32_t* resultX, int32_t* resultY, int32_t* resultZ, uint32_t* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + ColoredCubesVolume* volume = getColoredCubesVolumeFromHandle(volumeIndex); + + if(pickLastEmptyVoxel(volume, rayStartX, rayStartY, rayStartZ, rayDirX, rayDirY, rayDirZ, resultX, resultY, resultZ)) + { + *result = 1; + } + else + { + *result = 0; + } + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuPickTerrainSurface(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, float* resultX, float* resultY, float* resultZ, uint32_t* result) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + + if(pickTerrainSurface(volume, rayStartX, rayStartY, rayStartZ, rayDirX, rayDirY, rayDirZ, resultX, resultY, resultZ)) + { + *result = 1; + } + else + { + *result = 0; + } + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Editing functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuSculptTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + + sculptTerrainVolume(volume, Vector3F(brushX, brushY, brushZ), Brush(brushInnerRadius, brushOuterRadius, opacity)); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuBlurTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + + blurTerrainVolume(volume, Vector3F(brushX, brushY, brushZ), Brush(brushInnerRadius, brushOuterRadius, opacity)); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuBlurTerrainVolumeRegion(uint32_t volumeHandle, int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + + blurTerrainVolume(volume, Region(lowerX, lowerY, lowerZ, upperX, upperY, upperZ)); + + CLOSE_C_INTERFACE +} + +CUBIQUITYC_API int32_t cuPaintTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity, uint32_t materialIndex) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + + paintTerrainVolume(volume, Vector3F(brushX, brushY, brushZ), Brush(brushInnerRadius, brushOuterRadius, opacity), materialIndex); + + CLOSE_C_INTERFACE +} + +//////////////////////////////////////////////////////////////////////////////// +// Volume generation functions +//////////////////////////////////////////////////////////////////////////////// +CUBIQUITYC_API int32_t cuGenerateFloor(uint32_t volumeHandle, int32_t lowerLayerHeight, uint32_t lowerLayerMaterial, int32_t upperLayerHeight, uint32_t upperLayerMaterial) +{ + OPEN_C_INTERFACE + + uint32_t volumeType, volumeIndex, nodeIndex; + decodeHandle(volumeHandle, &volumeType, &volumeIndex, &nodeIndex); + TerrainVolume* volume = getTerrainVolumeFromHandle(volumeIndex); + + generateFloor(volume, lowerLayerHeight, lowerLayerMaterial, upperLayerHeight, upperLayerMaterial); + + CLOSE_C_INTERFACE +} diff --git a/ThirdParty/CubiquityC/Src/CubiquityC.h b/ThirdParty/CubiquityC/Src/CubiquityC.h new file mode 100644 index 0000000..365916c --- /dev/null +++ b/ThirdParty/CubiquityC/Src/CubiquityC.h @@ -0,0 +1,223 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 CUBIQUITY_C_INTERFACE_H_ +#define CUBIQUITY_C_INTERFACE_H_ + +#include //C99 fixed size data types. + +// The following ifdef block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the CUBIQUITYC_EXPORTS +// symbol defined on the command line. This symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// CUBIQUITYC_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +#if defined _WIN32 || defined __CYGWIN__ + #ifdef CUBIQUITYC_EXPORTS + #define CUBIQUITYC_API __declspec(dllexport) + #else + #define CUBIQUITYC_API __declspec(dllimport) + #endif +#else + #define CUBIQUITYC_API __attribute__ ((visibility("default"))) +#endif + +extern "C" +{ + const int32_t CU_OK = 0; + + // Standard exceptions, based on list here: http://www.cplusplus.com/reference/exception/exception/ + const int32_t CU_EXCEPTION = 10; + const int32_t CU_BAD_ALLOC = 20; + const int32_t CU_BAD_CAST = 30; + const int32_t CU_BAD_EXCEPTION = 40; + const int32_t CU_BAD_FUNCTION_CALL = 50; + const int32_t CU_BAD_TYPEID = 60; + const int32_t CU_BAD_WEAK_PTR = 70; + //const int32_t ios_base::failure // Included below + const int32_t CU_LOGIC_ERROR = 80; + const int32_t CU_RUNTIME_ERROR = 90; + + const int32_t CU_DOMAIN_ERROR = 100; + const int32_t CU_FUTURE_ERROR = 110; + const int32_t CU_INVALID_ARGUMENT = 120; + const int32_t CU_LENGTH_ERROR = 130; + const int32_t CU_OUT_OF_RANGE = 140; + + const int32_t CU_OVERFLOW_ERROR = 150; + const int32_t CU_RANGE_ERROR = 160; + const int32_t CU_SYSTEM_ERROR = 170; + const int32_t CU_UNDERFLOW_ERROR = 180; + + const int32_t CU_BAD_ARRAY_NEW_LENGTH = 190; + + const int32_t CU_IOS_BASE_FAILURE = 200; + + // Non-standard exceptions + const int32_t CU_DATABASE_ERROR = 210; + const int32_t CU_COMPRESSION_ERROR = 220; + + // Unknown error (caught by ...) + const int32_t CU_UNKNOWN_ERROR = 1000; + + // C version of Cubiquity::WritePermissions + // Fixme - should this be a C enum? + const uint32_t CU_READONLY = 0; + const uint32_t CU_READWRITE = 1; + + // Fixme - should this be a C enum? + // Also, apped '_VOLUME_TYPE'? + const uint32_t CU_COLORED_CUBES = 0; + const uint32_t CU_TERRAIN = 1; + const uint32_t CU_UNKNOWN = 0xFFFFFFFF; + + struct CuColor_s + { + uint32_t data; + }; + typedef struct CuColor_s CuColor; + + struct CuMaterialSet_s + { + uint64_t data; + }; + typedef struct CuMaterialSet_s CuMaterialSet; + + struct CuTerrainVertex_s + { + public: + uint16_t encodedPosX; + uint16_t encodedPosY; + uint16_t encodedPosZ; + uint16_t encodedNormal; + uint8_t material0; + uint8_t material1; + uint8_t material2; + uint8_t material3; + uint8_t material4; + uint8_t material5; + uint8_t material6; + uint8_t material7; + }; + typedef struct CuTerrainVertex_s CuTerrainVertex; + + struct CuColoredCubesVertex_s + { + public: + uint8_t encodedPosX; + uint8_t encodedPosY; + uint8_t encodedPosZ; + uint8_t dummy; + uint32_t data; + }; + typedef struct CuColoredCubesVertex_s CuColoredCubesVertex; + + struct CuOctreeNode_s + { + public: + int32_t posX; + int32_t posY; + int32_t posZ; + + uint32_t structureLastChanged; + uint32_t propertiesLastChanged; + uint32_t meshLastChanged; + uint32_t nodeOrChildrenLastChanged; + + uint32_t childHandles[2][2][2]; + + uint8_t hasMesh; + uint8_t renderThisNode; + uint8_t height; + }; + typedef struct CuOctreeNode_s CuOctreeNode; + + // Version functions + CUBIQUITYC_API int32_t cuGetVersionNumber(uint32_t* majorVersion, uint32_t* minorVersion, uint32_t* patchVersion, uint32_t* buildVersion); + + // Logging functions - Doesn't return error code as it is too simple to fail. + CUBIQUITYC_API const char* cuGetLogFilePath(void); + + // Error handling functions - Don't return error code as they are too simple to fail. + CUBIQUITYC_API const char* cuGetErrorCodeAsString(int32_t errorCode); + CUBIQUITYC_API const char* cuGetLastErrorMessage(void); + + // Color functions - these don't return error codes because they are too simple to fail. + CUBIQUITYC_API uint8_t cuGetRed(CuColor color); + CUBIQUITYC_API uint8_t cuGetGreen(CuColor color); + CUBIQUITYC_API uint8_t cuGetBlue(CuColor color); + CUBIQUITYC_API uint8_t cuGetAlpha(CuColor color); + CUBIQUITYC_API void cuGetAllComponents(CuColor color, uint8_t* red, uint8_t* green, uint8_t* blue, uint8_t* alpha); + + CUBIQUITYC_API CuColor cuMakeColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha); + + // Volume functions + CUBIQUITYC_API int32_t cuNewEmptyColoredCubesVolume(int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ, const char* pathToNewVoxelDatabase, uint32_t baseNodeSize, uint32_t* result); + CUBIQUITYC_API int32_t cuNewColoredCubesVolumeFromVDB(const char* pathToExistingVoxelDatabase, uint32_t writePermissions, uint32_t baseNodeSize, uint32_t* result); + CUBIQUITYC_API int32_t cuUpdateVolume(uint32_t volumeHandle, float eyePosX, float eyePosY, float eyePosZ, float lodThreshold, uint32_t* isUpToDate); + CUBIQUITYC_API int32_t cuDeleteVolume(uint32_t volumeHandle); + + CUBIQUITYC_API int32_t cuGetEnclosingRegion(uint32_t volumeHandle, int32_t* lowerX, int32_t* lowerY, int32_t* lowerZ, int32_t* upperX, int32_t* upperY, int32_t* upperZ); + + CUBIQUITYC_API int32_t cuAcceptOverrideChunks(uint32_t volumeHandle); + CUBIQUITYC_API int32_t cuDiscardOverrideChunks(uint32_t volumeHandle); + + CUBIQUITYC_API int32_t cuNewEmptyTerrainVolume(int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ, const char* pathToNewVoxelDatabase, uint32_t baseNodeSize, uint32_t* result); + CUBIQUITYC_API int32_t cuNewTerrainVolumeFromVDB(const char* pathToExistingVoxelDatabase, uint32_t writePermissions, uint32_t baseNodeSize, uint32_t* result); + + CUBIQUITYC_API int32_t cuGetVolumeType(uint32_t volumeHandle, uint32_t* result); + + // Voxel functions + CUBIQUITYC_API int32_t cuGetVoxel(uint32_t volumeHandle, int32_t x, int32_t y, int32_t z, void* result); + CUBIQUITYC_API int32_t cuSetVoxel(uint32_t volumeHandle, int32_t x, int32_t y, int32_t z, void* value); + + // Octree functions + CUBIQUITYC_API int32_t cuHasRootOctreeNode(uint32_t volumeHandle, uint32_t* result); + CUBIQUITYC_API int32_t cuGetRootOctreeNode(uint32_t volumeHandle, uint32_t* result); + CUBIQUITYC_API int32_t cuGetOctreeNode(uint32_t nodeHandle, CuOctreeNode* result); + + // Mesh functions + CUBIQUITYC_API int32_t cuSetLodRange(uint32_t volumeHandle, int32_t minimumLOD, int32_t maximumLOD); + CUBIQUITYC_API int32_t cuGetMesh(uint32_t nodeHandle, uint16_t* noOfVertices, void** vertices, uint32_t* noOfIndices, uint16_t** indices); + + // Clock functions + CUBIQUITYC_API int32_t cuGetCurrentTime(uint32_t* result); + + // Raycasting functions + CUBIQUITYC_API int32_t cuPickFirstSolidVoxel(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, int32_t* resultX, int32_t* resultY, int32_t* resultZ, uint32_t* result); + CUBIQUITYC_API int32_t cuPickLastEmptyVoxel(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, int32_t* resultX, int32_t* resultY, int32_t* resultZ, uint32_t* result); + + CUBIQUITYC_API int32_t cuPickTerrainSurface(uint32_t volumeHandle, float rayStartX, float rayStartY, float rayStartZ, float rayDirX, float rayDirY, float rayDirZ, float* resultX, float* resultY, float* resultZ, uint32_t* result); + + // Editing functions + CUBIQUITYC_API int32_t cuSculptTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity); + CUBIQUITYC_API int32_t cuBlurTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity); + CUBIQUITYC_API int32_t cuBlurTerrainVolumeRegion(uint32_t volumeHandle, int32_t lowerX, int32_t lowerY, int32_t lowerZ, int32_t upperX, int32_t upperY, int32_t upperZ); + CUBIQUITYC_API int32_t cuPaintTerrainVolume(uint32_t volumeHandle, float brushX, float brushY, float brushZ, float brushInnerRadius, float brushOuterRadius, float opacity, uint32_t materialIndex); + + // Volume generation functions + CUBIQUITYC_API int32_t cuGenerateFloor(uint32_t volumeHandle, int32_t lowerLayerHeight, uint32_t lowerLayerMaterial, int32_t upperLayerHeight, uint32_t upperLayerMaterial); +} + +#endif //CUBIQUITY_C_INTERFACE_H_ diff --git a/ThirdParty/CubiquityC/Src/CubiquityForwardDeclarations.h b/ThirdParty/CubiquityC/Src/CubiquityForwardDeclarations.h new file mode 100644 index 0000000..50900c8 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/CubiquityForwardDeclarations.h @@ -0,0 +1,69 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2016 David Williams and Matthew Williams +* +* 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 __Cubiquity_ForwardDeclarations_H__ +#define __Cubiquity_ForwardDeclarations_H__ + +namespace Cubiquity +{ + class Brush; + class Clock; + + class Color; + + class ColoredCubesIsQuadNeeded; + + class ColoredCubesVolume; + + class ColoredCubicSurfaceExtractionTask; + + class MainThreadTaskProcessor; + + class MaterialSet; + + class MaterialSetMarchingCubesController; + + template + class Octree; + + template + class OctreeNode; + + class SmoothSurfaceExtractionTask; + + class TerrainVolume; + + class TerrainVolumeEditor; + + template + class VoxelDatabase; + + class Task; + class TaskProcessor; + + template + class Volume; +} + +#endif //__Cubiquity_ForwardDeclarations_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/LICENSE-EXCEPTION.txt b/ThirdParty/CubiquityC/Src/Dependancies/LICENSE-EXCEPTION.txt new file mode 100644 index 0000000..ce6394a --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/LICENSE-EXCEPTION.txt @@ -0,0 +1 @@ +This folder contains external dependencies which are not part of Cubiquity and which may be under a different license. In each case a LICENSE.txt file in included with the dependency. All licenses are compatible with the MIT license use by Cubiquity. \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AStarPathfinder.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AStarPathfinder.h new file mode 100644 index 0000000..ef698ae --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AStarPathfinder.h @@ -0,0 +1,188 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_AStarPathfinder_H__ +#define __PolyVox_AStarPathfinder_H__ + +#include "Impl/AStarPathfinderImpl.h" +#include "Impl/PlatformDefinitions.h" + +#include +#include +#include //For runtime_error + +namespace PolyVox +{ + /// This function provides the default method for checking whether a given voxel + /// is valid for the path computed by the AStarPathfinder. + template + bool aStarDefaultVoxelValidator(const VolumeType* volData, const Vector3DInt32& v3dPos); + + /// Provides a configuration for the AStarPathfinder. + //////////////////////////////////////////////////////////////////////////////// + /// This structure stores the AStarPathfinder%s configuration options, because this + /// is simpler than providing a large number of get/set properties within the + /// AStarPathfinder itself. In order to create an instance of this structure you + /// must provide at least a volume, a start and end point, and a list to store + /// the result. All the other option have sensible default values which can + /// optionally be changed for more precise control over the pathfinder's behaviour. + /// + /// \sa AStarPathfinder + //////////////////////////////////////////////////////////////////////////////// + template + struct AStarPathfinderParams + { + public: + AStarPathfinderParams + ( + VolumeType* volData, + const Vector3DInt32& v3dStart, + const Vector3DInt32& v3dEnd, + std::list* listResult, + float fHBias = 1.0, + uint32_t uMaxNoOfNodes = 10000, + Connectivity requiredConnectivity = TwentySixConnected, + std::function funcIsVoxelValidForPath = &aStarDefaultVoxelValidator, + std::function funcProgressCallback = nullptr + ) + :volume(volData) + , start(v3dStart) + , end(v3dEnd) + , result(listResult) + , connectivity(requiredConnectivity) + , hBias(fHBias) + , maxNumberOfNodes(uMaxNoOfNodes) + , isVoxelValidForPath(funcIsVoxelValidForPath) + , progressCallback(funcProgressCallback) + { + } + + /// This is the volume through which the AStarPathfinder must find a path. + VolumeType* volume; + + /// The start point for the pathfinding algorithm. + Vector3DInt32 start; + + /// The end point for the pathfinding algorithm. + Vector3DInt32 end; + + /// The resulting path will be stored as a series of points in + /// this list. Any existing contents will be cleared. + std::list* result; + + /// The AStarPathfinder performs its search by examining the neighbours + /// of each voxel it encounters. This property controls the meaning of + /// neighbour - e.g. whether two voxels must share a face, edge, or corner. + Connectivity connectivity; + + /// For each voxel the pathfinder tracks its distance to the start (known as g()) + /// and estimates its distance to the end (known as h()). Increasing or decreasing + /// h() has an effect on the way the pathfinder behaves. If h() is an underestimate + /// of the true distance then the pathfinder will act more like a greedy search - + /// always finding the shortest path but taking longer to do so. If h() is an over + /// estimate then the pathfinder will behave more like a best-first search - returning + /// a potentially suboptimal path but finding it more quickly. The hBias is multiplied + /// by the estimated h() value to control this behaviour. + float hBias; + + /// Volumes can be pretty huge (millions of voxels) and processing each one of these + /// can take a long time. In A* terminology each voxel is a node, and this property + /// controls the maximum number of nodes that will be considered when finding the path, + /// before giving up and throwing an exception because a path can't be found. + uint32_t maxNumberOfNodes; + + /// This function is called to determine whether the path can pass though a given voxel. The + /// default behaviour is specified by aStarDefaultVoxelValidator(), but users can specify thier + /// own criteria if desired. For example, if you always want a path to follow a surface then + /// you could check to ensure that the voxel above is empty and the voxel below is solid. + /// + /// \sa aStarDefaultVoxelValidator + std::function isVoxelValidForPath; + + /// This function is called by the AStarPathfinder to report on its progress in getting to + /// the goal. The progress is reported by computing the distance from the closest node found + /// so far to the end node, and comparing this with the distance from the start node to the + /// end node. This progress value is guarenteed to never decrease, but it may stop increasing + ///for short periods of time. It may even stop increasing altogether if a path cannot be found. + std::function progressCallback; + }; + + /// The AStarPathfinder compute a path from one point in the volume to another. + //////////////////////////////////////////////////////////////////////////////// + /// A* is a well known pathfinding algorithm commonly used in computer games. It + /// takes as input a pair of points in the world, and works out a path between + /// them which avoids obstacles and adheres to other user defined criteria. The + /// resulting path is usually the shortest possible, but a less optimal path can + /// be exchanged for reduced computation time. + /// + /// For an excellent overview of the A* algorithm please see Amit Patel's Game + /// Programming page here: http://theory.stanford.edu/~amitp/GameProgramming/ + /// Much of this class is based on the principles described in those pages. + /// + /// Usage of this class if very strightforward. You create an instance of it + /// by passing an instance of the AStarPathfinderParams structure to the constructor. + /// The details of the AStarPathfinderParams and the options it provides are described + /// in the documentation for that class. + /// + /// Next you call the execute() function and wait for it to return. If a path is + /// found then this is stored in the list which was set as the 'result' field of + /// the AStarPathfinderParams. If a path cannot be found then an exception of type + /// std::runtime_error is thrown. + /// + /// \sa AStarPathfinderParams + //////////////////////////////////////////////////////////////////////////////// + template + class AStarPathfinder + { + public: + AStarPathfinder(const AStarPathfinderParams& params); + + void execute(); + + private: + void processNeighbour(const Vector3DInt32& neighbourPos, float neighbourGVal); + + float SixConnectedCost(const Vector3DInt32& a, const Vector3DInt32& b); + float EighteenConnectedCost(const Vector3DInt32& a, const Vector3DInt32& b); + float TwentySixConnectedCost(const Vector3DInt32& a, const Vector3DInt32& b); + float computeH(const Vector3DInt32& a, const Vector3DInt32& b); + uint32_t hash(uint32_t a); + + //Node containers + AllNodesContainer allNodes; + OpenNodesContainer openNodes; + ClosedNodesContainer closedNodes; + + //The current node + AllNodesContainer::iterator current; + + float m_fProgress; + + AStarPathfinderParams m_params; + }; +} + +#include "AStarPathfinder.inl" + +#endif //__PolyVox_AStarPathfinder_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AStarPathfinder.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AStarPathfinder.inl new file mode 100644 index 0000000..93ec5e4 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AStarPathfinder.inl @@ -0,0 +1,397 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/ErrorHandling.h" + +namespace PolyVox +{ + //////////////////////////////////////////////////////////////////////////////// + // Useful constants + //////////////////////////////////////////////////////////////////////////////// + const float sqrt_1 = 1.0f; + const float sqrt_2 = 1.4143f; + const float sqrt_3 = 1.7321f; + + const Vector3DInt32 arrayPathfinderFaces[6] = + { + Vector3DInt32(0, 0, -1), + Vector3DInt32(0, 0, +1), + Vector3DInt32(0, -1, 0), + Vector3DInt32(0, +1, 0), + Vector3DInt32(-1, 0, 0), + Vector3DInt32(+1, 0, 0) + }; + + const Vector3DInt32 arrayPathfinderEdges[12] = + { + Vector3DInt32(0, -1, -1), + Vector3DInt32(0, -1, +1), + Vector3DInt32(0, +1, -1), + Vector3DInt32(0, +1, +1), + Vector3DInt32(-1, 0, -1), + Vector3DInt32(-1, 0, +1), + Vector3DInt32(+1, 0, -1), + Vector3DInt32(+1, 0, +1), + Vector3DInt32(-1, -1, 0), + Vector3DInt32(-1, +1, 0), + Vector3DInt32(+1, -1, 0), + Vector3DInt32(+1, +1, 0) + }; + + const Vector3DInt32 arrayPathfinderCorners[8] = + { + Vector3DInt32(-1, -1, -1), + Vector3DInt32(-1, -1, +1), + Vector3DInt32(-1, +1, -1), + Vector3DInt32(-1, +1, +1), + Vector3DInt32(+1, -1, -1), + Vector3DInt32(+1, -1, +1), + Vector3DInt32(+1, +1, -1), + Vector3DInt32(+1, +1, +1) + }; + + //////////////////////////////////////////////////////////////////////////////// + /// Using this function, a voxel is considered valid for the path if it is inside the + /// volume and if its density is below that returned by the voxel's getDensity() function. + /// \return true is the voxel is valid for the path + //////////////////////////////////////////////////////////////////////////////// + template + bool aStarDefaultVoxelValidator(const VolumeType* volData, const Vector3DInt32& v3dPos) + { + //Voxels are considered valid candidates for the path if they are inside the volume... + if (volData->getEnclosingRegion().containsPoint(v3dPos) == false) + { + return false; + } + + return true; + } + + //////////////////////////////////////////////////////////////////////////////// + // AStarPathfinder Class + //////////////////////////////////////////////////////////////////////////////// + template + AStarPathfinder::AStarPathfinder(const AStarPathfinderParams& params) + :m_params(params) + { + } + + template + void AStarPathfinder::execute() + { + //Clear any existing nodes + allNodes.clear(); + openNodes.clear(); + closedNodes.clear(); + + //Clear the result + m_params.result->clear(); + + //Iterators to start and end node. + AllNodesContainer::iterator startNode = allNodes.insert(Node(m_params.start.getX(), m_params.start.getY(), m_params.start.getZ())).first; + AllNodesContainer::iterator endNode = allNodes.insert(Node(m_params.end.getX(), m_params.end.getY(), m_params.end.getZ())).first; + + //Regarding the const_cast - normally you should not modify an object which is in an sdt::set. + //The reason is that objects in a set are stored sorted in a tree so they can be accessed quickly, + //and changing the object directly can break the sorting. However, in our case we have provided a + //custom sort operator for the set which we know only uses the position to sort. Hence we can safely + //modify other properties of the object while it is in the set. + Node* tempStart = const_cast(&(*startNode)); + tempStart->gVal = 0; + tempStart->hVal = computeH(startNode->position, endNode->position); + + Node* tempEnd = const_cast(&(*endNode)); + tempEnd->hVal = 0.0f; + + openNodes.insert(startNode); + + float fDistStartToEnd = (endNode->position - startNode->position).length(); + m_fProgress = 0.0f; + if (m_params.progressCallback) + { + m_params.progressCallback(m_fProgress); + } + + while ((openNodes.empty() == false) && (openNodes.getFirst() != endNode)) + { + //Move the first node from open to closed. + current = openNodes.getFirst(); + openNodes.removeFirst(); + closedNodes.insert(current); + + //Update the user on our progress + if (m_params.progressCallback) + { + const float fMinProgresIncreament = 0.001f; + float fDistCurrentToEnd = (endNode->position - current->position).length(); + float fDistNormalised = fDistCurrentToEnd / fDistStartToEnd; + float fProgress = 1.0f - fDistNormalised; + if (fProgress >= m_fProgress + fMinProgresIncreament) + { + m_fProgress = fProgress; + m_params.progressCallback(m_fProgress); + } + } + + //The distance from one cell to another connected by face, edge, or corner. + const float fFaceCost = sqrt_1; + const float fEdgeCost = sqrt_2; + const float fCornerCost = sqrt_3; + + //Process the neighbours. Note the deliberate lack of 'break' + //statements, larger connectivities include smaller ones. + switch (m_params.connectivity) + { + case TwentySixConnected: + processNeighbour(current->position + arrayPathfinderCorners[0], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[1], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[2], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[3], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[4], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[5], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[6], current->gVal + fCornerCost); + processNeighbour(current->position + arrayPathfinderCorners[7], current->gVal + fCornerCost); + + case EighteenConnected: + processNeighbour(current->position + arrayPathfinderEdges[0], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[1], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[2], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[3], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[4], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[5], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[6], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[7], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[8], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[9], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[10], current->gVal + fEdgeCost); + processNeighbour(current->position + arrayPathfinderEdges[11], current->gVal + fEdgeCost); + + case SixConnected: + processNeighbour(current->position + arrayPathfinderFaces[0], current->gVal + fFaceCost); + processNeighbour(current->position + arrayPathfinderFaces[1], current->gVal + fFaceCost); + processNeighbour(current->position + arrayPathfinderFaces[2], current->gVal + fFaceCost); + processNeighbour(current->position + arrayPathfinderFaces[3], current->gVal + fFaceCost); + processNeighbour(current->position + arrayPathfinderFaces[4], current->gVal + fFaceCost); + processNeighbour(current->position + arrayPathfinderFaces[5], current->gVal + fFaceCost); + } + + if (allNodes.size() > m_params.maxNumberOfNodes) + { + //We've reached the specified maximum number + //of nodes. Just give up on the search. + break; + } + } + + if ((openNodes.empty()) || (openNodes.getFirst() != endNode)) + { + //In this case we failed to find a valid path. + POLYVOX_THROW(std::runtime_error, "No path found"); + } + else + { + //Regarding the const_cast - normally you should not modify an object which is in an sdt::set. + //The reason is that objects in a set are stored sorted in a tree so they can be accessed quickly, + //and changing the object directly can break the sorting. However, in our case we have provided a + //custom sort operator for the set which we know only uses the position to sort. Hence we can safely + //modify other properties of the object while it is in the set. + Node* n = const_cast(&(*endNode)); + while (n != 0) + { + m_params.result->push_front(n->position); + n = n->parent; + } + } + + if (m_params.progressCallback) + { + m_params.progressCallback(1.0f); + } + } + + template + void AStarPathfinder::processNeighbour(const Vector3DInt32& neighbourPos, float neighbourGVal) + { + bool bIsVoxelValidForPath = m_params.isVoxelValidForPath(m_params.volume, neighbourPos); + if (!bIsVoxelValidForPath) + { + return; + } + + float cost = neighbourGVal; + + std::pair insertResult = allNodes.insert(Node(neighbourPos.getX(), neighbourPos.getY(), neighbourPos.getZ())); + AllNodesContainer::iterator neighbour = insertResult.first; + + if (insertResult.second == true) //New node, compute h. + { + Node* tempNeighbour = const_cast(&(*neighbour)); + tempNeighbour->hVal = computeH(neighbour->position, m_params.end); + } + + OpenNodesContainer::iterator openIter = openNodes.find(neighbour); + if (openIter != openNodes.end()) + { + if (cost < neighbour->gVal) + { + openNodes.remove(openIter); + openIter = openNodes.end(); + } + } + + //TODO - Nodes could keep track of if they are in open or closed? And a pointer to where they are? + ClosedNodesContainer::iterator closedIter = closedNodes.find(neighbour); + if (closedIter != closedNodes.end()) + { + if (cost < neighbour->gVal) + { + //Probably shouldn't happen? + closedNodes.remove(closedIter); + closedIter = closedNodes.end(); + } + } + + if ((openIter == openNodes.end()) && (closedIter == closedNodes.end())) + { + //Regarding the const_cast - normally you should not modify an object which is in an sdt::set. + //The reason is that objects in a set are stored sorted in a tree so they can be accessed quickly, + //and changing the object directly can break the sorting. However, in our case we have provided a + //custom sort operator for the set which we know only uses the position to sort. Hence we can safely + //modify other properties of the object while it is in the set. + Node* temp = const_cast(&(*neighbour)); + temp->gVal = cost; + openNodes.insert(neighbour); + temp->parent = const_cast(&(*current)); + } + } + + template + float AStarPathfinder::SixConnectedCost(const Vector3DInt32& a, const Vector3DInt32& b) + { + //This is the only heuristic I'm sure of - just use the manhatten distance for the 6-connected case. + uint32_t faceSteps = std::abs(a.getX() - b.getX()) + std::abs(a.getY() - b.getY()) + std::abs(a.getZ() - b.getZ()); + + return faceSteps * 1.0f; + } + + template + float AStarPathfinder::EighteenConnectedCost(const Vector3DInt32& a, const Vector3DInt32& b) + { + //I'm not sure of the correct heuristic for the 18-connected case, so I'm just letting it fall through to the + //6-connected case. This means 'h' will be bigger than it should be, resulting in a faster path which may not + //actually be the shortest one. If you have a correct heuristic for the 18-connected case then please let me know. + + return SixConnectedCost(a, b); + } + + template + float AStarPathfinder::TwentySixConnectedCost(const Vector3DInt32& a, const Vector3DInt32& b) + { + //Can't say I'm certain about this heuristic - if anyone has + //a better idea of what it should be then please let me know. + uint32_t array[3]; + array[0] = std::abs(a.getX() - b.getX()); + array[1] = std::abs(a.getY() - b.getY()); + array[2] = std::abs(a.getZ() - b.getZ()); + + //Maybe this is better implemented directly + //using three compares and two swaps... but not + //until the profiler says so. + std::sort(&array[0], &array[3]); + + uint32_t cornerSteps = array[0]; + uint32_t edgeSteps = array[1] - array[0]; + uint32_t faceSteps = array[2] - array[1]; + + return cornerSteps * sqrt_3 + edgeSteps * sqrt_2 + faceSteps * sqrt_1; + } + + template + float AStarPathfinder::computeH(const Vector3DInt32& a, const Vector3DInt32& b) + { + float hVal; + + switch (m_params.connectivity) + { + case TwentySixConnected: + hVal = TwentySixConnectedCost(a, b); + break; + case EighteenConnected: + hVal = EighteenConnectedCost(a, b); + break; + case SixConnected: + hVal = SixConnectedCost(a, b); + break; + default: + POLYVOX_THROW(std::invalid_argument, "Connectivity parameter has an unrecognised value."); + } + + //Sanity checks in debug mode. These can come out eventually, but I + //want to make sure that the heuristics I've come up with make sense. + POLYVOX_ASSERT((a - b).length() <= TwentySixConnectedCost(a, b), "A* heuristic error."); + POLYVOX_ASSERT(TwentySixConnectedCost(a, b) <= EighteenConnectedCost(a, b), "A* heuristic error."); + POLYVOX_ASSERT(EighteenConnectedCost(a, b) <= SixConnectedCost(a, b), "A* heuristic error."); + + //Apply the bias to the computed h value; + hVal *= m_params.hBias; + + //Having computed hVal, we now apply some random bias to break ties. + //This needs to be deterministic on the input position. This random + //bias means it is much les likely that two paths are exactly the same + //length, and so far fewer nodes must be expanded to find the shortest path. + //See http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S12 + + //Note that if the hash is zero we can have differences between the Linux vs. Windows + //(or perhaps GCC vs. VS) versions of the code. This is probably because of the way + //sorting inside the std::set works (i.e. one system swaps values which are identical + //while the other one doesn't - both approaches are valid). For the same reason we want + //to make sure that position (x,y,z) has a differnt hash from e.g. position (x,z,y). + uint32_t aX = (a.getX() << 16) & 0x00FF0000; + uint32_t aY = (a.getY() << 8) & 0x0000FF00; + uint32_t aZ = (a.getZ()) & 0x000000FF; + uint32_t hashVal = hash(aX | aY | aZ); + + //Stop hashVal going over 65535, and divide by 1000000 to make sure it is small. + hashVal &= 0x0000FFFF; + float fHash = hashVal / 1000000.0f; + + //Apply the hash and return + hVal += fHash; + return hVal; + } + + // Robert Jenkins' 32 bit integer hash function + // http://www.burtleburtle.net/bob/hash/integer.html + template + uint32_t AStarPathfinder::hash(uint32_t a) + { + a = (a + 0x7ed55d16) + (a << 12); + a = (a ^ 0xc761c23c) ^ (a >> 19); + a = (a + 0x165667b1) + (a << 5); + a = (a + 0xd3a2646c) ^ (a << 9); + a = (a + 0xfd7046c5) + (a << 3); + a = (a ^ 0xb55a4f09) ^ (a >> 16); + return a; + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AmbientOcclusionCalculator.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AmbientOcclusionCalculator.h new file mode 100644 index 0000000..585b1ed --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AmbientOcclusionCalculator.h @@ -0,0 +1,79 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __AmbientOcclusionCalculator_H__ +#define __AmbientOcclusionCalculator_H__ + +#include "Impl/RandomUnitVectors.h" +#include "Impl/RandomVectors.h" + +#include "Array.h" +#include "Region.h" +#include "Raycast.h" + +#include + +namespace PolyVox +{ + /** + * \file + * + * Ambient occlusion + */ + + template + class AmbientOcclusionCalculatorRaycastCallback + { + public: + AmbientOcclusionCalculatorRaycastCallback(IsVoxelTransparentCallback isVoxelTransparentCallback) : mIsVoxelTransparentCallback(isVoxelTransparentCallback) + { + } + + bool operator()(const typename VolumeType::Sampler& sampler) + { + auto sample = sampler.getVoxel(); + bool func = mIsVoxelTransparentCallback(sample); + return func; + } + + IsVoxelTransparentCallback mIsVoxelTransparentCallback; + }; + + // NOTE: The callback needs to be a functor not a function. I haven't been + // able to work the required template magic to get functions working as well. + // + // Matt: If you make the function take a "IsVoxelTransparentCallback&&" then + // it will forward it on. Works for functors, functions and lambdas. + // This will be 'perfect forwarding' using 'universal references' + // This will require C++11 rvalue references which is why I haven't made the + // change yet. + + /// Calculate the ambient occlusion for the volume + template + void calculateAmbientOcclusion(VolumeType* volInput, Array<3, uint8_t>* arrayResult, const Region& region, float fRayLength, uint8_t uNoOfSamplesPerOutputElement, IsVoxelTransparentCallback isVoxelTransparentCallback); +} + +#include "AmbientOcclusionCalculator.inl" + +#endif //__AmbientOcclusionCalculator_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AmbientOcclusionCalculator.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AmbientOcclusionCalculator.inl new file mode 100644 index 0000000..19336b2 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/AmbientOcclusionCalculator.inl @@ -0,0 +1,147 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + /** + * This function fills a 3D array with ambient occlusion values computed by raycasting through the volume. + * This approach to ambient occlusion is only appropriate for relatvely small volumes, otherwise it will + * become very slow and consume a lot of memory. You will need to find a way to actually use the generated + * ambient occlusion data, which might mean uploading it the the GPU as a volume texture or sampling on + * the CPU using the vertex positions from your generated mesh. + * + * In practice we have not made much use of this implementation ourselves, so you may find it needs some + * optimizations or improvements to be useful. It is likely that there are actually better approaches to + * the ambient occlusion problem. + * + * \param volInput The volume to calculate the ambient occlusion for + * \param[out] arrayResult The output of the calculator + * \param region The region of the volume for which the occlusion should be calculated + * \param fRayLength The length for each test ray + * \param uNoOfSamplesPerOutputElement The number of samples to calculate the occlusion + * \param isVoxelTransparentCallback A callback which takes a \a VoxelType and returns a \a bool whether the voxel is transparent + */ + template + void calculateAmbientOcclusion(VolumeType* volInput, Array<3, uint8_t>* arrayResult, const Region& region, float fRayLength, uint8_t uNoOfSamplesPerOutputElement, IsVoxelTransparentCallback isVoxelTransparentCallback) + { + //Make sure that the size of the volume is an exact multiple of the size of the array. + if (region.getWidthInVoxels() % arrayResult->getDimension(0) != 0) + { + POLYVOX_THROW(std::invalid_argument, "Volume width must be an exact multiple of array width."); + } + if (region.getHeightInVoxels() % arrayResult->getDimension(1) != 0) + { + POLYVOX_THROW(std::invalid_argument, "Volume width must be an exact multiple of array height."); + } + if (region.getDepthInVoxels() % arrayResult->getDimension(2) != 0) + { + POLYVOX_THROW(std::invalid_argument, "Volume width must be an exact multiple of array depth."); + } + + uint16_t uRandomUnitVectorIndex = 0; + uint16_t uRandomVectorIndex = 0; + uint16_t uIndexIncreament; + + //Our initial indices. It doesn't matter exactly what we set here, but the code below makes + //sure they are different for different regions which helps reduce tiling patterns in the results. + uRandomUnitVectorIndex += region.getLowerX() + region.getLowerY() + region.getLowerZ(); + uRandomVectorIndex += region.getLowerX() + region.getLowerY() + region.getLowerZ(); + + //This value helps us jump around in the array a bit more, so the + //nth 'random' value isn't always followed by the n+1th 'random' value. + uIndexIncreament = 1; + + const int iRatioX = region.getWidthInVoxels() / arrayResult->getDimension(0); + const int iRatioY = region.getHeightInVoxels() / arrayResult->getDimension(1); + const int iRatioZ = region.getDepthInVoxels() / arrayResult->getDimension(2); + + const float fRatioX = iRatioX; + const float fRatioY = iRatioY; + const float fRatioZ = iRatioZ; + const Vector3DFloat v3dRatio(fRatioX, fRatioY, fRatioZ); + + const float fHalfRatioX = fRatioX * 0.5f; + const float fHalfRatioY = fRatioY * 0.5f; + const float fHalfRatioZ = fRatioZ * 0.5f; + const Vector3DFloat v3dHalfRatio(fHalfRatioX, fHalfRatioY, fHalfRatioZ); + + const Vector3DFloat v3dOffset(0.5f, 0.5f, 0.5f); + + //This loop iterates over the bottom-lower-left voxel in each of the cells in the output array + for (uint16_t z = region.getLowerZ(); z <= region.getUpperZ(); z += iRatioZ) + { + for (uint16_t y = region.getLowerY(); y <= region.getUpperY(); y += iRatioY) + { + for (uint16_t x = region.getLowerX(); x <= region.getUpperX(); x += iRatioX) + { + //Compute a start position corresponding to + //the centre of the cell in the output array. + Vector3DFloat v3dStart(x, y, z); + v3dStart -= v3dOffset; + v3dStart += v3dHalfRatio; + + //Keep track of how many rays did not hit anything + uint8_t uVisibleDirections = 0; + + for (int ct = 0; ct < uNoOfSamplesPerOutputElement; ct++) + { + //We take a random vector with components going from -1 to 1 and scale it to go from -halfRatio to +halfRatio. + //This jitter value moves our sample point from the centre of the array cell to somewhere else in the array cell + Vector3DFloat v3dJitter = randomVectors[(uRandomVectorIndex += (++uIndexIncreament)) % 1019]; //Prime number helps avoid repetition on successive loops. + v3dJitter *= v3dHalfRatio; + const Vector3DFloat v3dRayStart = v3dStart + v3dJitter; + + Vector3DFloat v3dRayDirection = randomUnitVectors[(uRandomUnitVectorIndex += (++uIndexIncreament)) % 1021]; //Different prime number. + v3dRayDirection *= fRayLength; + + AmbientOcclusionCalculatorRaycastCallback ambientOcclusionCalculatorRaycastCallback(isVoxelTransparentCallback); + RaycastResult result = raycastWithDirection(volInput, v3dRayStart, v3dRayDirection, ambientOcclusionCalculatorRaycastCallback); + + // Note - The performance of this could actually be improved it we exited as soon + // as the ray left the volume. The raycast test has an example of how to do this. + if (result == RaycastResults::Completed) + { + ++uVisibleDirections; + } + } + + float fVisibility; + if (uNoOfSamplesPerOutputElement == 0) + { + //The user might request zero samples (I've done this in the past while debugging - I don't want to + //wait for ambient occlusion but I do want as valid result for rendering). Avoid the divide by zero. + fVisibility = 1.0f; + } + else + { + fVisibility = static_cast(uVisibleDirections) / static_cast(uNoOfSamplesPerOutputElement); + POLYVOX_ASSERT((fVisibility >= 0.0f) && (fVisibility <= 1.0f), "Visibility value out of range."); + } + + (*arrayResult)(z / iRatioZ, y / iRatioY, x / iRatioX) = static_cast(255.0f * fVisibility); + } + } + } + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Array.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Array.h new file mode 100644 index 0000000..c8ad172 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Array.h @@ -0,0 +1,195 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Array_H__ +#define __PolyVox_Array_H__ + +#include "Impl/ErrorHandling.h" +#include "Impl/PlatformDefinitions.h" + +#include + +namespace PolyVox +{ + template + class Array + { + public: + + Array(uint32_t width) + :m_pElements(0) + { + static_assert(noOfDims == 1, "This constructor can only be used with a one-dimensional array"); + + m_uDimensions[0] = width; + + initialize(); + } + + Array(uint32_t width, uint32_t height) + :m_pElements(0) + { + static_assert(noOfDims == 2, "This constructor can only be used with a two-dimensional array"); + + m_uDimensions[0] = width; + m_uDimensions[1] = height; + + initialize(); + } + + Array(uint32_t width, uint32_t height, uint32_t depth) + :m_pElements(0) + { + static_assert(noOfDims == 3, "This constructor can only be used with a three-dimensional array"); + + m_uDimensions[0] = width; + m_uDimensions[1] = height; + m_uDimensions[2] = depth; + + initialize(); + } + + // These are deleted to avoid accidental copying. + Array(const Array&) = delete; + Array& operator=(const Array&) = delete; + + ~Array() + { + delete[] m_pElements; + } + + ElementType& operator()(uint32_t x) const + { + static_assert(noOfDims == 1, "This accessor can only be used with a one-dimensional array"); + POLYVOX_ASSERT(x < m_uDimensions[0], "Array access is out-of-range."); + return m_pElements[x]; + } + + ElementType& operator()(uint32_t x, uint32_t y) const + { + static_assert(noOfDims == 2, "This accessor can only be used with a two-dimensional array"); + POLYVOX_ASSERT(x < m_uDimensions[0] && y < m_uDimensions[1], "Array access is out-of-range."); + return m_pElements[y * m_uDimensions[0] + x]; + } + + ElementType& operator()(uint32_t x, uint32_t y, uint32_t z) const + { + static_assert(noOfDims == 3, "This accessor can only be used with a three-dimensional array"); + POLYVOX_ASSERT(x < m_uDimensions[0] && y < m_uDimensions[1] && z < m_uDimensions[2], "Array access is out-of-range."); + return m_pElements[z * m_uDimensions[0] * m_uDimensions[1] + y * m_uDimensions[0] + x]; + } + + uint32_t getDimension(uint32_t dimension) const + { + return m_uDimensions[dimension]; + } + + ElementType* getRawData() + { + return m_pElements; + } + + uint32_t getNoOfElements() + { + return m_uNoOfElements; + } + + void swap(Array& other) + { + ElementType* temp = other.m_pElements; + other.m_pElements = m_pElements; + m_pElements = temp; + } + + private: + + void initialize(void) + { + // Calculate the total number of elements in the array. + m_uNoOfElements = 1; + for (uint32_t i = 0; i < noOfDims; i++) + { + m_uNoOfElements *= m_uDimensions[i]; + } + m_pElements = new ElementType[m_uNoOfElements]; + } + + uint32_t m_uDimensions[noOfDims]; + uint32_t m_uNoOfElements; + ElementType* m_pElements; + }; + + ///A 1D Array of floats. + typedef Array<1, float> Array1DFloat; + ///A 1D Array of doubles. + typedef Array<1, double> Array1DDouble; + ///A 1D Array of signed 8-bit values. + typedef Array<1, int8_t> Array1DInt8; + ///A 1D Array of unsigned 8-bit values. + typedef Array<1, uint8_t> Array1DUint8; + ///A 1D Array of signed 16-bit values. + typedef Array<1, int16_t> Array1DInt16; + ///A 1D Array of unsigned 16-bit values. + typedef Array<1, uint16_t> Array1DUint16; + ///A 1D Array of signed 32-bit values. + typedef Array<1, int32_t> Array1DInt32; + ///A 1D Array of unsigned 32-bit values. + typedef Array<1, uint32_t> Array1DUint32; + + ///A 2D Array of floats. + typedef Array<2, float> Array2DFloat; + ///A 2D Array of doubles. + typedef Array<2, double> Array2DDouble; + ///A 2D Array of signed 8-bit values. + typedef Array<2, int8_t> Array2DInt8; + ///A 2D Array of unsigned 8-bit values. + typedef Array<2, uint8_t> Array2DUint8; + ///A 2D Array of signed 16-bit values. + typedef Array<2, int16_t> Array2DInt16; + ///A 2D Array of unsigned 16-bit values. + typedef Array<2, uint16_t> Array2DUint16; + ///A 2D Array of signed 32-bit values. + typedef Array<2, int32_t> Array2DInt32; + ///A 2D Array of unsigned 32-bit values. + typedef Array<2, uint32_t> Array2DUint32; + + ///A 3D Array of floats. + typedef Array<3, float> Array3DFloat; + ///A 3D Array of doubles. + typedef Array<3, double> Array3DDouble; + ///A 3D Array of signed 8-bit values. + typedef Array<3, int8_t> Array3DInt8; + ///A 3D Array of unsigned 8-bit values. + typedef Array<3, uint8_t> Array3DUint8; + ///A 3D Array of signed 16-bit values. + typedef Array<3, int16_t> Array3DInt16; + ///A 3D Array of unsigned 16-bit values. + typedef Array<3, uint16_t> Array3DUint16; + ///A 3D Array of signed 32-bit values. + typedef Array<3, int32_t> Array3DInt32; + ///A 3D Array of unsigned 32-bit values. + typedef Array<3, uint32_t> Array3DUint32; +} + +#endif //__PolyVox_Array_H__ \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolume.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolume.h new file mode 100644 index 0000000..5a42389 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolume.h @@ -0,0 +1,142 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_BaseVolume_H__ +#define __PolyVox_BaseVolume_H__ + +#include "Region.h" +#include "Vector.h" + +#include + +namespace PolyVox +{ + /// The BaseVolume class provides common functionality and an interface for other volume classes to implement. + /// You should not try to create an instance of this class directly. Instead you should use RawVolume or PagedVolume. + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /// \sa RawVolume, PagedVolume + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + template + class BaseVolume + { + public: + typedef _VoxelType VoxelType; + +#ifndef SWIG + template + class Sampler + { + public: + Sampler(DerivedVolumeType* volume); + ~Sampler(); + + Vector3DInt32 getPosition(void) const; + inline VoxelType getVoxel(void) const; + + void setPosition(const Vector3DInt32& v3dNewPos); + void setPosition(int32_t xPos, int32_t yPos, int32_t zPos); + inline bool setVoxel(VoxelType tValue); + + void movePositiveX(void); + void movePositiveY(void); + void movePositiveZ(void); + + void moveNegativeX(void); + void moveNegativeY(void); + void moveNegativeZ(void); + + inline VoxelType peekVoxel1nx1ny1nz(void) const; + inline VoxelType peekVoxel1nx1ny0pz(void) const; + inline VoxelType peekVoxel1nx1ny1pz(void) const; + inline VoxelType peekVoxel1nx0py1nz(void) const; + inline VoxelType peekVoxel1nx0py0pz(void) const; + inline VoxelType peekVoxel1nx0py1pz(void) const; + inline VoxelType peekVoxel1nx1py1nz(void) const; + inline VoxelType peekVoxel1nx1py0pz(void) const; + inline VoxelType peekVoxel1nx1py1pz(void) const; + + inline VoxelType peekVoxel0px1ny1nz(void) const; + inline VoxelType peekVoxel0px1ny0pz(void) const; + inline VoxelType peekVoxel0px1ny1pz(void) const; + inline VoxelType peekVoxel0px0py1nz(void) const; + inline VoxelType peekVoxel0px0py0pz(void) const; + inline VoxelType peekVoxel0px0py1pz(void) const; + inline VoxelType peekVoxel0px1py1nz(void) const; + inline VoxelType peekVoxel0px1py0pz(void) const; + inline VoxelType peekVoxel0px1py1pz(void) const; + + inline VoxelType peekVoxel1px1ny1nz(void) const; + inline VoxelType peekVoxel1px1ny0pz(void) const; + inline VoxelType peekVoxel1px1ny1pz(void) const; + inline VoxelType peekVoxel1px0py1nz(void) const; + inline VoxelType peekVoxel1px0py0pz(void) const; + inline VoxelType peekVoxel1px0py1pz(void) const; + inline VoxelType peekVoxel1px1py1nz(void) const; + inline VoxelType peekVoxel1px1py0pz(void) const; + inline VoxelType peekVoxel1px1py1pz(void) const; + + protected: + + DerivedVolumeType* mVolume; + + //The current position in the volume + int32_t mXPosInVolume; + int32_t mYPosInVolume; + int32_t mZPosInVolume; + }; +#endif // SWIG + + public: + /// Gets a voxel at the position given by x,y,z coordinates + VoxelType getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos) const; + /// Gets a voxel at the position given by a 3D vector + VoxelType getVoxel(const Vector3DInt32& v3dPos) const; + + /// Sets the voxel at the position given by x,y,z coordinates + void setVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue); + /// Sets the voxel at the position given by a 3D vector + void setVoxel(const Vector3DInt32& v3dPos, VoxelType tValue); + + /// Calculates approximatly how many bytes of memory the volume is currently using. + uint32_t calculateSizeInBytes(void); + + protected: + /// Constructor for creating a volume. + BaseVolume(); + + /// Copy constructor + BaseVolume(const BaseVolume& rhs); + + /// Destructor + ~BaseVolume(); + + /// Assignment operator + BaseVolume& operator=(const BaseVolume& rhs); + }; +} + +#include "BaseVolume.inl" +#include "BaseVolumeSampler.inl" + +#endif //__PolyVox_BaseVolume_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolume.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolume.inl new file mode 100644 index 0000000..a54227f --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolume.inl @@ -0,0 +1,130 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + //////////////////////////////////////////////////////////////////////////////// + /// This is protected because you should never create a BaseVolume directly, you should instead use one of the derived classes. + /// + /// \sa RawVolume, PagedVolume + //////////////////////////////////////////////////////////////////////////////// + template + BaseVolume::BaseVolume() + { + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should never be called. Copying volumes by value would be expensive, and we want to prevent users from doing + /// it by accident (such as when passing them as paramenters to functions). That said, there are times when you really do want to + /// make a copy of a volume and in this case you should look at the VolumeResampler. + /// + /// \sa VolumeResampler + //////////////////////////////////////////////////////////////////////////////// + template + BaseVolume::BaseVolume(const BaseVolume& /*rhs*/) + { + POLYVOX_THROW(not_implemented, "Volume copy constructor not implemented to prevent accidental copying."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// Destroys the volume + //////////////////////////////////////////////////////////////////////////////// + template + BaseVolume::~BaseVolume() + { + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should never be called. Copying volumes by value would be expensive, and we want to prevent users from doing + /// it by accident (such as when passing them as paramenters to functions). That said, there are times when you really do want to + /// make a copy of a volume and in this case you should look at the VolumeResampler. + /// + /// \sa VolumeResampler + //////////////////////////////////////////////////////////////////////////////// + template + BaseVolume& BaseVolume::operator=(const BaseVolume& /*rhs*/) + { + POLYVOX_THROW(not_implemented, "Volume copy constructor not implemented to prevent accidental copying."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This version of the function is provided so that the wrap mode does not need + /// to be specified as a template parameter, as it may be confusing to some users. + /// \param uXPos The \c x position of the voxel + /// \param uYPos The \c y position of the voxel + /// \param uZPos The \c z position of the voxel + /// \return The voxel value + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType BaseVolume::getVoxel(int32_t /*uXPos*/, int32_t /*uYPos*/, int32_t /*uZPos*/) const + { + POLYVOX_ASSERT(false, "You should never call the base class version of this function."); + return VoxelType(); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This version of the function is provided so that the wrap mode does not need + /// to be specified as a template parameter, as it may be confusing to some users. + /// \param v3dPos The 3D position of the voxel + /// \return The voxel value + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType BaseVolume::getVoxel(const Vector3DInt32& /*v3dPos*/) const + { + POLYVOX_ASSERT(false, "You should never call the base class version of this function."); + return VoxelType(); + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param uXPos the \c x position of the voxel + /// \param uYPos the \c y position of the voxel + /// \param uZPos the \c z position of the voxel + /// \param tValue the value to which the voxel will be set + //////////////////////////////////////////////////////////////////////////////// + template + void BaseVolume::setVoxel(int32_t /*uXPos*/, int32_t /*uYPos*/, int32_t /*uZPos*/, VoxelType /*tValue*/) + { + POLYVOX_THROW(not_implemented, "You should never call the base class version of this function."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param v3dPos the 3D position of the voxel + /// \param tValue the value to which the voxel will be set + //////////////////////////////////////////////////////////////////////////////// + template + void BaseVolume::setVoxel(const Vector3DInt32& /*v3dPos*/, VoxelType /*tValue*/) + { + POLYVOX_THROW(not_implemented, "You should never call the base class version of this function."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// + //////////////////////////////////////////////////////////////////////////////// + template + uint32_t BaseVolume::calculateSizeInBytes(void) + { + POLYVOX_THROW(not_implemented, "You should never call the base class version of this function."); + } +} + diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolumeSampler.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolumeSampler.inl new file mode 100644 index 0000000..c85f571 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/BaseVolumeSampler.inl @@ -0,0 +1,316 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/Utility.h" + +namespace PolyVox +{ + template + template + BaseVolume::Sampler::Sampler(DerivedVolumeType* volume) + :mVolume(volume) + , mXPosInVolume(0) + , mYPosInVolume(0) + , mZPosInVolume(0) + { + } + + template + template + BaseVolume::Sampler::~Sampler() + { + } + + template + template + Vector3DInt32 BaseVolume::Sampler::getPosition(void) const + { + return Vector3DInt32(mXPosInVolume, mYPosInVolume, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::getVoxel(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume, mZPosInVolume); + } + + template + template + void BaseVolume::Sampler::setPosition(const Vector3DInt32& v3dNewPos) + { + setPosition(v3dNewPos.getX(), v3dNewPos.getY(), v3dNewPos.getZ()); + } + + template + template + void BaseVolume::Sampler::setPosition(int32_t xPos, int32_t yPos, int32_t zPos) + { + mXPosInVolume = xPos; + mYPosInVolume = yPos; + mZPosInVolume = zPos; + } + + template + template + bool BaseVolume::Sampler::setVoxel(VoxelType tValue) + { + return mVolume->setVoxel(mXPosInVolume, mYPosInVolume, mZPosInVolume, tValue); + } + + template + template + void BaseVolume::Sampler::movePositiveX(void) + { + mXPosInVolume++; + } + + template + template + void BaseVolume::Sampler::movePositiveY(void) + { + mYPosInVolume++; + } + + template + template + void BaseVolume::Sampler::movePositiveZ(void) + { + mZPosInVolume++; + } + + template + template + void BaseVolume::Sampler::moveNegativeX(void) + { + mXPosInVolume--; + } + + template + template + void BaseVolume::Sampler::moveNegativeY(void) + { + mYPosInVolume--; + } + + template + template + void BaseVolume::Sampler::moveNegativeZ(void) + { + mZPosInVolume--; + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx1ny1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume - 1, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx1ny0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume - 1, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx1ny1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume - 1, mZPosInVolume + 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx0py1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx0py0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx0py1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume, mZPosInVolume + 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx1py1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume + 1, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx1py0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume + 1, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1nx1py1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume - 1, mYPosInVolume + 1, mZPosInVolume + 1); + } + + ////////////////////////////////////////////////////////////////////////// + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px1ny1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume - 1, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px1ny0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume - 1, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px1ny1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume - 1, mZPosInVolume + 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px0py1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px0py0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px0py1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume, mZPosInVolume + 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px1py1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume + 1, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px1py0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume + 1, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel0px1py1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume, mYPosInVolume + 1, mZPosInVolume + 1); + } + + ////////////////////////////////////////////////////////////////////////// + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px1ny1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume - 1, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px1ny0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume - 1, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px1ny1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume - 1, mZPosInVolume + 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px0py1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px0py0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px0py1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume, mZPosInVolume + 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px1py1nz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume + 1, mZPosInVolume - 1); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px1py0pz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume + 1, mZPosInVolume); + } + + template + template + VoxelType BaseVolume::Sampler::peekVoxel1px1py1pz(void) const + { + return mVolume->getVoxel(mXPosInVolume + 1, mYPosInVolume + 1, mZPosInVolume + 1); + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Config.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Config.h new file mode 100644 index 0000000..5a0ef8a --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Config.h @@ -0,0 +1,38 @@ +/******************************************************************************* +The MIT License (MIT) + +Copyright (c) 2015 David Williams and Matthew Williams + +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 __PolyVox_Config_H__ +#define __PolyVox_Config_H__ + +//#define POLYVOX_LOG_TRACE_ENABLED +//#define POLYVOX_LOG_DEBUG_ENABLED +#define POLYVOX_LOG_INFO_ENABLED +#define POLYVOX_LOG_WARNING_ENABLED +#define POLYVOX_LOG_ERROR_ENABLED +#define POLYVOX_LOG_FATAL_ENABLED + +//#define POLYVOX_ASSERTS_ENABLED +#define POLYVOX_THROW_ENABLED + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/CubicSurfaceExtractor.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/CubicSurfaceExtractor.h new file mode 100644 index 0000000..d0499b8 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/CubicSurfaceExtractor.h @@ -0,0 +1,78 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_CubicSurfaceExtractor_H__ +#define __PolyVox_CubicSurfaceExtractor_H__ + +#include "Impl/PlatformDefinitions.h" + +#include "Array.h" +#include "BaseVolume.h" //For wrap modes... should move these? +#include "DefaultIsQuadNeeded.h" +#include "Mesh.h" +#include "Vertex.h" + +namespace PolyVox +{ + /// A specialised vertex format which encodes the data from the cubic extraction algorithm in a very + /// compact way. You will probably want to use the decodeVertex() function to turn it into a regular + /// Vertex for rendering, but advanced users should also be able to decode it on the GPU (not tested). + template + struct CubicVertex + { + typedef _DataType DataType; + + /// Each component of the position is stored as a single unsigned byte. + /// The true position is found by offseting each component by 0.5f. + Vector3DUint8 encodedPosition; + + /// A copy of the data which was stored in the voxel which generated this vertex. + DataType data; + }; + + // Convienient shorthand for declaring a mesh of 'cubic' vertices + // Currently disabled because it requires GCC 4.7 + //template + //using CubicMesh = Mesh< CubicVertex, IndexType >; + + /// Decodes a position from a CubicVertex + inline Vector3DFloat decodePosition(const Vector3DUint8& encodedPosition); + + /// Decodes a CubicVertex by converting it into a regular Vertex which can then be directly used for rendering. + template + Vertex decodeVertex(const CubicVertex& cubicVertex); + + /// Generates a cubic-style mesh from the voxel data. + template > + void extractCubicMeshCustom(VolumeType* volData, Region region, MeshType* result, IsQuadNeeded isQuadNeeded = IsQuadNeeded(), bool bMergeQuads = true); + + /// Generates a cubic-style mesh from the voxel data, placing the result into a user-provided Mesh. + template > + Mesh > extractCubicMesh(VolumeType* volData, Region region, IsQuadNeeded isQuadNeeded = IsQuadNeeded(), bool bMergeQuads = true); + +} + +#include "CubicSurfaceExtractor.inl" + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/CubicSurfaceExtractor.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/CubicSurfaceExtractor.inl new file mode 100644 index 0000000..846c776 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/CubicSurfaceExtractor.inl @@ -0,0 +1,422 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/Timer.h" + +namespace PolyVox +{ + // This constant defines the maximum number of quads which can share a vertex in a cubic style mesh. + // + // We try to avoid duplicate vertices by checking whether a vertex has already been added at a given position. + // However, it is possible that vertices have the same position but different materials. In this case, the + // vertices are not true duplicates and both must be added to the mesh. As far as I can tell, it is possible to have + // at most eight vertices with the same position but different materials. For example, this worst-case scenario + // happens when we have a 2x2x2 group of voxels, all with different materials and some/all partially transparent. + // The vertex position at the center of this group is then going to be used by all eight voxels all with different + // materials. + const uint32_t MaxVerticesPerPosition = 8; + + //////////////////////////////////////////////////////////////////////////////// + // Data structures + //////////////////////////////////////////////////////////////////////////////// + + enum FaceNames + { + PositiveX, + PositiveY, + PositiveZ, + NegativeX, + NegativeY, + NegativeZ, + NoOfFaces + }; + + struct Quad + { + Quad(uint32_t v0, uint32_t v1, uint32_t v2, uint32_t v3) + { + vertices[0] = v0; + vertices[1] = v1; + vertices[2] = v2; + vertices[3] = v3; + } + + uint32_t vertices[4]; + }; + + template + struct IndexAndMaterial + { + int32_t iIndex; + typename VolumeType::VoxelType uMaterial; + }; + + //////////////////////////////////////////////////////////////////////////////// + // Vertex encoding/decoding + //////////////////////////////////////////////////////////////////////////////// + + inline Vector3DFloat decodePosition(const Vector3DUint8& encodedPosition) + { + Vector3DFloat result(encodedPosition.getX(), encodedPosition.getY(), encodedPosition.getZ()); + result -= 0.5f; // Apply the required offset + return result; + } + + template + Vertex decodeVertex(const CubicVertex& cubicVertex) + { + Vertex result; + result.position = decodePosition(cubicVertex.encodedPosition); + result.normal.setElements(0.0f, 0.0f, 0.0f); // Currently not calculated + result.data = cubicVertex.data; // Data is not encoded + return result; + } + + //////////////////////////////////////////////////////////////////////////////// + // Surface extraction + //////////////////////////////////////////////////////////////////////////////// + + template + bool mergeQuads(Quad& q1, Quad& q2, MeshType* m_meshCurrent) + { + //All four vertices of a given quad have the same data, + //so just check that the first pair of vertices match. + if (m_meshCurrent->getVertex(q1.vertices[0]).data == m_meshCurrent->getVertex(q2.vertices[0]).data) + { + //Now check whether quad 2 is adjacent to quad one by comparing vertices. + //Adjacent quads must share two vertices, and the second quad could be to the + //top, bottom, left, of right of the first one. This gives four combinations to test. + if ((q1.vertices[0] == q2.vertices[1]) && ((q1.vertices[3] == q2.vertices[2]))) + { + q1.vertices[0] = q2.vertices[0]; + q1.vertices[3] = q2.vertices[3]; + return true; + } + else if ((q1.vertices[3] == q2.vertices[0]) && ((q1.vertices[2] == q2.vertices[1]))) + { + q1.vertices[3] = q2.vertices[3]; + q1.vertices[2] = q2.vertices[2]; + return true; + } + else if ((q1.vertices[1] == q2.vertices[0]) && ((q1.vertices[2] == q2.vertices[3]))) + { + q1.vertices[1] = q2.vertices[1]; + q1.vertices[2] = q2.vertices[2]; + return true; + } + else if ((q1.vertices[0] == q2.vertices[3]) && ((q1.vertices[1] == q2.vertices[2]))) + { + q1.vertices[0] = q2.vertices[0]; + q1.vertices[1] = q2.vertices[1]; + return true; + } + } + + //Quads cannot be merged. + return false; + } + + template + bool performQuadMerging(std::list& quads, MeshType* m_meshCurrent) + { + bool bDidMerge = false; + for (typename std::list::iterator outerIter = quads.begin(); outerIter != quads.end(); outerIter++) + { + typename std::list::iterator innerIter = outerIter; + innerIter++; + while (innerIter != quads.end()) + { + Quad& q1 = *outerIter; + Quad& q2 = *innerIter; + + bool result = mergeQuads(q1, q2, m_meshCurrent); + + if (result) + { + bDidMerge = true; + innerIter = quads.erase(innerIter); + } + else + { + innerIter++; + } + } + } + + return bDidMerge; + } + + template + int32_t addVertex(uint32_t uX, uint32_t uY, uint32_t uZ, typename VolumeType::VoxelType uMaterialIn, Array<3, IndexAndMaterial >& existingVertices, MeshType* m_meshCurrent) + { + for (uint32_t ct = 0; ct < MaxVerticesPerPosition; ct++) + { + IndexAndMaterial& rEntry = existingVertices(uX, uY, ct); + + if (rEntry.iIndex == -1) + { + //No vertices matched and we've now hit an empty space. Fill it by creating a vertex. The 0.5f offset is because vertices set between voxels in order to build cubes around them. + CubicVertex cubicVertex; + cubicVertex.encodedPosition.setElements(static_cast(uX), static_cast(uY), static_cast(uZ)); + cubicVertex.data = uMaterialIn; + rEntry.iIndex = m_meshCurrent->addVertex(cubicVertex); + rEntry.uMaterial = uMaterialIn; + + return rEntry.iIndex; + } + + //If we have an existing vertex and the material matches then we can return it. + if (rEntry.uMaterial == uMaterialIn) + { + return rEntry.iIndex; + } + } + + // If we exit the loop here then apparently all the slots were full but none of them matched. + // This shouldn't ever happen, so if it does it is probably a bug in PolyVox. Please report it to us! + POLYVOX_THROW(std::runtime_error, "All slots full but no matches during cubic surface extraction. This is probably a bug in PolyVox"); + return -1; //Should never happen. + } + + /// The CubicSurfaceExtractor creates a mesh in which each voxel appears to be rendered as a cube + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /// Introduction + /// ------------ + /// Games such as Minecraft and Voxatron have a unique graphical style in which each voxel in the world appears to be rendered as a single cube. Actually rendering a cube for each voxel would be very expensive, but in practice the only faces which need to be drawn are those which lie on the boundary between solid and empty voxels. The CubicSurfaceExtractor can be used to create such a mesh from PolyVox volume data. As an example, images from Minecraft and Voxatron are shown below: + /// + /// \image html MinecraftAndVoxatron.jpg + /// + /// Before we get into the specifics of the CubicSurfaceExtractor, it is useful to understand the principles which apply to *all* PolyVox surface extractors and which are described in the Surface Extraction document (ADD LINK). From here on, it is assumed that you are familier with PolyVox regions and how they are used to limit surface extraction to a particular part of the volume. The principles of allowing dynamic terrain are also common to all surface extractors and are described here (ADD LINK). + /// + /// Basic Operation + /// --------------- + /// At its core, the CubicSurfaceExtractor works by by looking at pairs of adjacent voxels and determining whether a quad should be placed between then. The most simple situation to imagine is a binary volume where every voxel is either solid or empty. In this case a quad should be generated whenever a solid voxel is next to an empty voxel as this represents part of the surface of the solid object. There is no need to generate a quad between two solid voxels (this quad would never be seen as it is inside the object) and there is no need to generate a quad between two empty voxels (there is no object here). PolyVox allows the principle to be extended far beyond such simple binary volumes but they provide a useful starting point for understanding how the algorithm works. + /// + /// As an example, lets consider the part of a volume shown below. We are going to explain the principles in only two dimensions as this makes it much simpler to illustrate, so you will need to mentally extend the process into the third dimension. Hopefully you will find this intuitive. The diagram below shows a small part of a larger volume (as indicated by the voxel coordinates on the axes) which contains only solid and empty voxels represented by solid and hollow circles respectively. The region on which we are running the surface extractor is marked in pink, and for the purpose of this example it corresponds to the whole of the diagram. + /// + /// \image html CubicSurfaceExtractor1.png + /// + /// The output of the surface extractor is the mesh marked in red. As you can see, this forms a closed object which corrsponds to the shape of the underlying voxel data. We won't describe the rendering of such meshes here - for details of this please see (SOME LINK HERE). + /// + /// Working with Regions + /// -------------------- + /// So far the behaviour is easy to understand, but let's look at what happens when the extraction is limited to a particular region of the volume. The figure below shows the same data set as the previous figure, but the extraction region (still marked in pink) has been limited to 13 to 16 in x and 47 to 51 in y: + /// + /// \image html CubicSurfaceExtractor2.png + /// + /// As you can see, the extractor continues to generate a number of quads as indicated by the solid red lines. However, you can also see that the shape is no longer closed. This is because the solid voxels actually extend outside the region which is being processed, and so the extractor does not encounter a boundary between solid and empty voxels. Although this may initially appear problematic, the hole in the mesh does not actually matter because it will be hidden by the mesh corresponding to the region adjacent to it (see next diagram). + /// + /// More interestingly, the diagram also contains a couple of dotted red lines lying on the bottom and right hand side of the extracted region. These are present to illustrate a common point of confusion, which is that *no quads are generated at this position even though it is a boundary between solid and empty voxels*. This is indeed somewhat counter intuitive but there is a rational reasaoning behind it. + /// If you consider the dashed line on the righthand side of the extracted region, then it is clear that this lies on a boundary between solid and empty voxels and so we do need to create quads here. But what is not so clear is whether these quads should be assigned to the mesh which corresponds to the region in pink, or whether they should be assigned to the region to the right of it which is marked in blue in the diagram below: + /// + /// \image html CubicSurfaceExtractor3.png + /// + /// We could choose to add the quads to *both* regions, but this can cause confusion when one of the region is modified (causing the face to disappear or a new one to be created) as *both* regions need to have their mesh regenerated to correctly represent the new state of the volume data. Such pairs of coplanar quads can also cause problems with physics engines, and may prevent transparent voxels from rendering correctly. Therefore we choose to instead only add the quad to one of the the regions and we always choose the one with the greater coordinate value in the direction in which they differ. In the above example the regions differ by the 'x' component of their position, and so the quad is added to the region with the greater 'x' value (the one marked in blue). + /// + /// **Note:** *This behaviour has changed recently (September 2012). Earlier versions of PolyVox tried to be smart about this problem by looking beyond the region which was being processed, but this complicated the code and didn't work very well. Ultimatly we decided to simply stick with the convention outlined above.* + /// + /// One of the practical implications of this is that when you modify a voxel *you may have to re-extract the mesh for regions other than region which actually contains the voxel you modified.* This happens when the voxel lies on the upper x,y or z face of a region. Assuming that you have some management code which can mark a region as needing re-extraction when a voxel changes, you should probably extend this to mark the regions of neighbouring voxels as invalid (this will have no effect when the voxel is well within a region, but will mark the neighbouring region as needing an update if the voxel lies on a region face). + /// + /// Another scenario which sometimes results in confusion is when you wish to extract a region which corresponds to the whole volume, partcularly when solid voxels extend right to the edge of the volume. + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + template + Mesh > extractCubicMesh(VolumeType* volData, Region region, IsQuadNeeded isQuadNeeded, bool bMergeQuads) + { + Mesh< CubicVertex > result; + extractCubicMeshCustom(volData, region, &result, isQuadNeeded, bMergeQuads); + return result; + } + + /// This version of the function performs the extraction into a user-provided mesh rather than allocating a mesh automatically. + /// There are a few reasons why this might be useful to more advanced users: + /// + /// 1. It leaves the user in control of memory allocation and would allow them to implement e.g. a mesh pooling system. + /// 2. The user-provided mesh could have a different index type (e.g. 16-bit indices) to reduce memory usage. + /// 3. The user could provide a custom mesh class, e.g a thin wrapper around an openGL VBO to allow direct writing into this structure. + /// + /// We don't provide a default MeshType here. If the user doesn't want to provide a MeshType then it probably makes + /// more sense to use the other variant of this function where the mesh is a return value rather than a parameter. + /// + /// Note: This function is called 'extractCubicMeshCustom' rather than 'extractCubicMesh' to avoid ambiguity when only three parameters + /// are provided (would the third parameter be a controller or a mesh?). It seems this can be fixed by using enable_if/static_assert to emulate concepts, + /// but this is relatively complex and I haven't done it yet. Could always add it later as another overload. + template + void extractCubicMeshCustom(VolumeType* volData, Region region, MeshType* result, IsQuadNeeded isQuadNeeded, bool bMergeQuads) + { + // This extractor has a limit as to how large the extracted region can be, because the vertex positions are encoded with a single byte per component. + int32_t maxReionDimensionInVoxels = 255; + POLYVOX_THROW_IF(region.getWidthInVoxels() > maxReionDimensionInVoxels, std::invalid_argument, "Requested extraction region exceeds maximum dimensions"); + POLYVOX_THROW_IF(region.getHeightInVoxels() > maxReionDimensionInVoxels, std::invalid_argument, "Requested extraction region exceeds maximum dimensions"); + POLYVOX_THROW_IF(region.getDepthInVoxels() > maxReionDimensionInVoxels, std::invalid_argument, "Requested extraction region exceeds maximum dimensions"); + + Timer timer; + result->clear(); + + //Used to avoid creating duplicate vertices. + Array<3, IndexAndMaterial > m_previousSliceVertices(region.getUpperX() - region.getLowerX() + 2, region.getUpperY() - region.getLowerY() + 2, MaxVerticesPerPosition); + Array<3, IndexAndMaterial > m_currentSliceVertices(region.getUpperX() - region.getLowerX() + 2, region.getUpperY() - region.getLowerY() + 2, MaxVerticesPerPosition); + + //During extraction we create a number of different lists of quads. All the + //quads in a given list are in the same plane and facing in the same direction. + std::vector< std::list > m_vecQuads[NoOfFaces]; + + + memset(m_previousSliceVertices.getRawData(), 0xff, m_previousSliceVertices.getNoOfElements() * sizeof(IndexAndMaterial)); + memset(m_currentSliceVertices.getRawData(), 0xff, m_currentSliceVertices.getNoOfElements() * sizeof(IndexAndMaterial)); + + m_vecQuads[NegativeX].resize(region.getUpperX() - region.getLowerX() + 2); + m_vecQuads[PositiveX].resize(region.getUpperX() - region.getLowerX() + 2); + + m_vecQuads[NegativeY].resize(region.getUpperY() - region.getLowerY() + 2); + m_vecQuads[PositiveY].resize(region.getUpperY() - region.getLowerY() + 2); + + m_vecQuads[NegativeZ].resize(region.getUpperZ() - region.getLowerZ() + 2); + m_vecQuads[PositiveZ].resize(region.getUpperZ() - region.getLowerZ() + 2); + + typename VolumeType::Sampler volumeSampler(volData); + + for (int32_t z = region.getLowerZ(); z <= region.getUpperZ(); z++) + { + uint32_t regZ = z - region.getLowerZ(); + + for (int32_t y = region.getLowerY(); y <= region.getUpperY(); y++) + { + uint32_t regY = y - region.getLowerY(); + + volumeSampler.setPosition(region.getLowerX(), y, z); + + for (int32_t x = region.getLowerX(); x <= region.getUpperX(); x++) + { + uint32_t regX = x - region.getLowerX(); + + typename VolumeType::VoxelType material; //Filled in by callback + typename VolumeType::VoxelType currentVoxel = volumeSampler.getVoxel(); + typename VolumeType::VoxelType negXVoxel = volumeSampler.peekVoxel1nx0py0pz(); + typename VolumeType::VoxelType negYVoxel = volumeSampler.peekVoxel0px1ny0pz(); + typename VolumeType::VoxelType negZVoxel = volumeSampler.peekVoxel0px0py1nz(); + + // X + if (isQuadNeeded(currentVoxel, negXVoxel, material)) + { + uint32_t v0 = addVertex(regX, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v1 = addVertex(regX, regY, regZ + 1, material, m_currentSliceVertices, result); + uint32_t v2 = addVertex(regX, regY + 1, regZ + 1, material, m_currentSliceVertices, result); + uint32_t v3 = addVertex(regX, regY + 1, regZ, material, m_previousSliceVertices, result); + + m_vecQuads[NegativeX][regX].push_back(Quad(v0, v1, v2, v3)); + } + + if (isQuadNeeded(negXVoxel, currentVoxel, material)) + { + uint32_t v0 = addVertex(regX, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v1 = addVertex(regX, regY, regZ + 1, material, m_currentSliceVertices, result); + uint32_t v2 = addVertex(regX, regY + 1, regZ + 1, material, m_currentSliceVertices, result); + uint32_t v3 = addVertex(regX, regY + 1, regZ, material, m_previousSliceVertices, result); + + m_vecQuads[PositiveX][regX].push_back(Quad(v0, v3, v2, v1)); + } + + // Y + if (isQuadNeeded(currentVoxel, negYVoxel, material)) + { + uint32_t v0 = addVertex(regX, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v1 = addVertex(regX + 1, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v2 = addVertex(regX + 1, regY, regZ + 1, material, m_currentSliceVertices, result); + uint32_t v3 = addVertex(regX, regY, regZ + 1, material, m_currentSliceVertices, result); + + m_vecQuads[NegativeY][regY].push_back(Quad(v0, v1, v2, v3)); + } + + if (isQuadNeeded(negYVoxel, currentVoxel, material)) + { + uint32_t v0 = addVertex(regX, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v1 = addVertex(regX + 1, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v2 = addVertex(regX + 1, regY, regZ + 1, material, m_currentSliceVertices, result); + uint32_t v3 = addVertex(regX, regY, regZ + 1, material, m_currentSliceVertices, result); + + m_vecQuads[PositiveY][regY].push_back(Quad(v0, v3, v2, v1)); + } + + // Z + if (isQuadNeeded(currentVoxel, negZVoxel, material)) + { + uint32_t v0 = addVertex(regX, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v1 = addVertex(regX, regY + 1, regZ, material, m_previousSliceVertices, result); + uint32_t v2 = addVertex(regX + 1, regY + 1, regZ, material, m_previousSliceVertices, result); + uint32_t v3 = addVertex(regX + 1, regY, regZ, material, m_previousSliceVertices, result); + + m_vecQuads[NegativeZ][regZ].push_back(Quad(v0, v1, v2, v3)); + } + + if (isQuadNeeded(negZVoxel, currentVoxel, material)) + { + uint32_t v0 = addVertex(regX, regY, regZ, material, m_previousSliceVertices, result); + uint32_t v1 = addVertex(regX, regY + 1, regZ, material, m_previousSliceVertices, result); + uint32_t v2 = addVertex(regX + 1, regY + 1, regZ, material, m_previousSliceVertices, result); + uint32_t v3 = addVertex(regX + 1, regY, regZ, material, m_previousSliceVertices, result); + + m_vecQuads[PositiveZ][regZ].push_back(Quad(v0, v3, v2, v1)); + } + + volumeSampler.movePositiveX(); + } + } + + m_previousSliceVertices.swap(m_currentSliceVertices); + memset(m_currentSliceVertices.getRawData(), 0xff, m_currentSliceVertices.getNoOfElements() * sizeof(IndexAndMaterial)); + } + + for (uint32_t uFace = 0; uFace < NoOfFaces; uFace++) + { + std::vector< std::list >& vecListQuads = m_vecQuads[uFace]; + + for (uint32_t slice = 0; slice < vecListQuads.size(); slice++) + { + std::list& listQuads = vecListQuads[slice]; + + if (bMergeQuads) + { + //Repeatedly call this function until it returns + //false to indicate nothing more can be done. + while (performQuadMerging(listQuads, result)){} + } + + typename std::list::iterator iterEnd = listQuads.end(); + for (typename std::list::iterator quadIter = listQuads.begin(); quadIter != iterEnd; quadIter++) + { + Quad& quad = *quadIter; + result->addTriangle(quad.vertices[0], quad.vertices[1], quad.vertices[2]); + result->addTriangle(quad.vertices[0], quad.vertices[2], quad.vertices[3]); + } + } + } + + result->setOffset(region.getLowerCorner()); + result->removeUnusedVertices(); + + POLYVOX_LOG_TRACE("Cubic surface extraction took ", timer.elapsedTimeInMilliSeconds(), + "ms (Region size = ", m_regSizeInVoxels.getWidthInVoxels(), "x", m_regSizeInVoxels.getHeightInVoxels(), + "x", m_regSizeInVoxels.getDepthInVoxels(), ")"); + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/DefaultIsQuadNeeded.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/DefaultIsQuadNeeded.h new file mode 100644 index 0000000..d8b3dd3 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/DefaultIsQuadNeeded.h @@ -0,0 +1,62 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_DefaultIsQuadNeeded_H__ +#define __PolyVox_DefaultIsQuadNeeded_H__ + +#include "Impl/PlatformDefinitions.h" + +#include + +namespace PolyVox +{ + /// Default implementation of a function object for deciding when + /// the cubic surface extractor should insert a face between two voxels. + /// + /// The criteria used here are that the voxel in front of the potential + /// quad should have a value of zero (which would typically indicate empty + /// space) while the voxel behind the potential quad would have a value + /// geater than zero (typically indicating it is solid). Note that for + /// different behaviour users can create their own implementation and pass + /// it to extractCubicMesh(). + template + class DefaultIsQuadNeeded + { + public: + bool operator()(VoxelType back, VoxelType front, VoxelType& materialToUse) + { + if ((back > 0) && (front == 0)) + { + materialToUse = static_cast(back); + return true; + } + else + { + return false; + } + } + }; +} + +#endif //__PolyVox_DefaultIsQuadNeeded_H__ \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/DefaultMarchingCubesController.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/DefaultMarchingCubesController.h new file mode 100644 index 0000000..463f301 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/DefaultMarchingCubesController.h @@ -0,0 +1,154 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_MarchingCubesController_H__ +#define __PolyVox_MarchingCubesController_H__ + +#include "BaseVolume.h" + +#include + +namespace PolyVox +{ + /** + * This class provides a default implementation of a controller for the MarchingCubesSurfaceExtractor. It controls the behaviour of the + * MarchingCubesSurfaceExtractor and provides the required properties from the underlying voxel type. + * + * PolyVox does not enforce any requirements regarding what data must be present in a voxel, and instead allows any primitive or user-defined + * type to be used. However, the Marching Cubes algorithm does have some requirents about the underlying data in that conceptually it operates + * on a density field. In addition, the PolyVox implementation of the Marching Cubes algorithm also understands the idea of each voxel + * having a material which is copied into the vertex data. + * + * Because we want the MarchingCubesSurfaceExtractor to work on any voxel type, we use a Marching Cubes controller (passed as + * a parameter of the MarchingCubesSurfaceExtractor) to expose the required properties. This parameter defaults to the DefaultMarchingCubesController. + * The main implementation of this class is designed to work with primitives data types, and the class is also specialised for the Material, + * Density and MaterialdensityPair classes. + * + * If you create a custom class for your voxel data then you probably want to include a specialisation of DefaultMarchingCubesController, + * though you don't have to if you don't want to use the Marching Cubes algorithm or if you prefer to define a seperate Marching Cubes controller + * and pass it as an explicit parameter (rather than relying on the default). + * + * For primitive types, the DefaultMarchingCubesController considers the value of the voxel to represent it's density and just returns a constant + * for the material. So you can, for example, run the MarchingCubesSurfaceExtractor on a volume of floats or ints. + * + * It is possible to customise the behaviour of the controller by providing a threshold value through the constructor. The extracted surface + * will pass through the density value specified by the threshold, and so you should make sure that the threshold value you choose is between + * the minimum and maximum values found in your volume data. By default it is in the middle of the representable range of the underlying type. + * + * \sa extractMarchingCubesMesh + * + */ + template + class DefaultMarchingCubesController + { + public: + /// Used to inform the MarchingCubesSurfaceExtractor about which type it should use for representing densities. + typedef VoxelType DensityType; + /// Used to inform the MarchingCubesSurfaceExtractor about which type it should use for representing materials. + typedef VoxelType MaterialType; + + /** + * Constructor + * + * This version of the constructor takes no parameters and sets the threshold to the middle of the representable range of the underlying type. + * For example, if the voxel type is 'uint8_t' then the representable range is 0-255, and the threshold will be set to 127. On the other hand, + * if the voxel type is 'float' then the representable range is -FLT_MAX to FLT_MAX and the threshold will be set to zero. + */ + DefaultMarchingCubesController(void) + { + if (std::is_signed()) + { + m_tThreshold = DensityType(0); + } + else + { + m_tThreshold = (((std::numeric_limits::min)() + (std::numeric_limits::max)()) / 2); + } + } + + /** + * Converts the underlying voxel type into a density value. + * + * The default implementation of this function just returns the voxel type directly and is suitable for primitives types. Specialisations of + * this class can modify this behaviour. + */ + DensityType convertToDensity(VoxelType voxel) + { + return voxel; + } + + /** + * Converts the underlying voxel type into a material value. + * + * The default implementation of this function just returns the constant '1'. There's not much else it can do, as it needs to work with primitive + * types and the actual value of the type is already being considered to be the density. Specialisations of this class can modify this behaviour. + */ + MaterialType convertToMaterial(VoxelType /*voxel*/) + { + return 1; + } + + /** + * Returns a material which is in some sense a weighted combination of the supplied materials. + * + * The Marching Cubes algotithm generates vertices which lie between voxels, and ideally the material of the vertex should be interpolated from the materials + * of the voxels. In practice, that material type is often an integer identifier (e.g. 1 = rock, 2 = soil, 3 = grass) and an interpolation doean't make sense + * (e.g. soil is not a combination or rock and grass). Therefore this default interpolation just returns whichever material is associated with a voxel of the + * higher density, but if more advanced voxel types do support interpolation then it can be implemented in this function. + */ + MaterialType blendMaterials(VoxelType a, VoxelType b, float /*weight*/) + { + if (convertToDensity(a) > convertToDensity(b)) + { + return convertToMaterial(a); + } + else + { + return convertToMaterial(b); + } + } + + /** + * Returns the density value which was passed to the constructor. + * + * As mentioned in the class description, the extracted surface will pass through the density value specified by the threshold, and so you + * should make sure that the threshold value you choose is between the minimum and maximum values found in your volume data. By default it + * is in the middle of the representable range of the underlying type. + */ + DensityType getThreshold(void) + { + return m_tThreshold; + } + + void setThreshold(DensityType tThreshold) + { + m_tThreshold = tThreshold; + } + + private: + DensityType m_tThreshold; + }; +} + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Density.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Density.h new file mode 100644 index 0000000..9a7a3fe --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Density.h @@ -0,0 +1,196 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Density_H__ +#define __PolyVox_Density_H__ + +#include "DefaultMarchingCubesController.h" //We'll specialise the controller contained in here + +#include "Impl/PlatformDefinitions.h" + +#include + +#undef min +#undef max + +namespace PolyVox +{ + /// This class represents a voxel storing only a density. + //////////////////////////////////////////////////////////////////////////////// + /// Note that this should probably just be considered an example of how to define + /// a voxel type for the Marching Cubes algorithm. Advanced users are likely to + /// define custom voxel types and possibly custom controllers. + /// + /// \sa Material, MaterialDensityPair + //////////////////////////////////////////////////////////////////////////////// + template + class Density + { + public: + /// Constructor + Density() : m_uDensity(0) {} + + /// Copy constructor + Density(Type uDensity) : m_uDensity(uDensity) {} + + // The LowPassFilter uses this to convert between normal and accumulated types. + /// Copy constructor with cast + template explicit Density(const Density& density) + { + m_uDensity = static_cast(density.getDensity()); + } + + bool operator==(const Density& rhs) const + { + return (m_uDensity == rhs.m_uDensity); + }; + + bool operator!=(const Density& rhs) const + { + return !(*this == rhs); + } + + // For densities we can supply mathematical operators which behave in an intuitive way. + // In particular the ability to add and subtract densities is important in order to + // apply an averaging filter. The ability to divide by an integer is also needed for + // this same purpose. + Density& operator+=(const Density& rhs) + { + m_uDensity += rhs.m_uDensity; + return *this; + } + + Density& operator-=(const Density& rhs) + { + m_uDensity -= rhs.m_uDensity; + return *this; + } + + Density& operator/=(uint32_t rhs) + { + m_uDensity /= rhs; + return *this; + } + + /// \return The current density of the voxel + Type getDensity() const { return m_uDensity; } + /** + * Set the density of the voxel + * + * \param uDensity The density to set to + */ + void setDensity(Type uDensity) { m_uDensity = uDensity; } + + /// \return The maximum allowed density of the voxel + static Type getMaxDensity() { return (std::numeric_limits::max)(); } + /// \return The minimum allowed density of the voxel + static Type getMinDensity() { return (std::numeric_limits::min)(); } + + private: + Type m_uDensity; + }; + + template + Density operator+(const Density& lhs, const Density& rhs) + { + Density result = lhs; + result += rhs; + return result; + } + + template + Density operator-(const Density& lhs, const Density& rhs) + { + Density result = lhs; + result -= rhs; + return result; + } + + template + Density operator/(const Density& lhs, uint32_t rhs) + { + Density result = lhs; + result /= rhs; + return result; + } + + // These are the predefined density types. The 8-bit types are sufficient for many purposes (including + // most games) but 16-bit and float types do have uses particularly in medical/scientific visualisation. + typedef Density Density8; + typedef Density Density16; + typedef Density Density32; + typedef Density DensityFloat; + + /** + * This is a specialisation of DefaultMarchingCubesController for the Density voxel type + */ + template + class DefaultMarchingCubesController< Density > + { + public: + typedef Type DensityType; + typedef float MaterialType; + + DefaultMarchingCubesController(void) + { + // Default to a threshold value halfway between the min and max possible values. + m_tThreshold = (Density::getMinDensity() + Density::getMaxDensity()) / 2; + } + + DefaultMarchingCubesController(DensityType tThreshold) + { + m_tThreshold = tThreshold; + } + + DensityType convertToDensity(Density voxel) + { + return voxel.getDensity(); + } + + MaterialType convertToMaterial(Density /*voxel*/) + { + return 1; + } + + MaterialType blendMaterials(Density /*a*/, Density /*b*/, float /*weight*/) + { + return 1; + } + + DensityType getThreshold(void) + { + return m_tThreshold; + } + + void setThreshold(DensityType tThreshold) + { + m_tThreshold = tThreshold; + } + + private: + DensityType m_tThreshold; + }; +} + +#endif //__PolyVox_Density_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Exceptions.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Exceptions.h new file mode 100644 index 0000000..d8dd383 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Exceptions.h @@ -0,0 +1,62 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Exceptions_H__ +#define __PolyVox_Exceptions_H__ + +#include // For base exception classes. +#include // Exception constuctors take strings. + +// These exceptions form part of the public API because client code may need to catch them. +// Note that our utility macros such as 'POLYVOX_THROW_IF' do not form part of the public API +// as they are only for our own internal use. +namespace PolyVox +{ + /// A general purpose exception to indicate that an operation cannot be peformed. + class invalid_operation : public std::logic_error + { + public: + explicit invalid_operation(const std::string& message) + : logic_error(message.c_str()) {} + + explicit invalid_operation(const char *message) + : logic_error(message) {} + }; + + /// Thrown to indicate that a function is deliberatly not implmented. For example, perhaps you called a function + /// in a base class whereas you are supposed to use a derived class which implements the function, or perhaps the + /// function is not defined for a particular template parameter. It may be that the function is required to + /// compile sucessfully but it should not be called. + class not_implemented : public std::logic_error + { + public: + explicit not_implemented(const std::string& message) + : logic_error(message.c_str()) {} + + explicit not_implemented(const char *message) + : logic_error(message) {} + }; +} + +#endif //__PolyVox_Exceptions_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/FilePager.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/FilePager.h new file mode 100644 index 0000000..03b254b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/FilePager.h @@ -0,0 +1,179 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_FilePager_H__ +#define __PolyVox_FilePager_H__ + +#include "Impl/PlatformDefinitions.h" + +#include "PagedVolume.h" +#include "Region.h" + +#include +#include +#include +#include +#include +#include + +namespace PolyVox +{ + /** + * An implementation of Pager which stores voxels to files on disk. Each chunk is written + * to a seperate file and you can specify the name of a folder where these will be stored. + * + * Note that no compression is performed (mostly to avoid dependancies) so for large + * volumes you may want to consider this class as an example and create a custom version + * with compression. + */ + template + class FilePager : public PagedVolume::Pager + { + public: + /// Constructor + FilePager(const std::string& strFolderName = ".") + :PagedVolume::Pager() + , m_strFolderName(strFolderName) + { + // Add the trailing slash, assuming the user dind't already do it. + if ((m_strFolderName.back() != '/') && (m_strFolderName.back() != '\\')) + { + m_strFolderName.append("/"); + } + + // Build a unique postfix to avoid filename conflicts between multiple pagers/runs. + // Not a very robust solution but this class is meant as an example for testing really. + std::stringstream ss; + ss << time(0) << "--"; // Avoid multiple runs using the same filenames. + ss << this; // Avoid multiple FilePagers using the same filenames. + m_strPostfix = ss.str(); + } + + /// Destructor + virtual ~FilePager() + { + for (std::vector::iterator iter = m_vecCreatedFiles.begin(); iter < m_vecCreatedFiles.end(); iter++) + { + POLYVOX_LOG_WARNING_IF(std::remove(iter->c_str()) != 0, "Failed to delete '", *iter, "' when destroying FilePager"); + } + + m_vecCreatedFiles.clear(); + } + + virtual void pageIn(const Region& region, typename PagedVolume::Chunk* pChunk) + { + POLYVOX_ASSERT(pChunk, "Attempting to page in NULL chunk"); + POLYVOX_ASSERT(pChunk->getData(), "Chunk must have valid data"); + + std::stringstream ssFilename; + ssFilename << m_strFolderName << "/" + << region.getLowerX() << "_" << region.getLowerY() << "_" << region.getLowerZ() << "_" + << region.getUpperX() << "_" << region.getUpperY() << "_" << region.getUpperZ() + << "--" << m_strPostfix; + + std::string filename = ssFilename.str(); + + // FIXME - This should be replaced by C++ style IO, but currently this causes problems with + // the gameplay-cubiquity integration. See: https://github.com/blackberry/GamePlay/issues/919 + + FILE* pFile = fopen(filename.c_str(), "rb"); + if (pFile) + { + POLYVOX_LOG_TRACE("Paging in data for ", region); + + /*fseek(pFile, 0L, SEEK_END); + size_t fileSizeInBytes = ftell(pFile); + fseek(pFile, 0L, SEEK_SET); + + uint8_t* buffer = new uint8_t[fileSizeInBytes]; + fread(buffer, sizeof(uint8_t), fileSizeInBytes, pFile); + pChunk->setData(buffer, fileSizeInBytes); + delete[] buffer;*/ + + fread(pChunk->getData(), sizeof(uint8_t), pChunk->getDataSizeInBytes(), pFile); + + if (ferror(pFile)) + { + POLYVOX_THROW(std::runtime_error, "Error reading in chunk data, even though a file exists."); + } + + fclose(pFile); + } + else + { + POLYVOX_LOG_TRACE("No data found for ", region, " during paging in."); + + // Just fill with zeros. This feels hacky... perhaps we should just throw + // an exception and let the calling code handle it and fill with zeros. + uint32_t noOfVoxels = region.getWidthInVoxels() * region.getHeightInVoxels() * region.getDepthInVoxels(); + std::fill(pChunk->getData(), pChunk->getData() + noOfVoxels, VoxelType()); + } + } + + virtual void pageOut(const Region& region, typename PagedVolume::Chunk* pChunk) + { + POLYVOX_ASSERT(pChunk, "Attempting to page out NULL chunk"); + POLYVOX_ASSERT(pChunk->getData(), "Chunk must have valid data"); + + POLYVOX_LOG_TRACE("Paging out data for ", region); + + std::stringstream ssFilename; + ssFilename << m_strFolderName << "/" + << region.getLowerX() << "_" << region.getLowerY() << "_" << region.getLowerZ() << "_" + << region.getUpperX() << "_" << region.getUpperY() << "_" << region.getUpperZ() + << "--" << m_strPostfix; + + std::string filename = ssFilename.str(); + + // FIXME - This should be replaced by C++ style IO, but currently this causes problems with + // the gameplay-cubiquity integration. See: https://github.com/blackberry/GamePlay/issues/919 + + FILE* pFile = fopen(filename.c_str(), "wb"); + if (!pFile) + { + POLYVOX_THROW(std::runtime_error, "Unable to open file to write out chunk data."); + } + + //The file has been created, so add it to the list to delete on shutdown. + m_vecCreatedFiles.push_back(filename); + + fwrite(pChunk->getData(), sizeof(uint8_t), pChunk->getDataSizeInBytes(), pFile); + + if (ferror(pFile)) + { + POLYVOX_THROW(std::runtime_error, "Error writing out chunk data."); + } + + fclose(pFile); + } + + protected: + std::string m_strFolderName; + std::string m_strPostfix; + + std::vector m_vecCreatedFiles; + }; +} + +#endif //__PolyVox_FilePager_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/AStarPathfinderImpl.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/AStarPathfinderImpl.h new file mode 100644 index 0000000..611c33b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/AStarPathfinderImpl.h @@ -0,0 +1,223 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_AStarPathfinderImpl_H__ +#define __PolyVox_AStarPathfinderImpl_H__ + +#include "../Vector.h" + +#include +#include //For numeric_limits +#include +#include + +namespace PolyVox +{ + class OpenNodesContainer; + class ClosedNodesContainer; + + /// The Connectivity of a voxel determines how many neighbours it has. + enum Connectivity + { + /// Each voxel has six neighbours, which are those sharing a face. + SixConnected, + /// Each voxel has 18 neighbours, which are those sharing a face or an edge. + EighteenConnected, + /// Each voxel has 26 neighbours, which are those sharing a face, edge, or corner. + TwentySixConnected + }; + + struct Node + { + Node(int x, int y, int z) + :gVal(std::numeric_limits::quiet_NaN()) //Initilise with NaNs so that we will + , hVal(std::numeric_limits::quiet_NaN()) //know if we forget to set these properly. + , parent(0) + { + position.setX(x); + position.setY(y); + position.setZ(z); + } + + bool operator==(const Node& rhs) const + { + return position == rhs.position; + } + + bool operator<(const Node& rhs) const + { + if (position.getX() < rhs.position.getX()) + return true; + if (rhs.position.getX() < position.getX()) + return false; + + if (position.getY() < rhs.position.getY()) + return true; + if (rhs.position.getY() < position.getY()) + return false; + + if (position.getZ() < rhs.position.getZ()) + return true; + if (rhs.position.getZ() < position.getZ()) + return false; + + return false; + } + + PolyVox::Vector3DInt32 position; + float gVal; + float hVal; + Node* parent; + + float f(void) const + { + return gVal + hVal; + } + }; + + typedef std::set AllNodesContainer; + + class AllNodesContainerIteratorComparator + { + public: + bool operator() (const AllNodesContainer::iterator& lhs, const AllNodesContainer::iterator& rhs) const + { + return (&(*lhs)) < (&(*rhs)); + } + }; + + class NodeSort + { + public: + bool operator() (const AllNodesContainer::iterator& lhs, const AllNodesContainer::iterator& rhs) const + { + return lhs->f() > rhs->f(); + } + }; + + class OpenNodesContainer + { + public: + typedef std::vector::iterator iterator; + + public: + void clear(void) + { + open.clear(); + } + + bool empty(void) const + { + return open.empty(); + } + + void insert(AllNodesContainer::iterator node) + { + open.push_back(node); + push_heap(open.begin(), open.end(), NodeSort()); + } + + AllNodesContainer::iterator getFirst(void) + { + return open[0]; + } + + void removeFirst(void) + { + pop_heap(open.begin(), open.end(), NodeSort()); + open.pop_back(); + } + + void remove(iterator iterToRemove) + { + open.erase(iterToRemove); + make_heap(open.begin(), open.end(), NodeSort()); + } + + iterator begin(void) + { + return open.begin(); + } + + iterator end(void) + { + return open.end(); + } + + iterator find(AllNodesContainer::iterator node) + { + std::vector::iterator openIter = std::find(open.begin(), open.end(), node); + return openIter; + } + + private: + std::vector open; + }; + + class ClosedNodesContainer + { + public: + typedef std::set::iterator iterator; + + public: + void clear(void) + { + closed.clear(); + } + + void insert(AllNodesContainer::iterator node) + { + closed.insert(node); + } + + void remove(iterator iterToRemove) + { + closed.erase(iterToRemove); + } + + iterator begin(void) + { + return closed.begin(); + } + + iterator end(void) + { + return closed.end(); + } + + iterator find(AllNodesContainer::iterator node) + { + iterator iter = std::find(closed.begin(), closed.end(), node); + return iter; + } + + private: + std::set closed; + }; + + + //bool operator<(const AllNodesContainer::iterator& lhs, const AllNodesContainer::iterator& rhs); +} + +#endif //__PolyVox_AStarPathfinderImpl_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Assertions.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Assertions.h new file mode 100644 index 0000000..9e8ad4b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Assertions.h @@ -0,0 +1,76 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Assertions_H__ +#define __PolyVox_Assertions_H__ + +#include "../Config.h" + +#include "LoggingImpl.h" // Asserts can log when they fire. +#include "PlatformDefinitions.h" + +// The code below implements a custom assert function called POLYVOX_ASSERT which has a number of advantages compared +// to the standard C/C++ assert(). It is inspired by http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ +// which provides code under the MIT license. + +#ifdef POLYVOX_ASSERTS_ENABLED + + #define POLYVOX_ASSERT(condition, message) \ + /* We use the do...while(0) construct in our macros (for reasons see here: http://stackoverflow.com/a/154138) \ + but Visual Studio gives unhelpful 'conditional expression is constant' warnings. The recommended solution \ + (http://stackoverflow.com/a/1946485) is to disable these warnings. */ \ + POLYVOX_MSC_WARNING_PUSH \ + POLYVOX_DISABLE_MSC_WARNING(4127) \ + do \ + { \ + if (!(condition)) \ + { \ + std::stringstream ss; \ + ss << "\n"; \ + ss << " PolyVox Assertion Failed!"; \ + ss << " ========================="; \ + ss << " Condition: " << #condition; \ + ss << " Message: " << (message); \ + ss << " Location: " << "Line " << __LINE__ << " of " << __FILE__; \ + ss << "\n"; \ + PolyVox::getLoggerInstance()->logFatalMessage(ss.str()); \ + POLYVOX_HALT(); \ + } \ + } while(0) \ + POLYVOX_MSC_WARNING_POP + +#else + + #define POLYVOX_ASSERT(condition, message) \ + /* We use the do...while(0) construct in our macros (for reasons see here: http://stackoverflow.com/a/154138) \ + but Visual Studio gives unhelpful 'conditional expression is constant' warnings. The recommended solution \ + (http://stackoverflow.com/a/1946485) is to disable these warnings. */ \ + POLYVOX_MSC_WARNING_PUSH \ + POLYVOX_DISABLE_MSC_WARNING(4127) \ + do { POLYVOX_UNUSED(condition); POLYVOX_UNUSED(message); } while(0) \ + POLYVOX_MSC_WARNING_POP + +#endif + +#endif //__PolyVox_Assertions_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/ErrorHandling.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/ErrorHandling.h new file mode 100644 index 0000000..9035324 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/ErrorHandling.h @@ -0,0 +1,33 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +// This file provides a simple way to include all error-handling functionality. +#ifndef __PolyVox_ErrorHandling_H__ +#define __PolyVox_ErrorHandling_H__ + +#include "Assertions.h" +#include "ExceptionsImpl.h" +#include "LoggingImpl.h" + +#endif //__PolyVox_ErrorHandling_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/ExceptionsImpl.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/ExceptionsImpl.h new file mode 100644 index 0000000..5662a21 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/ExceptionsImpl.h @@ -0,0 +1,155 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_ExceptionsImpl_H__ +#define __PolyVox_ExceptionsImpl_H__ + +#include "../Config.h" +#include "../Exceptions.h" + +#include "LoggingImpl.h" // Exceptions can log when they are thrown. + +#include // For std::exit +#include // For std::cerr +#include +#include + +#ifdef POLYVOX_THROW_ENABLED + + namespace PolyVox + { + namespace Impl + { + template< typename ExceptionType, typename ... Args > + void polyvox_throw(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); +#ifdef POLYVOX_LOG_ERROR_ENABLED + getLoggerInstance()->logErrorMessage(message); +#endif + throw ExceptionType(message); + } + + template< typename ExceptionType, typename ... Args > + void polyvox_throw_if(bool condition, Args const& ... messageArgs) + { + if (condition) { polyvox_throw(messageArgs...); } + } + } + } + + #define POLYVOX_THROW(type, ...) PolyVox::Impl::polyvox_throw(__VA_ARGS__) + #define POLYVOX_THROW_IF(condition, type, ...) PolyVox::Impl::polyvox_throw_if(condition, __VA_ARGS__) + +#else + + // This stuff should possibly be in the 'Impl' namespace, but it may be complex and it's not + // clear if this ability to disable throwing of exceptions is useful in the long term anyway. + namespace PolyVox + { + typedef void(*ThrowHandler)(std::exception& e, const char* file, int line); + + inline void defaultThrowHandler(std::exception& e, const char* file, int line) + { + std::stringstream ss; \ + ss << "\n"; \ + ss << " PolyVox exception thrown!"; \ + ss << " ========================="; \ + ss << " PolyVox has tried to throw an exception but it was built without support"; \ + ss << " for exceptions. In this scenario PolyVox will call a 'throw handler'"; \ + ss << " and this message is being printed by the default throw handler."; \ + ss << "\n"; \ + ss << " If you don't want to enable exceptions then you should try to determine why"; \ + ss << " this exception was thrown and make sure it doesn't happen again. If it was"; \ + ss << " due to something like an invalid argument to a function then you should be"; \ + ss << " able to fix it quite easily by validating parameters as appropriate. More"; \ + ss << " complex exception scenarios (out of memory, etc) might be harder to fix and"; \ + ss << " you should replace this default handler with something which is more"; \ + ss << " meaningful to your users."; \ + ss << "\n"; \ + ss << " Exception details"; \ + ss << " -----------------"; \ + ss << " Line: " << line; \ + ss << " File: " << file; \ + ss << " Message: " << e.what(); \ + ss << "\n"; \ + PolyVox::Impl::getLoggerInstance()->logFatalMessage(ss.str()); \ + POLYVOX_HALT(); \ + } + + inline ThrowHandler& getThrowHandlerInstance() + { + static ThrowHandler s_fThrowHandler = &defaultThrowHandler; + return s_fThrowHandler; + } + + inline ThrowHandler getThrowHandler() + { + return getThrowHandlerInstance(); + } + + inline void setThrowHandler(ThrowHandler fNewHandler) + { + getThrowHandlerInstance() = fNewHandler; + } + } + + #define POLYVOX_THROW_IF(condition, type, message) \ + /* We use the do...while(0) construct in our macros (for reasons see here: http://stackoverflow.com/a/154138) \ + but Visual Studio gives unhelpful 'conditional expression is constant' warnings. The recommended solution \ + (http://stackoverflow.com/a/1946485) is to disable these warnings. */ \ + POLYVOX_MSC_WARNING_PUSH \ + POLYVOX_DISABLE_MSC_WARNING(4127) \ + do \ + { \ + if ((condition)) \ + { \ + std::stringstream ss; \ + ss << message; \ + PolyVox::Impl::getLoggerInstance()->logErrorMessage(ss.str()); \ + type except = (type)(ss.str()); \ + getThrowHandler()((except), __FILE__, __LINE__); \ + } \ + } while(0) \ + POLYVOX_MSC_WARNING_POP + + #define POLYVOX_THROW(type, message) \ + /* We use the do...while(0) construct in our macros (for reasons see here: http://stackoverflow.com/a/154138) \ + but Visual Studio gives unhelpful 'conditional expression is constant' warnings. The recommended solution \ + (http://stackoverflow.com/a/1946485) is to disable these warnings. */ \ + POLYVOX_MSC_WARNING_PUSH \ + POLYVOX_DISABLE_MSC_WARNING(4127) \ + do \ + { \ + std::stringstream ss; \ + ss << message; \ + PolyVox::Impl::getLoggerInstance()->logErrorMessage(ss.str()); \ + type except = (type)(ss.str()); \ + getThrowHandler()((except), __FILE__, __LINE__); \ + } while(0) \ + POLYVOX_MSC_WARNING_POP + +#endif + +#endif //__PolyVox_ExceptionsImpl_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Interpolation.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Interpolation.h new file mode 100644 index 0000000..c01865e --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Interpolation.h @@ -0,0 +1,73 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Interpolation_H__ +#define __PolyVox_Interpolation_H__ + +namespace PolyVox +{ + template + Type lerp( + const Type& v0, const Type& v1, + const float x) + { + //Interpolate along X + Type v0_1 = (v1 - v0) * x + v0; + + return v0_1; + } + + template + Type bilerp( + const Type& v00, const Type& v10, const Type& v01, const Type& v11, + const float x, const float y) + { + // Linearly interpolate along x + Type v00_10 = lerp(v00, v10, x); + Type v01_11 = lerp(v01, v11, x); + + // And linearly interpolate the results along y + Type v00_10__v01_11 = lerp(v00_10, v01_11, y); + + return v00_10__v01_11; + } + + template + Type trilerp( + const Type& v000, const Type& v100, const Type& v010, const Type& v110, + const Type& v001, const Type& v101, const Type& v011, const Type& v111, + const float x, const float y, const float z) + { + // Bilinearly interpolate along Y + Type v000_v100__v010_v110 = bilerp(v000, v100, v010, v110, x, y); + Type v001_v101__v011_v111 = bilerp(v001, v101, v011, v111, x, y); + + // And linearly interpolate the results along z + Type v000_v100__v010_v110____v001_v101__v011_v111 = lerp(v000_v100__v010_v110, v001_v101__v011_v111, z); + + return v000_v100__v010_v110____v001_v101__v011_v111; + } +} + +#endif //__PolyVox_Interpolation_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/IteratorController.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/IteratorController.h new file mode 100644 index 0000000..4dd83e0 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/IteratorController.h @@ -0,0 +1,48 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_IteratorController_H__ +#define __PolyVox_IteratorController_H__ + +#include "../Region.h" + +namespace PolyVox +{ + /// Unfinished class/feature, not appropriate for end user at the moment. + template + class IteratorController + { + public: + void reset(void); + bool moveForward(void); + + public: + Region m_regValid; + IteratorType* m_Iter; + }; +} + +#include "IteratorController.inl" + +#endif //__PolyVox_IteratorController_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/IteratorController.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/IteratorController.inl new file mode 100644 index 0000000..b3d01db --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/IteratorController.inl @@ -0,0 +1,64 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + template + void IteratorController::reset(void) + { + m_Iter->setPosition(m_regValid.getLowerCorner()); + } + + template + bool IteratorController::moveForward(void) + { + Vector3DInt32 v3dInitialPosition(m_Iter->getPosition().getX(), m_Iter->getPosition().getY(), m_Iter->getPosition().getZ()); + + if (v3dInitialPosition.getX() < m_regValid.getUpperX()) + { + m_Iter->movePositiveX(); + return true; + } + + v3dInitialPosition.setX(m_regValid.getLowerX()); + + if (v3dInitialPosition.getY() < m_regValid.getUpperY()) + { + v3dInitialPosition.setY(v3dInitialPosition.getY() + 1); + m_Iter->setPosition(v3dInitialPosition); + return true; + } + + v3dInitialPosition.setY(m_regValid.getLowerY()); + + if (v3dInitialPosition.getZ() < m_regValid.getUpperZ()) + { + v3dInitialPosition.setZ(v3dInitialPosition.getZ() + 1); + m_Iter->setPosition(v3dInitialPosition); + return true; + } + + return false; + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/LoggingImpl.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/LoggingImpl.h new file mode 100644 index 0000000..7a1401b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/LoggingImpl.h @@ -0,0 +1,182 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_LoggingImpl_H__ +#define __PolyVox_LoggingImpl_H__ + +#include "../Config.h" +#include "../Logging.h" + +#include + +namespace PolyVox +{ + namespace Impl + { + // Used for building the log messages - convert a list of variables into a string. + // Based on second approach here: http://stackoverflow.com/a/25386444/2337254 + template< typename ... Args > + std::string argListToString(const Args& ... args) + { + std::ostringstream oss; + int a[] = { 0, ((void)(oss << args), 0) ... }; + (void)a; // POLYVOX_UNUSED() doesn't seem to work here? + return oss.str(); + } + + // Log trace message + template< typename ... Args > + void logTraceMessage(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); + getLoggerInstance()->logTraceMessage(message); + } + + template< typename ... Args > + void logTraceMessageIf(bool condition, Args const& ... messageArgs) + { + if (condition) { logTraceMessage(messageArgs...); } + } + + // Log debug message + template< typename ... Args > + void logDebugMessage(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); + getLoggerInstance()->logDebugMessage(message); + } + + template< typename ... Args > + void logDebugMessageIf(bool condition, Args const& ... messageArgs) + { + if (condition) { logDebugMessage(messageArgs...); } + } + + // Log info message + template< typename ... Args > + void logInfoMessage(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); + getLoggerInstance()->logInfoMessage(message); + } + + template< typename ... Args > + void logInfoMessageIf(bool condition, Args const& ... messageArgs) + { + if (condition) { logInfoMessage(messageArgs...); } + } + + // Log warning message + template< typename ... Args > + void logWarningMessage(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); + getLoggerInstance()->logWarningMessage(message); + } + + template< typename ... Args > + void logWarningMessageIf(bool condition, Args const& ... messageArgs) + { + if (condition) { logWarningMessage(messageArgs...); } + } + + // Log error message + template< typename ... Args > + void logErrorMessage(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); + getLoggerInstance()->logErrorMessage(message); + } + + template< typename ... Args > + void logErrorMessageIf(bool condition, Args const& ... messageArgs) + { + if (condition) { logErrorMessage(messageArgs...); } + } + + // Log fatal message + template< typename ... Args > + void logFatalMessage(Args const& ... messageArgs) + { + std::string message = argListToString(messageArgs...); + getLoggerInstance()->logFatalMessage(message); + } + + template< typename ... Args > + void logFatalMessageIf(bool condition, Args const& ... messageArgs) + { + if (condition) { logFatalMessage(messageArgs...); } + } + } +} + +#ifdef POLYVOX_LOG_TRACE_ENABLED +#define POLYVOX_LOG_TRACE(...) PolyVox::Impl::logTraceMessage(__VA_ARGS__) + #define POLYVOX_LOG_TRACE_IF(condition, ...) PolyVox::Impl::logTraceMessageIf(condition, __VA_ARGS__) +#else + #define POLYVOX_LOG_TRACE(...) + #define POLYVOX_LOG_TRACE_IF(condition, ...) +#endif + +#ifdef POLYVOX_LOG_DEBUG_ENABLED +#define POLYVOX_LOG_DEBUG(...) PolyVox::Impl::logDebugMessage(__VA_ARGS__) +#define POLYVOX_LOG_DEBUG_IF(condition, ...) PolyVox::Impl::logDebugMessageIf(condition, __VA_ARGS__) +#else + #define POLYVOX_LOG_DEBUG(...) + #define POLYVOX_LOG_DEBUG_IF(condition, ...) +#endif + +#ifdef POLYVOX_LOG_INFO_ENABLED +#define POLYVOX_LOG_INFO(...) PolyVox::Impl::logInfoMessage(__VA_ARGS__) +#define POLYVOX_LOG_INFO_IF(condition, ...) PolyVox::Impl::logInfoMessageIf(condition, __VA_ARGS__) +#else + #define POLYVOX_LOG_INFO(...) + #define POLYVOX_LOG_INFO_IF(condition, ...) +#endif + +#ifdef POLYVOX_LOG_WARNING_ENABLED +#define POLYVOX_LOG_WARNING(...) PolyVox::Impl::logWarningMessage(__VA_ARGS__) +#define POLYVOX_LOG_WARNING_IF(condition, ...) PolyVox::Impl::logWarningMessageIf(condition, __VA_ARGS__) +#else + #define POLYVOX_LOG_WARNING(...) + #define POLYVOX_LOG_WARNING_IF(condition, ...) +#endif + +#ifdef POLYVOX_LOG_ERROR_ENABLED +#define POLYVOX_LOG_ERROR(...) PolyVox::Impl::logErrorMessage(__VA_ARGS__) +#define POLYVOX_LOG_ERROR_IF(condition, ...) PolyVox::Impl::logErrorMessageIf(condition, __VA_ARGS__) +#else + #define POLYVOX_LOG_ERROR(...) + #define POLYVOX_LOG_ERROR_IF(condition, ...) +#endif + +#ifdef POLYVOX_LOG_FATAL_ENABLED +#define POLYVOX_LOG_FATAL(...) PolyVox::Impl::logFatalMessage(__VA_ARGS__) +#define POLYVOX_LOG_FATAL_IF(condition, ...) PolyVox::Impl::logFatalMessageIf(condition, __VA_ARGS__) +#else + #define POLYVOX_LOG_FATAL(...) + #define POLYVOX_LOG_FATAL_IF(condition, ...) +#endif + +#endif //__PolyVox_LoggingImpl_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/MarchingCubesTables.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/MarchingCubesTables.h new file mode 100644 index 0000000..fb7039b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/MarchingCubesTables.h @@ -0,0 +1,336 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_MarchingCubeTables_H__ +#define __PolyVox_MarchingCubeTables_H__ + +#include "PlatformDefinitions.h" + +#include + +namespace PolyVox +{ + //These tables were based on the article "Polygonising a scalar field". + //They have been optimised to allow a more efficient algorithm via bitwise operations. + + // http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/index.html + + const uint16_t edgeTable[256] = + { + 0x000, 0x109, 0x203, 0x30a, 0x80c, 0x905, 0xa0f, 0xb06, + 0x406, 0x50f, 0x605, 0x70c, 0xc0a, 0xd03, 0xe09, 0xf00, + 0x190, 0x099, 0x393, 0x29a, 0x99c, 0x895, 0xb9f, 0xa96, + 0x596, 0x49f, 0x795, 0x69c, 0xd9a, 0xc93, 0xf99, 0xe90, + 0x230, 0x339, 0x033, 0x13a, 0xa3c, 0xb35, 0x83f, 0x936, + 0x636, 0x73f, 0x435, 0x53c, 0xe3a, 0xf33, 0xc39, 0xd30, + 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0xbac, 0xaa5, 0x9af, 0x8a6, + 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xfaa, 0xea3, 0xda9, 0xca0, + 0x8c0, 0x9c9, 0xac3, 0xbca, 0x0cc, 0x1c5, 0x2cf, 0x3c6, + 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x4ca, 0x5c3, 0x6c9, 0x7c0, + 0x950, 0x859, 0xb53, 0xa5a, 0x15c, 0x055, 0x35f, 0x256, + 0xd56, 0xc5f, 0xf55, 0xe5c, 0x55a, 0x453, 0x759, 0x650, + 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0x2fc, 0x3f5, 0x0ff, 0x1f6, + 0xef6, 0xfff, 0xcf5, 0xdfc, 0x6fa, 0x7f3, 0x4f9, 0x5f0, + 0xb60, 0xa69, 0x963, 0x86a, 0x36c, 0x265, 0x16f, 0x066, + 0xf66, 0xe6f, 0xd65, 0xc6c, 0x76a, 0x663, 0x569, 0x460, + 0x460, 0x569, 0x663, 0x76a, 0xc6c, 0xd65, 0xe6f, 0xf66, + 0x066, 0x16f, 0x265, 0x36c, 0x86a, 0x963, 0xa69, 0xb60, + 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0xdfc, 0xcf5, 0xfff, 0xef6, + 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0x9fa, 0x8f3, 0xbf9, 0xaf0, + 0x650, 0x759, 0x453, 0x55a, 0xe5c, 0xf55, 0xc5f, 0xd56, + 0x256, 0x35f, 0x055, 0x15c, 0xa5a, 0xb53, 0x859, 0x950, + 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0xfcc, 0xec5, 0xdcf, 0xcc6, + 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xbca, 0xac3, 0x9c9, 0x8c0, + 0xca0, 0xda9, 0xea3, 0xfaa, 0x4ac, 0x5a5, 0x6af, 0x7a6, + 0x8a6, 0x9af, 0xaa5, 0xbac, 0x0aa, 0x1a3, 0x2a9, 0x3a0, + 0xd30, 0xc39, 0xf33, 0xe3a, 0x53c, 0x435, 0x73f, 0x636, + 0x936, 0x83f, 0xb35, 0xa3c, 0x13a, 0x033, 0x339, 0x230, + 0xe90, 0xf99, 0xc93, 0xd9a, 0x69c, 0x795, 0x49f, 0x596, + 0xa96, 0xb9f, 0x895, 0x99c, 0x29a, 0x393, 0x099, 0x190, + 0xf00, 0xe09, 0xd03, 0xc0a, 0x70c, 0x605, 0x50f, 0x406, + 0xb06, 0xa0f, 0x905, 0x80c, 0x30a, 0x203, 0x109, 0x000 + }; + + const int8_t triTable[256][16] = + { + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1, }, + { 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1, }, + { 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1, }, + { 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1, }, + { 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1, }, + { 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1, }, + { 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1, }, + { 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1, }, + { 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1, }, + { 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1, }, + { 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1, }, + { 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1, }, + { 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1, }, + { 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1, }, + { 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1, }, + { 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1, }, + { 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1, }, + { 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1, }, + { 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1, }, + { 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1, }, + { 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1, }, + { 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1, }, + { 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1, }, + { 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1, }, + { 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1, }, + { 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1, }, + { 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1, }, + { 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1, }, + { 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1, }, + { 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1, }, + { 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1, }, + { 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1, }, + { 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1, }, + { 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1, }, + { 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1, }, + { 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1, }, + { 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1, }, + { 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1, }, + { 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1, }, + { 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1, }, + { 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1, }, + { 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1, }, + { 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1, }, + { 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1, }, + { 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1, }, + { 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1, }, + { 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1, }, + { 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1, }, + { 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1, }, + { 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1, }, + { 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1, }, + { 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1, }, + { 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1, }, + { 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1, }, + { 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, }, + { 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1, }, + { 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1, }, + { 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1, }, + { 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1, }, + { 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1, }, + { 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1, }, + { 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1, }, + { 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1, }, + { 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1, }, + { 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1, }, + { 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1, }, + { 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1, }, + { 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1, }, + { 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1, }, + { 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1, }, + { 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1, }, + { 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1, }, + { 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1, }, + { 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1, }, + { 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1, }, + { 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1, }, + { 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1, }, + { 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1, }, + { 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1, }, + { 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1, }, + { 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1, }, + { 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1, }, + { 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1, }, + { 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1, }, + { 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1, }, + { 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1, }, + { 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1, }, + { 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1, }, + { 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1, }, + { 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, }, + { 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1, }, + { 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1, }, + { 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1, }, + { 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1, }, + { 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1, }, + { 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1, }, + { 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1, }, + { 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1, }, + { 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1, }, + { 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1, }, + { 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1, }, + { 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1, }, + { 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1, }, + { 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1, }, + { 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1, }, + { 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1, }, + { 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1, }, + { 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1, }, + { 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1, }, + { 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1, }, + { 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1, }, + { 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1, }, + { 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1, }, + { 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1, }, + { 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, } + }; +} + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Morton.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Morton.h new file mode 100644 index 0000000..107a338 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Morton.h @@ -0,0 +1,160 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Morton_H__ +#define __PolyVox_Morton_H__ + +namespace PolyVox +{ + // Based on: http://www.forceflow.be/2013/10/07/morton-encodingdecoding-through-bit-interleaving-implementations/ + static const uint32_t morton256_x[256] = + { + 0x00000000, + 0x00000001, 0x00000008, 0x00000009, 0x00000040, 0x00000041, 0x00000048, 0x00000049, 0x00000200, + 0x00000201, 0x00000208, 0x00000209, 0x00000240, 0x00000241, 0x00000248, 0x00000249, 0x00001000, + 0x00001001, 0x00001008, 0x00001009, 0x00001040, 0x00001041, 0x00001048, 0x00001049, 0x00001200, + 0x00001201, 0x00001208, 0x00001209, 0x00001240, 0x00001241, 0x00001248, 0x00001249, 0x00008000, + 0x00008001, 0x00008008, 0x00008009, 0x00008040, 0x00008041, 0x00008048, 0x00008049, 0x00008200, + 0x00008201, 0x00008208, 0x00008209, 0x00008240, 0x00008241, 0x00008248, 0x00008249, 0x00009000, + 0x00009001, 0x00009008, 0x00009009, 0x00009040, 0x00009041, 0x00009048, 0x00009049, 0x00009200, + 0x00009201, 0x00009208, 0x00009209, 0x00009240, 0x00009241, 0x00009248, 0x00009249, 0x00040000, + 0x00040001, 0x00040008, 0x00040009, 0x00040040, 0x00040041, 0x00040048, 0x00040049, 0x00040200, + 0x00040201, 0x00040208, 0x00040209, 0x00040240, 0x00040241, 0x00040248, 0x00040249, 0x00041000, + 0x00041001, 0x00041008, 0x00041009, 0x00041040, 0x00041041, 0x00041048, 0x00041049, 0x00041200, + 0x00041201, 0x00041208, 0x00041209, 0x00041240, 0x00041241, 0x00041248, 0x00041249, 0x00048000, + 0x00048001, 0x00048008, 0x00048009, 0x00048040, 0x00048041, 0x00048048, 0x00048049, 0x00048200, + 0x00048201, 0x00048208, 0x00048209, 0x00048240, 0x00048241, 0x00048248, 0x00048249, 0x00049000, + 0x00049001, 0x00049008, 0x00049009, 0x00049040, 0x00049041, 0x00049048, 0x00049049, 0x00049200, + 0x00049201, 0x00049208, 0x00049209, 0x00049240, 0x00049241, 0x00049248, 0x00049249, 0x00200000, + 0x00200001, 0x00200008, 0x00200009, 0x00200040, 0x00200041, 0x00200048, 0x00200049, 0x00200200, + 0x00200201, 0x00200208, 0x00200209, 0x00200240, 0x00200241, 0x00200248, 0x00200249, 0x00201000, + 0x00201001, 0x00201008, 0x00201009, 0x00201040, 0x00201041, 0x00201048, 0x00201049, 0x00201200, + 0x00201201, 0x00201208, 0x00201209, 0x00201240, 0x00201241, 0x00201248, 0x00201249, 0x00208000, + 0x00208001, 0x00208008, 0x00208009, 0x00208040, 0x00208041, 0x00208048, 0x00208049, 0x00208200, + 0x00208201, 0x00208208, 0x00208209, 0x00208240, 0x00208241, 0x00208248, 0x00208249, 0x00209000, + 0x00209001, 0x00209008, 0x00209009, 0x00209040, 0x00209041, 0x00209048, 0x00209049, 0x00209200, + 0x00209201, 0x00209208, 0x00209209, 0x00209240, 0x00209241, 0x00209248, 0x00209249, 0x00240000, + 0x00240001, 0x00240008, 0x00240009, 0x00240040, 0x00240041, 0x00240048, 0x00240049, 0x00240200, + 0x00240201, 0x00240208, 0x00240209, 0x00240240, 0x00240241, 0x00240248, 0x00240249, 0x00241000, + 0x00241001, 0x00241008, 0x00241009, 0x00241040, 0x00241041, 0x00241048, 0x00241049, 0x00241200, + 0x00241201, 0x00241208, 0x00241209, 0x00241240, 0x00241241, 0x00241248, 0x00241249, 0x00248000, + 0x00248001, 0x00248008, 0x00248009, 0x00248040, 0x00248041, 0x00248048, 0x00248049, 0x00248200, + 0x00248201, 0x00248208, 0x00248209, 0x00248240, 0x00248241, 0x00248248, 0x00248249, 0x00249000, + 0x00249001, 0x00249008, 0x00249009, 0x00249040, 0x00249041, 0x00249048, 0x00249049, 0x00249200, + 0x00249201, 0x00249208, 0x00249209, 0x00249240, 0x00249241, 0x00249248, 0x00249249 + }; + + // pre-shifted table for Y coordinates (1 bit to the left) + static const uint32_t morton256_y[256] = { + 0x00000000, + 0x00000002, 0x00000010, 0x00000012, 0x00000080, 0x00000082, 0x00000090, 0x00000092, 0x00000400, + 0x00000402, 0x00000410, 0x00000412, 0x00000480, 0x00000482, 0x00000490, 0x00000492, 0x00002000, + 0x00002002, 0x00002010, 0x00002012, 0x00002080, 0x00002082, 0x00002090, 0x00002092, 0x00002400, + 0x00002402, 0x00002410, 0x00002412, 0x00002480, 0x00002482, 0x00002490, 0x00002492, 0x00010000, + 0x00010002, 0x00010010, 0x00010012, 0x00010080, 0x00010082, 0x00010090, 0x00010092, 0x00010400, + 0x00010402, 0x00010410, 0x00010412, 0x00010480, 0x00010482, 0x00010490, 0x00010492, 0x00012000, + 0x00012002, 0x00012010, 0x00012012, 0x00012080, 0x00012082, 0x00012090, 0x00012092, 0x00012400, + 0x00012402, 0x00012410, 0x00012412, 0x00012480, 0x00012482, 0x00012490, 0x00012492, 0x00080000, + 0x00080002, 0x00080010, 0x00080012, 0x00080080, 0x00080082, 0x00080090, 0x00080092, 0x00080400, + 0x00080402, 0x00080410, 0x00080412, 0x00080480, 0x00080482, 0x00080490, 0x00080492, 0x00082000, + 0x00082002, 0x00082010, 0x00082012, 0x00082080, 0x00082082, 0x00082090, 0x00082092, 0x00082400, + 0x00082402, 0x00082410, 0x00082412, 0x00082480, 0x00082482, 0x00082490, 0x00082492, 0x00090000, + 0x00090002, 0x00090010, 0x00090012, 0x00090080, 0x00090082, 0x00090090, 0x00090092, 0x00090400, + 0x00090402, 0x00090410, 0x00090412, 0x00090480, 0x00090482, 0x00090490, 0x00090492, 0x00092000, + 0x00092002, 0x00092010, 0x00092012, 0x00092080, 0x00092082, 0x00092090, 0x00092092, 0x00092400, + 0x00092402, 0x00092410, 0x00092412, 0x00092480, 0x00092482, 0x00092490, 0x00092492, 0x00400000, + 0x00400002, 0x00400010, 0x00400012, 0x00400080, 0x00400082, 0x00400090, 0x00400092, 0x00400400, + 0x00400402, 0x00400410, 0x00400412, 0x00400480, 0x00400482, 0x00400490, 0x00400492, 0x00402000, + 0x00402002, 0x00402010, 0x00402012, 0x00402080, 0x00402082, 0x00402090, 0x00402092, 0x00402400, + 0x00402402, 0x00402410, 0x00402412, 0x00402480, 0x00402482, 0x00402490, 0x00402492, 0x00410000, + 0x00410002, 0x00410010, 0x00410012, 0x00410080, 0x00410082, 0x00410090, 0x00410092, 0x00410400, + 0x00410402, 0x00410410, 0x00410412, 0x00410480, 0x00410482, 0x00410490, 0x00410492, 0x00412000, + 0x00412002, 0x00412010, 0x00412012, 0x00412080, 0x00412082, 0x00412090, 0x00412092, 0x00412400, + 0x00412402, 0x00412410, 0x00412412, 0x00412480, 0x00412482, 0x00412490, 0x00412492, 0x00480000, + 0x00480002, 0x00480010, 0x00480012, 0x00480080, 0x00480082, 0x00480090, 0x00480092, 0x00480400, + 0x00480402, 0x00480410, 0x00480412, 0x00480480, 0x00480482, 0x00480490, 0x00480492, 0x00482000, + 0x00482002, 0x00482010, 0x00482012, 0x00482080, 0x00482082, 0x00482090, 0x00482092, 0x00482400, + 0x00482402, 0x00482410, 0x00482412, 0x00482480, 0x00482482, 0x00482490, 0x00482492, 0x00490000, + 0x00490002, 0x00490010, 0x00490012, 0x00490080, 0x00490082, 0x00490090, 0x00490092, 0x00490400, + 0x00490402, 0x00490410, 0x00490412, 0x00490480, 0x00490482, 0x00490490, 0x00490492, 0x00492000, + 0x00492002, 0x00492010, 0x00492012, 0x00492080, 0x00492082, 0x00492090, 0x00492092, 0x00492400, + 0x00492402, 0x00492410, 0x00492412, 0x00492480, 0x00492482, 0x00492490, 0x00492492 + }; + + // Pre-shifted table for z (2 bits to the left) + static const uint32_t morton256_z[256] = { + 0x00000000, + 0x00000004, 0x00000020, 0x00000024, 0x00000100, 0x00000104, 0x00000120, 0x00000124, 0x00000800, + 0x00000804, 0x00000820, 0x00000824, 0x00000900, 0x00000904, 0x00000920, 0x00000924, 0x00004000, + 0x00004004, 0x00004020, 0x00004024, 0x00004100, 0x00004104, 0x00004120, 0x00004124, 0x00004800, + 0x00004804, 0x00004820, 0x00004824, 0x00004900, 0x00004904, 0x00004920, 0x00004924, 0x00020000, + 0x00020004, 0x00020020, 0x00020024, 0x00020100, 0x00020104, 0x00020120, 0x00020124, 0x00020800, + 0x00020804, 0x00020820, 0x00020824, 0x00020900, 0x00020904, 0x00020920, 0x00020924, 0x00024000, + 0x00024004, 0x00024020, 0x00024024, 0x00024100, 0x00024104, 0x00024120, 0x00024124, 0x00024800, + 0x00024804, 0x00024820, 0x00024824, 0x00024900, 0x00024904, 0x00024920, 0x00024924, 0x00100000, + 0x00100004, 0x00100020, 0x00100024, 0x00100100, 0x00100104, 0x00100120, 0x00100124, 0x00100800, + 0x00100804, 0x00100820, 0x00100824, 0x00100900, 0x00100904, 0x00100920, 0x00100924, 0x00104000, + 0x00104004, 0x00104020, 0x00104024, 0x00104100, 0x00104104, 0x00104120, 0x00104124, 0x00104800, + 0x00104804, 0x00104820, 0x00104824, 0x00104900, 0x00104904, 0x00104920, 0x00104924, 0x00120000, + 0x00120004, 0x00120020, 0x00120024, 0x00120100, 0x00120104, 0x00120120, 0x00120124, 0x00120800, + 0x00120804, 0x00120820, 0x00120824, 0x00120900, 0x00120904, 0x00120920, 0x00120924, 0x00124000, + 0x00124004, 0x00124020, 0x00124024, 0x00124100, 0x00124104, 0x00124120, 0x00124124, 0x00124800, + 0x00124804, 0x00124820, 0x00124824, 0x00124900, 0x00124904, 0x00124920, 0x00124924, 0x00800000, + 0x00800004, 0x00800020, 0x00800024, 0x00800100, 0x00800104, 0x00800120, 0x00800124, 0x00800800, + 0x00800804, 0x00800820, 0x00800824, 0x00800900, 0x00800904, 0x00800920, 0x00800924, 0x00804000, + 0x00804004, 0x00804020, 0x00804024, 0x00804100, 0x00804104, 0x00804120, 0x00804124, 0x00804800, + 0x00804804, 0x00804820, 0x00804824, 0x00804900, 0x00804904, 0x00804920, 0x00804924, 0x00820000, + 0x00820004, 0x00820020, 0x00820024, 0x00820100, 0x00820104, 0x00820120, 0x00820124, 0x00820800, + 0x00820804, 0x00820820, 0x00820824, 0x00820900, 0x00820904, 0x00820920, 0x00820924, 0x00824000, + 0x00824004, 0x00824020, 0x00824024, 0x00824100, 0x00824104, 0x00824120, 0x00824124, 0x00824800, + 0x00824804, 0x00824820, 0x00824824, 0x00824900, 0x00824904, 0x00824920, 0x00824924, 0x00900000, + 0x00900004, 0x00900020, 0x00900024, 0x00900100, 0x00900104, 0x00900120, 0x00900124, 0x00900800, + 0x00900804, 0x00900820, 0x00900824, 0x00900900, 0x00900904, 0x00900920, 0x00900924, 0x00904000, + 0x00904004, 0x00904020, 0x00904024, 0x00904100, 0x00904104, 0x00904120, 0x00904124, 0x00904800, + 0x00904804, 0x00904820, 0x00904824, 0x00904900, 0x00904904, 0x00904920, 0x00904924, 0x00920000, + 0x00920004, 0x00920020, 0x00920024, 0x00920100, 0x00920104, 0x00920120, 0x00920124, 0x00920800, + 0x00920804, 0x00920820, 0x00920824, 0x00920900, 0x00920904, 0x00920920, 0x00920924, 0x00924000, + 0x00924004, 0x00924020, 0x00924024, 0x00924100, 0x00924104, 0x00924120, 0x00924124, 0x00924800, + 0x00924804, 0x00924820, 0x00924824, 0x00924900, 0x00924904, 0x00924920, 0x00924924 + }; + + /*inline uint32_t convertCoordinates(uint16_t uXPos, uint16_t uYPos, uint16_t uZPos) + { + uint64_t answer = 0; + answer = morton256_z[(uZPos >> 16) & 0xFF] | // we start by shifting the third byte, since we only look at the first 21 bits + morton256_y[(uYPos >> 16) & 0xFF] | + morton256_x[(uXPos >> 16) & 0xFF]; + answer = answer << 48 | + morton256_z[(uZPos >> 8) & 0xFF] | // shifting second byte + morton256_y[(uYPos >> 8) & 0xFF] | + morton256_x[(uXPos >> 8) & 0xFF]; + answer = answer << 24 | + morton256_z[(uZPos)& 0xFF] | // first byte + morton256_y[(uYPos)& 0xFF] | + morton256_x[(uXPos)& 0xFF]; + return answer; + }*/ +} + +#endif //__PolyVox_Morton_H__ \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/PlatformDefinitions.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/PlatformDefinitions.h new file mode 100644 index 0000000..50bb0e0 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/PlatformDefinitions.h @@ -0,0 +1,85 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +// This file contains definitions for various macros, etc, which need to be different +// for each platform. It helps keep per-platform logic outside the rest of PolyVox. +#ifndef __PolyVox_PlatformDefinitions_H__ +#define __PolyVox_PlatformDefinitions_H__ + +// An error message like the one below makes it much clearer to the user that they are using +// an unsupported compiler, rather than them wondering if they are using PolyVox incorrectly. +#if defined(_MSC_VER) && (_MSC_VER < 1800) + #error "Your version of Visual Studio is too old to build PolyVox. You need at least version Visual Stusio 2013" +#endif + +// Macros cannot contain #ifdefs, but some of our macros need to disable warnings and such warning supression is +// platform specific. But macros can contain other macros, so we create macros to control the warnings and use +// those instead. This set of warning supression macros can be extended to GCC/Clang when required. +#if defined(_MSC_VER) + #define POLYVOX_MSC_WARNING_PUSH __pragma(warning(push)) + #define POLYVOX_DISABLE_MSC_WARNING(x) __pragma(warning(disable:x)) + #define POLYVOX_MSC_WARNING_POP __pragma(warning(pop)) +#else + #define POLYVOX_MSC_WARNING_PUSH + #define POLYVOX_DISABLE_MSC_WARNING(x) + #define POLYVOX_MSC_WARNING_POP +#endif + +// Used to mark functions as deprecated prior to us removing them. +#if defined _WIN32 || defined __CYGWIN__ + #define POLYVOX_DEPRECATED __declspec(deprecated) +#else + #define POLYVOX_DEPRECATED __attribute__((deprecated)) +#endif + +// The depreacated macro (and possibly others?) cause confusion for SWIG, so we undefine them if SWIG is running. +#if defined SWIG + //Do nothing in this case +#else + #undef POLYVOX_DEPRECATED + #define POLYVOX_DEPRECATED //Define it to nothing to avoid warnings +#endif + +// Halts the application is the most elegant way possible (dropping into a debugger if we can). +#if defined(_MSC_VER) + // In Visual Studio we can use this function to go into the debugger. + #define POLYVOX_HALT() __debugbreak() +#else + // On other platforms we just halt by forcing a crash. + // Hopefully this puts us in the debugger if one is running + #if defined(__linux__) || defined(__APPLE__) + #define POLYVOX_HALT() raise(SIGTRAP) + #else + #define POLYVOX_HALT() *((unsigned int*)0) = 0xDEAD + #endif +#endif + +// Used to prevent the compiler complaining about unused varuables, particularly useful when +// e.g. asserts are disabled and the parameter it was checking isn't used anywhere else. +// Note that this implementation doesn't seem to work everywhere, for some reason I have +// seen it give compile errors when combined with variadic template functions (to be confirmed)? +// Implementation from here: http://stackoverflow.com/a/4851173/2337254 +#define POLYVOX_UNUSED(x) do { (void)sizeof(x); } while(0) + +#endif //__PolyVox_PlatformDefinitions_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/RandomUnitVectors.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/RandomUnitVectors.h new file mode 100644 index 0000000..3a33fd7 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/RandomUnitVectors.h @@ -0,0 +1,1063 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_RandomUnitVectors_H__ +#define __PolyVox_RandomUnitVectors_H__ + +#include "PlatformDefinitions.h" + +#include "../Vector.h" + +namespace PolyVox +{ + const Vector3DFloat randomUnitVectors[1024] = + { + Vector3DFloat(+0.339922f, +0.827727f, -0.446454f), + Vector3DFloat(+0.084104f, -0.552666f, -0.829148f), + Vector3DFloat(+0.272549f, -0.946890f, +0.170637f), + Vector3DFloat(-0.366941f, -0.785500f, -0.498341f), + Vector3DFloat(-0.566493f, -0.533056f, +0.628440f), + Vector3DFloat(+0.964857f, -0.261032f, -0.030203f), + Vector3DFloat(+0.692249f, -0.251370f, +0.676465f), + Vector3DFloat(-0.962508f, -0.173232f, -0.208734f), + Vector3DFloat(-0.659700f, +0.712315f, +0.239589f), + Vector3DFloat(+0.818392f, -0.574522f, +0.012631f), + Vector3DFloat(+0.560367f, -0.792890f, -0.239405f), + Vector3DFloat(+0.906429f, -0.307885f, +0.289127f), + Vector3DFloat(-0.159051f, +0.461737f, +0.872641f), + Vector3DFloat(-0.231332f, +0.080769f, +0.969516f), + Vector3DFloat(-0.053423f, +0.774833f, +0.629904f), + Vector3DFloat(+0.824248f, -0.144982f, +0.547353f), + Vector3DFloat(+0.174020f, -0.439121f, -0.881413f), + Vector3DFloat(+0.467553f, +0.882007f, -0.058800f), + Vector3DFloat(+0.538442f, -0.808622f, +0.237089f), + Vector3DFloat(+0.502236f, +0.150786f, -0.851483f), + Vector3DFloat(+0.735645f, +0.569407f, -0.366882f), + Vector3DFloat(-0.855825f, -0.328077f, -0.399912f), + Vector3DFloat(-0.474060f, -0.211393f, +0.854740f), + Vector3DFloat(+0.828518f, -0.114561f, +0.548119f), + Vector3DFloat(+0.740223f, -0.663929f, +0.106149f), + Vector3DFloat(-0.604006f, -0.756687f, +0.250204f), + Vector3DFloat(+0.382515f, -0.373773f, -0.844971f), + Vector3DFloat(-0.819034f, -0.162715f, -0.550188f), + Vector3DFloat(-0.982375f, +0.169525f, -0.078743f), + Vector3DFloat(+0.367097f, +0.380576f, +0.848765f), + Vector3DFloat(+0.569529f, +0.516287f, +0.639597f), + Vector3DFloat(-0.853575f, -0.243752f, +0.460429f), + Vector3DFloat(+0.678039f, -0.729861f, -0.086982f), + Vector3DFloat(-0.869225f, +0.393408f, +0.299462f), + Vector3DFloat(-0.916254f, -0.295218f, +0.270784f), + Vector3DFloat(-0.070601f, +0.873182f, +0.482253f), + Vector3DFloat(-0.863217f, +0.189580f, +0.467885f), + Vector3DFloat(-0.691774f, -0.687382f, -0.221257f), + Vector3DFloat(-0.229393f, -0.552390f, +0.801402f), + Vector3DFloat(+0.463007f, -0.161958f, -0.871432f), + Vector3DFloat(-0.952260f, +0.214379f, +0.217352f), + Vector3DFloat(+0.052543f, -0.983907f, +0.170781f), + Vector3DFloat(+0.286530f, +0.546131f, -0.787173f), + Vector3DFloat(+0.975618f, -0.202665f, +0.084242f), + Vector3DFloat(-0.946903f, +0.193782f, -0.256561f), + Vector3DFloat(+0.602392f, +0.563710f, +0.565115f), + Vector3DFloat(-0.419515f, -0.334134f, -0.844015f), + Vector3DFloat(+0.032529f, -0.018906f, -0.999292f), + Vector3DFloat(+0.683276f, +0.293783f, -0.668450f), + Vector3DFloat(+0.194348f, +0.974682f, +0.110565f), + Vector3DFloat(-0.140892f, +0.831281f, +0.537700f), + Vector3DFloat(+0.685721f, -0.335248f, -0.646062f), + Vector3DFloat(+0.308294f, +0.062479f, -0.949237f), + Vector3DFloat(-0.619897f, +0.133633f, -0.773220f), + Vector3DFloat(+0.568018f, -0.694982f, +0.440858f), + Vector3DFloat(+0.014460f, +0.810882f, -0.585031f), + Vector3DFloat(-0.939900f, +0.051870f, +0.337488f), + Vector3DFloat(+0.886477f, -0.450612f, -0.105395f), + Vector3DFloat(-0.787830f, +0.158037f, -0.595271f), + Vector3DFloat(-0.318153f, -0.830670f, -0.456910f), + Vector3DFloat(-0.106830f, -0.755766f, -0.646069f), + Vector3DFloat(-0.077610f, -0.893295f, -0.442720f), + Vector3DFloat(+0.321718f, -0.338373f, +0.884309f), + Vector3DFloat(+0.405993f, -0.037181f, +0.913119f), + Vector3DFloat(+0.635434f, -0.612340f, +0.470387f), + Vector3DFloat(-0.440661f, +0.527619f, -0.726248f), + Vector3DFloat(+0.682630f, +0.730693f, +0.010181f), + Vector3DFloat(+0.364300f, -0.398796f, -0.841574f), + Vector3DFloat(+0.023390f, -0.827974f, +0.560279f), + Vector3DFloat(-0.647533f, -0.750712f, +0.130894f), + Vector3DFloat(+0.618352f, +0.694153f, +0.368499f), + Vector3DFloat(+0.087485f, -0.552555f, +0.828872f), + Vector3DFloat(-0.317011f, -0.740865f, -0.592134f), + Vector3DFloat(+0.992075f, +0.089501f, +0.088190f), + Vector3DFloat(+0.660945f, -0.628212f, -0.410490f), + Vector3DFloat(-0.376167f, +0.394528f, -0.838359f), + Vector3DFloat(+0.761817f, -0.647395f, -0.022690f), + Vector3DFloat(+0.839361f, -0.432911f, -0.328727f), + Vector3DFloat(-0.411275f, +0.046377f, -0.910331f), + Vector3DFloat(+0.078506f, -0.797408f, +0.598312f), + Vector3DFloat(-0.381022f, +0.922073f, +0.067844f), + Vector3DFloat(-0.837489f, -0.501853f, +0.216232f), + Vector3DFloat(-0.993133f, +0.055873f, -0.102786f), + Vector3DFloat(+0.927419f, -0.354639f, -0.118844f), + Vector3DFloat(+0.159676f, +0.614049f, -0.772947f), + Vector3DFloat(-0.187074f, +0.846574f, +0.498312f), + Vector3DFloat(+0.516069f, +0.728369f, -0.450724f), + Vector3DFloat(-0.960108f, -0.233106f, -0.154447f), + Vector3DFloat(-0.987760f, -0.112007f, +0.108557f), + Vector3DFloat(+0.049202f, +0.998738f, -0.010071f), + Vector3DFloat(-0.821445f, +0.254709f, +0.510247f), + Vector3DFloat(+0.252350f, -0.204056f, +0.945876f), + Vector3DFloat(-0.398037f, +0.781383f, -0.480633f), + Vector3DFloat(+0.527785f, +0.747611f, -0.403137f), + Vector3DFloat(-0.998566f, +0.043248f, +0.031542f), + Vector3DFloat(+0.548139f, +0.684886f, +0.480078f), + Vector3DFloat(-0.566315f, -0.745438f, +0.351581f), + Vector3DFloat(-0.848496f, -0.030994f, +0.528294f), + Vector3DFloat(-0.070703f, +0.825305f, -0.560244f), + Vector3DFloat(+0.624014f, -0.043543f, +0.780199f), + Vector3DFloat(+0.964602f, -0.189230f, -0.183670f), + Vector3DFloat(+0.637905f, -0.539396f, +0.549663f), + Vector3DFloat(+0.114321f, +0.904904f, -0.409974f), + Vector3DFloat(-0.021617f, +0.186501f, +0.982217f), + Vector3DFloat(+0.469141f, -0.747866f, +0.469685f), + Vector3DFloat(+0.132117f, +0.385378f, +0.913252f), + Vector3DFloat(-0.252634f, -0.349595f, +0.902197f), + Vector3DFloat(-0.145421f, +0.945344f, +0.291851f), + Vector3DFloat(-0.600604f, +0.448416f, -0.661965f), + Vector3DFloat(+0.381683f, -0.700133f, -0.603433f), + Vector3DFloat(+0.569938f, -0.030470f, +0.821122f), + Vector3DFloat(+0.112037f, +0.915575f, +0.386225f), + Vector3DFloat(+0.059716f, -0.821586f, -0.566949f), + Vector3DFloat(-0.158273f, -0.639328f, -0.752468f), + Vector3DFloat(+0.001205f, -0.990747f, -0.135715f), + Vector3DFloat(-0.100969f, -0.176804f, -0.979054f), + Vector3DFloat(+0.169578f, -0.733794f, -0.657868f), + Vector3DFloat(+0.474056f, +0.669558f, -0.571807f), + Vector3DFloat(+0.014190f, -0.179546f, -0.983647f), + Vector3DFloat(-0.506680f, +0.784137f, -0.358337f), + Vector3DFloat(+0.402466f, +0.736544f, -0.543621f), + Vector3DFloat(-0.740589f, +0.430129f, +0.516252f), + Vector3DFloat(-0.731489f, -0.411418f, +0.543745f), + Vector3DFloat(-0.372220f, +0.822132f, -0.430756f), + Vector3DFloat(-0.403935f, +0.195178f, +0.893724f), + Vector3DFloat(+0.893255f, -0.191946f, +0.406512f), + Vector3DFloat(+0.257182f, +0.933321f, +0.250537f), + Vector3DFloat(-0.946047f, -0.252800f, +0.202699f), + Vector3DFloat(+0.287823f, -0.484935f, +0.825830f), + Vector3DFloat(+0.880378f, +0.321649f, +0.348535f), + Vector3DFloat(-0.820150f, +0.481236f, +0.309460f), + Vector3DFloat(-0.888465f, +0.169680f, -0.426425f), + Vector3DFloat(+0.761535f, -0.481027f, +0.434371f), + Vector3DFloat(+0.581314f, +0.037144f, -0.812831f), + Vector3DFloat(-0.014257f, -0.470925f, +0.882058f), + Vector3DFloat(+0.327440f, +0.265095f, -0.906922f), + Vector3DFloat(+0.445945f, +0.877176f, +0.178034f), + Vector3DFloat(+0.724926f, -0.523194f, -0.448052f), + Vector3DFloat(-0.649973f, +0.748818f, -0.129641f), + Vector3DFloat(-0.862141f, -0.181190f, -0.473163f), + Vector3DFloat(+0.546248f, -0.486978f, -0.681517f), + Vector3DFloat(-0.466403f, -0.132595f, +0.874578f), + Vector3DFloat(-0.726486f, +0.640533f, -0.248868f), + Vector3DFloat(-0.717238f, -0.164892f, +0.677038f), + Vector3DFloat(-0.173482f, -0.912751f, -0.369852f), + Vector3DFloat(+0.151425f, +0.097703f, +0.983628f), + Vector3DFloat(-0.367962f, +0.286588f, -0.884574f), + Vector3DFloat(-0.269776f, -0.681349f, +0.680430f), + Vector3DFloat(+0.587256f, +0.243525f, +0.771898f), + Vector3DFloat(+0.052027f, +0.391610f, -0.918659f), + Vector3DFloat(+0.991548f, -0.106357f, +0.074308f), + Vector3DFloat(+0.659039f, +0.457360f, -0.597067f), + Vector3DFloat(-0.626734f, -0.682082f, -0.376787f), + Vector3DFloat(-0.353101f, +0.033567f, -0.934983f), + Vector3DFloat(+0.621237f, -0.289495f, +0.728188f), + Vector3DFloat(+0.490845f, -0.189807f, +0.850320f), + Vector3DFloat(-0.699031f, -0.710681f, -0.079302f), + Vector3DFloat(-0.050094f, +0.880791f, +0.470847f), + Vector3DFloat(+0.070288f, -0.086374f, +0.993780f), + Vector3DFloat(+0.853154f, +0.022317f, +0.521181f), + Vector3DFloat(+0.230886f, +0.693269f, -0.682693f), + Vector3DFloat(-0.466130f, +0.883868f, -0.038727f), + Vector3DFloat(-0.551610f, +0.824661f, +0.125144f), + Vector3DFloat(-0.137494f, +0.409326f, -0.901968f), + Vector3DFloat(-0.890857f, -0.180159f, +0.417034f), + Vector3DFloat(+0.553659f, -0.392300f, +0.734549f), + Vector3DFloat(+0.406329f, -0.048366f, +0.912446f), + Vector3DFloat(-0.270581f, +0.233748f, -0.933888f), + Vector3DFloat(-0.197245f, +0.810087f, -0.552136f), + Vector3DFloat(+0.295429f, +0.704757f, +0.645011f), + Vector3DFloat(+0.717722f, -0.581869f, -0.382496f), + Vector3DFloat(+0.626543f, -0.539930f, +0.562067f), + Vector3DFloat(+0.971598f, -0.144608f, +0.187311f), + Vector3DFloat(-0.697722f, -0.464932f, -0.544998f), + Vector3DFloat(+0.457003f, +0.780926f, +0.425797f), + Vector3DFloat(+0.183694f, +0.717668f, -0.671720f), + Vector3DFloat(+0.251615f, -0.738280f, -0.625805f), + Vector3DFloat(+0.545768f, +0.806104f, +0.228766f), + Vector3DFloat(-0.928760f, -0.348049f, +0.127545f), + Vector3DFloat(+0.137432f, -0.972652f, -0.187242f), + Vector3DFloat(-0.804669f, -0.253834f, +0.536727f), + Vector3DFloat(-0.931569f, -0.252185f, -0.261882f), + Vector3DFloat(-0.604266f, -0.710349f, +0.360924f), + Vector3DFloat(-0.687860f, -0.535154f, -0.490367f), + Vector3DFloat(+0.017091f, +0.824354f, -0.565817f), + Vector3DFloat(+0.978598f, +0.134960f, +0.155346f), + Vector3DFloat(-0.802635f, +0.545353f, -0.241595f), + Vector3DFloat(+0.155235f, +0.909842f, +0.384824f), + Vector3DFloat(+0.499090f, -0.206100f, -0.841684f), + Vector3DFloat(-0.474793f, -0.216500f, +0.853053f), + Vector3DFloat(-0.317506f, -0.762610f, -0.563575f), + Vector3DFloat(-0.914433f, +0.049911f, -0.401649f), + Vector3DFloat(+0.209168f, +0.632836f, -0.745498f), + Vector3DFloat(+0.571789f, +0.197009f, -0.796395f), + Vector3DFloat(-0.364670f, +0.917590f, -0.158254f), + Vector3DFloat(-0.966271f, +0.140594f, -0.215761f), + Vector3DFloat(-0.915867f, +0.394413f, +0.075008f), + Vector3DFloat(+0.035516f, +0.991982f, -0.121285f), + Vector3DFloat(+0.334756f, -0.834260f, +0.438120f), + Vector3DFloat(+0.471469f, +0.810497f, -0.347579f), + Vector3DFloat(-0.630204f, -0.370799f, -0.682166f), + Vector3DFloat(+0.752076f, -0.232512f, +0.616701f), + Vector3DFloat(+0.780218f, -0.524134f, +0.341385f), + Vector3DFloat(-0.717151f, -0.558684f, -0.416614f), + Vector3DFloat(+0.026975f, +0.354843f, +0.934537f), + Vector3DFloat(+0.660713f, -0.205604f, +0.721931f), + Vector3DFloat(+0.569071f, -0.717916f, +0.400942f), + Vector3DFloat(+0.345670f, +0.917475f, -0.196853f), + Vector3DFloat(+0.109370f, +0.150700f, -0.982511f), + Vector3DFloat(-0.075296f, +0.867593f, -0.491541f), + Vector3DFloat(+0.427583f, +0.181258f, -0.885617f), + Vector3DFloat(-0.423011f, -0.536708f, +0.730073f), + Vector3DFloat(+0.410061f, +0.902819f, +0.129491f), + Vector3DFloat(+0.783330f, +0.352044f, -0.512307f), + Vector3DFloat(+0.019660f, +0.294402f, +0.955480f), + Vector3DFloat(+0.370284f, +0.795152f, -0.480232f), + Vector3DFloat(+0.620337f, +0.569302f, -0.539516f), + Vector3DFloat(-0.947343f, -0.008934f, +0.320097f), + Vector3DFloat(-0.093679f, +0.931693f, -0.350960f), + Vector3DFloat(-0.555730f, +0.665103f, +0.498802f), + Vector3DFloat(+0.319960f, +0.176651f, -0.930817f), + Vector3DFloat(-0.679840f, +0.281903f, +0.677014f), + Vector3DFloat(-0.954067f, +0.193782f, +0.228484f), + Vector3DFloat(+0.592922f, -0.708226f, +0.383222f), + Vector3DFloat(-0.759157f, -0.391265f, +0.520184f), + Vector3DFloat(-0.256083f, +0.304044f, +0.917594f), + Vector3DFloat(-0.462124f, +0.481197f, +0.744910f), + Vector3DFloat(-0.679480f, +0.733098f, +0.029563f), + Vector3DFloat(+0.025552f, -0.585890f, -0.809987f), + Vector3DFloat(-0.060045f, +0.002791f, +0.998192f), + Vector3DFloat(-0.507954f, +0.858736f, +0.067494f), + Vector3DFloat(-0.060525f, +0.636414f, -0.768969f), + Vector3DFloat(-0.874884f, +0.448472f, -0.182895f), + Vector3DFloat(+0.643562f, +0.762645f, -0.064807f), + Vector3DFloat(-0.516967f, -0.154231f, +0.841996f), + Vector3DFloat(+0.448249f, -0.717116f, -0.533683f), + Vector3DFloat(+0.536270f, -0.786853f, +0.305411f), + Vector3DFloat(+0.000761f, +0.527854f, -0.849335f), + Vector3DFloat(+0.723561f, -0.634332f, +0.272181f), + Vector3DFloat(+0.112740f, -0.371782f, -0.921449f), + Vector3DFloat(+0.966055f, +0.051903f, +0.253070f), + Vector3DFloat(-0.600327f, +0.248981f, -0.760011f), + Vector3DFloat(+0.091875f, +0.041693f, -0.994897f), + Vector3DFloat(-0.302152f, +0.607269f, +0.734798f), + Vector3DFloat(+0.287662f, -0.651858f, -0.701663f), + Vector3DFloat(-0.004536f, +0.679631f, +0.733540f), + Vector3DFloat(+0.526143f, +0.799583f, -0.289551f), + Vector3DFloat(-0.603927f, +0.789648f, -0.108294f), + Vector3DFloat(-0.033126f, +0.944024f, -0.328210f), + Vector3DFloat(-0.167102f, -0.851884f, -0.496358f), + Vector3DFloat(+0.288185f, -0.113731f, +0.950797f), + Vector3DFloat(+0.578194f, -0.436702f, -0.689190f), + Vector3DFloat(+0.217496f, +0.313876f, +0.924217f), + Vector3DFloat(-0.915961f, -0.158736f, -0.368535f), + Vector3DFloat(-0.498651f, +0.155245f, +0.852787f), + Vector3DFloat(-0.248762f, +0.679310f, -0.690403f), + Vector3DFloat(-0.582908f, +0.077123f, +0.808870f), + Vector3DFloat(+0.686950f, +0.229251f, -0.689597f), + Vector3DFloat(-0.647296f, +0.760051f, +0.057711f), + Vector3DFloat(-0.485938f, -0.092580f, +0.869076f), + Vector3DFloat(+0.418369f, +0.089460f, -0.903861f), + Vector3DFloat(-0.047269f, +0.350493f, -0.935372f), + Vector3DFloat(-0.242049f, -0.214469f, +0.946264f), + Vector3DFloat(-0.804456f, +0.566448f, +0.178852f), + Vector3DFloat(+0.097365f, -0.900938f, +0.422885f), + Vector3DFloat(+0.956649f, +0.290563f, +0.019905f), + Vector3DFloat(-0.783547f, +0.574387f, -0.236925f), + Vector3DFloat(-0.308724f, -0.086733f, -0.947189f), + Vector3DFloat(-0.035715f, +0.856029f, -0.515692f), + Vector3DFloat(+0.920461f, +0.190617f, +0.341199f), + Vector3DFloat(+0.637306f, +0.769628f, -0.038913f), + Vector3DFloat(-0.040111f, +0.877976f, +0.477021f), + Vector3DFloat(+0.110588f, +0.251198f, +0.961598f), + Vector3DFloat(-0.391595f, +0.858960f, +0.329911f), + Vector3DFloat(+0.159040f, +0.801465f, -0.576507f), + Vector3DFloat(-0.420361f, +0.896705f, +0.138623f), + Vector3DFloat(-0.706685f, -0.506701f, -0.493812f), + Vector3DFloat(+0.589701f, +0.807018f, -0.031213f), + Vector3DFloat(+0.613812f, +0.504595f, -0.607140f), + Vector3DFloat(+0.453930f, +0.802963f, +0.386261f), + Vector3DFloat(+0.034816f, +0.204525f, +0.978242f), + Vector3DFloat(+0.557178f, -0.795610f, +0.237816f), + Vector3DFloat(+0.694672f, -0.364363f, +0.620218f), + Vector3DFloat(+0.703004f, +0.571702f, +0.423015f), + Vector3DFloat(-0.821828f, -0.569379f, +0.020152f), + Vector3DFloat(+0.999573f, +0.011862f, +0.026716f), + Vector3DFloat(+0.045244f, +0.476148f, +0.878201f), + Vector3DFloat(-0.879083f, +0.458490f, +0.130387f), + Vector3DFloat(-0.548204f, +0.534573f, -0.643198f), + Vector3DFloat(+0.371419f, +0.536568f, +0.757722f), + Vector3DFloat(-0.121365f, +0.656202f, -0.744761f), + Vector3DFloat(-0.594210f, +0.803019f, -0.045540f), + Vector3DFloat(+0.249812f, +0.564218f, -0.786926f), + Vector3DFloat(+0.807295f, +0.588715f, -0.041117f), + Vector3DFloat(-0.333582f, +0.911830f, +0.239350f), + Vector3DFloat(+0.437116f, -0.527554f, -0.728434f), + Vector3DFloat(+0.061956f, +0.967757f, +0.244147f), + Vector3DFloat(+0.511582f, -0.822519f, -0.248487f), + Vector3DFloat(-0.341118f, -0.068048f, -0.937554f), + Vector3DFloat(+0.387840f, +0.793197f, +0.469487f), + Vector3DFloat(+0.682570f, +0.445391f, -0.579418f), + Vector3DFloat(+0.769534f, -0.445299f, -0.457740f), + Vector3DFloat(-0.883027f, -0.468901f, -0.019884f), + Vector3DFloat(-0.595228f, +0.589924f, +0.545613f), + Vector3DFloat(+0.123593f, +0.850082f, +0.511943f), + Vector3DFloat(+0.428617f, -0.326588f, -0.842394f), + Vector3DFloat(-0.838837f, +0.492096f, +0.232796f), + Vector3DFloat(-0.912950f, -0.283450f, -0.293562f), + Vector3DFloat(-0.701007f, +0.660260f, +0.269527f), + Vector3DFloat(-0.726761f, -0.673596f, -0.134488f), + Vector3DFloat(+0.969362f, -0.234200f, +0.074084f), + Vector3DFloat(-0.249448f, -0.056271f, +0.966752f), + Vector3DFloat(+0.996651f, -0.018843f, +0.079570f), + Vector3DFloat(+0.807648f, +0.476489f, +0.347367f), + Vector3DFloat(-0.749837f, -0.398796f, -0.527926f), + Vector3DFloat(+0.739222f, +0.268296f, +0.617712f), + Vector3DFloat(+0.770822f, -0.517357f, -0.371720f), + Vector3DFloat(-0.799675f, +0.207189f, +0.563554f), + Vector3DFloat(+0.858095f, +0.081493f, +0.506983f), + Vector3DFloat(+0.677579f, -0.727246f, +0.109543f), + Vector3DFloat(-0.745912f, -0.097643f, +0.658848f), + Vector3DFloat(+0.923446f, -0.321145f, +0.210033f), + Vector3DFloat(+0.633275f, +0.749248f, -0.193880f), + Vector3DFloat(+0.445950f, +0.115095f, +0.887627f), + Vector3DFloat(-0.813021f, +0.255444f, -0.523207f), + Vector3DFloat(-0.872976f, -0.483345f, -0.065502f), + Vector3DFloat(+0.587776f, +0.807323f, -0.052440f), + Vector3DFloat(-0.324123f, +0.518088f, -0.791536f), + Vector3DFloat(+0.041866f, +0.935359f, -0.351214f), + Vector3DFloat(-0.745819f, -0.037221f, -0.665108f), + Vector3DFloat(-0.625395f, -0.780290f, -0.005274f), + Vector3DFloat(-0.949212f, -0.125200f, -0.288653f), + Vector3DFloat(+0.746352f, +0.513825f, -0.423016f), + Vector3DFloat(+0.165203f, -0.819308f, -0.549038f), + Vector3DFloat(+0.749447f, -0.199908f, +0.631162f), + Vector3DFloat(-0.935221f, +0.313398f, +0.164751f), + Vector3DFloat(+0.574888f, +0.577243f, -0.579908f), + Vector3DFloat(+0.213935f, -0.439668f, +0.872309f), + Vector3DFloat(-0.067281f, -0.429365f, -0.900621f), + Vector3DFloat(-0.675176f, -0.265100f, -0.688374f), + Vector3DFloat(-0.940780f, -0.187993f, +0.282119f), + Vector3DFloat(+0.608412f, -0.674603f, -0.418026f), + Vector3DFloat(+0.226805f, -0.971072f, -0.074690f), + Vector3DFloat(-0.922002f, -0.058313f, -0.382768f), + Vector3DFloat(-0.889078f, -0.285307f, +0.357968f), + Vector3DFloat(-0.463386f, -0.780956f, +0.418785f), + Vector3DFloat(+0.480335f, -0.863968f, +0.151120f), + Vector3DFloat(-0.467641f, -0.601770f, -0.647444f), + Vector3DFloat(+0.752364f, -0.628982f, +0.195781f), + Vector3DFloat(+0.068107f, -0.990481f, -0.119616f), + Vector3DFloat(+0.225170f, -0.147543f, +0.963083f), + Vector3DFloat(+0.225228f, +0.971322f, +0.076195f), + Vector3DFloat(-0.991397f, -0.118660f, +0.055239f), + Vector3DFloat(-0.160493f, -0.746967f, +0.645200f), + Vector3DFloat(-0.458821f, -0.208468f, +0.863727f), + Vector3DFloat(+0.333033f, +0.516134f, +0.789110f), + Vector3DFloat(+0.732654f, +0.260905f, -0.628607f), + Vector3DFloat(-0.669918f, -0.656301f, -0.347102f), + Vector3DFloat(-0.786699f, +0.543142f, -0.293431f), + Vector3DFloat(+0.347036f, +0.004466f, +0.937841f), + Vector3DFloat(-0.484482f, -0.771461f, +0.412463f), + Vector3DFloat(+0.103332f, +0.547687f, -0.830278f), + Vector3DFloat(+0.119923f, -0.930107f, -0.347159f), + Vector3DFloat(+0.005754f, +0.994568f, +0.103930f), + Vector3DFloat(-0.033282f, +0.896829f, +0.441124f), + Vector3DFloat(+0.457958f, +0.771949f, +0.440874f), + Vector3DFloat(-0.519990f, +0.369290f, -0.770218f), + Vector3DFloat(-0.171662f, -0.061337f, -0.983245f), + Vector3DFloat(+0.250848f, +0.937167f, -0.242472f), + Vector3DFloat(-0.527961f, -0.608927f, +0.592001f), + Vector3DFloat(+0.524343f, -0.097826f, +0.845869f), + Vector3DFloat(-0.900974f, +0.373399f, +0.220951f), + Vector3DFloat(+0.287497f, +0.561963f, +0.775592f), + Vector3DFloat(+0.540008f, +0.803719f, -0.249855f), + Vector3DFloat(+0.566511f, +0.497948f, -0.656592f), + Vector3DFloat(+0.337228f, +0.656232f, -0.675009f), + Vector3DFloat(+0.978888f, -0.153522f, -0.134940f), + Vector3DFloat(+0.720676f, +0.649026f, +0.243702f), + Vector3DFloat(+0.530737f, +0.228155f, -0.816250f), + Vector3DFloat(+0.429492f, +0.091242f, -0.898449f), + Vector3DFloat(-0.572942f, +0.085360f, +0.815139f), + Vector3DFloat(+0.918652f, -0.255422f, +0.301395f), + Vector3DFloat(+0.947882f, -0.087598f, +0.306343f), + Vector3DFloat(+0.108362f, +0.969752f, -0.218719f), + Vector3DFloat(-0.471217f, +0.713578f, +0.518421f), + Vector3DFloat(+0.750274f, -0.244288f, -0.614339f), + Vector3DFloat(+0.560909f, -0.563116f, -0.606862f), + Vector3DFloat(+0.863412f, -0.431809f, +0.260886f), + Vector3DFloat(+0.316636f, +0.937246f, -0.145983f), + Vector3DFloat(-0.292652f, +0.171648f, +0.940687f), + Vector3DFloat(-0.636577f, +0.687143f, -0.350149f), + Vector3DFloat(+0.876483f, +0.262488f, +0.403581f), + Vector3DFloat(-0.477533f, +0.501607f, +0.721355f), + Vector3DFloat(+0.620654f, +0.186584f, +0.761561f), + Vector3DFloat(+0.085796f, +0.736783f, +0.670664f), + Vector3DFloat(-0.444489f, -0.220480f, -0.868227f), + Vector3DFloat(-0.380013f, +0.496385f, +0.780508f), + Vector3DFloat(+0.076912f, -0.385017f, -0.919699f), + Vector3DFloat(+0.148937f, -0.407401f, -0.901023f), + Vector3DFloat(+0.790103f, +0.361770f, -0.494833f), + Vector3DFloat(+0.206634f, +0.909197f, +0.361474f), + Vector3DFloat(+0.171861f, -0.895971f, -0.409512f), + Vector3DFloat(-0.961243f, +0.146552f, -0.233527f), + Vector3DFloat(-0.142180f, +0.815553f, +0.560944f), + Vector3DFloat(-0.423930f, -0.030949f, +0.905166f), + Vector3DFloat(+0.618879f, -0.685650f, +0.383241f), + Vector3DFloat(-0.209245f, +0.545013f, +0.811898f), + Vector3DFloat(+0.377987f, +0.747944f, -0.545624f), + Vector3DFloat(-0.791300f, +0.607509f, -0.069108f), + Vector3DFloat(+0.754199f, -0.113604f, -0.646744f), + Vector3DFloat(-0.583229f, -0.063801f, +0.809798f), + Vector3DFloat(-0.469901f, +0.015164f, +0.882589f), + Vector3DFloat(-0.978270f, +0.003442f, -0.207306f), + Vector3DFloat(+0.655500f, +0.726545f, +0.206039f), + Vector3DFloat(+0.967185f, -0.245972f, +0.063652f), + Vector3DFloat(-0.442760f, +0.675317f, +0.589840f), + Vector3DFloat(+0.403392f, +0.270425f, +0.874154f), + Vector3DFloat(+0.902052f, +0.135317f, +0.409868f), + Vector3DFloat(-0.210257f, -0.926257f, -0.312794f), + Vector3DFloat(-0.933559f, -0.225815f, -0.278344f), + Vector3DFloat(-0.635320f, +0.772243f, -0.003054f), + Vector3DFloat(-0.554821f, +0.812428f, -0.179259f), + Vector3DFloat(-0.844807f, +0.091109f, -0.527258f), + Vector3DFloat(-0.748601f, +0.549263f, -0.371358f), + Vector3DFloat(-0.081435f, +0.491490f, -0.867067f), + Vector3DFloat(+0.005014f, -0.658765f, +0.752332f), + Vector3DFloat(-0.384916f, +0.588836f, -0.710712f), + Vector3DFloat(-0.563287f, -0.436926f, -0.701287f), + Vector3DFloat(+0.075923f, -0.889985f, +0.449624f), + Vector3DFloat(+0.460179f, +0.240506f, -0.854630f), + Vector3DFloat(+0.133134f, +0.863013f, +0.487323f), + Vector3DFloat(-0.451891f, -0.691915f, +0.563071f), + Vector3DFloat(+0.482576f, +0.491924f, -0.724659f), + Vector3DFloat(-0.772395f, +0.503554f, +0.387091f), + Vector3DFloat(-0.861070f, -0.363456f, -0.355610f), + Vector3DFloat(-0.219092f, -0.539591f, +0.812921f), + Vector3DFloat(-0.232021f, +0.937887f, +0.257940f), + Vector3DFloat(+0.864410f, +0.411132f, +0.289425f), + Vector3DFloat(-0.657914f, +0.356283f, +0.663485f), + Vector3DFloat(-0.695536f, -0.354660f, -0.624856f), + Vector3DFloat(-0.984126f, +0.139830f, -0.109283f), + Vector3DFloat(-0.739931f, -0.568047f, +0.360312f), + Vector3DFloat(-0.422765f, +0.793857f, -0.437105f), + Vector3DFloat(+0.695244f, +0.499122f, +0.517216f), + Vector3DFloat(+0.620847f, +0.772096f, +0.135708f), + Vector3DFloat(+0.640543f, +0.693625f, -0.329529f), + Vector3DFloat(-0.716203f, +0.695845f, -0.053417f), + Vector3DFloat(+0.688286f, -0.614140f, +0.386127f), + Vector3DFloat(+0.990001f, -0.012803f, -0.140479f), + Vector3DFloat(-0.842904f, +0.537664f, +0.020753f), + Vector3DFloat(+0.008333f, +0.285713f, +0.958279f), + Vector3DFloat(-0.276086f, -0.823605f, +0.495431f), + Vector3DFloat(+0.795835f, -0.446944f, +0.408518f), + Vector3DFloat(-0.068520f, +0.989143f, -0.130001f), + Vector3DFloat(-0.995477f, -0.013318f, -0.094068f), + Vector3DFloat(-0.013256f, -0.205680f, +0.978530f), + Vector3DFloat(+0.286330f, +0.478558f, +0.830058f), + Vector3DFloat(-0.312670f, -0.000134f, +0.949862f), + Vector3DFloat(-0.992102f, -0.018784f, -0.124017f), + Vector3DFloat(-0.218201f, +0.471729f, +0.854318f), + Vector3DFloat(-0.885932f, -0.441603f, +0.141812f), + Vector3DFloat(+0.410418f, -0.903853f, +0.120862f), + Vector3DFloat(-0.046755f, -0.618559f, +0.784346f), + Vector3DFloat(+0.561077f, +0.827730f, +0.007490f), + Vector3DFloat(-0.264927f, +0.963738f, +0.031968f), + Vector3DFloat(+0.360743f, +0.887368f, -0.287127f), + Vector3DFloat(+0.829757f, -0.531319f, -0.170889f), + Vector3DFloat(-0.716516f, -0.646065f, +0.263068f), + Vector3DFloat(+0.557460f, +0.677923f, -0.479227f), + Vector3DFloat(-0.709849f, +0.694781f, -0.115733f), + Vector3DFloat(+0.853291f, -0.488531f, -0.182299f), + Vector3DFloat(+0.455284f, -0.849392f, -0.266925f), + Vector3DFloat(+0.417165f, +0.856319f, -0.304453f), + Vector3DFloat(+0.871881f, +0.388090f, +0.298681f), + Vector3DFloat(-0.103988f, +0.510844f, -0.853361f), + Vector3DFloat(+0.351047f, +0.889847f, -0.291441f), + Vector3DFloat(+0.389540f, -0.053379f, -0.919462f), + Vector3DFloat(-0.581684f, +0.075521f, +0.809901f), + Vector3DFloat(-0.422965f, -0.141455f, +0.895037f), + Vector3DFloat(+0.213377f, +0.454586f, -0.864767f), + Vector3DFloat(+0.159390f, +0.466820f, +0.869870f), + Vector3DFloat(+0.385902f, -0.013831f, +0.922436f), + Vector3DFloat(-0.360291f, -0.335817f, -0.870297f), + Vector3DFloat(-0.420892f, +0.570921f, -0.704910f), + Vector3DFloat(+0.046113f, -0.619140f, -0.783925f), + Vector3DFloat(+0.454440f, +0.871791f, -0.182935f), + Vector3DFloat(+0.523305f, -0.762818f, +0.379816f), + Vector3DFloat(-0.639517f, -0.634506f, -0.434073f), + Vector3DFloat(+0.286115f, -0.720485f, +0.631695f), + Vector3DFloat(+0.391046f, -0.912504f, -0.120079f), + Vector3DFloat(+0.562545f, +0.825619f, +0.043556f), + Vector3DFloat(+0.976939f, +0.145670f, -0.156113f), + Vector3DFloat(-0.197444f, -0.653530f, -0.730695f), + Vector3DFloat(-0.727176f, +0.159246f, +0.667724f), + Vector3DFloat(+0.977135f, +0.039408f, +0.208935f), + Vector3DFloat(+0.487883f, -0.668376f, -0.561466f), + Vector3DFloat(+0.081173f, -0.454129f, -0.887231f), + Vector3DFloat(+0.007776f, -0.558369f, -0.829556f), + Vector3DFloat(+0.392559f, -0.216208f, +0.893952f), + Vector3DFloat(+0.552351f, -0.797994f, -0.241067f), + Vector3DFloat(-0.812645f, +0.582758f, -0.000884f), + Vector3DFloat(+0.723477f, +0.425448f, +0.543668f), + Vector3DFloat(-0.290387f, -0.824836f, +0.485099f), + Vector3DFloat(-0.648037f, +0.731057f, +0.213549f), + Vector3DFloat(-0.112077f, +0.911214f, +0.396394f), + Vector3DFloat(-0.257374f, +0.878627f, +0.402212f), + Vector3DFloat(-0.871679f, -0.449228f, -0.195884f), + Vector3DFloat(-0.832643f, +0.503619f, -0.230377f), + Vector3DFloat(-0.750683f, +0.454826f, -0.479174f), + Vector3DFloat(+0.668945f, -0.737419f, +0.093412f), + Vector3DFloat(+0.232689f, -0.239415f, -0.942622f), + Vector3DFloat(+0.932416f, +0.058455f, -0.356629f), + Vector3DFloat(-0.266008f, -0.899388f, +0.346900f), + Vector3DFloat(+0.574940f, -0.817948f, -0.020127f), + Vector3DFloat(-0.332832f, +0.728233f, +0.599083f), + Vector3DFloat(+0.252574f, -0.202957f, +0.946052f), + Vector3DFloat(+0.614750f, -0.787545f, +0.043079f), + Vector3DFloat(+0.502885f, +0.757385f, -0.416503f), + Vector3DFloat(-0.829003f, +0.454711f, -0.325562f), + Vector3DFloat(-0.568805f, +0.542102f, +0.618536f), + Vector3DFloat(-0.024095f, -0.673837f, -0.738487f), + Vector3DFloat(+0.138735f, -0.428584f, -0.892787f), + Vector3DFloat(-0.535936f, -0.016858f, +0.844090f), + Vector3DFloat(-0.040976f, +0.588714f, +0.807302f), + Vector3DFloat(-0.691862f, -0.721945f, +0.011050f), + Vector3DFloat(+0.862563f, -0.438786f, -0.251897f), + Vector3DFloat(+0.278186f, +0.894754f, +0.349326f), + Vector3DFloat(-0.377682f, -0.908327f, +0.179719f), + Vector3DFloat(-0.632125f, -0.611940f, +0.475339f), + Vector3DFloat(-0.575327f, -0.789967f, -0.212015f), + Vector3DFloat(+0.112909f, -0.993543f, -0.011156f), + Vector3DFloat(+0.593082f, -0.037683f, -0.804260f), + Vector3DFloat(-0.067094f, -0.620832f, +0.781067f), + Vector3DFloat(-0.152754f, +0.253291f, -0.955254f), + Vector3DFloat(-0.325782f, +0.882758f, -0.338533f), + Vector3DFloat(+0.359581f, -0.906944f, +0.219441f), + Vector3DFloat(-0.436527f, +0.597887f, +0.672291f), + Vector3DFloat(-0.475060f, +0.315753f, +0.821351f), + Vector3DFloat(-0.504146f, +0.392763f, -0.769138f), + Vector3DFloat(+0.732747f, -0.275063f, -0.622432f), + Vector3DFloat(-0.222604f, +0.239178f, +0.945115f), + Vector3DFloat(+0.929953f, +0.212024f, +0.300389f), + Vector3DFloat(+0.212224f, -0.914623f, -0.344129f), + Vector3DFloat(+0.744091f, -0.069074f, +0.664498f), + Vector3DFloat(+0.378632f, +0.925135f, -0.027624f), + Vector3DFloat(-0.657970f, +0.042972f, +0.751817f), + Vector3DFloat(-0.475295f, -0.858227f, -0.193754f), + Vector3DFloat(-0.002138f, -0.163379f, -0.986561f), + Vector3DFloat(+0.762016f, +0.464503f, -0.451186f), + Vector3DFloat(+0.110962f, +0.350977f, +0.929786f), + Vector3DFloat(+0.359220f, -0.409270f, +0.838725f), + Vector3DFloat(+0.067679f, -0.492517f, -0.867667f), + Vector3DFloat(-0.765643f, -0.627245f, -0.142671f), + Vector3DFloat(-0.736364f, -0.613024f, -0.286304f), + Vector3DFloat(-0.404067f, -0.396451f, +0.824352f), + Vector3DFloat(-0.908793f, +0.158289f, +0.386057f), + Vector3DFloat(-0.582767f, +0.467557f, +0.664660f), + Vector3DFloat(+0.437506f, -0.078200f, -0.895809f), + Vector3DFloat(+0.079580f, -0.165593f, -0.982978f), + Vector3DFloat(-0.152308f, +0.193183f, +0.969269f), + Vector3DFloat(+0.537776f, -0.029450f, -0.842573f), + Vector3DFloat(+0.242145f, -0.450593f, +0.859262f), + Vector3DFloat(-0.731540f, -0.287459f, +0.618237f), + Vector3DFloat(-0.822775f, +0.200303f, +0.531903f), + Vector3DFloat(+0.814744f, -0.396544f, +0.423019f), + Vector3DFloat(+0.981241f, +0.108708f, -0.159215f), + Vector3DFloat(+0.435099f, -0.134466f, -0.890285f), + Vector3DFloat(-0.863642f, -0.333093f, +0.378379f), + Vector3DFloat(+0.975214f, -0.007932f, +0.221121f), + Vector3DFloat(+0.562312f, +0.756514f, -0.333904f), + Vector3DFloat(-0.860757f, -0.321366f, -0.394743f), + Vector3DFloat(+0.202468f, +0.651174f, +0.731423f), + Vector3DFloat(+0.070835f, -0.997485f, -0.002525f), + Vector3DFloat(-0.282142f, -0.646099f, +0.709191f), + Vector3DFloat(+0.734636f, +0.546486f, -0.402073f), + Vector3DFloat(-0.792802f, +0.359455f, -0.492196f), + Vector3DFloat(+0.064556f, -0.768826f, +0.636192f), + Vector3DFloat(-0.387159f, -0.539262f, +0.747867f), + Vector3DFloat(-0.321231f, +0.945995f, +0.043642f), + Vector3DFloat(-0.051543f, -0.358058f, +0.932276f), + Vector3DFloat(+0.463676f, -0.211202f, +0.860464f), + Vector3DFloat(-0.985546f, -0.040806f, -0.164421f), + Vector3DFloat(-0.956965f, +0.289910f, -0.013071f), + Vector3DFloat(-0.575614f, -0.401429f, -0.712406f), + Vector3DFloat(+0.005411f, +0.912319f, +0.409443f), + Vector3DFloat(-0.147120f, +0.145609f, +0.978342f), + Vector3DFloat(+0.381181f, -0.303247f, +0.873351f), + Vector3DFloat(+0.646964f, -0.669990f, -0.364076f), + Vector3DFloat(+0.335662f, -0.334853f, +0.880457f), + Vector3DFloat(+0.812790f, -0.515621f, -0.271122f), + Vector3DFloat(+0.406265f, +0.443117f, -0.799122f), + Vector3DFloat(+0.818068f, +0.142779f, +0.557117f), + Vector3DFloat(-0.202146f, +0.482979f, +0.851979f), + Vector3DFloat(-0.359491f, -0.834883f, +0.416817f), + Vector3DFloat(+0.897243f, +0.373837f, -0.234949f), + Vector3DFloat(+0.734938f, -0.377211f, -0.563541f), + Vector3DFloat(+0.938936f, +0.089082f, +0.332362f), + Vector3DFloat(+0.847286f, +0.101367f, -0.521375f), + Vector3DFloat(+0.976962f, +0.212808f, -0.016060f), + Vector3DFloat(-0.484037f, -0.785288f, -0.386045f), + Vector3DFloat(+0.412432f, -0.846393f, -0.336925f), + Vector3DFloat(-0.290605f, -0.951829f, +0.097828f), + Vector3DFloat(+0.522856f, +0.099925f, -0.846544f), + Vector3DFloat(-0.268624f, -0.592962f, +0.759103f), + Vector3DFloat(+0.532873f, -0.247493f, +0.809193f), + Vector3DFloat(-0.313247f, +0.857502f, -0.408126f), + Vector3DFloat(-0.279136f, +0.481391f, +0.830870f), + Vector3DFloat(-0.648063f, -0.437447f, -0.623422f), + Vector3DFloat(+0.693159f, -0.411042f, +0.592094f), + Vector3DFloat(-0.361556f, -0.008347f, -0.932313f), + Vector3DFloat(-0.706752f, -0.017905f, +0.707235f), + Vector3DFloat(+0.277671f, +0.588210f, +0.759544f), + Vector3DFloat(+0.706147f, +0.436673f, -0.557380f), + Vector3DFloat(+0.329465f, -0.938612f, -0.102275f), + Vector3DFloat(+0.941491f, +0.304731f, -0.143996f), + Vector3DFloat(-0.530440f, -0.419970f, -0.736382f), + Vector3DFloat(-0.933059f, +0.333768f, -0.134161f), + Vector3DFloat(-0.799598f, -0.383384f, -0.462234f), + Vector3DFloat(+0.589799f, +0.017619f, -0.807358f), + Vector3DFloat(-0.157486f, -0.147213f, +0.976487f), + Vector3DFloat(+0.144612f, -0.765441f, +0.627046f), + Vector3DFloat(-0.224062f, +0.971686f, +0.074988f), + Vector3DFloat(-0.525446f, +0.743496f, +0.413666f), + Vector3DFloat(+0.913834f, -0.396502f, +0.087711f), + Vector3DFloat(+0.551810f, +0.713484f, -0.431793f), + Vector3DFloat(-0.988855f, +0.027355f, +0.146346f), + Vector3DFloat(+0.129678f, -0.922163f, +0.364417f), + Vector3DFloat(-0.443546f, +0.337851f, +0.830135f), + Vector3DFloat(-0.076099f, -0.128182f, -0.988827f), + Vector3DFloat(-0.930714f, -0.363326f, +0.042022f), + Vector3DFloat(-0.062724f, +0.597013f, -0.799776f), + Vector3DFloat(+0.674612f, -0.080125f, +0.733811f), + Vector3DFloat(-0.732149f, -0.106968f, -0.672693f), + Vector3DFloat(-0.477404f, -0.735544f, +0.480688f), + Vector3DFloat(+0.720306f, +0.691043f, +0.060162f), + Vector3DFloat(-0.480694f, -0.691928f, -0.538673f), + Vector3DFloat(+0.284364f, -0.490827f, +0.823545f), + Vector3DFloat(-0.467068f, -0.635840f, +0.614455f), + Vector3DFloat(+0.259424f, +0.728928f, +0.633532f), + Vector3DFloat(-0.829024f, +0.499711f, +0.251015f), + Vector3DFloat(+0.918101f, +0.199840f, +0.342278f), + Vector3DFloat(-0.132256f, +0.844697f, -0.518648f), + Vector3DFloat(-0.880945f, +0.470246f, +0.052958f), + Vector3DFloat(-0.907893f, +0.418701f, -0.020494f), + Vector3DFloat(-0.898489f, +0.435552f, -0.054882f), + Vector3DFloat(-0.181486f, -0.981241f, -0.065032f), + Vector3DFloat(+0.612484f, -0.390415f, -0.687342f), + Vector3DFloat(-0.674745f, +0.504350f, +0.538841f), + Vector3DFloat(-0.489037f, -0.427926f, +0.760080f), + Vector3DFloat(-0.629283f, +0.776741f, +0.026012f), + Vector3DFloat(-0.327015f, +0.559793f, +0.761375f), + Vector3DFloat(+0.143982f, -0.052568f, +0.988183f), + Vector3DFloat(+0.963642f, +0.246339f, -0.103498f), + Vector3DFloat(+0.083550f, +0.206217f, +0.974933f), + Vector3DFloat(+0.985008f, +0.097629f, -0.142221f), + Vector3DFloat(+0.386516f, -0.544556f, +0.744355f), + Vector3DFloat(-0.390134f, -0.377051f, +0.840017f), + Vector3DFloat(+0.188428f, -0.872526f, -0.450770f), + Vector3DFloat(-0.249415f, +0.963139f, +0.100774f), + Vector3DFloat(-0.246900f, -0.688081f, +0.682338f), + Vector3DFloat(-0.815515f, -0.341331f, -0.467363f), + Vector3DFloat(-0.828295f, -0.545972f, +0.125866f), + Vector3DFloat(-0.251196f, +0.860882f, +0.442473f), + Vector3DFloat(+0.787130f, -0.124629f, -0.604065f), + Vector3DFloat(-0.546825f, -0.350565f, +0.760320f), + Vector3DFloat(+0.910761f, +0.326941f, +0.252237f), + Vector3DFloat(-0.822947f, -0.029868f, +0.567332f), + Vector3DFloat(-0.119863f, -0.101264f, +0.987612f), + Vector3DFloat(+0.338978f, +0.251339f, +0.906600f), + Vector3DFloat(-0.168116f, +0.130641f, +0.977072f), + Vector3DFloat(+0.630274f, -0.051172f, +0.774685f), + Vector3DFloat(+0.509020f, +0.860289f, -0.028316f), + Vector3DFloat(-0.741184f, +0.614383f, -0.270518f), + Vector3DFloat(+0.783367f, +0.216068f, -0.582796f), + Vector3DFloat(-0.917044f, -0.239253f, -0.319042f), + Vector3DFloat(+0.326503f, +0.605534f, +0.725758f), + Vector3DFloat(-0.858028f, +0.033090f, +0.512536f), + Vector3DFloat(+0.920390f, +0.341687f, +0.190084f), + Vector3DFloat(+0.184870f, +0.206034f, -0.960923f), + Vector3DFloat(-0.320575f, -0.873361f, -0.366704f), + Vector3DFloat(-0.908564f, +0.179683f, -0.377129f), + Vector3DFloat(-0.995162f, +0.060094f, -0.077721f), + Vector3DFloat(-0.970805f, +0.057864f, +0.232786f), + Vector3DFloat(-0.438989f, -0.719230f, -0.538514f), + Vector3DFloat(-0.305764f, +0.586163f, +0.750281f), + Vector3DFloat(+0.813263f, +0.070638f, +0.577593f), + Vector3DFloat(-0.856072f, +0.356367f, -0.374356f), + Vector3DFloat(-0.291393f, -0.496711f, -0.817538f), + Vector3DFloat(-0.465919f, +0.423021f, +0.777157f), + Vector3DFloat(-0.197288f, +0.747479f, +0.634312f), + Vector3DFloat(+0.459532f, -0.294706f, +0.837842f), + Vector3DFloat(-0.669432f, -0.715572f, -0.199543f), + Vector3DFloat(+0.651361f, +0.729418f, -0.208995f), + Vector3DFloat(+0.899675f, -0.409092f, +0.152409f), + Vector3DFloat(-0.909013f, +0.374561f, +0.182756f), + Vector3DFloat(+0.584390f, +0.675714f, -0.449332f), + Vector3DFloat(-0.679644f, +0.693287f, -0.239658f), + Vector3DFloat(-0.447022f, -0.041260f, +0.893571f), + Vector3DFloat(-0.116547f, +0.050542f, -0.991898f), + Vector3DFloat(+0.395893f, +0.741111f, -0.542239f), + Vector3DFloat(+0.350204f, -0.445076f, -0.824175f), + Vector3DFloat(-0.172775f, +0.743090f, -0.646503f), + Vector3DFloat(+0.990144f, +0.139743f, -0.009361f), + Vector3DFloat(+0.519086f, +0.780496f, -0.348389f), + Vector3DFloat(-0.437746f, -0.398253f, +0.806085f), + Vector3DFloat(-0.008119f, +0.986280f, -0.164880f), + Vector3DFloat(+0.597715f, -0.604411f, -0.526711f), + Vector3DFloat(-0.097509f, +0.175580f, -0.979624f), + Vector3DFloat(+0.660655f, -0.124974f, +0.740214f), + Vector3DFloat(-0.206022f, +0.283440f, -0.936599f), + Vector3DFloat(-0.702342f, +0.672455f, -0.233496f), + Vector3DFloat(+0.306125f, -0.350950f, -0.884942f), + Vector3DFloat(+0.572172f, -0.424424f, -0.701772f), + Vector3DFloat(-0.218533f, -0.939401f, -0.264138f), + Vector3DFloat(+0.409469f, -0.491877f, -0.768370f), + Vector3DFloat(-0.651781f, -0.191800f, +0.733754f), + Vector3DFloat(+0.900352f, -0.242264f, -0.361490f), + Vector3DFloat(+0.809489f, +0.255902f, -0.528434f), + Vector3DFloat(+0.615724f, -0.777952f, +0.125199f), + Vector3DFloat(-0.337892f, -0.510143f, -0.790938f), + Vector3DFloat(-0.326182f, -0.695879f, +0.639811f), + Vector3DFloat(-0.877877f, -0.220692f, +0.425002f), + Vector3DFloat(+0.837897f, -0.278492f, -0.469436f), + Vector3DFloat(-0.802587f, -0.151114f, +0.577077f), + Vector3DFloat(+0.409855f, +0.796889f, -0.443832f), + Vector3DFloat(-0.374483f, +0.669830f, -0.641164f), + Vector3DFloat(-0.745860f, +0.343937f, -0.570438f), + Vector3DFloat(-0.202905f, +0.156353f, +0.966635f), + Vector3DFloat(+0.556026f, +0.322254f, -0.766151f), + Vector3DFloat(+0.776714f, +0.240272f, -0.582224f), + Vector3DFloat(-0.125301f, +0.638214f, -0.759594f), + Vector3DFloat(+0.399976f, +0.226329f, -0.888141f), + Vector3DFloat(-0.704797f, +0.579196f, -0.409625f), + Vector3DFloat(-0.007629f, +0.072037f, +0.997373f), + Vector3DFloat(-0.284284f, +0.861559f, +0.420592f), + Vector3DFloat(+0.775941f, +0.385137f, -0.499586f), + Vector3DFloat(-0.234994f, +0.400120f, +0.885823f), + Vector3DFloat(+0.575813f, +0.632406f, +0.518172f), + Vector3DFloat(+0.076477f, +0.592931f, -0.801613f), + Vector3DFloat(+0.603536f, -0.788719f, -0.116900f), + Vector3DFloat(-0.301173f, -0.779883f, -0.548705f), + Vector3DFloat(-0.315064f, -0.948217f, +0.040230f), + Vector3DFloat(+0.332902f, +0.851413f, -0.405304f), + Vector3DFloat(-0.403429f, +0.778318f, +0.481110f), + Vector3DFloat(-0.213870f, +0.976545f, +0.024873f), + Vector3DFloat(-0.753760f, -0.519440f, +0.402528f), + Vector3DFloat(-0.293424f, +0.935690f, -0.195925f), + Vector3DFloat(-0.370354f, +0.922391f, -0.109697f), + Vector3DFloat(+0.278418f, +0.666623f, +0.691445f), + Vector3DFloat(-0.284329f, +0.930765f, +0.229857f), + Vector3DFloat(+0.860824f, -0.367097f, -0.352452f), + Vector3DFloat(+0.541854f, -0.702580f, -0.461275f), + Vector3DFloat(+0.912176f, +0.185368f, -0.365478f), + Vector3DFloat(+0.168057f, +0.931969f, -0.321232f), + Vector3DFloat(-0.267320f, +0.845122f, +0.462934f), + Vector3DFloat(-0.201487f, +0.198600f, +0.959146f), + Vector3DFloat(-0.839945f, -0.276826f, -0.466754f), + Vector3DFloat(-0.740956f, -0.484640f, +0.464874f), + Vector3DFloat(-0.383491f, +0.705487f, -0.596006f), + Vector3DFloat(-0.954405f, -0.026765f, -0.297313f), + Vector3DFloat(+0.468574f, +0.859438f, +0.204460f), + Vector3DFloat(-0.940360f, +0.331786f, +0.075105f), + Vector3DFloat(-0.852277f, +0.454172f, -0.259522f), + Vector3DFloat(-0.759647f, +0.519837f, -0.390776f), + Vector3DFloat(+0.111525f, -0.475265f, -0.872746f), + Vector3DFloat(-0.452079f, -0.035104f, +0.891287f), + Vector3DFloat(+0.390392f, -0.669936f, -0.631490f), + Vector3DFloat(-0.292073f, +0.321693f, -0.900670f), + Vector3DFloat(+0.104005f, +0.994338f, +0.021788f), + Vector3DFloat(+0.960865f, +0.271665f, +0.054189f), + Vector3DFloat(-0.723235f, +0.690428f, +0.015487f), + Vector3DFloat(+0.179328f, -0.278614f, +0.943513f), + Vector3DFloat(+0.673808f, +0.589682f, +0.445263f), + Vector3DFloat(+0.731197f, +0.497511f, +0.466726f), + Vector3DFloat(+0.153734f, -0.134017f, +0.978982f), + Vector3DFloat(+0.456781f, -0.221267f, -0.861622f), + Vector3DFloat(+0.688864f, +0.648593f, +0.323719f), + Vector3DFloat(-0.036351f, +0.715024f, -0.698155f), + Vector3DFloat(+0.979208f, -0.118292f, +0.164797f), + Vector3DFloat(-0.543655f, -0.797469f, -0.261692f), + Vector3DFloat(+0.474224f, -0.342549f, -0.811031f), + Vector3DFloat(+0.455954f, +0.830262f, +0.320580f), + Vector3DFloat(+0.050584f, -0.993831f, -0.098696f), + Vector3DFloat(-0.061916f, +0.662832f, +0.746204f), + Vector3DFloat(+0.153491f, -0.981695f, +0.112766f), + Vector3DFloat(-0.303003f, +0.664435f, +0.683165f), + Vector3DFloat(+0.490302f, +0.248088f, -0.835497f), + Vector3DFloat(-0.909045f, +0.282351f, -0.306455f), + Vector3DFloat(+0.412988f, -0.552647f, +0.723894f), + Vector3DFloat(-0.254003f, -0.874419f, +0.413370f), + Vector3DFloat(-0.254922f, +0.922643f, -0.289387f), + Vector3DFloat(+0.788379f, -0.515671f, +0.335474f), + Vector3DFloat(+0.704882f, -0.446475f, -0.551182f), + Vector3DFloat(+0.446454f, +0.893141f, -0.054572f), + Vector3DFloat(-0.139484f, +0.078095f, -0.987140f), + Vector3DFloat(+0.196257f, -0.117325f, -0.973508f), + Vector3DFloat(-0.887951f, -0.452728f, +0.081119f), + Vector3DFloat(+0.482286f, +0.838290f, -0.254304f), + Vector3DFloat(-0.085400f, +0.836828f, +0.540764f), + Vector3DFloat(-0.033243f, -0.288034f, +0.957043f), + Vector3DFloat(+0.262770f, -0.771585f, +0.579318f), + Vector3DFloat(-0.911785f, -0.235533f, +0.336411f), + Vector3DFloat(+0.927275f, +0.367451f, -0.071696f), + Vector3DFloat(+0.771172f, -0.229858f, +0.593683f), + Vector3DFloat(-0.375316f, -0.068341f, -0.924374f), + Vector3DFloat(-0.735343f, +0.284450f, -0.615109f), + Vector3DFloat(-0.985363f, +0.154529f, +0.071973f), + Vector3DFloat(-0.544949f, +0.792232f, -0.274589f), + Vector3DFloat(-0.565066f, -0.783807f, -0.257579f), + Vector3DFloat(-0.188990f, +0.764476f, -0.616328f), + Vector3DFloat(+0.011964f, -0.681395f, +0.731818f), + Vector3DFloat(+0.647082f, +0.652894f, -0.393719f), + Vector3DFloat(-0.883463f, +0.088810f, -0.460006f), + Vector3DFloat(-0.443140f, -0.048579f, -0.895135f), + Vector3DFloat(+0.925708f, +0.333853f, -0.177785f), + Vector3DFloat(-0.057825f, -0.850139f, +0.523373f), + Vector3DFloat(+0.376782f, +0.740216f, +0.556881f), + Vector3DFloat(-0.711665f, -0.184658f, -0.677816f), + Vector3DFloat(+0.410214f, -0.115790f, -0.904609f), + Vector3DFloat(+0.382722f, +0.646393f, -0.660076f), + Vector3DFloat(-0.300767f, -0.354337f, +0.885429f), + Vector3DFloat(+0.568398f, +0.272778f, +0.776219f), + Vector3DFloat(-0.157935f, +0.980750f, +0.114830f), + Vector3DFloat(+0.359219f, +0.495150f, -0.791068f), + Vector3DFloat(-0.349238f, +0.056262f, -0.935344f), + Vector3DFloat(-0.633800f, +0.743629f, +0.212869f), + Vector3DFloat(+0.097107f, -0.993326f, -0.062246f), + Vector3DFloat(+0.372454f, -0.806078f, -0.459908f), + Vector3DFloat(-0.263428f, +0.934015f, +0.241290f), + Vector3DFloat(-0.943443f, +0.122444f, +0.308095f), + Vector3DFloat(+0.408781f, +0.502375f, -0.761917f), + Vector3DFloat(+0.697179f, -0.332546f, -0.635102f), + Vector3DFloat(-0.491802f, +0.870583f, -0.014715f), + Vector3DFloat(+0.737536f, -0.656902f, +0.156592f), + Vector3DFloat(+0.827336f, -0.246097f, +0.504928f), + Vector3DFloat(-0.446202f, +0.667651f, +0.595941f), + Vector3DFloat(-0.964936f, -0.243630f, +0.097691f), + Vector3DFloat(+0.897134f, -0.435766f, -0.072518f), + Vector3DFloat(-0.669699f, -0.151247f, -0.727068f), + Vector3DFloat(-0.016765f, -0.955618f, +0.294130f), + Vector3DFloat(-0.230630f, +0.832879f, -0.503112f), + Vector3DFloat(+0.899464f, +0.318825f, -0.298856f), + Vector3DFloat(+0.058885f, -0.789911f, +0.610388f), + Vector3DFloat(+0.659402f, +0.666930f, +0.346977f), + Vector3DFloat(+0.284813f, -0.414001f, -0.864572f), + Vector3DFloat(+0.484149f, -0.789140f, -0.377964f), + Vector3DFloat(+0.738956f, +0.298547f, -0.603998f), + Vector3DFloat(+0.136326f, +0.352541f, -0.925813f), + Vector3DFloat(+0.868090f, +0.478579f, +0.131841f), + Vector3DFloat(+0.446372f, -0.633533f, -0.631972f), + Vector3DFloat(-0.464744f, -0.873724f, +0.143596f), + Vector3DFloat(-0.157889f, +0.556623f, -0.815624f), + Vector3DFloat(-0.916952f, -0.270205f, +0.293579f), + Vector3DFloat(-0.968515f, +0.157169f, -0.193071f), + Vector3DFloat(-0.428526f, -0.889206f, +0.160242f), + Vector3DFloat(+0.396152f, +0.173085f, +0.901724f), + Vector3DFloat(+0.966792f, +0.160015f, -0.199271f), + Vector3DFloat(-0.912490f, -0.111826f, +0.393519f), + Vector3DFloat(+0.866392f, -0.192509f, -0.460765f), + Vector3DFloat(+0.480992f, +0.492893f, -0.725054f), + Vector3DFloat(-0.355535f, +0.884194f, +0.302977f), + Vector3DFloat(+0.980976f, -0.055915f, +0.185905f), + Vector3DFloat(-0.740688f, +0.154276f, -0.653896f), + Vector3DFloat(+0.193789f, -0.135151f, -0.971689f), + Vector3DFloat(-0.301940f, -0.417607f, -0.856993f), + Vector3DFloat(-0.519232f, +0.773966f, -0.362455f), + Vector3DFloat(+0.938672f, -0.020909f, -0.344177f), + Vector3DFloat(+0.637853f, -0.449939f, +0.625058f), + Vector3DFloat(+0.544105f, -0.664601f, -0.512109f), + Vector3DFloat(-0.170728f, -0.774921f, +0.608563f), + Vector3DFloat(+0.669668f, +0.441721f, -0.597016f), + Vector3DFloat(-0.311388f, -0.044999f, -0.949217f), + Vector3DFloat(+0.146744f, +0.375501f, +0.915131f), + Vector3DFloat(-0.703678f, -0.557559f, -0.440414f), + Vector3DFloat(-0.470187f, +0.695298f, +0.543585f), + Vector3DFloat(-0.254132f, -0.184139f, +0.949479f), + Vector3DFloat(-0.900622f, +0.005714f, +0.434565f), + Vector3DFloat(-0.014656f, +0.303063f, -0.952858f), + Vector3DFloat(-0.865696f, -0.264074f, +0.425247f), + Vector3DFloat(+0.481061f, +0.842497f, +0.242445f), + Vector3DFloat(-0.450784f, +0.137271f, +0.882015f), + Vector3DFloat(+0.091619f, +0.964503f, +0.247669f), + Vector3DFloat(-0.135659f, -0.122365f, +0.983170f), + Vector3DFloat(-0.322292f, +0.502269f, +0.802405f), + Vector3DFloat(+0.157842f, +0.435303f, +0.886339f), + Vector3DFloat(+0.158697f, -0.622087f, -0.766696f), + Vector3DFloat(+0.427134f, -0.647168f, -0.631451f), + Vector3DFloat(-0.101271f, +0.917326f, +0.385042f), + Vector3DFloat(-0.351641f, -0.653340f, -0.670445f), + Vector3DFloat(-0.903498f, -0.392917f, +0.171195f), + Vector3DFloat(+0.227012f, -0.849095f, -0.476974f), + Vector3DFloat(-0.094069f, -0.890637f, +0.444878f), + Vector3DFloat(+0.803352f, -0.594284f, -0.038110f), + Vector3DFloat(-0.094739f, -0.865030f, -0.492695f), + Vector3DFloat(+0.264702f, -0.854667f, +0.446629f), + Vector3DFloat(-0.897678f, +0.277821f, -0.342037f), + Vector3DFloat(-0.327036f, +0.939653f, +0.100497f), + Vector3DFloat(-0.826248f, -0.337885f, -0.450719f), + Vector3DFloat(+0.066622f, -0.956883f, +0.282730f), + Vector3DFloat(-0.746913f, -0.121996f, +0.653635f), + Vector3DFloat(-0.671734f, +0.736418f, +0.080385f), + Vector3DFloat(+0.693715f, +0.576755f, -0.431408f), + Vector3DFloat(-0.788320f, -0.082995f, -0.609642f), + Vector3DFloat(-0.456573f, +0.863290f, -0.215108f), + Vector3DFloat(-0.622201f, +0.453957f, +0.637800f), + Vector3DFloat(+0.723922f, +0.655748f, +0.214319f), + Vector3DFloat(+0.882913f, -0.420816f, -0.208276f), + Vector3DFloat(-0.926551f, +0.212056f, -0.310703f), + Vector3DFloat(+0.388695f, -0.691965f, +0.608358f), + Vector3DFloat(+0.728427f, +0.198534f, -0.655728f), + Vector3DFloat(+0.319262f, +0.105299f, +0.941798f), + Vector3DFloat(-0.333911f, +0.881805f, +0.333050f), + Vector3DFloat(+0.245338f, -0.611922f, -0.751904f), + Vector3DFloat(+0.220061f, -0.101481f, -0.970193f), + Vector3DFloat(+0.930032f, -0.311841f, +0.194412f), + Vector3DFloat(+0.048087f, -0.993913f, +0.099115f), + Vector3DFloat(-0.275537f, +0.705669f, +0.652772f), + Vector3DFloat(+0.383019f, -0.163631f, -0.909132f), + Vector3DFloat(-0.135900f, -0.988939f, +0.059414f), + Vector3DFloat(-0.662199f, +0.747009f, +0.058896f), + Vector3DFloat(-0.124689f, +0.015288f, +0.992078f), + Vector3DFloat(+0.489432f, -0.555663f, -0.672082f), + Vector3DFloat(-0.780927f, -0.255976f, +0.569763f), + Vector3DFloat(+0.694171f, +0.278571f, -0.663720f), + Vector3DFloat(-0.604581f, -0.463542f, -0.647774f), + Vector3DFloat(-0.676259f, -0.684602f, -0.272018f), + Vector3DFloat(+0.494855f, -0.701192f, -0.513272f), + Vector3DFloat(+0.565633f, +0.823079f, +0.050993f), + Vector3DFloat(+0.050237f, -0.998492f, +0.022122f), + Vector3DFloat(-0.386389f, -0.893963f, -0.227011f), + Vector3DFloat(+0.888703f, -0.437519f, -0.137056f), + Vector3DFloat(-0.914197f, +0.390980f, +0.106670f), + Vector3DFloat(+0.778906f, -0.627140f, -0.001437f), + Vector3DFloat(-0.603014f, +0.672265f, -0.429458f), + Vector3DFloat(+0.501042f, -0.665212f, +0.553579f), + Vector3DFloat(-0.995164f, +0.092308f, -0.033577f), + Vector3DFloat(-0.998104f, +0.018497f, +0.058712f), + Vector3DFloat(+0.929569f, +0.123842f, -0.347225f), + Vector3DFloat(+0.235077f, -0.609238f, +0.757343f), + Vector3DFloat(-0.452902f, -0.887545f, +0.084525f), + Vector3DFloat(-0.137550f, -0.488131f, -0.861863f), + Vector3DFloat(+0.660545f, -0.371465f, +0.652453f), + Vector3DFloat(+0.747313f, -0.657236f, +0.097799f), + Vector3DFloat(-0.543312f, -0.315699f, -0.777911f), + Vector3DFloat(+0.189959f, -0.346861f, +0.918478f), + Vector3DFloat(+0.323571f, +0.300781f, +0.897125f), + Vector3DFloat(-0.482606f, +0.875832f, -0.003165f), + Vector3DFloat(-0.936502f, +0.291824f, -0.194430f), + Vector3DFloat(-0.503609f, -0.390560f, +0.770610f), + Vector3DFloat(-0.540142f, +0.002774f, -0.841569f), + Vector3DFloat(-0.085055f, -0.996376f, -0.000148f), + Vector3DFloat(-0.615309f, +0.059981f, -0.786000f), + Vector3DFloat(+0.718191f, +0.505958f, -0.477711f), + Vector3DFloat(-0.167397f, +0.844465f, -0.508780f), + Vector3DFloat(+0.636446f, -0.344036f, -0.690345f), + Vector3DFloat(+0.663267f, +0.700418f, -0.263613f), + Vector3DFloat(+0.602334f, +0.435514f, +0.668970f), + Vector3DFloat(-0.275820f, -0.393792f, +0.876842f), + Vector3DFloat(+0.437736f, -0.747931f, +0.498986f), + Vector3DFloat(+0.882319f, +0.417138f, +0.217965f), + Vector3DFloat(-0.851108f, -0.482384f, -0.207174f), + Vector3DFloat(+0.320590f, +0.898664f, +0.299375f), + Vector3DFloat(-0.621201f, -0.614972f, +0.485714f), + Vector3DFloat(+0.911173f, +0.041873f, +0.409892f), + Vector3DFloat(+0.729444f, +0.142692f, -0.668992f), + Vector3DFloat(+0.666307f, -0.735324f, +0.123831f), + Vector3DFloat(+0.463591f, +0.847227f, -0.259402f), + Vector3DFloat(+0.894296f, +0.059634f, +0.443484f), + Vector3DFloat(-0.736335f, -0.674274f, +0.056256f), + Vector3DFloat(+0.469502f, -0.733536f, +0.491420f), + Vector3DFloat(-0.391723f, -0.837099f, +0.381861f), + Vector3DFloat(-0.437372f, -0.437618f, -0.785618f), + Vector3DFloat(-0.203384f, -0.343038f, -0.917039f), + Vector3DFloat(-0.945306f, +0.221497f, +0.239450f), + Vector3DFloat(+0.773091f, +0.496793f, +0.394369f), + Vector3DFloat(-0.710103f, +0.093103f, +0.697915f), + Vector3DFloat(-0.456786f, +0.151779f, +0.876533f), + Vector3DFloat(+0.373153f, +0.587166f, -0.718326f), + Vector3DFloat(-0.559785f, -0.793881f, +0.237473f), + Vector3DFloat(-0.884665f, +0.422952f, +0.196163f), + Vector3DFloat(-0.468879f, +0.300549f, -0.830556f), + Vector3DFloat(+0.958105f, +0.285330f, -0.024919f), + Vector3DFloat(+0.825326f, -0.423197f, -0.373819f), + Vector3DFloat(-0.034122f, +0.999414f, +0.002781f), + Vector3DFloat(-0.904795f, -0.041789f, -0.423792f), + Vector3DFloat(-0.799927f, +0.541477f, -0.258687f), + Vector3DFloat(+0.995132f, +0.000543f, -0.098546f), + Vector3DFloat(+0.843984f, -0.507103f, -0.174749f), + Vector3DFloat(-0.640934f, +0.618163f, +0.455058f), + Vector3DFloat(+0.543397f, +0.492878f, +0.679553f), + Vector3DFloat(+0.408980f, -0.467105f, +0.783932f), + Vector3DFloat(+0.219682f, +0.823953f, +0.522343f), + Vector3DFloat(+0.845523f, +0.410442f, -0.341509f), + Vector3DFloat(-0.997099f, +0.057254f, -0.050159f), + Vector3DFloat(+0.535588f, +0.112415f, +0.836964f), + Vector3DFloat(+0.139015f, +0.182777f, +0.973277f), + Vector3DFloat(+0.681261f, +0.731126f, -0.036585f), + Vector3DFloat(-0.161589f, +0.986188f, -0.036352f), + Vector3DFloat(-0.294098f, +0.640063f, +0.709806f), + Vector3DFloat(+0.213370f, -0.880985f, -0.422301f), + Vector3DFloat(-0.903331f, +0.383376f, +0.192395f), + Vector3DFloat(+0.020283f, +0.989297f, -0.144498f), + Vector3DFloat(+0.550858f, -0.603955f, +0.576016f), + Vector3DFloat(-0.297499f, -0.396883f, -0.868319f), + Vector3DFloat(-0.125581f, +0.971238f, +0.202303f), + Vector3DFloat(+0.994606f, -0.096856f, +0.037125f), + Vector3DFloat(+0.959844f, -0.254636f, -0.117729f), + Vector3DFloat(-0.332961f, +0.808031f, +0.486028f), + Vector3DFloat(+0.118411f, -0.818829f, +0.561692f), + Vector3DFloat(-0.329010f, +0.932571f, +0.148536f), + Vector3DFloat(+0.386616f, -0.386923f, -0.837149f), + Vector3DFloat(+0.501223f, -0.201907f, -0.841433f), + Vector3DFloat(+0.555119f, -0.793008f, -0.250959f), + Vector3DFloat(-0.512485f, +0.850268f, -0.120011f), + Vector3DFloat(+0.573352f, +0.737293f, +0.357306f), + Vector3DFloat(+0.315311f, -0.182192f, +0.931335f), + Vector3DFloat(+0.156167f, -0.963694f, -0.216579f), + Vector3DFloat(-0.285174f, -0.542273f, +0.790326f), + Vector3DFloat(-0.277593f, +0.668866f, +0.689609f), + Vector3DFloat(+0.319798f, -0.921924f, +0.218599f), + Vector3DFloat(-0.727455f, -0.686116f, -0.007338f), + Vector3DFloat(+0.219712f, -0.952663f, +0.210141f), + Vector3DFloat(+0.491792f, +0.552463f, -0.672997f), + Vector3DFloat(-0.526640f, +0.820445f, +0.222533f) + }; +} + +#endif //__PolyVox_RandomUnitVectors_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/RandomVectors.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/RandomVectors.h new file mode 100644 index 0000000..f23d6e6 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/RandomVectors.h @@ -0,0 +1,1063 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_RandomVectors_H__ +#define __PolyVox_RandomVectors_H__ + +#include "PlatformDefinitions.h" + +#include "../Vector.h" + +namespace PolyVox +{ + const Vector3DFloat randomVectors[1024] = + { + Vector3DFloat(+0.348918f, -0.385662f, +0.650197f), + Vector3DFloat(-0.259255f, +0.791559f, +0.920957f), + Vector3DFloat(+0.940733f, -0.101535f, +0.250160f), + Vector3DFloat(-0.308939f, +0.367656f, +0.877987f), + Vector3DFloat(+0.112949f, -0.047090f, -0.730277f), + Vector3DFloat(-0.605579f, +0.039705f, +0.310160f), + Vector3DFloat(+0.086459f, +0.376446f, -0.496078f), + Vector3DFloat(+0.565661f, -0.261574f, -0.924986f), + Vector3DFloat(-0.285745f, -0.792047f, -0.582568f), + Vector3DFloat(+0.943175f, +0.226844f, +0.823481f), + Vector3DFloat(+0.599414f, +0.846797f, -0.438215f), + Vector3DFloat(-0.502731f, -0.907407f, +0.170751f), + Vector3DFloat(+0.136204f, -0.735527f, -0.066622f), + Vector3DFloat(-0.618763f, +0.825617f, -0.325053f), + Vector3DFloat(+0.942076f, +0.608325f, -0.532517f), + Vector3DFloat(-0.466414f, -0.248756f, -0.189856f), + Vector3DFloat(+0.618213f, +0.879513f, +0.120090f), + Vector3DFloat(-0.918393f, +0.876522f, +0.265114f), + Vector3DFloat(+0.345195f, +0.670705f, -0.914243f), + Vector3DFloat(-0.600757f, -0.417646f, -0.736747f), + Vector3DFloat(-0.271828f, +0.215674f, +0.890622f), + Vector3DFloat(+0.100986f, +0.821955f, +0.429975f), + Vector3DFloat(+0.811823f, -0.506943f, +0.635853f), + Vector3DFloat(+0.647084f, +0.297403f, -0.714774f), + Vector3DFloat(+0.531907f, -0.917417f, +0.795770f), + Vector3DFloat(-0.151585f, +0.250038f, +0.959105f), + Vector3DFloat(+0.311747f, -0.850948f, +0.946348f), + Vector3DFloat(+0.641407f, -0.747978f, +0.464583f), + Vector3DFloat(+0.297769f, -0.427839f, +0.867489f), + Vector3DFloat(+0.305032f, +0.985900f, +0.071261f), + Vector3DFloat(+0.105930f, -0.895016f, +0.871700f), + Vector3DFloat(+0.060335f, -0.312235f, +0.247475f), + Vector3DFloat(+0.174718f, +0.776055f, -0.783563f), + Vector3DFloat(-0.018342f, -0.031343f, +0.533982f), + Vector3DFloat(+0.136753f, -0.201575f, -0.694998f), + Vector3DFloat(+0.606006f, +0.353069f, -0.174841f), + Vector3DFloat(-0.720573f, +0.272805f, -0.679189f), + Vector3DFloat(+0.802484f, -0.649281f, -0.884274f), + Vector3DFloat(-0.577807f, -0.794610f, +0.227332f), + Vector3DFloat(-0.391644f, +0.440474f, -0.927854f), + Vector3DFloat(+0.631825f, +0.072115f, +0.943785f), + Vector3DFloat(-0.898312f, +0.257363f, -0.942930f), + Vector3DFloat(-0.608264f, +0.583667f, +0.228126f), + Vector3DFloat(-0.788202f, +0.777764f, +0.722953f), + Vector3DFloat(-0.624622f, -0.296976f, -0.382122f), + Vector3DFloat(+0.921323f, -0.356365f, -0.750542f), + Vector3DFloat(-0.899106f, +0.578234f, +0.937132f), + Vector3DFloat(+0.830744f, -0.789422f, -0.026154f), + Vector3DFloat(+0.720634f, +0.135166f, -0.366985f), + Vector3DFloat(+0.796930f, +0.687124f, +0.807855f), + Vector3DFloat(+0.262001f, -0.120945f, -0.196631f), + Vector3DFloat(+0.562426f, -0.886166f, +0.699149f), + Vector3DFloat(+0.047945f, -0.781793f, +0.465987f), + Vector3DFloat(+0.219275f, +0.152440f, +0.726127f), + Vector3DFloat(-0.970641f, -0.384136f, -0.340739f), + Vector3DFloat(+0.244606f, +0.969848f, +0.466903f), + Vector3DFloat(+0.608753f, +0.329936f, -0.411542f), + Vector3DFloat(+0.959593f, -0.833186f, -0.698721f), + Vector3DFloat(+0.475692f, -0.320658f, +0.507675f), + Vector3DFloat(-0.155431f, -0.050447f, -0.455855f), + Vector3DFloat(-0.738456f, +0.917173f, -0.407758f), + Vector3DFloat(-0.555284f, +0.842891f, -0.984619f), + Vector3DFloat(+0.696951f, +0.155553f, -0.031526f), + Vector3DFloat(-0.131565f, -0.563707f, +0.076815f), + Vector3DFloat(-0.319376f, +0.620106f, +0.567614f), + Vector3DFloat(-0.628163f, -0.813959f, -0.438581f), + Vector3DFloat(+0.484115f, +0.060640f, -0.176183f), + Vector3DFloat(-0.523240f, -0.572314f, +0.633778f), + Vector3DFloat(-0.524949f, -0.334574f, -0.326701f), + Vector3DFloat(+0.747673f, +0.725944f, +0.701651f), + Vector3DFloat(-0.500961f, +0.564867f, -0.902341f), + Vector3DFloat(+0.995422f, -0.245949f, +0.301065f), + Vector3DFloat(+0.655080f, -0.783380f, +0.835871f), + Vector3DFloat(+0.541795f, -0.693472f, -0.355083f), + Vector3DFloat(+0.891110f, +0.891171f, -0.891903f), + Vector3DFloat(+0.507675f, -0.949034f, -0.485214f), + Vector3DFloat(-0.116123f, +0.368999f, +0.514756f), + Vector3DFloat(-0.859432f, -0.525071f, +0.632008f), + Vector3DFloat(-0.707205f, +0.077914f, +0.930540f), + Vector3DFloat(-0.783380f, -0.577074f, -0.180212f), + Vector3DFloat(-0.047884f, -0.523789f, +0.471664f), + Vector3DFloat(-0.210791f, +0.904904f, -0.585864f), + Vector3DFloat(+0.132664f, +0.792230f, +0.707266f), + Vector3DFloat(-0.735710f, -0.263710f, -0.258827f), + Vector3DFloat(+0.912290f, +0.497421f, -0.518845f), + Vector3DFloat(-0.790521f, -0.707144f, +0.314982f), + Vector3DFloat(-0.799249f, +0.381207f, -0.756462f), + Vector3DFloat(+0.694998f, -0.521836f, +0.957213f), + Vector3DFloat(+0.310709f, +0.049837f, +0.920652f), + Vector3DFloat(+0.581530f, +0.164647f, +0.560900f), + Vector3DFloat(+0.406903f, -0.650563f, -0.674551f), + Vector3DFloat(-0.749016f, +0.119663f, -0.040193f), + Vector3DFloat(+0.955260f, -0.142552f, +0.175756f), + Vector3DFloat(-0.925108f, -0.970824f, -0.430952f), + Vector3DFloat(+0.666372f, +0.449507f, -0.801813f), + Vector3DFloat(-0.311991f, -0.079928f, -0.608142f), + Vector3DFloat(-0.344829f, +0.280862f, +0.800775f), + Vector3DFloat(-0.880123f, +0.318217f, -0.120212f), + Vector3DFloat(-0.146519f, +0.573412f, -0.358013f), + Vector3DFloat(+0.297220f, -0.889523f, +0.246620f), + Vector3DFloat(-0.628834f, -0.383404f, -0.630360f), + Vector3DFloat(-0.397382f, +0.547533f, -0.579150f), + Vector3DFloat(+0.758049f, +0.631947f, -0.916807f), + Vector3DFloat(-0.678030f, -0.606433f, -0.881527f), + Vector3DFloat(+0.213233f, +0.854060f, -0.043428f), + Vector3DFloat(+0.175085f, +0.139500f, -0.208472f), + Vector3DFloat(+0.983520f, -0.389386f, +0.178076f), + Vector3DFloat(+0.956603f, +0.696951f, -0.307657f), + Vector3DFloat(-0.276345f, +0.576220f, +0.182104f), + Vector3DFloat(+0.864742f, -0.657582f, +0.253639f), + Vector3DFloat(-0.275735f, -0.012177f, +0.306619f), + Vector3DFloat(-0.385235f, -0.881649f, +0.658071f), + Vector3DFloat(-0.117466f, -0.306681f, -0.235755f), + Vector3DFloat(+0.173254f, +0.685720f, +0.116733f), + Vector3DFloat(-0.641041f, +0.704642f, -0.585864f), + Vector3DFloat(+0.154820f, +0.999939f, -0.761345f), + Vector3DFloat(-0.726310f, +0.695181f, -0.490036f), + Vector3DFloat(-0.149510f, -0.593188f, -0.794122f), + Vector3DFloat(+0.798212f, +0.872555f, -0.361980f), + Vector3DFloat(+0.749687f, -0.931944f, +0.519211f), + Vector3DFloat(-0.151952f, -0.889096f, -0.313822f), + Vector3DFloat(-0.467879f, +0.289651f, -0.901242f), + Vector3DFloat(+0.522752f, +0.406781f, +0.157079f), + Vector3DFloat(+0.088534f, -0.421735f, -0.236122f), + Vector3DFloat(+0.722221f, -0.136692f, -0.292825f), + Vector3DFloat(-0.572436f, +0.349162f, +0.819697f), + Vector3DFloat(+0.252113f, +0.773614f, -0.299051f), + Vector3DFloat(-0.401410f, +0.400250f, -0.091037f), + Vector3DFloat(+0.449507f, +0.205115f, +0.075533f), + Vector3DFloat(+0.246803f, -0.197851f, -0.322123f), + Vector3DFloat(-0.822077f, +0.037263f, +0.157445f), + Vector3DFloat(+0.373455f, +0.983154f, -0.580920f), + Vector3DFloat(+0.201758f, -0.075289f, +0.514878f), + Vector3DFloat(+0.552477f, +0.760430f, +0.938963f), + Vector3DFloat(-0.297525f, -0.603504f, -0.285318f), + Vector3DFloat(-0.504257f, +0.135899f, +0.694021f), + Vector3DFloat(-0.701895f, +0.509140f, -0.768914f), + Vector3DFloat(+0.725639f, +0.083834f, -0.985961f), + Vector3DFloat(+0.617847f, -0.604114f, +0.976440f), + Vector3DFloat(-0.557115f, +0.562853f, +0.214087f), + Vector3DFloat(-0.480819f, -0.048738f, -0.759392f), + Vector3DFloat(-0.268105f, -0.168493f, -0.141881f), + Vector3DFloat(+0.664357f, -0.999207f, +0.486740f), + Vector3DFloat(-0.739128f, +0.089328f, +0.611194f), + Vector3DFloat(-0.355876f, +0.889523f, +0.701895f), + Vector3DFloat(-0.123692f, -0.252358f, -0.739250f), + Vector3DFloat(+0.405438f, -0.276772f, -0.896786f), + Vector3DFloat(-0.803644f, +0.517563f, -0.146886f), + Vector3DFloat(+0.647511f, +0.766289f, -0.811518f), + Vector3DFloat(-0.266457f, -0.779534f, +0.720634f), + Vector3DFloat(-0.643849f, -0.014130f, -0.345134f), + Vector3DFloat(-0.527390f, +0.047700f, -0.271340f), + Vector3DFloat(+0.993957f, -0.305643f, +0.841731f), + Vector3DFloat(+0.441816f, -0.849117f, -0.411664f), + Vector3DFloat(+0.303323f, -0.088473f, -0.677602f), + Vector3DFloat(+0.897824f, +0.203833f, +0.821039f), + Vector3DFloat(+0.468123f, +0.717338f, +0.338542f), + Vector3DFloat(-0.452986f, -0.830622f, -0.832942f), + Vector3DFloat(-0.245582f, -0.273171f, -0.820612f), + Vector3DFloat(-0.007660f, -0.799371f, +0.156896f), + Vector3DFloat(-0.022919f, +0.152013f, +0.614246f), + Vector3DFloat(-0.414045f, +0.637440f, -0.542711f), + Vector3DFloat(+0.453108f, -0.034516f, +0.330607f), + Vector3DFloat(+0.324015f, +0.689505f, +0.719108f), + Vector3DFloat(-0.236854f, +0.700491f, +0.276406f), + Vector3DFloat(-0.405316f, +0.871944f, +0.233863f), + Vector3DFloat(+0.898373f, +0.660756f, -0.914609f), + Vector3DFloat(+0.737114f, -0.179601f, -0.990539f), + Vector3DFloat(-0.536241f, -0.980712f, -0.352702f), + Vector3DFloat(+0.730094f, -0.970214f, -0.857967f), + Vector3DFloat(-0.194800f, -0.286782f, +0.604236f), + Vector3DFloat(+0.163366f, -0.441755f, -0.149022f), + Vector3DFloat(+0.457564f, +0.433149f, -0.626698f), + Vector3DFloat(+0.192846f, -0.909848f, +0.501572f), + Vector3DFloat(+0.444563f, -0.377789f, -0.545213f), + Vector3DFloat(-0.296670f, -0.809259f, +0.614246f), + Vector3DFloat(-0.068209f, +0.480148f, +0.537828f), + Vector3DFloat(+0.638173f, +0.371685f, -0.495956f), + Vector3DFloat(+0.798822f, +0.767510f, +0.516282f), + Vector3DFloat(-0.336161f, -0.035615f, +0.058687f), + Vector3DFloat(-0.888852f, -0.022370f, +0.215552f), + Vector3DFloat(-0.737541f, -0.977783f, -0.506638f), + Vector3DFloat(+0.471969f, +0.429670f, +0.668508f), + Vector3DFloat(+0.240394f, -0.212500f, -0.026215f), + Vector3DFloat(-0.916379f, -0.706229f, -0.593799f), + Vector3DFloat(-0.246681f, +0.919736f, -0.984741f), + Vector3DFloat(+0.291055f, -0.263771f, +0.703726f), + Vector3DFloat(-0.468245f, -0.062777f, +0.808527f), + Vector3DFloat(+0.661245f, +0.514817f, -0.715995f), + Vector3DFloat(-0.709830f, -0.580920f, +0.323710f), + Vector3DFloat(-0.463912f, -0.279092f, -0.101291f), + Vector3DFloat(-0.426252f, -0.292520f, -0.523057f), + Vector3DFloat(-0.285928f, -0.806574f, +0.701468f), + Vector3DFloat(-0.216468f, +0.385968f, +0.031953f), + Vector3DFloat(+0.737053f, +0.683767f, +0.684561f), + Vector3DFloat(+0.080172f, -0.063753f, +0.526902f), + Vector3DFloat(+0.414228f, +0.367351f, +0.884335f), + Vector3DFloat(-0.460677f, -0.048189f, -0.403851f), + Vector3DFloat(+0.973998f, +0.039399f, -0.148839f), + Vector3DFloat(+0.578539f, -0.651173f, +0.859432f), + Vector3DFloat(-0.172948f, +0.534593f, +0.255531f), + Vector3DFloat(+0.537584f, -0.570116f, +0.317606f), + Vector3DFloat(-0.380535f, +0.841548f, -0.274880f), + Vector3DFloat(+0.627247f, +0.655507f, -0.813532f), + Vector3DFloat(+0.288186f, +0.273171f, -0.674123f), + Vector3DFloat(-0.489303f, +0.828913f, +0.552599f), + Vector3DFloat(-0.541002f, +0.170019f, -0.242836f), + Vector3DFloat(+0.802972f, +0.340190f, +0.414716f), + Vector3DFloat(-0.997253f, -0.806635f, +0.588122f), + Vector3DFloat(+0.011017f, -0.599109f, -0.183325f), + Vector3DFloat(-0.871578f, -0.430708f, -0.042634f), + Vector3DFloat(+0.144627f, -0.921751f, +0.142003f), + Vector3DFloat(-0.695059f, -0.091037f, -0.647694f), + Vector3DFloat(-0.346477f, +0.663381f, -0.528977f), + Vector3DFloat(-0.194739f, +0.724967f, +0.615894f), + Vector3DFloat(+0.741874f, +0.720695f, -0.544847f), + Vector3DFloat(-0.984863f, +0.715445f, +0.461287f), + Vector3DFloat(-0.277871f, +0.329936f, +0.678091f), + Vector3DFloat(+0.090854f, +0.565905f, -0.254250f), + Vector3DFloat(-0.844050f, +0.781915f, -0.783929f), + Vector3DFloat(+0.332377f, -0.336528f, +0.820673f), + Vector3DFloat(-0.673391f, +0.589953f, -0.685598f), + Vector3DFloat(+0.022370f, +0.979980f, +0.686453f), + Vector3DFloat(-0.640065f, +0.369488f, +0.022919f), + Vector3DFloat(+0.699088f, -0.286355f, +0.684378f), + Vector3DFloat(-0.702139f, -0.827754f, +0.528367f), + Vector3DFloat(+0.150365f, -0.669851f, -0.695486f), + Vector3DFloat(+0.885617f, +0.492416f, -0.964599f), + Vector3DFloat(-0.923643f, -0.338847f, -0.369060f), + Vector3DFloat(+0.009064f, +0.632435f, +0.628956f), + Vector3DFloat(+0.620411f, +0.959777f, -0.769890f), + Vector3DFloat(+0.865413f, +0.685659f, -0.149327f), + Vector3DFloat(-0.933042f, +0.517258f, +0.168493f), + Vector3DFloat(+0.309732f, +0.299417f, +0.995361f), + Vector3DFloat(+0.196814f, -0.128025f, +0.565233f), + Vector3DFloat(-0.343669f, +0.889157f, +0.616688f), + Vector3DFloat(-0.676870f, +0.035432f, +0.906430f), + Vector3DFloat(-0.238868f, +0.320475f, -0.307596f), + Vector3DFloat(+0.164159f, +0.774468f, +0.502792f), + Vector3DFloat(+0.733146f, +0.517563f, +0.572741f), + Vector3DFloat(+0.676931f, -0.930235f, +0.231056f), + Vector3DFloat(-0.640370f, +0.241127f, -0.518479f), + Vector3DFloat(-0.953795f, +0.673086f, -0.706656f), + Vector3DFloat(+0.538621f, -0.340495f, +0.202124f), + Vector3DFloat(+0.431501f, +0.452315f, +0.422651f), + Vector3DFloat(+0.935606f, -0.442793f, -0.087191f), + Vector3DFloat(-0.921873f, -0.794733f, -0.003388f), + Vector3DFloat(+0.978576f, +0.342814f, -0.813898f), + Vector3DFloat(-0.750969f, +0.077853f, -0.849117f), + Vector3DFloat(+0.416120f, +0.678030f, +0.187475f), + Vector3DFloat(+0.370342f, -0.101901f, -0.544053f), + Vector3DFloat(+0.248512f, +0.803766f, -0.654042f), + Vector3DFloat(-0.925230f, +0.883480f, +0.287698f), + Vector3DFloat(-0.861873f, -0.263771f, +0.476730f), + Vector3DFloat(-0.298868f, -0.459517f, +0.932798f), + Vector3DFloat(+0.680532f, +0.697928f, +0.761162f), + Vector3DFloat(-0.466964f, -0.590625f, +0.972716f), + Vector3DFloat(+0.400067f, -0.316507f, +0.385418f), + Vector3DFloat(-0.123814f, -0.144444f, -0.161290f), + Vector3DFloat(-0.703726f, +0.189489f, +0.250099f), + Vector3DFloat(-0.766533f, -0.369854f, +0.871395f), + Vector3DFloat(-0.561205f, -0.891415f, +0.247658f), + Vector3DFloat(+0.590991f, +0.661489f, -0.996887f), + Vector3DFloat(-0.244667f, +0.857723f, +0.402692f), + Vector3DFloat(-0.574572f, -0.257790f, +0.561449f), + Vector3DFloat(+0.020600f, -0.784173f, -0.057711f), + Vector3DFloat(+0.735954f, +0.708487f, +0.913022f), + Vector3DFloat(-0.615101f, -0.643666f, +0.350017f), + Vector3DFloat(+0.436933f, +0.596423f, +0.985412f), + Vector3DFloat(-0.167577f, +0.400555f, +0.914670f), + Vector3DFloat(-0.920896f, -0.621570f, -0.637074f), + Vector3DFloat(-0.020356f, -0.234657f, +0.460860f), + Vector3DFloat(+0.336650f, -0.537767f, +0.907712f), + Vector3DFloat(-0.138768f, +0.860653f, +0.093661f), + Vector3DFloat(-0.733512f, -0.564196f, -0.046724f), + Vector3DFloat(+0.058260f, -0.429060f, +0.150792f), + Vector3DFloat(+0.255837f, -0.187780f, +0.312601f), + Vector3DFloat(-0.050081f, +0.680105f, -0.609485f), + Vector3DFloat(+0.075411f, +0.016511f, -0.127293f), + Vector3DFloat(-0.735710f, -0.787957f, +0.992248f), + Vector3DFloat(-0.191931f, +0.812311f, +0.681692f), + Vector3DFloat(-0.284402f, -0.177160f, -0.533128f), + Vector3DFloat(+0.859432f, +0.042940f, +0.404096f), + Vector3DFloat(+0.599841f, +0.131260f, +0.313028f), + Vector3DFloat(-0.955809f, -0.792474f, +0.086947f), + Vector3DFloat(-0.980712f, -0.525498f, -0.539598f), + Vector3DFloat(-0.877377f, -0.748222f, +0.590320f), + Vector3DFloat(-0.822443f, -0.733634f, -0.529588f), + Vector3DFloat(+0.379620f, -0.710013f, +0.038484f), + Vector3DFloat(-0.826472f, -0.831050f, -0.645436f), + Vector3DFloat(+0.160131f, -0.977050f, -0.502609f), + Vector3DFloat(-0.818964f, +0.921567f, -0.011261f), + Vector3DFloat(+0.932005f, -0.364727f, +0.023103f), + Vector3DFloat(-0.923826f, -0.862300f, +0.680410f), + Vector3DFloat(-0.298379f, +0.196936f, -0.486618f), + Vector3DFloat(-0.281411f, -0.045747f, -0.252602f), + Vector3DFloat(+0.706534f, +0.296976f, +0.672292f), + Vector3DFloat(-0.543077f, +0.319376f, +0.238075f), + Vector3DFloat(-0.501938f, +0.067293f, +0.119602f), + Vector3DFloat(-0.740287f, -0.783197f, +0.407514f), + Vector3DFloat(-0.933470f, -0.855098f, -0.503952f), + Vector3DFloat(-0.574877f, -0.533067f, +0.525437f), + Vector3DFloat(+0.785394f, -0.262612f, +0.571642f), + Vector3DFloat(-0.659108f, -0.811396f, +0.264138f), + Vector3DFloat(+0.926695f, -0.963622f, +0.121372f), + Vector3DFloat(+0.505661f, -0.209815f, -0.439131f), + Vector3DFloat(-0.433882f, +0.026887f, +0.928953f), + Vector3DFloat(-0.771599f, +0.737785f, -0.288003f), + Vector3DFloat(-0.894406f, +0.505905f, +0.971068f), + Vector3DFloat(+0.350383f, +0.570421f, -0.211646f), + Vector3DFloat(+0.644093f, -0.882748f, -0.131382f), + Vector3DFloat(+0.225745f, +0.948973f, -0.488327f), + Vector3DFloat(+0.277810f, -0.337748f, +0.322672f), + Vector3DFloat(-0.686514f, +0.185766f, +0.752129f), + Vector3DFloat(+0.350566f, +0.122959f, +0.722526f), + Vector3DFloat(-0.687002f, +0.955260f, -0.955687f), + Vector3DFloat(+0.958983f, -0.019074f, -0.317118f), + Vector3DFloat(+0.076937f, -0.015839f, -0.772027f), + Vector3DFloat(+0.899777f, -0.224647f, +0.174230f), + Vector3DFloat(+0.805719f, -0.288797f, +0.742119f), + Vector3DFloat(+0.964904f, -0.322794f, +0.416486f), + Vector3DFloat(-0.485641f, -0.559130f, -0.500168f), + Vector3DFloat(+0.310282f, +0.408185f, -0.946471f), + Vector3DFloat(-0.279031f, +0.645131f, -0.118259f), + Vector3DFloat(+0.780694f, -0.650136f, -0.433943f), + Vector3DFloat(+0.981262f, +0.039521f, -0.532395f), + Vector3DFloat(+0.830866f, +0.430769f, -0.333293f), + Vector3DFloat(-0.462081f, -0.872799f, -0.070711f), + Vector3DFloat(+0.276894f, -0.418683f, -0.198767f), + Vector3DFloat(+0.217750f, +0.312662f, -0.725211f), + Vector3DFloat(-0.193091f, -0.522752f, -0.901486f), + Vector3DFloat(+0.040071f, -0.307291f, +0.622669f), + Vector3DFloat(-0.788446f, -0.817438f, -0.566027f), + Vector3DFloat(-0.947508f, -0.519822f, +0.143468f), + Vector3DFloat(-0.072970f, -0.580920f, +0.925230f), + Vector3DFloat(-0.072359f, +0.954772f, +0.980163f), + Vector3DFloat(+0.954344f, -0.229774f, -0.562059f), + Vector3DFloat(+0.095004f, +0.123020f, +0.103366f), + Vector3DFloat(+0.784478f, -0.571764f, +0.774529f), + Vector3DFloat(-0.113498f, -0.852229f, +0.422468f), + Vector3DFloat(-0.128941f, -0.637196f, -0.590869f), + Vector3DFloat(+0.603259f, -0.670766f, +0.303201f), + Vector3DFloat(+0.693960f, +0.278542f, +0.171422f), + Vector3DFloat(+0.801813f, +0.236671f, +0.195227f), + Vector3DFloat(-0.193823f, +0.684072f, -0.594714f), + Vector3DFloat(+0.715201f, +0.750725f, +0.591479f), + Vector3DFloat(+0.698782f, +0.073214f, +0.106052f), + Vector3DFloat(+0.803522f, -0.470809f, +0.279763f), + Vector3DFloat(+0.099704f, +0.861385f, -0.397687f), + Vector3DFloat(+0.230506f, -0.993286f, +0.054292f), + Vector3DFloat(-0.292398f, +0.585376f, +0.762139f), + Vector3DFloat(-0.168004f, +0.731132f, -0.020051f), + Vector3DFloat(+0.577441f, +0.205359f, +0.703848f), + Vector3DFloat(-0.869076f, +0.873653f, -0.802301f), + Vector3DFloat(+0.697256f, +0.399335f, +0.842708f), + Vector3DFloat(-0.590258f, -0.620777f, -0.628040f), + Vector3DFloat(-0.048982f, +0.759697f, -0.957335f), + Vector3DFloat(+0.026582f, +0.696402f, -0.537645f), + Vector3DFloat(+0.919431f, +0.040254f, +0.931394f), + Vector3DFloat(+0.308512f, +0.591052f, -0.194739f), + Vector3DFloat(-0.934202f, +0.307718f, -0.688894f), + Vector3DFloat(-0.285318f, +0.460860f, +0.757012f), + Vector3DFloat(+0.048799f, -0.720389f, +0.325968f), + Vector3DFloat(-0.202246f, +0.068697f, +0.641407f), + Vector3DFloat(-0.566088f, +0.523301f, +0.857295f), + Vector3DFloat(+0.040193f, -0.036836f, +0.699881f), + Vector3DFloat(-0.789422f, -0.195959f, -0.217505f), + Vector3DFloat(-0.836665f, +0.293741f, +0.418867f), + Vector3DFloat(+0.489486f, +0.954344f, +0.486007f), + Vector3DFloat(-0.755913f, -0.485153f, +0.253822f), + Vector3DFloat(+0.823420f, -0.565722f, -0.393353f), + Vector3DFloat(-0.817560f, +0.851436f, -0.368755f), + Vector3DFloat(+0.004791f, -0.474899f, -0.299417f), + Vector3DFloat(-0.012726f, +0.620289f, -0.555773f), + Vector3DFloat(+0.197058f, -0.916318f, -0.469466f), + Vector3DFloat(+0.243812f, +0.820734f, -0.694021f), + Vector3DFloat(-0.896359f, -0.753716f, -0.676321f), + Vector3DFloat(-0.761589f, -0.936033f, -0.154149f), + Vector3DFloat(+0.821528f, +0.641224f, -0.188025f), + Vector3DFloat(+0.799432f, +0.168981f, +0.571520f), + Vector3DFloat(+0.309793f, -0.181005f, -0.565416f), + Vector3DFloat(+0.211890f, -0.153539f, -0.473312f), + Vector3DFloat(+0.284097f, +0.968444f, -0.005829f), + Vector3DFloat(+0.835994f, +0.087374f, -0.599780f), + Vector3DFloat(+0.068270f, -0.178930f, -0.439741f), + Vector3DFloat(-0.455611f, +0.404218f, -0.862911f), + Vector3DFloat(+0.754143f, +0.197058f, +0.762749f), + Vector3DFloat(+0.053499f, -0.794549f, -0.285257f), + Vector3DFloat(+0.176916f, +0.163121f, -0.941954f), + Vector3DFloat(-0.102817f, -0.446944f, +0.830195f), + Vector3DFloat(+0.970824f, -0.484848f, -0.661977f), + Vector3DFloat(-0.561998f, -0.377544f, -0.955321f), + Vector3DFloat(-0.434980f, +0.501022f, +0.627186f), + Vector3DFloat(-0.828120f, +0.591540f, +0.701895f), + Vector3DFloat(-0.327555f, +0.628346f, -0.159581f), + Vector3DFloat(-0.082980f, -0.308084f, -0.077731f), + Vector3DFloat(+0.858150f, -0.706473f, +0.886532f), + Vector3DFloat(+0.526475f, +0.001373f, +0.438276f), + Vector3DFloat(-0.594958f, +0.084994f, -0.935057f), + Vector3DFloat(+0.783746f, -0.501877f, -0.797052f), + Vector3DFloat(-0.835566f, -0.808405f, +0.956359f), + Vector3DFloat(+0.380169f, +0.184118f, +0.857540f), + Vector3DFloat(+0.647206f, +0.652089f, -0.895383f), + Vector3DFloat(-0.421369f, -0.038667f, +0.500046f), + Vector3DFloat(-0.478133f, +0.447432f, +0.981750f), + Vector3DFloat(+0.593921f, -0.330485f, -0.966674f), + Vector3DFloat(-0.811823f, +0.928892f, -0.741935f), + Vector3DFloat(+0.115879f, -0.490707f, -0.080355f), + Vector3DFloat(+0.443159f, +0.030061f, -0.465560f), + Vector3DFloat(+0.013703f, -0.765435f, -0.311502f), + Vector3DFloat(+0.698782f, -0.612903f, +0.660207f), + Vector3DFloat(+0.341227f, -0.746940f, +0.284341f), + Vector3DFloat(-0.005036f, -0.863460f, -0.168432f), + Vector3DFloat(-0.434370f, -0.629933f, +0.545152f), + Vector3DFloat(-0.570544f, +0.023591f, +0.072970f), + Vector3DFloat(+0.709830f, +0.603626f, +0.031831f), + Vector3DFloat(-0.148961f, +0.783807f, -0.292154f), + Vector3DFloat(+0.088107f, -0.467818f, +0.319498f), + Vector3DFloat(+0.976623f, -0.185339f, +0.274087f), + Vector3DFloat(+0.770867f, +0.267861f, -0.022004f), + Vector3DFloat(-0.245338f, +0.171056f, -0.720389f), + Vector3DFloat(-0.909299f, +0.616993f, -0.950926f), + Vector3DFloat(+0.050935f, -0.842341f, -0.519944f), + Vector3DFloat(+0.646779f, +0.560839f, +0.129673f), + Vector3DFloat(-0.171361f, -0.501328f, -0.762749f), + Vector3DFloat(-0.374065f, -0.905209f, -0.561144f), + Vector3DFloat(-0.811029f, -0.510483f, -0.757073f), + Vector3DFloat(-0.905332f, -0.027924f, -0.263649f), + Vector3DFloat(-0.828730f, -0.067721f, -0.295206f), + Vector3DFloat(-0.538133f, +0.242714f, +0.914914f), + Vector3DFloat(-0.657949f, -0.732658f, -0.743584f), + Vector3DFloat(+0.837214f, -0.077181f, +0.767449f), + Vector3DFloat(+0.174047f, +0.397687f, +0.602405f), + Vector3DFloat(-0.256996f, +0.911435f, -0.927915f), + Vector3DFloat(+0.282754f, +0.500900f, +0.510178f), + Vector3DFloat(+0.849971f, +0.652821f, +0.002838f), + Vector3DFloat(-1.000000f, -0.103305f, -0.548814f), + Vector3DFloat(-0.673208f, -0.734489f, +0.204749f), + Vector3DFloat(-0.235511f, -0.977477f, -0.771538f), + Vector3DFloat(+0.294412f, +0.173009f, -0.075533f), + Vector3DFloat(-0.339946f, -0.970946f, -0.443525f), + Vector3DFloat(-0.016144f, -0.066134f, -0.394635f), + Vector3DFloat(-0.627003f, +0.683401f, -0.967101f), + Vector3DFloat(-0.217994f, -0.777642f, -0.404584f), + Vector3DFloat(+0.123447f, -0.590747f, +0.507614f), + Vector3DFloat(+0.648610f, +0.006806f, -0.677969f), + Vector3DFloat(+0.006561f, +0.662648f, -0.236305f), + Vector3DFloat(+0.658132f, +0.166173f, -0.283975f), + Vector3DFloat(-0.098178f, +0.665273f, -0.068636f), + Vector3DFloat(-0.091891f, +0.319620f, +0.058870f), + Vector3DFloat(+0.922666f, +0.077731f, +0.399701f), + Vector3DFloat(-0.007050f, +0.772942f, -0.957945f), + Vector3DFloat(-0.456832f, -0.293313f, +0.437300f), + Vector3DFloat(+0.917173f, -0.542100f, +0.909665f), + Vector3DFloat(-0.711722f, -0.917356f, +0.513169f), + Vector3DFloat(-0.032624f, +0.808100f, +0.354472f), + Vector3DFloat(-0.526597f, -0.049409f, +0.691702f), + Vector3DFloat(-0.073946f, +0.923521f, -0.389813f), + Vector3DFloat(+0.172216f, +0.642140f, -0.302896f), + Vector3DFloat(-0.660024f, +0.381329f, -0.833064f), + Vector3DFloat(+0.622791f, -0.809076f, +0.557787f), + Vector3DFloat(+0.609790f, +0.897702f, +0.998352f), + Vector3DFloat(-0.084384f, +0.169042f, -0.596667f), + Vector3DFloat(-0.315470f, -0.014618f, -0.640187f), + Vector3DFloat(+0.275552f, -0.199438f, -0.759941f), + Vector3DFloat(-0.615223f, -0.960021f, +0.367901f), + Vector3DFloat(+0.819514f, -0.787225f, +0.627308f), + Vector3DFloat(+0.083834f, -0.836299f, +0.926450f), + Vector3DFloat(-0.420637f, -0.047273f, +0.370281f), + Vector3DFloat(-0.097629f, -0.240577f, -0.594836f), + Vector3DFloat(+0.085604f, +0.385601f, -0.121189f), + Vector3DFloat(+0.968444f, -0.255104f, +0.021027f), + Vector3DFloat(+0.152440f, -0.450484f, +0.971496f), + Vector3DFloat(-0.095737f, +0.395672f, -0.605213f), + Vector3DFloat(+0.949278f, -0.284951f, +0.875118f), + Vector3DFloat(+0.787286f, +0.580248f, +0.494613f), + Vector3DFloat(+0.225990f, -0.455123f, +0.239540f), + Vector3DFloat(+0.630238f, -0.251747f, -0.617725f), + Vector3DFloat(+0.940733f, -0.390484f, +0.394024f), + Vector3DFloat(+0.197851f, -0.276345f, -0.893368f), + Vector3DFloat(-0.240883f, +0.349651f, -0.922178f), + Vector3DFloat(-0.037080f, -0.609119f, -0.018342f), + Vector3DFloat(-0.787042f, +0.624500f, -0.274880f), + Vector3DFloat(-0.536485f, +0.989746f, -0.400128f), + Vector3DFloat(+0.963988f, +0.006012f, +0.323649f), + Vector3DFloat(-0.501022f, -0.791864f, +0.514817f), + Vector3DFloat(-0.126316f, -0.782769f, +0.155553f), + Vector3DFloat(-0.254921f, +0.828547f, -0.173925f), + Vector3DFloat(-0.321512f, -0.180822f, +0.603198f), + Vector3DFloat(+0.733757f, -0.407514f, +0.170385f), + Vector3DFloat(-0.741691f, -0.322611f, -0.070956f), + Vector3DFloat(-0.025300f, +0.454329f, -0.889767f), + Vector3DFloat(+0.024751f, +0.133518f, -0.246498f), + Vector3DFloat(+0.545701f, -0.260842f, +0.869747f), + Vector3DFloat(+0.082247f, -0.579638f, -0.885495f), + Vector3DFloat(-0.000885f, -0.834346f, +0.040254f), + Vector3DFloat(-0.211097f, -0.059297f, +0.747856f), + Vector3DFloat(-0.829646f, +0.475753f, +0.527451f), + Vector3DFloat(+0.409162f, -0.167882f, -0.177099f), + Vector3DFloat(-0.319865f, -0.205664f, -0.130222f), + Vector3DFloat(+0.962523f, -0.992615f, +0.062655f), + Vector3DFloat(+0.849361f, -0.935301f, +0.394024f), + Vector3DFloat(+0.373699f, -0.148350f, +0.208594f), + Vector3DFloat(+0.639332f, +0.220557f, -0.277444f), + Vector3DFloat(+0.880734f, +0.209937f, -0.576708f), + Vector3DFloat(+0.342814f, +0.416364f, -0.832453f), + Vector3DFloat(+0.594958f, +0.479843f, -0.306070f), + Vector3DFloat(+0.335002f, -0.107334f, +0.784173f), + Vector3DFloat(+0.395917f, +0.763604f, +0.866756f), + Vector3DFloat(-0.507553f, +0.148717f, -0.436750f), + Vector3DFloat(-0.780450f, -0.599048f, -0.146031f), + Vector3DFloat(-0.841304f, -0.712577f, -0.329997f), + Vector3DFloat(+0.524033f, +0.033845f, +0.057100f), + Vector3DFloat(-0.976562f, -0.066866f, +0.026887f), + Vector3DFloat(-0.469405f, -0.094394f, +0.398175f), + Vector3DFloat(+0.238685f, -0.750237f, +0.156713f), + Vector3DFloat(+0.000702f, +0.617298f, -0.206397f), + Vector3DFloat(-0.228553f, +0.562548f, -0.719840f), + Vector3DFloat(-0.939451f, -0.698782f, +0.688162f), + Vector3DFloat(+0.637623f, +0.149022f, -0.536058f), + Vector3DFloat(-0.814386f, +0.379315f, +0.647145f), + Vector3DFloat(+0.523179f, -0.820368f, +0.386517f), + Vector3DFloat(+0.146092f, +0.999146f, +0.227332f), + Vector3DFloat(-0.366924f, -0.211707f, +0.274697f), + Vector3DFloat(+0.751640f, +0.136509f, +0.662648f), + Vector3DFloat(+0.657888f, +0.102695f, +0.022736f), + Vector3DFloat(+0.861019f, -0.535813f, +0.561449f), + Vector3DFloat(+0.766839f, +0.006317f, +0.681204f), + Vector3DFloat(+0.596301f, +0.671255f, -0.933470f), + Vector3DFloat(+0.776910f, -0.313211f, -0.353923f), + Vector3DFloat(+0.266213f, +0.215796f, +0.026093f), + Vector3DFloat(-0.648732f, +0.907407f, -0.755425f), + Vector3DFloat(-0.585498f, -0.234535f, -0.085421f), + Vector3DFloat(-0.490890f, +0.657582f, +0.242897f), + Vector3DFloat(+0.913450f, +0.066622f, -0.220252f), + Vector3DFloat(+0.121067f, +0.658193f, -0.645314f), + Vector3DFloat(+0.367779f, +0.941588f, +0.618702f), + Vector3DFloat(-0.320231f, +0.354900f, -0.653005f), + Vector3DFloat(+0.540147f, -0.212317f, +0.559374f), + Vector3DFloat(+0.715812f, -0.211951f, +0.078646f), + Vector3DFloat(-0.711051f, +0.598132f, -0.708914f), + Vector3DFloat(+0.029756f, +0.324809f, +0.014924f), + Vector3DFloat(-0.106418f, +0.386090f, +0.596301f), + Vector3DFloat(-0.317179f, -0.068880f, -0.315165f), + Vector3DFloat(+0.860164f, -0.772881f, -0.158788f), + Vector3DFloat(-0.326640f, -0.304239f, +0.445906f), + Vector3DFloat(+0.621265f, -0.815729f, +0.129429f), + Vector3DFloat(+0.687063f, -0.052767f, -0.969481f), + Vector3DFloat(-0.800043f, -0.598621f, +0.764702f), + Vector3DFloat(-0.518052f, -0.221534f, -0.066256f), + Vector3DFloat(+0.164953f, +0.886898f, +0.954100f), + Vector3DFloat(-0.384808f, -0.641102f, -1.000000f), + Vector3DFloat(+0.299051f, +0.218360f, +0.561205f), + Vector3DFloat(-0.419050f, +0.324992f, -0.161779f), + Vector3DFloat(-0.403241f, -0.176305f, +0.442976f), + Vector3DFloat(+0.262001f, +0.042817f, -0.818842f), + Vector3DFloat(+0.740410f, +0.888852f, -0.281716f), + Vector3DFloat(-0.853084f, +0.886227f, -0.736442f), + Vector3DFloat(-0.666616f, +0.555956f, +0.477950f), + Vector3DFloat(-0.714164f, +0.112156f, -0.032197f), + Vector3DFloat(+0.142674f, -0.842341f, +0.199744f), + Vector3DFloat(-0.305948f, -0.295999f, +0.131504f), + Vector3DFloat(+0.667470f, -0.966674f, +0.728629f), + Vector3DFloat(+0.122166f, +0.928281f, -0.725028f), + Vector3DFloat(-0.236854f, -0.756096f, +0.374798f), + Vector3DFloat(+0.035432f, -0.423505f, -0.663747f), + Vector3DFloat(+0.051973f, -0.510910f, +0.716849f), + Vector3DFloat(+0.540208f, -0.821711f, +0.055757f), + Vector3DFloat(+0.699149f, +0.988098f, +0.326579f), + Vector3DFloat(+0.108188f, -0.867367f, +0.668996f), + Vector3DFloat(+0.077181f, -0.738884f, +0.103671f), + Vector3DFloat(-0.467391f, +0.957335f, -0.194494f), + Vector3DFloat(+0.123386f, +0.893674f, -0.523118f), + Vector3DFloat(-0.151036f, +0.955809f, +0.199622f), + Vector3DFloat(+0.075411f, +0.726493f, -0.363994f), + Vector3DFloat(+0.224647f, -0.208960f, +0.242531f), + Vector3DFloat(+0.993591f, +0.751213f, -0.535203f), + Vector3DFloat(+0.308512f, +0.990905f, -0.197241f), + Vector3DFloat(+0.292886f, +0.536180f, +0.191748f), + Vector3DFloat(+0.489853f, -0.461531f, +0.351665f), + Vector3DFloat(-0.329447f, +0.531602f, +0.216834f), + Vector3DFloat(-0.809320f, +0.675649f, +0.516037f), + Vector3DFloat(+0.565172f, -0.661184f, +0.359111f), + Vector3DFloat(-0.039460f, +0.110080f, +0.978698f), + Vector3DFloat(+0.885372f, -0.763787f, +0.145726f), + Vector3DFloat(+0.006195f, +0.231117f, +0.417585f), + Vector3DFloat(-0.566027f, +0.179846f, -0.010407f), + Vector3DFloat(-0.879391f, +0.940123f, +0.163305f), + Vector3DFloat(+0.490646f, +0.391949f, +0.415998f), + Vector3DFloat(-0.973815f, +0.550096f, +0.710868f), + Vector3DFloat(+0.643544f, +0.763543f, +0.160375f), + Vector3DFloat(-0.832759f, +0.150792f, -0.602466f), + Vector3DFloat(-0.564745f, -0.121982f, +0.213172f), + Vector3DFloat(-0.775750f, +0.120640f, +0.703970f), + Vector3DFloat(+0.952208f, -0.233375f, +0.984619f), + Vector3DFloat(+0.330241f, +0.344707f, -0.002472f), + Vector3DFloat(-0.601489f, +0.772454f, +0.954527f), + Vector3DFloat(-0.605335f, +0.422590f, -0.629261f), + Vector3DFloat(+0.199011f, +0.389996f, -0.293069f), + Vector3DFloat(-0.664479f, +0.964110f, -0.223731f), + Vector3DFloat(-0.477340f, +0.905515f, +0.378521f), + Vector3DFloat(-0.366741f, +0.233497f, +0.181860f), + Vector3DFloat(-0.438826f, -0.664724f, +0.521653f), + Vector3DFloat(-0.298990f, +0.153844f, -0.795587f), + Vector3DFloat(+0.679983f, -0.192114f, +0.451033f), + Vector3DFloat(-0.630360f, +0.283303f, +0.892270f), + Vector3DFloat(+0.940489f, +0.396222f, +0.550890f), + Vector3DFloat(-0.448653f, +0.065889f, -0.753105f), + Vector3DFloat(+0.712821f, +0.740410f, +0.025178f), + Vector3DFloat(-0.862606f, +0.692923f, +0.973937f), + Vector3DFloat(-0.583789f, +0.849544f, -0.579455f), + Vector3DFloat(+0.640675f, +0.542711f, +0.062960f), + Vector3DFloat(-0.916196f, +0.493881f, +0.192602f), + Vector3DFloat(+0.270119f, +0.636525f, +0.380108f), + Vector3DFloat(-0.297952f, -0.165502f, +0.871578f), + Vector3DFloat(-0.731132f, -0.883175f, +0.756951f), + Vector3DFloat(+0.373760f, +0.645436f, -0.736503f), + Vector3DFloat(-0.289407f, +0.663259f, +0.329142f), + Vector3DFloat(+0.544115f, +0.908933f, -0.156713f), + Vector3DFloat(+0.780816f, +0.264870f, -0.632984f), + Vector3DFloat(-0.935667f, +0.959899f, -0.686148f), + Vector3DFloat(+0.121250f, -0.882687f, -0.204260f), + Vector3DFloat(-0.002106f, -0.032807f, -0.532334f), + Vector3DFloat(+0.334208f, -0.147862f, -0.719474f), + Vector3DFloat(-0.956114f, +0.622791f, -0.764702f), + Vector3DFloat(+0.482162f, -0.907651f, +0.396100f), + Vector3DFloat(-0.477645f, +0.710196f, -0.589221f), + Vector3DFloat(-0.374676f, -0.293008f, -0.738578f), + Vector3DFloat(+0.273232f, -0.007050f, +0.227454f), + Vector3DFloat(-0.634449f, -0.640675f, -0.644276f), + Vector3DFloat(-0.173315f, +0.852840f, -0.000580f), + Vector3DFloat(+0.258766f, +0.261086f, -0.720450f), + Vector3DFloat(+0.048921f, +0.562609f, +0.668569f), + Vector3DFloat(+0.072970f, -0.296182f, -0.753594f), + Vector3DFloat(+0.409528f, -0.742302f, -0.429365f), + Vector3DFloat(-0.551012f, +0.193579f, -0.672414f), + Vector3DFloat(-0.698111f, -0.188940f, +0.302896f), + Vector3DFloat(-0.176366f, +0.111606f, +0.180273f), + Vector3DFloat(-0.273537f, -0.817988f, -0.519028f), + Vector3DFloat(+0.742546f, -0.983154f, -0.585864f), + Vector3DFloat(-0.631031f, +0.641469f, +0.681936f), + Vector3DFloat(+0.181127f, +0.238929f, -0.851680f), + Vector3DFloat(-0.075655f, -0.175085f, +0.213904f), + Vector3DFloat(-0.554369f, -0.458724f, -0.080172f), + Vector3DFloat(-0.326273f, +0.086398f, -0.203162f), + Vector3DFloat(+0.905332f, +0.605762f, +0.191443f), + Vector3DFloat(-0.920835f, -0.636525f, -0.977844f), + Vector3DFloat(-0.552110f, +0.156102f, +0.504135f), + Vector3DFloat(-0.243934f, +0.970763f, -0.160070f), + Vector3DFloat(+0.418195f, -0.050996f, +0.090060f), + Vector3DFloat(+0.875729f, -0.335307f, +0.542589f), + Vector3DFloat(-0.873226f, -0.135777f, +0.750908f), + Vector3DFloat(+0.086032f, -0.780999f, +0.032624f), + Vector3DFloat(-0.929746f, +0.173376f, -0.738212f), + Vector3DFloat(+0.665639f, -0.140172f, +0.821223f), + Vector3DFloat(-0.977416f, +0.008698f, +0.739372f), + Vector3DFloat(-0.899045f, +0.494980f, -0.542833f), + Vector3DFloat(+0.395062f, -0.662465f, +0.553148f), + Vector3DFloat(-0.157689f, +0.970824f, +0.186377f), + Vector3DFloat(+0.969970f, -0.372051f, +0.728263f), + Vector3DFloat(+0.902463f, +0.860225f, -0.170141f), + Vector3DFloat(+0.539415f, +0.112949f, -0.387066f), + Vector3DFloat(-0.530259f, +0.773553f, -0.593554f), + Vector3DFloat(-0.626392f, +0.377483f, +0.141209f), + Vector3DFloat(-0.949278f, -0.859554f, -0.846858f), + Vector3DFloat(-0.942442f, +0.152562f, -0.463973f), + Vector3DFloat(-0.897763f, -0.911557f, +0.570482f), + Vector3DFloat(+0.317179f, -0.045076f, -0.960204f), + Vector3DFloat(+0.895077f, -0.314066f, +0.184240f), + Vector3DFloat(-0.744621f, -0.192602f, -0.536485f), + Vector3DFloat(-0.266274f, +0.682974f, -0.871090f), + Vector3DFloat(-0.809748f, -0.032258f, +0.273232f), + Vector3DFloat(-0.124363f, -0.786309f, +0.657216f), + Vector3DFloat(-0.726981f, -0.371563f, -0.172521f), + Vector3DFloat(+0.812860f, -0.024384f, +0.532212f), + Vector3DFloat(+0.523545f, -0.821589f, -0.509934f), + Vector3DFloat(+0.236671f, +0.420148f, -0.802911f), + Vector3DFloat(+0.093783f, -0.909177f, -0.071932f), + Vector3DFloat(+0.262429f, +0.728141f, -0.095798f), + Vector3DFloat(+0.717826f, +0.067171f, -0.797784f), + Vector3DFloat(-0.413678f, +0.049593f, -0.137364f), + Vector3DFloat(-0.334391f, +0.978515f, +0.529893f), + Vector3DFloat(-0.559862f, +0.913511f, +0.188513f), + Vector3DFloat(-0.644642f, -0.352214f, +0.085849f), + Vector3DFloat(-0.257302f, +0.108371f, -0.744804f), + Vector3DFloat(-0.676015f, +0.866207f, -0.834712f), + Vector3DFloat(-0.021882f, -0.053072f, -0.795160f), + Vector3DFloat(-0.219214f, +0.475448f, -0.291055f), + Vector3DFloat(-0.698721f, -0.089816f, -0.867977f), + Vector3DFloat(-0.297403f, +0.136876f, +0.832881f), + Vector3DFloat(+0.438887f, +0.468001f, -0.946959f), + Vector3DFloat(+0.638905f, +0.782952f, -0.127903f), + Vector3DFloat(+0.363811f, -0.358745f, +0.460494f), + Vector3DFloat(+0.320109f, -0.028047f, -0.223365f), + Vector3DFloat(-0.274758f, -0.139256f, +0.302469f), + Vector3DFloat(-0.943297f, -0.316263f, +0.749382f), + Vector3DFloat(+0.863704f, -0.867183f, -0.148473f), + Vector3DFloat(+0.030122f, +0.751030f, -0.963439f), + Vector3DFloat(-0.818232f, -0.299966f, +0.403485f), + Vector3DFloat(-0.841548f, +0.378826f, -0.981689f), + Vector3DFloat(+0.927671f, +0.527696f, +0.309549f), + Vector3DFloat(+0.521897f, +0.299844f, -0.545579f), + Vector3DFloat(+0.324992f, +0.310648f, +0.759880f), + Vector3DFloat(+0.599170f, -0.695303f, +0.165380f), + Vector3DFloat(+0.708914f, +0.528916f, -0.764336f), + Vector3DFloat(+0.059297f, -0.576586f, +0.825312f), + Vector3DFloat(+0.139805f, +0.627247f, -0.101657f), + Vector3DFloat(+0.805414f, +0.160619f, +0.154210f), + Vector3DFloat(+0.131443f, +0.918393f, -0.376629f), + Vector3DFloat(-0.354289f, +0.161534f, +0.880612f), + Vector3DFloat(+0.880184f, +0.543138f, -0.826594f), + Vector3DFloat(-0.388714f, +0.751946f, +0.645680f), + Vector3DFloat(-0.018586f, -0.968078f, -0.617969f), + Vector3DFloat(+0.802057f, -0.795648f, +0.790704f), + Vector3DFloat(+0.311075f, -0.065828f, +0.444746f), + Vector3DFloat(-0.024201f, -0.412152f, +0.955382f), + Vector3DFloat(+0.783868f, +0.879452f, +0.727409f), + Vector3DFloat(-0.854427f, -0.093844f, +0.874935f), + Vector3DFloat(-0.670522f, -0.453780f, +0.165014f), + Vector3DFloat(-0.530381f, +0.169836f, +0.937071f), + Vector3DFloat(+0.902158f, +0.596423f, +0.575976f), + Vector3DFloat(+0.957152f, -0.666372f, -0.794610f), + Vector3DFloat(+0.901425f, -0.066378f, -0.684988f), + Vector3DFloat(+0.219581f, -0.090426f, -0.020356f), + Vector3DFloat(+0.297342f, +0.915708f, -0.119419f), + Vector3DFloat(+0.923887f, -0.212622f, +0.793695f), + Vector3DFloat(-0.747124f, -0.364666f, -0.375591f), + Vector3DFloat(-0.003021f, -0.386944f, +0.304849f), + Vector3DFloat(-0.614368f, +0.345805f, +0.845210f), + Vector3DFloat(+0.245827f, -0.766961f, +0.046358f), + Vector3DFloat(-0.746818f, +0.777642f, -0.485580f), + Vector3DFloat(+0.138524f, +0.468673f, -0.247108f), + Vector3DFloat(-0.569628f, -0.256020f, -0.044465f), + Vector3DFloat(-0.707572f, +0.080599f, +0.177892f), + Vector3DFloat(+0.925657f, -0.710807f, +0.201453f), + Vector3DFloat(+0.986267f, +0.476547f, +0.244362f), + Vector3DFloat(-0.092746f, -0.028718f, -0.235450f), + Vector3DFloat(-0.001740f, +0.748466f, +0.268288f), + Vector3DFloat(-0.974181f, -0.081942f, -0.602161f), + Vector3DFloat(+0.534898f, -0.743217f, -0.895077f), + Vector3DFloat(-0.720573f, -0.683096f, -0.631825f), + Vector3DFloat(+0.183569f, -0.549913f, -0.348125f), + Vector3DFloat(+0.623341f, -0.764275f, -0.951964f), + Vector3DFloat(+0.973693f, -0.825251f, -0.558580f), + Vector3DFloat(+0.620350f, +0.380169f, +0.510849f), + Vector3DFloat(+0.989074f, +0.641774f, +0.327128f), + Vector3DFloat(+0.624805f, +0.817988f, +0.537339f), + Vector3DFloat(+0.809870f, -0.280984f, +0.755486f), + Vector3DFloat(+0.521531f, -0.903928f, -0.742851f), + Vector3DFloat(-0.389325f, -0.433699f, -0.928343f), + Vector3DFloat(+0.176366f, -0.211768f, -0.189428f), + Vector3DFloat(-0.737602f, -0.928159f, -0.016449f), + Vector3DFloat(+0.723380f, -0.405866f, +0.167211f), + Vector3DFloat(+0.523301f, -0.666372f, -0.046480f), + Vector3DFloat(-0.118259f, +0.912290f, -0.160985f), + Vector3DFloat(+0.611927f, -0.191748f, +0.149998f), + Vector3DFloat(+0.905881f, -0.424482f, +0.913816f), + Vector3DFloat(-0.620411f, -0.027131f, +0.923276f), + Vector3DFloat(+0.774957f, -0.569140f, +0.871944f), + Vector3DFloat(-0.804193f, +0.661061f, +0.820795f), + Vector3DFloat(+0.077059f, -0.102023f, +0.278054f), + Vector3DFloat(+0.772637f, -0.104831f, -0.823847f), + Vector3DFloat(+0.983947f, +0.818659f, -0.089267f), + Vector3DFloat(+0.735221f, -0.709586f, -0.454268f), + Vector3DFloat(+0.996643f, -0.944945f, -0.538316f), + Vector3DFloat(+0.049165f, -0.796014f, +0.971374f), + Vector3DFloat(-0.976623f, +0.655263f, -0.156163f), + Vector3DFloat(+0.681143f, -0.005585f, +0.476547f), + Vector3DFloat(-0.928159f, +0.237648f, -0.346538f), + Vector3DFloat(+0.361003f, -0.709586f, +0.595325f), + Vector3DFloat(-0.345927f, +0.798700f, -0.321390f), + Vector3DFloat(-0.731803f, -0.701346f, -0.652272f), + Vector3DFloat(+0.164708f, -0.335795f, -0.213599f), + Vector3DFloat(-0.857601f, +0.151463f, +0.157689f), + Vector3DFloat(-0.754692f, -0.954283f, +0.308939f), + Vector3DFloat(-0.037446f, -0.637562f, -0.991150f), + Vector3DFloat(+0.744987f, -0.130894f, -0.575610f), + Vector3DFloat(-0.799249f, -0.131687f, +0.906247f), + Vector3DFloat(+0.580004f, +0.468734f, -0.745232f), + Vector3DFloat(+0.991882f, +0.138401f, +0.694693f), + Vector3DFloat(+0.830195f, +0.634877f, +0.715140f), + Vector3DFloat(+0.607532f, -0.317972f, -0.250710f), + Vector3DFloat(+0.037629f, -0.384320f, +0.812922f), + Vector3DFloat(+0.645009f, +0.224036f, -0.778924f), + Vector3DFloat(-0.852779f, -0.743522f, +0.346843f), + Vector3DFloat(+0.578478f, -0.894955f, -0.327616f), + Vector3DFloat(-0.905759f, -0.239296f, -0.945799f), + Vector3DFloat(+0.028352f, -0.658254f, -0.705313f), + Vector3DFloat(+0.954405f, +0.825434f, -0.553575f), + Vector3DFloat(-0.471480f, +0.504440f, -0.262856f), + Vector3DFloat(-0.924131f, +0.393353f, +0.106967f), + Vector3DFloat(-0.032685f, +0.385846f, -0.877255f), + Vector3DFloat(-0.039094f, +0.220557f, +0.356731f), + Vector3DFloat(+0.490890f, -0.403790f, -0.650624f), + Vector3DFloat(-0.896115f, -0.866817f, -0.837825f), + Vector3DFloat(-0.260842f, -0.027558f, +0.511582f), + Vector3DFloat(+0.782037f, +0.493759f, +0.229835f), + Vector3DFloat(+0.086337f, -0.713431f, +0.484664f), + Vector3DFloat(+0.168615f, -0.742058f, +0.639637f), + Vector3DFloat(+0.325968f, -0.567919f, -0.359294f), + Vector3DFloat(-0.633717f, -0.662709f, +0.374615f), + Vector3DFloat(+0.230995f, -0.701041f, +0.557970f), + Vector3DFloat(-0.729911f, -0.967650f, +0.951170f), + Vector3DFloat(-0.126011f, -0.819819f, -0.299539f), + Vector3DFloat(-0.166540f, +0.321024f, -0.704398f), + Vector3DFloat(+0.769890f, -0.977111f, -0.374187f), + Vector3DFloat(+0.562120f, +0.025300f, +0.299234f), + Vector3DFloat(+0.048189f, +0.404462f, -0.420026f), + Vector3DFloat(-0.840632f, +0.586291f, +0.360515f), + Vector3DFloat(+0.223792f, +0.024140f, +0.607593f), + Vector3DFloat(-0.562120f, +0.602771f, +0.948302f), + Vector3DFloat(+0.968627f, -0.994263f, -0.206030f), + Vector3DFloat(+0.146886f, -0.315287f, +0.034455f), + Vector3DFloat(+0.836848f, -0.348613f, +0.213904f), + Vector3DFloat(+0.494980f, -0.216041f, +0.405927f), + Vector3DFloat(-0.584338f, -0.268715f, -0.165258f), + Vector3DFloat(+0.118686f, -0.751091f, -0.381817f), + Vector3DFloat(-0.887753f, +0.178686f, -0.730216f), + Vector3DFloat(-0.684194f, -0.351543f, +0.952330f), + Vector3DFloat(-0.006256f, -0.564562f, +0.137974f), + Vector3DFloat(-0.229408f, +0.182470f, +0.427168f), + Vector3DFloat(+0.024445f, +0.920713f, +0.119724f), + Vector3DFloat(-0.996948f, -0.518784f, -0.045991f), + Vector3DFloat(-0.062166f, -0.592090f, +0.849117f), + Vector3DFloat(-0.377422f, -0.942808f, -0.649770f), + Vector3DFloat(+0.093478f, -0.242470f, -0.198096f), + Vector3DFloat(-0.594348f, -0.156102f, +0.401105f), + Vector3DFloat(-0.746574f, -0.294351f, +0.577685f), + Vector3DFloat(+0.504929f, +0.405194f, +0.724296f), + Vector3DFloat(-0.489059f, -0.492294f, +0.680288f), + Vector3DFloat(-0.025971f, -0.241127f, +0.103977f), + Vector3DFloat(+0.875301f, -0.574206f, -0.671804f), + Vector3DFloat(-0.483444f, +0.592029f, -0.537339f), + Vector3DFloat(+0.504257f, -0.413984f, -0.779839f), + Vector3DFloat(+0.182043f, -0.805292f, +0.988403f), + Vector3DFloat(+0.533372f, -0.142064f, +0.793512f), + Vector3DFloat(-0.105380f, -0.039338f, -0.624317f), + Vector3DFloat(+0.125950f, +0.384259f, +0.596973f), + Vector3DFloat(+0.452071f, +0.039216f, +0.924802f), + Vector3DFloat(-0.986694f, +0.452498f, +0.199194f), + Vector3DFloat(+0.230323f, +0.931516f, -0.380596f), + Vector3DFloat(+0.657277f, +0.811945f, -0.176733f), + Vector3DFloat(-0.477767f, -0.251137f, -0.468734f), + Vector3DFloat(+0.499252f, +0.543260f, +0.886898f), + Vector3DFloat(-0.528855f, +0.747124f, -0.789300f), + Vector3DFloat(-0.188330f, +0.434675f, -0.915891f), + Vector3DFloat(-0.807733f, +0.861080f, +0.386029f), + Vector3DFloat(-0.314615f, +0.761223f, -0.177953f), + Vector3DFloat(-0.855098f, +0.549486f, +0.547227f), + Vector3DFloat(-0.072970f, +0.647816f, -0.034089f), + Vector3DFloat(+0.385784f, +0.557482f, -0.912534f), + Vector3DFloat(-0.654530f, -0.923032f, -0.783624f), + Vector3DFloat(-0.755425f, -0.523789f, -0.132725f), + Vector3DFloat(+0.333781f, +0.322733f, +0.267678f), + Vector3DFloat(-0.533982f, -0.534471f, -0.399884f), + Vector3DFloat(-0.953673f, -0.589465f, +0.450423f), + Vector3DFloat(-0.789911f, -0.535936f, -0.409833f), + Vector3DFloat(+0.085726f, +0.363079f, +0.082003f), + Vector3DFloat(+0.744194f, -0.114292f, +0.322245f), + Vector3DFloat(+0.693472f, -0.256447f, -0.516160f), + Vector3DFloat(+0.446028f, -0.553026f, +0.471908f), + Vector3DFloat(-0.757561f, +0.608997f, +0.833064f), + Vector3DFloat(+0.115024f, +0.632191f, +0.314493f), + Vector3DFloat(-0.403851f, -0.325663f, -0.057161f), + Vector3DFloat(-0.188696f, +0.636097f, +0.514756f), + Vector3DFloat(-0.110813f, -0.473861f, -0.041597f), + Vector3DFloat(-0.239540f, +0.673940f, -0.874325f), + Vector3DFloat(+0.739982f, +0.350932f, -0.930418f), + Vector3DFloat(+0.519639f, -0.430952f, +0.569262f), + Vector3DFloat(-0.916807f, +0.117832f, +0.924070f), + Vector3DFloat(+0.856136f, +0.764763f, +0.653798f), + Vector3DFloat(+0.953185f, +0.721061f, +0.723441f), + Vector3DFloat(-0.113010f, +0.617176f, -0.436140f), + Vector3DFloat(+0.912839f, +0.496811f, -0.742058f), + Vector3DFloat(+0.219275f, -0.751701f, +0.479965f), + Vector3DFloat(+0.655690f, -0.964538f, +0.619312f), + Vector3DFloat(+0.364971f, +0.635975f, -0.697989f), + Vector3DFloat(-0.142247f, +0.554918f, +0.291238f), + Vector3DFloat(-0.163732f, -0.772820f, -0.887997f), + Vector3DFloat(-0.122593f, -0.456404f, -0.006989f), + Vector3DFloat(-0.704154f, -0.551378f, -0.237770f), + Vector3DFloat(+0.637501f, -0.831843f, -0.706534f), + Vector3DFloat(-0.794061f, -0.717887f, +0.576464f), + Vector3DFloat(+0.233558f, -0.683218f, +0.879147f), + Vector3DFloat(-0.170934f, +0.848811f, +0.840510f), + Vector3DFloat(+0.735282f, -0.625965f, -0.309732f), + Vector3DFloat(-0.562975f, +0.929746f, +0.794794f), + Vector3DFloat(-0.455611f, -0.860836f, -0.810114f), + Vector3DFloat(+0.433882f, -0.190222f, -0.529405f), + Vector3DFloat(+0.785638f, -0.040864f, +0.050569f), + Vector3DFloat(-0.963134f, -0.993713f, -0.817011f), + Vector3DFloat(+0.787347f, -0.598071f, +0.782220f), + Vector3DFloat(-0.551378f, +0.589526f, +0.061983f), + Vector3DFloat(-0.987243f, +0.894589f, -0.469649f), + Vector3DFloat(+0.329264f, +0.164464f, -0.088656f), + Vector3DFloat(+0.068270f, +0.938841f, +0.700858f), + Vector3DFloat(+0.101535f, -0.583850f, -0.809503f), + Vector3DFloat(+0.906980f, -0.943724f, +0.461592f), + Vector3DFloat(+0.438520f, -0.329264f, +0.261086f), + Vector3DFloat(-0.700003f, -0.259316f, +0.784356f), + Vector3DFloat(+0.442305f, +0.444502f, +0.481185f), + Vector3DFloat(+0.326701f, -0.331523f, -0.227393f), + Vector3DFloat(-0.222327f, -0.308390f, +0.517136f), + Vector3DFloat(+0.275369f, -0.513169f, -0.177892f), + Vector3DFloat(-0.378887f, +0.668203f, +0.619312f), + Vector3DFloat(-0.785455f, -0.093661f, -0.071322f), + Vector3DFloat(-0.022309f, -0.744987f, +0.832820f), + Vector3DFloat(-0.177892f, +0.829707f, -0.550218f), + Vector3DFloat(+0.952879f, +0.477767f, +0.428999f), + Vector3DFloat(+0.113376f, +0.097568f, -0.921201f), + Vector3DFloat(+0.195898f, -0.924619f, -0.494613f), + Vector3DFloat(+0.727592f, -0.628956f, -0.029756f), + Vector3DFloat(-0.796197f, -0.450484f, -0.045686f), + Vector3DFloat(+0.670888f, +0.958068f, -0.902402f), + Vector3DFloat(-0.259194f, -0.570666f, +0.098422f), + Vector3DFloat(+0.120273f, -0.732475f, -0.712272f), + Vector3DFloat(+0.539109f, +0.754753f, -0.517075f), + Vector3DFloat(+0.320170f, +0.300821f, -0.790643f), + Vector3DFloat(-0.049287f, +0.269814f, -0.149998f), + Vector3DFloat(-0.004120f, +0.402081f, -0.856807f), + Vector3DFloat(+0.566881f, -0.224464f, -0.552049f), + Vector3DFloat(+0.323405f, -0.345317f, -0.119114f), + Vector3DFloat(-0.736198f, -0.234352f, +0.803278f), + Vector3DFloat(-0.424421f, +0.059358f, -0.162389f), + Vector3DFloat(+0.918516f, -0.884640f, -0.853511f), + Vector3DFloat(-0.633717f, +0.231239f, +0.672170f), + Vector3DFloat(+0.417096f, +0.454878f, +0.097201f), + Vector3DFloat(+0.183630f, -0.957030f, -0.368938f), + Vector3DFloat(-0.199133f, +0.191687f, -0.787774f), + Vector3DFloat(-0.109104f, +0.676077f, +0.731193f), + Vector3DFloat(-0.288186f, -0.801691f, +0.855037f), + Vector3DFloat(+0.332133f, -0.828730f, +0.005402f), + Vector3DFloat(+0.959166f, +0.197790f, -0.221107f), + Vector3DFloat(-0.646046f, +0.043428f, -0.379254f), + Vector3DFloat(-0.717338f, +0.122105f, +0.107883f), + Vector3DFloat(-0.299783f, +0.089389f, +0.977172f), + Vector3DFloat(+0.486862f, -0.577990f, -0.726615f), + Vector3DFloat(-0.400922f, +0.430769f, -0.834956f), + Vector3DFloat(+0.308756f, +0.735221f, -0.809076f), + Vector3DFloat(-0.304605f, +0.335551f, -0.350627f), + Vector3DFloat(-0.078219f, -0.288491f, -0.225318f), + Vector3DFloat(+0.529099f, +0.710562f, +0.002960f), + Vector3DFloat(+0.102695f, +0.410932f, -0.950072f), + Vector3DFloat(-0.715751f, +0.598621f, +0.188879f), + Vector3DFloat(-0.936460f, -0.232398f, -0.123203f), + Vector3DFloat(-0.733146f, -0.201819f, -0.463851f), + Vector3DFloat(-0.982971f, -0.581347f, -0.104953f), + Vector3DFloat(-0.219459f, +0.104648f, +0.416425f), + Vector3DFloat(+0.952391f, -0.038789f, +0.993530f), + Vector3DFloat(+0.992370f, +0.891537f, +0.959227f), + Vector3DFloat(+0.104221f, -0.305704f, -0.359722f), + Vector3DFloat(-0.722770f, +0.069735f, -0.801447f), + Vector3DFloat(+0.444563f, +0.354961f, +0.041414f), + Vector3DFloat(+0.642018f, -0.878903f, +0.058809f), + Vector3DFloat(-0.532579f, -0.463668f, +0.565233f), + Vector3DFloat(+0.411176f, -0.843379f, -0.172704f), + Vector3DFloat(+0.823908f, +0.619922f, +0.439863f), + Vector3DFloat(-0.340007f, +0.048189f, -0.529160f), + Vector3DFloat(+0.241310f, -0.585070f, +0.637135f), + Vector3DFloat(+0.146886f, +0.873226f, -0.425153f), + Vector3DFloat(-0.114658f, -0.465621f, +0.364483f), + Vector3DFloat(+0.987121f, -0.552599f, -0.918821f), + Vector3DFloat(+0.138401f, -0.917722f, +0.930479f), + Vector3DFloat(-0.732536f, -0.150731f, +0.613269f), + Vector3DFloat(-0.071139f, +0.752373f, +0.192541f), + Vector3DFloat(+0.475143f, -0.187353f, +0.258950f), + Vector3DFloat(-0.500412f, -0.829157f, -0.418073f), + Vector3DFloat(+0.260414f, +0.930479f, +0.483016f), + Vector3DFloat(-0.899106f, +0.528550f, +0.076510f), + Vector3DFloat(-0.084384f, +0.022614f, +0.609180f), + Vector3DFloat(-0.213843f, -0.532334f, -0.282022f), + Vector3DFloat(-0.715323f, +0.025117f, -0.698477f), + Vector3DFloat(+0.521348f, +0.088656f, -0.415265f), + Vector3DFloat(-0.131809f, -0.395672f, +0.932432f), + Vector3DFloat(-0.549364f, -0.948363f, -0.207862f), + Vector3DFloat(+0.908322f, +0.643605f, -0.103732f), + Vector3DFloat(+0.632496f, +0.330973f, +0.345622f), + Vector3DFloat(-0.522141f, +0.031892f, -0.920713f), + Vector3DFloat(-0.875912f, +0.481918f, -0.229408f), + Vector3DFloat(-0.698172f, -0.934202f, +0.051668f), + Vector3DFloat(-0.791070f, -0.452193f, -0.366680f), + Vector3DFloat(-0.531907f, +0.497299f, +0.386517f), + Vector3DFloat(-0.942808f, -0.775811f, -0.397320f), + Vector3DFloat(+0.577563f, +0.075289f, -0.943297f), + Vector3DFloat(+0.464827f, -0.145848f, -0.167638f), + Vector3DFloat(-0.503220f, +0.592273f, -0.617359f), + Vector3DFloat(+0.752739f, +0.503464f, -0.586230f), + Vector3DFloat(-0.040315f, +0.197180f, -0.259072f), + Vector3DFloat(-0.304422f, -0.989380f, -0.281289f), + Vector3DFloat(+0.063387f, -0.662954f, +0.451338f), + Vector3DFloat(-0.272744f, +0.768914f, -0.141270f), + Vector3DFloat(+0.475021f, +0.378033f, +0.186010f), + Vector3DFloat(+0.893613f, -0.671560f, +0.494491f), + Vector3DFloat(+0.154027f, +0.994873f, +0.138096f), + Vector3DFloat(-0.661061f, -0.039094f, +0.072787f), + Vector3DFloat(+0.849666f, -0.956298f, +0.300699f), + Vector3DFloat(-0.227027f, +0.343913f, +0.514512f), + Vector3DFloat(+0.812738f, -0.891659f, +0.790277f), + Vector3DFloat(+0.619251f, -0.234779f, -0.342448f), + Vector3DFloat(-0.698904f, -0.525620f, -0.553331f), + Vector3DFloat(-0.357524f, +0.950194f, -0.358623f), + Vector3DFloat(-0.174352f, -0.802911f, +0.215552f), + Vector3DFloat(+0.046175f, +0.043794f, +0.139927f), + Vector3DFloat(+0.911924f, +0.433149f, +0.302286f), + Vector3DFloat(+0.563463f, -0.326823f, -0.832759f), + Vector3DFloat(-0.293741f, -0.448103f, -0.951781f), + Vector3DFloat(+0.196448f, +0.627979f, +0.340800f), + Vector3DFloat(-0.727042f, -0.013886f, -0.847346f), + Vector3DFloat(-0.769707f, +0.780084f, +0.239174f), + Vector3DFloat(+0.168493f, +0.564806f, +0.509690f), + Vector3DFloat(-0.786126f, +0.663564f, -0.908261f), + Vector3DFloat(+0.084017f, -0.548631f, -0.207312f), + Vector3DFloat(+0.011567f, +0.906552f, +0.726188f), + Vector3DFloat(-0.723746f, +0.031648f, +0.250587f), + Vector3DFloat(+0.031892f, +0.693045f, -0.263283f), + Vector3DFloat(-0.601856f, -0.585742f, -0.769280f), + Vector3DFloat(+0.588122f, -0.108127f, -0.535020f), + Vector3DFloat(+0.455672f, +0.864498f, +0.963378f), + Vector3DFloat(-0.712882f, -0.335490f, -0.143712f), + Vector3DFloat(+0.199194f, +0.747002f, +0.380840f), + Vector3DFloat(+0.626820f, +0.508042f, -0.177465f), + Vector3DFloat(-0.441816f, +0.652150f, -0.549058f), + Vector3DFloat(+0.862667f, +0.053377f, +0.652333f), + Vector3DFloat(-0.002289f, +0.568834f, -0.069185f) + }; +} + +#endif //__PolyVox_RandomVectors_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Timer.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Timer.h new file mode 100644 index 0000000..ea3dcd4 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Timer.h @@ -0,0 +1,73 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Timer_H__ +#define __PolyVox_Timer_H__ + +#include +#include + +namespace PolyVox +{ + class Timer + { + public: + Timer(bool bAutoStart = true) + { + if (bAutoStart) + { + start(); + } + } + + void start(void) + { + m_start = clock::now(); + } + + float elapsedTimeInSeconds(void) + { + std::chrono::duration elapsed_seconds = clock::now() - m_start; + return elapsed_seconds.count(); + } + + float elapsedTimeInMilliSeconds(void) + { + std::chrono::duration elapsed_milliseconds = clock::now() - m_start; + return elapsed_milliseconds.count(); + } + + float elapsedTimeInMicroSeconds(void) + { + std::chrono::duration elapsed_microseconds = clock::now() - m_start; + return elapsed_microseconds.count(); + } + + private: + typedef std::chrono::system_clock clock; + std::chrono::time_point m_start; + }; +} + +#endif //__PolyVox_Timer_H__ \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Utility.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Utility.h new file mode 100644 index 0000000..8b668df --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Impl/Utility.h @@ -0,0 +1,94 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Utility_H__ +#define __PolyVox_Utility_H__ + +#include "PlatformDefinitions.h" + +#include + +namespace PolyVox +{ + inline bool isPowerOf2(uint32_t uInput) + { + if (uInput == 0) + return false; + else + return ((uInput & (uInput - 1)) == 0); + } + + //Note: this function only works for inputs which are a power of two and not zero + //If this is not the case then the output is undefined. + inline uint8_t logBase2(uint32_t uInput) + { + //Release mode validation + if (uInput == 0) + { + POLYVOX_THROW(std::invalid_argument, "Cannot compute the log of zero."); + } + if (!isPowerOf2(uInput)) + { + POLYVOX_THROW(std::invalid_argument, "Input must be a power of two in order to compute the log."); + } + + uint32_t uResult = 0; + while ((uInput >> uResult) != 0) + { + ++uResult; + } + return static_cast(uResult - 1); + } + + // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 + inline uint32_t upperPowerOfTwo(uint32_t v) + { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + + inline int32_t roundTowardsNegInf(float r) + { + return (r >= 0.0) ? static_cast(r) : static_cast(r - 1.0f); + } + + inline int32_t roundToNearestInteger(float r) + { + return (r >= 0.0) ? static_cast(r + 0.5f) : static_cast(r - 0.5f); + } + + template + inline Type clamp(const Type& value, const Type& low, const Type& high) + { + return (std::min)(high, (std::max)(low, value)); + } +} + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LICENSE.txt b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LICENSE.txt new file mode 100644 index 0000000..9b495cc --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 David Williams and Matthew Williams + +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. diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Logging.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Logging.h new file mode 100644 index 0000000..05da985 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Logging.h @@ -0,0 +1,77 @@ +/******************************************************************************* +The MIT License (MIT) + +Copyright (c) 2015 David Williams and Matthew Williams + +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 __PolyVox_Logging_H__ +#define __PolyVox_Logging_H__ + +#include +#include + +// We expose the logger class to the user so that they can provide custom implementations +// to redirect PolyVox's log messages. However, it is not expected that user code will make +// use of PolyVox's logging macros s these are part of the private implementation. +namespace PolyVox +{ + class Logger + { + public: + Logger() {}; + virtual ~Logger() {}; + + virtual void logTraceMessage(const std::string& message) = 0; + virtual void logDebugMessage(const std::string& message) = 0; + virtual void logInfoMessage(const std::string& message) = 0; + virtual void logWarningMessage(const std::string& message) = 0; + virtual void logErrorMessage(const std::string& message) = 0; + virtual void logFatalMessage(const std::string& message) = 0; + }; + + class DefaultLogger : public Logger + { + public: + DefaultLogger() : Logger() {} + virtual ~DefaultLogger() {} + + // Appending the 'std::endl' forces the stream to be flushed. + void logTraceMessage(const std::string& /*message*/) { } + void logDebugMessage(const std::string& /*message*/) { } + void logInfoMessage(const std::string& message) { std::cout << message << std::endl; } + void logWarningMessage(const std::string& message) { std::cerr << message << std::endl; } + void logErrorMessage(const std::string& message) { std::cerr << message << std::endl; } + void logFatalMessage(const std::string& message) { std::cerr << message << std::endl; } + }; + + inline Logger*& getLoggerInstance() + { + static Logger* s_pLogger = new DefaultLogger; + return s_pLogger; + } + + inline void setLoggerInstance(Logger* pLogger) + { + getLoggerInstance() = pLogger; + } +} + +#endif //__PolyVox_Logging_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LowPassFilter.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LowPassFilter.h new file mode 100644 index 0000000..4ac51a3 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LowPassFilter.h @@ -0,0 +1,64 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_LowPassFilter_H__ +#define __PolyVox_LowPassFilter_H__ + +#include "Impl/IteratorController.h" + +#include "Region.h" + +namespace PolyVox +{ + /// This class is able to copy volume data from a source volume to a destination volume while performing low-pass filtering (blurring). + template< typename SrcVolumeType, typename DstVolumeType, typename AccumulationType> + class LowPassFilter + { + public: + LowPassFilter(SrcVolumeType* pVolSrc, Region regSrc, DstVolumeType* pVolDst, Region regDst, uint32_t uKernelSize); + + /// Execute a standard approach to filtering which performs a number of neighbourhood look-ups per voxel. + void execute(); + /// Execute a version with 'Summed Area Tables'. This should be faster for large kernel sizes but this hasn't really been confirmed yet. + void executeSAT(); + + private: + //Source data + SrcVolumeType* m_pVolSrc; + Region m_regSrc; + + //Destination data + DstVolumeType* m_pVolDst; + Region m_regDst; + + //Kernel size + uint32_t m_uKernelSize; + }; + +}//namespace PolyVox + +#include "LowPassFilter.inl" + +#endif //__PolyVox_LowPassFilter_H__ + diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LowPassFilter.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LowPassFilter.inl new file mode 100644 index 0000000..f66ab22 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/LowPassFilter.inl @@ -0,0 +1,258 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "PolyVox/RawVolume.h" // Currently used by exectureSAT() method - should be replaced by PagedVolume or a template parameter? + +namespace PolyVox +{ + /** + * \param pVolSrc + * \param regSrc + * \param[out] pVolDst + * \param regDst + * \param uKernelSize + */ + template< typename SrcVolumeType, typename DstVolumeType, typename AccumulationType> + LowPassFilter::LowPassFilter(SrcVolumeType* pVolSrc, Region regSrc, DstVolumeType* pVolDst, Region regDst, uint32_t uKernelSize) + :m_pVolSrc(pVolSrc) + , m_regSrc(regSrc) + , m_pVolDst(pVolDst) + , m_regDst(regDst) + , m_uKernelSize(uKernelSize) + { + //Kernel size must be at least three + if (m_uKernelSize < 3) + { + POLYVOX_THROW(std::invalid_argument, "Kernel size must be at least three"); + } + + //Kernel size must be odd + if (m_uKernelSize % 2 == 0) + { + POLYVOX_THROW(std::invalid_argument, "Kernel size must be odd"); + } + } + + template< typename SrcVolumeType, typename DstVolumeType, typename AccumulationType> + void LowPassFilter::execute() + { + int32_t iSrcMinX = m_regSrc.getLowerX(); + int32_t iSrcMinY = m_regSrc.getLowerY(); + int32_t iSrcMinZ = m_regSrc.getLowerZ(); + + int32_t iSrcMaxX = m_regSrc.getUpperX(); + int32_t iSrcMaxY = m_regSrc.getUpperY(); + int32_t iSrcMaxZ = m_regSrc.getUpperZ(); + + int32_t iDstMinX = m_regDst.getLowerX(); + int32_t iDstMinY = m_regDst.getLowerY(); + int32_t iDstMinZ = m_regDst.getLowerZ(); + + //int32_t iDstMaxX = m_regDst.getUpperX(); + //int32_t iDstMaxY = m_regDst.getUpperY(); + //int32_t iDstMaxZ = m_regDst.getUpperZ(); + + typename SrcVolumeType::Sampler srcSampler(m_pVolSrc); + + for (int32_t iSrcZ = iSrcMinZ, iDstZ = iDstMinZ; iSrcZ <= iSrcMaxZ; iSrcZ++, iDstZ++) + { + for (int32_t iSrcY = iSrcMinY, iDstY = iDstMinY; iSrcY <= iSrcMaxY; iSrcY++, iDstY++) + { + for (int32_t iSrcX = iSrcMinX, iDstX = iDstMinX; iSrcX <= iSrcMaxX; iSrcX++, iDstX++) + { + AccumulationType tSrcVoxel(0); + srcSampler.setPosition(iSrcX, iSrcY, iSrcZ); + + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx1ny1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx1ny0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx1ny1pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx0py1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx0py0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx0py1pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx1py1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx1py0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1nx1py1pz()); + + tSrcVoxel += static_cast(srcSampler.peekVoxel0px1ny1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px1ny0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px1ny1pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px0py1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px0py0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px0py1pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px1py1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px1py0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel0px1py1pz()); + + tSrcVoxel += static_cast(srcSampler.peekVoxel1px1ny1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px1ny0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px1ny1pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px0py1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px0py0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px0py1pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px1py1nz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px1py0pz()); + tSrcVoxel += static_cast(srcSampler.peekVoxel1px1py1pz()); + + tSrcVoxel /= 27; + + //tSrcVoxel.setDensity(uDensity); + m_pVolDst->setVoxel(iSrcX, iSrcY, iSrcZ, static_cast(tSrcVoxel)); + } + } + } + } + + template< typename SrcVolumeType, typename DstVolumeType, typename AccumulationType> + void LowPassFilter::executeSAT() + { + const uint32_t border = (m_uKernelSize - 1) / 2; + + Vector3DInt32 satLowerCorner = m_regSrc.getLowerCorner() - Vector3DInt32(border, border, border); + Vector3DInt32 satUpperCorner = m_regSrc.getUpperCorner() + Vector3DInt32(border, border, border); + + //Use floats for the SAT volume to ensure it works with negative + //densities and with both integral and floating point input volumes. + RawVolume satVolume(Region(satLowerCorner, satUpperCorner)); + + //Clear to zeros (necessary?) + //FIXME - use Volume::fill() method. Implemented in base class as below + //but with optimised implementations in subclasses? + for (int32_t z = satLowerCorner.getZ(); z <= satUpperCorner.getZ(); z++) + { + for (int32_t y = satLowerCorner.getY(); y <= satUpperCorner.getY(); y++) + { + for (int32_t x = satLowerCorner.getX(); x <= satUpperCorner.getX(); x++) + { + satVolume.setVoxel(x, y, z, 0); + } + } + } + + typename RawVolume::Sampler satVolumeIter(&satVolume); + + IteratorController::Sampler> satIterCont; + satIterCont.m_regValid = Region(satLowerCorner, satUpperCorner); + satIterCont.m_Iter = &satVolumeIter; + satIterCont.reset(); + + typename SrcVolumeType::Sampler srcVolumeIter(m_pVolSrc); + + IteratorController srcIterCont; + srcIterCont.m_regValid = Region(satLowerCorner, satUpperCorner); + srcIterCont.m_Iter = &srcVolumeIter; + srcIterCont.reset(); + + do + { + AccumulationType previousSum = static_cast(satVolumeIter.peekVoxel1nx0py0pz()); + AccumulationType currentVal = static_cast(srcVolumeIter.getVoxel()); + + satVolumeIter.setVoxel(previousSum + currentVal); + + srcIterCont.moveForward(); + + } while (satIterCont.moveForward()); + + //Build SAT in three passes + /*for(int32_t z = satLowerCorner.getZ(); z <= satUpperCorner.getZ(); z++) + { + for(int32_t y = satLowerCorner.getY(); y <= satUpperCorner.getY(); y++) + { + for(int32_t x = satLowerCorner.getX(); x <= satUpperCorner.getX(); x++) + { + AccumulationType previousSum = static_cast(satVolume.getVoxel(x-1,y,z)); + AccumulationType currentVal = static_cast(m_pVolSrc->getVoxel(x,y,z)); + + satVolume.setVoxel(x,y,z,previousSum + currentVal); + } + } + }*/ + + for (int32_t z = satLowerCorner.getZ(); z <= satUpperCorner.getZ(); z++) + { + for (int32_t y = satLowerCorner.getY(); y <= satUpperCorner.getY(); y++) + { + for (int32_t x = satLowerCorner.getX(); x <= satUpperCorner.getX(); x++) + { + AccumulationType previousSum = static_cast(satVolume.getVoxel(x, y - 1, z)); + AccumulationType currentSum = static_cast(satVolume.getVoxel(x, y, z)); + + satVolume.setVoxel(x, y, z, previousSum + currentSum); + } + } + } + + for (int32_t z = satLowerCorner.getZ(); z <= satUpperCorner.getZ(); z++) + { + for (int32_t y = satLowerCorner.getY(); y <= satUpperCorner.getY(); y++) + { + for (int32_t x = satLowerCorner.getX(); x <= satUpperCorner.getX(); x++) + { + AccumulationType previousSum = static_cast(satVolume.getVoxel(x, y, z - 1)); + AccumulationType currentSum = static_cast(satVolume.getVoxel(x, y, z)); + + satVolume.setVoxel(x, y, z, previousSum + currentSum); + } + } + } + + //Now compute the average + const Vector3DInt32& v3dDstLowerCorner = m_regDst.getLowerCorner(); + const Vector3DInt32& v3dDstUpperCorner = m_regDst.getUpperCorner(); + + const Vector3DInt32& v3dSrcLowerCorner = m_regSrc.getLowerCorner(); + + for (int32_t iDstZ = v3dDstLowerCorner.getZ(), iSrcZ = v3dSrcLowerCorner.getZ(); iDstZ <= v3dDstUpperCorner.getZ(); iDstZ++, iSrcZ++) + { + for (int32_t iDstY = v3dDstLowerCorner.getY(), iSrcY = v3dSrcLowerCorner.getY(); iDstY <= v3dDstUpperCorner.getY(); iDstY++, iSrcY++) + { + for (int32_t iDstX = v3dDstLowerCorner.getX(), iSrcX = v3dSrcLowerCorner.getX(); iDstX <= v3dDstUpperCorner.getX(); iDstX++, iSrcX++) + { + int32_t satLowerX = iSrcX - border - 1; + int32_t satLowerY = iSrcY - border - 1; + int32_t satLowerZ = iSrcZ - border - 1; + + int32_t satUpperX = iSrcX + border; + int32_t satUpperY = iSrcY + border; + int32_t satUpperZ = iSrcZ + border; + + AccumulationType a = satVolume.getVoxel(satLowerX, satLowerY, satLowerZ); + AccumulationType b = satVolume.getVoxel(satUpperX, satLowerY, satLowerZ); + AccumulationType c = satVolume.getVoxel(satLowerX, satUpperY, satLowerZ); + AccumulationType d = satVolume.getVoxel(satUpperX, satUpperY, satLowerZ); + AccumulationType e = satVolume.getVoxel(satLowerX, satLowerY, satUpperZ); + AccumulationType f = satVolume.getVoxel(satUpperX, satLowerY, satUpperZ); + AccumulationType g = satVolume.getVoxel(satLowerX, satUpperY, satUpperZ); + AccumulationType h = satVolume.getVoxel(satUpperX, satUpperY, satUpperZ); + + AccumulationType sum = h + c - d - g - f - a + b + e; + uint32_t sideLength = border * 2 + 1; + AccumulationType average = sum / (sideLength*sideLength*sideLength); + + m_pVolDst->setVoxel(iDstX, iDstY, iDstZ, static_cast(average)); + } + } + } + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MarchingCubesSurfaceExtractor.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MarchingCubesSurfaceExtractor.h new file mode 100644 index 0000000..ef672aa --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MarchingCubesSurfaceExtractor.h @@ -0,0 +1,78 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_SurfaceExtractor_H__ +#define __PolyVox_SurfaceExtractor_H__ + +#include "Impl/MarchingCubesTables.h" +#include "Impl/PlatformDefinitions.h" + +#include "Array.h" +#include "DefaultMarchingCubesController.h" +#include "Mesh.h" +#include "Vertex.h" + +namespace PolyVox +{ + /// A specialised vertex format which encodes the data from the Marching Cubes algorithm in a very + /// compact way. You will probably want to use the decodeVertex() function to turn it into a regular + /// Vertex for rendering, but advanced users can also decode it on the GPU (see PolyVox examples). + template + struct MarchingCubesVertex + { + typedef _DataType DataType; + + /// Each component of the position is stored using 8.8 fixed-point encoding. + Vector3DUint16 encodedPosition; + + /// The normal is encoded as a 16-bit unsigned integer using the 'oct16' + /// encoding described here: http://jcgt.org/published/0003/02/01/ + uint16_t encodedNormal; + + /// The interpolated voxel data from the neighbouring voxels which generated this + /// vertex (every vertex is placed between two voxels by the MArching Cubes algorithm) + DataType data; + }; + + // Convienient shorthand for declaring a mesh of marching cubes vertices + // Currently disabled because it requires GCC 4.7 + //template + //using MarchingCubesMesh = Mesh< MarchingCubesVertex, IndexType >; + + /// Decodes a MarchingCubesVertex by converting it into a regular Vertex which can then be directly used for rendering. + template + Vertex decodeVertex(const MarchingCubesVertex& marchingCubesVertex); + + /// Generates a mesh from the voxel data using the Marching Cubes algorithm. + template< typename VolumeType, typename ControllerType = DefaultMarchingCubesController > + Mesh > extractMarchingCubesMesh(VolumeType* volData, Region region, ControllerType controller = ControllerType()); + + /// Generates a mesh from the voxel data using the Marching Cubes algorithm, placing the result into a user-provided Mesh. + template< typename VolumeType, typename MeshType, typename ControllerType = DefaultMarchingCubesController > + void extractMarchingCubesMeshCustom(VolumeType* volData, Region region, MeshType* result, ControllerType controller = ControllerType()); +} + +#include "MarchingCubesSurfaceExtractor.inl" + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MarchingCubesSurfaceExtractor.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MarchingCubesSurfaceExtractor.inl new file mode 100644 index 0000000..7680ec3 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MarchingCubesSurfaceExtractor.inl @@ -0,0 +1,585 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/Timer.h" + +namespace PolyVox +{ + //////////////////////////////////////////////////////////////////////////////// + // Vertex encoding/decoding + //////////////////////////////////////////////////////////////////////////////// + + inline Vector3DFloat decodePosition(const Vector3DUint16& encodedPosition) + { + Vector3DFloat result(encodedPosition.getX(), encodedPosition.getY(), encodedPosition.getZ()); + result *= (1.0f / 256.0f); // Division is compile-time constant + return result; + } + + inline uint16_t encodeNormal(const Vector3DFloat& normal) + { + // The first part of this function is based off the code in Listing 1 of http://jcgt.org/published/0003/02/01/ + // It was rewritten in C++ and is restructued for the CPU rather than the GPU. + + // Get the input components + float vx = normal.getX(); + float vy = normal.getY(); + float vz = normal.getZ(); + + // Project the sphere onto the octahedron, and then onto the xy plane + float px = vx * (1.0f / (std::abs(vx) + std::abs(vy) + std::abs(vz))); + float py = vy * (1.0f / (std::abs(vx) + std::abs(vy) + std::abs(vz))); + + // Reflect the folds of the lower hemisphere over the diagonals. + if (vz <= 0.0f) + { + float refx = ((1.0f - std::abs(py)) * (px >= 0.0f ? +1.0f : -1.0f)); + float refy = ((1.0f - std::abs(px)) * (py >= 0.0f ? +1.0f : -1.0f)); + px = refx; + py = refy; + } + + // The next part was not given in the paper. We map our two + // floats into two bytes and store them in a single uint16_t + + // Move from range [-1.0f, 1.0f] to [0.0f, 255.0f] + px = (px + 1.0f) * 127.5f; + py = (py + 1.0f) * 127.5f; + + // Convert to uints + uint16_t resultX = static_cast(px + 0.5f); + uint16_t resultY = static_cast(py + 0.5f); + + // Make sure only the lower bits are set. Probably + // not necessary but we're just being careful really. + resultX &= 0xFF; + resultY &= 0xFF; + + // Contatenate the bytes and return the result. + return (resultX << 8) | resultY; + } + + inline Vector3DFloat decodeNormal(const uint16_t& encodedNormal) + { + // Extract the two bytes from the uint16_t. + uint16_t ux = (encodedNormal >> 8) & 0xFF; + uint16_t uy = (encodedNormal)& 0xFF; + + // Convert to floats in the range [-1.0f, +1.0f]. + float ex = ux / 127.5f - 1.0f; + float ey = uy / 127.5f - 1.0f; + + // Reconstruct the origninal vector. This is a C++ implementation + // of Listing 2 of http://jcgt.org/published/0003/02/01/ + float vx = ex; + float vy = ey; + float vz = 1.0f - std::abs(ex) - std::abs(ey); + + if (vz < 0.0f) + { + float refX = ((1.0f - std::abs(vy)) * (vx >= 0.0f ? +1.0f : -1.0f)); + float refY = ((1.0f - std::abs(vx)) * (vy >= 0.0f ? +1.0f : -1.0f)); + vx = refX; + vy = refY; + } + + // Normalise and return the result. + Vector3DFloat v(vx, vy, vz); + v.normalise(); + return v; + } + + template + Vertex decodeVertex(const MarchingCubesVertex& marchingCubesVertex) + { + Vertex result; + result.position = decodePosition(marchingCubesVertex.encodedPosition); + result.normal = decodeNormal(marchingCubesVertex.encodedNormal); + result.data = marchingCubesVertex.data; // Data is not encoded + return result; + } + + //////////////////////////////////////////////////////////////////////////////// + // Gradient estimation + //////////////////////////////////////////////////////////////////////////////// + + template< typename Sampler, typename ControllerType> + Vector3DFloat computeCentralDifferenceGradient(const Sampler& volIter, ControllerType& controller) + { + //FIXME - Should actually use DensityType here, both in principle and because the maths may be + //faster (and to reduce casts). So it would be good to add a way to get DensityType from a voxel. + //But watch out for when the DensityType is unsigned and the difference could be negative. + float voxel1nx = static_cast(controller.convertToDensity(volIter.peekVoxel1nx0py0pz())); + float voxel1px = static_cast(controller.convertToDensity(volIter.peekVoxel1px0py0pz())); + + float voxel1ny = static_cast(controller.convertToDensity(volIter.peekVoxel0px1ny0pz())); + float voxel1py = static_cast(controller.convertToDensity(volIter.peekVoxel0px1py0pz())); + + float voxel1nz = static_cast(controller.convertToDensity(volIter.peekVoxel0px0py1nz())); + float voxel1pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px0py1pz())); + + return Vector3DFloat + ( + voxel1nx - voxel1px, + voxel1ny - voxel1py, + voxel1nz - voxel1pz + ); + } + + // This 'sobel' version of gradient estimation provides better (smoother) normals than the central difference version. + // Even with the 16-bit normal encoding it does seem to make a difference, so is probably worth keeping. However, there + // is no way to call it at the moment beyond modifying the main Marching Cubes function below to call this function + // instead of the central difference one. We should provide a way to control the normal generation method, perhaps + // including *no* normals incase the user wants to generate them afterwards (e.g. from the mesh). + template< typename Sampler, typename ControllerType> + Vector3DFloat computeSobelGradient(const Sampler& volIter, ControllerType& controller) + { + static const int weights[3][3][3] = { { { 2, 3, 2 }, { 3, 6, 3 }, { 2, 3, 2 } }, { + { 3, 6, 3 }, { 6, 0, 6 }, { 3, 6, 3 } }, { { 2, 3, 2 }, { 3, 6, 3 }, { 2, 3, 2 } } }; + + //FIXME - Should actually use DensityType here, both in principle and because the maths may be + //faster (and to reduce casts). So it would be good to add a way to get DensityType from a voxel. + //But watch out for when the DensityType is unsigned and the difference could be negative. + const float pVoxel1nx1ny1nz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx1ny1nz())); + const float pVoxel1nx1ny0pz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx1ny0pz())); + const float pVoxel1nx1ny1pz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx1ny1pz())); + const float pVoxel1nx0py1nz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx0py1nz())); + const float pVoxel1nx0py0pz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx0py0pz())); + const float pVoxel1nx0py1pz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx0py1pz())); + const float pVoxel1nx1py1nz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx1py1nz())); + const float pVoxel1nx1py0pz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx1py0pz())); + const float pVoxel1nx1py1pz = static_cast(controller.convertToDensity(volIter.peekVoxel1nx1py1pz())); + + const float pVoxel0px1ny1nz = static_cast(controller.convertToDensity(volIter.peekVoxel0px1ny1nz())); + const float pVoxel0px1ny0pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px1ny0pz())); + const float pVoxel0px1ny1pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px1ny1pz())); + const float pVoxel0px0py1nz = static_cast(controller.convertToDensity(volIter.peekVoxel0px0py1nz())); + //const float pVoxel0px0py0pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px0py0pz())); + const float pVoxel0px0py1pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px0py1pz())); + const float pVoxel0px1py1nz = static_cast(controller.convertToDensity(volIter.peekVoxel0px1py1nz())); + const float pVoxel0px1py0pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px1py0pz())); + const float pVoxel0px1py1pz = static_cast(controller.convertToDensity(volIter.peekVoxel0px1py1pz())); + + const float pVoxel1px1ny1nz = static_cast(controller.convertToDensity(volIter.peekVoxel1px1ny1nz())); + const float pVoxel1px1ny0pz = static_cast(controller.convertToDensity(volIter.peekVoxel1px1ny0pz())); + const float pVoxel1px1ny1pz = static_cast(controller.convertToDensity(volIter.peekVoxel1px1ny1pz())); + const float pVoxel1px0py1nz = static_cast(controller.convertToDensity(volIter.peekVoxel1px0py1nz())); + const float pVoxel1px0py0pz = static_cast(controller.convertToDensity(volIter.peekVoxel1px0py0pz())); + const float pVoxel1px0py1pz = static_cast(controller.convertToDensity(volIter.peekVoxel1px0py1pz())); + const float pVoxel1px1py1nz = static_cast(controller.convertToDensity(volIter.peekVoxel1px1py1nz())); + const float pVoxel1px1py0pz = static_cast(controller.convertToDensity(volIter.peekVoxel1px1py0pz())); + const float pVoxel1px1py1pz = static_cast(controller.convertToDensity(volIter.peekVoxel1px1py1pz())); + + const float xGrad(-weights[0][0][0] * pVoxel1nx1ny1nz - + weights[1][0][0] * pVoxel1nx1ny0pz - weights[2][0][0] * + pVoxel1nx1ny1pz - weights[0][1][0] * pVoxel1nx0py1nz - + weights[1][1][0] * pVoxel1nx0py0pz - weights[2][1][0] * + pVoxel1nx0py1pz - weights[0][2][0] * pVoxel1nx1py1nz - + weights[1][2][0] * pVoxel1nx1py0pz - weights[2][2][0] * + pVoxel1nx1py1pz + weights[0][0][2] * pVoxel1px1ny1nz + + weights[1][0][2] * pVoxel1px1ny0pz + weights[2][0][2] * + pVoxel1px1ny1pz + weights[0][1][2] * pVoxel1px0py1nz + + weights[1][1][2] * pVoxel1px0py0pz + weights[2][1][2] * + pVoxel1px0py1pz + weights[0][2][2] * pVoxel1px1py1nz + + weights[1][2][2] * pVoxel1px1py0pz + weights[2][2][2] * + pVoxel1px1py1pz); + + const float yGrad(-weights[0][0][0] * pVoxel1nx1ny1nz - + weights[1][0][0] * pVoxel1nx1ny0pz - weights[2][0][0] * + pVoxel1nx1ny1pz + weights[0][2][0] * pVoxel1nx1py1nz + + weights[1][2][0] * pVoxel1nx1py0pz + weights[2][2][0] * + pVoxel1nx1py1pz - weights[0][0][1] * pVoxel0px1ny1nz - + weights[1][0][1] * pVoxel0px1ny0pz - weights[2][0][1] * + pVoxel0px1ny1pz + weights[0][2][1] * pVoxel0px1py1nz + + weights[1][2][1] * pVoxel0px1py0pz + weights[2][2][1] * + pVoxel0px1py1pz - weights[0][0][2] * pVoxel1px1ny1nz - + weights[1][0][2] * pVoxel1px1ny0pz - weights[2][0][2] * + pVoxel1px1ny1pz + weights[0][2][2] * pVoxel1px1py1nz + + weights[1][2][2] * pVoxel1px1py0pz + weights[2][2][2] * + pVoxel1px1py1pz); + + const float zGrad(-weights[0][0][0] * pVoxel1nx1ny1nz + + weights[2][0][0] * pVoxel1nx1ny1pz - weights[0][1][0] * + pVoxel1nx0py1nz + weights[2][1][0] * pVoxel1nx0py1pz - + weights[0][2][0] * pVoxel1nx1py1nz + weights[2][2][0] * + pVoxel1nx1py1pz - weights[0][0][1] * pVoxel0px1ny1nz + + weights[2][0][1] * pVoxel0px1ny1pz - weights[0][1][1] * + pVoxel0px0py1nz + weights[2][1][1] * pVoxel0px0py1pz - + weights[0][2][1] * pVoxel0px1py1nz + weights[2][2][1] * + pVoxel0px1py1pz - weights[0][0][2] * pVoxel1px1ny1nz + + weights[2][0][2] * pVoxel1px1ny1pz - weights[0][1][2] * + pVoxel1px0py1nz + weights[2][1][2] * pVoxel1px0py1pz - + weights[0][2][2] * pVoxel1px1py1nz + weights[2][2][2] * + pVoxel1px1py1pz); + + //Note: The above actually give gradients going from low density to high density. + //For our normals we want the the other way around, so we switch the components as we return them. + return Vector3DFloat(-xGrad, -yGrad, -zGrad); + } + + //////////////////////////////////////////////////////////////////////////////// + // Surface extraction + //////////////////////////////////////////////////////////////////////////////// + + /// This is probably the version of Marching Cubes extraction which you will want to use initially, at least + /// until you determine you have a need for the extra functionality provied by extractMarchingCubesMeshCustom(). + template< typename VolumeType, typename ControllerType > + Mesh > extractMarchingCubesMesh(VolumeType* volData, Region region, ControllerType controller) + { + Mesh > result; + extractMarchingCubesMeshCustom, DefaultIndexType > >(volData, region, &result, controller); + return result; + } + + /// This version of the function performs the extraction into a user-provided mesh rather than allocating a mesh automatically. + /// There are a few reasons why this might be useful to more advanced users: + /// + /// 1. It leaves the user in control of memory allocation and would allow them to implement e.g. a mesh pooling system. + /// 2. The user-provided mesh could have a different index type (e.g. 16-bit indices) to reduce memory usage. + /// 3. The user could provide a custom mesh class, e.g a thin wrapper around an OpenGL VBO to allow direct writing into this structure. + /// + /// We don't provide a default MeshType here. If the user doesn't want to provide a MeshType then it probably makes + /// more sense to use the other variant of this function where the mesh is a return value rather than a parameter. + /// + /// Note: This function is called 'extractMarchingCubesMeshCustom' rather than 'extractMarchingCubesMesh' to avoid ambiguity when only three parameters + /// are provided (would the third parameter be a controller or a mesh?). It seems this can be fixed by using enable_if/static_assert to emulate concepts, + /// but this is relatively complex and I haven't done it yet. Could always add it later as another overload. + template< typename VolumeType, typename MeshType, typename ControllerType > + void extractMarchingCubesMeshCustom(VolumeType* volData, Region region, MeshType* result, ControllerType controller) + { + // Validate parameters + POLYVOX_THROW_IF(volData == nullptr, std::invalid_argument, "Provided volume cannot be null"); + POLYVOX_THROW_IF(result == nullptr, std::invalid_argument, "Provided mesh cannot be null"); + + // For profiling this function + Timer timer; + + // Performance note: Profiling indicates that simply adding vertices and indices to the std::vector is one + // of the bottlenecks when generating the mesh. Reserving space in advance helps here but is wasteful in the + // common case that no/few vertices are generated. Maybe it's worth reserving a couple of thousand or so? + // Alternatively, maybe the docs should suggest the user reserves some space in the mesh they pass in? + result->clear(); + + // Store some commonly used values for performance and convienience + const uint32_t uRegionWidthInVoxels = region.getWidthInVoxels(); + const uint32_t uRegionHeightInVoxels = region.getHeightInVoxels(); + const uint32_t uRegionDepthInVoxels = region.getDepthInVoxels(); + + typename ControllerType::DensityType tThreshold = controller.getThreshold(); + + // A naive implemetation of Marching Cubes might sample the eight corner voxels of every cell to determine the cell index. + // However, when processing the cells sequentially we cn observe that many of the voxels are shared with previous adjacent + // cells, and so we can obtain these by careful bit-shifting. These variables keep track of previous cells for this purpose. + // We don't clear the arrays because the algorithm ensures that we only read from elements we have previously written to. + uint8_t uPreviousCellIndex = 0; + Array1DUint8 pPreviousRowCellIndices(uRegionWidthInVoxels); + Array2DUint8 pPreviousSliceCellIndices(uRegionWidthInVoxels, uRegionHeightInVoxels); + + // A given vertex may be shared by multiple triangles, so we need to keep track of the indices into the vertex array. + // We don't clear the arrays because the algorithm ensures that we only read from elements we have previously written to. + Array<2, Vector3DInt32> pIndices(uRegionWidthInVoxels, uRegionHeightInVoxels); + Array<2, Vector3DInt32> pPreviousIndices(uRegionWidthInVoxels, uRegionHeightInVoxels); + + // A sampler pointing at the beginning of the region, which gets incremented to always point at the beginning of a slice. + typename VolumeType::Sampler startOfSlice(volData); + startOfSlice.setPosition(region.getLowerX(), region.getLowerY(), region.getLowerZ()); + + for (uint32_t uZRegSpace = 0; uZRegSpace < uRegionDepthInVoxels; uZRegSpace++) + { + // A sampler pointing at the beginning of the slice, which gets incremented to always point at the beginning of a row. + typename VolumeType::Sampler startOfRow = startOfSlice; + + for (uint32_t uYRegSpace = 0; uYRegSpace < uRegionHeightInVoxels; uYRegSpace++) + { + // Copying a sampler which is already pointing at the correct location seems (slightly) faster than + // calling setPosition(). Therefore we make use of 'startOfRow' and 'startOfSlice' to reset the sampler. + typename VolumeType::Sampler sampler = startOfRow; + + for (uint32_t uXRegSpace = 0; uXRegSpace < uRegionWidthInVoxels; uXRegSpace++) + { + // Note: In many cases the provided region will be (mostly) empty which means mesh vertices/indices + // are not generated and the only thing that is done for each cell is the computation of uCellIndex. + // It appears that retriving the voxel value is not so expensive and that it is the bitwise combining + // which actually carries the cost. + // + // If we really need to speed this up more then it may be possible to pack 4 8-bit cell indices into + // a single 32-bit value and then perform the bitwise logic on all four of them at the same time. + // However, this complicates the code and there would still be the cost of packing/unpacking so it's + // not clear if there is really a benefit. It's something to consider in the future. + + // Each bit of the cell index specifies whether a given corner of the cell is above or below the threshold. + uint8_t uCellIndex = 0; + + // Four bits of our cube index are obtained by looking at the cube index for + // the previous slice and copying four of those bits into their new positions. + uint8_t uPreviousCellIndexZ = pPreviousSliceCellIndices(uXRegSpace, uYRegSpace); + uPreviousCellIndexZ >>= 4; + uCellIndex |= uPreviousCellIndexZ; + + // Two bits of our cube index are obtained by looking at the cube index for + // the previous row and copying two of those bits into their new positions. + uint8_t uPreviousCellIndexY = pPreviousRowCellIndices(uXRegSpace); + uPreviousCellIndexY &= 204; //204 = 128+64+8+4 + uPreviousCellIndexY >>= 2; + uCellIndex |= uPreviousCellIndexY; + + // One bit of our cube index are obtained by looking at the cube index for + // the previous cell and copying one of those bits into it's new position. + uint8_t UPreviousCellIndexX = uPreviousCellIndex; + UPreviousCellIndexX &= 170; //170 = 128+32+8+2 + UPreviousCellIndexX >>= 1; + uCellIndex |= UPreviousCellIndexX; + + // The last bit of our cube index is obtained by looking + // at the relevant voxel and comparing it to the threshold + typename VolumeType::VoxelType v111 = sampler.getVoxel(); + if (controller.convertToDensity(v111) < tThreshold) uCellIndex |= 128; + + // The current value becomes the previous value, ready for the next iteration. + uPreviousCellIndex = uCellIndex; + pPreviousRowCellIndices(uXRegSpace) = uCellIndex; + pPreviousSliceCellIndices(uXRegSpace, uYRegSpace) = uCellIndex; + + // 12 bits of uEdge determine whether a vertex is placed on each of the 12 edges of the cell. + uint16_t uEdge = edgeTable[uCellIndex]; + + // Test whether any vertices and indices should be generated for the current cell (i.e. it is occupied). + // Performance note: This condition is usually false because most cells in a volume are completely above + // or below the threshold and hence unoccupied. However, even when it is always false (testing on an empty + // volume) it still incurs significant overhead, probably because the code is large and bloats the for loop + // which contains it. On my empty volume test case the code as given runs in 34ms, but if I replace the + // condition with 'false' it runs in 24ms and gives the same output (i.e. none). + // + // An improvement is to move the code into a seperate function which does speed things up (30ms), but this + // is messy as the function needs to be passed about 10 differnt parameters, probably adding some overhead + // in its self. This does indeed seem to slow down the case when cells are occupied, by about 10-20%. + // + // Overall I don't know the right solution, but I'm leaving the code as-is to avoid making it messy. If we + // can reduce the number of parameters which need to be passed then it might be worth moving it into a + // function, or otherwise it may simply be worth trying to shorten the code (e.g. adding other function + // calls). For now we will leave it as-is, until we have more information from real-world profiling. + if (uEdge != 0) + { + auto v111Density = controller.convertToDensity(v111); + + // Performance note: Computing normals is one of the bottlencks in the mesh generation process. The + // central difference approach actually samples the same voxel more than once as we call it on two + // adjacent voxels. Perhaps we could expand this and eliminate dupicates in the future. Alternatively, + // we could compute vertex normals from adjacent face normals instead of via central differencing, + // but not for vertices on the edge of the region (as this causes visual discontinities). + const Vector3DFloat n111 = computeCentralDifferenceGradient(sampler, controller); + + /* Find the vertices where the surface intersects the cube */ + if ((uEdge & 64) && (uXRegSpace > 0)) + { + sampler.moveNegativeX(); + typename VolumeType::VoxelType v011 = sampler.getVoxel(); + auto v011Density = controller.convertToDensity(v011); + const float fInterp = static_cast(tThreshold - v011Density) / static_cast(v111Density - v011Density); + + // Compute the position + const Vector3DFloat v3dPosition(static_cast(uXRegSpace - 1) + fInterp, static_cast(uYRegSpace), static_cast(uZRegSpace)); + + // Compute the normal + const Vector3DFloat n011 = computeCentralDifferenceGradient(sampler, controller); + Vector3DFloat v3dNormal = (n111*fInterp) + (n011*(1 - fInterp)); + + // The gradient for a voxel can be zero (e.g. solid voxel surrounded by empty ones) and so + // the interpolated normal can also be zero (e.g. a grid of alternating solid and empty voxels). + if (v3dNormal.lengthSquared() > 0.000001f) + { + v3dNormal.normalise(); + } + + // Allow the controller to decide how the material should be derived from the voxels. + const typename VolumeType::VoxelType uMaterial = controller.blendMaterials(v011, v111, fInterp); + + MarchingCubesVertex surfaceVertex; + const Vector3DUint16 v3dScaledPosition(static_cast(v3dPosition.getX() * 256.0f), static_cast(v3dPosition.getY() * 256.0f), static_cast(v3dPosition.getZ() * 256.0f)); + surfaceVertex.encodedPosition = v3dScaledPosition; + surfaceVertex.encodedNormal = encodeNormal(v3dNormal); + surfaceVertex.data = uMaterial; + + const uint32_t uLastVertexIndex = result->addVertex(surfaceVertex); + pIndices(uXRegSpace, uYRegSpace).setX(uLastVertexIndex); + + sampler.movePositiveX(); + } + if ((uEdge & 32) && (uYRegSpace > 0)) + { + sampler.moveNegativeY(); + typename VolumeType::VoxelType v101 = sampler.getVoxel(); + auto v101Density = controller.convertToDensity(v101); + const float fInterp = static_cast(tThreshold - v101Density) / static_cast(v111Density - v101Density); + + // Compute the position + const Vector3DFloat v3dPosition(static_cast(uXRegSpace), static_cast(uYRegSpace - 1) + fInterp, static_cast(uZRegSpace)); + + // Compute the normal + const Vector3DFloat n101 = computeCentralDifferenceGradient(sampler, controller); + Vector3DFloat v3dNormal = (n111*fInterp) + (n101*(1 - fInterp)); + + // The gradient for a voxel can be zero (e.g. solid voxel surrounded by empty ones) and so + // the interpolated normal can also be zero (e.g. a grid of alternating solid and empty voxels). + if (v3dNormal.lengthSquared() > 0.000001f) + { + v3dNormal.normalise(); + } + + // Allow the controller to decide how the material should be derived from the voxels. + const typename VolumeType::VoxelType uMaterial = controller.blendMaterials(v101, v111, fInterp); + + MarchingCubesVertex surfaceVertex; + const Vector3DUint16 v3dScaledPosition(static_cast(v3dPosition.getX() * 256.0f), static_cast(v3dPosition.getY() * 256.0f), static_cast(v3dPosition.getZ() * 256.0f)); + surfaceVertex.encodedPosition = v3dScaledPosition; + surfaceVertex.encodedNormal = encodeNormal(v3dNormal); + surfaceVertex.data = uMaterial; + + uint32_t uLastVertexIndex = result->addVertex(surfaceVertex); + pIndices(uXRegSpace, uYRegSpace).setY(uLastVertexIndex); + + sampler.movePositiveY(); + } + if ((uEdge & 1024) && (uZRegSpace > 0)) + { + sampler.moveNegativeZ(); + typename VolumeType::VoxelType v110 = sampler.getVoxel(); + auto v110Density = controller.convertToDensity(v110); + const float fInterp = static_cast(tThreshold - v110Density) / static_cast(v111Density - v110Density); + + // Compute the position + const Vector3DFloat v3dPosition(static_cast(uXRegSpace), static_cast(uYRegSpace), static_cast(uZRegSpace - 1) + fInterp); + + // Compute the normal + const Vector3DFloat n110 = computeCentralDifferenceGradient(sampler, controller); + Vector3DFloat v3dNormal = (n111*fInterp) + (n110*(1 - fInterp)); + + // The gradient for a voxel can be zero (e.g. solid voxel surrounded by empty ones) and so + // the interpolated normal can also be zero (e.g. a grid of alternating solid and empty voxels). + if (v3dNormal.lengthSquared() > 0.000001f) + { + v3dNormal.normalise(); + } + + // Allow the controller to decide how the material should be derived from the voxels. + const typename VolumeType::VoxelType uMaterial = controller.blendMaterials(v110, v111, fInterp); + + MarchingCubesVertex surfaceVertex; + const Vector3DUint16 v3dScaledPosition(static_cast(v3dPosition.getX() * 256.0f), static_cast(v3dPosition.getY() * 256.0f), static_cast(v3dPosition.getZ() * 256.0f)); + surfaceVertex.encodedPosition = v3dScaledPosition; + surfaceVertex.encodedNormal = encodeNormal(v3dNormal); + surfaceVertex.data = uMaterial; + + const uint32_t uLastVertexIndex = result->addVertex(surfaceVertex); + pIndices(uXRegSpace, uYRegSpace).setZ(uLastVertexIndex); + + sampler.movePositiveZ(); + } + + // Now output the indices. For the first row, column or slice there aren't + // any (the region size in cells is one less than the region size in voxels) + if ((uXRegSpace != 0) && (uYRegSpace != 0) && (uZRegSpace != 0)) + { + + int32_t indlist[12]; + + /* Find the vertices where the surface intersects the cube */ + if (uEdge & 1) + { + indlist[0] = pPreviousIndices(uXRegSpace, uYRegSpace - 1).getX(); + } + if (uEdge & 2) + { + indlist[1] = pPreviousIndices(uXRegSpace, uYRegSpace).getY(); + } + if (uEdge & 4) + { + indlist[2] = pPreviousIndices(uXRegSpace, uYRegSpace).getX(); + } + if (uEdge & 8) + { + indlist[3] = pPreviousIndices(uXRegSpace - 1, uYRegSpace).getY(); + } + if (uEdge & 16) + { + indlist[4] = pIndices(uXRegSpace, uYRegSpace - 1).getX(); + } + if (uEdge & 32) + { + indlist[5] = pIndices(uXRegSpace, uYRegSpace).getY(); + } + if (uEdge & 64) + { + indlist[6] = pIndices(uXRegSpace, uYRegSpace).getX(); + } + if (uEdge & 128) + { + indlist[7] = pIndices(uXRegSpace - 1, uYRegSpace).getY(); + } + if (uEdge & 256) + { + indlist[8] = pIndices(uXRegSpace - 1, uYRegSpace - 1).getZ(); + } + if (uEdge & 512) + { + indlist[9] = pIndices(uXRegSpace, uYRegSpace - 1).getZ(); + } + if (uEdge & 1024) + { + indlist[10] = pIndices(uXRegSpace, uYRegSpace).getZ(); + } + if (uEdge & 2048) + { + indlist[11] = pIndices(uXRegSpace - 1, uYRegSpace).getZ(); + } + + for (int i = 0; triTable[uCellIndex][i] != -1; i += 3) + { + const int32_t ind0 = indlist[triTable[uCellIndex][i]]; + const int32_t ind1 = indlist[triTable[uCellIndex][i + 1]]; + const int32_t ind2 = indlist[triTable[uCellIndex][i + 2]]; + + if ((ind0 != -1) && (ind1 != -1) && (ind2 != -1)) + { + result->addTriangle(ind0, ind1, ind2); + } + } // For each triangle + } + } // For each cell + sampler.movePositiveX(); + } // For X + startOfRow.movePositiveY(); + } // For Y + startOfSlice.movePositiveZ(); + + pIndices.swap(pPreviousIndices); + } // For Z + + result->setOffset(region.getLowerCorner()); + + POLYVOX_LOG_TRACE("Marching cubes surface extraction took ", timer.elapsedTimeInMilliSeconds(), + "ms (Region size = ", region.getWidthInVoxels(), "x", region.getHeightInVoxels(), + "x", region.getDepthInVoxels(), ")"); + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Material.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Material.h new file mode 100644 index 0000000..c87d0a0 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Material.h @@ -0,0 +1,94 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Material_H__ +#define __PolyVox_Material_H__ + +#include "Impl/PlatformDefinitions.h" + +#include "DefaultIsQuadNeeded.h" //we'll specialise this function for this voxel type + +namespace PolyVox +{ + ///This class represents a voxel storing only a material. + //////////////////////////////////////////////////////////////////////////////// + /// Note that this should probably just be considered an example of how to define + /// a voxel type for the Marching Cubes algorithm. Advanced users are likely to + /// define custom voxel types and possibly custom controllers. + /// + /// \sa Density, MaterialDensityPair + //////////////////////////////////////////////////////////////////////////////// + template + class Material + { + public: + Material() : m_uMaterial(0) {} + Material(Type uMaterial) : m_uMaterial(uMaterial) {} + + bool operator==(const Material& rhs) const + { + return (m_uMaterial == rhs.m_uMaterial); + }; + + bool operator!=(const Material& rhs) const + { + return !(*this == rhs); + } + + /// \return The current material value of the voxel + Type getMaterial() const { return m_uMaterial; } + /** + * Set the material value of the voxel + * + * \param uMaterial The material to set to + */ + void setMaterial(Type uMaterial) { m_uMaterial = uMaterial; } + + private: + Type m_uMaterial; + }; + + typedef Material Material8; + typedef Material Material16; + + template + class DefaultIsQuadNeeded< Material > + { + public: + bool operator()(Material back, Material front, Material& materialToUse) + { + if ((back.getMaterial() > 0) && (front.getMaterial() == 0)) + { + materialToUse = back; + return true; + } + else + { + return false; + } + } + }; +} + +#endif //__PolyVox_Material_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MaterialDensityPair.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MaterialDensityPair.h new file mode 100644 index 0000000..02721c1 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/MaterialDensityPair.h @@ -0,0 +1,168 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_MaterialDensityPair_H__ +#define __PolyVox_MaterialDensityPair_H__ + +#include "DefaultIsQuadNeeded.h" //we'll specialise this function for this voxel type +#include "DefaultMarchingCubesController.h" //We'll specialise the controller contained in here + +#include "Impl/PlatformDefinitions.h" + +namespace PolyVox +{ + /// This class represents a voxel storing only a density. + //////////////////////////////////////////////////////////////////////////////// + /// Note that this should probably just be considered an example of how to define + /// a voxel type for the Marching Cubes algorithm. Advanced users are likely to + /// define custom voxel types and possibly custom controllers. + /// + /// \sa Density, Material + //////////////////////////////////////////////////////////////////////////////// + template + class MaterialDensityPair + { + public: + MaterialDensityPair() : m_uMaterial(0), m_uDensity(0) {} + MaterialDensityPair(Type uMaterial, Type uDensity) : m_uMaterial(uMaterial), m_uDensity(uDensity) {} + + bool operator==(const MaterialDensityPair& rhs) const + { + return (m_uMaterial == rhs.m_uMaterial) && (m_uDensity == rhs.m_uDensity); + }; + + bool operator!=(const MaterialDensityPair& rhs) const + { + return !(*this == rhs); + } + + MaterialDensityPair& operator+=(const MaterialDensityPair& rhs) + { + m_uDensity += rhs.m_uDensity; + + // What should we do with the material? Conceptually the idea of adding materials makes no sense, but for our + // purposes we consider the 'sum' of two materials to just be the max. At least this way it is commutative. + m_uMaterial = (std::max)(m_uMaterial, rhs.m_uMaterial); + + return *this; + } + + MaterialDensityPair& operator/=(uint32_t rhs) + { + // There's nothing sensible we can do with the material, so this function only affects the density. + m_uDensity /= rhs; + return *this; + } + + Type getDensity() const { return m_uDensity; } + Type getMaterial() const { return m_uMaterial; } + + void setDensity(Type uDensity) { m_uDensity = uDensity; } + void setMaterial(Type uMaterial) { m_uMaterial = uMaterial; } + + static Type getMaxDensity() { return (0x01 << NoOfDensityBits) - 1; } + static Type getMinDensity() { return 0; } + + private: + Type m_uMaterial : NoOfMaterialBits; + Type m_uDensity : NoOfDensityBits; + }; + + template + class DefaultIsQuadNeeded< MaterialDensityPair > + { + public: + bool operator()(MaterialDensityPair back, MaterialDensityPair front, MaterialDensityPair& materialToUse) + { + if ((back.getMaterial() > 0) && (front.getMaterial() == 0)) + { + materialToUse = back; + return true; + } + else + { + return false; + } + } + }; + + template + class DefaultMarchingCubesController< MaterialDensityPair > + { + public: + typedef Type DensityType; + typedef Type MaterialType; + + DefaultMarchingCubesController(void) + { + // Default to a threshold value halfway between the min and max possible values. + m_tThreshold = (MaterialDensityPair::getMinDensity() + MaterialDensityPair::getMaxDensity()) / 2; + } + + DefaultMarchingCubesController(DensityType tThreshold) + { + m_tThreshold = tThreshold; + } + + DensityType convertToDensity(MaterialDensityPair voxel) + { + return voxel.getDensity(); + } + + MaterialType convertToMaterial(MaterialDensityPair voxel) + { + return voxel.getMaterial(); + } + + MaterialDensityPair blendMaterials(MaterialDensityPair a, MaterialDensityPair b, float /*weight*/) + { + if (convertToDensity(a) > convertToDensity(b)) + { + return a; + } + else + { + return b; + } + } + + DensityType getThreshold(void) + { + return m_tThreshold; + } + + void setThreshold(DensityType tThreshold) + { + m_tThreshold = tThreshold; + } + + private: + DensityType m_tThreshold; + }; + + typedef MaterialDensityPair MaterialDensityPair44; + typedef MaterialDensityPair MaterialDensityPair88; +} + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Mesh.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Mesh.h new file mode 100644 index 0000000..f5f016e --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Mesh.h @@ -0,0 +1,108 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Mesh_H__ +#define __PolyVox_Mesh_H__ + +#include "Impl/PlatformDefinitions.h" + +#include "Region.h" +#include "Vertex.h" //Should probably do away with this one in the future... + +#include +#include +#include +#include +#include +#include + +namespace PolyVox +{ + /// A simple and general-purpose mesh class to represent the data returned by the surface extraction functions. + /// It supports different vertex types (which will vary depending on the surface extractor used and the contents + /// of the volume) and both 16-bit and 32 bit indices. + typedef uint32_t DefaultIndexType; + template + class Mesh + { + public: + + typedef _VertexType VertexType; + typedef _IndexType IndexType; + + Mesh(); + ~Mesh(); + + IndexType getNoOfVertices(void) const; + const VertexType& getVertex(IndexType index) const; + const VertexType* getRawVertexData(void) const; + + size_t getNoOfIndices(void) const; + IndexType getIndex(uint32_t index) const; + const IndexType* getRawIndexData(void) const; + + const Vector3DInt32& getOffset(void) const; + void setOffset(const Vector3DInt32& offset); + + IndexType addVertex(const VertexType& vertex); + void addTriangle(IndexType index0, IndexType index1, IndexType index2); + + void clear(void); + bool isEmpty(void) const; + void removeUnusedVertices(void); + + private: + std::vector m_vecIndices; + std::vector m_vecVertices; + Vector3DInt32 m_offset; + }; + + /// Meshes returned by the surface extractors often have vertices with efficient compressed + /// formats which are hard to interpret directly (see CubicVertex and MarchingCubesVertex). + /// This function creates a new uncompressed mesh containing the much simpler Vertex objects. + template + Mesh< Vertex< typename MeshType::VertexType::DataType >, typename MeshType::IndexType > decodeMesh(const MeshType& encodedMesh) + { + Mesh< Vertex< typename MeshType::VertexType::DataType >, typename MeshType::IndexType > decodedMesh; + + for (typename MeshType::IndexType ct = 0; ct < encodedMesh.getNoOfVertices(); ct++) + { + decodedMesh.addVertex(decodeVertex(encodedMesh.getVertex(ct))); + } + + POLYVOX_ASSERT(encodedMesh.getNoOfIndices() % 3 == 0, "The number of indices must always be a multiple of three."); + for (uint32_t ct = 0; ct < encodedMesh.getNoOfIndices(); ct += 3) + { + decodedMesh.addTriangle(encodedMesh.getIndex(ct), encodedMesh.getIndex(ct + 1), encodedMesh.getIndex(ct + 2)); + } + + decodedMesh.setOffset(encodedMesh.getOffset()); + + return decodedMesh; + } +} + +#include "Mesh.inl" + +#endif /* __Mesh_H__ */ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Mesh.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Mesh.inl new file mode 100644 index 0000000..61a8095 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Mesh.inl @@ -0,0 +1,152 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + template + Mesh::Mesh() + { + } + + template + Mesh::~Mesh() + { + } + + template + IndexType Mesh::getNoOfVertices(void) const + { + return static_cast(m_vecVertices.size()); + } + + template + const VertexType& Mesh::getVertex(IndexType index) const + { + return m_vecVertices[index]; + } + + template + const VertexType* Mesh::getRawVertexData(void) const + { + return m_vecVertices.data(); + } + + template + size_t Mesh::getNoOfIndices(void) const + { + return m_vecIndices.size(); + } + + template + IndexType Mesh::getIndex(uint32_t index) const + { + return m_vecIndices[index]; + } + + template + const IndexType* Mesh::getRawIndexData(void) const + { + return m_vecIndices.data(); + } + + template + const Vector3DInt32& Mesh::getOffset(void) const + { + return m_offset; + } + + template + void Mesh::setOffset(const Vector3DInt32& offset) + { + m_offset = offset; + } + + template + void Mesh::addTriangle(IndexType index0, IndexType index1, IndexType index2) + { + //Make sure the specified indices correspond to valid vertices. + POLYVOX_ASSERT(index0 < m_vecVertices.size(), "Index points at an invalid vertex."); + POLYVOX_ASSERT(index1 < m_vecVertices.size(), "Index points at an invalid vertex."); + POLYVOX_ASSERT(index2 < m_vecVertices.size(), "Index points at an invalid vertex."); + + m_vecIndices.push_back(index0); + m_vecIndices.push_back(index1); + m_vecIndices.push_back(index2); + } + + template + IndexType Mesh::addVertex(const VertexType& vertex) + { + // We should not add more vertices than our chosen index type will let us index. + POLYVOX_THROW_IF(m_vecVertices.size() >= std::numeric_limits::max(), std::out_of_range, "Mesh has more vertices that the chosen index type allows."); + + m_vecVertices.push_back(vertex); + return m_vecVertices.size() - 1; + } + + template + void Mesh::clear(void) + { + m_vecVertices.clear(); + m_vecIndices.clear(); + } + + template + bool Mesh::isEmpty(void) const + { + return (getNoOfVertices() == 0) || (getNoOfIndices() == 0); + } + + template + void Mesh::removeUnusedVertices(void) + { + std::vector isVertexUsed(m_vecVertices.size()); + std::fill(isVertexUsed.begin(), isVertexUsed.end(), false); + + for (uint32_t triCt = 0; triCt < m_vecIndices.size(); triCt++) + { + int v = m_vecIndices[triCt]; + isVertexUsed[v] = true; + } + + int noOfUsedVertices = 0; + std::vector newPos(m_vecVertices.size()); + for (IndexType vertCt = 0; vertCt < m_vecVertices.size(); vertCt++) + { + if (isVertexUsed[vertCt]) + { + m_vecVertices[noOfUsedVertices] = m_vecVertices[vertCt]; + newPos[vertCt] = noOfUsedVertices; + noOfUsedVertices++; + } + } + + m_vecVertices.resize(noOfUsedVertices); + + for (uint32_t triCt = 0; triCt < m_vecIndices.size(); triCt++) + { + m_vecIndices[triCt] = newPos[m_vecIndices[triCt]]; + } + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolume.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolume.h new file mode 100644 index 0000000..d8f5669 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolume.h @@ -0,0 +1,278 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_PagedVolume_H__ +#define __PolyVox_PagedVolume_H__ + +#include "BaseVolume.h" +#include "Region.h" +#include "Vector.h" + +#include +#include //For abort() +#include //For memcpy +#include +#include +#include +#include +#include //For invalid_argument +#include + +namespace PolyVox +{ + /// This class provide a volume implementation which avoids storing all the data in memory at all times. Instead it breaks the volume + /// down into a set of chunks and moves these into and out of memory on demand. This means it is much more memory efficient than the + /// RawVolume, but may also be slower and is more complicated We encourage uses to work with RawVolume initially, and then switch to + /// PagedVolume once they have a larger application and/or a better understanding of PolyVox. + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /// + /// The PagedVolume makes use of a Pager which defines the source and/or destination for data paged into and out of memory. PolyVox + /// comes with an example FilePager though users can also implement their own approaches. For example, the Pager could instead stream + /// data from a network connection or generate it procedurally on demand. + /// + /// A consequence of this paging approach is that (unlike the RawVolume) the PagedVolume does not need to have a predefined size. After + /// the volume has been created you can begin acessing voxels anywhere in space and the required data will be created automatically. + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + template + class PagedVolume : public BaseVolume + { + public: + /// The PagedVolume stores it data as a set of Chunk instances which can be loaded and unloaded as memory requirements dictate. + class Chunk; + /// The Pager class is responsible for the loading and unloading of Chunks, and can be subclassed by the user. + class Pager; + + class Chunk + { + friend class PagedVolume; + + public: + Chunk(Vector3DInt32 v3dPosition, uint16_t uSideLength, Pager* pPager = nullptr); + ~Chunk(); + + VoxelType* getData(void) const; + uint32_t getDataSizeInBytes(void) const; + + VoxelType getVoxel(uint32_t uXPos, uint32_t uYPos, uint32_t uZPos) const; + VoxelType getVoxel(const Vector3DUint16& v3dPos) const; + + void setVoxel(uint32_t uXPos, uint32_t uYPos, uint32_t uZPos, VoxelType tValue); + void setVoxel(const Vector3DUint16& v3dPos, VoxelType tValue); + + void changeLinearOrderingToMorton(void); + void changeMortonOrderingToLinear(void); + + private: + /// Private copy constructor to prevent accisdental copying + Chunk(const Chunk& /*rhs*/) {}; + + /// Private assignment operator to prevent accisdental copying + Chunk& operator=(const Chunk& /*rhs*/) {}; + + // This is updated by the PagedVolume and used to discard the least recently used chunks. + uint32_t m_uChunkLastAccessed; + + // This is so we can tell whether a uncompressed chunk has to be recompressed and whether + // a compressed chunk has to be paged back to disk, or whether they can just be discarded. + bool m_bDataModified; + + uint32_t calculateSizeInBytes(void); + static uint32_t calculateSizeInBytes(uint32_t uSideLength); + + VoxelType* m_tData; + uint16_t m_uSideLength; + uint8_t m_uSideLengthPower; + Pager* m_pPager; + + // Note: Do we really need to store this position here as well as in the block maps? + Vector3DInt32 m_v3dChunkSpacePosition; + }; + + /** + * Users can override this class and provide an instance of the derived class to the PagedVolume constructor. This derived class + * could then perform tasks such as compression and decompression of the data, and read/writing it to a file, database, network, + * or other storage as appropriate. See FilePager for a simple example of such a derived class. + */ + class Pager + { + public: + /// Constructor + Pager() {}; + /// Destructor + virtual ~Pager() {}; + + virtual void pageIn(const Region& region, Chunk* pChunk) = 0; + virtual void pageOut(const Region& region, Chunk* pChunk) = 0; + }; + + //There seems to be some descrepency between Visual Studio and GCC about how the following class should be declared. + //There is a work around (see also See http://goo.gl/qu1wn) given below which appears to work on VS2010 and GCC, but + //which seems to cause internal compiler errors on VS2008 when building with the /Gm 'Enable Minimal Rebuild' compiler + //option. For now it seems best to 'fix' it with the preprocessor insstead, but maybe the workaround can be reinstated + //in the future + //typedef Volume VolumeOfVoxelType; //Workaround for GCC/VS2010 differences. + //class Sampler : public VolumeOfVoxelType::template Sampler< PagedVolume > +#ifndef SWIG +#if defined(_MSC_VER) + class Sampler : public BaseVolume::Sampler< PagedVolume > //This line works on VS2010 +#else + class Sampler : public BaseVolume::template Sampler< PagedVolume > //This line works on GCC +#endif + { + public: + Sampler(PagedVolume* volume); + ~Sampler(); + + inline VoxelType getVoxel(void) const; + + void setPosition(const Vector3DInt32& v3dNewPos); + void setPosition(int32_t xPos, int32_t yPos, int32_t zPos); + inline bool setVoxel(VoxelType tValue); + + void movePositiveX(void); + void movePositiveY(void); + void movePositiveZ(void); + + void moveNegativeX(void); + void moveNegativeY(void); + void moveNegativeZ(void); + + inline VoxelType peekVoxel1nx1ny1nz(void) const; + inline VoxelType peekVoxel1nx1ny0pz(void) const; + inline VoxelType peekVoxel1nx1ny1pz(void) const; + inline VoxelType peekVoxel1nx0py1nz(void) const; + inline VoxelType peekVoxel1nx0py0pz(void) const; + inline VoxelType peekVoxel1nx0py1pz(void) const; + inline VoxelType peekVoxel1nx1py1nz(void) const; + inline VoxelType peekVoxel1nx1py0pz(void) const; + inline VoxelType peekVoxel1nx1py1pz(void) const; + + inline VoxelType peekVoxel0px1ny1nz(void) const; + inline VoxelType peekVoxel0px1ny0pz(void) const; + inline VoxelType peekVoxel0px1ny1pz(void) const; + inline VoxelType peekVoxel0px0py1nz(void) const; + inline VoxelType peekVoxel0px0py0pz(void) const; + inline VoxelType peekVoxel0px0py1pz(void) const; + inline VoxelType peekVoxel0px1py1nz(void) const; + inline VoxelType peekVoxel0px1py0pz(void) const; + inline VoxelType peekVoxel0px1py1pz(void) const; + + inline VoxelType peekVoxel1px1ny1nz(void) const; + inline VoxelType peekVoxel1px1ny0pz(void) const; + inline VoxelType peekVoxel1px1ny1pz(void) const; + inline VoxelType peekVoxel1px0py1nz(void) const; + inline VoxelType peekVoxel1px0py0pz(void) const; + inline VoxelType peekVoxel1px0py1pz(void) const; + inline VoxelType peekVoxel1px1py1nz(void) const; + inline VoxelType peekVoxel1px1py0pz(void) const; + inline VoxelType peekVoxel1px1py1pz(void) const; + + private: + //Other current position information + VoxelType* mCurrentVoxel; + + uint16_t m_uXPosInChunk; + uint16_t m_uYPosInChunk; + uint16_t m_uZPosInChunk; + + // This should ideally be const, but that prevent automatic generation of an assignment operator (https://goo.gl/Sn7KpZ). + // We could provide one manually, but it's currently unused so there is no real test for if it works. I'm putting + // together a new release at the moment so I'd rathern not make 'risky' changes. + uint16_t m_uChunkSideLengthMinusOne; + }; + +#endif // SWIG + + public: + /// Constructor for creating a fixed size volume. + PagedVolume(Pager* pPager, uint32_t uTargetMemoryUsageInBytes = 256 * 1024 * 1024, uint16_t uChunkSideLength = 32); + /// Destructor + ~PagedVolume(); + + /// Gets a voxel at the position given by x,y,z coordinates + VoxelType getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos) const; + /// Gets a voxel at the position given by a 3D vector + VoxelType getVoxel(const Vector3DInt32& v3dPos) const; + + /// Sets the voxel at the position given by x,y,z coordinates + void setVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue); + /// Sets the voxel at the position given by a 3D vector + void setVoxel(const Vector3DInt32& v3dPos, VoxelType tValue); + + /// Tries to ensure that the voxels within the specified Region are loaded into memory. + void prefetch(Region regPrefetch); + /// Removes all voxels from memory + void flushAll(); + + /// Calculates approximatly how many bytes of memory the volume is currently using. + uint32_t calculateSizeInBytes(void); + + protected: + /// Copy constructor + PagedVolume(const PagedVolume& rhs); + + /// Assignment operator + PagedVolume& operator=(const PagedVolume& rhs); + + private: + bool canReuseLastAccessedChunk(int32_t iChunkX, int32_t iChunkY, int32_t iChunkZ) const; + Chunk* getChunk(int32_t uChunkX, int32_t uChunkY, int32_t uChunkZ) const; + + // Storing these properties individually has proved to be faster than keeping + // them in a Vector3DInt32 as it avoids constructions and comparison overheads. + // They are also at the start of the class in the hope that they will be pulled + // into cache - I've got no idea if this actually makes a difference. + mutable int32_t m_v3dLastAccessedChunkX = 0; + mutable int32_t m_v3dLastAccessedChunkY = 0; + mutable int32_t m_v3dLastAccessedChunkZ = 0; + mutable Chunk* m_pLastAccessedChunk = nullptr; + + mutable uint32_t m_uTimestamper = 0; + + uint32_t m_uChunkCountLimit = 0; + + // Chunks are stored in the following array which is used as a hash-table. Conventional wisdom is that such a hash-table + // should not be more than half full to avoid conflicts, and a practical chunk size seems to be 64^3. With this configuration + // there can be up to 32768*64^3 = 8 gigavoxels (with each voxel perhaps being many bytes). This should effectively make use + // of even high end machines. Of course, the user can choose to limit the memory usage in which case much less of the chunk + // array will actually be used. None-the-less, we have chosen to use a fixed size array (rather than a vector) as it appears to + // be slightly faster (probably due to the extra pointer indirection in a vector?) and the actual size of this array should + // just be 1Mb or so. + static const uint32_t uChunkArraySize = 65536; + mutable std::unique_ptr< Chunk > m_arrayChunks[uChunkArraySize]; + + // The size of the chunks + uint16_t m_uChunkSideLength; + uint8_t m_uChunkSideLengthPower; + int32_t m_iChunkMask; + + Pager* m_pPager = nullptr; + }; +} + +#include "PagedVolume.inl" +#include "PagedVolumeChunk.inl" +#include "PagedVolumeSampler.inl" + +#endif //__PolyVox_PagedVolume_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolume.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolume.inl new file mode 100644 index 0000000..45247ca --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolume.inl @@ -0,0 +1,362 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/ErrorHandling.h" + +#include +#include + +namespace PolyVox +{ + //////////////////////////////////////////////////////////////////////////////// + /// This constructor creates a volume with a fixed size which is specified as a parameter. By default this constructor will not enable paging but you can override this if desired. If you do wish to enable paging then you are required to provide the call back function (see the other PagedVolume constructor). + /// \param pPager Called by PolyVox to load and unload data on demand. + /// \param uTargetMemoryUsageInBytes The upper limit to how much memory this PagedVolume should aim to use. + /// \param uChunkSideLength The size of the chunks making up the volume. Small chunks will compress/decompress faster, but there will also be more of them meaning voxel access could be slower. + //////////////////////////////////////////////////////////////////////////////// + template + PagedVolume::PagedVolume(Pager* pPager, uint32_t uTargetMemoryUsageInBytes, uint16_t uChunkSideLength) + :BaseVolume() + , m_uChunkSideLength(uChunkSideLength) + , m_pPager(pPager) + { + // Validation of parameters + POLYVOX_THROW_IF(!pPager, std::invalid_argument, "You must provide a valid pager when constructing a PagedVolume"); + POLYVOX_THROW_IF(uTargetMemoryUsageInBytes < 1 * 1024 * 1024, std::invalid_argument, "Target memory usage is too small to be practical"); + POLYVOX_THROW_IF(m_uChunkSideLength == 0, std::invalid_argument, "Chunk side length cannot be zero."); + POLYVOX_THROW_IF(m_uChunkSideLength > 256, std::invalid_argument, "Chunk size is too large to be practical."); + POLYVOX_THROW_IF(!isPowerOf2(m_uChunkSideLength), std::invalid_argument, "Chunk side length must be a power of two."); + + // Used to perform multiplications and divisions by bit shifting. + m_uChunkSideLengthPower = logBase2(m_uChunkSideLength); + // Use to perform modulo by bit operations + m_iChunkMask = m_uChunkSideLength - 1; + + // Calculate the number of chunks based on the memory limit and the size of each chunk. + uint32_t uChunkSizeInBytes = PagedVolume::Chunk::calculateSizeInBytes(m_uChunkSideLength); + m_uChunkCountLimit = uTargetMemoryUsageInBytes / uChunkSizeInBytes; + + // Enforce sensible limits on the number of chunks. + const uint32_t uMinPracticalNoOfChunks = 32; // Enough to make sure a chunks and it's neighbours can be loaded, with a few to spare. + const uint32_t uMaxPracticalNoOfChunks = uChunkArraySize / 2; // A hash table should only become half-full to avoid too many clashes. + POLYVOX_LOG_WARNING_IF(m_uChunkCountLimit < uMinPracticalNoOfChunks, "Requested memory usage limit of ", + uTargetMemoryUsageInBytes / (1024 * 1024), "Mb is too low and cannot be adhered to."); + m_uChunkCountLimit = (std::max)(m_uChunkCountLimit, uMinPracticalNoOfChunks); + m_uChunkCountLimit = (std::min)(m_uChunkCountLimit, uMaxPracticalNoOfChunks); + + // Inform the user about the chosen memory configuration. + POLYVOX_LOG_DEBUG("Memory usage limit for volume now set to ", (m_uChunkCountLimit * uChunkSizeInBytes) / (1024 * 1024), + "Mb (", m_uChunkCountLimit, " chunks of ", uChunkSizeInBytes / 1024, "Kb each)."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should never be called. Copying volumes by value would be expensive, and we want to prevent users from doing + /// it by accident (such as when passing them as paramenters to functions). That said, there are times when you really do want to + /// make a copy of a volume and in this case you should look at the VolumeResampler. + /// + /// \sa VolumeResampler + //////////////////////////////////////////////////////////////////////////////// + template + PagedVolume::PagedVolume(const PagedVolume& /*rhs*/) + { + POLYVOX_THROW(not_implemented, "Volume copy constructor not implemented to prevent accidental copying."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// Destroys the volume The destructor will call flushAll() to ensure that a paging volume has the chance to save it's data via the dataOverflowHandler() if desired. + //////////////////////////////////////////////////////////////////////////////// + template + PagedVolume::~PagedVolume() + { + flushAll(); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should never be called. Copying volumes by value would be expensive, and we want to prevent users from doing + /// it by accident (such as when passing them as paramenters to functions). That said, there are times when you really do want to + /// make a copy of a volume and in this case you should look at the Volumeresampler. + /// + /// \sa VolumeResampler + //////////////////////////////////////////////////////////////////////////////// + template + PagedVolume& PagedVolume::operator=(const PagedVolume& /*rhs*/) + { + POLYVOX_THROW(not_implemented, "Volume assignment operator not implemented to prevent accidental copying."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This version of the function is provided so that the wrap mode does not need + /// to be specified as a template parameter, as it may be confusing to some users. + /// \param uXPos The \c x position of the voxel + /// \param uYPos The \c y position of the voxel + /// \param uZPos The \c z position of the voxel + /// \return The voxel value + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType PagedVolume::getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos) const + { + const int32_t chunkX = uXPos >> m_uChunkSideLengthPower; + const int32_t chunkY = uYPos >> m_uChunkSideLengthPower; + const int32_t chunkZ = uZPos >> m_uChunkSideLengthPower; + + const uint16_t xOffset = static_cast(uXPos & m_iChunkMask); + const uint16_t yOffset = static_cast(uYPos & m_iChunkMask); + const uint16_t zOffset = static_cast(uZPos & m_iChunkMask); + + auto pChunk = canReuseLastAccessedChunk(chunkX, chunkY, chunkZ) ? m_pLastAccessedChunk : getChunk(chunkX, chunkY, chunkZ); + + return pChunk->getVoxel(xOffset, yOffset, zOffset); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This version of the function is provided so that the wrap mode does not need + /// to be specified as a template parameter, as it may be confusing to some users. + /// \param v3dPos The 3D position of the voxel + /// \return The voxel value + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType PagedVolume::getVoxel(const Vector3DInt32& v3dPos) const + { + return getVoxel(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ()); + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param uXPos the \c x position of the voxel + /// \param uYPos the \c y position of the voxel + /// \param uZPos the \c z position of the voxel + //////////////////////////////////////////////////////////////////////////////// + template + void PagedVolume::setVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue) + { + const int32_t chunkX = uXPos >> m_uChunkSideLengthPower; + const int32_t chunkY = uYPos >> m_uChunkSideLengthPower; + const int32_t chunkZ = uZPos >> m_uChunkSideLengthPower; + + const uint16_t xOffset = static_cast(uXPos - (chunkX << m_uChunkSideLengthPower)); + const uint16_t yOffset = static_cast(uYPos - (chunkY << m_uChunkSideLengthPower)); + const uint16_t zOffset = static_cast(uZPos - (chunkZ << m_uChunkSideLengthPower)); + + auto pChunk = canReuseLastAccessedChunk(chunkX, chunkY, chunkZ) ? m_pLastAccessedChunk : getChunk(chunkX, chunkY, chunkZ); + + pChunk->setVoxel(xOffset, yOffset, zOffset, tValue); + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param v3dPos the 3D position of the voxel + /// \param tValue the value to which the voxel will be set + //////////////////////////////////////////////////////////////////////////////// + template + void PagedVolume::setVoxel(const Vector3DInt32& v3dPos, VoxelType tValue) + { + setVoxel(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ(), tValue); + } + + //////////////////////////////////////////////////////////////////////////////// + /// Note that if the memory usage limit is not large enough to support the region this function will only load part of the region. In this case it is undefined which parts will actually be loaded. If all the voxels in the given region are already loaded, this function will not do anything. Other voxels might be unloaded to make space for the new voxels. + /// \param regPrefetch The Region of voxels to prefetch into memory. + //////////////////////////////////////////////////////////////////////////////// + template + void PagedVolume::prefetch(Region regPrefetch) + { + // Convert the start and end positions into chunk space coordinates + Vector3DInt32 v3dStart; + for (int i = 0; i < 3; i++) + { + v3dStart.setElement(i, regPrefetch.getLowerCorner().getElement(i) >> m_uChunkSideLengthPower); + } + + Vector3DInt32 v3dEnd; + for (int i = 0; i < 3; i++) + { + v3dEnd.setElement(i, regPrefetch.getUpperCorner().getElement(i) >> m_uChunkSideLengthPower); + } + + // Ensure we don't page in more chunks than the volume can hold. + Region region(v3dStart, v3dEnd); + uint32_t uNoOfChunks = static_cast(region.getWidthInVoxels() * region.getHeightInVoxels() * region.getDepthInVoxels()); + POLYVOX_LOG_WARNING_IF(uNoOfChunks > m_uChunkCountLimit, "Attempting to prefetch more than the maximum number of chunks (this will cause thrashing)."); + uNoOfChunks = (std::min)(uNoOfChunks, m_uChunkCountLimit); + + // Loops over the specified positions and touch the corresponding chunks. + for (int32_t x = v3dStart.getX(); x <= v3dEnd.getX(); x++) + { + for (int32_t y = v3dStart.getY(); y <= v3dEnd.getY(); y++) + { + for (int32_t z = v3dStart.getZ(); z <= v3dEnd.getZ(); z++) + { + getChunk(x, y, z); + } + } + } + } + + //////////////////////////////////////////////////////////////////////////////// + /// Removes all voxels from memory, and calls dataOverflowHandler() to ensure the application has a chance to store the data. + //////////////////////////////////////////////////////////////////////////////// + template + void PagedVolume::flushAll() + { + // Clear this pointer as all chunks are about to be removed. + m_pLastAccessedChunk = nullptr; + + // Erase all the most recently used chunks. + for (uint32_t uIndex = 0; uIndex < uChunkArraySize; uIndex++) + { + m_arrayChunks[uIndex] = nullptr; + } + } + + template + bool PagedVolume::canReuseLastAccessedChunk(int32_t iChunkX, int32_t iChunkY, int32_t iChunkZ) const + { + return ((iChunkX == m_v3dLastAccessedChunkX) && + (iChunkY == m_v3dLastAccessedChunkY) && + (iChunkZ == m_v3dLastAccessedChunkZ) && + (m_pLastAccessedChunk)); + } + + template + typename PagedVolume::Chunk* PagedVolume::getChunk(int32_t uChunkX, int32_t uChunkY, int32_t uChunkZ) const + { + Chunk* pChunk = nullptr; + + // We generate a 16-bit hash here and assume this matches the range available in the chunk + // array. The assert here is just to make sure we take care if change this in the future. + static_assert(uChunkArraySize == 65536, "Chunk array size has changed, check if the hash calculation needs updating."); + // Extract the lower five bits from each position component. + const uint32_t uChunkXLowerBits = static_cast(uChunkX & 0x1F); + const uint32_t uChunkYLowerBits = static_cast(uChunkY & 0x1F); + const uint32_t uChunkZLowerBits = static_cast(uChunkZ & 0x1F); + // Combine then to form a 15-bit hash of the position. Also shift by one to spread the values out in the whole 16-bit space. + const uint32_t iPosisionHash = (((uChunkXLowerBits)) | ((uChunkYLowerBits) << 5) | ((uChunkZLowerBits) << 10) << 1); + + // Starting at the position indicated by the hash, and then search through the whole array looking for a chunk with the correct + // position. In most cases we expect to find it in the first place we look. Note that this algorithm is slow in the case that + // the chunk is not found because the whole array has to be searched, but in this case we are going to have to page the data in + // from an external source which is likely to be slow anyway. + uint32_t iIndex = iPosisionHash; + do + { + if (m_arrayChunks[iIndex]) + { + Vector3DInt32& entryPos = m_arrayChunks[iIndex]->m_v3dChunkSpacePosition; + if (entryPos.getX() == uChunkX && entryPos.getY() == uChunkY && entryPos.getZ() == uChunkZ) + { + pChunk = m_arrayChunks[iIndex].get(); + pChunk->m_uChunkLastAccessed = ++m_uTimestamper; + break; + } + } + + iIndex++; + iIndex %= uChunkArraySize; + } while (iIndex != iPosisionHash); // Keep searching until we get back to our start position. + + // If we still haven't found the chunk then it's time to create a new one and page it in from disk. + if (!pChunk) + { + // The chunk was not found so we will create a new one. + Vector3DInt32 v3dChunkPos(uChunkX, uChunkY, uChunkZ); + pChunk = new PagedVolume::Chunk(v3dChunkPos, m_uChunkSideLength, m_pPager); + pChunk->m_uChunkLastAccessed = ++m_uTimestamper; // Important, as we may soon delete the oldest chunk + + // Store the chunk at the appropriate place in out chunk array. Ideally this place is + // given by the hash, otherwise we do a linear search for the next available location + // We always expect to find a free place because we aim to keep the array only half full. + uint32_t iIndex = iPosisionHash; + bool bInsertedSucessfully = false; + do + { + if (m_arrayChunks[iIndex] == nullptr) + { + m_arrayChunks[iIndex] = std::move(std::unique_ptr< Chunk >(pChunk)); + bInsertedSucessfully = true; + break; + } + + iIndex++; + iIndex %= uChunkArraySize; + } while (iIndex != iPosisionHash); // Keep searching until we get back to our start position. + + // This should never really happen unless we are failing to keep our number of active chunks + // significantly under the target amount. Perhaps if chunks are 'pinned' for threading purposes? + POLYVOX_THROW_IF(!bInsertedSucessfully, std::logic_error, "No space in chunk array for new chunk."); + + // As we have added a chunk we may have exceeded our target chunk limit. Search through the array to + // determine how many chunks we have, as well as finding the oldest timestamp. Note that this is potentially + // wasteful and we may instead wish to track how many chunks we have and/or delete a chunk at random (or + // just check e.g. 10 and delete the oldest of those) but we'll see if this is a bottleneck first. Paging + // the data in is probably more expensive. + uint32_t uChunkCount = 0; + uint32_t uOldestChunkIndex = 0; + uint32_t uOldestChunkTimestamp = std::numeric_limits::max(); + for (uint32_t uIndex = 0; uIndex < uChunkArraySize; uIndex++) + { + if (m_arrayChunks[uIndex]) + { + uChunkCount++; + if (m_arrayChunks[uIndex]->m_uChunkLastAccessed < uOldestChunkTimestamp) + { + uOldestChunkTimestamp = m_arrayChunks[uIndex]->m_uChunkLastAccessed; + uOldestChunkIndex = uIndex; + } + } + } + + // Check if we have too many chunks, and delete the oldest if so. + if (uChunkCount > m_uChunkCountLimit) + { + m_arrayChunks[uOldestChunkIndex] = nullptr; + } + } + + m_pLastAccessedChunk = pChunk; + m_v3dLastAccessedChunkX = uChunkX; + m_v3dLastAccessedChunkY = uChunkY; + m_v3dLastAccessedChunkZ = uChunkZ; + + return pChunk; + } + + //////////////////////////////////////////////////////////////////////////////// + /// Calculate the memory usage of the volume. + //////////////////////////////////////////////////////////////////////////////// + template + uint32_t PagedVolume::calculateSizeInBytes(void) + { + uint32_t uChunkCount = 0; + for (uint32_t uIndex = 0; uIndex < uChunkArraySize; uIndex++) + { + if (m_arrayChunks[uIndex]) + { + uChunkCount++; + } + } + + // Note: We disregard the size of the other class members as they are likely to be very small compared to the size of the + // allocated voxel data. This also keeps the reported size as a power of two, which makes other memory calculations easier. + return PagedVolume::Chunk::calculateSizeInBytes(m_uChunkSideLength) * uChunkCount; + } +} + diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolumeChunk.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolumeChunk.inl new file mode 100644 index 0000000..d11ee30 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolumeChunk.inl @@ -0,0 +1,217 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/Morton.h" +#include "Impl/Utility.h" + +namespace PolyVox +{ + template + PagedVolume::Chunk::Chunk(Vector3DInt32 v3dPosition, uint16_t uSideLength, Pager* pPager) + :m_uChunkLastAccessed(0) + , m_bDataModified(true) + , m_tData(0) + , m_uSideLength(0) + , m_uSideLengthPower(0) + , m_pPager(pPager) + , m_v3dChunkSpacePosition(v3dPosition) + { + POLYVOX_ASSERT(m_pPager, "No valid pager supplied to chunk constructor."); + POLYVOX_ASSERT(uSideLength <= 256, "Chunk side length cannot be greater than 256."); + + // Compute the side length + m_uSideLength = uSideLength; + m_uSideLengthPower = logBase2(uSideLength); + + // Allocate the data + const uint32_t uNoOfVoxels = m_uSideLength * m_uSideLength * m_uSideLength; + m_tData = new VoxelType[uNoOfVoxels]; + + // Pass the chunk to the Pager to give it a chance to initialise it with any data + // From the coordinates of the chunk we deduce the coordinates of the contained voxels. + Vector3DInt32 v3dLower = m_v3dChunkSpacePosition * static_cast(m_uSideLength); + Vector3DInt32 v3dUpper = v3dLower + Vector3DInt32(m_uSideLength - 1, m_uSideLength - 1, m_uSideLength - 1); + Region reg(v3dLower, v3dUpper); + + // A valid pager is normally present - this check is mostly to ease unit testing. + if (m_pPager) + { + // Page the data in + m_pPager->pageIn(reg, this); + } + + // We'll use this later to decide if data needs to be paged out again. + m_bDataModified = false; + } + + template + PagedVolume::Chunk::~Chunk() + { + if (m_bDataModified && m_pPager) + { + // From the coordinates of the chunk we deduce the coordinates of the contained voxels. + Vector3DInt32 v3dLower = m_v3dChunkSpacePosition * static_cast(m_uSideLength); + Vector3DInt32 v3dUpper = v3dLower + Vector3DInt32(m_uSideLength - 1, m_uSideLength - 1, m_uSideLength - 1); + + // Page the data out + m_pPager->pageOut(Region(v3dLower, v3dUpper), this); + } + + delete[] m_tData; + m_tData = 0; + } + + template + VoxelType* PagedVolume::Chunk::getData(void) const + { + return m_tData; + } + + template + uint32_t PagedVolume::Chunk::getDataSizeInBytes(void) const + { + return m_uSideLength * m_uSideLength * m_uSideLength * sizeof(VoxelType); + } + + template + VoxelType PagedVolume::Chunk::getVoxel(uint32_t uXPos, uint32_t uYPos, uint32_t uZPos) const + { + // This code is not usually expected to be called by the user, with the exception of when implementing paging + // of uncompressed data. It's a performance critical code path so we use asserts rather than exceptions. + POLYVOX_ASSERT(uXPos < m_uSideLength, "Supplied position is outside of the chunk"); + POLYVOX_ASSERT(uYPos < m_uSideLength, "Supplied position is outside of the chunk"); + POLYVOX_ASSERT(uZPos < m_uSideLength, "Supplied position is outside of the chunk"); + POLYVOX_ASSERT(m_tData, "No uncompressed data - chunk must be decompressed before accessing voxels."); + + uint32_t index = morton256_x[uXPos] | morton256_y[uYPos] | morton256_z[uZPos]; + + return m_tData[index]; + } + + template + VoxelType PagedVolume::Chunk::getVoxel(const Vector3DUint16& v3dPos) const + { + return getVoxel(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ()); + } + + template + void PagedVolume::Chunk::setVoxel(uint32_t uXPos, uint32_t uYPos, uint32_t uZPos, VoxelType tValue) + { + // This code is not usually expected to be called by the user, with the exception of when implementing paging + // of uncompressed data. It's a performance critical code path so we use asserts rather than exceptions. + POLYVOX_ASSERT(uXPos < m_uSideLength, "Supplied position is outside of the chunk"); + POLYVOX_ASSERT(uYPos < m_uSideLength, "Supplied position is outside of the chunk"); + POLYVOX_ASSERT(uZPos < m_uSideLength, "Supplied position is outside of the chunk"); + POLYVOX_ASSERT(m_tData, "No uncompressed data - chunk must be decompressed before accessing voxels."); + + uint32_t index = morton256_x[uXPos] | morton256_y[uYPos] | morton256_z[uZPos]; + + m_tData[index] = tValue; + + this->m_bDataModified = true; + } + + template + void PagedVolume::Chunk::setVoxel(const Vector3DUint16& v3dPos, VoxelType tValue) + { + setVoxel(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ(), tValue); + } + + template + uint32_t PagedVolume::Chunk::calculateSizeInBytes(void) + { + // Call through to the static version + return calculateSizeInBytes(m_uSideLength); + } + + template + uint32_t PagedVolume::Chunk::calculateSizeInBytes(uint32_t uSideLength) + { + // Note: We disregard the size of the other class members as they are likely to be very small compared to the size of the + // allocated voxel data. This also keeps the reported size as a power of two, which makes other memory calculations easier. + uint32_t uSizeInBytes = uSideLength * uSideLength * uSideLength * sizeof(VoxelType); + return uSizeInBytes; + } + + // This convienience function exists for historical reasons. Chunks used to store their data in 'linear' order but now we + // use Morton encoding. Users who still have data in linear order (on disk, in databases, etc) will need to call this function + // if they load the data in by memcpy()ing it via the raw pointer. On the other hand, if they set the data using setVoxel() + // then the ordering is automatically handled correctly. + template + void PagedVolume::Chunk::changeLinearOrderingToMorton(void) + { + VoxelType* pTempBuffer = new VoxelType[m_uSideLength * m_uSideLength * m_uSideLength]; + + // We should prehaps restructure this loop. From: https://fgiesen.wordpress.com/2011/01/17/texture-tiling-and-swizzling/ + // + // "There's two basic ways to structure the actual swizzling: either you go through the (linear) source image in linear order, + // writing in (somewhat) random order, or you iterate over the output data, picking the right source pixel for each target + // location. The former is more natural, especially when updating subrects of the destination texture (the source pixels still + // consist of one linear sequence of bytes per line; the pattern of destination addresses written is considerably more + // complicated), but the latter is usually much faster, especially if the source image data is in cached memory while the output + // data resides in non-cached write-combined memory where non-sequential writes are expensive." + // + // This is something to consider if profiling identifies it as a hotspot. + for (uint16_t z = 0; z < m_uSideLength; z++) + { + for (uint16_t y = 0; y < m_uSideLength; y++) + { + for (uint16_t x = 0; x < m_uSideLength; x++) + { + uint32_t uLinearIndex = x + y * m_uSideLength + z * m_uSideLength * m_uSideLength; + uint32_t uMortonIndex = morton256_x[x] | morton256_y[y] | morton256_z[z]; + pTempBuffer[uMortonIndex] = m_tData[uLinearIndex]; + } + } + } + + std::memcpy(m_tData, pTempBuffer, getDataSizeInBytes()); + + delete[] pTempBuffer; + } + + // Like the above function, this is provided fot easing backwards compatibility. In Cubiquity we have some + // old databases which use linear ordering, and we need to continue to save such data in linear order. + template + void PagedVolume::Chunk::changeMortonOrderingToLinear(void) + { + VoxelType* pTempBuffer = new VoxelType[m_uSideLength * m_uSideLength * m_uSideLength]; + for (uint16_t z = 0; z < m_uSideLength; z++) + { + for (uint16_t y = 0; y < m_uSideLength; y++) + { + for (uint16_t x = 0; x < m_uSideLength; x++) + { + uint32_t uLinearIndex = x + y * m_uSideLength + z * m_uSideLength * m_uSideLength; + uint32_t uMortonIndex = morton256_x[x] | morton256_y[y] | morton256_z[z]; + pTempBuffer[uLinearIndex] = m_tData[uMortonIndex]; + } + } + } + + std::memcpy(m_tData, pTempBuffer, getDataSizeInBytes()); + + delete[] pTempBuffer; + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolumeSampler.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolumeSampler.inl new file mode 100644 index 0000000..c910da9 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/PagedVolumeSampler.inl @@ -0,0 +1,506 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include + +#define CAN_GO_NEG_X(val) (val > 0) +#define CAN_GO_POS_X(val) (val < this->m_uChunkSideLengthMinusOne) +#define CAN_GO_NEG_Y(val) (val > 0) +#define CAN_GO_POS_Y(val) (val < this->m_uChunkSideLengthMinusOne) +#define CAN_GO_NEG_Z(val) (val > 0) +#define CAN_GO_POS_Z(val) (val < this->m_uChunkSideLengthMinusOne) + +#define NEG_X_DELTA (-(deltaX[this->m_uXPosInChunk-1])) +#define POS_X_DELTA (deltaX[this->m_uXPosInChunk]) +#define NEG_Y_DELTA (-(deltaY[this->m_uYPosInChunk-1])) +#define POS_Y_DELTA (deltaY[this->m_uYPosInChunk]) +#define NEG_Z_DELTA (-(deltaZ[this->m_uZPosInChunk-1])) +#define POS_Z_DELTA (deltaZ[this->m_uZPosInChunk]) + +namespace PolyVox +{ + // These precomputed offset are used to determine how much we move our pointer by to move a single voxel in the x, y, or z direction given an x, y, or z starting position inside a chunk. + // More information in this discussion: https://bitbucket.org/volumesoffun/polyvox/issue/61/experiment-with-morton-ordering-of-voxel + static const std::array deltaX = { 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 28087, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 224695, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 28087, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 1797559, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 28087, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 224695, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 28087, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1, 3511, 1, 7, 1, 55, 1, 7, 1, 439, 1, 7, 1, 55, 1, 7, 1 }; + static const std::array deltaY = { 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 56174, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 449390, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 56174, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 3595118, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 56174, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 449390, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 56174, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2, 7022, 2, 14, 2, 110, 2, 14, 2, 878, 2, 14, 2, 110, 2, 14, 2 }; + static const std::array deltaZ = { 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 112348, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 898780, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 112348, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 7190236, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 112348, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 898780, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 112348, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4, 14044, 4, 28, 4, 220, 4, 28, 4, 1756, 4, 28, 4, 220, 4, 28, 4 }; + + template + PagedVolume::Sampler::Sampler(PagedVolume* volume) + :BaseVolume::template Sampler< PagedVolume >(volume), m_uChunkSideLengthMinusOne(volume->m_uChunkSideLength - 1) + { + } + + template + PagedVolume::Sampler::~Sampler() + { + } + + template + VoxelType PagedVolume::Sampler::getVoxel(void) const + { + return *mCurrentVoxel; + } + + template + void PagedVolume::Sampler::setPosition(const Vector3DInt32& v3dNewPos) + { + setPosition(v3dNewPos.getX(), v3dNewPos.getY(), v3dNewPos.getZ()); + } + + template + void PagedVolume::Sampler::setPosition(int32_t xPos, int32_t yPos, int32_t zPos) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::setPosition(xPos, yPos, zPos); + + // Then we update the voxel pointer + const int32_t uXChunk = this->mXPosInVolume >> this->mVolume->m_uChunkSideLengthPower; + const int32_t uYChunk = this->mYPosInVolume >> this->mVolume->m_uChunkSideLengthPower; + const int32_t uZChunk = this->mZPosInVolume >> this->mVolume->m_uChunkSideLengthPower; + + m_uXPosInChunk = static_cast(this->mXPosInVolume - (uXChunk << this->mVolume->m_uChunkSideLengthPower)); + m_uYPosInChunk = static_cast(this->mYPosInVolume - (uYChunk << this->mVolume->m_uChunkSideLengthPower)); + m_uZPosInChunk = static_cast(this->mZPosInVolume - (uZChunk << this->mVolume->m_uChunkSideLengthPower)); + + uint32_t uVoxelIndexInChunk = morton256_x[m_uXPosInChunk] | morton256_y[m_uYPosInChunk] | morton256_z[m_uZPosInChunk]; + + auto pCurrentChunk = this->mVolume->canReuseLastAccessedChunk(uXChunk, uYChunk, uZChunk) ? + this->mVolume->m_pLastAccessedChunk : this->mVolume->getChunk(uXChunk, uYChunk, uZChunk); + + mCurrentVoxel = pCurrentChunk->m_tData + uVoxelIndexInChunk; + } + + template + bool PagedVolume::Sampler::setVoxel(VoxelType tValue) + { + //Need to think what effect this has on any existing iterators. + POLYVOX_THROW(not_implemented, "This function cannot be used on PagedVolume samplers."); + return false; + } + + template + void PagedVolume::Sampler::movePositiveX(void) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::movePositiveX(); + + // Then we update the voxel pointer + if (CAN_GO_POS_X(this->m_uXPosInChunk)) + { + //No need to compute new chunk. + mCurrentVoxel += POS_X_DELTA; + this->m_uXPosInChunk++; + } + else + { + //We've hit the chunk boundary. Just calling setPosition() is the easiest way to resolve this. + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void PagedVolume::Sampler::movePositiveY(void) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::movePositiveY(); + + // Then we update the voxel pointer + if (CAN_GO_POS_Y(this->m_uYPosInChunk)) + { + //No need to compute new chunk. + mCurrentVoxel += POS_Y_DELTA; + this->m_uYPosInChunk++; + } + else + { + //We've hit the chunk boundary. Just calling setPosition() is the easiest way to resolve this. + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void PagedVolume::Sampler::movePositiveZ(void) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::movePositiveZ(); + + // Then we update the voxel pointer + if (CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + //No need to compute new chunk. + mCurrentVoxel += POS_Z_DELTA; + this->m_uZPosInChunk++; + } + else + { + //We've hit the chunk boundary. Just calling setPosition() is the easiest way to resolve this. + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void PagedVolume::Sampler::moveNegativeX(void) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::moveNegativeX(); + + // Then we update the voxel pointer + if (CAN_GO_NEG_X(this->m_uXPosInChunk)) + { + //No need to compute new chunk. + mCurrentVoxel += NEG_X_DELTA; + this->m_uXPosInChunk--; + } + else + { + //We've hit the chunk boundary. Just calling setPosition() is the easiest way to resolve this. + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void PagedVolume::Sampler::moveNegativeY(void) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::moveNegativeY(); + + // Then we update the voxel pointer + if (CAN_GO_NEG_Y(this->m_uYPosInChunk)) + { + //No need to compute new chunk. + mCurrentVoxel += NEG_Y_DELTA; + this->m_uYPosInChunk--; + } + else + { + //We've hit the chunk boundary. Just calling setPosition() is the easiest way to resolve this. + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void PagedVolume::Sampler::moveNegativeZ(void) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< PagedVolume >::moveNegativeZ(); + + // Then we update the voxel pointer + if (CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + //No need to compute new chunk. + mCurrentVoxel += NEG_Z_DELTA; + this->m_uZPosInChunk--; + } + else + { + //We've hit the chunk boundary. Just calling setPosition() is the easiest way to resolve this. + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx1ny1nz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_NEG_Y(this->m_uYPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + NEG_Y_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume - 1, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx1ny0pz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_NEG_Y(this->m_uYPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + NEG_Y_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume - 1, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx1ny1pz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_NEG_Y(this->m_uYPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + NEG_Y_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume - 1, this->mZPosInVolume + 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx0py1nz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx0py0pz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx0py1pz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume, this->mZPosInVolume + 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx1py1nz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_POS_Y(this->m_uYPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + POS_Y_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume + 1, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx1py0pz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_POS_Y(this->m_uYPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + POS_Y_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume + 1, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1nx1py1pz(void) const + { + if (CAN_GO_NEG_X(this->m_uXPosInChunk) && CAN_GO_POS_Y(this->m_uYPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_X_DELTA + POS_Y_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume + 1, this->mZPosInVolume + 1); + } + + ////////////////////////////////////////////////////////////////////////// + + template + VoxelType PagedVolume::Sampler::peekVoxel0px1ny1nz(void) const + { + if (CAN_GO_NEG_Y(this->m_uYPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_Y_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume - 1, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px1ny0pz(void) const + { + if (CAN_GO_NEG_Y(this->m_uYPosInChunk)) + { + return *(mCurrentVoxel + NEG_Y_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume - 1, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px1ny1pz(void) const + { + if (CAN_GO_NEG_Y(this->m_uYPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_Y_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume - 1, this->mZPosInVolume + 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px0py1nz(void) const + { + if (CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px0py0pz(void) const + { + return *mCurrentVoxel; + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px0py1pz(void) const + { + if (CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume + 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px1py1nz(void) const + { + if (CAN_GO_POS_Y(this->m_uYPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_Y_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume + 1, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px1py0pz(void) const + { + if (CAN_GO_POS_Y(this->m_uYPosInChunk)) + { + return *(mCurrentVoxel + POS_Y_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume + 1, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel0px1py1pz(void) const + { + if (CAN_GO_POS_Y(this->m_uYPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_Y_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume + 1, this->mZPosInVolume + 1); + } + + ////////////////////////////////////////////////////////////////////////// + + template + VoxelType PagedVolume::Sampler::peekVoxel1px1ny1nz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_NEG_Y(this->m_uYPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + NEG_Y_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume - 1, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px1ny0pz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_NEG_Y(this->m_uYPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + NEG_Y_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume - 1, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px1ny1pz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_NEG_Y(this->m_uYPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + NEG_Y_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume - 1, this->mZPosInVolume + 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px0py1nz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px0py0pz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px0py1pz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume, this->mZPosInVolume + 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px1py1nz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_POS_Y(this->m_uYPosInChunk) && CAN_GO_NEG_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + POS_Y_DELTA + NEG_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume + 1, this->mZPosInVolume - 1); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px1py0pz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_POS_Y(this->m_uYPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + POS_Y_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume + 1, this->mZPosInVolume); + } + + template + VoxelType PagedVolume::Sampler::peekVoxel1px1py1pz(void) const + { + if (CAN_GO_POS_X(this->m_uXPosInChunk) && CAN_GO_POS_Y(this->m_uYPosInChunk) && CAN_GO_POS_Z(this->m_uZPosInChunk)) + { + return *(mCurrentVoxel + POS_X_DELTA + POS_Y_DELTA + POS_Z_DELTA); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume + 1, this->mZPosInVolume + 1); + } +} + +#undef CAN_GO_NEG_X +#undef CAN_GO_POS_X +#undef CAN_GO_NEG_Y +#undef CAN_GO_POS_Y +#undef CAN_GO_NEG_Z +#undef CAN_GO_POS_Z + +#undef NEG_X_DELTA +#undef POS_X_DELTA +#undef NEG_Y_DELTA +#undef POS_Y_DELTA +#undef NEG_Z_DELTA +#undef POS_Z_DELTA \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Picking.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Picking.h new file mode 100644 index 0000000..6f92a85 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Picking.h @@ -0,0 +1,50 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Picking_H__ +#define __PolyVox_Picking_H__ + +#include "Vector.h" + +namespace PolyVox +{ + /** + * A structure containing the information about a picking operation + */ + struct PickResult + { + PickResult() : didHit(false) {} + bool didHit; ///< Did the picking operation hit anything + Vector3DInt32 hitVoxel; ///< The location of the solid voxel it hit + Vector3DInt32 previousVoxel; ///< The location of the voxel before the one it hit + }; + + /// Pick the first solid voxel along a vector + template + PickResult pickVoxel(VolumeType* volData, const Vector3DFloat& v3dStart, const Vector3DFloat& v3dDirectionAndLength, const typename VolumeType::VoxelType& emptyVoxelExample); +} + +#include "Picking.inl" + +#endif //__PolyVox_Picking_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Picking.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Picking.inl new file mode 100644 index 0000000..c876d93 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Picking.inl @@ -0,0 +1,85 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Raycast.h" + +namespace PolyVox +{ + namespace + { + /** + * This is just an implementation class for the pickVoxel function + * + * It makes note of the sort of empty voxel you're looking for in the constructor. + * + * Each time the operator() is called: + * * if it's hit a voxel it sets up the result and returns false + * * otherwise it preps the result for the next iteration and returns true + */ + template + class RaycastPickingFunctor + { + public: + RaycastPickingFunctor(const typename VolumeType::VoxelType& emptyVoxelExample) + :m_emptyVoxelExample(emptyVoxelExample) + , m_result() + { + } + + bool operator()(const typename VolumeType::Sampler& sampler) + { + if (sampler.getVoxel() != m_emptyVoxelExample) //If we've hit something + { + m_result.didHit = true; + m_result.hitVoxel = sampler.getPosition(); + return false; + } + + m_result.previousVoxel = sampler.getPosition(); + + return true; + } + const typename VolumeType::VoxelType& m_emptyVoxelExample; + PickResult m_result; + }; + } + + /** + * \param volData The volume to pass the ray though + * \param v3dStart The start position in the volume + * \param v3dDirectionAndLength The direction and length of the ray + * \param emptyVoxelExample The value used to represent empty voxels in your volume + * + * \return A PickResult containing the hit information + */ + template + PickResult pickVoxel(VolumeType* volData, const Vector3DFloat& v3dStart, const Vector3DFloat& v3dDirectionAndLength, const typename VolumeType::VoxelType& emptyVoxelExample) + { + RaycastPickingFunctor functor(emptyVoxelExample); + + raycastWithDirection(volData, v3dStart, v3dDirectionAndLength, functor); + + return functor.m_result; + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolume.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolume.h new file mode 100644 index 0000000..fd7a5c4 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolume.h @@ -0,0 +1,184 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_RawVolume_H__ +#define __PolyVox_RawVolume_H__ + +#include "BaseVolume.h" +#include "Region.h" +#include "Vector.h" + +#include //For abort() +#include +#include +#include //For invalid_argument + +namespace PolyVox +{ + /** + * Simple volume implementation which stores data in a single large 3D array. + * + * This class is less memory-efficient than the PagedVolume, but it is the simplest possible + * volume implementation which makes it useful for debugging and getting started with PolyVox. + */ + template + class RawVolume : public BaseVolume + { + public: +#ifndef SWIG + //There seems to be some descrepency between Visual Studio and GCC about how the following class should be declared. + //There is a work around (see also See http://goo.gl/qu1wn) given below which appears to work on VS2010 and GCC, but + //which seems to cause internal compiler errors on VS2008 when building with the /Gm 'Enable Minimal Rebuild' compiler + //option. For now it seems best to 'fix' it with the preprocessor insstead, but maybe the workaround can be reinstated + //in the future + //typedef Volume VolumeOfVoxelType; //Workaround for GCC/VS2010 differences. + //class Sampler : public VolumeOfVoxelType::template Sampler< RawVolume > +#if defined(_MSC_VER) + class Sampler : public BaseVolume::Sampler< RawVolume > //This line works on VS2010 +#else + class Sampler : public BaseVolume::template Sampler< RawVolume > //This line works on GCC +#endif + { + public: + Sampler(RawVolume* volume); + ~Sampler(); + + inline VoxelType getVoxel(void) const; + + bool isCurrentPositionValid(void) const; + + void setPosition(const Vector3DInt32& v3dNewPos); + void setPosition(int32_t xPos, int32_t yPos, int32_t zPos); + inline bool setVoxel(VoxelType tValue); + + void movePositiveX(void); + void movePositiveY(void); + void movePositiveZ(void); + + void moveNegativeX(void); + void moveNegativeY(void); + void moveNegativeZ(void); + + inline VoxelType peekVoxel1nx1ny1nz(void) const; + inline VoxelType peekVoxel1nx1ny0pz(void) const; + inline VoxelType peekVoxel1nx1ny1pz(void) const; + inline VoxelType peekVoxel1nx0py1nz(void) const; + inline VoxelType peekVoxel1nx0py0pz(void) const; + inline VoxelType peekVoxel1nx0py1pz(void) const; + inline VoxelType peekVoxel1nx1py1nz(void) const; + inline VoxelType peekVoxel1nx1py0pz(void) const; + inline VoxelType peekVoxel1nx1py1pz(void) const; + + inline VoxelType peekVoxel0px1ny1nz(void) const; + inline VoxelType peekVoxel0px1ny0pz(void) const; + inline VoxelType peekVoxel0px1ny1pz(void) const; + inline VoxelType peekVoxel0px0py1nz(void) const; + inline VoxelType peekVoxel0px0py0pz(void) const; + inline VoxelType peekVoxel0px0py1pz(void) const; + inline VoxelType peekVoxel0px1py1nz(void) const; + inline VoxelType peekVoxel0px1py0pz(void) const; + inline VoxelType peekVoxel0px1py1pz(void) const; + + inline VoxelType peekVoxel1px1ny1nz(void) const; + inline VoxelType peekVoxel1px1ny0pz(void) const; + inline VoxelType peekVoxel1px1ny1pz(void) const; + inline VoxelType peekVoxel1px0py1nz(void) const; + inline VoxelType peekVoxel1px0py0pz(void) const; + inline VoxelType peekVoxel1px0py1pz(void) const; + inline VoxelType peekVoxel1px1py1nz(void) const; + inline VoxelType peekVoxel1px1py0pz(void) const; + inline VoxelType peekVoxel1px1py1pz(void) const; + + private: + + //Other current position information + VoxelType* mCurrentVoxel; + + //Whether the current position is inside the volume + //FIXME - Replace these with flags + bool m_bIsCurrentPositionValidInX; + bool m_bIsCurrentPositionValidInY; + bool m_bIsCurrentPositionValidInZ; + }; +#endif // SWIG + + public: + /// Constructor for creating a fixed size volume. + RawVolume(const Region& regValid); + + /// Destructor + ~RawVolume(); + + /// Gets the value used for voxels which are outside the volume + VoxelType getBorderValue(void) const; + /// Gets a Region representing the extents of the Volume. + const Region& getEnclosingRegion(void) const; + + /// Gets the width of the volume in voxels. + int32_t getWidth(void) const; + /// Gets the height of the volume in voxels. + int32_t getHeight(void) const; + /// Gets the depth of the volume in voxels. + int32_t getDepth(void) const; + + /// Gets a voxel at the position given by x,y,z coordinates + VoxelType getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos) const; + /// Gets a voxel at the position given by a 3D vector + VoxelType getVoxel(const Vector3DInt32& v3dPos) const; + + /// Sets the value used for voxels which are outside the volume + void setBorderValue(const VoxelType& tBorder); + /// Sets the voxel at the position given by x,y,z coordinates + void setVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue); + /// Sets the voxel at the position given by a 3D vector + void setVoxel(const Vector3DInt32& v3dPos, VoxelType tValue); + + /// Calculates approximatly how many bytes of memory the volume is currently using. + uint32_t calculateSizeInBytes(void); + + protected: + /// Copy constructor + RawVolume(const RawVolume& rhs); + + /// Assignment operator + RawVolume& operator=(const RawVolume& rhs); + + private: + void initialise(const Region& regValidRegion); + + //The size of the volume + Region m_regValidRegion; + + //The border value + VoxelType m_tBorderValue; + + //The voxel data + VoxelType* m_pData; + }; +} + +#include "RawVolume.inl" +#include "RawVolumeSampler.inl" + +#endif //__PolyVox_RawVolume_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolume.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolume.inl new file mode 100644 index 0000000..7f6713b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolume.inl @@ -0,0 +1,255 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + //////////////////////////////////////////////////////////////////////////////// + /// This constructor creates a volume with a fixed size which is specified as a parameter. + /// \param regValid Specifies the minimum and maximum valid voxel positions. + //////////////////////////////////////////////////////////////////////////////// + template + RawVolume::RawVolume(const Region& regValid) + :BaseVolume() + , m_regValidRegion(regValid) + , m_tBorderValue() + { + this->setBorderValue(VoxelType()); + + //Create a volume of the right size. + initialise(regValid); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should never be called. Copying volumes by value would be expensive, and we want to prevent users from doing + /// it by accident (such as when passing them as paramenters to functions). That said, there are times when you really do want to + /// make a copy of a volume and in this case you should look at the Volumeresampler. + /// + /// \sa VolumeResampler + //////////////////////////////////////////////////////////////////////////////// + template + RawVolume::RawVolume(const RawVolume& /*rhs*/) + { + POLYVOX_THROW(not_implemented, "Volume copy constructor not implemented for performance reasons."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// Destroys the volume + //////////////////////////////////////////////////////////////////////////////// + template + RawVolume::~RawVolume() + { + delete[] m_pData; + m_pData = 0; + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should never be called. Copying volumes by value would be expensive, and we want to prevent users from doing + /// it by accident (such as when passing them as paramenters to functions). That said, there are times when you really do want to + /// make a copy of a volume and in this case you should look at the Volumeresampler. + /// + /// \sa VolumeResampler + //////////////////////////////////////////////////////////////////////////////// + template + RawVolume& RawVolume::operator=(const RawVolume& /*rhs*/) + { + POLYVOX_THROW(not_implemented, "Volume assignment operator not implemented for performance reasons."); + } + + //////////////////////////////////////////////////////////////////////////////// + /// The border value is returned whenever an attempt is made to read a voxel which + /// is outside the extents of the volume. + /// \return The value used for voxels outside of the volume + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType RawVolume::getBorderValue(void) const + { + return m_tBorderValue; + } + + //////////////////////////////////////////////////////////////////////////////// + /// \return A Region representing the extent of the volume. + //////////////////////////////////////////////////////////////////////////////// + template + const Region& RawVolume::getEnclosingRegion(void) const + { + return m_regValidRegion; + } + + //////////////////////////////////////////////////////////////////////////////// + /// \return The width of the volume in voxels. Note that this value is inclusive, so that if the valid range is e.g. 0 to 63 then the width is 64. + /// \sa getHeight(), getDepth() + //////////////////////////////////////////////////////////////////////////////// + template + int32_t RawVolume::getWidth(void) const + { + return m_regValidRegion.getUpperX() - m_regValidRegion.getLowerX() + 1; + } + + //////////////////////////////////////////////////////////////////////////////// + /// \return The height of the volume in voxels. Note that this value is inclusive, so that if the valid range is e.g. 0 to 63 then the height is 64. + /// \sa getWidth(), getDepth() + //////////////////////////////////////////////////////////////////////////////// + template + int32_t RawVolume::getHeight(void) const + { + return m_regValidRegion.getUpperY() - m_regValidRegion.getLowerY() + 1; + } + + //////////////////////////////////////////////////////////////////////////////// + /// \return The depth of the volume in voxels. Note that this value is inclusive, so that if the valid range is e.g. 0 to 63 then the depth is 64. + /// \sa getWidth(), getHeight() + //////////////////////////////////////////////////////////////////////////////// + template + int32_t RawVolume::getDepth(void) const + { + return m_regValidRegion.getUpperZ() - m_regValidRegion.getLowerZ() + 1; + } + + //////////////////////////////////////////////////////////////////////////////// + /// This version of the function is provided so that the wrap mode does not need + /// to be specified as a template parameter, as it may be confusing to some users. + /// \param uXPos The \c x position of the voxel + /// \param uYPos The \c y position of the voxel + /// \param uZPos The \c z position of the voxel + /// \return The voxel value + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType RawVolume::getVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos) const + { + if (this->m_regValidRegion.containsPoint(uXPos, uYPos, uZPos)) + { + const Region& regValidRegion = this->m_regValidRegion; + int32_t iLocalXPos = uXPos - regValidRegion.getLowerX(); + int32_t iLocalYPos = uYPos - regValidRegion.getLowerY(); + int32_t iLocalZPos = uZPos - regValidRegion.getLowerZ(); + + return m_pData + [ + iLocalXPos + + iLocalYPos * this->getWidth() + + iLocalZPos * this->getWidth() * this->getHeight() + ]; + } + else + { + return m_tBorderValue; + } + } + + //////////////////////////////////////////////////////////////////////////////// + /// This version of the function is provided so that the wrap mode does not need + /// to be specified as a template parameter, as it may be confusing to some users. + /// \param v3dPos The 3D position of the voxel + /// \return The voxel value + //////////////////////////////////////////////////////////////////////////////// + template + VoxelType RawVolume::getVoxel(const Vector3DInt32& v3dPos) const + { + return getVoxel(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ()); + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param tBorder The value to use for voxels outside the volume. + //////////////////////////////////////////////////////////////////////////////// + template + void RawVolume::setBorderValue(const VoxelType& tBorder) + { + m_tBorderValue = tBorder; + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param uXPos the \c x position of the voxel + /// \param uYPos the \c y position of the voxel + /// \param uZPos the \c z position of the voxel + /// \param tValue the value to which the voxel will be set + //////////////////////////////////////////////////////////////////////////////// + template + void RawVolume::setVoxel(int32_t uXPos, int32_t uYPos, int32_t uZPos, VoxelType tValue) + { + if (this->m_regValidRegion.containsPoint(Vector3DInt32(uXPos, uYPos, uZPos)) == false) + { + POLYVOX_THROW(std::out_of_range, "Position is outside valid region"); + } + + const Vector3DInt32& v3dLowerCorner = this->m_regValidRegion.getLowerCorner(); + int32_t iLocalXPos = uXPos - v3dLowerCorner.getX(); + int32_t iLocalYPos = uYPos - v3dLowerCorner.getY(); + int32_t iLocalZPos = uZPos - v3dLowerCorner.getZ(); + + m_pData + [ + iLocalXPos + + iLocalYPos * this->getWidth() + + iLocalZPos * this->getWidth() * this->getHeight() + ] = tValue; + } + + //////////////////////////////////////////////////////////////////////////////// + /// \param v3dPos the 3D position of the voxel + /// \param tValue the value to which the voxel will be set + //////////////////////////////////////////////////////////////////////////////// + template + void RawVolume::setVoxel(const Vector3DInt32& v3dPos, VoxelType tValue) + { + setVoxel(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ(), tValue); + } + + //////////////////////////////////////////////////////////////////////////////// + /// This function should probably be made internal... + //////////////////////////////////////////////////////////////////////////////// + template + void RawVolume::initialise(const Region& regValidRegion) + { + this->m_regValidRegion = regValidRegion; + + if (this->getWidth() <= 0) + { + POLYVOX_THROW(std::invalid_argument, "Volume width must be greater than zero."); + } + if (this->getHeight() <= 0) + { + POLYVOX_THROW(std::invalid_argument, "Volume height must be greater than zero."); + } + if (this->getDepth() <= 0) + { + POLYVOX_THROW(std::invalid_argument, "Volume depth must be greater than zero."); + } + + //Create the data + m_pData = new VoxelType[this->getWidth() * this->getHeight()* this->getDepth()]; + + // Clear to zeros + std::fill(m_pData, m_pData + this->getWidth() * this->getHeight()* this->getDepth(), VoxelType()); + } + + //////////////////////////////////////////////////////////////////////////////// + /// Note: This function needs reviewing for accuracy... + //////////////////////////////////////////////////////////////////////////////// + template + uint32_t RawVolume::calculateSizeInBytes(void) + { + return this->getWidth() * this->getHeight() * this->getDepth() * sizeof(VoxelType); + } +} + diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolumeSampler.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolumeSampler.inl new file mode 100644 index 0000000..953640c --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/RawVolumeSampler.inl @@ -0,0 +1,531 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +#define CAN_GO_NEG_X(val) (val > this->mVolume->getEnclosingRegion().getLowerX()) +#define CAN_GO_POS_X(val) (val < this->mVolume->getEnclosingRegion().getUpperX()) +#define CAN_GO_NEG_Y(val) (val > this->mVolume->getEnclosingRegion().getLowerY()) +#define CAN_GO_POS_Y(val) (val < this->mVolume->getEnclosingRegion().getUpperY()) +#define CAN_GO_NEG_Z(val) (val > this->mVolume->getEnclosingRegion().getLowerZ()) +#define CAN_GO_POS_Z(val) (val < this->mVolume->getEnclosingRegion().getUpperZ()) + +namespace PolyVox +{ + template + RawVolume::Sampler::Sampler(RawVolume* volume) + :BaseVolume::template Sampler< RawVolume >(volume) + , mCurrentVoxel(0) + , m_bIsCurrentPositionValidInX(false) + , m_bIsCurrentPositionValidInY(false) + , m_bIsCurrentPositionValidInZ(false) + { + } + + template + RawVolume::Sampler::~Sampler() + { + } + + template + VoxelType RawVolume::Sampler::getVoxel(void) const + { + if (this->isCurrentPositionValid()) + { + return *mCurrentVoxel; + } + else + { + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + bool inline RawVolume::Sampler::isCurrentPositionValid(void) const + { + return m_bIsCurrentPositionValidInX && m_bIsCurrentPositionValidInY && m_bIsCurrentPositionValidInZ; + } + + template + void RawVolume::Sampler::setPosition(const Vector3DInt32& v3dNewPos) + { + setPosition(v3dNewPos.getX(), v3dNewPos.getY(), v3dNewPos.getZ()); + } + + template + void RawVolume::Sampler::setPosition(int32_t xPos, int32_t yPos, int32_t zPos) + { + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::setPosition(xPos, yPos, zPos); + + m_bIsCurrentPositionValidInX = this->mVolume->getEnclosingRegion().containsPointInX(xPos); + m_bIsCurrentPositionValidInY = this->mVolume->getEnclosingRegion().containsPointInY(yPos); + m_bIsCurrentPositionValidInZ = this->mVolume->getEnclosingRegion().containsPointInZ(zPos); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid()) + { + const Vector3DInt32& v3dLowerCorner = this->mVolume->m_regValidRegion.getLowerCorner(); + int32_t iLocalXPos = xPos - v3dLowerCorner.getX(); + int32_t iLocalYPos = yPos - v3dLowerCorner.getY(); + int32_t iLocalZPos = zPos - v3dLowerCorner.getZ(); + + const int32_t uVoxelIndex = iLocalXPos + + iLocalYPos * this->mVolume->getWidth() + + iLocalZPos * this->mVolume->getWidth() * this->mVolume->getHeight(); + + mCurrentVoxel = this->mVolume->m_pData + uVoxelIndex; + } + else + { + mCurrentVoxel = 0; + } + } + + template + bool RawVolume::Sampler::setVoxel(VoxelType tValue) + { + //return m_bIsCurrentPositionValid ? *mCurrentVoxel : this->mVolume->getBorderValue(); + if (this->m_bIsCurrentPositionValidInX && this->m_bIsCurrentPositionValidInY && this->m_bIsCurrentPositionValidInZ) + { + *mCurrentVoxel = tValue; + return true; + } + else + { + return false; + } + } + + template + void RawVolume::Sampler::movePositiveX(void) + { + // We'll need this in a moment... + bool bIsOldPositionValid = this->isCurrentPositionValid(); + + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::movePositiveX(); + + m_bIsCurrentPositionValidInX = this->mVolume->getEnclosingRegion().containsPointInX(this->mXPosInVolume); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid() && bIsOldPositionValid) + { + ++mCurrentVoxel; + } + else + { + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void RawVolume::Sampler::movePositiveY(void) + { + // We'll need this in a moment... + bool bIsOldPositionValid = this->isCurrentPositionValid(); + + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::movePositiveY(); + + m_bIsCurrentPositionValidInY = this->mVolume->getEnclosingRegion().containsPointInY(this->mYPosInVolume); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid() && bIsOldPositionValid) + { + mCurrentVoxel += this->mVolume->getWidth(); + } + else + { + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void RawVolume::Sampler::movePositiveZ(void) + { + // We'll need this in a moment... + bool bIsOldPositionValid = this->isCurrentPositionValid(); + + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::movePositiveZ(); + + m_bIsCurrentPositionValidInZ = this->mVolume->getEnclosingRegion().containsPointInZ(this->mZPosInVolume); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid() && bIsOldPositionValid) + { + mCurrentVoxel += this->mVolume->getWidth() * this->mVolume->getHeight(); + } + else + { + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void RawVolume::Sampler::moveNegativeX(void) + { + // We'll need this in a moment... + bool bIsOldPositionValid = this->isCurrentPositionValid(); + + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::moveNegativeX(); + + m_bIsCurrentPositionValidInX = this->mVolume->getEnclosingRegion().containsPointInX(this->mXPosInVolume); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid() && bIsOldPositionValid) + { + --mCurrentVoxel; + } + else + { + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void RawVolume::Sampler::moveNegativeY(void) + { + // We'll need this in a moment... + bool bIsOldPositionValid = this->isCurrentPositionValid(); + + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::moveNegativeY(); + + m_bIsCurrentPositionValidInY = this->mVolume->getEnclosingRegion().containsPointInY(this->mYPosInVolume); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid() && bIsOldPositionValid) + { + mCurrentVoxel -= this->mVolume->getWidth(); + } + else + { + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + void RawVolume::Sampler::moveNegativeZ(void) + { + // We'll need this in a moment... + bool bIsOldPositionValid = this->isCurrentPositionValid(); + + // Base version updates position and validity flags. + BaseVolume::template Sampler< RawVolume >::moveNegativeZ(); + + m_bIsCurrentPositionValidInZ = this->mVolume->getEnclosingRegion().containsPointInZ(this->mZPosInVolume); + + // Then we update the voxel pointer + if (this->isCurrentPositionValid() && bIsOldPositionValid) + { + mCurrentVoxel -= this->mVolume->getWidth() * this->mVolume->getHeight(); + } + else + { + setPosition(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx1ny1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_NEG_Y(this->mYPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - 1 - this->mVolume->getWidth() - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume - 1, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx1ny0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_NEG_Y(this->mYPosInVolume)) + { + return *(mCurrentVoxel - 1 - this->mVolume->getWidth()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume - 1, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx1ny1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_NEG_Y(this->mYPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - 1 - this->mVolume->getWidth() + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume - 1, this->mZPosInVolume + 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx0py1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - 1 - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx0py0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume)) + { + return *(mCurrentVoxel - 1); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx0py1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - 1 + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume, this->mZPosInVolume + 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx1py1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_POS_Y(this->mYPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - 1 + this->mVolume->getWidth() - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume + 1, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx1py0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_POS_Y(this->mYPosInVolume)) + { + return *(mCurrentVoxel - 1 + this->mVolume->getWidth()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume + 1, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1nx1py1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_X(this->mXPosInVolume) && CAN_GO_POS_Y(this->mYPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - 1 + this->mVolume->getWidth() + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume - 1, this->mYPosInVolume + 1, this->mZPosInVolume + 1); + } + + ////////////////////////////////////////////////////////////////////////// + + template + VoxelType RawVolume::Sampler::peekVoxel0px1ny1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_Y(this->mYPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - this->mVolume->getWidth() - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume - 1, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px1ny0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_Y(this->mYPosInVolume)) + { + return *(mCurrentVoxel - this->mVolume->getWidth()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume - 1, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px1ny1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_Y(this->mYPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - this->mVolume->getWidth() + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume - 1, this->mZPosInVolume + 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px0py1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px0py0pz(void) const + { + if ((this->isCurrentPositionValid())) + { + return *mCurrentVoxel; + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px0py1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume, this->mZPosInVolume + 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px1py1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_Y(this->mYPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + this->mVolume->getWidth() - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume + 1, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px1py0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_Y(this->mYPosInVolume)) + { + return *(mCurrentVoxel + this->mVolume->getWidth()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume + 1, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel0px1py1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_Y(this->mYPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + this->mVolume->getWidth() + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume, this->mYPosInVolume + 1, this->mZPosInVolume + 1); + } + + ////////////////////////////////////////////////////////////////////////// + + template + VoxelType RawVolume::Sampler::peekVoxel1px1ny1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_NEG_Y(this->mYPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + 1 - this->mVolume->getWidth() - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume - 1, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px1ny0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_NEG_Y(this->mYPosInVolume)) + { + return *(mCurrentVoxel + 1 - this->mVolume->getWidth()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume - 1, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px1ny1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_NEG_Y(this->mYPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + 1 - this->mVolume->getWidth() + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume - 1, this->mZPosInVolume + 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px0py1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + 1 - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px0py0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume)) + { + return *(mCurrentVoxel + 1); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px0py1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + 1 + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume, this->mZPosInVolume + 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px1py1nz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_POS_Y(this->mYPosInVolume) && CAN_GO_NEG_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + 1 + this->mVolume->getWidth() - this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume + 1, this->mZPosInVolume - 1); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px1py0pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_POS_Y(this->mYPosInVolume)) + { + return *(mCurrentVoxel + 1 + this->mVolume->getWidth()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume + 1, this->mZPosInVolume); + } + + template + VoxelType RawVolume::Sampler::peekVoxel1px1py1pz(void) const + { + if ((this->isCurrentPositionValid()) && CAN_GO_POS_X(this->mXPosInVolume) && CAN_GO_POS_Y(this->mYPosInVolume) && CAN_GO_POS_Z(this->mZPosInVolume)) + { + return *(mCurrentVoxel + 1 + this->mVolume->getWidth() + this->mVolume->getWidth() * this->mVolume->getHeight()); + } + return this->mVolume->getVoxel(this->mXPosInVolume + 1, this->mYPosInVolume + 1, this->mZPosInVolume + 1); + } +} + +#undef CAN_GO_NEG_X +#undef CAN_GO_POS_X +#undef CAN_GO_NEG_Y +#undef CAN_GO_POS_Y +#undef CAN_GO_NEG_Z +#undef CAN_GO_POS_Z diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Raycast.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Raycast.h new file mode 100644 index 0000000..e512046 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Raycast.h @@ -0,0 +1,86 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Raycast_H__ +#define __PolyVox_Raycast_H__ + +#include "Vector.h" + +namespace PolyVox +{ + namespace RaycastResults + { + /** + * The results of a raycast + */ + enum RaycastResult + { + Completed, ///< If the ray passed through the volume without being interupted + Interupted ///< If the ray was interupted while travelling + }; + } + typedef RaycastResults::RaycastResult RaycastResult; + + /// OUT OF DATE SINCE UNCLASSING + //////////////////////////////////////////////////////////////////////////////// + /// \file Raycast.h + /// + /// The principle behind raycasting is to fire a 'ray' through the volume and determine + /// what (if anything) that ray hits. This simple test can be used for the purpose of + /// picking, visibility checks, lighting calculations, or numerous other applications. + /// + /// A ray is a stright line in space define by a start point and a direction vector. + /// The length of the direction vector represents the length of the ray. When you + /// execute a raycast it will iterate over each voxel which lies on the ray, + /// starting from the defined start point. It will examine each voxel and terminate + /// either when it encounters a solid voxel or when it reaches the end of the ray. + /// + /// **Important Note:** These has been confusion in the past with people not realising + /// that the length of the direction vector is important. Most graphics API can provide + /// a camera position and view direction for picking purposes, but the view direction is + /// usually normalised (i.e. of length one). If you use this view direction directly you + /// will only iterate over a single voxel and won't find what you are looking for. Instead + /// you must scale the direction vector so that it's length represents the maximum distance + /// over which you want the ray to be cast. + /// + /// Some further notes, the Raycast uses full 26-connectivity, which basically means it + /// will examine every voxel the ray touches, even if it just passes through the corner. + /// Also, it peforms a simple binary test against a voxel's threshold, rather than making + /// use of it's density. Therefore it will work best in conjunction with one of the 'cubic' + /// surace extractors. It's behaviour with the Marching Cubes surface extractor has not + /// been tested yet. + /// + /// Note that we also have a pickVoxel() function which provides a slightly higher-level interface. + //////////////////////////////////////////////////////////////////////////////// + + template + RaycastResult raycastWithEndpoints(VolumeType* volData, const Vector3DFloat& v3dStart, const Vector3DFloat& v3dEnd, Callback& callback); + + template + RaycastResult raycastWithDirection(VolumeType* volData, const Vector3DFloat& v3dStart, const Vector3DFloat& v3dDirectionAndLength, Callback& callback); +} + +#include "Raycast.inl" + +#endif //__PolyVox_Raycast_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Raycast.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Raycast.inl new file mode 100644 index 0000000..376fb8c --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Raycast.inl @@ -0,0 +1,181 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + // This function is based on Christer Ericson's code and description of the 'Uniform Grid Intersection Test' in + // 'Real Time Collision Detection'. The following information from the errata on the book website is also relevent: + // + // pages 326-327. In the function VisitCellsOverlapped() the two lines calculating tx and ty are incorrect. + // The less-than sign in each line should be a greater-than sign. That is, the two lines should read: + // + // float tx = ((x1 > x2) ? (x1 - minx) : (maxx - x1)) / Abs(x2 - x1); + // float ty = ((y1 > y2) ? (y1 - miny) : (maxy - y1)) / Abs(y2 - y1); + // + // Thanks to Jetro Lauha of Fathammer in Helsinki, Finland for reporting this error. + // + // Jetro also points out that the computations of i, j, iend, and jend are incorrectly rounded if the line + // coordinates are allowed to go negative. While that was not really the intent of the code -- that is, I + // assumed grids to be numbered from (0, 0) to (m, n) -- I'm at fault for not making my assumption clear. + // Where it is important to handle negative line coordinates the computation of these variables should be + // changed to something like this: + // + // // Determine start grid cell coordinates (i, j) + // int i = (int)floorf(x1 / CELL_SIDE); + // int j = (int)floorf(y1 / CELL_SIDE); + // + // // Determine end grid cell coordinates (iend, jend) + // int iend = (int)floorf(x2 / CELL_SIDE); + // int jend = (int)floorf(y2 / CELL_SIDE); + // + // page 328. The if-statement that reads "if (ty <= tx && ty <= tz)" has a superfluous condition. + // It should simply read "if (ty <= tz)". + // + // This error was reported by Joey Hammer (PixelActive). + + /** + * Cast a ray through a volume by specifying the start and end positions + * + * The ray will move from \a v3dStart to \a v3dEnd, calling \a callback for each + * voxel it passes through until \a callback returns \a false. In this case it + * returns a RaycastResults::Interupted. If it passes from start to end + * without \a callback returning \a false, it returns RaycastResults::Completed. + * + * \param volData The volume to pass the ray though + * \param v3dStart The start position in the volume + * \param v3dEnd The end position in the volume + * \param callback The callback to call for each voxel + * + * \return A RaycastResults designating whether the ray hit anything or not + */ + template + RaycastResult raycastWithEndpoints(VolumeType* volData, const Vector3DFloat& v3dStart, const Vector3DFloat& v3dEnd, Callback& callback) + { + typename VolumeType::Sampler sampler(volData); + + //The doRaycast function is assuming that it is iterating over the areas defined between + //voxels. We actually want to define the areas as being centered on voxels (as this is + //what the CubicSurfaceExtractor generates). We add 0.5 here to adjust for this. + const float x1 = v3dStart.getX() + 0.5f; + const float y1 = v3dStart.getY() + 0.5f; + const float z1 = v3dStart.getZ() + 0.5f; + const float x2 = v3dEnd.getX() + 0.5f; + const float y2 = v3dEnd.getY() + 0.5f; + const float z2 = v3dEnd.getZ() + 0.5f; + + int i = (int)floorf(x1); + int j = (int)floorf(y1); + int k = (int)floorf(z1); + + const int iend = (int)floorf(x2); + const int jend = (int)floorf(y2); + const int kend = (int)floorf(z2); + + const int di = ((x1 < x2) ? 1 : ((x1 > x2) ? -1 : 0)); + const int dj = ((y1 < y2) ? 1 : ((y1 > y2) ? -1 : 0)); + const int dk = ((z1 < z2) ? 1 : ((z1 > z2) ? -1 : 0)); + + const float deltatx = 1.0f / std::abs(x2 - x1); + const float deltaty = 1.0f / std::abs(y2 - y1); + const float deltatz = 1.0f / std::abs(z2 - z1); + + const float minx = floorf(x1), maxx = minx + 1.0f; + float tx = ((x1 > x2) ? (x1 - minx) : (maxx - x1)) * deltatx; + const float miny = floorf(y1), maxy = miny + 1.0f; + float ty = ((y1 > y2) ? (y1 - miny) : (maxy - y1)) * deltaty; + const float minz = floorf(z1), maxz = minz + 1.0f; + float tz = ((z1 > z2) ? (z1 - minz) : (maxz - z1)) * deltatz; + + sampler.setPosition(i, j, k); + + for (;;) + { + if (!callback(sampler)) + { + return RaycastResults::Interupted; + } + + if (tx <= ty && tx <= tz) + { + if (i == iend) break; + tx += deltatx; + i += di; + + if (di == 1) sampler.movePositiveX(); + if (di == -1) sampler.moveNegativeX(); + } + else if (ty <= tz) + { + if (j == jend) break; + ty += deltaty; + j += dj; + + if (dj == 1) sampler.movePositiveY(); + if (dj == -1) sampler.moveNegativeY(); + } + else + { + if (k == kend) break; + tz += deltatz; + k += dk; + + if (dk == 1) sampler.movePositiveZ(); + if (dk == -1) sampler.moveNegativeZ(); + } + } + + return RaycastResults::Completed; + } + + /** + * Cast a ray through a volume by specifying the start and a direction + * + * The ray will move from \a v3dStart along \a v3dDirectionAndLength, calling + * \a callback for each voxel it passes through until \a callback returns + * \a false. In this case it returns a RaycastResults::Interupted. If it + * passes from start to end without \a callback returning \a false, it + * returns RaycastResults::Completed. + * + * \note These has been confusion in the past with people not realising + * that the length of the direction vector is important. Most graphics API can provide + * a camera position and view direction for picking purposes, but the view direction is + * usually normalised (i.e. of length one). If you use this view direction directly you + * will only iterate over a single voxel and won't find what you are looking for. Instead + * you must scale the direction vector so that it's length represents the maximum distance + * over which you want the ray to be cast. + * + * \param volData The volume to pass the ray though + * \param v3dStart The start position in the volume + * \param v3dDirectionAndLength The direction and length of the ray + * \param callback The callback to call for each voxel + * + * \return A RaycastResults designating whether the ray hit anything or not + */ + template + RaycastResult raycastWithDirection(VolumeType* volData, const Vector3DFloat& v3dStart, const Vector3DFloat& v3dDirectionAndLength, Callback& callback) + { + Vector3DFloat v3dEnd = v3dStart + v3dDirectionAndLength; + return raycastWithEndpoints(volData, v3dStart, v3dEnd, callback); + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Region.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Region.h new file mode 100644 index 0000000..7e6893d --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Region.h @@ -0,0 +1,460 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Region_H__ +#define __PolyVox_Region_H__ + +#include "Impl/PlatformDefinitions.h" + +#include "Vector.h" + +namespace PolyVox +{ + /** Represents a part of a Volume. + * + * Many operations in PolyVox are constrained to only part of a volume. For example, when running the surface extractors + * it is unlikely that you will want to run it on the whole volume at once, as this will give a very large mesh which may + * be too much to render. Instead you will probably want to run a surface extractor a number of times on different parts + * of the volume, there by giving a number of meshes which can be culled and rendered seperately. + * + * The Region class is used to define these parts (regions) of the volume. Essentially it consists of an upper and lower + * bound which specify the range of voxels positions considered to be part of the region. Note that these bounds are + * inclusive. + * + * As well as the expected set of getters and setters, this class also provide utility functions for increasing and decresing + * the size of the Region, shifting the Region in 3D space, testing whether it contains a given position, enlarging it so that + * it does contain a given position, croppng it to another Region, and various other utility functions. + * + * \Note The dimensions of a region can be measured either in voxels or in cells. See the manual for more information + * about these definitions. + * + */ + class Region + { + public: + + /// A Region with the lower corner set as low as possible and the upper corner set as high as possible. + static Region MaxRegion(); + /// A Region with the lower corner set as high as possible and the upper corner set as low as possible. + static Region InvertedRegion(); + + /// Constructor + Region(); + /// Constructor + Region(const Vector3DInt32& v3dLowerCorner, const Vector3DInt32& v3dUpperCorner); + /// Constructor + Region(int32_t iLowerX, int32_t iLowerY, int32_t iLowerZ, int32_t iUpperX, int32_t iUpperY, int32_t iUpperZ); + + /// Equality Operator. + bool operator==(const Region& rhs) const; + /// Inequality Operator. + bool operator!=(const Region& rhs) const; + + /// Gets the 'x' position of the centre. + int32_t getCentreX(void) const; + /// Gets the 'y' position of the centre. + int32_t getCentreY(void) const; + /// Gets the 'z' position of the centrer. + int32_t getCentreZ(void) const; + /// Gets the 'x' position of the lower corner. + int32_t getLowerX(void) const; + /// Gets the 'y' position of the lower corner. + int32_t getLowerY(void) const; + /// Gets the 'z' position of the lower corner. + int32_t getLowerZ(void) const; + /// Gets the 'x' position of the upper corner. + int32_t getUpperX(void) const; + /// Gets the 'y' position of the upper corner. + int32_t getUpperY(void) const; + /// Gets the 'z' position of the upper corner. + int32_t getUpperZ(void) const; + + /// Gets the centre of the region + Vector3DInt32 getCentre(void) const; + /// Gets the position of the lower corner. + Vector3DInt32 getLowerCorner(void) const; + /// Gets the position of the upper corner. + Vector3DInt32 getUpperCorner(void) const; + + /// Gets the width of the region measured in voxels. + int32_t getWidthInVoxels(void) const; + /// Gets the height of the region measured in voxels. + int32_t getHeightInVoxels(void) const; + /// Gets the depth of the region measured in voxels. + int32_t getDepthInVoxels(void) const; + /// Gets the dimensions of the region measured in voxels. + Vector3DInt32 getDimensionsInVoxels(void) const; + + /// Gets the width of the region measured in cells. + int32_t getWidthInCells(void) const; + /// Gets the height of the region measured in cells. + int32_t getHeightInCells(void) const; + /// Gets the depth of the region measured in cells. + int32_t getDepthInCells(void) const; + /// Gets the dimensions of the region measured in cells. + Vector3DInt32 getDimensionsInCells(void) const; + + /// Sets the 'x' position of the lower corner. + void setLowerX(int32_t iX); + /// Sets the 'y' position of the lower corner. + void setLowerY(int32_t iY); + /// Sets the 'z' position of the lower corner. + void setLowerZ(int32_t iZ); + /// Sets the 'x' position of the upper corner. + void setUpperX(int32_t iX); + /// Sets the 'y' position of the upper corner. + void setUpperY(int32_t iY); + /// Sets the 'z' position of the upper corner. + void setUpperZ(int32_t iZ); + + /// Sets the position of the lower corner. + void setLowerCorner(const Vector3DInt32& v3dLowerCorner); + /// Sets the position of the upper corner. + void setUpperCorner(const Vector3DInt32& v3dUpperCorner); + + /// Tests whether the given point is contained in this Region. + bool containsPoint(float fX, float fY, float fZ, float boundary = 0.0f) const; + /// Tests whether the given point is contained in this Region. + bool containsPoint(const Vector3DFloat& pos, float boundary = 0.0f) const; + /// Tests whether the given point is contained in this Region. + bool containsPoint(int32_t iX, int32_t iY, int32_t iZ, uint8_t boundary = 0) const; + /// Tests whether the given point is contained in this Region. + bool containsPoint(const Vector3DInt32& pos, uint8_t boundary = 0) const; + /// Tests whether the given position is contained in the 'x' range of this Region. + bool containsPointInX(float pos, float boundary = 0.0f) const; + /// Tests whether the given position is contained in the 'x' range of this Region. + bool containsPointInX(int32_t pos, uint8_t boundary = 0) const; + /// Tests whether the given position is contained in the 'y' range of this Region. + bool containsPointInY(float pos, float boundary = 0.0f) const; + /// Tests whether the given position is contained in the 'y' range of this Region. + bool containsPointInY(int32_t pos, uint8_t boundary = 0) const; + /// Tests whether the given position is contained in the 'z' range of this Region. + bool containsPointInZ(float pos, float boundary = 0.0f) const; + /// Tests whether the given position is contained in the 'z' range of this Region. + bool containsPointInZ(int32_t pos, uint8_t boundary = 0) const; + + /// Tests whether the given Region is contained in this Region. + bool containsRegion(const Region& reg, uint8_t boundary = 0) const; + + /// Enlarges the Region so that it contains the specified position. + void accumulate(int32_t iX, int32_t iY, int32_t iZ); + /// Enlarges the Region so that it contains the specified position. + void accumulate(const Vector3DInt32& v3dPos); + /// Enlarges the Region so that it contains the specified Region. + void accumulate(const Region& reg); + + /// Crops the extents of this Region accoring to another Region. + void cropTo(const Region& other); + + /// Grows this region by the amount specified. + void grow(int32_t iAmount); + /// Grows this region by the amounts specified. + void grow(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ); + /// Grows this region by the amounts specified. + void grow(const Vector3DInt32& v3dAmount); + + /// Tests whether all components of the upper corner are at least + /// as great as the corresponding components of the lower corner. + bool isValid(void) const; + + /// Moves the Region by the amount specified. + void shift(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ); + /// Moves the Region by the amount specified. + void shift(const Vector3DInt32& v3dAmount); + /// Moves the lower corner of the Region by the amount specified. + void shiftLowerCorner(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ); + /// Moves the lower corner of the Region by the amount specified. + void shiftLowerCorner(const Vector3DInt32& v3dAmount); + /// Moves the upper corner of the Region by the amount specified. + void shiftUpperCorner(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ); + /// Moves the upper corner of the Region by the amount specified. + void shiftUpperCorner(const Vector3DInt32& v3dAmount); + + /// Shrinks this region by the amount specified. + void shrink(int32_t iAmount); + /// Shrinks this region by the amounts specified. + void shrink(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ); + /// Shrinks this region by the amounts specified. + void shrink(const Vector3DInt32& v3dAmount); + + private: + int32_t m_iLowerX; + int32_t m_iLowerY; + int32_t m_iLowerZ; + int32_t m_iUpperX; + int32_t m_iUpperY; + int32_t m_iUpperZ; + }; + + // Non-member functions + bool intersects(const Region& a, const Region& b); + + // Non-member overloaded operators. + /// Stream insertion operator. + std::ostream& operator<<(std::ostream& os, const Region& region); + + // Functions to be inlined to to be in the header rather than the .cpp. + // 'inline' keyword is used for the definition rather than the declaration. + // See also http://www.parashift.com/c++-faq-lite/inline-functions.html + + /** + * \return The 'x' position of the centre. + */ + inline int32_t Region::getCentreX(void) const + { + return (m_iLowerX + m_iUpperX) / 2; + } + + /** + * \return The 'y' position of the centre. + */ + inline int32_t Region::getCentreY(void) const + { + return (m_iLowerY + m_iUpperY) / 2; + } + + /** + * \return The 'z' position of the centre. + */ + inline int32_t Region::getCentreZ(void) const + { + return (m_iLowerZ + m_iUpperZ) / 2; + } + + /** + * \return The 'x' position of the lower corner. + */ + inline int32_t Region::getLowerX(void) const + { + return m_iLowerX; + } + + /** + * \return The 'y' position of the lower corner. + */ + inline int32_t Region::getLowerY(void) const + { + return m_iLowerY; + } + + /** + * \return The 'z' position of the lower corner. + */ + inline int32_t Region::getLowerZ(void) const + { + return m_iLowerZ; + } + + /** + * \return The 'x' position of the upper corner. + */ + inline int32_t Region::getUpperX(void) const + { + return m_iUpperX; + } + + /** + * \return The 'y' position of the upper corner. + */ + inline int32_t Region::getUpperY(void) const + { + return m_iUpperY; + } + + /** + * \return The 'z' position of the upper corner. + */ + inline int32_t Region::getUpperZ(void) const + { + return m_iUpperZ; + } + + /** + * \return The position of the lower corner. + */ + inline Vector3DInt32 Region::getCentre(void) const + { + return Vector3DInt32(getCentreX(), getCentreY(), getCentreZ()); + } + + /** + * \return The position of the lower corner. + */ + inline Vector3DInt32 Region::getLowerCorner(void) const + { + return Vector3DInt32(m_iLowerX, m_iLowerY, m_iLowerZ); + } + + /** + * \return The position of the upper corner. + */ + inline Vector3DInt32 Region::getUpperCorner(void) const + { + return Vector3DInt32(m_iUpperX, m_iUpperY, m_iUpperZ); + } + + /** + * \return The width of the region measured in voxels. + * \sa getWidthInCells() + */ + inline int32_t Region::getWidthInVoxels(void) const + { + return getWidthInCells() + 1; + } + + /** + * \return The height of the region measured in voxels. + * \sa getHeightInCells() + */ + inline int32_t Region::getHeightInVoxels(void) const + { + return getHeightInCells() + 1; + } + + /** + * \return The depth of the region measured in voxels. + * \sa getDepthInCells() + */ + inline int32_t Region::getDepthInVoxels(void) const + { + return getDepthInCells() + 1; + } + + /** + * \return The dimensions of the region measured in voxels. + * \sa getDimensionsInCells() + */ + inline Vector3DInt32 Region::getDimensionsInVoxels(void) const + { + return getDimensionsInCells() + Vector3DInt32(1, 1, 1); + } + + /** + * \return The width of the region measured in cells. + * \sa getWidthInVoxels() + */ + inline int32_t Region::getWidthInCells(void) const + { + return m_iUpperX - m_iLowerX; + } + + /** + * \return The height of the region measured in cells. + * \sa getHeightInVoxels() + */ + inline int32_t Region::getHeightInCells(void) const + { + return m_iUpperY - m_iLowerY; + } + + /** + * \return The depth of the region measured in cells. + * \sa getDepthInVoxels() + */ + inline int32_t Region::getDepthInCells(void) const + { + return m_iUpperZ - m_iLowerZ; + } + + /** + * \return The dimensions of the region measured in cells. + * \sa getDimensionsInVoxels() + */ + inline Vector3DInt32 Region::getDimensionsInCells(void) const + { + return Vector3DInt32(getWidthInCells(), getHeightInCells(), getDepthInCells()); + } + + /** + * \param iX The new 'x' position of the lower corner. + */ + inline void Region::setLowerX(int32_t iX) + { + m_iLowerX = iX; + } + + /** + * \param iY The new 'y' position of the lower corner. + */ + inline void Region::setLowerY(int32_t iY) + { + m_iLowerY = iY; + } + + /** + * \param iZ The new 'z' position of the lower corner. + */ + inline void Region::setLowerZ(int32_t iZ) + { + m_iLowerZ = iZ; + } + + /** + * \param iX The new 'x' position of the upper corner. + */ + inline void Region::setUpperX(int32_t iX) + { + m_iUpperX = iX; + } + + /** + * \param iY The new 'y' position of the upper corner. + */ + inline void Region::setUpperY(int32_t iY) + { + m_iUpperY = iY; + } + + /** + * \param iZ The new 'z' position of the upper corner. + */ + inline void Region::setUpperZ(int32_t iZ) + { + m_iUpperZ = iZ; + } + + /** + * \param v3dLowerCorner The new position of the lower corner. + */ + inline void Region::setLowerCorner(const Vector3DInt32& v3dLowerCorner) + { + m_iLowerX = v3dLowerCorner.getX(); + m_iLowerY = v3dLowerCorner.getY(); + m_iLowerZ = v3dLowerCorner.getZ(); + } + + /** + * \param v3dUpperCorner The new position of the upper corner. + */ + inline void Region::setUpperCorner(const Vector3DInt32& v3dUpperCorner) + { + m_iUpperX = v3dUpperCorner.getX(); + m_iUpperY = v3dUpperCorner.getY(); + m_iUpperZ = v3dUpperCorner.getZ(); + } +} + +#include "Region.inl" + +#endif diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Region.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Region.inl new file mode 100644 index 0000000..436106b --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Region.inl @@ -0,0 +1,519 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include +#include + +namespace PolyVox +{ + /** + */ + inline Region Region::MaxRegion() + { + return Region( + (std::numeric_limits::min)(), (std::numeric_limits::min)(), (std::numeric_limits::min)(), + (std::numeric_limits::max)(), (std::numeric_limits::max)(), (std::numeric_limits::max)()); + } + + /** + * This Region is not considered valid as defined by isValid(). It's main application + * is to initialise a Region to this value and then() accumulate positions. The result + * of this will be a Region which encompasses all positions specified. + */ + inline Region Region::InvertedRegion() + { + return Region( + (std::numeric_limits::max)(), (std::numeric_limits::max)(), (std::numeric_limits::max)(), + (std::numeric_limits::min)(), (std::numeric_limits::min)(), (std::numeric_limits::min)()); + } + + /** + * \param iX The 'x' component of the position to accumulate. + * \param iY The 'y' component of the position to accumulate. + * \param iZ The 'z' component of the position to accumulate. + */ + inline void Region::accumulate(int32_t iX, int32_t iY, int32_t iZ) + { + m_iLowerX = ((std::min)(m_iLowerX, iX)); + m_iLowerY = ((std::min)(m_iLowerY, iY)); + m_iLowerZ = ((std::min)(m_iLowerZ, iZ)); + m_iUpperX = ((std::max)(m_iUpperX, iX)); + m_iUpperY = ((std::max)(m_iUpperY, iY)); + m_iUpperZ = ((std::max)(m_iUpperZ, iZ)); + } + + /** + * \param v3dPos The position to accumulate. + */ + inline void Region::accumulate(const Vector3DInt32& v3dPos) + { + accumulate(v3dPos.getX(), v3dPos.getY(), v3dPos.getZ()); + } + + /** + * Note that this is not the same as computing the union of two Regions (as the result of + * such a union may not be a shape which can be exactly represented by a Region). Instead, + * the result is simply big enough to contain both this Region and the one passed as a parameter. + * \param reg The Region to accumulate. This must be valid as defined by the isValid() function. + * \sa isValid() + */ + inline void Region::accumulate(const Region& reg) + { + if (!reg.isValid()) + { + POLYVOX_THROW(invalid_operation, "You cannot accumulate an invalid region."); //The result of accumulating an invalid region is not defined. + } + + m_iLowerX = ((std::min)(m_iLowerX, reg.getLowerX())); + m_iLowerY = ((std::min)(m_iLowerY, reg.getLowerY())); + m_iLowerZ = ((std::min)(m_iLowerZ, reg.getLowerZ())); + m_iUpperX = ((std::max)(m_iUpperX, reg.getUpperX())); + m_iUpperY = ((std::max)(m_iUpperY, reg.getUpperY())); + m_iUpperZ = ((std::max)(m_iUpperZ, reg.getUpperZ())); + } + + /** + * Constructs a Region and clears all extents to zero. + */ + inline Region::Region() + :m_iLowerX(0) + , m_iLowerY(0) + , m_iLowerZ(0) + , m_iUpperX(0) + , m_iUpperY(0) + , m_iUpperZ(0) + { + } + + /** + * Constructs a Region and sets the lower and upper corners to the specified values. + * \param v3dLowerCorner The desired lower corner of the Region. + * \param v3dUpperCorner The desired upper corner of the Region. + */ + inline Region::Region(const Vector3DInt32& v3dLowerCorner, const Vector3DInt32& v3dUpperCorner) + :m_iLowerX(v3dLowerCorner.getX()) + , m_iLowerY(v3dLowerCorner.getY()) + , m_iLowerZ(v3dLowerCorner.getZ()) + , m_iUpperX(v3dUpperCorner.getX()) + , m_iUpperY(v3dUpperCorner.getY()) + , m_iUpperZ(v3dUpperCorner.getZ()) + { + } + + /** + * Constructs a Region and sets the extents to the specified values. + * \param iLowerX The desired lower 'x' extent of the Region. + * \param iLowerY The desired lower 'y' extent of the Region. + * \param iLowerZ The desired lower 'z' extent of the Region. + * \param iUpperX The desired upper 'x' extent of the Region. + * \param iUpperY The desired upper 'y' extent of the Region. + * \param iUpperZ The desired upper 'z' extent of the Region. + */ + inline Region::Region(int32_t iLowerX, int32_t iLowerY, int32_t iLowerZ, int32_t iUpperX, int32_t iUpperY, int32_t iUpperZ) + :m_iLowerX(iLowerX) + , m_iLowerY(iLowerY) + , m_iLowerZ(iLowerZ) + , m_iUpperX(iUpperX) + , m_iUpperY(iUpperY) + , m_iUpperZ(iUpperZ) + { + } + + /** + * Two regions are considered equal if all their extents match. + * \param rhs The Region to compare to. + * \return true if the Regions match. + * \sa operator!= + */ + inline bool Region::operator==(const Region& rhs) const + { + return ((m_iLowerX == rhs.m_iLowerX) && (m_iLowerY == rhs.m_iLowerY) && (m_iLowerZ == rhs.m_iLowerZ) + && (m_iUpperX == rhs.m_iUpperX) && (m_iUpperY == rhs.m_iUpperY) && (m_iUpperZ == rhs.m_iUpperZ)); + } + + /** + * Two regions are considered different if any of their extents differ. + * \param rhs The Region to compare to. + * \return true if the Regions are different. + * \sa operator== + */ + inline bool Region::operator!=(const Region& rhs) const + { + return !(*this == rhs); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in all directions. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param fX The 'x' position of the point to test. + * \param fY The 'y' position of the point to test. + * \param fZ The 'z' position of the point to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPoint(float fX, float fY, float fZ, float boundary) const + { + return (fX <= m_iUpperX - boundary) + && (fY <= m_iUpperY - boundary) + && (fZ <= m_iUpperZ - boundary) + && (fX >= m_iLowerX + boundary) + && (fY >= m_iLowerY + boundary) + && (fZ >= m_iLowerZ + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in all directions. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPoint(const Vector3DFloat& pos, float boundary) const + { + return containsPoint(pos.getX(), pos.getY(), pos.getZ(), boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in all directions. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param iX The 'x' position of the point to test. + * \param iY The 'y' position of the point to test. + * \param iZ The 'z' position of the point to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPoint(int32_t iX, int32_t iY, int32_t iZ, uint8_t boundary) const + { + return (iX <= m_iUpperX - boundary) + && (iY <= m_iUpperY - boundary) + && (iZ <= m_iUpperZ - boundary) + && (iX >= m_iLowerX + boundary) + && (iY >= m_iLowerY + boundary) + && (iZ >= m_iLowerZ + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in all directions. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPoint(const Vector3DInt32& pos, uint8_t boundary) const + { + return containsPoint(pos.getX(), pos.getY(), pos.getZ(), boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in the 'x' direction. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPointInX(float pos, float boundary) const + { + return (pos <= m_iUpperX - boundary) + && (pos >= m_iLowerX + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in the 'x' direction. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPointInX(int32_t pos, uint8_t boundary) const + { + return (pos <= m_iUpperX - boundary) + && (pos >= m_iLowerX + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in the 'y' direction. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPointInY(float pos, float boundary) const + { + return (pos <= m_iUpperY - boundary) + && (pos >= m_iLowerY + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in the 'y' direction. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPointInY(int32_t pos, uint8_t boundary) const + { + return (pos <= m_iUpperY - boundary) + && (pos >= m_iLowerY + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in the 'z' direction. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPointInZ(float pos, float boundary) const + { + return (pos <= m_iUpperZ - boundary) + && (pos >= m_iLowerZ + boundary); + } + + /** + * The boundary value can be used to ensure a position is only considered to be inside + * the Region if it is that far in in the 'z' direction. Also, the test is inclusive such + * that positions lying exactly on the edge of the Region are considered to be inside it. + * \param pos The position to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsPointInZ(int32_t pos, uint8_t boundary) const + { + return (pos <= m_iUpperZ - boundary) + && (pos >= m_iLowerZ + boundary); + } + + /** + * The boundary value can be used to ensure a region is only considered to be inside + * another Region if it is that far in in all directions. Also, the test is inclusive such + * that a region is considered to be inside of itself. + * \param reg The region to test. + * \param boundary The desired boundary value. + */ + inline bool Region::containsRegion(const Region& reg, uint8_t boundary) const + { + return (reg.m_iUpperX <= m_iUpperX - boundary) + && (reg.m_iUpperY <= m_iUpperY - boundary) + && (reg.m_iUpperZ <= m_iUpperZ - boundary) + && (reg.m_iLowerX >= m_iLowerX + boundary) + && (reg.m_iLowerY >= m_iLowerY + boundary) + && (reg.m_iLowerZ >= m_iLowerZ + boundary); + } + + /** + * After calling this functions, the extents of this Region are given by the intersection + * of this Region and the one it was cropped to. + * \param other The Region to crop to. + */ + inline void Region::cropTo(const Region& other) + { + m_iLowerX = ((std::max)(m_iLowerX, other.m_iLowerX)); + m_iLowerY = ((std::max)(m_iLowerY, other.m_iLowerY)); + m_iLowerZ = ((std::max)(m_iLowerZ, other.m_iLowerZ)); + m_iUpperX = ((std::min)(m_iUpperX, other.m_iUpperX)); + m_iUpperY = ((std::min)(m_iUpperY, other.m_iUpperY)); + m_iUpperZ = ((std::min)(m_iUpperZ, other.m_iUpperZ)); + } + + /** + * The same amount of growth is applied in all directions. Negative growth + * is possible but you should prefer the shrink() function for clarity. + * \param iAmount The amount to grow by. + */ + inline void Region::grow(int32_t iAmount) + { + m_iLowerX -= iAmount; + m_iLowerY -= iAmount; + m_iLowerZ -= iAmount; + + m_iUpperX += iAmount; + m_iUpperY += iAmount; + m_iUpperZ += iAmount; + } + + /** + * The amount can be specified seperatly for each direction. Negative growth + * is possible but you should prefer the shrink() function for clarity. + * \param iAmountX The amount to grow by in 'x'. + * \param iAmountY The amount to grow by in 'y'. + * \param iAmountZ The amount to grow by in 'z'. + */ + inline void Region::grow(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ) + { + m_iLowerX -= iAmountX; + m_iLowerY -= iAmountY; + m_iLowerZ -= iAmountZ; + + m_iUpperX += iAmountX; + m_iUpperY += iAmountY; + m_iUpperZ += iAmountZ; + } + + /** + * The amount can be specified seperatly for each direction. Negative growth + * is possible but you should prefer the shrink() function for clarity. + * \param v3dAmount The amount to grow by (one component for each direction). + */ + inline void Region::grow(const Vector3DInt32& v3dAmount) + { + grow(v3dAmount.getX(), v3dAmount.getY(), v3dAmount.getZ()); + } + + /** + */ + inline bool Region::isValid(void) const + { + return (m_iUpperX >= m_iLowerX) && (m_iUpperY >= m_iLowerY) && (m_iUpperZ >= m_iLowerZ); + } + + /** + * \param iAmountX The amount to move the Region by in 'x'. + * \param iAmountY The amount to move the Region by in 'y'. + * \param iAmountZ The amount to move the Region by in 'z'. + */ + inline void Region::shift(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ) + { + shiftLowerCorner(iAmountX, iAmountY, iAmountZ); + shiftUpperCorner(iAmountX, iAmountY, iAmountZ); + } + + /** + * \param v3dAmount The amount to move the Region by. + */ + inline void Region::shift(const Vector3DInt32& v3dAmount) + { + shiftLowerCorner(v3dAmount); + shiftUpperCorner(v3dAmount); + } + + /** + * \param iAmountX The amount to move the lower corner by in 'x'. + * \param iAmountY The amount to move the lower corner by in 'y'. + * \param iAmountZ The amount to move the lower corner by in 'z'. + */ + inline void Region::shiftLowerCorner(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ) + { + m_iLowerX += iAmountX; + m_iLowerY += iAmountY; + m_iLowerZ += iAmountZ; + } + + /** + * \param v3dAmount The amount to move the lower corner by. + */ + inline void Region::shiftLowerCorner(const Vector3DInt32& v3dAmount) + { + shiftLowerCorner(v3dAmount.getX(), v3dAmount.getY(), v3dAmount.getZ()); + } + + /** + * \param iAmountX The amount to move the upper corner by in 'x'. + * \param iAmountY The amount to move the upper corner by in 'y'. + * \param iAmountZ The amount to move the upper corner by in 'z'. + */ + inline void Region::shiftUpperCorner(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ) + { + m_iUpperX += iAmountX; + m_iUpperY += iAmountY; + m_iUpperZ += iAmountZ; + } + + /** + * \param v3dAmount The amount to move the upper corner by. + */ + inline void Region::shiftUpperCorner(const Vector3DInt32& v3dAmount) + { + shiftUpperCorner(v3dAmount.getX(), v3dAmount.getY(), v3dAmount.getZ()); + } + + /** + * The same amount of shrinkage is applied in all directions. Negative shrinkage + * is possible but you should prefer the grow() function for clarity. + * \param iAmount The amount to shrink by. + */ + inline void Region::shrink(int32_t iAmount) + { + m_iLowerX += iAmount; + m_iLowerY += iAmount; + m_iLowerZ += iAmount; + + m_iUpperX -= iAmount; + m_iUpperY -= iAmount; + m_iUpperZ -= iAmount; + } + + /** + * The amount can be specified seperatly for each direction. Negative shrinkage + * is possible but you should prefer the grow() function for clarity. + * \param iAmountX The amount to shrink by in 'x'. + * \param iAmountY The amount to shrink by in 'y'. + * \param iAmountZ The amount to shrink by in 'z'. + */ + inline void Region::shrink(int32_t iAmountX, int32_t iAmountY, int32_t iAmountZ) + { + m_iLowerX += iAmountX; + m_iLowerY += iAmountY; + m_iLowerZ += iAmountZ; + + m_iUpperX -= iAmountX; + m_iUpperY -= iAmountY; + m_iUpperZ -= iAmountZ; + } + + /** + * The amount can be specified seperatly for each direction. Negative shrinkage + * is possible but you should prefer the grow() function for clarity. + * \param v3dAmount The amount to shrink by (one component for each direction). + */ + inline void Region::shrink(const Vector3DInt32& v3dAmount) + { + shrink(v3dAmount.getX(), v3dAmount.getY(), v3dAmount.getZ()); + } + + /** + * This function only returns true if the regions are really intersecting and not simply touching. + */ + inline bool intersects(const Region& a, const Region& b) + { + // No intersection if seperated along an axis. + if (a.getUpperX() < b.getLowerX() || a.getLowerX() > b.getUpperX()) return false; + if (a.getUpperY() < b.getLowerY() || a.getLowerY() > b.getUpperY()) return false; + if (a.getUpperZ() < b.getLowerZ() || a.getLowerZ() > b.getUpperZ()) return false; + + // Overlapping on all axes means Regions are intersecting. + return true; + } + + /** + * Enables the Region to be used intuitively with output streams such as cout. + * \param os The output stream to write to. + * \param region The Region to write to the stream. + * \return A reference to the output stream to allow chaining. + */ + inline std::ostream& operator<<(std::ostream& os, const Region& region) + { + os << "(" << region.getLowerX() << "," << region.getLowerY() << "," << region.getLowerZ() << + ") to (" << region.getUpperX() << "," << region.getUpperY() << "," << region.getUpperZ() << ")"; + return os; + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vector.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vector.h new file mode 100644 index 0000000..8d3c29e --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vector.h @@ -0,0 +1,247 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Vector_H__ +#define __PolyVox_Vector_H__ + +#include "Impl/ErrorHandling.h" +#include "Impl/PlatformDefinitions.h" + +#include +#include +#include +#include +#include +#include + +namespace PolyVox +{ + /** + * Represents a vector in space. + * + * This is a generl purpose vector class designed to represent both positions and directions. It is templatised + * on both size and data type but note that some of the operations do not make sense with integer types. For + * example it does not make conceptual sense to try and normalise an integer Vector. + * + * Every Vector must have at at least two elements, and the first four elements of any vector are known as the + * X, Y, Z and W elements. Note that W is last even though it comes before X in the alphabet. These elements can + * be accessed through getX(), setX(), getY(), setY(), getZ(), setZ(), getW() and setW(), while other elements + * can be accessed through getElemen() and setElement(). + * + * This class includes a number of common mathematical operations (addition, subtraction, etc) as well as vector + * specific operations such as the dot and cross products. Note that this class is also templatised on an + * OperationType which is used for many internal calculations and some results. For example, the square of a + * vector's length will always be an integer if all the elements are integers, but the value might be outside + * that which can be represented by the StorageType. You don't need to worry about this as long as you are using + * the built in typedefs for common configurations. + * + * Typedefs are provided for 2, 3 and 4 dimensional vector with int8_t, uint8_t, int16_t, uint6_t, int32_t, + * uint32_t, float and double types. These typedefs are used as follows: + * + * \code + * Vector2DInt32 test(1,2); //Declares a 2 dimensional Vector of type int32_t. + * \endcode + */ + template + class Vector + { + public: + /// Constructor + Vector(void); + /// Constructor. + Vector(StorageType tFillValue); + /// Constructor. + Vector(StorageType x, StorageType y); + /// Constructor. + Vector(StorageType x, StorageType y, StorageType z); + /// Constructor. + Vector(StorageType x, StorageType y, StorageType z, StorageType w); + /// Copy Constructor. + Vector(const Vector& vector); + /// Copy Constructor which performs casting. + template explicit Vector(const Vector& vector); + /// Destructor. + ~Vector(void); + + /// Assignment Operator. + Vector& operator=(const Vector& rhs); + /// Equality Operator. + bool operator==(const Vector& rhs) const; + /// Inequality Operator. + bool operator!=(const Vector& rhs) const; + /// Addition and Assignment Operator. + Vector& operator+=(const Vector &rhs); + /// Subtraction and Assignment Operator. + Vector& operator-=(const Vector &rhs); + /// Multiplication and Assignment Operator. + Vector& operator*=(const Vector &rhs); + /// Division and Assignment Operator. + Vector& operator/=(const Vector &rhs); + /// Multiplication and Assignment Operator. + Vector& operator*=(const StorageType& rhs); + /// Division and Assignment Operator. + Vector& operator/=(const StorageType& rhs); + + /// Element Access. + StorageType getElement(uint32_t index) const; + /// Get the x component of the vector. + StorageType getX(void) const; + /// Get the y component of the vector. + StorageType getY(void) const; + /// Get the z component of the vector. + StorageType getZ(void) const; + /// Get the w component of the vector. + StorageType getW(void) const; + + /// Element Access. + void setElement(uint32_t index, StorageType tValue); + /// Element Access. + void setElements(StorageType x, StorageType y); + /// Element Access. + void setElements(StorageType x, StorageType y, StorageType z); + /// Element Access. + void setElements(StorageType x, StorageType y, StorageType z, StorageType w); + /// Set the x component of the vector. + void setX(StorageType tX); + /// Set the y component of the vector. + void setY(StorageType tY); + /// Set the z component of the vector. + void setZ(StorageType tZ); + /// Set the w component of the vector. + void setW(StorageType tW); + + /// Get the length of the vector. + float length(void) const; + /// Get the squared length of the vector. + OperationType lengthSquared(void) const; + /// Find the angle between this vector and that which is passed as a parameter. + float angleTo(const Vector& vector) const; + /// Find the cross product between this vector and the vector passed as a parameter. + Vector cross(const Vector& vector) const; + /// Find the dot product between this vector and the vector passed as a parameter. + OperationType dot(const Vector& rhs) const; + /// Normalise the vector. + void normalise(void); + + private: + // Values for the vector + StorageType m_tElements[Size]; + }; + + // Non-member overloaded operators. + /// Addition operator. + template + Vector operator+(const Vector& lhs, const Vector& rhs); + /// Subtraction operator. + template + Vector operator-(const Vector& lhs, const Vector& rhs); + /// Multiplication operator. + template + Vector operator*(const Vector& lhs, const Vector& rhs); + /// Division operator. + template + Vector operator/(const Vector& lhs, const Vector& rhs); + /// Multiplication operator. + template + Vector operator*(const Vector& lhs, const StorageType& rhs); + /// Division operator. + template + Vector operator/(const Vector& lhs, const StorageType& rhs); + /// Stream insertion operator. + template + std::ostream& operator<<(std::ostream& os, const Vector& vector); + + //Some handy typedefs + + /// A 2D Vector of floats. + typedef Vector<2, float, float> Vector2DFloat; + /// A 2D Vector of doubles. + typedef Vector<2, double, double> Vector2DDouble; + /// A 2D Vector of signed 8-bit values. + typedef Vector<2, int8_t, int32_t> Vector2DInt8; + /// A 2D Vector of unsigned 8-bit values. + typedef Vector<2, uint8_t, int32_t> Vector2DUint8; + /// A 2D Vector of signed 16-bit values. + typedef Vector<2, int16_t, int32_t> Vector2DInt16; + /// A 2D Vector of unsigned 16-bit values. + typedef Vector<2, uint16_t, int32_t> Vector2DUint16; + /// A 2D Vector of signed 32-bit values. + typedef Vector<2, int32_t, int32_t> Vector2DInt32; + /// A 2D Vector of unsigned 32-bit values. + typedef Vector<2, uint32_t, int32_t> Vector2DUint32; + + /// A 3D Vector of floats. + typedef Vector<3, float, float> Vector3DFloat; + /// A 3D Vector of doubles. + typedef Vector<3, double, double> Vector3DDouble; + /// A 3D Vector of signed 8-bit values. + typedef Vector<3, int8_t, int32_t> Vector3DInt8; + /// A 3D Vector of unsigned 8-bit values. + typedef Vector<3, uint8_t, int32_t> Vector3DUint8; + /// A 3D Vector of signed 16-bit values. + typedef Vector<3, int16_t, int32_t> Vector3DInt16; + /// A 3D Vector of unsigned 16-bit values. + typedef Vector<3, uint16_t, int32_t> Vector3DUint16; + /// A 3D Vector of signed 32-bit values. + typedef Vector<3, int32_t, int32_t> Vector3DInt32; + /// A 3D Vector of unsigned 32-bit values. + typedef Vector<3, uint32_t, int32_t> Vector3DUint32; + + /// A 4D Vector of floats. + typedef Vector<4, float, float> Vector4DFloat; + /// A 4D Vector of doubles. + typedef Vector<4, double, double> Vector4DDouble; + /// A 4D Vector of signed 8-bit values. + typedef Vector<4, int8_t, int32_t> Vector4DInt8; + /// A 4D Vector of unsigned 8-bit values. + typedef Vector<4, uint8_t, int32_t> Vector4DUint8; + /// A 4D Vector of signed 16-bit values. + typedef Vector<4, int16_t, int32_t> Vector4DInt16; + /// A 4D Vector of unsigned 16-bit values. + typedef Vector<4, uint16_t, int32_t> Vector4DUint16; + /// A 4D Vector of signed 32-bit values. + typedef Vector<4, int32_t, int32_t> Vector4DInt32; + /// A 4D Vector of unsigned 32-bit values. + typedef Vector<4, uint32_t, int32_t> Vector4DUint32; + + +}//namespace PolyVox + +namespace std +{ + template <> + struct hash + { + std::size_t operator()(const PolyVox::Vector3DInt32& vec) const + { + return ((vec.getX() & 0xFF)) | ((vec.getY() & 0xFF) << 8) | ((vec.getZ() & 0xFF) << 16); + } + }; +} + + +#include "Vector.inl" + +#endif + diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vector.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vector.inl new file mode 100644 index 0000000..21d666c --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vector.inl @@ -0,0 +1,649 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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. +*******************************************************************************/ + +namespace PolyVox +{ + //-------------------------- Constructors, etc --------------------------------- + /** + * Creates a Vector object but does not initialise it. + */ + template + Vector::Vector(void) + { + } + + /** + * Creates a Vector object and initialises all components with the given value. + * \param tFillValue The value to write to every component. + */ + template + Vector::Vector(StorageType tFillValue) + { + std::fill(m_tElements, m_tElements + Size, tFillValue); + } + + /** + * Creates a Vector object and initialises it with given values. + * \param x The X component to set. + * \param y The Y component to set. + */ + template + Vector::Vector(StorageType x, StorageType y) + { + static_assert(Size == 2, "This constructor should only be used for vectors with two elements."); + + m_tElements[0] = x; + m_tElements[1] = y; + } + + /** + * Creates a Vector3D object and initialises it with given values. + * \param x The X component to set. + * \param y The Y component to set. + * \param z the Z component to set. + */ + template + Vector::Vector(StorageType x, StorageType y, StorageType z) + { + static_assert(Size == 3, "This constructor should only be used for vectors with three elements."); + + m_tElements[0] = x; + m_tElements[1] = y; + m_tElements[2] = z; + + } + + /** + * Creates a Vector3D object and initialises it with given values. + * \param x The X component to set. + * \param y The Y component to set. + * \param z The Z component to set. + * \param w The W component to set. + */ + template + Vector::Vector(StorageType x, StorageType y, StorageType z, StorageType w) + { + static_assert(Size == 4, "This constructor should only be used for vectors with four elements."); + + m_tElements[0] = x; + m_tElements[1] = y; + m_tElements[2] = z; + m_tElements[3] = w; + } + + /** + * Copy constructor builds object based on object passed as parameter. + * \param vector A reference to the Vector to be copied. + */ + template + Vector::Vector(const Vector& vector) + { + std::memcpy(m_tElements, vector.m_tElements, sizeof(StorageType)* Size); + } + + /** + * This copy constructor allows casting between vectors with different data types. + * It makes it possible to use code such as: + * + * Vector3DDouble v3dDouble(1.0,2.0,3.0); + * Vector3DFloat v3dFloat = static_cast(v3dDouble); //Casting + * + * \param vector A reference to the Vector to be copied. + */ + template + template + Vector::Vector(const Vector& vector) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] = static_cast(vector.getElement(ct)); + } + } + + /** + * Destroys the Vector. + */ + template + Vector::~Vector(void) + { + // We put the static asserts in the destructor because there is one one of these, + // where as there are multiple constructors. + + // Force a vector to have a length greater than one. There is no need for a + // vector with one element, and supporting this would cause confusion over the + // behaviour of the constructor taking a single value, as this fills all elements + // to that value rather than just the first one. + static_assert(Size > 1, "Vector must have a length greater than one."); + } + + /** + * Assignment operator copies each element of first Vector to the second. + * \param rhs Vector to assign to. + * \return A reference to the result to allow chaining. + */ + template + Vector& Vector::operator=(const Vector& rhs) + { + if (this == &rhs) + { + return *this; + } + std::memcpy(m_tElements, rhs.m_tElements, sizeof(StorageType)* Size); + return *this; + } + + /** + * Checks whether two Vectors are equal. + * \param rhs The Vector to compare to. + * \return true if the Vectors match. + * \see operator!= + */ + template + inline bool Vector::operator==(const Vector &rhs) const + { + bool equal = true; + for (uint32_t ct = 0; ct < Size; ++ct) + { + if (m_tElements[ct] != rhs.m_tElements[ct]) + { + equal = false; + break; + } + } + return equal; + } + + /** + * Checks whether two Vectors are not equal. + * \param rhs The Vector to compare to. + * \return true if the Vectors do not match. + * \see operator== + */ + template + inline bool Vector::operator!=(const Vector &rhs) const + { + return !(*this == rhs); //Just call equality operator and invert the result. + } + + /** + * Addition operator adds corresponding elements of the two Vectors. + * \param rhs The Vector to add + * \return The resulting Vector. + */ + template + inline Vector& Vector::operator+=(const Vector& rhs) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] += rhs.m_tElements[ct]; + } + return *this; + } + + /** + * Subtraction operator subtracts corresponding elements of one Vector from the other. + * \param rhs The Vector to subtract + * \return The resulting Vector. + */ + template + inline Vector& Vector::operator-=(const Vector& rhs) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] -= rhs.m_tElements[ct]; + } + return *this; + } + + /** + * Multiplication operator multiplies corresponding elements of the two Vectors. + * \param rhs The Vector to multiply by + * \return The resulting Vector. + */ + template + inline Vector& Vector::operator*=(const Vector& rhs) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] *= rhs.m_tElements[ct]; + } + return *this; + } + + /** + * Division operator divides corresponding elements of one Vector by the other. + * \param rhs The Vector to divide by + * \return The resulting Vector. + */ + template + inline Vector& Vector::operator/=(const Vector& rhs) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] /= rhs.m_tElements[ct]; + } + return *this; + } + + /** + * Multiplication operator multiplies each element of the Vector by a number. + * \param rhs The number the Vector is multiplied by. + * \return The resulting Vector. + */ + template + inline Vector& Vector::operator*=(const StorageType& rhs) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] *= rhs; + } + return *this; + } + + /** + * Division operator divides each element of the Vector by a number. + * \param rhs The number the Vector is divided by. + * \return The resulting Vector. + */ + template + inline Vector& Vector::operator/=(const StorageType& rhs) + { + for (uint32_t ct = 0; ct < Size; ++ct) + { + m_tElements[ct] /= rhs; + } + return *this; + } + + /** + * Addition operator adds corresponding elements of the two Vectors. + * \param lhs The Vector to add to. + * \param rhs The Vector to add. + * \return The resulting Vector. + */ + template + Vector operator+(const Vector& lhs, const Vector& rhs) + { + Vector result = lhs; + result += rhs; + return result; + } + + /** + * Subtraction operator subtracts corresponding elements of one Vector from the other. + * \param lhs The Vector to subtract from. + * \param rhs The Vector to subtract. + * \return The resulting Vector. + */ + template + Vector operator-(const Vector& lhs, const Vector& rhs) + { + Vector result = lhs; + result -= rhs; + return result; + } + + /** + * Multiplication operator mulitplies corresponding elements of the two Vectors. + * \param lhs The Vector to multiply. + * \param rhs The Vector to multiply by. + * \return The resulting Vector. + */ + template + Vector operator*(const Vector& lhs, const Vector& rhs) + { + Vector result = lhs; + result *= rhs; + return result; + } + + /** + * Division operator divides corresponding elements of one Vector by the other. + * \param lhs The Vector to divide. + * \param rhs The Vector to divide by. + * \return The resulting Vector. + */ + template + Vector operator/(const Vector& lhs, const Vector& rhs) + { + Vector result = lhs; + result /= rhs; + return result; + } + + /** + * Multiplication operator multiplies each element of the Vector by a number. + * \param lhs The Vector to multiply. + * \param rhs The number the Vector is multiplied by. + * \return The resulting Vector. + */ + template + Vector operator*(const Vector& lhs, const StorageType& rhs) + { + Vector result = lhs; + result *= rhs; + return result; + } + + /** + * Division operator divides each element of the Vector by a number. + * \param lhs The Vector to divide. + * \param rhs The number the Vector is divided by. + * \return The resulting Vector. + */ + template + Vector operator/(const Vector& lhs, const StorageType& rhs) + { + Vector result = lhs; + result /= rhs; + return result; + } + + /** + * Enables the Vector to be used intuitively with output streams such as cout. + * \param os The output stream to write to. + * \param vector The Vector to write to the stream. + * \return A reference to the output stream to allow chaining. + */ + template + std::ostream& operator<<(std::ostream& os, const Vector& vector) + { + os << "("; + for (uint32_t ct = 0; ct < Size; ++ct) + { + os << vector.getElement(ct); + if (ct < (Size - 1)) + { + os << ","; + } + } + os << ")"; + return os; + } + + /** + * Returns the element at the given position. + * \param index The index of the element to return. + * \return The element. + */ + template + inline StorageType Vector::getElement(uint32_t index) const + { + if (index >= Size) + { + POLYVOX_THROW(std::out_of_range, "Attempted to access invalid vector element."); + } + + return m_tElements[index]; + } + + /** + * \return A const reference to the X component of a 1, 2, 3, or 4 dimensional Vector. + */ + template + inline StorageType Vector::getX(void) const + { + return m_tElements[0]; // This is fine, a Vector always contains at least two elements. + } + + /** + * \return A const reference to the Y component of a 2, 3, or 4 dimensional Vector. + */ + template + inline StorageType Vector::getY(void) const + { + return m_tElements[1]; // This is fine, a Vector always contains at least two elements. + } + + /** + * \return A const reference to the Z component of a 3 or 4 dimensional Vector. + */ + template + inline StorageType Vector::getZ(void) const + { + static_assert(Size >= 3, "You can only get the 'z' component from a vector with at least three elements."); + + return m_tElements[2]; + } + + /** + * \return A const reference to the W component of a 4 dimensional Vector. + */ + template + inline StorageType Vector::getW(void) const + { + static_assert(Size >= 4, "You can only get the 'w' component from a vector with at least four elements."); + + return m_tElements[3]; + } + + /** + * \param index The index of the element to set. + * \param tValue The new value for the element. + */ + template + inline void Vector::setElement(uint32_t index, StorageType tValue) + { + if (index >= Size) + { + POLYVOX_THROW(std::out_of_range, "Attempted to access invalid vector element."); + } + + m_tElements[index] = tValue; + } + + /** + * Sets several elements of a vector at once. + * \param x The X component to set. + * \param y The Y component to set. + */ + template + inline void Vector::setElements(StorageType x, StorageType y) + { + // This is fine, a Vector always contains at least two elements. + m_tElements[0] = x; + m_tElements[1] = y; + } + + /** + * Sets several elements of a vector at once. + * \param x The X component to set. + * \param y The Y component to set. + * \param z The Z component to set. + */ + template + inline void Vector::setElements(StorageType x, StorageType y, StorageType z) + { + static_assert(Size >= 3, "You can only use this version of setElements() on a vector with at least three elements."); + + m_tElements[0] = x; + m_tElements[1] = y; + m_tElements[2] = z; + } + + /** + * Sets several elements of a vector at once. + * \param x The X component to set. + * \param y The Y component to set. + * \param z The Z component to set. + * \param w The W component to set. + */ + template + inline void Vector::setElements(StorageType x, StorageType y, StorageType z, StorageType w) + { + static_assert(Size >= 4, "You can only use this version of setElements() on a vector with at least four elements."); + + m_tElements[0] = x; + m_tElements[1] = y; + m_tElements[2] = z; + m_tElements[3] = w; + } + + /** + * \param tX The new value for the X component of a 1, 2, 3, or 4 dimensional Vector. + */ + template + inline void Vector::setX(StorageType tX) + { + m_tElements[0] = tX; // This is fine, a Vector always contains at least two elements. + } + + /** + * \param tY The new value for the Y component of a 2, 3, or 4 dimensional Vector. + */ + template + inline void Vector::setY(StorageType tY) + { + m_tElements[1] = tY; // This is fine, a Vector always contains at least two elements. + } + + /** + * \param tZ The new value for the Z component of a 3 or 4 dimensional Vector. + */ + template + inline void Vector::setZ(StorageType tZ) + { + static_assert(Size >= 3, "You can only set the 'w' component from a vector with at least three elements."); + + m_tElements[2] = tZ; + } + + /** + * \param tW The new value for the W component of a 4 dimensional Vector. + */ + template + inline void Vector::setW(StorageType tW) + { + static_assert(Size >= 4, "You can only set the 'w' component from a vector with at least four elements."); + + m_tElements[3] = tW; + } + + /** + * \note This function always returns a single precision floating point value, even when the StorageType is a double precision floating point value or an integer. + * \return The length of the Vector. + */ + template + inline float Vector::length(void) const + { + return sqrt(static_cast(lengthSquared())); + } + + /** + * \return The squared length of the Vector. + */ + template + inline OperationType Vector::lengthSquared(void) const + { + OperationType tLengthSquared = static_cast(0); + for (uint32_t ct = 0; ct < Size; ++ct) + { + tLengthSquared += static_cast(m_tElements[ct]) * static_cast(m_tElements[ct]); + } + return tLengthSquared; + } + + /** + * This function is commutative, such that a.angleTo(b) == b.angleTo(a). The angle + * returned is in radians and varies between 0 and 3.14(pi). It is always positive. + * + * \note This function always returns a single precision floating point value, even when the StorageType is a double precision floating point value or an integer. + * + * \param vector The Vector to find the angle to. + * \return The angle between them in radians. + */ + template + inline float Vector::angleTo(const Vector& vector) const + { + return acos(static_cast(dot(vector)) / (vector.length() * this->length())); + } + + /** + * This function is used to calculate the cross product of two Vectors. + * The cross product is the Vector which is perpendicular to the two + * given Vectors. It is worth remembering that, unlike the dot product, + * it is not commutative. E.g a.b != b.a. The cross product obeys the + * right-hand rule such that if the two vectors are given by the index + * finger and middle finger respectively then the cross product is given + * by the thumb. + * \param vector The vector to cross with this + * \return The value of the cross product. + * \see dot() + */ + template + inline Vector Vector::cross(const Vector& vector) const + { + StorageType i = vector.getZ() * this->getY() - vector.getY() * this->getZ(); + StorageType j = vector.getX() * this->getZ() - vector.getZ() * this->getX(); + StorageType k = vector.getY() * this->getX() - vector.getX() * this->getY(); + return Vector(i, j, k); + } + + /** + * Calculates the dot product of the Vector and the parameter. + * This function is commutative, such that a.dot(b) == b.dot(a). + * \param rhs The Vector to find the dot product with. + * \return The value of the dot product. + * \see cross() + */ + template + inline OperationType Vector::dot(const Vector& rhs) const + { + OperationType dotProduct = static_cast(0); + for (uint32_t ct = 0; ct < Size; ++ct) + { + dotProduct += static_cast(m_tElements[ct]) * static_cast(rhs.m_tElements[ct]); + } + return dotProduct; + } + + /** + * Divides the i, j, and k components by the length to give a Vector of length 1.0. If the vector is + * very short (or zero) then a divide by zero may cause elements to take on invalid values. You may + * want to check for this before normalising. + * + * \note You should not attempt to normalise a vector whose StorageType is an integer. + */ + template + inline void Vector::normalise(void) + { + float fLength = this->length(); + + // We could wait until the NAN occurs before throwing, but then we'd have to add some roll-back code. + // This seems like a lot of overhead for a common operation which should rarely go wrong. + if (fLength <= 0.0001) + { + POLYVOX_THROW(invalid_operation, "Cannot normalise a vector with a length of zero"); + } + + for (uint32_t ct = 0; ct < Size; ++ct) + { + // Standard float rules apply for divide-by-zero + m_tElements[ct] /= fLength; + + //This shouldn't happen as we had the length check earlier. So it's probably a bug if it does happen. + POLYVOX_ASSERT(m_tElements[ct] == m_tElements[ct], "Obtained NAN during vector normalisation. Perhaps the input vector was too short?"); + } + } +}//namespace PolyVox diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vertex.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vertex.h new file mode 100644 index 0000000..1fbf65f --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/Vertex.h @@ -0,0 +1,53 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_Vertex_H__ +#define __PolyVox_Vertex_H__ + +#include "Impl/PlatformDefinitions.h" + +#include "Vector.h" + +#include +#include + +namespace PolyVox +{ + /** + * Represents a vertex in a mesh and includes position and normal information. + * There is also a 'data' member, which usually stores the (possibly interpolated) + * value of the voxel(s) which caused the vertex to be generated. + */ + template + struct Vertex + { + typedef _DataType DataType; + + Vector3DFloat position; + Vector3DFloat normal; + DataType data; + }; +} + +#endif // __PolyVox_Vertex_H__ diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/VolumeResampler.h b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/VolumeResampler.h new file mode 100644 index 0000000..5711055 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/VolumeResampler.h @@ -0,0 +1,62 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* 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 __PolyVox_VolumeResampler_H__ +#define __PolyVox_VolumeResampler_H__ + +#include "Region.h" + +namespace PolyVox +{ + /** + * This class can be used to copy data from one volume to another, possibly while + * resizing it. It has not been heavily used an may or may not work as expected. + */ + template< typename SrcVolumeType, typename DstVolumeType> + class VolumeResampler + { + public: + VolumeResampler(SrcVolumeType* pVolSrc, const Region& regSrc, DstVolumeType* pVolDst, const Region& regDst); + + void execute(); + + private: + void resampleSameSize(); + void resampleArbitrary(); + + //Source data + SrcVolumeType* m_pVolSrc; + Region m_regSrc; + + //Destination data + DstVolumeType* m_pVolDst; + Region m_regDst; + }; + +}//namespace PolyVox + +#include "VolumeResampler.inl" + +#endif + diff --git a/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/VolumeResampler.inl b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/VolumeResampler.inl new file mode 100644 index 0000000..b1141f3 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/PolyVox/VolumeResampler.inl @@ -0,0 +1,139 @@ +/******************************************************************************* +* The MIT License (MIT) +* +* Copyright (c) 2015 David Williams and Matthew Williams +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE. +*******************************************************************************/ + +#include "Impl/Interpolation.h" + +#include + +namespace PolyVox +{ + /** + * \param pVolSrc + * \param regSrc + * \param[out] pVolDst + * \param regDst + */ + template< typename SrcVolumeType, typename DstVolumeType> + VolumeResampler::VolumeResampler(SrcVolumeType* pVolSrc, const Region ®Src, DstVolumeType* pVolDst, const Region& regDst) + :m_pVolSrc(pVolSrc) + , m_regSrc(regSrc) + , m_pVolDst(pVolDst) + , m_regDst(regDst) + { + } + + template< typename SrcVolumeType, typename DstVolumeType> + void VolumeResampler::execute() + { + int32_t uSrcWidth = m_regSrc.getUpperX() - m_regSrc.getLowerX() + 1; + int32_t uSrcHeight = m_regSrc.getUpperY() - m_regSrc.getLowerY() + 1; + int32_t uSrcDepth = m_regSrc.getUpperZ() - m_regSrc.getLowerZ() + 1; + + int32_t uDstWidth = m_regDst.getUpperX() - m_regDst.getLowerX() + 1; + int32_t uDstHeight = m_regDst.getUpperY() - m_regDst.getLowerY() + 1; + int32_t uDstDepth = m_regDst.getUpperZ() - m_regDst.getLowerZ() + 1; + + if ((uSrcWidth == uDstWidth) && (uSrcHeight == uDstHeight) && (uSrcDepth == uDstDepth)) + { + resampleSameSize(); + } + else + { + resampleArbitrary(); + } + } + + template< typename SrcVolumeType, typename DstVolumeType> + void VolumeResampler::resampleSameSize() + { + for (int32_t sz = m_regSrc.getLowerZ(), dz = m_regDst.getLowerZ(); dz <= m_regDst.getUpperZ(); sz++, dz++) + { + for (int32_t sy = m_regSrc.getLowerY(), dy = m_regDst.getLowerY(); dy <= m_regDst.getUpperY(); sy++, dy++) + { + for (int32_t sx = m_regSrc.getLowerX(), dx = m_regDst.getLowerX(); dx <= m_regDst.getUpperX(); sx++, dx++) + { + const typename SrcVolumeType::VoxelType& tSrcVoxel = m_pVolSrc->getVoxel(sx, sy, sz); + const typename DstVolumeType::VoxelType& tDstVoxel = static_cast(tSrcVoxel); + m_pVolDst->setVoxel(dx, dy, dz, tDstVoxel); + } + } + } + } + + template< typename SrcVolumeType, typename DstVolumeType> + void VolumeResampler::resampleArbitrary() + { + float srcWidth = m_regSrc.getWidthInCells(); + float srcHeight = m_regSrc.getHeightInCells(); + float srcDepth = m_regSrc.getDepthInCells(); + + float dstWidth = m_regDst.getWidthInCells(); + float dstHeight = m_regDst.getHeightInCells(); + float dstDepth = m_regDst.getDepthInCells(); + + float fScaleX = srcWidth / dstWidth; + float fScaleY = srcHeight / dstHeight; + float fScaleZ = srcDepth / dstDepth; + + typename SrcVolumeType::Sampler sampler(m_pVolSrc); + + for (int32_t dz = m_regDst.getLowerZ(); dz <= m_regDst.getUpperZ(); dz++) + { + for (int32_t dy = m_regDst.getLowerY(); dy <= m_regDst.getUpperY(); dy++) + { + for (int32_t dx = m_regDst.getLowerX(); dx <= m_regDst.getUpperX(); dx++) + { + float sx = (dx - m_regDst.getLowerX()) * fScaleX; + float sy = (dy - m_regDst.getLowerY()) * fScaleY; + float sz = (dz - m_regDst.getLowerZ()) * fScaleZ; + + sx += m_regSrc.getLowerX(); + sy += m_regSrc.getLowerY(); + sz += m_regSrc.getLowerZ(); + + sampler.setPosition(sx, sy, sz); + const typename SrcVolumeType::VoxelType& voxel000 = sampler.peekVoxel0px0py0pz(); + const typename SrcVolumeType::VoxelType& voxel001 = sampler.peekVoxel0px0py1pz(); + const typename SrcVolumeType::VoxelType& voxel010 = sampler.peekVoxel0px1py0pz(); + const typename SrcVolumeType::VoxelType& voxel011 = sampler.peekVoxel0px1py1pz(); + const typename SrcVolumeType::VoxelType& voxel100 = sampler.peekVoxel1px0py0pz(); + const typename SrcVolumeType::VoxelType& voxel101 = sampler.peekVoxel1px0py1pz(); + const typename SrcVolumeType::VoxelType& voxel110 = sampler.peekVoxel1px1py0pz(); + const typename SrcVolumeType::VoxelType& voxel111 = sampler.peekVoxel1px1py1pz(); + + //FIXME - should accept all float parameters, but GCC complains? + double dummy; + sx = modf(sx, &dummy); + sy = modf(sy, &dummy); + sz = modf(sz, &dummy); + + typename SrcVolumeType::VoxelType tInterpolatedValue = trilerp(voxel000, voxel100, voxel010, voxel110, voxel001, voxel101, voxel011, voxel111, sx, sy, sz); + + typename DstVolumeType::VoxelType result = static_cast(tInterpolatedValue); + m_pVolDst->setVoxel(dx, dy, dz, result); + } + } + } + } +} diff --git a/ThirdParty/CubiquityC/Src/Dependancies/SQLite/LICENSE.txt b/ThirdParty/CubiquityC/Src/Dependancies/SQLite/LICENSE.txt new file mode 100644 index 0000000..148a81d --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/SQLite/LICENSE.txt @@ -0,0 +1,7 @@ +2001 September 15 +The author disclaims copyright to this source code. In place of +a legal notice, here is a blessing: + + May you do good and not evil. + May you find forgiveness for yourself and forgive others. + May you share freely, never taking more than you give. \ No newline at end of file diff --git a/ThirdParty/CubiquityC/Src/Dependancies/SQLite/sqlite3.c b/ThirdParty/CubiquityC/Src/Dependancies/SQLite/sqlite3.c new file mode 100644 index 0000000..9657356 --- /dev/null +++ b/ThirdParty/CubiquityC/Src/Dependancies/SQLite/sqlite3.c @@ -0,0 +1,141343 @@ +/****************************************************************************** +** This file is an amalgamation of many separate C source files from SQLite +** version 3.8.0.2. By combining all the individual C code files into this +** single large file, the entire code can be compiled as a single translation +** unit. This allows many compilers to do optimizations that would not be +** possible if the files were compiled separately. Performance improvements +** of 5% or more are commonly seen when SQLite is compiled as a single +** translation unit. +** +** This file is all you need to compile SQLite. To use SQLite in other +** programs, you need this file and the "sqlite3.h" header file that defines +** the programming interface to the SQLite library. (If you do not have +** the "sqlite3.h" header file at hand, you will find a copy embedded within +** the text of this file. Search for "Begin file sqlite3.h" to find the start +** of the embedded sqlite3.h header file.) Additional code files may be needed +** if you want a wrapper to interface SQLite with your choice of programming +** language. The code for the "sqlite3" command-line shell is also in a +** separate file. This file contains only code for the core SQLite library. +*/ +#define SQLITE_CORE 1 +#define SQLITE_AMALGAMATION 1 +#ifndef SQLITE_PRIVATE +# define SQLITE_PRIVATE static +#endif +#ifndef SQLITE_API +# define SQLITE_API +#endif +/************** Begin file sqliteInt.h ***************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Internal interface definitions for SQLite. +** +*/ +#ifndef _SQLITEINT_H_ +#define _SQLITEINT_H_ + +/* +** These #defines should enable >2GB file support on POSIX if the +** underlying operating system supports it. If the OS lacks +** large file support, or if the OS is windows, these should be no-ops. +** +** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any +** system #includes. Hence, this block of code must be the very first +** code in all source files. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: Red Hat 7.2) but you want your code to work +** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in Red Hat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +/* +** Include the configuration header output by 'configure' if we're using the +** autoconf-based build +*/ +#ifdef _HAVE_SQLITE_CONFIG_H +#include "config.h" +#endif + +/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ +/************** Begin file sqliteLimit.h *************************************/ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file defines various limits of what SQLite can process. +*/ + +/* +** The maximum length of a TEXT or BLOB in bytes. This also +** limits the size of a row in a table or index. +** +** The hard limit is the ability of a 32-bit signed integer +** to count the size: 2^31-1 or 2147483647. +*/ +#ifndef SQLITE_MAX_LENGTH +# define SQLITE_MAX_LENGTH 1000000000 +#endif + +/* +** This is the maximum number of +** +** * Columns in a table +** * Columns in an index +** * Columns in a view +** * Terms in the SET clause of an UPDATE statement +** * Terms in the result set of a SELECT statement +** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. +** * Terms in the VALUES clause of an INSERT statement +** +** The hard upper limit here is 32676. Most database people will +** tell you that in a well-normalized database, you usually should +** not have more than a dozen or so columns in any table. And if +** that is the case, there is no point in having more than a few +** dozen values in any of the other situations described above. +*/ +#ifndef SQLITE_MAX_COLUMN +# define SQLITE_MAX_COLUMN 2000 +#endif + +/* +** The maximum length of a single SQL statement in bytes. +** +** It used to be the case that setting this value to zero would +** turn the limit off. That is no longer true. It is not possible +** to turn this limit off. +*/ +#ifndef SQLITE_MAX_SQL_LENGTH +# define SQLITE_MAX_SQL_LENGTH 1000000000 +#endif + +/* +** The maximum depth of an expression tree. This is limited to +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might +** want to place more severe limits on the complexity of an +** expression. +** +** A value of 0 used to mean that the limit was not enforced. +** But that is no longer true. The limit is now strictly enforced +** at all times. +*/ +#ifndef SQLITE_MAX_EXPR_DEPTH +# define SQLITE_MAX_EXPR_DEPTH 1000 +#endif + +/* +** The maximum number of terms in a compound SELECT statement. +** The code generator for compound SELECT statements does one +** level of recursion for each term. A stack overflow can result +** if the number of terms is too large. In practice, most SQL +** never has more than 3 or 4 terms. Use a value of 0 to disable +** any limit on the number of terms in a compount SELECT. +*/ +#ifndef SQLITE_MAX_COMPOUND_SELECT +# define SQLITE_MAX_COMPOUND_SELECT 500 +#endif + +/* +** The maximum number of opcodes in a VDBE program. +** Not currently enforced. +*/ +#ifndef SQLITE_MAX_VDBE_OP +# define SQLITE_MAX_VDBE_OP 25000 +#endif + +/* +** The maximum number of arguments to an SQL function. +*/ +#ifndef SQLITE_MAX_FUNCTION_ARG +# define SQLITE_MAX_FUNCTION_ARG 127 +#endif + +/* +** The maximum number of in-memory pages to use for the main database +** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE +*/ +#ifndef SQLITE_DEFAULT_CACHE_SIZE +# define SQLITE_DEFAULT_CACHE_SIZE 2000 +#endif +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 +#endif + +/* +** The default number of frames to accumulate in the log file before +** checkpointing the database in WAL mode. +*/ +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 +#endif + +/* +** The maximum number of attached databases. This must be between 0 +** and 62. The upper bound on 62 is because a 64-bit integer bitmap +** is used internally to track attached databases. +*/ +#ifndef SQLITE_MAX_ATTACHED +# define SQLITE_MAX_ATTACHED 10 +#endif + + +/* +** The maximum value of a ?nnn wildcard that the parser will accept. +*/ +#ifndef SQLITE_MAX_VARIABLE_NUMBER +# define SQLITE_MAX_VARIABLE_NUMBER 999 +#endif + +/* Maximum page size. The upper bound on this value is 65536. This a limit +** imposed by the use of 16-bit offsets within each page. +** +** Earlier versions of SQLite allowed the user to change this value at +** compile time. This is no longer permitted, on the grounds that it creates +** a library that is technically incompatible with an SQLite library +** compiled with a different limit. If a process operating on a database +** with a page-size of 65536 bytes crashes, then an instance of SQLite +** compiled with the default page-size limit will not be able to rollback +** the aborted transaction. This could lead to database corruption. +*/ +#ifdef SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_PAGE_SIZE +#endif +#define SQLITE_MAX_PAGE_SIZE 65536 + + +/* +** The default size of a database page. +*/ +#ifndef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE 1024 +#endif +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + +/* +** Ordinarily, if no value is explicitly provided, SQLite creates databases +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain +** device characteristics (sector-size and atomic write() support), +** SQLite may choose a larger value. This constant is the maximum value +** SQLite will choose on its own. +*/ +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 +#endif +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + + +/* +** Maximum number of pages in one database file. +** +** This is really just the default value for the max_page_count pragma. +** This value can be lowered (or raised) at run-time using that the +** max_page_count macro. +*/ +#ifndef SQLITE_MAX_PAGE_COUNT +# define SQLITE_MAX_PAGE_COUNT 1073741823 +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Maximum depth of recursion for triggers. +** +** A value of 1 means that a trigger program will not be able to itself +** fire any triggers. A value of 0 means that no trigger programs at all +** may be executed. +*/ +#ifndef SQLITE_MAX_TRIGGER_DEPTH +# define SQLITE_MAX_TRIGGER_DEPTH 1000 +#endif + +/************** End of sqliteLimit.h *****************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/* Disable nuisance warnings on Borland compilers */ +#if defined(__BORLANDC__) +#pragma warn -rch /* unreachable code */ +#pragma warn -ccc /* Condition is always true or false */ +#pragma warn -aus /* Assigned value is never used */ +#pragma warn -csu /* Comparing signed and unsigned */ +#pragma warn -spa /* Suspicious pointer arithmetic */ +#endif + +/* Needed for various definitions... */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE +#endif + +#if defined(__OpenBSD__) && !defined(_BSD_SOURCE) +# define _BSD_SOURCE +#endif + +/* +** Include standard header files as necessary +*/ +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif + +/* +** The following macros are used to cast pointers to integers and +** integers to pointers. The way you do this varies from one compiler +** to the next, so we have developed the following set of #if statements +** to generate appropriate macros for a wide range of compilers. +** +** The correct "ANSI" way to do this is to use the intptr_t type. +** Unfortunately, that typedef is not available on all compilers, or +** if it is available, it requires an #include of specific headers +** that vary from one machine to the next. +** +** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on +** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). +** So we have to define the macros in different ways depending on the +** compiler. +*/ +#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ +# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) +#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ +# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) +# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) +#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ +# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) +#else /* Generates a warning - but it always works */ +# define SQLITE_INT_TO_PTR(X) ((void*)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(X)) +#endif + +/* +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. +** 0 means mutexes are permanently disable and the library is never +** threadsafe. 1 means the library is serialized which is the highest +** level of threadsafety. 2 means the library is multithreaded - multiple +** threads can use SQLite as long as no two threads try to use the same +** database connection at the same time. +** +** Older versions of SQLite used an optional THREADSAFE macro. +** We support that for legacy. +*/ +#if !defined(SQLITE_THREADSAFE) +# if defined(THREADSAFE) +# define SQLITE_THREADSAFE THREADSAFE +# else +# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ +# endif +#endif + +/* +** Powersafe overwrite is on by default. But can be turned off using +** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. +*/ +#ifndef SQLITE_POWERSAFE_OVERWRITE +# define SQLITE_POWERSAFE_OVERWRITE 1 +#endif + +/* +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. +** It determines whether or not the features related to +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can +** be overridden at runtime using the sqlite3_config() API. +*/ +#if !defined(SQLITE_DEFAULT_MEMSTATUS) +# define SQLITE_DEFAULT_MEMSTATUS 1 +#endif + +/* +** Exactly one of the following macros must be defined in order to +** specify which memory allocation subsystem to use. +** +** SQLITE_SYSTEM_MALLOC // Use normal system malloc() +** SQLITE_WIN32_MALLOC // Use Win32 native heap API +** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails +** SQLITE_MEMDEBUG // Debugging version of system malloc() +** +** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the +** assert() macro is enabled, each call into the Win32 native heap subsystem +** will cause HeapValidate to be called. If heap validation should fail, an +** assertion will be triggered. +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ +#if defined(SQLITE_SYSTEM_MALLOC) \ + + defined(SQLITE_WIN32_MALLOC) \ + + defined(SQLITE_ZERO_MALLOC) \ + + defined(SQLITE_MEMDEBUG)>1 +# error "Two or more of the following compile-time configuration options\ + are defined but at most one is allowed:\ + SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ + SQLITE_ZERO_MALLOC" +#endif +#if defined(SQLITE_SYSTEM_MALLOC) \ + + defined(SQLITE_WIN32_MALLOC) \ + + defined(SQLITE_ZERO_MALLOC) \ + + defined(SQLITE_MEMDEBUG)==0 +# define SQLITE_SYSTEM_MALLOC 1 +#endif + +/* +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the +** sizes of memory allocations below this value where possible. +*/ +#if !defined(SQLITE_MALLOC_SOFT_LIMIT) +# define SQLITE_MALLOC_SOFT_LIMIT 1024 +#endif + +/* +** We need to define _XOPEN_SOURCE as follows in order to enable +** recursive mutexes on most Unix systems and fchmod() on OpenBSD. +** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit +** it. +*/ +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) +# define _XOPEN_SOURCE 600 +#endif + +/* +** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that +** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, +** make it true by defining or undefining NDEBUG. +** +** Setting NDEBUG makes the code smaller and faster by disabling the +** assert() statements in the code. So we want the default action +** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG +** is set. Thus NDEBUG becomes an opt-in rather than an opt-out +** feature. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif +#if defined(NDEBUG) && defined(SQLITE_DEBUG) +# undef NDEBUG +#endif + +/* +** The testcase() macro is used to aid in coverage testing. When +** doing coverage testing, the condition inside the argument to +** testcase() must be evaluated both true and false in order to +** get full branch coverage. The testcase() macro is inserted +** to help ensure adequate test coverage in places where simple +** condition/decision coverage is inadequate. For example, testcase() +** can be used to make sure boundary values are tested. For +** bitmask tests, testcase() can be used to make sure each bit +** is significant and used at least once. On switch statements +** where multiple cases go to the same block of code, testcase() +** can insure that all cases are evaluated. +** +*/ +#ifdef SQLITE_COVERAGE_TEST +SQLITE_PRIVATE void sqlite3Coverage(int); +# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +#else +# define testcase(X) +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +/* +** Sometimes we need a small amount of code such as a variable initialization +** to setup for a later assert() statement. We do not want this code to +** appear when assert() is disabled. The following macro is therefore +** used to contain that setup code. The "VVA" acronym stands for +** "Verification, Validation, and Accreditation". In other words, the +** code within VVA_ONLY() will only run during verification processes. +*/ +#ifndef NDEBUG +# define VVA_ONLY(X) X +#else +# define VVA_ONLY(X) +#endif + +/* +** The ALWAYS and NEVER macros surround boolean expressions which +** are intended to always be true or false, respectively. Such +** expressions could be omitted from the code completely. But they +** are included in a few cases in order to enhance the resilience +** of SQLite to unexpected behavior - to make the code "self-healing" +** or "ductile" rather than being "brittle" and crashing at the first +** hint of unplanned behavior. +** +** In other words, ALWAYS and NEVER are added for defensive code. +** +** When doing coverage testing ALWAYS and NEVER are hard-coded to +** be true and false so that the unreachable code they specify will +** not be counted as untested code. +*/ +#if defined(SQLITE_COVERAGE_TEST) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif + +/* +** Return true (non-zero) if the input is a integer that is too large +** to fit in 32-bits. This macro is used inside of various testcase() +** macros to verify that we have tested SQLite for large-file support. +*/ +#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) + +/* +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. These hints could, +** in theory, be used by the compiler to generate better code, but +** currently they are just comments for human readers. +*/ +#define likely(X) (X) +#define unlikely(X) (X) + +/************** Include sqlite3.h in the middle of sqliteInt.h ***************/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve the right to make minor changes +** if experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +#ifndef SQLITE_API +# define SQLITE_API +#endif + + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.8.0.2" +#define SQLITE_VERSION_NUMBER 3008000 +#define SQLITE_SOURCE_ID "2013-09-03 17:11:13 7dd4968f235d6e1ca9547cda9cf3bd570e1609ef" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled with mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** and [sqlite3_close_v2()] are its destructors. There are many other +** interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors +** for the [sqlite3] object. +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if +** the [sqlite3] object is successfully destroyed and all associated +** resources are deallocated. +** +** ^If the database connection is associated with unfinalized prepared +** statements or unfinished sqlite3_backup objects then sqlite3_close() +** will leave the database connection open and return [SQLITE_BUSY]. +** ^If sqlite3_close_v2() is called with unfinalized prepared statements +** and unfinished sqlite3_backups, then the database connection becomes +** an unusable "zombie" which will automatically be deallocated when the +** last prepared statement is finalized or the last sqlite3_backup is +** finished. The sqlite3_close_v2() interface is intended for use with +** host languages that are garbage collected, and where the order in which +** destructors are called is arbitrary. +** +** Applications should [sqlite3_finalize | finalize] all [prepared statements], +** [sqlite3_blob_close | close] all [BLOB handles], and +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated +** with the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close_v2() is called on a [database connection] that still has +** outstanding [prepared statements], [BLOB handles], and/or +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation +** of resources is deferred until all [prepared statements], [BLOB handles], +** and [sqlite3_backup] objects are also destroyed. +** +** ^If an [sqlite3] object is destroyed while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** argument is a harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3*); +SQLITE_API int sqlite3_close_v2(sqlite3*); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicate success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes], +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) +#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) +#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) +#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) +#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) +#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) +#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) +#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) +#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) +#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) +#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) +#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) +#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) +#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) +#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) +#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) +#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) +#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* Reserved: 0x00F00000 */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that +** after reboot following a crash or power loss, the only bytes in a +** file that were written at the application level might have changed +** and that adjacent bytes, even bytes within the same sector are +** guaranteed to be unchanged. +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + /* Methods above are valid for version 3 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +**
    +**
  • [[SQLITE_FCNTL_SIZE_HINT]] +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +**
  • [[SQLITE_FCNTL_CHUNK_SIZE]] +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +**
  • [[SQLITE_FCNTL_FILE_POINTER]] +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +**
  • [[SQLITE_FCNTL_SYNC_OMITTED]] +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specialized VFSes +** that do require it. +** +**
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic +** retry counts and intervals for certain disk I/O operations for the +** windows [VFS] in order to provide robustness in the presence of +** anti-virus programs. By default, the windows VFS will retry file read, +** file write, and file delete operations up to 10 times, with a delay +** of 25 milliseconds before the first retry and with the delay increasing +** by an additional 25 milliseconds with each subsequent retry. This +** opcode allows these two values (10 retries and 25 milliseconds of delay) +** to be adjusted. The values are changed for all database connections +** within the same process. The argument is a pointer to an array of two +** integers where the first integer i the new retry count and the second +** integer is the delay. If either integer is negative, then the setting +** is not changed but instead the prior value of that setting is written +** into the array entry, allowing the current retry settings to be +** interrogated. The zDbName parameter is ignored. +** +**
  • [[SQLITE_FCNTL_PERSIST_WAL]] +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the +** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary +** write ahead log and shared memory files used for transaction control +** are automatically deleted when the latest connection to the database +** closes. Setting persistent WAL mode causes those files to persist after +** close. Persisting the files is useful when other processes that do not +** have write permission on the directory containing the database file want +** to read the database file, as the WAL and shared memory files must exist +** in order for the database to be readable. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent +** WAL mode. If the integer is -1, then it is overwritten with the current +** WAL persistence setting. +** +**
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the +** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the +** xDeviceCharacteristics methods. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage +** mode. If the integer is -1, then it is overwritten with the current +** zero-damage mode setting. +** +**
  • [[SQLITE_FCNTL_OVERWRITE]] +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening +** a write transaction to indicate that, unless it is rolled back for some +** reason, the entire database file will be overwritten by the current +** transaction. This is used by VACUUM operations. +** +**
  • [[SQLITE_FCNTL_VFSNAME]] +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of +** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** final bottom-level VFS are written into memory obtained from +** [sqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [sqlite3_file_control()] points to. +** The caller is responsible for freeing the memory when done. As with +** all file-control actions, there is no guarantee that this will actually +** do anything. Callers should initialize the char* variable to a NULL +** pointer in case this file-control is not implemented. This file-control +** is intended for diagnostic use only. +** +**
  • [[SQLITE_FCNTL_PRAGMA]] +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] +** file control is sent to the open [sqlite3_file] object corresponding +** to the database file to which the pragma statement refers. ^The argument +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of +** pointers to strings (char**) in which the second element of the array +** is the name of the pragma and the third element is the argument to the +** pragma or NULL if the pragma has no argument. ^The handler for an +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element +** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** or the equivalent and that string will become the result of the pragma or +** the error message if the pragma fails. ^If the +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal +** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] +** file control returns [SQLITE_OK], then the parser assumes that the +** VFS has handled the PRAGMA itself and the parser generates a no-op +** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means +** that the VFS encountered an error while handling the [PRAGMA] and the +** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] +** file control occurs at the beginning of pragma statement analysis and so +** it is able to override built-in [PRAGMA] statements. +** +**
  • [[SQLITE_FCNTL_BUSYHANDLER]] +** ^The [SQLITE_FCNTL_BUSYHANDLER] +** file-control may be invoked by SQLite on the database file handle +** shortly after it is opened in order to provide a custom VFS with access +** to the connections busy-handler callback. The argument is of type (void **) +** - an array of two (void *) values. The first (void *) actually points +** to a function of type (int (*)(void *)). In order to invoke the connections +** busy-handler, this function should be invoked with the second (void *) in +** the array as the only argument. If it returns non-zero, then the operation +** should be retried. If it returns zero, the custom VFS should abandon the +** current operation. +** +**
  • [[SQLITE_FCNTL_TEMPFILENAME]] +** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** to have SQLite generate a +** temporary filename using the same algorithm that is followed to generate +** temporary filenames for TEMP tables and other internal uses. The +** argument should be a char** which will be filled with the filename +** written into memory obtained from [sqlite3_malloc()]. The caller should +** invoke [sqlite3_free()] on the result to avoid a memory leak. +** +**
  • [[SQLITE_FCNTL_MMAP_SIZE]] +** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the +** maximum number of bytes that will be used for memory-mapped I/O. +** The argument is a pointer to a value of type sqlite3_int64 that +** is an advisory maximum number of bytes in the file to memory map. The +** pointer is overwritten with the old value. The limit is not changed if +** the value originally pointed to is negative, and so the current limit +** can be queried by passing in a pointer to a negative number. This +** file-control is used internally to implement [PRAGMA mmap_size]. +** +**
+*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 +#define SQLITE_FCNTL_WIN32_AV_RETRY 9 +#define SQLITE_FCNTL_PERSIST_WAL 10 +#define SQLITE_FCNTL_OVERWRITE 11 +#define SQLITE_FCNTL_VFSNAME 12 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 +#define SQLITE_FCNTL_PRAGMA 14 +#define SQLITE_FCNTL_BUSYHANDLER 15 +#define SQLITE_FCNTL_TEMPFILENAME 16 +#define SQLITE_FCNTL_MMAP_SIZE 18 + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 11 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_MASTER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc, xRealloc, and xFree methods must work like the +** malloc(), realloc() and free() functions from the standard C library. +** ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
+**
^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
+**
^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scratch allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
+** +** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+**
^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implementation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
+** +** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
+**
^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2**12. Reasonable values +** for the minimum allocation size are 2**5 through 2**8.
+** +** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+**
^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
+** +** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
+**
^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods2] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
+** +** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
+**
^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods2] object. SQLite copies of the current +** page cache implementation into that object.)^
+** +** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+**
The SQLITE_CONFIG_LOG option is used to configure the SQLite +** global [error log]. +** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI +**
This option takes a single argument of type int. If non-zero, then +** URI handling is globally enabled. If the parameter is zero, then URI handling +** is globally disabled. If URI handling is globally enabled, all filenames +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined. +** +** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN +**
This option takes a single integer argument which is interpreted as +** a boolean in order to enable or disable the use of covering indices for +** full table scans in the query optimizer. The default setting is determined +** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" +** if that compile-time option is omitted. +** The ability to disable the use of covering indices for full table scans +** is because some incorrectly coded legacy applications might malfunction +** malfunction when the optimization is enabled. Providing the ability to +** disable the optimization allows the older, buggy application code to work +** without change even with newer versions of SQLite. +** +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] +**
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE +**
These options are obsolete and should not be used by new code. +** They are retained for backwards compatibility but are now no-ops. +**
+** +** [[SQLITE_CONFIG_SQLLOG]] +**
SQLITE_CONFIG_SQLLOG +**
This option is only available if sqlite is compiled with the +** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should +** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** The second should be of type (void*). The callback is invoked by the library +** in three separate circumstances, identified by the value passed as the +** fourth parameter. If the fourth parameter is 0, then the database connection +** passed as the second argument has just been opened. The third argument +** points to a buffer containing the name of the main database file. If the +** fourth parameter is 1, then the SQL statement that the third parameter +** points to has just been executed. Or, if the fourth parameter is 2, then +** the connection being passed as the second parameter is being closed. The +** third parameter is passed NULL In this case. An example of using this +** configuration option can be seen in the "test_sqllog.c" source file in +** the canonical SQLite source tree.
+** +** [[SQLITE_CONFIG_MMAP_SIZE]] +**
SQLITE_CONFIG_MMAP_SIZE +**
SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** that are the default mmap size limit (the default setting for +** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. +** The default setting can be overridden by each database connection using +** either the [PRAGMA mmap_size] command, or by using the +** [SQLITE_FCNTL_MMAP_SIZE] file control. The maximum allowed mmap size +** cannot be changed at run-time. Nor may the maximum allowed mmap size +** exceed the compile-time maximum mmap size set by the +** [SQLITE_MAX_MMAP_SIZE] compile-time option. +** If either argument to this option is negative, then that argument is +** changed to its compile-time default. +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* no-op */ +#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ +#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ +#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_DBCONFIG_LOOKASIDE
+**
^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to a memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
+** +**
SQLITE_DBCONFIG_ENABLE_FKEY
+**
^This option is used to enable or disable the enforcement of +** [foreign key constraints]. There should be two additional arguments. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
+** +**
SQLITE_DBCONFIG_ENABLE_TRIGGER
+**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back.
+** +**
+*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^As of SQLite version 3.7.7, this routines +** records the last insert rowid of both ordinary tables and [virtual tables]. +** ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger or within a [virtual table] +** method, then this routine will return the [rowid] of the inserted +** row as long as the trigger or virtual table method is running. +** But once the trigger or virtual table method ends, the value returned +** by this routine reverts to what it was before the trigger or virtual +** table method began.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a nul-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
+**  char *zText = "It's a happy day!";
+** 
+** +** One can use this text in an SQL statement as follows: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
+**  INSERT INTO table1 VALUES('It''s a happy day!')
+** 
+** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
+**  INSERT INTO table1 VALUES('It's a happy day!');
+** 
+** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** Prior to SQLite version 3.7.10, the Windows OS interface layer called +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors were detected, but +** they were reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] +** from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit +** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the approximate number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. ^If N is less than one then the progress +** handler is disabled. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

URI Filenames

+** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the fourth argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** As of SQLite version 3.7.7, URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^On windows, the first component of an absolute path +** is a drive specification (e.g. "C:"). +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite interprets the following three query parameters: +** +**
    +**
  • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
  • mode: ^(The mode parameter may be set to either "ro", "rw", +** "rwc", or "memory". Attempting to set it to any other value is +** an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_open_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is +** set to "memory" then a pure [in-memory database] that never reads +** or writes from disk is used. ^It is an error to specify a value for +** the mode parameter that is less restrictive than that specified by +** the flags passed in the third parameter to sqlite3_open_v2(). +** +**
  • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behavior requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +**
+** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

URI filename examples

+** +** +**
URI filenames Results +**
file:data.db +** Open the file "data.db" in the current directory. +**
file:/home/fred/data.db
+** file:///home/fred/data.db
+** file://localhost/home/fred/data.db
+** Open the database file "/home/fred/data.db". +**
file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
file:/home/fred/data.db?vfs=unix-nolock +** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". +**
file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +**
+** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** features that require the use of temporary files may fail. +** +** See also: [sqlite3_temp_directory] +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** These are utility routines, useful to VFS implementations, that check +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of that query parameter. +** +** If F is the database filename pointer passed into the xOpen() method of +** a VFS implementation when the flags parameter to xOpen() has one or +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and +** P is the name of the query parameter, then +** sqlite3_uri_parameter(F,P) returns the value of the P +** parameter if it exists or a NULL pointer if P does not appear as a +** query parameter on F. If P is a query parameter of F +** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** a pointer to an empty string. +** +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** parameter and returns true (1) or false (0) according to the value +** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** value of query parameter P is one of "yes", "true", or "on" in any +** case or if the value begins with a non-zero number. The +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** query parameter P is one of "no", "false", or "off" in any case or +** if the value begins with a numeric zero. If P is not a query +** parameter on F or if the value of P is does not match any of the +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** 64-bit signed integer and returns that integer, or D if P does not +** exist. If the value of P is something other than an integer, then +** zero is returned. +** +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and +** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that SQLite passed into the xOpen +** VFS method, then the behavior of this routine is undefined and probably +** undesirable. +*/ +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); + + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** ^The sqlite3_errstr() interface returns the English-language text +** that describes the [result code], as UTF-8. +** ^(Memory to hold the error message string is managed internally +** and must not be freed by the application)^. +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); +SQLITE_API const char *sqlite3_errstr(int); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
    +**
  1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
  2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
)^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes as this saves SQLite from having to +** make a copy of the input string. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] +** retries will occur before sqlite3_step() gives up and returns an error. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** the +**
  6. +**
+*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** [prepared statement] S has been stepped at least once using +** [sqlite3_step(S)] but has not run to completion and/or has not +** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** interface returns false if S is a NULL pointer. If S is not a +** NULL pointer and is not a pointer to a valid [prepared statement] +** object, then the behavior is undefined and probably undesirable. +** +** This interface can be used in combination [sqlite3_next_stmt()] +** to locate all prepared statements associated with a database +** connection that are in need of being reset. This can be used, +** for example, in diagnostic routines to search for prepared +** statements that are holding a transaction open. +*/ +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as sqlite3_bind_null(). +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** is negative, then the length of the string is +** the number of bytes up to the first zero terminator. +** If the fourth parameter to sqlite3_bind_blob() is negative, then +** the behavior is undefined. +** If a non-negative fourth parameter is provided to sqlite3_bind_text() +** or sqlite3_bind_text16() then that parameter must be the byte offset +** where the NUL terminator would occur assuming the string were NUL +** terminated. If any NUL characters occur at byte offsets less than +** the value of the fourth parameter then the resulting string value will +** contain embedded NULs. The result of expressions involving strings +** with embedded NULs is undefined. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to +** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) +** will return non-zero if previous call to [sqlite3_step](P) returned +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] +** where it always returns zero since each step of that multi-step +** pragma returns 0 columns of data. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero-terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is NULL pointer +**
NULL BLOB Result is NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER Convert from float to integer +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB Same as FLOAT->TEXT +**
TEXT INTEGER Use atoi() +**
TEXT FLOAT Use atof() +**
TEXT BLOB No change +**
BLOB INTEGER Convert to TEXT then use atoi() +**
BLOB FLOAT Convert to TEXT then use atof() +**
BLOB TEXT Add a zero terminator if needed +**
+**
)^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), + void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** when first called if N is less than or equal to zero or if a memory +** allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ Within the xFinal callback, it is customary to set +** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** pointless memory allocations occur. +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** These functions may be used by (non-aggregate) SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. An example +** of where this might be useful is in a regular-expression matching +** function. The compiled version of the regular expression can be stored as +** metadata associated with the pattern string. +** Then as long as the pattern string remains the same, +** the compiled regular expression can be reused on multiple +** invocations of the same function. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If there is no metadata +** associated with the function argument, this sqlite3_get_auxdata() interface +** returns a NULL pointer. +** +** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th +** argument of the application-defined function. ^Subsequent +** calls to sqlite3_get_auxdata(C,N) return P from the most recent +** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or +** NULL if the metadata has been discarded. +** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** SQLite will invoke the destructor function X with parameter P exactly +** once, when the metadata is discarded. +** SQLite is free to discard the metadata at any time, including:
    +**
  • when the corresponding function parameter changes, or +**
  • when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** SQL statement, or +**
  • when sqlite3_set_auxdata() is invoked again on the same parameter, or +**
  • during the original sqlite3_set_auxdata() call when a memory +** allocation error occurs.
)^ +** +** Note the last bullet in particular. The destructor X in +** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** should be called near the end of the function implementation and the +** function implementation should not make any use of P after +** sqlite3_set_auxdata() has been called. +** +** ^(In practice, metadata is preserved between function calls for +** function parameters that are compile-time constants, including literal +** values and [parameters] and expressions composed from the same.)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** error indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** error indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. If the 3rd parameter is non-negative, then it +** must be the byte offset into the string where the NUL terminator would +** appear if the string where NUL terminated. If any NUL characters occur +** in the string at a byte offset that is less than the value of the 3rd +** parameter, then the resulting string will contain embedded NULs and the +** result of expressions operating on strings with embedded NULs is undefined. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); +SQLITE_API int sqlite3_key_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); +SQLITE_API int sqlite3_rekey_v2( + sqlite3 *db, /* Database to be rekeyed */ + const char *zDbName, /* Name of the database */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +SQLITE_API void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** features that require the use of temporary files may fail. Here is an +** example of how to do this using C++ with the Windows Runtime: +** +**
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+**       TemporaryFolder->Path->Data();
+** char zPathBuf[MAX_PATH + 1];
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+**       NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** 
+*/ +SQLITE_API char *sqlite3_temp_directory; + +/* +** CAPI3REF: Name Of The Folder Holding Database Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all database files +** specified with a relative pathname and created or accessed by +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** to be relative to that directory.)^ ^If this variable is a NULL +** pointer, then SQLite assumes that all database files specified +** with a relative pathname are relative to the current directory +** for the process. Only the windows VFS makes use of this global +** variable; it is ignored by the unix VFS. +** +** Changing the value of this variable while a database connection is +** open can result in a corrupt database. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [data_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [data_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [data_store_directory pragma] should be avoided. +*/ +SQLITE_API char *sqlite3_data_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Return The Filename For A Database Connection +** +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename +** associated with database N of connection D. ^The main database file +** has the name "main". If there is no attached database N on the database +** connection D, or if database N is a temporary or in-memory database, then +** a NULL pointer is returned. +** +** ^The filename returned by this function is the output of the +** xFullPathname method of the [VFS]. ^In other words, the filename +** will be an absolute pathname, even if the filename used +** to open the database originally was a URI or relative pathname. +*/ +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine if a database is read-only +** +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** of connection D is read-only, 0 if it is read/write, or -1 if N is not +** the name of a database on connection D. +*/ +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The commit and rollback hook callbacks are not reentrant. +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that running any other SQL statements, including SELECT statements, +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** the database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** This interface is threadsafe on processors where writing a +** 32-bit integer is atomic. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** See also: [sqlite3_db_release_memory()] +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Free Memory Used By A Database Connection +** +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** memory as possible from database connection D. Unlike the +** [sqlite3_release_memory()] interface, this interface is effect even +** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is +** omitted. +** +** See also: [sqlite3_release_memory()] +*/ +SQLITE_API int sqlite3_db_release_memory(sqlite3*); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The soft heap limit is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** [SQLite extension] library contained in the file zFile. If +** the file cannot be loaded directly, attempts are made to load +** with various operating-system specific extensions added. +** So for example, if "samplelib" cannot be loaded, then names like +** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might +** be tried also. +** +** ^The entry point is zProc. +** ^(zProc may be 0, in which case SQLite will try to come up with an +** entry point name on its own. It first tries "sqlite3_extension_init". +** If that does not work, it constructs a name "sqlite3_X_init" where the +** X is consists of the lower-case equivalent of all ASCII alphabetic +** characters in the filename from the last "/" to the first following +** "." and omitting any initial "lib".)^ +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with [extension loading], and as a means of disabling +** [extension loading] while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked [SQLite extension] +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()] +** and [sqlite3_cancel_auto_extension()] +*/ +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Cancel Automatic Extension Loading +** +** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** initialization routine X that was registered using a prior call to +** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** routine returns 1 if initialization routine X was successfully +** unregistered and it returns 0 if X was not on the list of initialization +** routines. +*/ +SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_PTHREADS +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
)^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix +** and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_LRU2 +**
)^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provide versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 +#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 +#define SQLITE_TESTCTRL_LAST 19 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
+**
This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
)^ +** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
)^ +** +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
+**
This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
+**
This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
+**
This parameter returns the number of pager cache hits that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
+**
This parameter returns the number of pager cache misses that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
+**
This parameter returns the number of dirty cache entries that have +** been written to disk. Specifically, the number of pages written to the +** wal file in wal mode databases, or the number of pages written to the +** database file in rollback mode databases. Any pages written as part of +** transaction rollback or database recovery operations are not included. +** If an IO or other error occurs while writing a page to disk, the effect +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +**
+** +** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(
SQLITE_DBSTATUS_DEFERRED_FKS
+**
This parameter returns zero for the current value if and only if +** all foreign key constraints (deferred or immediate) have been +** resolved.)^ ^The highwater mark is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_CACHE_HIT 7 +#define SQLITE_DBSTATUS_CACHE_MISS 8 +#define SQLITE_DBSTATUS_CACHE_WRITE 9 +#define SQLITE_DBSTATUS_DEFERRED_FKS 10 +#define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+** +** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
+**
^This is the number of virtual machine operations executed +** by the prepared statement if that number is less than or equal +** to 2147483647. The number of virtual machine operations can be +** used as a proxy for the total work done by the prepared statement. +** If the number of virtual machine operations exceeds 2147483647 +** then the value returned by this statement status code is undefined. +**
+**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 +#define SQLITE_STMTSTATUS_VM_STEP 4 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache_page object represents a single page in the +** page cache. The page cache will allocate instances of this +** object. Various methods of the page cache use pointers to instances +** of this object as parameters or as their return value. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache_page sqlite3_pcache_page; +struct sqlite3_pcache_page { + void *pBuf; /* The content of the page */ + void *pExtra; /* Extra information associated with the page */ +}; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods2 structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will always a power of two. ^The +** second parameter szExtra is a number of bytes of extra storage +** associated with each page cache entry. ^The szExtra parameter will +** a number less than 250. SQLite will use the +** extra szExtra bytes on each page to store metadata about the underlying +** database page on disk. The value passed into szExtra depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^The third argument to xCreate(), bPurgeable, is true if the cache being +** created will be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** an sqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned sqlite3_pcache_page object will be a +** pointer to a buffer of szPage bytes used to store the content of a +** single database page. The pExtra element of sqlite3_pcache_page will be +** a pointer to the szExtra bytes of extra storage that SQLite has requested +** for each entry in the page cache. +** +** The page to be fetched is determined by the key. ^The minimum key value +** is 1. After it has been retrieved using xFetch, the page is considered +** to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behavior when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** functions. +** +** [[the xShrink() page cache method]] +** ^SQLite invokes the xShrink() method when it wants the page cache to +** free up as much of heap memory as possible. The page cache implementation +** is not obligated to free any memory, but well-behaved implementations should +** do their best. +*/ +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; +struct sqlite3_pcache_methods2 { + int iVersion; + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); + void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); + void (*xShrink)(sqlite3_pcache*); +}; + +/* +** This is the obsolete pcache_methods object that has now been replaced +** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** retained in the header file for backwards compatibility only. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** and extensions to compare the contents of two buffers containing UTF-8 +** strings in a case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_stricmp(const char *, const char *); +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: String Globbing +* +** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches +** the glob pattern P, and it returns non-zero if string X does not match +** the glob pattern P. ^The definition of glob pattern matching used in +** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case +** sensitive. +** +** Note that this routine returns zero on a match and non-zero if the strings +** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +*/ +SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +** +** See also: [sqlite3_wal_checkpoint_v2()] +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** +** Run a checkpoint operation on WAL database zDb attached to database +** handle db. The specific operation is determined by the value of the +** eMode parameter: +** +**
+**
SQLITE_CHECKPOINT_PASSIVE
+** Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish. Sync the db file if all frames in the log +** are checkpointed. This mode is the same as calling +** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. +** +**
SQLITE_CHECKPOINT_FULL
+** This mode blocks (calls the busy-handler callback) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. It then checkpoints all frames in the log file and syncs the +** database file. This call blocks database writers while it is running, +** but not database readers. +** +**
SQLITE_CHECKPOINT_RESTART
+** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after +** checkpointing the log file it blocks (calls the busy-handler callback) +** until all readers are reading from the database file only. This ensures +** that the next client to write to the database file restarts the log file +** from the beginning. This call blocks database writers while it is running, +** but not database readers. +**
+** +** If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to +** the total number of checkpointed frames (including any that were already +** checkpointed when this function is called). *pnLog and *pnCkpt may be +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. +** If no values are available because of an error, they are both set to -1 +** before returning to communicate this to the caller. +** +** All calls obtain an exclusive "checkpoint" lock on the database file. If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive +** "writer" lock on the database file. If the writer lock cannot be obtained +** immediately, and a busy-handler is configured, it is invoked and the writer +** lock retried until either the busy-handler returns 0 or the lock is +** successfully obtained. The busy-handler is also invoked while waiting for +** database readers as described above. If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. SQLITE_BUSY is returned in this case. +** +** If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned to the caller. If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code returned to the caller immediately. If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint operation parameters +** +** These constants can be used as the 3rd parameter to +** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] +** documentation for additional information about the meaning and use of +** each of these values. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 +#define SQLITE_CHECKPOINT_FULL 1 +#define SQLITE_CHECKPOINT_RESTART 2 + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** At present, there is only one option that may be configured using +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options +** may be added in the future. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
+**
SQLITE_VTAB_CONSTRAINT_SUPPORT +**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
+*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Conflict resolution modes +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + + + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif /* _SQLITE3_H_ */ + +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#if 0 +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, +#ifdef SQLITE_RTREE_INT_ONLY + int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes), +#else + int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes), +#endif + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#if 0 +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include hash.h in the middle of sqliteInt.h ******************/ +/************** Begin file hash.h ********************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implementation +** used in SQLite. +*/ +#ifndef _SQLITE_HASH_H_ +#define _SQLITE_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Hash Hash; +typedef struct HashElem HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, some of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +** +** All elements of the hash table are on a single doubly-linked list. +** Hash.first points to the head of this list. +** +** There are Hash.htsize buckets. Each bucket points to a spot in +** the global doubly-linked list. The contents of the bucket are the +** element pointed to plus the next _ht.count-1 elements in the list. +** +** Hash.htsize and Hash.ht may be zero. In that case lookup is done +** by a linear search of the global list. For small tables, the +** Hash.ht table is never allocated because if there are few elements +** in the table, it is faster to do a linear search than to manage +** the hash table. +*/ +struct Hash { + unsigned int htsize; /* Number of buckets in the hash table */ + unsigned int count; /* Number of entries in this table */ + HashElem *first; /* The first element of the array */ + struct _ht { /* the hash table */ + int count; /* Number of entries with this hash */ + HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct HashElem { + HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + const char *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +SQLITE_PRIVATE void sqlite3HashInit(Hash*); +SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); +SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); +SQLITE_PRIVATE void sqlite3HashClear(Hash*); + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Hash h; +** HashElem *p; +** ... +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ +** SomeStructure *pData = sqliteHashData(p); +** // do something with pData +** } +*/ +#define sqliteHashFirst(H) ((H)->first) +#define sqliteHashNext(E) ((E)->next) +#define sqliteHashData(E) ((E)->data) +/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ +/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ + +/* +** Number of entries in a hash table +*/ +/* #define sqliteHashCount(H) ((H)->count) // NOT USED */ + +#endif /* _SQLITE_HASH_H_ */ + +/************** End of hash.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include parse.h in the middle of sqliteInt.h *****************/ +/************** Begin file parse.h *******************************************/ +#define TK_SEMI 1 +#define TK_EXPLAIN 2 +#define TK_QUERY 3 +#define TK_PLAN 4 +#define TK_BEGIN 5 +#define TK_TRANSACTION 6 +#define TK_DEFERRED 7 +#define TK_IMMEDIATE 8 +#define TK_EXCLUSIVE 9 +#define TK_COMMIT 10 +#define TK_END 11 +#define TK_ROLLBACK 12 +#define TK_SAVEPOINT 13 +#define TK_RELEASE 14 +#define TK_TO 15 +#define TK_TABLE 16 +#define TK_CREATE 17 +#define TK_IF 18 +#define TK_NOT 19 +#define TK_EXISTS 20 +#define TK_TEMP 21 +#define TK_LP 22 +#define TK_RP 23 +#define TK_AS 24 +#define TK_COMMA 25 +#define TK_ID 26 +#define TK_INDEXED 27 +#define TK_ABORT 28 +#define TK_ACTION 29 +#define TK_AFTER 30 +#define TK_ANALYZE 31 +#define TK_ASC 32 +#define TK_ATTACH 33 +#define TK_BEFORE 34 +#define TK_BY 35 +#define TK_CASCADE 36 +#define TK_CAST 37 +#define TK_COLUMNKW 38 +#define TK_CONFLICT 39 +#define TK_DATABASE 40 +#define TK_DESC 41 +#define TK_DETACH 42 +#define TK_EACH 43 +#define TK_FAIL 44 +#define TK_FOR 45 +#define TK_IGNORE 46 +#define TK_INITIALLY 47 +#define TK_INSTEAD 48 +#define TK_LIKE_KW 49 +#define TK_MATCH 50 +#define TK_NO 51 +#define TK_KEY 52 +#define TK_OF 53 +#define TK_OFFSET 54 +#define TK_PRAGMA 55 +#define TK_RAISE 56 +#define TK_REPLACE 57 +#define TK_RESTRICT 58 +#define TK_ROW 59 +#define TK_TRIGGER 60 +#define TK_VACUUM 61 +#define TK_VIEW 62 +#define TK_VIRTUAL 63 +#define TK_REINDEX 64 +#define TK_RENAME 65 +#define TK_CTIME_KW 66 +#define TK_ANY 67 +#define TK_OR 68 +#define TK_AND 69 +#define TK_IS 70 +#define TK_BETWEEN 71 +#define TK_IN 72 +#define TK_ISNULL 73 +#define TK_NOTNULL 74 +#define TK_NE 75 +#define TK_EQ 76 +#define TK_GT 77 +#define TK_LE 78 +#define TK_LT 79 +#define TK_GE 80 +#define TK_ESCAPE 81 +#define TK_BITAND 82 +#define TK_BITOR 83 +#define TK_LSHIFT 84 +#define TK_RSHIFT 85 +#define TK_PLUS 86 +#define TK_MINUS 87 +#define TK_STAR 88 +#define TK_SLASH 89 +#define TK_REM 90 +#define TK_CONCAT 91 +#define TK_COLLATE 92 +#define TK_BITNOT 93 +#define TK_STRING 94 +#define TK_JOIN_KW 95 +#define TK_CONSTRAINT 96 +#define TK_DEFAULT 97 +#define TK_NULL 98 +#define TK_PRIMARY 99 +#define TK_UNIQUE 100 +#define TK_CHECK 101 +#define TK_REFERENCES 102 +#define TK_AUTOINCR 103 +#define TK_ON 104 +#define TK_INSERT 105 +#define TK_DELETE 106 +#define TK_UPDATE 107 +#define TK_SET 108 +#define TK_DEFERRABLE 109 +#define TK_FOREIGN 110 +#define TK_DROP 111 +#define TK_UNION 112 +#define TK_ALL 113 +#define TK_EXCEPT 114 +#define TK_INTERSECT 115 +#define TK_SELECT 116 +#define TK_DISTINCT 117 +#define TK_DOT 118 +#define TK_FROM 119 +#define TK_JOIN 120 +#define TK_USING 121 +#define TK_ORDER 122 +#define TK_GROUP 123 +#define TK_HAVING 124 +#define TK_LIMIT 125 +#define TK_WHERE 126 +#define TK_INTO 127 +#define TK_VALUES 128 +#define TK_INTEGER 129 +#define TK_FLOAT 130 +#define TK_BLOB 131 +#define TK_REGISTER 132 +#define TK_VARIABLE 133 +#define TK_CASE 134 +#define TK_WHEN 135 +#define TK_THEN 136 +#define TK_ELSE 137 +#define TK_INDEX 138 +#define TK_ALTER 139 +#define TK_ADD 140 +#define TK_TO_TEXT 141 +#define TK_TO_BLOB 142 +#define TK_TO_NUMERIC 143 +#define TK_TO_INT 144 +#define TK_TO_REAL 145 +#define TK_ISNOT 146 +#define TK_END_OF_FILE 147 +#define TK_ILLEGAL 148 +#define TK_SPACE 149 +#define TK_UNCLOSED_STRING 150 +#define TK_FUNCTION 151 +#define TK_COLUMN 152 +#define TK_AGG_FUNCTION 153 +#define TK_AGG_COLUMN 154 +#define TK_CONST_FUNC 155 +#define TK_UMINUS 156 +#define TK_UPLUS 157 + +/************** End of parse.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +#include +#include +#include +#include +#include + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite_int64 +# define float sqlite_int64 +# define LONGDOUBLE_TYPE sqlite_int64 +# ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +# endif +# define SQLITE_OMIT_DATETIME_FUNCS 1 +# define SQLITE_OMIT_TRACE 1 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +# undef SQLITE_HAVE_ISNAN +#endif +#ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (1e99) +#endif + +/* +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 +** afterward. Having this macro allows us to cause the C compiler +** to omit code used by TEMP tables without messy #ifndef statements. +*/ +#ifdef SQLITE_OMIT_TEMPDB +#define OMIT_TEMPDB 1 +#else +#define OMIT_TEMPDB 0 +#endif + +/* +** The "file format" number is an integer that is incremented whenever +** the VDBE-level file format changes. The following macros define the +** the default file format for new databases and the maximum file format +** that the library can read. +*/ +#define SQLITE_MAX_FILE_FORMAT 4 +#ifndef SQLITE_DEFAULT_FILE_FORMAT +# define SQLITE_DEFAULT_FILE_FORMAT 4 +#endif + +/* +** Determine whether triggers are recursive by default. This can be +** changed at run-time using a pragma. +*/ +#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS +# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 +#endif + +/* +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** on the command-line +*/ +#ifndef SQLITE_TEMP_STORE +# define SQLITE_TEMP_STORE 1 +# define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */ +#endif + +/* +** GCC does not define the offsetof() macro so we'll have to do it +** ourselves. +*/ +#ifndef offsetof +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +#endif + +/* +** Macros to compute minimum and maximum of two numbers. +*/ +#define MIN(A,B) ((A)<(B)?(A):(B)) +#define MAX(A,B) ((A)>(B)?(A):(B)) + +/* +** Check to see if this machine uses EBCDIC. (Yes, believe it or +** not, there are still machines out there that use EBCDIC.) +*/ +#if 'A' == '\301' +# define SQLITE_EBCDIC 1 +#else +# define SQLITE_ASCII 1 +#endif + +/* +** Integers of known sizes. These typedefs might change for architectures +** where the sizes very. Preprocessor macros are available so that the +** types can be conveniently redefined at compile-type. Like this: +** +** cc '-DUINTPTR_TYPE=long long int' ... +*/ +#ifndef UINT32_TYPE +# ifdef HAVE_UINT32_T +# define UINT32_TYPE uint32_t +# else +# define UINT32_TYPE unsigned int +# endif +#endif +#ifndef UINT16_TYPE +# ifdef HAVE_UINT16_T +# define UINT16_TYPE uint16_t +# else +# define UINT16_TYPE unsigned short int +# endif +#endif +#ifndef INT16_TYPE +# ifdef HAVE_INT16_T +# define INT16_TYPE int16_t +# else +# define INT16_TYPE short int +# endif +#endif +#ifndef UINT8_TYPE +# ifdef HAVE_UINT8_T +# define UINT8_TYPE uint8_t +# else +# define UINT8_TYPE unsigned char +# endif +#endif +#ifndef INT8_TYPE +# ifdef HAVE_INT8_T +# define INT8_TYPE int8_t +# else +# define INT8_TYPE signed char +# endif +#endif +#ifndef LONGDOUBLE_TYPE +# define LONGDOUBLE_TYPE long double +#endif +typedef sqlite_int64 i64; /* 8-byte signed integer */ +typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ +typedef INT16_TYPE i16; /* 2-byte signed integer */ +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ +typedef INT8_TYPE i8; /* 1-byte signed integer */ + +/* +** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value +** that can be stored in a u32 without loss of data. The value +** is 0x00000000ffffffff. But because of quirks of some compilers, we +** have to specify the value in the less intuitive manner shown: +*/ +#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) + +/* +** The datatype used to store estimates of the number of rows in a +** table or index. This is an unsigned integer type. For 99.9% of +** the world, a 32-bit integer is sufficient. But a 64-bit integer +** can be used at compile-time if desired. +*/ +#ifdef SQLITE_64BIT_STATS + typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */ +#else + typedef u32 tRowcnt; /* 32-bit is the default */ +#endif + +/* +** Macros to determine whether the machine is big or little endian, +** evaluated at runtime. +*/ +#ifdef SQLITE_AMALGAMATION +SQLITE_PRIVATE const int sqlite3one = 1; +#else +SQLITE_PRIVATE const int sqlite3one; +#endif +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ + || defined(__x86_64) || defined(__x86_64__) +# define SQLITE_BIGENDIAN 0 +# define SQLITE_LITTLEENDIAN 1 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else +# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) +#endif + +/* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + +/* +** Round up a number to the next larger multiple of 8. This is used +** to force 8-byte alignment on 64-bit architectures. +*/ +#define ROUND8(x) (((x)+7)&~7) + +/* +** Round down to the nearest multiple of 8 +*/ +#define ROUNDDOWN8(x) ((x)&~7) + +/* +** Assert that the pointer X is aligned to an 8-byte boundary. This +** macro is used only within assert() to verify that the code gets +** all alignment restrictions correct. +** +** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the +** underlying malloc() implemention might return us 4-byte aligned +** pointers. In that case, only verify 4-byte alignment. +*/ +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) +#else +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) +#endif + +/* +** Disable MMAP on platforms where it is known to not work +*/ +#if defined(__OpenBSD__) || defined(__QNXNTO__) +# undef SQLITE_MAX_MMAP_SIZE +# define SQLITE_MAX_MMAP_SIZE 0 +#endif + +/* +** Default maximum size of memory used by memory-mapped I/O in the VFS +*/ +#ifdef __APPLE__ +# include +# if TARGET_OS_IPHONE +# undef SQLITE_MAX_MMAP_SIZE +# define SQLITE_MAX_MMAP_SIZE 0 +# endif +#endif +#ifndef SQLITE_MAX_MMAP_SIZE +# if defined(__linux__) \ + || defined(_WIN32) \ + || (defined(__APPLE__) && defined(__MACH__)) \ + || defined(__sun) +# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */ +# else +# define SQLITE_MAX_MMAP_SIZE 0 +# endif +# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */ +#endif + +/* +** The default MMAP_SIZE is zero on all platforms. Or, even if a larger +** default MMAP_SIZE is specified at compile-time, make sure that it does +** not exceed the maximum mmap size. +*/ +#ifndef SQLITE_DEFAULT_MMAP_SIZE +# define SQLITE_DEFAULT_MMAP_SIZE 0 +# define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */ +#endif +#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE +# undef SQLITE_DEFAULT_MMAP_SIZE +# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE +#endif + +/* +** An instance of the following structure is used to store the busy-handler +** callback for a given sqlite handle. +** +** The sqlite.busyHandler member of the sqlite struct contains the busy +** callback for the database handle. Each pager opened via the sqlite +** handle is passed a pointer to sqlite.busyHandler. The busy-handler +** callback is currently invoked only from within pager.c. +*/ +typedef struct BusyHandler BusyHandler; +struct BusyHandler { + int (*xFunc)(void *,int); /* The busy callback */ + void *pArg; /* First arg to busy callback */ + int nBusy; /* Incremented with each busy call */ +}; + +/* +** Name of the master database table. The master database table +** is a special table that holds the names and attributes of all +** user tables and indices. +*/ +#define MASTER_NAME "sqlite_master" +#define TEMP_MASTER_NAME "sqlite_temp_master" + +/* +** The root-page of the master database table. +*/ +#define MASTER_ROOT 1 + +/* +** The name of the schema table. +*/ +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + +/* +** A convenience macro that returns the number of elements in +** an array. +*/ +#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) + +/* +** Determine if the argument is a power of two +*/ +#define IsPowerOfTwo(X) (((X)&((X)-1))==0) + +/* +** The following value as a destructor means to use sqlite3DbFree(). +** The sqlite3DbFree() routine requires two parameters instead of the +** one parameter that destructors normally want. So we have to introduce +** this magic value that the code knows to handle differently. Any +** pointer will work here as long as it is distinct from SQLITE_STATIC +** and SQLITE_TRANSIENT. +*/ +#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) + +/* +** When SQLITE_OMIT_WSD is defined, it means that the target platform does +** not support Writable Static Data (WSD) such as global and static variables. +** All variables must either be on the stack or dynamically allocated from +** the heap. When WSD is unsupported, the variable declarations scattered +** throughout the SQLite code must become constants instead. The SQLITE_WSD +** macro is used for this purpose. And instead of referencing the variable +** directly, we use its constant as a key to lookup the run-time allocated +** buffer that holds real variable. The constant is also the initializer +** for the run-time allocated buffer. +** +** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL +** macros become no-ops and have zero performance impact. +*/ +#ifdef SQLITE_OMIT_WSD + #define SQLITE_WSD const + #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) + #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) +SQLITE_API int sqlite3_wsd_init(int N, int J); +SQLITE_API void *sqlite3_wsd_find(void *K, int L); +#else + #define SQLITE_WSD + #define GLOBAL(t,v) v + #define sqlite3GlobalConfig sqlite3Config +#endif + +/* +** The following macros are used to suppress compiler warnings and to +** make it clear to human readers when a function parameter is deliberately +** left unused within the body of a function. This usually happens when +** a function is called via a function pointer. For example the +** implementation of an SQL aggregate step callback may not use the +** parameter indicating the number of arguments passed to the aggregate, +** if it knows that this is enforced elsewhere. +** +** When a function parameter is not used at all within the body of a function, +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. +** However, these macros may also be used to suppress warnings related to +** parameters that may or may not be used depending on compilation options. +** For example those parameters only used in assert() statements. In these +** cases the parameters are named as per the usual conventions. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) + +/* +** Forward references to structures +*/ +typedef struct AggInfo AggInfo; +typedef struct AuthContext AuthContext; +typedef struct AutoincInfo AutoincInfo; +typedef struct Bitvec Bitvec; +typedef struct CollSeq CollSeq; +typedef struct Column Column; +typedef struct Db Db; +typedef struct Schema Schema; +typedef struct Expr Expr; +typedef struct ExprList ExprList; +typedef struct ExprSpan ExprSpan; +typedef struct FKey FKey; +typedef struct FuncDestructor FuncDestructor; +typedef struct FuncDef FuncDef; +typedef struct FuncDefHash FuncDefHash; +typedef struct IdList IdList; +typedef struct Index Index; +typedef struct IndexSample IndexSample; +typedef struct KeyClass KeyClass; +typedef struct KeyInfo KeyInfo; +typedef struct Lookaside Lookaside; +typedef struct LookasideSlot LookasideSlot; +typedef struct Module Module; +typedef struct NameContext NameContext; +typedef struct Parse Parse; +typedef struct RowSet RowSet; +typedef struct Savepoint Savepoint; +typedef struct Select Select; +typedef struct SelectDest SelectDest; +typedef struct SrcList SrcList; +typedef struct StrAccum StrAccum; +typedef struct Table Table; +typedef struct TableLock TableLock; +typedef struct Token Token; +typedef struct Trigger Trigger; +typedef struct TriggerPrg TriggerPrg; +typedef struct TriggerStep TriggerStep; +typedef struct UnpackedRecord UnpackedRecord; +typedef struct VTable VTable; +typedef struct VtabCtx VtabCtx; +typedef struct Walker Walker; +typedef struct WhereInfo WhereInfo; + +/* +** Defer sourcing vdbe.h and btree.h until after the "u8" and +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque +** pointer types (i.e. FuncDef) defined above. +*/ +/************** Include btree.h in the middle of sqliteInt.h *****************/ +/************** Begin file btree.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite B-Tree file +** subsystem. See comments in the source code for a detailed description +** of what each interface routine does. +*/ +#ifndef _BTREE_H_ +#define _BTREE_H_ + +/* TODO: This definition is just included so other modules compile. It +** needs to be revisited. +*/ +#define SQLITE_N_BTREE_META 10 + +/* +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise +** it must be turned on for each database using "PRAGMA auto_vacuum = 1". +*/ +#ifndef SQLITE_DEFAULT_AUTOVACUUM + #define SQLITE_DEFAULT_AUTOVACUUM 0 +#endif + +#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ +#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ +#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ + +/* +** Forward declarations of structure +*/ +typedef struct Btree Btree; +typedef struct BtCursor BtCursor; +typedef struct BtShared BtShared; + + +SQLITE_PRIVATE int sqlite3BtreeOpen( + sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ + const char *zFilename, /* Name of database file to open */ + sqlite3 *db, /* Associated database connection */ + Btree **ppBtree, /* Return open Btree* here */ + int flags, /* Flags */ + int vfsFlags /* Flags passed through to VFS open */ +); + +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the +** following values. +** +** NOTE: These values must match the corresponding PAGER_ values in +** pager.h. +*/ +#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ +#define BTREE_MEMORY 2 /* This is an in-memory DB */ +#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ +#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ + +SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); +SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned); +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) +SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); +#endif +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); + +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); + +SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); + +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR +** of the flags shown below. +** +** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. +** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data +** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With +** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored +** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL +** indices.) +*/ +#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ +#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ + +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); + +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); + +SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); + +/* +** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta +** should be one of the following values. The integer values are assigned +** to constants so that the offset of the corresponding field in an +** SQLite database header may be found using the following formula: +** +** offset = 36 + (idx * 4) +** +** For example, the free-page-count field is located at byte offset 36 of +** the database file header. The incr-vacuum-flag field is located at +** byte offset 64 (== 36+4*7). +*/ +#define BTREE_FREE_PAGE_COUNT 0 +#define BTREE_SCHEMA_VERSION 1 +#define BTREE_FILE_FORMAT 2 +#define BTREE_DEFAULT_CACHE_SIZE 3 +#define BTREE_LARGEST_ROOT_PAGE 4 +#define BTREE_TEXT_ENCODING 5 +#define BTREE_USER_VERSION 6 +#define BTREE_INCR_VACUUM 7 +#define BTREE_APPLICATION_ID 8 + +/* +** Values that may be OR'd together to form the second argument of an +** sqlite3BtreeCursorHints() call. +*/ +#define BTREE_BULKLOAD 0x00000001 + +SQLITE_PRIVATE int sqlite3BtreeCursor( + Btree*, /* BTree containing table to open */ + int iTable, /* Index of root page */ + int wrFlag, /* 1 for writing. 0 for read-only */ + struct KeyInfo*, /* First argument to compare function */ + BtCursor *pCursor /* Space to write cursor structure */ +); +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); + +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( + BtCursor*, + UnpackedRecord *pUnKey, + i64 intKey, + int bias, + int *pRes +); +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, + const void *pData, int nData, + int nZero, int bias, int seekResult); +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); +SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); + +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); +SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); + +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); +SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask); + +#ifndef NDEBUG +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); +#endif + +#ifndef SQLITE_OMIT_BTREECOUNT +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); +SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); +#endif + +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); +#endif + +/* +** If we are not using shared cache, then there is no need to +** use mutexes to access the BtShared structures. So make the +** Enter and Leave procedures no-ops. +*/ +#ifndef SQLITE_OMIT_SHARED_CACHE +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); +#else +# define sqlite3BtreeEnter(X) +# define sqlite3BtreeEnterAll(X) +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE +SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); +SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); +#ifndef NDEBUG + /* These routines are used inside assert() statements only. */ +SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); +SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); +SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); +#endif +#else + +# define sqlite3BtreeSharable(X) 0 +# define sqlite3BtreeLeave(X) +# define sqlite3BtreeEnterCursor(X) +# define sqlite3BtreeLeaveCursor(X) +# define sqlite3BtreeLeaveAll(X) + +# define sqlite3BtreeHoldsMutex(X) 1 +# define sqlite3BtreeHoldsAllMutexes(X) 1 +# define sqlite3SchemaMutexHeld(X,Y,Z) 1 +#endif + + +#endif /* _BTREE_H_ */ + +/************** End of btree.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include vdbe.h in the middle of sqliteInt.h ******************/ +/************** Begin file vdbe.h ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Header file for the Virtual DataBase Engine (VDBE) +** +** This header defines the interface to the virtual database engine +** or VDBE. The VDBE implements an abstract machine that runs a +** simple program to access and modify the underlying database. +*/ +#ifndef _SQLITE_VDBE_H_ +#define _SQLITE_VDBE_H_ +/* #include */ + +/* +** A single VDBE is an opaque structure named "Vdbe". Only routines +** in the source file sqliteVdbe.c are allowed to see the insides +** of this structure. +*/ +typedef struct Vdbe Vdbe; + +/* +** The names of the following types declared in vdbeInt.h are required +** for the VdbeOp definition. +*/ +typedef struct Mem Mem; +typedef struct SubProgram SubProgram; + +/* +** A single instruction of the virtual machine has an opcode +** and as many as three operands. The instruction is recorded +** as an instance of the following structure: +*/ +struct VdbeOp { + u8 opcode; /* What operation to perform */ + signed char p4type; /* One of the P4_xxx constants for p4 */ + u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */ + u8 p5; /* Fifth parameter is an unsigned character */ + int p1; /* First operand */ + int p2; /* Second parameter (often the jump destination) */ + int p3; /* The third parameter */ + union { /* fourth parameter */ + int i; /* Integer value if p4type==P4_INT32 */ + void *p; /* Generic pointer */ + char *z; /* Pointer to data for string (char array) types */ + i64 *pI64; /* Used when p4type is P4_INT64 */ + double *pReal; /* Used when p4type is P4_REAL */ + FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ + CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ + Mem *pMem; /* Used when p4type is P4_MEM */ + VTable *pVtab; /* Used when p4type is P4_VTAB */ + KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ + int *ai; /* Used when p4type is P4_INTARRAY */ + SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ + int (*xAdvance)(BtCursor *, int *); + } p4; +#ifdef SQLITE_DEBUG + char *zComment; /* Comment to improve readability */ +#endif +#ifdef VDBE_PROFILE + int cnt; /* Number of times this instruction was executed */ + u64 cycles; /* Total time spent executing this instruction */ +#endif +}; +typedef struct VdbeOp VdbeOp; + + +/* +** A sub-routine used to implement a trigger program. +*/ +struct SubProgram { + VdbeOp *aOp; /* Array of opcodes for sub-program */ + int nOp; /* Elements in aOp[] */ + int nMem; /* Number of memory cells required */ + int nCsr; /* Number of cursors required */ + int nOnce; /* Number of OP_Once instructions */ + void *token; /* id that may be used to recursive triggers */ + SubProgram *pNext; /* Next sub-program already visited */ +}; + +/* +** A smaller version of VdbeOp used for the VdbeAddOpList() function because +** it takes up less space. +*/ +struct VdbeOpList { + u8 opcode; /* What operation to perform */ + signed char p1; /* First operand */ + signed char p2; /* Second parameter (often the jump destination) */ + signed char p3; /* Third parameter */ +}; +typedef struct VdbeOpList VdbeOpList; + +/* +** Allowed values of VdbeOp.p4type +*/ +#define P4_NOTUSED 0 /* The P4 parameter is not used */ +#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ +#define P4_STATIC (-2) /* Pointer to a static string */ +#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ +#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ +#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ +#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ +#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ +#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ +#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ +#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ +#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ +#define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ + +/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure +** is made. That copy is freed when the Vdbe is finalized. But if the +** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still +** gets freed when the Vdbe is finalized so it still should be obtained +** from a single sqliteMalloc(). But no copy is made and the calling +** function should *not* try to free the KeyInfo. +*/ +#define P4_KEYINFO_HANDOFF (-16) +#define P4_KEYINFO_STATIC (-17) + +/* +** The Vdbe.aColName array contains 5n Mem structures, where n is the +** number of columns of data returned by the statement. +*/ +#define COLNAME_NAME 0 +#define COLNAME_DECLTYPE 1 +#define COLNAME_DATABASE 2 +#define COLNAME_TABLE 3 +#define COLNAME_COLUMN 4 +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ +#else +# ifdef SQLITE_OMIT_DECLTYPE +# define COLNAME_N 1 /* Store only the name */ +# else +# define COLNAME_N 2 /* Store the name and decltype */ +# endif +#endif + +/* +** The following macro converts a relative address in the p2 field +** of a VdbeOp structure into a negative number so that +** sqlite3VdbeAddOpList() knows that the address is relative. Calling +** the macro again restores the address. +*/ +#define ADDR(X) (-1-(X)) + +/* +** The makefile scans the vdbe.c source file and creates the "opcodes.h" +** header file that defines a number for each opcode used by the VDBE. +*/ +/************** Include opcodes.h in the middle of vdbe.h ********************/ +/************** Begin file opcodes.h *****************************************/ +/* Automatically generated. Do not edit */ +/* See the mkopcodeh.awk script for details */ +#define OP_Function 1 +#define OP_Savepoint 2 +#define OP_AutoCommit 3 +#define OP_Transaction 4 +#define OP_SorterNext 5 +#define OP_Prev 6 +#define OP_Next 7 +#define OP_AggStep 8 +#define OP_Checkpoint 9 +#define OP_JournalMode 10 +#define OP_Vacuum 11 +#define OP_VFilter 12 +#define OP_VUpdate 13 +#define OP_Goto 14 +#define OP_Gosub 15 +#define OP_Return 16 +#define OP_Yield 17 +#define OP_HaltIfNull 18 +#define OP_Not 19 /* same as TK_NOT */ +#define OP_Halt 20 +#define OP_Integer 21 +#define OP_Int64 22 +#define OP_String 23 +#define OP_Null 24 +#define OP_Blob 25 +#define OP_Variable 26 +#define OP_Move 27 +#define OP_Copy 28 +#define OP_SCopy 29 +#define OP_ResultRow 30 +#define OP_CollSeq 31 +#define OP_AddImm 32 +#define OP_MustBeInt 33 +#define OP_RealAffinity 34 +#define OP_Permutation 35 +#define OP_Compare 36 +#define OP_Jump 37 +#define OP_Once 38 +#define OP_If 39 +#define OP_IfNot 40 +#define OP_Column 41 +#define OP_Affinity 42 +#define OP_MakeRecord 43 +#define OP_Count 44 +#define OP_ReadCookie 45 +#define OP_SetCookie 46 +#define OP_VerifyCookie 47 +#define OP_OpenRead 48 +#define OP_OpenWrite 49 +#define OP_OpenAutoindex 50 +#define OP_OpenEphemeral 51 +#define OP_SorterOpen 52 +#define OP_OpenPseudo 53 +#define OP_Close 54 +#define OP_SeekLt 55 +#define OP_SeekLe 56 +#define OP_SeekGe 57 +#define OP_SeekGt 58 +#define OP_Seek 59 +#define OP_NotFound 60 +#define OP_Found 61 +#define OP_IsUnique 62 +#define OP_NotExists 63 +#define OP_Sequence 64 +#define OP_NewRowid 65 +#define OP_Insert 66 +#define OP_InsertInt 67 +#define OP_Or 68 /* same as TK_OR */ +#define OP_And 69 /* same as TK_AND */ +#define OP_Delete 70 +#define OP_ResetCount 71 +#define OP_SorterCompare 72 +#define OP_IsNull 73 /* same as TK_ISNULL */ +#define OP_NotNull 74 /* same as TK_NOTNULL */ +#define OP_Ne 75 /* same as TK_NE */ +#define OP_Eq 76 /* same as TK_EQ */ +#define OP_Gt 77 /* same as TK_GT */ +#define OP_Le 78 /* same as TK_LE */ +#define OP_Lt 79 /* same as TK_LT */ +#define OP_Ge 80 /* same as TK_GE */ +#define OP_SorterData 81 +#define OP_BitAnd 82 /* same as TK_BITAND */ +#define OP_BitOr 83 /* same as TK_BITOR */ +#define OP_ShiftLeft 84 /* same as TK_LSHIFT */ +#define OP_ShiftRight 85 /* same as TK_RSHIFT */ +#define OP_Add 86 /* same as TK_PLUS */ +#define OP_Subtract 87 /* same as TK_MINUS */ +#define OP_Multiply 88 /* same as TK_STAR */ +#define OP_Divide 89 /* same as TK_SLASH */ +#define OP_Remainder 90 /* same as TK_REM */ +#define OP_Concat 91 /* same as TK_CONCAT */ +#define OP_RowKey 92 +#define OP_BitNot 93 /* same as TK_BITNOT */ +#define OP_String8 94 /* same as TK_STRING */ +#define OP_RowData 95 +#define OP_Rowid 96 +#define OP_NullRow 97 +#define OP_Last 98 +#define OP_SorterSort 99 +#define OP_Sort 100 +#define OP_Rewind 101 +#define OP_SorterInsert 102 +#define OP_IdxInsert 103 +#define OP_IdxDelete 104 +#define OP_IdxRowid 105 +#define OP_IdxLT 106 +#define OP_IdxGE 107 +#define OP_Destroy 108 +#define OP_Clear 109 +#define OP_CreateIndex 110 +#define OP_CreateTable 111 +#define OP_ParseSchema 112 +#define OP_LoadAnalysis 113 +#define OP_DropTable 114 +#define OP_DropIndex 115 +#define OP_DropTrigger 116 +#define OP_IntegrityCk 117 +#define OP_RowSetAdd 118 +#define OP_RowSetRead 119 +#define OP_RowSetTest 120 +#define OP_Program 121 +#define OP_Param 122 +#define OP_FkCounter 123 +#define OP_FkIfZero 124 +#define OP_MemMax 125 +#define OP_IfPos 126 +#define OP_IfNeg 127 +#define OP_IfZero 128 +#define OP_AggFinal 129 +#define OP_Real 130 /* same as TK_FLOAT */ +#define OP_IncrVacuum 131 +#define OP_Expire 132 +#define OP_TableLock 133 +#define OP_VBegin 134 +#define OP_VCreate 135 +#define OP_VDestroy 136 +#define OP_VOpen 137 +#define OP_VColumn 138 +#define OP_VNext 139 +#define OP_VRename 140 +#define OP_ToText 141 /* same as TK_TO_TEXT */ +#define OP_ToBlob 142 /* same as TK_TO_BLOB */ +#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ +#define OP_ToInt 144 /* same as TK_TO_INT */ +#define OP_ToReal 145 /* same as TK_TO_REAL */ +#define OP_Pagecount 146 +#define OP_MaxPgcnt 147 +#define OP_Trace 148 +#define OP_Noop 149 +#define OP_Explain 150 + + +/* Properties such as "out2" or "jump" that are specified in +** comments following the "case" for each opcode in the vdbe.c +** are encoded into bitvectors as follows: +*/ +#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ +#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ +#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ +#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ +#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ +#define OPFLG_OUT2 0x0020 /* out2: P2 is an output */ +#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */ +#define OPFLG_INITIALIZER {\ +/* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\ +/* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\ +/* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\ +/* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\ +/* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\ +/* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\ +/* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\ +/* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\ +/* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\ +/* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ +/* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\ +/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\ +/* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\ +/* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\ +/* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\ +/* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\ +/* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\ +/* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\ +/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,} + +/************** End of opcodes.h *********************************************/ +/************** Continuing where we left off in vdbe.h ***********************/ + +/* +** Prototypes for the VDBE interface. See comments on the implementation +** for a description of what each of these routines does. +*/ +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); +SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr); +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); +SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); +#endif +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); +#ifndef SQLITE_OMIT_TRACE +SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); +#endif + +SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); +SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); + +#ifndef SQLITE_OMIT_TRIGGER +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); +#endif + + +#ifndef NDEBUG +SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); +# define VdbeComment(X) sqlite3VdbeComment X +SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); +# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +#else +# define VdbeComment(X) +# define VdbeNoopComment(X) +#endif + +#endif + +/************** End of vdbe.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pager.h in the middle of sqliteInt.h *****************/ +/************** Begin file pager.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. The page cache subsystem reads and writes a file a page +** at a time and provides a journal for rollback. +*/ + +#ifndef _PAGER_H_ +#define _PAGER_H_ + +/* +** Default maximum size for persistent journal files. A negative +** value means no limit. This value may be overridden using the +** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". +*/ +#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 +#endif + +/* +** The type used to represent a page number. The first page in a file +** is called page 1. 0 is used to represent "not a page". +*/ +typedef u32 Pgno; + +/* +** Each open file is managed by a separate instance of the "Pager" structure. +*/ +typedef struct Pager Pager; + +/* +** Handle type for pages. +*/ +typedef struct PgHdr DbPage; + +/* +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is +** reserved for working around a windows/posix incompatibility). It is +** used in the journal to signify that the remainder of the journal file +** is devoted to storing a master journal name - there are no more pages to +** roll back. See comments for function writeMasterJournal() in pager.c +** for details. +*/ +#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) + +/* +** Allowed values for the flags parameter to sqlite3PagerOpen(). +** +** NOTE: These values must match the corresponding BTREE_ values in btree.h. +*/ +#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ +#define PAGER_MEMORY 0x0002 /* In-memory database */ + +/* +** Valid values for the second argument to sqlite3PagerLockingMode(). +*/ +#define PAGER_LOCKINGMODE_QUERY -1 +#define PAGER_LOCKINGMODE_NORMAL 0 +#define PAGER_LOCKINGMODE_EXCLUSIVE 1 + +/* +** Numeric constants that encode the journalmode. +*/ +#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ +#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ +#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ +#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ +#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ +#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ +#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ + +/* +** Flags that make up the mask passed to sqlite3PagerAcquire(). +*/ +#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ +#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ + +/* +** Flags for sqlite3PagerSetFlags() +*/ +#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */ +#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */ +#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */ +#define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */ +#define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */ +#define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */ +#define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */ +#define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */ + +/* +** The remainder of this file contains the declarations of the functions +** that make up the Pager sub-system API. See source code comments for +** a detailed description of each routine. +*/ + +/* Open and close a Pager connection. */ +SQLITE_PRIVATE int sqlite3PagerOpen( + sqlite3_vfs*, + Pager **ppPager, + const char*, + int, + int, + int, + void(*)(DbPage*) +); +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); + +/* Functions used to configure a Pager object. */ +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); +SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); +SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned); +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); + +/* Functions used to obtain and release page references. */ +SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); +SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); + +/* Operations on page references. */ +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); +SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); + +/* Functions used to manage pager transactions and savepoints. */ +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); +SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); +SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); + +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); +SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); +SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); +#endif + +#ifdef SQLITE_ENABLE_ZIPVFS +SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); +#endif + +/* Functions used to query pager state and configuration. */ +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*); +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); +SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); +SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); +SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *); +SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); + +/* Functions used to truncate the database file. */ +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); + +#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) +SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); +#endif + +/* Functions to support testing and debugging. */ +#if !defined(NDEBUG) || defined(SQLITE_TEST) +SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); +SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); +#endif +#ifdef SQLITE_TEST +SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); +SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); + void disable_simulated_io_errors(void); + void enable_simulated_io_errors(void); +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +#endif /* _PAGER_H_ */ + +/************** End of pager.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pcache.h in the middle of sqliteInt.h ****************/ +/************** Begin file pcache.h ******************************************/ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. +*/ + +#ifndef _PCACHE_H_ + +typedef struct PgHdr PgHdr; +typedef struct PCache PCache; + +/* +** Every page in the cache is controlled by an instance of the following +** structure. +*/ +struct PgHdr { + sqlite3_pcache_page *pPage; /* Pcache object page handle */ + void *pData; /* Page data */ + void *pExtra; /* Extra content */ + PgHdr *pDirty; /* Transient list of dirty pages */ + Pager *pPager; /* The pager this page is part of */ + Pgno pgno; /* Page number for this page */ +#ifdef SQLITE_CHECK_PAGES + u32 pageHash; /* Hash of page content */ +#endif + u16 flags; /* PGHDR flags defined below */ + + /********************************************************************** + ** Elements above are public. All that follows is private to pcache.c + ** and should not be accessed by other modules. + */ + i16 nRef; /* Number of users of this page */ + PCache *pCache; /* Cache that owns this page */ + + PgHdr *pDirtyNext; /* Next element in list of dirty pages */ + PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ +}; + +/* Bit values for PgHdr.flags */ +#define PGHDR_DIRTY 0x002 /* Page has changed */ +#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before + ** writing this page to the database */ +#define PGHDR_NEED_READ 0x008 /* Content is unread */ +#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ +#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ + +#define PGHDR_MMAP 0x040 /* This is an mmap page object */ + +/* Initialize and shutdown the page cache subsystem */ +SQLITE_PRIVATE int sqlite3PcacheInitialize(void); +SQLITE_PRIVATE void sqlite3PcacheShutdown(void); + +/* Page cache buffer management: +** These routines implement SQLITE_CONFIG_PAGECACHE. +*/ +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); + +/* Create a new pager cache. +** Under memory stress, invoke xStress to try to make pages clean. +** Only clean and unpinned pages can be reclaimed. +*/ +SQLITE_PRIVATE void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *pToInit /* Preallocated space for the PCache */ +); + +/* Modify the page-size after the cache has been created. */ +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int); + +/* Return the size in bytes of a PCache object. Used to preallocate +** storage space. +*/ +SQLITE_PRIVATE int sqlite3PcacheSize(void); + +/* One release per successful fetch. Page is pinned until released. +** Reference counted. +*/ +SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); + +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ + +/* Change a page number. Used by incr-vacuum. */ +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); + +/* Remove all pages with pgno>x. Reset the cache if x==0 */ +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); + +/* Get a list of all dirty pages in the cache, sorted by page number */ +SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); + +/* Reset and close the cache object */ +SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); + +/* Clear flags from pages of the page cache */ +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); + +/* Discard the contents of the cache */ +SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); + +/* Return the total number of outstanding page references */ +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); + +/* Increment the reference count of an existing page */ +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); + +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); + +/* Return the total number of pages stored in the cache */ +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* Iterate through all dirty pages currently stored in the cache. This +** interface is only available if SQLITE_CHECK_PAGES is defined when the +** library is built. +*/ +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); +#endif + +/* Set and get the suggested cache-size for the specified pager-cache. +** +** If no global maximum is configured, then the system attempts to limit +** the total number of pages cached by purgeable pager-caches to the sum +** of the suggested cache-sizes. +*/ +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); +#endif + +/* Free up as much memory as possible from the page cache */ +SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* Try to return memory used by the pcache module to the main memory heap */ +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); +#endif + +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); + +#endif /* _PCACHE_H_ */ + +/************** End of pcache.h **********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/************** Include os.h in the middle of sqliteInt.h ********************/ +/************** Begin file os.h **********************************************/ +/* +** 2001 September 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file (together with is companion C source-code file +** "os.c") attempt to abstract the underlying operating system so that +** the SQLite library will work on both POSIX and windows systems. +** +** This header file is #include-ed by sqliteInt.h and thus ends up +** being included by every source file. +*/ +#ifndef _SQLITE_OS_H_ +#define _SQLITE_OS_H_ + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# endif +# else +# define SQLITE_OS_UNIX 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +#if SQLITE_OS_WIN +# include +#endif + +/* +** Determine if we are dealing with Windows NT. +** +** We ought to be able to determine if we are compiling for win98 or winNT +** using the _WIN32_WINNT macro as follows: +** +** #if defined(_WIN32_WINNT) +** # define SQLITE_OS_WINNT 1 +** #else +** # define SQLITE_OS_WINNT 0 +** #endif +** +** However, vs2005 does not set _WIN32_WINNT by default, as it ought to, +** so the above test does not work. We'll just assume that everything is +** winNT unless the programmer explicitly says otherwise by setting +** SQLITE_OS_WINNT to 0. +*/ +#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) +# define SQLITE_OS_WINNT 1 +#endif + +/* +** Determine if we are dealing with WindowsCE - which has a much +** reduced API. +*/ +#if defined(_WIN32_WCE) +# define SQLITE_OS_WINCE 1 +#else +# define SQLITE_OS_WINCE 0 +#endif + +/* +** Determine if we are dealing with WinRT, which provides only a subset of +** the full Win32 API. +*/ +#if !defined(SQLITE_OS_WINRT) +# define SQLITE_OS_WINRT 0 +#endif + +/* If the SET_FULLSYNC macro is not defined above, then make it +** a no-op +*/ +#ifndef SET_FULLSYNC +# define SET_FULLSYNC(x,y) +#endif + +/* +** The default size of a disk sector +*/ +#ifndef SQLITE_DEFAULT_SECTOR_SIZE +# define SQLITE_DEFAULT_SECTOR_SIZE 4096 +#endif + +/* +** Temporary files are named starting with this prefix followed by 16 random +** alphanumeric characters, and no file extension. They are stored in the +** OS's standard temporary file directory, and are deleted prior to exit. +** If sqlite is being embedded in another program, you may wish to change the +** prefix to reflect your program's name, so that if your program exits +** prematurely, old temporary files can be easily identified. This can be done +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. +** +** 2006-10-31: The default prefix used to be "sqlite_". But then +** Mcafee started using SQLite in their anti-virus product and it +** started putting files with the "sqlite" name in the c:/temp folder. +** This annoyed many windows users. Those users would then do a +** Google search for "sqlite", find the telephone numbers of the +** developers and call to wake them up at night and complain. +** For this reason, the default name prefix is changed to be "sqlite" +** spelled backwards. So the temp files are still identified, but +** anybody smart enough to figure out the code is also likely smart +** enough to know that calling the developer will not help get rid +** of the file. +*/ +#ifndef SQLITE_TEMP_FILE_PREFIX +# define SQLITE_TEMP_FILE_PREFIX "etilqs_" +#endif + +/* +** The following values may be passed as the second argument to +** sqlite3OsLock(). The various locks exhibit the following semantics: +** +** SHARED: Any number of processes may hold a SHARED lock simultaneously. +** RESERVED: A single process may hold a RESERVED lock on a file at +** any time. Other processes may hold and obtain new SHARED locks. +** PENDING: A single process may hold a PENDING lock on a file at +** any one time. Existing SHARED locks may persist, but no new +** SHARED locks may be obtained by other processes. +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. +** +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** process that requests an EXCLUSIVE lock may actually obtain a PENDING +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to +** sqlite3OsLock(). +*/ +#define NO_LOCK 0 +#define SHARED_LOCK 1 +#define RESERVED_LOCK 2 +#define PENDING_LOCK 3 +#define EXCLUSIVE_LOCK 4 + +/* +** File Locking Notes: (Mostly about windows but also some info for Unix) +** +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because +** those functions are not available. So we use only LockFile() and +** UnlockFile(). +** +** LockFile() prevents not just writing but also reading by other processes. +** A SHARED_LOCK is obtained by locking a single randomly-chosen +** byte out of a specific range of bytes. The lock byte is obtained at +** random so two separate readers can probably access the file at the +** same time, unless they are unlucky and choose the same lock byte. +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. +** There can only be one writer. A RESERVED_LOCK is obtained by locking +** a single byte of the file that is designated as the reserved lock byte. +** A PENDING_LOCK is obtained by locking a designated byte different from +** the RESERVED_LOCK byte. +** +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, +** which means we can use reader/writer locks. When reader/writer locks +** are used, the lock is placed on the same range of bytes that is used +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme +** will support two or more Win95 readers or two or more WinNT readers. +** But a single Win95 reader will lock out all WinNT readers and a single +** WinNT reader will lock out all other Win95 readers. +** +** The following #defines specify the range of bytes used for locking. +** SHARED_SIZE is the number of bytes available in the pool from which +** a random byte is selected for a shared lock. The pool of bytes for +** shared locks begins at SHARED_FIRST. +** +** The same locking strategy and +** byte ranges are used for Unix. This leaves open the possiblity of having +** clients on win95, winNT, and unix all talking to the same shared file +** and all locking correctly. To do so would require that samba (or whatever +** tool is being used for file sharing) implements locks correctly between +** windows and unix. I'm guessing that isn't likely to happen, but by +** using the same locking range we are at least open to the possibility. +** +** Locking in windows is manditory. For this reason, we cannot store +** actual data in the bytes used for locking. The pager never allocates +** the pages involved in locking therefore. SHARED_SIZE is selected so +** that all locks will fit on a single page even at the minimum page size. +** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE +** is set high so that we don't have to allocate an unused page except +** for very large databases. But one should test the page skipping logic +** by setting PENDING_BYTE low and running the entire regression suite. +** +** Changing the value of PENDING_BYTE results in a subtly incompatible +** file format. Depending on how it is changed, you might not notice +** the incompatibility right away, even running a full regression test. +** The default location of PENDING_BYTE is the first byte past the +** 1GB boundary. +** +*/ +#ifdef SQLITE_OMIT_WSD +# define PENDING_BYTE (0x40000000) +#else +# define PENDING_BYTE sqlite3PendingByte +#endif +#define RESERVED_BYTE (PENDING_BYTE+1) +#define SHARED_FIRST (PENDING_BYTE+2) +#define SHARED_SIZE 510 + +/* +** Wrapper around OS specific sqlite3_os_init() function. +*/ +SQLITE_PRIVATE int sqlite3OsInit(void); + +/* +** Functions for accessing sqlite3_file methods +*/ +SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*); +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); +SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); +#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); +SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); +SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *); + + +/* +** Functions for accessing sqlite3_vfs methods +*/ +SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); +SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); + +/* +** Convenience functions for opening and closing files using +** sqlite3_malloc() to obtain space for the file-handle structure. +*/ +SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); + +#endif /* _SQLITE_OS_H_ */ + +/************** End of os.h **************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include mutex.h in the middle of sqliteInt.h *****************/ +/************** Begin file mutex.h *******************************************/ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the common header for all mutex implementations. +** The sqliteInt.h header #includes this file so that it is available +** to all source files. We break it out in an effort to keep the code +** better organized. +** +** NOTE: source files should *not* #include this header file directly. +** Source files should #include the sqliteInt.h file and let that file +** include this one indirectly. +*/ + + +/* +** Figure out what version of the code to use. The choices are +** +** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The +** mutexes implemention cannot be overridden +** at start-time. +** +** SQLITE_MUTEX_NOOP For single-threaded applications. No +** mutual exclusion is provided. But this +** implementation can be overridden at +** start-time. +** +** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. +** +** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. +*/ +#if !SQLITE_THREADSAFE +# define SQLITE_MUTEX_OMIT +#endif +#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) +# if SQLITE_OS_UNIX +# define SQLITE_MUTEX_PTHREADS +# elif SQLITE_OS_WIN +# define SQLITE_MUTEX_W32 +# else +# define SQLITE_MUTEX_NOOP +# endif +#endif + +#ifdef SQLITE_MUTEX_OMIT +/* +** If this is a no-op implementation, implement everything as macros. +*/ +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) +#define sqlite3MutexInit() SQLITE_OK +#define sqlite3MutexEnd() +#define MUTEX_LOGIC(X) +#else +#define MUTEX_LOGIC(X) X +#endif /* defined(SQLITE_MUTEX_OMIT) */ + +/************** End of mutex.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + + +/* +** Each database file to be accessed by the system is an instance +** of the following structure. There are normally two of these structures +** in the sqlite.aDb[] array. aDb[0] is the main database file and +** aDb[1] is the database file used to hold temporary tables. Additional +** databases may be attached. +*/ +struct Db { + char *zName; /* Name of this database */ + Btree *pBt; /* The B*Tree structure for this database file */ + u8 safety_level; /* How aggressive at syncing data to disk */ + Schema *pSchema; /* Pointer to database schema (possibly shared) */ +}; + +/* +** An instance of the following structure stores a database schema. +** +** Most Schema objects are associated with a Btree. The exception is +** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. +** In shared cache mode, a single Schema object can be shared by multiple +** Btrees that refer to the same underlying BtShared object. +** +** Schema objects are automatically deallocated when the last Btree that +** references them is destroyed. The TEMP Schema is manually freed by +** sqlite3_close(). +* +** A thread must be holding a mutex on the corresponding Btree in order +** to access Schema content. This implies that the thread must also be +** holding a mutex on the sqlite3 connection pointer that owns the Btree. +** For a TEMP Schema, only the connection mutex is required. +*/ +struct Schema { + int schema_cookie; /* Database schema version number for this file */ + int iGeneration; /* Generation counter. Incremented with each change */ + Hash tblHash; /* All tables indexed by name */ + Hash idxHash; /* All (named) indices indexed by name */ + Hash trigHash; /* All triggers indexed by name */ + Hash fkeyHash; /* All foreign keys by referenced table name */ + Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ + u8 file_format; /* Schema format version for this file */ + u8 enc; /* Text encoding used by this database */ + u16 flags; /* Flags associated with this schema */ + int cache_size; /* Number of pages to use in the cache */ +}; + +/* +** These macros can be used to test, set, or clear bits in the +** Db.pSchema->flags field. +*/ +#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) +#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) +#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) + +/* +** Allowed values for the DB.pSchema->flags field. +** +** The DB_SchemaLoaded flag is set after the database schema has been +** read into internal hash tables. +** +** DB_UnresetViews means that one or more views have column names that +** have been filled out. If the schema changes, these column names might +** changes and so the view will need to be reset. +*/ +#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ +#define DB_UnresetViews 0x0002 /* Some views have defined column names */ +#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ + +/* +** The number of different kinds of things that can be limited +** using the sqlite3_limit() interface. +*/ +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) + +/* +** Lookaside malloc is a set of fixed-size buffers that can be used +** to satisfy small transient memory allocation requests for objects +** associated with a particular database connection. The use of +** lookaside malloc provides a significant performance enhancement +** (approx 10%) by avoiding numerous malloc/free requests while parsing +** SQL statements. +** +** The Lookaside structure holds configuration information about the +** lookaside malloc subsystem. Each available memory allocation in +** the lookaside subsystem is stored on a linked list of LookasideSlot +** objects. +** +** Lookaside allocations are only allowed for objects that are associated +** with a particular database connection. Hence, schema information cannot +** be stored in lookaside because in shared cache mode the schema information +** is shared by multiple database connections. Therefore, while parsing +** schema information, the Lookaside.bEnabled flag is cleared so that +** lookaside allocations are not used to construct the schema objects. +*/ +struct Lookaside { + u16 sz; /* Size of each buffer in bytes */ + u8 bEnabled; /* False to disable new lookaside allocations */ + u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ + int nOut; /* Number of buffers currently checked out */ + int mxOut; /* Highwater mark for nOut */ + int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + LookasideSlot *pFree; /* List of available buffers */ + void *pStart; /* First byte of available memory space */ + void *pEnd; /* First byte past end of available space */ +}; +struct LookasideSlot { + LookasideSlot *pNext; /* Next buffer in the list of free buffers */ +}; + +/* +** A hash table for function definitions. +** +** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. +** Collisions are on the FuncDef.pHash chain. +*/ +struct FuncDefHash { + FuncDef *a[23]; /* Hash table for functions */ +}; + +/* +** Each database connection is an instance of the following structure. +*/ +struct sqlite3 { + sqlite3_vfs *pVfs; /* OS Interface */ + struct Vdbe *pVdbe; /* List of active virtual machines */ + CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ + sqlite3_mutex *mutex; /* Connection mutex */ + Db *aDb; /* All backends */ + int nDb; /* Number of backends currently in use */ + int flags; /* Miscellaneous flags. See below */ + i64 lastRowid; /* ROWID of most recent insert (see above) */ + i64 szMmap; /* Default mmap_size setting */ + unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + int errCode; /* Most recent error code (SQLITE_*) */ + int errMask; /* & result codes with this before returning */ + u16 dbOptFlags; /* Flags to enable/disable optimizations */ + u8 autoCommit; /* The auto-commit flag. */ + u8 temp_store; /* 1: file 2: memory 0: default */ + u8 mallocFailed; /* True if we have seen a malloc failure */ + u8 dfltLockMode; /* Default locking-mode for attached dbs */ + signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ + u8 suppressErr; /* Do not issue error messages if true */ + u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ + u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ + int nextPagesize; /* Pagesize after VACUUM if >0 */ + u32 magic; /* Magic number for detect library misuse */ + int nChange; /* Value returned by sqlite3_changes() */ + int nTotalChange; /* Value returned by sqlite3_total_changes() */ + int aLimit[SQLITE_N_LIMIT]; /* Limits */ + struct sqlite3InitInfo { /* Information used during initialization */ + int newTnum; /* Rootpage of table being initialized */ + u8 iDb; /* Which db file is being initialized */ + u8 busy; /* TRUE if currently initializing */ + u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ + } init; + int nVdbeActive; /* Number of VDBEs currently running */ + int nVdbeRead; /* Number of active VDBEs that read or write */ + int nVdbeWrite; /* Number of active VDBEs that read and write */ + int nVdbeExec; /* Number of nested calls to VdbeExec() */ + int nExtension; /* Number of loaded extensions */ + void **aExtension; /* Array of shared library handles */ + void (*xTrace)(void*,const char*); /* Trace function */ + void *pTraceArg; /* Argument to the trace function */ + void (*xProfile)(void*,const char*,u64); /* Profiling function */ + void *pProfileArg; /* Argument to profile function */ + void *pCommitArg; /* Argument to xCommitCallback() */ + int (*xCommitCallback)(void*); /* Invoked at every commit. */ + void *pRollbackArg; /* Argument to xRollbackCallback() */ + void (*xRollbackCallback)(void*); /* Invoked at every commit. */ + void *pUpdateArg; + void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); +#ifndef SQLITE_OMIT_WAL + int (*xWalCallback)(void *, sqlite3 *, const char *, int); + void *pWalArg; +#endif + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); + void *pCollNeededArg; + sqlite3_value *pErr; /* Most recent error message */ + char *zErrMsg; /* Most recent error message (UTF-8 encoded) */ + char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */ + union { + volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ + double notUsed1; /* Spacer */ + } u1; + Lookaside lookaside; /* Lookaside malloc configuration */ +#ifndef SQLITE_OMIT_AUTHORIZATION + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + /* Access authorization function */ + void *pAuthArg; /* 1st argument to the access auth function */ +#endif +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + int (*xProgress)(void *); /* The progress callback */ + void *pProgressArg; /* Argument to the progress callback */ + unsigned nProgressOps; /* Number of opcodes for progress callback */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + int nVTrans; /* Allocated size of aVTrans */ + Hash aModule; /* populated by sqlite3_create_module() */ + VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ + VTable **aVTrans; /* Virtual tables with open transactions */ + VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ +#endif + FuncDefHash aFunc; /* Hash table of connection functions */ + Hash aCollSeq; /* All collating sequences */ + BusyHandler busyHandler; /* Busy callback */ + Db aDbStatic[2]; /* Static space for the 2 default backends */ + Savepoint *pSavepoint; /* List of active savepoints */ + int busyTimeout; /* Busy handler timeout, in msec */ + int nSavepoint; /* Number of non-transaction savepoints */ + int nStatement; /* Number of nested statement-transactions */ + i64 nDeferredCons; /* Net deferred constraints this transaction. */ + i64 nDeferredImmCons; /* Net deferred immediate constraints */ + int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + /* The following variables are all protected by the STATIC_MASTER + ** mutex, not by sqlite3.mutex. They are used by code in notify.c. + ** + ** When X.pUnlockConnection==Y, that means that X is waiting for Y to + ** unlock so that it can proceed. + ** + ** When X.pBlockingConnection==Y, that means that something that X tried + ** tried to do recently failed with an SQLITE_LOCKED error due to locks + ** held by Y. + */ + sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ + sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ + void *pUnlockArg; /* Argument to xUnlockNotify */ + void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ + sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ +#endif +}; + +/* +** A macro to discover the encoding of a database. +*/ +#define ENC(db) ((db)->aDb[0].pSchema->enc) + +/* +** Possible values for the sqlite3.flags. +*/ +#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ +#define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ +#define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */ +#define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */ +#define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */ +#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */ +#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ +#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ + /* DELETE, or UPDATE and return */ + /* the count using a callback. */ +#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ + /* result set is empty */ +#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ +#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ +#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ +#define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */ +#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ +#define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */ +#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ +#define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */ +#define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */ +#define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */ +#define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */ +#define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */ +#define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */ +#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ +#define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */ +#define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */ +#define SQLITE_QueryOnly 0x02000000 /* Disable database changes */ + + +/* +** Bits of the sqlite3.dbOptFlags field that are used by the +** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to +** selectively disable various optimizations. +*/ +#define SQLITE_QueryFlattener 0x0001 /* Query flattening */ +#define SQLITE_ColumnCache 0x0002 /* Column cache */ +#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ +#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ +#define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */ +#define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ +#define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ +#define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ +#define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ +#define SQLITE_Transitive 0x0200 /* Transitive constraints */ +#define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */ +#define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */ +#define SQLITE_AllOpts 0xffff /* All optimizations */ + +/* +** Macros for testing whether or not optimizations are enabled or disabled. +*/ +#ifndef SQLITE_OMIT_BUILTIN_TEST +#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) +#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) +#else +#define OptimizationDisabled(db, mask) 0 +#define OptimizationEnabled(db, mask) 1 +#endif + +/* +** Possible values for the sqlite.magic field. +** The numbers are obtained at random and have no special meaning, other +** than being distinct from one another. +*/ +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ +#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ +#define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */ + +/* +** Each SQL function is defined by an instance of the following +** structure. A pointer to this structure is stored in the sqlite.aFunc +** hash table. When multiple functions have the same name, the hash table +** points to a linked list of these structures. +*/ +struct FuncDef { + i16 nArg; /* Number of arguments. -1 means unlimited */ + u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ + u8 flags; /* Some combination of SQLITE_FUNC_* */ + void *pUserData; /* User data parameter */ + FuncDef *pNext; /* Next function with same name */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ + void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ + void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ + char *zName; /* SQL name of the function. */ + FuncDef *pHash; /* Next with a different name but the same hash */ + FuncDestructor *pDestructor; /* Reference counted destructor function */ +}; + +/* +** This structure encapsulates a user-function destructor callback (as +** configured using create_function_v2()) and a reference counter. When +** create_function_v2() is called to create a function with a destructor, +** a single object of this type is allocated. FuncDestructor.nRef is set to +** the number of FuncDef objects created (either 1 or 3, depending on whether +** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor +** member of each of the new FuncDef objects is set to point to the allocated +** FuncDestructor. +** +** Thereafter, when one of the FuncDef objects is deleted, the reference +** count on this object is decremented. When it reaches 0, the destructor +** is invoked and the FuncDestructor structure freed. +*/ +struct FuncDestructor { + int nRef; + void (*xDestroy)(void *); + void *pUserData; +}; + +/* +** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF +** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There +** are assert() statements in the code to verify this. +*/ +#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ +#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ +#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ +#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ +#define SQLITE_FUNC_COUNT 0x10 /* Built-in count(*) aggregate */ +#define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */ +#define SQLITE_FUNC_LENGTH 0x40 /* Built-in length() function */ +#define SQLITE_FUNC_TYPEOF 0x80 /* Built-in typeof() function */ + +/* +** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are +** used to create the initializers for the FuncDef structures. +** +** FUNCTION(zName, nArg, iArg, bNC, xFunc) +** Used to create a scalar function definition of a function zName +** implemented by C function xFunc that accepts nArg arguments. The +** value passed as iArg is cast to a (void*) and made available +** as the user-data (sqlite3_user_data()) for the function. If +** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. +** +** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) +** Used to create an aggregate function definition implemented by +** the C functions xStep and xFinal. The first four parameters +** are interpreted in the same way as the first 4 parameters to +** FUNCTION(). +** +** LIKEFUNC(zName, nArg, pArg, flags) +** Used to create a scalar function definition of a function zName +** that accepts nArg arguments and is implemented by a call to C +** function likeFunc. Argument pArg is cast to a (void *) and made +** available as the function user-data (sqlite3_user_data()). The +** FuncDef.flags variable is set to the value passed as the flags +** parameter. +*/ +#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ + {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + pArg, 0, xFunc, 0, 0, #zName, 0, 0} +#define LIKEFUNC(zName, nArg, arg, flags) \ + {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0} +#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ + {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ + SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0} + +/* +** All current savepoints are stored in a linked list starting at +** sqlite3.pSavepoint. The first element in the list is the most recently +** opened savepoint. Savepoints are added to the list by the vdbe +** OP_Savepoint instruction. +*/ +struct Savepoint { + char *zName; /* Savepoint name (nul-terminated) */ + i64 nDeferredCons; /* Number of deferred fk violations */ + i64 nDeferredImmCons; /* Number of deferred imm fk. */ + Savepoint *pNext; /* Parent savepoint (if any) */ +}; + +/* +** The following are used as the second parameter to sqlite3Savepoint(), +** and as the P1 argument to the OP_Savepoint instruction. +*/ +#define SAVEPOINT_BEGIN 0 +#define SAVEPOINT_RELEASE 1 +#define SAVEPOINT_ROLLBACK 2 + + +/* +** Each SQLite module (virtual table definition) is defined by an +** instance of the following structure, stored in the sqlite3.aModule +** hash table. +*/ +struct Module { + const sqlite3_module *pModule; /* Callback pointers */ + const char *zName; /* Name passed to create_module() */ + void *pAux; /* pAux passed to create_module() */ + void (*xDestroy)(void *); /* Module destructor function */ +}; + +/* +** information about each column of an SQL table is held in an instance +** of this structure. +*/ +struct Column { + char *zName; /* Name of this column */ + Expr *pDflt; /* Default value of this column */ + char *zDflt; /* Original text of the default value */ + char *zType; /* Data type for this column */ + char *zColl; /* Collating sequence. If NULL, use the default */ + u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ + char affinity; /* One of the SQLITE_AFF_... values */ + u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */ +}; + +/* Allowed values for Column.colFlags: +*/ +#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ +#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ + +/* +** A "Collating Sequence" is defined by an instance of the following +** structure. Conceptually, a collating sequence consists of a name and +** a comparison routine that defines the order of that sequence. +** +** If CollSeq.xCmp is NULL, it means that the +** collating sequence is undefined. Indices built on an undefined +** collating sequence may not be read or written. +*/ +struct CollSeq { + char *zName; /* Name of the collating sequence, UTF-8 encoded */ + u8 enc; /* Text encoding handled by xCmp() */ + void *pUser; /* First argument to xCmp() */ + int (*xCmp)(void*,int, const void*, int, const void*); + void (*xDel)(void*); /* Destructor for pUser */ +}; + +/* +** A sort order can be either ASC or DESC. +*/ +#define SQLITE_SO_ASC 0 /* Sort in ascending order */ +#define SQLITE_SO_DESC 1 /* Sort in ascending order */ + +/* +** Column affinity types. +** +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and +** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve +** the speed a little by numbering the values consecutively. +** +** But rather than start with 0 or 1, we begin with 'a'. That way, +** when multiple affinity types are concatenated into a string and +** used as the P4 operand, they will be more readable. +** +** Note also that the numeric types are grouped together so that testing +** for a numeric type is a single comparison. +*/ +#define SQLITE_AFF_TEXT 'a' +#define SQLITE_AFF_NONE 'b' +#define SQLITE_AFF_NUMERIC 'c' +#define SQLITE_AFF_INTEGER 'd' +#define SQLITE_AFF_REAL 'e' + +#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) + +/* +** The SQLITE_AFF_MASK values masks off the significant bits of an +** affinity value. +*/ +#define SQLITE_AFF_MASK 0x67 + +/* +** Additional bit values that can be ORed with an affinity without +** changing the affinity. +*/ +#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ +#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ +#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ + +/* +** An object of this type is created for each virtual table present in +** the database schema. +** +** If the database schema is shared, then there is one instance of this +** structure for each database connection (sqlite3*) that uses the shared +** schema. This is because each database connection requires its own unique +** instance of the sqlite3_vtab* handle used to access the virtual table +** implementation. sqlite3_vtab* handles can not be shared between +** database connections, even when the rest of the in-memory database +** schema is shared, as the implementation often stores the database +** connection handle passed to it via the xConnect() or xCreate() method +** during initialization internally. This database connection handle may +** then be used by the virtual table implementation to access real tables +** within the database. So that they appear as part of the callers +** transaction, these accesses need to be made via the same database +** connection as that used to execute SQL operations on the virtual table. +** +** All VTable objects that correspond to a single table in a shared +** database schema are initially stored in a linked-list pointed to by +** the Table.pVTable member variable of the corresponding Table object. +** When an sqlite3_prepare() operation is required to access the virtual +** table, it searches the list for the VTable that corresponds to the +** database connection doing the preparing so as to use the correct +** sqlite3_vtab* handle in the compiled query. +** +** When an in-memory Table object is deleted (for example when the +** schema is being reloaded for some reason), the VTable objects are not +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed +** immediately. Instead, they are moved from the Table.pVTable list to +** another linked list headed by the sqlite3.pDisconnect member of the +** corresponding sqlite3 structure. They are then deleted/xDisconnected +** next time a statement is prepared using said sqlite3*. This is done +** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. +** Refer to comments above function sqlite3VtabUnlockList() for an +** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect +** list without holding the corresponding sqlite3.mutex mutex. +** +** The memory for objects of this type is always allocated by +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as +** the first argument. +*/ +struct VTable { + sqlite3 *db; /* Database connection associated with this table */ + Module *pMod; /* Pointer to module implementation */ + sqlite3_vtab *pVtab; /* Pointer to vtab instance */ + int nRef; /* Number of pointers to this structure */ + u8 bConstraint; /* True if constraints are supported */ + int iSavepoint; /* Depth of the SAVEPOINT stack */ + VTable *pNext; /* Next in linked list (see above) */ +}; + +/* +** Each SQL table is represented in memory by an instance of the +** following structure. +** +** Table.zName is the name of the table. The case of the original +** CREATE TABLE statement is stored, but case is not significant for +** comparisons. +** +** Table.nCol is the number of columns in this table. Table.aCol is a +** pointer to an array of Column structures, one for each column. +** +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of +** the column that is that key. Otherwise Table.iPKey is negative. Note +** that the datatype of the PRIMARY KEY must be INTEGER for this field to +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid +** is generated for each row of the table. TF_HasPrimaryKey is set if +** the table has any PRIMARY KEY, INTEGER or otherwise. +** +** Table.tnum is the page number for the root BTree page of the table in the +** database file. If Table.iDb is the index of the database table backend +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that +** holds temporary tables and indices. If TF_Ephemeral is set +** then the table is stored in a file that is automatically deleted +** when the VDBE cursor to the table is closed. In this case Table.tnum +** refers VDBE cursor number that holds the table open, not to the root +** page number. Transient tables are used to hold the results of a +** sub-query that appears instead of a real table name in the FROM clause +** of a SELECT statement. +*/ +struct Table { + char *zName; /* Name of the table or view */ + Column *aCol; /* Information about each column */ + Index *pIndex; /* List of SQL indexes on this table. */ + Select *pSelect; /* NULL for tables. Points to definition if a view. */ + FKey *pFKey; /* Linked list of all foreign keys in this table */ + char *zColAff; /* String defining the affinity of each column */ +#ifndef SQLITE_OMIT_CHECK + ExprList *pCheck; /* All CHECK constraints */ +#endif + tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ + int tnum; /* Root BTree node for this table (see note above) */ + i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */ + i16 nCol; /* Number of columns in this table */ + u16 nRef; /* Number of pointers to this Table */ + u8 tabFlags; /* Mask of TF_* values */ + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ +#ifndef SQLITE_OMIT_ALTERTABLE + int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + int nModuleArg; /* Number of arguments to the module */ + char **azModuleArg; /* Text of all module args. [0] is module name */ + VTable *pVTable; /* List of VTable objects. */ +#endif + Trigger *pTrigger; /* List of triggers stored in pSchema */ + Schema *pSchema; /* Schema that contains this table */ + Table *pNextZombie; /* Next on the Parse.pZombieTab list */ +}; + +/* +** Allowed values for Tabe.tabFlags. +*/ +#define TF_Readonly 0x01 /* Read-only system table */ +#define TF_Ephemeral 0x02 /* An ephemeral table */ +#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ +#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ +#define TF_Virtual 0x10 /* Is a virtual table */ + + +/* +** Test to see whether or not a table is a virtual table. This is +** done as a macro so that it will be optimized out when virtual +** table support is omitted from the build. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE +# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) +#else +# define IsVirtual(X) 0 +# define IsHiddenColumn(X) 0 +#endif + +/* +** Each foreign key constraint is an instance of the following structure. +** +** A foreign key is associated with two tables. The "from" table is +** the table that contains the REFERENCES clause that creates the foreign +** key. The "to" table is the table that is named in the REFERENCES clause. +** Consider this example: +** +** CREATE TABLE ex1( +** a INTEGER PRIMARY KEY, +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) +** ); +** +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** +** Each REFERENCES clause generates an instance of the following structure +** which is attached to the from-table. The to-table need not exist when +** the from-table is created. The existence of the to-table is not checked. +*/ +struct FKey { + Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ + FKey *pNextFrom; /* Next foreign key in pFrom */ + char *zTo; /* Name of table that the key points to (aka: Parent) */ + FKey *pNextTo; /* Next foreign key on table named zTo */ + FKey *pPrevTo; /* Previous foreign key on table named zTo */ + int nCol; /* Number of columns in this key */ + /* EV: R-30323-21917 */ + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ + Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ + int iFrom; /* Index of column in pFrom */ + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ + } aCol[1]; /* One entry for each of nCol column s */ +}; + +/* +** SQLite supports many different ways to resolve a constraint +** error. ROLLBACK processing means that a constraint violation +** causes the operation in process to fail and for the current transaction +** to be rolled back. ABORT processing means the operation in process +** fails and any prior changes from that one operation are backed out, +** but the transaction is not rolled back. FAIL processing means that +** the operation in progress stops and returns an error code. But prior +** changes due to the same operation are not backed out and no rollback +** occurs. IGNORE means that the particular row that caused the constraint +** error is not inserted or updated. Processing continues and no error +** is returned. REPLACE means that preexisting database rows that caused +** a UNIQUE constraint violation are removed so that the new insert or +** update can proceed. Processing continues and no error is reported. +** +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the +** referenced table row is propagated into the row that holds the +** foreign key. +** +** The following symbolic values are used to record which type +** of action to take. +*/ +#define OE_None 0 /* There is no constraint to check */ +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ +#define OE_Abort 2 /* Back out changes but do no rollback transaction */ +#define OE_Fail 3 /* Stop the operation but leave all prior changes */ +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ + +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ +#define OE_SetNull 7 /* Set the foreign key value to NULL */ +#define OE_SetDflt 8 /* Set the foreign key value to its default */ +#define OE_Cascade 9 /* Cascade the changes */ + +#define OE_Default 99 /* Do whatever the default action is */ + + +/* +** An instance of the following structure is passed as the first +** argument to sqlite3VdbeKeyCompare and is used to control the +** comparison of the two index keys. +** +** Note that aSortOrder[] and aColl[] have nField+1 slots. There +** are nField slots for the columns of an index then one extra slot +** for the rowid at the end. +*/ +struct KeyInfo { + sqlite3 *db; /* The database connection */ + u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ + u16 nField; /* Maximum index for aColl[] and aSortOrder[] */ + u8 *aSortOrder; /* Sort order for each column. */ + CollSeq *aColl[1]; /* Collating sequence for each term of the key */ +}; + +/* +** An instance of the following structure holds information about a +** single index record that has already been parsed out into individual +** values. +** +** A record is an object that contains one or more fields of data. +** Records are used to store the content of a table row and to store +** the key of an index. A blob encoding of a record is created by +** the OP_MakeRecord opcode of the VDBE and is disassembled by the +** OP_Column opcode. +** +** This structure holds a record that has already been disassembled +** into its constituent fields. +*/ +struct UnpackedRecord { + KeyInfo *pKeyInfo; /* Collation and sort-order information */ + u16 nField; /* Number of entries in apMem[] */ + u8 flags; /* Boolean settings. UNPACKED_... below */ + i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ + Mem *aMem; /* Values */ +}; + +/* +** Allowed values of UnpackedRecord.flags +*/ +#define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */ +#define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */ +#define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */ + +/* +** Each SQL index is represented in memory by an +** instance of the following structure. +** +** The columns of the table that are to be indexed are described +** by the aiColumn[] field of this structure. For example, suppose +** we have the following table and index: +** +** CREATE TABLE Ex1(c1 int, c2 int, c3 text); +** CREATE INDEX Ex2 ON Ex1(c3,c1); +** +** In the Table structure describing Ex1, nCol==3 because there are +** three columns in the table. In the Index structure describing +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. +** The second column to be indexed (c1) has an index of 0 in +** Ex1.aCol[], hence Ex2.aiColumn[1]==0. +** +** The Index.onError field determines whether or not the indexed columns +** must be unique and what to do if they are not. When Index.onError=OE_None, +** it means this is not a unique index. Otherwise it is a unique index +** and the value of Index.onError indicate the which conflict resolution +** algorithm to employ whenever an attempt is made to insert a non-unique +** element. +*/ +struct Index { + char *zName; /* Name of this index */ + int *aiColumn; /* Which columns are used by this index. 1st is 0 */ + tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */ + Table *pTable; /* The SQL table being indexed */ + char *zColAff; /* String defining the affinity of each column */ + Index *pNext; /* The next index associated with the same table */ + Schema *pSchema; /* Schema containing this index */ + u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ + char **azColl; /* Array of collation sequence names for index */ + Expr *pPartIdxWhere; /* WHERE clause for partial indices */ + int tnum; /* DB Page containing root of this index */ + u16 nColumn; /* Number of columns in table used by this index */ + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ + unsigned bUnordered:1; /* Use this index for == or IN queries only */ + unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ +#ifdef SQLITE_ENABLE_STAT3 + int nSample; /* Number of elements in aSample[] */ + tRowcnt avgEq; /* Average nEq value for key values not in aSample */ + IndexSample *aSample; /* Samples of the left-most key */ +#endif +}; + +/* +** Each sample stored in the sqlite_stat3 table is represented in memory +** using a structure of this type. See documentation at the top of the +** analyze.c source file for additional information. +*/ +struct IndexSample { + union { + char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */ + double r; /* Value if eType is SQLITE_FLOAT */ + i64 i; /* Value if eType is SQLITE_INTEGER */ + } u; + u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ + int nByte; /* Size in byte of text or blob. */ + tRowcnt nEq; /* Est. number of rows where the key equals this sample */ + tRowcnt nLt; /* Est. number of rows where key is less than this sample */ + tRowcnt nDLt; /* Est. number of distinct keys less than this sample */ +}; + +/* +** Each token coming out of the lexer is an instance of +** this structure. Tokens are also used as part of an expression. +** +** Note if Token.z==0 then Token.dyn and Token.n are undefined and +** may contain random values. Do not make any assumptions about Token.dyn +** and Token.n when Token.z==0. +*/ +struct Token { + const char *z; /* Text of the token. Not NULL-terminated! */ + unsigned int n; /* Number of characters in this token */ +}; + +/* +** An instance of this structure contains information needed to generate +** code for a SELECT that contains aggregate functions. +** +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a +** pointer to this structure. The Expr.iColumn field is the index in +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate +** code for that node. +** +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the +** original Select structure that describes the SELECT statement. These +** fields do not need to be freed when deallocating the AggInfo structure. +*/ +struct AggInfo { + u8 directMode; /* Direct rendering mode means take data directly + ** from source tables rather than from accumulators */ + u8 useSortingIdx; /* In direct mode, reference the sorting index rather + ** than the source table */ + int sortingIdx; /* Cursor number of the sorting index */ + int sortingIdxPTab; /* Cursor number of pseudo-table */ + int nSortingColumn; /* Number of columns in the sorting index */ + ExprList *pGroupBy; /* The group by clause */ + struct AggInfo_col { /* For each column used in source tables */ + Table *pTab; /* Source table */ + int iTable; /* Cursor number of the source table */ + int iColumn; /* Column number within the source table */ + int iSorterColumn; /* Column number in the sorting index */ + int iMem; /* Memory location that acts as accumulator */ + Expr *pExpr; /* The original expression */ + } *aCol; + int nColumn; /* Number of used entries in aCol[] */ + int nAccumulator; /* Number of columns that show through to the output. + ** Additional columns are used only as parameters to + ** aggregate functions */ + struct AggInfo_func { /* For each aggregate function */ + Expr *pExpr; /* Expression encoding the function */ + FuncDef *pFunc; /* The aggregate function implementation */ + int iMem; /* Memory location that acts as accumulator */ + int iDistinct; /* Ephemeral table used to enforce DISTINCT */ + } *aFunc; + int nFunc; /* Number of entries in aFunc[] */ +}; + +/* +** The datatype ynVar is a signed integer, either 16-bit or 32-bit. +** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater +** than 32767 we have to make it 32-bit. 16-bit is preferred because +** it uses less memory in the Expr object, which is a big memory user +** in systems with lots of prepared statements. And few applications +** need more than about 10 or 20 variables. But some extreme users want +** to have prepared statements with over 32767 variables, and for them +** the option is available (at compile-time). +*/ +#if SQLITE_MAX_VARIABLE_NUMBER<=32767 +typedef i16 ynVar; +#else +typedef int ynVar; +#endif + +/* +** Each node of an expression in the parse tree is an instance +** of this structure. +** +** Expr.op is the opcode. The integer parser token codes are reused +** as opcodes here. For example, the parser defines TK_GE to be an integer +** code representing the ">=" operator. This same integer code is reused +** to represent the greater-than-or-equal-to operator in the expression +** tree. +** +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, +** or TK_STRING), then Expr.token contains the text of the SQL literal. If +** the expression is a variable (TK_VARIABLE), then Expr.token contains the +** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), +** then Expr.token contains the name of the function. +** +** Expr.pRight and Expr.pLeft are the left and right subexpressions of a +** binary operator. Either or both may be NULL. +** +** Expr.x.pList is a list of arguments if the expression is an SQL function, +** a CASE expression or an IN expression of the form " IN (, ...)". +** Expr.x.pSelect is used if the expression is a sub-select or an expression of +** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is +** valid. +** +** An expression of the form ID or ID.ID refers to a column in a table. +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is +** the integer cursor number of a VDBE cursor pointing to that table and +** Expr.iColumn is the column number for the specific column. If the +** expression is used as a result in an aggregate SELECT, then the +** value is also stored in the Expr.iAgg column in the aggregate so that +** it can be accessed after all aggregates are computed. +** +** If the expression is an unbound variable marker (a question mark +** character '?' in the original SQL) then the Expr.iTable holds the index +** number for that variable. +** +** If the expression is a subquery then Expr.iColumn holds an integer +** register number containing the result of the subquery. If the +** subquery gives a constant result, then iTable is -1. If the subquery +** gives a different answer at different times during statement processing +** then iTable is the address of a subroutine that computes the subquery. +** +** If the Expr is of type OP_Column, and the table it is selecting from +** is a disk table or the "old.*" pseudo-table, then pTab points to the +** corresponding table definition. +** +** ALLOCATION NOTES: +** +** Expr objects can use a lot of memory space in database schema. To +** help reduce memory requirements, sometimes an Expr object will be +** truncated. And to reduce the number of memory allocations, sometimes +** two or more Expr objects will be stored in a single memory allocation, +** together with Expr.zToken strings. +** +** If the EP_Reduced and EP_TokenOnly flags are set when +** an Expr object is truncated. When EP_Reduced is set, then all +** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees +** are contained within the same memory allocation. Note, however, that +** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately +** allocated, regardless of whether or not EP_Reduced is set. +*/ +struct Expr { + u8 op; /* Operation performed by this node */ + char affinity; /* The affinity of the column or 0 if not a column */ + u16 flags; /* Various flags. EP_* See below */ + union { + char *zToken; /* Token value. Zero terminated and dequoted */ + int iValue; /* Non-negative integer value if EP_IntValue */ + } u; + + /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + + Expr *pLeft; /* Left subnode */ + Expr *pRight; /* Right subnode */ + union { + ExprList *pList; /* Function arguments or in " IN ( IN (