Merge branch 'develop' into feature/dualcontouring
Conflicts: library/PolyVoxCore/CMakeLists.txt
This commit is contained in:
commit
58051b7480
20
.gitattributes
vendored
Normal file
20
.gitattributes
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
# Based on GitHub sample: https://help.github.com/articles/dealing-with-line-endings
|
||||
|
||||
# Set the default behavior, in case people don't have core.autocrlf set.
|
||||
* text=auto
|
||||
|
||||
# Explicitly declare text files you want to always be normalized and converted
|
||||
# to native line endings on checkout.
|
||||
*.c text
|
||||
*.cpp text
|
||||
*.h text
|
||||
*.inl text
|
||||
*.txt text
|
||||
*.i text
|
||||
|
||||
# Declare files that will always have CRLF line endings on checkout.
|
||||
#*.sln text eol=crlf
|
||||
|
||||
# Denote all files that are truly binary and should not be modified.
|
||||
#*.png binary
|
||||
#*.jpg binary
|
255
CHANGELOG.txt
255
CHANGELOG.txt
@ -1,120 +1,135 @@
|
||||
Changes for PolyVox version 0.3
|
||||
===============================
|
||||
This release has focused on... (some introduction here).
|
||||
|
||||
This line was added just for testing.
|
||||
|
||||
Voxel access
|
||||
------------
|
||||
The getVoxelAt() and setVoxelAt() functions have been deprecated and replaced by getVoxel() and setVoxel(). These new functions provide more control over how edge cases are handled and can potentially be faster as well. Please see the 'Volumes' section of the user manual for more information about how voxel access should be performed.
|
||||
|
||||
LargeVolume
|
||||
-----------
|
||||
Behaviour and interface of the LargeVolume has changed significantly and code which uses it will certainly need to be updated. Plese see the LargeVolume API docs for full details of how it now works.
|
||||
|
||||
It is now possible to provide custom compressors for the data which is stored in a LargeVolume. Two compressor implementation are provided with PolyVox - RLECompressor which is suitable for cubic-style terrain, and MinizCompressor which uses the 'miniz' zlib implementation for smooth terrain or general purpose use. Users can provide their own implementation of the compressor interface if they wish.
|
||||
|
||||
Note that the setCompressionEnabled() functionality has been removed and a compressor must always be provided when constructing the volume. The ability to disable compression was of questionable benefit and was complicating the logic in the code.
|
||||
|
||||
The LargeVolume also supports custom paging code which can be supplied by providing a subclass of Pager and implementing the relevant methods. This replaces the dataRequiredHandler() and dataOverflowHandler() functions.
|
||||
|
||||
These changes regarding compression and paging have also affected the LargeVolume constructors(s). Please see the API docs to see how they look now.
|
||||
|
||||
Error Handling
|
||||
--------------
|
||||
PolyVox now has it's own POLYVOX_ASSERT() macro rather than using the standard assert(). This has some advantages such as allowing a message to be printed and providing file/line information, and it is also possible to enable/disable it independantly of whether you are making a debug or release build.
|
||||
|
||||
A simple logging system has also been added, and the output can be redirected by user code.
|
||||
|
||||
Please see the 'Error Handling' section of the user manual for more information about these changes.
|
||||
|
||||
Volume wrap modes
|
||||
-----------------
|
||||
This release has seen a overhaul of the way PolyVox handles voxel positions which are outside of the volume. It used to be the case that you could specify a border value which would be returned whenever an out-of-volume access was performed, but this was not flexible enough for all use cases. You can now choose between different wrapping modes (border, clamp, etc) and apply them to both the volume itself or to samplers. If you have multiple samplers pointing at the same volume then you can choose to have different wrap modes for each of them.
|
||||
|
||||
Within the Volume class the getVoxelAt() and setBorderValue() functions have been deprecated. Please see the 'Volumes' section of the user manual for more information about how voxel access should now be performed.
|
||||
|
||||
Various algorithms have also been updated to allow wrap modes to be specified when executing them.
|
||||
|
||||
Region class
|
||||
------------
|
||||
The Region class has been tidied up and enhanced with new functionality. It now contains functions for growing and shrinking regions, as well as 'accumulate()' functions which ensure the Region contains a given point. The concept of an invalid region has also been introduced - this is one whose lower corner is greater than it's upper corner.
|
||||
|
||||
Vector class
|
||||
------------
|
||||
The Vector class has been tidied up. Most notably it now makes use of an 'OperationType' which is used for internal calculations and some results. The documentation has also been updated.
|
||||
|
||||
Deprecated functionality
|
||||
------------------------
|
||||
Vector::operator<() has been deprecated. It was only present to allow Vectors to be used as the key to an std::map, but it makes more sense for this to be specified seperatly as a std::map comparison function. This is now done in the OpenGLExample (search for VectorCompare).
|
||||
|
||||
getVoxelAt() and setBorderValue() have been deprecated in the Volume class. See the section of this file on 'Volume wrap modes' for details.
|
||||
|
||||
Removed functionality
|
||||
--------------------
|
||||
Functionality deprecated for the previous release has now been removed. This includes:
|
||||
|
||||
- Region::getWidth() and related functions. You should now use Region::getWidthInVoxels() or Region::getWidthInCells.
|
||||
- The MeshDecimator. We don't have a direct replacement for this so you should consider an alternative such as downsampling the volume or using an external mesh processing library.
|
||||
- The SimpleInterface. This was primarily for the bindings, and we are making other efforts to get those working.
|
||||
- Serialisation. You should implement any required serialisation yourself.
|
||||
- This had a number of problems and was a little too high-level for PolyVox. You should implement change tracking yourself.
|
||||
|
||||
|
||||
Changes for PolyVox version 0.2
|
||||
===============================
|
||||
This is the first revision for which we have produced a changelog, as we are now trying to streamline our development and release process. Hence this changelog entry is not going to be as structured as we hope they will be in the future. We're writing it from memory, rather than having carefully kept track of all the relevant changes as we made them.
|
||||
|
||||
Deprecated functionality
|
||||
------------------------
|
||||
The following functionality is considered deprecated in this release of PolyVox and will probably be removed in future versions.
|
||||
|
||||
MeshDecimator: The mesh decimator was intended to reduce the amount of triangles in generated meshes but it has always had problems. It's far too slow and not very robust. For cubic meshes it is no longer needed anyway as the CubicSurfaceExtractor has built in decimation which is much more effective. For smooth (marching cubes) meshes there is no single alternative. You can consider downsampling the volume before you run the surface extractor (see the SmoothLODExample), and in the future we may add support for an external mesh processing library.
|
||||
|
||||
SimpleInterface: This was added so that people could create volumes without knowing about templates, and also to provide a target which was easier to wrap with SWIG. But overall we'd rather focus on getting the real SWIG bindings to work. The SimpleInterface is also extremely limited in the functionality it provides.
|
||||
|
||||
Serialisation: This is a difficult one. The current serialisation is rather old and only deals with loading/saving a whole volume at a time. It would make much more sense if it could serialise regions instead of whole volumes, and if it could handle compression. It would then be useful for serialising the data which is paged into and out of the LargeVolume, as well as other uses. Both these changes would likely require breaking the current format and interface. It is likely that serialisation will return to PolyVox in the future, but for now we would suggest just implementing your own.
|
||||
|
||||
VolumeChangeTracker: The idea behind this was was to provide a utility class to help the user keep track of which regions have been modified so they know when they need the surface extractor to be run again. But overall we'd rather keep such higher level functionality in user code as there are multiple ways it can be implemented. The current implementation is also old and does not support very large/infinite volumes, for example.
|
||||
|
||||
Refactor of basic voxel types
|
||||
-----------------------------
|
||||
Previous versions of PolyVox provided classes representing voxel data, such as MaterialDensityPair88. These classes were required to expose certain functions such as getDensity() and getMaterial(). This is no longer the case as now even primitive data types such as floats and ints can be used as voxels. You can also create new classes to represent voxel data and it is entirely up to you what kind of properties they have.
|
||||
|
||||
As an example, imagine you might want to store lighting values in a volume and propagate them according to some algorithm you devise. In this case the voxel data has no concept of densities or materials and there is no need to provide them. Algorithms which conceptually operate on densities (such as the MarchingCubesSurfaceExtractor) will not be able to operate on your lighting data but this would not make sense anyway.
|
||||
|
||||
Because algorithms now know nothing about the structure of the underlying voxels, some utility functions/classes are required. The principle is similar to the std::sort algorithm, which knows nothing about the type of data it is operating on but is told how to compare any two values via a comparator function object. In this sense, it will be useful to have an understanding of how algorithms such as std::sort are used.
|
||||
|
||||
We have continued to provide the Density, Material, and MaterialDensityPair classes to ease the transition into the new system, but really they should just be considered as examples of how you might create your own voxel types.
|
||||
|
||||
Some algorithms assume that basic mathematical operations can be applied to voxel types. For example, the LowPassFilter needs to compute the average of a set of voxels, and to do this it needs to be possible to add voxels together and divide by an integer. Obviously these operations are provided by primitive types, but it means that if you want to use the LowPassfilter on custom voxel types then these types need to provide operator+=, operator/=, etc. These have been added to the Density and MaterialDensityPair classes, but not to the Material class. This reflects the fact that applying a low pass filter to a material volume does not make conceptual sense.
|
||||
|
||||
Changes to build system
|
||||
-----------------------
|
||||
In order to make the build system easier to use, a number of CMake variables were changed to be more consistent. See :doc:`install` for details on the new variable naming.
|
||||
|
||||
Changes to CubicSurfaceExtractor
|
||||
--------------------------------
|
||||
The behaviour of the CubicSurfaceExtractor has been changed such that it no longer handles some edge cases. Because each generated quad lies between two voxels it can be unclear which region should 'own' a quad when the two voxels are from different regions. The previous version of the CubicSurfaceExtractor would attempt to handle this automatically, but as a result it was possible to get two quads existing at the same position in space. This can cause problems with transparency and with physics, as well as making it harder to decide which regions need to be updated when a voxel is changed.
|
||||
|
||||
The new system simplifies the behaviour of this surface extractor but does require a bit of care on the part of the user. You should be clear on the rules controlling when quads are generated and to which regions they will belong. To aid with this we have significantly improved the API documentation for the CubicSurfaceExtractor so be sure to have a look.
|
||||
|
||||
Changes to Raycast
|
||||
------------------
|
||||
The raycasting functionality was previously in a class (Raycast) but now it is provided by standalone functions. This is basically because there is no need for it to be a class, and it complicated usage. The new functions are called 'raycastWithDirection' and 'raycastWithEndpoints' which helps remove the previous ambiguity regarding the meaning of the two vectors which are passed as parameters.
|
||||
|
||||
The callback functionality (called for each processed voxel to determine whether to continue and also perform additional processing) is no longer implemented as an std::function. Instead the standard STL approach is used, in which a function or function object is used a a template parameter. This is faster than the std::function solution and should also be easier to integrate with other languages.
|
||||
|
||||
Usage of the new raycasting is demonstrated by a unit test.
|
||||
|
||||
Changes to AmbientOcclusionCalculator
|
||||
-------------------------------------
|
||||
The AmbientOcclusionCalculator has also been unclassed and is now called calculateAmbientOcclusion. The unit test has been updated to demonstrate the new usage.
|
||||
|
||||
Changes to A* pathfinder
|
||||
------------------------
|
||||
The A* pathfinder has always had different (but equally valid) results when building in Visual Studio vs. GCC. This is now fixed and results are consistent between platforms.
|
||||
|
||||
Copy and move semantics
|
||||
-----------------------
|
||||
All volume classes now have protected copy constructors and assignment operators to prevent you from accidentally copying them (which is expensive). Look at the VolumeResampler if you really do want to copy some volume data.
|
||||
Changes for PolyVox version 0.3
|
||||
===============================
|
||||
This release has focused on... (some introduction here).
|
||||
|
||||
*** Quick braindump of some changes ***
|
||||
|
||||
* SimpleVolume is now PagedVolume (slightly slower but can go larger).
|
||||
* MarchingCubesSurfaceExtractor class is now a free function extractMarchingCubesSurface()
|
||||
* Meshes are more templatized (e.g. on IndexType) and extracted meshes are encoded to save space. A 'decode' function is provided for these (or you can do it on the GPU).
|
||||
* Generally more templatization - you will want to use a lot of the 'auto' keyword to stay sane.
|
||||
* MarchingCubesController class gives more control over extraction process, but defaults should be fine for primative voxel types.
|
||||
* Requires VS2013 on Windows (GCC 4.7/Clang should be ok).
|
||||
* Support for 'WrapModes' when accessing outside volumes but I think these have bought a performance impact.
|
||||
* Documentation is as poor (or wrong) as ever but all tests and examples work.
|
||||
* New Array class is much faster
|
||||
|
||||
*** End of braindump ***
|
||||
|
||||
|
||||
This line was added just for testing.
|
||||
|
||||
Voxel access
|
||||
------------
|
||||
The getVoxelAt() and setVoxelAt() functions have been deprecated and replaced by getVoxel() and setVoxel(). These new functions provide more control over how edge cases are handled and can potentially be faster as well. Please see the 'Volumes' section of the user manual for more information about how voxel access should be performed.
|
||||
|
||||
LargeVolume
|
||||
-----------
|
||||
Behaviour and interface of the LargeVolume has changed significantly and code which uses it will certainly need to be updated. Plese see the LargeVolume API docs for full details of how it now works.
|
||||
|
||||
It is now possible to provide custom compressors for the data which is stored in a LargeVolume. Two compressor implementation are provided with PolyVox - RLECompressor which is suitable for cubic-style terrain, and MinizCompressor which uses the 'miniz' zlib implementation for smooth terrain or general purpose use. Users can provide their own implementation of the compressor interface if they wish.
|
||||
|
||||
Note that the setCompressionEnabled() functionality has been removed and a compressor must always be provided when constructing the volume. The ability to disable compression was of questionable benefit and was complicating the logic in the code.
|
||||
|
||||
The LargeVolume also supports custom paging code which can be supplied by providing a subclass of Pager and implementing the relevant methods. This replaces the dataRequiredHandler() and dataOverflowHandler() functions.
|
||||
|
||||
These changes regarding compression and paging have also affected the LargeVolume constructors(s). Please see the API docs to see how they look now.
|
||||
|
||||
Error Handling
|
||||
--------------
|
||||
PolyVox now has it's own POLYVOX_ASSERT() macro rather than using the standard assert(). This has some advantages such as allowing a message to be printed and providing file/line information, and it is also possible to enable/disable it independantly of whether you are making a debug or release build.
|
||||
|
||||
A simple logging system has also been added, and the output can be redirected by user code.
|
||||
|
||||
Please see the 'Error Handling' section of the user manual for more information about these changes.
|
||||
|
||||
Volume wrap modes
|
||||
-----------------
|
||||
This release has seen a overhaul of the way PolyVox handles voxel positions which are outside of the volume. It used to be the case that you could specify a border value which would be returned whenever an out-of-volume access was performed, but this was not flexible enough for all use cases. You can now choose between different wrapping modes (border, clamp, etc) and apply them to both the volume itself or to samplers. If you have multiple samplers pointing at the same volume then you can choose to have different wrap modes for each of them.
|
||||
|
||||
Within the Volume class the getVoxelAt() and setBorderValue() functions have been deprecated. Please see the 'Volumes' section of the user manual for more information about how voxel access should now be performed.
|
||||
|
||||
Various algorithms have also been updated to allow wrap modes to be specified when executing them.
|
||||
|
||||
Region class
|
||||
------------
|
||||
The Region class has been tidied up and enhanced with new functionality. It now contains functions for growing and shrinking regions, as well as 'accumulate()' functions which ensure the Region contains a given point. The concept of an invalid region has also been introduced - this is one whose lower corner is greater than it's upper corner.
|
||||
|
||||
Vector class
|
||||
------------
|
||||
The Vector class has been tidied up. Most notably it now makes use of an 'OperationType' which is used for internal calculations and some results. The documentation has also been updated.
|
||||
|
||||
Deprecated functionality
|
||||
------------------------
|
||||
Vector::operator<() has been deprecated. It was only present to allow Vectors to be used as the key to an std::map, but it makes more sense for this to be specified seperatly as a std::map comparison function. This is now done in the OpenGLExample (search for VectorCompare).
|
||||
|
||||
getVoxelAt() and setBorderValue() have been deprecated in the Volume class. See the section of this file on 'Volume wrap modes' for details.
|
||||
|
||||
Removed functionality
|
||||
--------------------
|
||||
Functionality deprecated for the previous release has now been removed. This includes:
|
||||
|
||||
- Region::getWidth() and related functions. You should now use Region::getWidthInVoxels() or Region::getWidthInCells.
|
||||
- The MeshDecimator. We don't have a direct replacement for this so you should consider an alternative such as downsampling the volume or using an external mesh processing library.
|
||||
- The SimpleInterface. This was primarily for the bindings, and we are making other efforts to get those working.
|
||||
- Serialisation. You should implement any required serialisation yourself.
|
||||
- This had a number of problems and was a little too high-level for PolyVox. You should implement change tracking yourself.
|
||||
|
||||
|
||||
Changes for PolyVox version 0.2
|
||||
===============================
|
||||
This is the first revision for which we have produced a changelog, as we are now trying to streamline our development and release process. Hence this changelog entry is not going to be as structured as we hope they will be in the future. We're writing it from memory, rather than having carefully kept track of all the relevant changes as we made them.
|
||||
|
||||
Deprecated functionality
|
||||
------------------------
|
||||
The following functionality is considered deprecated in this release of PolyVox and will probably be removed in future versions.
|
||||
|
||||
MeshDecimator: The mesh decimator was intended to reduce the amount of triangles in generated meshes but it has always had problems. It's far too slow and not very robust. For cubic meshes it is no longer needed anyway as the CubicSurfaceExtractor has built in decimation which is much more effective. For smooth (marching cubes) meshes there is no single alternative. You can consider downsampling the volume before you run the surface extractor (see the SmoothLODExample), and in the future we may add support for an external mesh processing library.
|
||||
|
||||
SimpleInterface: This was added so that people could create volumes without knowing about templates, and also to provide a target which was easier to wrap with SWIG. But overall we'd rather focus on getting the real SWIG bindings to work. The SimpleInterface is also extremely limited in the functionality it provides.
|
||||
|
||||
Serialisation: This is a difficult one. The current serialisation is rather old and only deals with loading/saving a whole volume at a time. It would make much more sense if it could serialise regions instead of whole volumes, and if it could handle compression. It would then be useful for serialising the data which is paged into and out of the LargeVolume, as well as other uses. Both these changes would likely require breaking the current format and interface. It is likely that serialisation will return to PolyVox in the future, but for now we would suggest just implementing your own.
|
||||
|
||||
VolumeChangeTracker: The idea behind this was was to provide a utility class to help the user keep track of which regions have been modified so they know when they need the surface extractor to be run again. But overall we'd rather keep such higher level functionality in user code as there are multiple ways it can be implemented. The current implementation is also old and does not support very large/infinite volumes, for example.
|
||||
|
||||
Refactor of basic voxel types
|
||||
-----------------------------
|
||||
Previous versions of PolyVox provided classes representing voxel data, such as MaterialDensityPair88. These classes were required to expose certain functions such as getDensity() and getMaterial(). This is no longer the case as now even primitive data types such as floats and ints can be used as voxels. You can also create new classes to represent voxel data and it is entirely up to you what kind of properties they have.
|
||||
|
||||
As an example, imagine you might want to store lighting values in a volume and propagate them according to some algorithm you devise. In this case the voxel data has no concept of densities or materials and there is no need to provide them. Algorithms which conceptually operate on densities (such as the MarchingCubesSurfaceExtractor) will not be able to operate on your lighting data but this would not make sense anyway.
|
||||
|
||||
Because algorithms now know nothing about the structure of the underlying voxels, some utility functions/classes are required. The principle is similar to the std::sort algorithm, which knows nothing about the type of data it is operating on but is told how to compare any two values via a comparator function object. In this sense, it will be useful to have an understanding of how algorithms such as std::sort are used.
|
||||
|
||||
We have continued to provide the Density, Material, and MaterialDensityPair classes to ease the transition into the new system, but really they should just be considered as examples of how you might create your own voxel types.
|
||||
|
||||
Some algorithms assume that basic mathematical operations can be applied to voxel types. For example, the LowPassFilter needs to compute the average of a set of voxels, and to do this it needs to be possible to add voxels together and divide by an integer. Obviously these operations are provided by primitive types, but it means that if you want to use the LowPassfilter on custom voxel types then these types need to provide operator+=, operator/=, etc. These have been added to the Density and MaterialDensityPair classes, but not to the Material class. This reflects the fact that applying a low pass filter to a material volume does not make conceptual sense.
|
||||
|
||||
Changes to build system
|
||||
-----------------------
|
||||
In order to make the build system easier to use, a number of CMake variables were changed to be more consistent. See :doc:`install` for details on the new variable naming.
|
||||
|
||||
Changes to CubicSurfaceExtractor
|
||||
--------------------------------
|
||||
The behaviour of the CubicSurfaceExtractor has been changed such that it no longer handles some edge cases. Because each generated quad lies between two voxels it can be unclear which region should 'own' a quad when the two voxels are from different regions. The previous version of the CubicSurfaceExtractor would attempt to handle this automatically, but as a result it was possible to get two quads existing at the same position in space. This can cause problems with transparency and with physics, as well as making it harder to decide which regions need to be updated when a voxel is changed.
|
||||
|
||||
The new system simplifies the behaviour of this surface extractor but does require a bit of care on the part of the user. You should be clear on the rules controlling when quads are generated and to which regions they will belong. To aid with this we have significantly improved the API documentation for the CubicSurfaceExtractor so be sure to have a look.
|
||||
|
||||
Changes to Raycast
|
||||
------------------
|
||||
The raycasting functionality was previously in a class (Raycast) but now it is provided by standalone functions. This is basically because there is no need for it to be a class, and it complicated usage. The new functions are called 'raycastWithDirection' and 'raycastWithEndpoints' which helps remove the previous ambiguity regarding the meaning of the two vectors which are passed as parameters.
|
||||
|
||||
The callback functionality (called for each processed voxel to determine whether to continue and also perform additional processing) is no longer implemented as an std::function. Instead the standard STL approach is used, in which a function or function object is used a a template parameter. This is faster than the std::function solution and should also be easier to integrate with other languages.
|
||||
|
||||
Usage of the new raycasting is demonstrated by a unit test.
|
||||
|
||||
Changes to AmbientOcclusionCalculator
|
||||
-------------------------------------
|
||||
The AmbientOcclusionCalculator has also been unclassed and is now called calculateAmbientOcclusion. The unit test has been updated to demonstrate the new usage.
|
||||
|
||||
Changes to A* pathfinder
|
||||
------------------------
|
||||
The A* pathfinder has always had different (but equally valid) results when building in Visual Studio vs. GCC. This is now fixed and results are consistent between platforms.
|
||||
|
||||
Copy and move semantics
|
||||
-----------------------
|
||||
All volume classes now have protected copy constructors and assignment operators to prevent you from accidentally copying them (which is expensive). Look at the VolumeResampler if you really do want to copy some volume data.
|
||||
|
253
CMakeLists.txt
253
CMakeLists.txt
@ -1,133 +1,120 @@
|
||||
# Copyright (c) 2007-2012 Matt Williams
|
||||
# Copyright (c) 2007-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.3)
|
||||
|
||||
PROJECT(PolyVox)
|
||||
|
||||
SET(POLYVOX_VERSION_MAJOR "0")
|
||||
SET(POLYVOX_VERSION_MINOR "2")
|
||||
SET(POLYVOX_VERSION_PATCH "1")
|
||||
SET(POLYVOX_VERSION "${POLYVOX_VERSION_MAJOR}.${POLYVOX_VERSION_MINOR}.${POLYVOX_VERSION_PATCH}" CACHE STRING "PolyVox version")
|
||||
MARK_AS_ADVANCED(FORCE POLYVOX_VERSION)
|
||||
|
||||
SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
include(FeatureSummary)
|
||||
|
||||
FIND_PACKAGE(Doxygen)
|
||||
OPTION(ENABLE_EXAMPLES "Should the examples be built" ON)
|
||||
|
||||
SET(LIBRARY_TYPE "DYNAMIC" CACHE STRING "Should the library be STATIC or DYNAMIC")
|
||||
SET_PROPERTY(CACHE LIBRARY_TYPE PROPERTY STRINGS DYNAMIC STATIC)
|
||||
IF(WIN32)
|
||||
SET(LIBRARY_TYPE "STATIC")
|
||||
ENDIF()
|
||||
|
||||
# Qt is required for building the tests, the example and optionally for bundling the documentation
|
||||
FIND_PACKAGE(Qt4 COMPONENTS QtCore QtGui QtOpenGL QtTest)
|
||||
INCLUDE(${QT_USE_FILE})
|
||||
if(CMAKE_VERSION VERSION_LESS "2.8.6")
|
||||
set_package_info(Doxygen "API documentation generator" http://www.doxygen.org "Building the API documentation")
|
||||
set_package_info(Qt4 "C++ framework" http://qt-project.org "Building the examples and tests")
|
||||
else()
|
||||
set_package_properties(Doxygen PROPERTIES URL http://www.doxygen.org DESCRIPTION "API documentation generator" TYPE OPTIONAL PURPOSE "Building the API documentation")
|
||||
set_package_properties(Qt4 PROPERTIES DESCRIPTION "C++ framework" URL http://qt-project.org)
|
||||
set_package_properties(Qt4 PROPERTIES TYPE RECOMMENDED PURPOSE "Building the examples")
|
||||
set_package_properties(Qt4 PROPERTIES TYPE OPTIONAL PURPOSE "Building the tests")
|
||||
endif()
|
||||
|
||||
if(MSVC AND (MSVC_VERSION LESS 1600))
|
||||
# Require boost for older (pre-vc2010) Visual Studio compilers
|
||||
# See library/include/polyvoxcore/impl/TypeDef.h
|
||||
find_package(Boost REQUIRED)
|
||||
include_directories(${Boost_INCLUDE_DIRS})
|
||||
endif()
|
||||
|
||||
IF(CMAKE_COMPILER_IS_GNUCXX) #Maybe "OR MINGW"
|
||||
ADD_DEFINITIONS(-std=c++0x) #Enable C++0x mode
|
||||
ENDIF()
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
ADD_DEFINITIONS(-std=c++0x) #Enable C++0x mode
|
||||
endif()
|
||||
|
||||
if(NOT MSVC) #This is causing problems in Visual Studio so disable it for now
|
||||
INCLUDE(cmake/Modules/CheckCXX11Features.cmake)
|
||||
endif()
|
||||
|
||||
ADD_SUBDIRECTORY(library)
|
||||
|
||||
OPTION(ENABLE_EXAMPLES "Should the examples be built" ON)
|
||||
IF(ENABLE_EXAMPLES AND QT_QTOPENGL_FOUND)
|
||||
ADD_SUBDIRECTORY(examples/common)
|
||||
ADD_SUBDIRECTORY(examples/Basic)
|
||||
ADD_SUBDIRECTORY(examples/Paging)
|
||||
ADD_SUBDIRECTORY(examples/OpenGL)
|
||||
ADD_SUBDIRECTORY(examples/SmoothLOD)
|
||||
ADD_SUBDIRECTORY(examples/Python)
|
||||
SET(BUILD_EXAMPLES ON)
|
||||
ELSE()
|
||||
SET(BUILD_EXAMPLES OFF)
|
||||
ENDIF()
|
||||
|
||||
INCLUDE(Packaging.cmake)
|
||||
|
||||
OPTION(ENABLE_TESTS "Should the tests be built" ON)
|
||||
IF(ENABLE_TESTS AND QT_QTTEST_FOUND)
|
||||
INCLUDE(CTest)
|
||||
MARK_AS_ADVANCED(FORCE DART_TESTING_TIMEOUT) #This is only needed to hide the variable in the GUI (CMake bug) until 2.8.5
|
||||
MARK_AS_ADVANCED(FORCE BUILD_TESTING)
|
||||
ADD_SUBDIRECTORY(tests)
|
||||
SET(BUILD_TESTS ON)
|
||||
ELSE()
|
||||
SET(BUILD_TESTS OFF)
|
||||
ENDIF()
|
||||
|
||||
#Check if we will building _and_ bundling the docs
|
||||
IF(DOXYGEN_FOUND AND QT_QCOLLECTIONGENERATOR_EXECUTABLE)
|
||||
SET(BUILD_AND_BUNDLE_DOCS ON)
|
||||
ELSE()
|
||||
SET(BUILD_AND_BUNDLE_DOCS OFF)
|
||||
ENDIF()
|
||||
|
||||
ADD_SUBDIRECTORY(documentation)
|
||||
|
||||
add_feature_info("Examples" BUILD_EXAMPLES "Examples of PolyVox usage")
|
||||
add_feature_info("Tests" BUILD_TESTS "Unit tests")
|
||||
add_feature_info("Bindings" BUILD_BINDINGS "SWIG bindings")
|
||||
add_feature_info("API docs" DOXYGEN_FOUND "HTML documentation of the API")
|
||||
add_feature_info("Qt Help" BUILD_AND_BUNDLE_DOCS "API docs in Qt Help format")
|
||||
add_feature_info("Manual" BUILD_MANUAL "HTML user's manual")
|
||||
|
||||
feature_summary(WHAT ALL)
|
||||
|
||||
# Option summary
|
||||
MESSAGE(STATUS "")
|
||||
MESSAGE(STATUS "Summary")
|
||||
MESSAGE(STATUS "-------")
|
||||
MESSAGE(STATUS "Library type: " ${LIBRARY_TYPE})
|
||||
MESSAGE(STATUS "Build examples: " ${BUILD_EXAMPLES})
|
||||
MESSAGE(STATUS "Build tests: " ${BUILD_TESTS})
|
||||
MESSAGE(STATUS "Build bindings: " ${BUILD_BINDINGS})
|
||||
MESSAGE(STATUS "API Docs available: " ${DOXYGEN_FOUND})
|
||||
MESSAGE(STATUS " - Qt Help bundling: " ${BUILD_AND_BUNDLE_DOCS})
|
||||
MESSAGE(STATUS "Build manual: " ${BUILD_MANUAL})
|
||||
MESSAGE(STATUS "")
|
||||
# Copyright (c) 2007-2012 Matt Williams
|
||||
# Copyright (c) 2007-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.6)
|
||||
|
||||
PROJECT(PolyVox)
|
||||
|
||||
SET(POLYVOX_VERSION_MAJOR "0")
|
||||
SET(POLYVOX_VERSION_MINOR "2")
|
||||
SET(POLYVOX_VERSION_PATCH "1")
|
||||
SET(POLYVOX_VERSION "${POLYVOX_VERSION_MAJOR}.${POLYVOX_VERSION_MINOR}.${POLYVOX_VERSION_PATCH}" CACHE STRING "PolyVox version")
|
||||
MARK_AS_ADVANCED(FORCE POLYVOX_VERSION)
|
||||
|
||||
SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON)
|
||||
include(FeatureSummary)
|
||||
|
||||
FIND_PACKAGE(Doxygen)
|
||||
OPTION(ENABLE_EXAMPLES "Should the examples be built" ON)
|
||||
|
||||
SET(LIBRARY_TYPE "DYNAMIC" CACHE STRING "Should the library be STATIC or DYNAMIC")
|
||||
SET_PROPERTY(CACHE LIBRARY_TYPE PROPERTY STRINGS DYNAMIC STATIC)
|
||||
IF(WIN32)
|
||||
SET(LIBRARY_TYPE "STATIC")
|
||||
ENDIF()
|
||||
|
||||
# Qt is required for building the tests, the example and optionally for bundling the documentation
|
||||
find_package(Qt5Test 5.2)
|
||||
find_package(Qt5OpenGL 5.2)
|
||||
|
||||
set_package_properties(Doxygen PROPERTIES URL http://www.doxygen.org DESCRIPTION "API documentation generator" TYPE OPTIONAL PURPOSE "Building the API documentation")
|
||||
set_package_properties(Qt5Test PROPERTIES DESCRIPTION "C++ framework" URL http://qt-project.org)
|
||||
set_package_properties(Qt5Test PROPERTIES TYPE OPTIONAL PURPOSE "Building the tests")
|
||||
set_package_properties(Qt5OpenGL PROPERTIES DESCRIPTION "C++ framework" URL http://qt-project.org)
|
||||
set_package_properties(Qt5OpenGL PROPERTIES TYPE RECOMMENDED PURPOSE "Building the examples")
|
||||
|
||||
IF(CMAKE_COMPILER_IS_GNUCXX) #Maybe "OR MINGW"
|
||||
ADD_DEFINITIONS(-std=c++0x) #Enable C++0x mode
|
||||
ENDIF()
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
ADD_DEFINITIONS(-std=c++0x) #Enable C++0x mode
|
||||
endif()
|
||||
|
||||
ADD_SUBDIRECTORY(include)
|
||||
|
||||
OPTION(ENABLE_EXAMPLES "Should the examples be built" ON)
|
||||
IF(ENABLE_EXAMPLES AND Qt5OpenGL_FOUND)
|
||||
ADD_SUBDIRECTORY(examples/Basic)
|
||||
ADD_SUBDIRECTORY(examples/Paging)
|
||||
ADD_SUBDIRECTORY(examples/OpenGL)
|
||||
ADD_SUBDIRECTORY(examples/SmoothLOD)
|
||||
ADD_SUBDIRECTORY(examples/DecodeOnGPU)
|
||||
ADD_SUBDIRECTORY(examples/Python)
|
||||
SET(BUILD_EXAMPLES ON)
|
||||
ELSE()
|
||||
SET(BUILD_EXAMPLES OFF)
|
||||
ENDIF()
|
||||
|
||||
INCLUDE(Packaging.cmake)
|
||||
|
||||
OPTION(ENABLE_TESTS "Should the tests be built" ON)
|
||||
IF(ENABLE_TESTS AND Qt5Test_FOUND)
|
||||
INCLUDE(CTest)
|
||||
MARK_AS_ADVANCED(FORCE BUILD_TESTING)
|
||||
ADD_SUBDIRECTORY(tests)
|
||||
SET(BUILD_TESTS ON)
|
||||
ELSE()
|
||||
SET(BUILD_TESTS OFF)
|
||||
ENDIF()
|
||||
|
||||
#Check if we will building _and_ bundling the docs
|
||||
IF(DOXYGEN_FOUND AND QT_QCOLLECTIONGENERATOR_EXECUTABLE)
|
||||
SET(BUILD_AND_BUNDLE_DOCS ON)
|
||||
ELSE()
|
||||
SET(BUILD_AND_BUNDLE_DOCS OFF)
|
||||
ENDIF()
|
||||
|
||||
ADD_SUBDIRECTORY(documentation)
|
||||
|
||||
ADD_SUBDIRECTORY(bindings)
|
||||
|
||||
add_feature_info("Examples" BUILD_EXAMPLES "Examples of PolyVox usage")
|
||||
add_feature_info("Tests" BUILD_TESTS "Unit tests")
|
||||
add_feature_info("Bindings" BUILD_BINDINGS "SWIG bindings")
|
||||
add_feature_info("API docs" DOXYGEN_FOUND "HTML documentation of the API")
|
||||
add_feature_info("Qt Help" BUILD_AND_BUNDLE_DOCS "API docs in Qt Help format")
|
||||
add_feature_info("Manual" BUILD_MANUAL "HTML user's manual")
|
||||
|
||||
feature_summary(WHAT ALL)
|
||||
|
||||
# Option summary
|
||||
MESSAGE(STATUS "")
|
||||
MESSAGE(STATUS "Summary")
|
||||
MESSAGE(STATUS "-------")
|
||||
MESSAGE(STATUS "Library type: " ${LIBRARY_TYPE})
|
||||
MESSAGE(STATUS "Build examples: " ${BUILD_EXAMPLES})
|
||||
MESSAGE(STATUS "Build tests: " ${BUILD_TESTS})
|
||||
MESSAGE(STATUS "Build bindings: " ${BUILD_BINDINGS})
|
||||
MESSAGE(STATUS "API Docs available: " ${DOXYGEN_FOUND})
|
||||
MESSAGE(STATUS " - Qt Help bundling: " ${BUILD_AND_BUNDLE_DOCS})
|
||||
MESSAGE(STATUS "Build manual: " ${BUILD_MANUAL})
|
||||
MESSAGE(STATUS "")
|
||||
|
12
CREDITS.txt
12
CREDITS.txt
@ -1,7 +1,7 @@
|
||||
David Williams - Lead programmer.
|
||||
Matthew Williams - Linux port, build system, support and maintenance.
|
||||
Oliver Schneider - Very large Volumes
|
||||
|
||||
Acknowledgements
|
||||
----------------
|
||||
David Williams - Lead programmer.
|
||||
Matthew Williams - Linux port, build system, support and maintenance.
|
||||
Oliver Schneider - Very large Volumes
|
||||
|
||||
Acknowledgements
|
||||
----------------
|
||||
PolyVox uses the 'miniz' for data compression. 'miniz' is public domain software and does not affect the license of PolyVox or of code using PolyVox. More details here: http://code.google.com/p/miniz/
|
@ -1,28 +1,28 @@
|
||||
# Copyright (c) 2010-2012 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
set(CTEST_PROJECT_NAME "PolyVox")
|
||||
set(CTEST_NIGHTLY_START_TIME "00:00:00 GMT")
|
||||
|
||||
set(CTEST_DROP_METHOD "http")
|
||||
set(CTEST_DROP_SITE "my.cdash.org")
|
||||
set(CTEST_DROP_LOCATION "/submit.php?project=PolyVox")
|
||||
set(CTEST_DROP_SITE_CDASH TRUE)
|
||||
# Copyright (c) 2010-2012 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
set(CTEST_PROJECT_NAME "PolyVox")
|
||||
set(CTEST_NIGHTLY_START_TIME "00:00:00 GMT")
|
||||
|
||||
set(CTEST_DROP_METHOD "http")
|
||||
set(CTEST_DROP_SITE "my.cdash.org")
|
||||
set(CTEST_DROP_LOCATION "/submit.php?project=PolyVox")
|
||||
set(CTEST_DROP_SITE_CDASH TRUE)
|
||||
|
258
INSTALL.txt
258
INSTALL.txt
@ -1,129 +1,129 @@
|
||||
****************
|
||||
Building PolyVox
|
||||
****************
|
||||
|
||||
Requirements
|
||||
============
|
||||
|
||||
To build PolyVox you need:
|
||||
|
||||
* `CMake <http://cmake.org>`_ 2.8.3 or greater
|
||||
* A C++ compiler with support for some C++0x features (GCC 4.3 or VC 2010 seem to work)
|
||||
|
||||
With the following optional packages:
|
||||
|
||||
* `Qt <http://qt.nokia.com>`_ for building the tests and the example applications
|
||||
* ``qcollectiongenerator`` which comes with Qt Assistant is used for bundling the docs for installation
|
||||
* `Doxygen <http://doxygen.org>`_ for building the documentation. Version 1.5.7 is needed to build the Qt Assistant docs. 1.7.0 or greater is recommended
|
||||
* `Python <http://python.org>`_, `Sphinx <http://sphinx.pocoo.org>`_ and `PyParsing <http://pyparsing.wikispaces.com/>`_ for generating the PolyVox manual in HTML
|
||||
* `Python development libraries <http://python.org>`_, `SWIG <http://swig.org/>`_ for generating the Python bindings
|
||||
|
||||
Linux
|
||||
=====
|
||||
|
||||
Navigate to the PolyVox source directory (the directory containing ``INSTALL.txt`` etc.) with and then enter the build directory with::
|
||||
|
||||
cd build
|
||||
|
||||
CMake
|
||||
-----
|
||||
|
||||
Now, we use CMake to generate the makefiles with::
|
||||
|
||||
cmake ..
|
||||
|
||||
The ``..`` tells CMake to look in the parent directory for the source.
|
||||
|
||||
By default this will set it to be installed in ``/usr/local`` so if you want to install it elsewhere, set the ``CMAKE_INSTALL_PREFIX`` variable to the path you want to install to.
|
||||
|
||||
You can set CMake variables by passing ``-D<variable>:<type>=<value>`` to the ``cmake`` command (the ``:<type>`` part is optional but recommended). For example, to set the install prefix, pass::
|
||||
|
||||
-DCMAKE_INSTALL_PREFIX:PATH=/whatever/you/want
|
||||
|
||||
The other available settings for PolyVox are:
|
||||
|
||||
``ENABLE_EXAMPLES`` (``ON`` or ``OFF``)
|
||||
Build the example applications that come with PolyVox. Defaults to ``ON``.
|
||||
|
||||
``ENABLE_TESTS`` (``ON`` or ``OFF``)
|
||||
Build the test applications that come with PolyVox. Running the tests is detailed in the next section. Defaults to ``ON``.
|
||||
|
||||
``ENABLE_BINDINGS`` (``ON`` or ``OFF``)
|
||||
Should the Python bindings to PolyVox be built. This requires the Python development libraries and SWIG to be installed. Defaults to ``ON``.
|
||||
|
||||
``LIBRARY_TYPE`` (``DYNAMIC`` or ``STATIC``)
|
||||
Choose whether static (``.a``) or dynamic libraries (``.so``) should be built. On Linux ``DYNAMIC`` is the default and on Windows ``STATIC`` is the default.
|
||||
|
||||
``CMAKE_BUILD_TYPE`` (``Debug``, ``Release``, ``RelWithDebInfo`` or ``MinSizeRel``)
|
||||
String option to set the type of build. This will automatically set some compilation flags such as the optimisation level or define ``NDEBUG``.
|
||||
|
||||
For development work against the library
|
||||
Use ``Debug`` or ``RelWithDebInfo``
|
||||
|
||||
For your final version
|
||||
Use ``Release``
|
||||
|
||||
For building packages (e.g. for Linux distributions)
|
||||
Use ``RelWithDebInfo``
|
||||
|
||||
Building and installing
|
||||
-----------------------
|
||||
|
||||
Once this has completed successfully, simply run::
|
||||
|
||||
make install
|
||||
|
||||
and all should work.
|
||||
|
||||
Testing
|
||||
-------
|
||||
|
||||
To run the tests you do not need to have run ``make install``. Simply run::
|
||||
|
||||
make
|
||||
make test
|
||||
|
||||
API Documentation
|
||||
-----------------
|
||||
|
||||
If you want to generate the API documentation, you'll need Doxygen installed. If you saw ``API Docs available: YES`` at the end of the CMake output then you're all set. To generate the docs, just run::
|
||||
|
||||
make doc
|
||||
|
||||
and the documentation can be browsed in plain HTML form at ``<build directory>/library/doc/html/index.html``.
|
||||
|
||||
On top of this, if ``qcollectiongenerator`` is installed, PolyVox can also compile and install this documentation as a *Qt Help Collection* file to ``<prefix>/share/doc/packages/polyvox/qthelp/polyvox.qhc`` (this file is in the build directory as ``<build directory>/library/doc/qthelp/polyvox.qhc``). To view this file you need Qt Assistant installed. You can open it with::
|
||||
|
||||
assistant -collectionFile library/doc/qthelp/polyvox.qhc
|
||||
|
||||
This allows indexed searching of the documentation and easier browsing.
|
||||
|
||||
Manual
|
||||
------
|
||||
|
||||
As well as the API documentation, PolyVox also provides a user manual. This is written using `Sphinx <http://sphinx.pocoo.org>`_ and so to convert the documentation sources to HTML requires Sphinx and Python to be installed. If these are installed and found then you will see ``Build manual: YES`` in the CMake summary output. If this is the case then just run::
|
||||
|
||||
make manual
|
||||
|
||||
and the HTML manual will be available at ``<build directory>/documentation/index.html``.
|
||||
|
||||
If you have Sphinx installed but you do not get the confirmation in the CMake output, you may need to set ``SPHINXBUILD_EXECUTABLE`` to the location of your ``sphinx-build`` executable.
|
||||
|
||||
If you do not have Python and Sphinx installed and do not want to install them then the manual is just plain text (``.rst`` files) which are readable in their plain form in the ``documentation`` directory of the source distribution.
|
||||
|
||||
Windows
|
||||
=======
|
||||
|
||||
For information about the dependencies, CMake configuration variables and buildable targets look at the Linux build information in the section above.
|
||||
|
||||
CMake
|
||||
-----
|
||||
|
||||
You need CMake installed so get the binary distribution from `CMake.org <http://cmake.org/cmake/resources/software.html>`_. Install it and run the CMake GUI.
|
||||
|
||||
Point the source directory to the directory holding this file and the build directory to the ``build`` subdirectory. Then, click the ``Configure`` button. Click through the dialog box that appears and once you've clicked ``Finish`` you should see text appearing in the bottom text area. Once this has finished, some options will appear in the top area. The purpose of these options in detailed in the Linux→CMake section above. Once you have set these options to what you please, click ``Configure`` again. If it completes without errors then you can click ``Generate`` which will generate your compilers project files in the build directory.
|
||||
|
||||
Building
|
||||
--------
|
||||
|
||||
Open the project files in your IDE and build the project as you normally would.
|
||||
****************
|
||||
Building PolyVox
|
||||
****************
|
||||
|
||||
Requirements
|
||||
============
|
||||
|
||||
To build PolyVox you need:
|
||||
|
||||
* `CMake <http://cmake.org>`_ 2.8.3 or greater
|
||||
* A C++ compiler with support for some C++0x features (GCC 4.3 or VC 2010 seem to work)
|
||||
|
||||
With the following optional packages:
|
||||
|
||||
* `Qt <http://qt.nokia.com>`_ for building the tests and the example applications
|
||||
* ``qcollectiongenerator`` which comes with Qt Assistant is used for bundling the docs for installation
|
||||
* `Doxygen <http://doxygen.org>`_ for building the documentation. Version 1.5.7 is needed to build the Qt Assistant docs. 1.7.0 or greater is recommended
|
||||
* `Python <http://python.org>`_, `Sphinx <http://sphinx.pocoo.org>`_ and `PyParsing <http://pyparsing.wikispaces.com/>`_ for generating the PolyVox manual in HTML
|
||||
* `Python development libraries <http://python.org>`_, `SWIG <http://swig.org/>`_ for generating the Python bindings
|
||||
|
||||
Linux
|
||||
=====
|
||||
|
||||
Navigate to the PolyVox source directory (the directory containing ``INSTALL.txt`` etc.) with and then enter the build directory with::
|
||||
|
||||
cd build
|
||||
|
||||
CMake
|
||||
-----
|
||||
|
||||
Now, we use CMake to generate the makefiles with::
|
||||
|
||||
cmake ..
|
||||
|
||||
The ``..`` tells CMake to look in the parent directory for the source.
|
||||
|
||||
By default this will set it to be installed in ``/usr/local`` so if you want to install it elsewhere, set the ``CMAKE_INSTALL_PREFIX`` variable to the path you want to install to.
|
||||
|
||||
You can set CMake variables by passing ``-D<variable>:<type>=<value>`` to the ``cmake`` command (the ``:<type>`` part is optional but recommended). For example, to set the install prefix, pass::
|
||||
|
||||
-DCMAKE_INSTALL_PREFIX:PATH=/whatever/you/want
|
||||
|
||||
The other available settings for PolyVox are:
|
||||
|
||||
``ENABLE_EXAMPLES`` (``ON`` or ``OFF``)
|
||||
Build the example applications that come with PolyVox. Defaults to ``ON``.
|
||||
|
||||
``ENABLE_TESTS`` (``ON`` or ``OFF``)
|
||||
Build the test applications that come with PolyVox. Running the tests is detailed in the next section. Defaults to ``ON``.
|
||||
|
||||
``ENABLE_BINDINGS`` (``ON`` or ``OFF``)
|
||||
Should the Python bindings to PolyVox be built. This requires the Python development libraries and SWIG to be installed. Defaults to ``ON``.
|
||||
|
||||
``LIBRARY_TYPE`` (``DYNAMIC`` or ``STATIC``)
|
||||
Choose whether static (``.a``) or dynamic libraries (``.so``) should be built. On Linux ``DYNAMIC`` is the default and on Windows ``STATIC`` is the default.
|
||||
|
||||
``CMAKE_BUILD_TYPE`` (``Debug``, ``Release``, ``RelWithDebInfo`` or ``MinSizeRel``)
|
||||
String option to set the type of build. This will automatically set some compilation flags such as the optimisation level or define ``NDEBUG``.
|
||||
|
||||
For development work against the library
|
||||
Use ``Debug`` or ``RelWithDebInfo``
|
||||
|
||||
For your final version
|
||||
Use ``Release``
|
||||
|
||||
For building packages (e.g. for Linux distributions)
|
||||
Use ``RelWithDebInfo``
|
||||
|
||||
Building and installing
|
||||
-----------------------
|
||||
|
||||
Once this has completed successfully, simply run::
|
||||
|
||||
make install
|
||||
|
||||
and all should work.
|
||||
|
||||
Testing
|
||||
-------
|
||||
|
||||
To run the tests you do not need to have run ``make install``. Simply run::
|
||||
|
||||
make
|
||||
make test
|
||||
|
||||
API Documentation
|
||||
-----------------
|
||||
|
||||
If you want to generate the API documentation, you'll need Doxygen installed. If you saw ``API Docs available: YES`` at the end of the CMake output then you're all set. To generate the docs, just run::
|
||||
|
||||
make doc
|
||||
|
||||
and the documentation can be browsed in plain HTML form at ``<build directory>/library/doc/html/index.html``.
|
||||
|
||||
On top of this, if ``qcollectiongenerator`` is installed, PolyVox can also compile and install this documentation as a *Qt Help Collection* file to ``<prefix>/share/doc/packages/polyvox/qthelp/polyvox.qhc`` (this file is in the build directory as ``<build directory>/library/doc/qthelp/polyvox.qhc``). To view this file you need Qt Assistant installed. You can open it with::
|
||||
|
||||
assistant -collectionFile library/doc/qthelp/polyvox.qhc
|
||||
|
||||
This allows indexed searching of the documentation and easier browsing.
|
||||
|
||||
Manual
|
||||
------
|
||||
|
||||
As well as the API documentation, PolyVox also provides a user manual. This is written using `Sphinx <http://sphinx.pocoo.org>`_ and so to convert the documentation sources to HTML requires Sphinx and Python to be installed. If these are installed and found then you will see ``Build manual: YES`` in the CMake summary output. If this is the case then just run::
|
||||
|
||||
make manual
|
||||
|
||||
and the HTML manual will be available at ``<build directory>/documentation/index.html``.
|
||||
|
||||
If you have Sphinx installed but you do not get the confirmation in the CMake output, you may need to set ``SPHINXBUILD_EXECUTABLE`` to the location of your ``sphinx-build`` executable.
|
||||
|
||||
If you do not have Python and Sphinx installed and do not want to install them then the manual is just plain text (``.rst`` files) which are readable in their plain form in the ``documentation`` directory of the source distribution.
|
||||
|
||||
Windows
|
||||
=======
|
||||
|
||||
For information about the dependencies, CMake configuration variables and buildable targets look at the Linux build information in the section above.
|
||||
|
||||
CMake
|
||||
-----
|
||||
|
||||
You need CMake installed so get the binary distribution from `CMake.org <http://cmake.org/cmake/resources/software.html>`_. Install it and run the CMake GUI.
|
||||
|
||||
Point the source directory to the directory holding this file and the build directory to the ``build`` subdirectory. Then, click the ``Configure`` button. Click through the dialog box that appears and once you've clicked ``Finish`` you should see text appearing in the bottom text area. Once this has finished, some options will appear in the top area. The purpose of these options in detailed in the Linux→CMake section above. Once you have set these options to what you please, click ``Configure`` again. If it completes without errors then you can click ``Generate`` which will generate your compilers project files in the build directory.
|
||||
|
||||
Building
|
||||
--------
|
||||
|
||||
Open the project files in your IDE and build the project as you normally would.
|
||||
|
40
LICENSE.TXT
40
LICENSE.TXT
@ -1,20 +1,20 @@
|
||||
Copyright (c) 2005-2012 David Williams and Matthew Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
Copyright (c) 2005-2012 David Williams and Matthew Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
|
110
Packaging.cmake
110
Packaging.cmake
@ -1,55 +1,55 @@
|
||||
# Copyright (c) 2009-2012 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
#INCLUDE(InstallRequiredSystemLibraries)
|
||||
|
||||
SET(CPACK_PACKAGE_NAME "PolyVox SDK")
|
||||
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "PolyVox SDK")
|
||||
SET(CPACK_PACKAGE_VENDOR "Thermite 3D Team")
|
||||
#SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/ReadMe.txt")
|
||||
#SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
|
||||
SET(CPACK_PACKAGE_VERSION_MAJOR ${POLYVOX_VERSION_MAJOR})
|
||||
SET(CPACK_PACKAGE_VERSION_MINOR ${POLYVOX_VERSION_MINOR})
|
||||
SET(CPACK_PACKAGE_VERSION_PATCH ${POLYVOX_VERSION_PATCH})
|
||||
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "PolyVox SDK ${POLYVOX_VERSION}")
|
||||
IF(WIN32 AND NOT UNIX)
|
||||
# There is a bug in NSIS that does not handle full unix paths properly.
|
||||
# Make sure there is at least one set of four backslashes.
|
||||
#SET(CPACK_PACKAGE_ICON "${CMake_SOURCE_DIR}/Utilities/Release\\\\InstallIcon.bmp")
|
||||
#SET(CPACK_NSIS_INSTALLED_ICON_NAME "bin\\\\MyExecutable.exe")
|
||||
SET(CPACK_NSIS_DISPLAY_NAME "PolyVox SDK ${POLYVOX_VERSION}")
|
||||
SET(CPACK_NSIS_HELP_LINK "http:\\\\\\\\thermite3d.org/phpBB/")
|
||||
SET(CPACK_NSIS_URL_INFO_ABOUT "http:\\\\\\\\thermite3d.org")
|
||||
SET(CPACK_NSIS_CONTACT "matt@milliams.com")
|
||||
SET(CPACK_NSIS_MODIFY_PATH ON)
|
||||
ELSE(WIN32 AND NOT UNIX)
|
||||
#SET(CPACK_STRIP_FILES "bin/MyExecutable")
|
||||
#SET(CPACK_SOURCE_STRIP_FILES "")
|
||||
ENDIF(WIN32 AND NOT UNIX)
|
||||
#SET(CPACK_PACKAGE_EXECUTABLES "MyExecutable" "My Executable")
|
||||
|
||||
INCLUDE(CPack)
|
||||
|
||||
CPACK_ADD_COMPONENT(library DISPLAY_NAME "Library" DESCRIPTION "The runtime libraries" REQUIRED)
|
||||
CPACK_ADD_COMPONENT(development DISPLAY_NAME "Development" DESCRIPTION "Files required for developing with PolyVox" DEPENDS library)
|
||||
CPACK_ADD_COMPONENT(example DISPLAY_NAME "OpenGL Example" DESCRIPTION "A PolyVox example application using OpenGL" DEPENDS library)
|
||||
cpack_add_component_group(bindings DISPLAY_NAME "Bindings" DESCRIPTION "Language bindings")
|
||||
CPACK_ADD_COMPONENT(python DISPLAY_NAME "Python Bindings" DESCRIPTION "PolyVox bindings for the Python language" DISABLED GROUP bindings DEPENDS library)
|
||||
# Copyright (c) 2009-2012 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
#INCLUDE(InstallRequiredSystemLibraries)
|
||||
|
||||
SET(CPACK_PACKAGE_NAME "PolyVox SDK")
|
||||
SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "PolyVox SDK")
|
||||
SET(CPACK_PACKAGE_VENDOR "Thermite 3D Team")
|
||||
#SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/ReadMe.txt")
|
||||
#SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
|
||||
SET(CPACK_PACKAGE_VERSION_MAJOR ${POLYVOX_VERSION_MAJOR})
|
||||
SET(CPACK_PACKAGE_VERSION_MINOR ${POLYVOX_VERSION_MINOR})
|
||||
SET(CPACK_PACKAGE_VERSION_PATCH ${POLYVOX_VERSION_PATCH})
|
||||
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "PolyVox SDK ${POLYVOX_VERSION}")
|
||||
IF(WIN32 AND NOT UNIX)
|
||||
# There is a bug in NSIS that does not handle full unix paths properly.
|
||||
# Make sure there is at least one set of four backslashes.
|
||||
#SET(CPACK_PACKAGE_ICON "${CMake_SOURCE_DIR}/Utilities/Release\\\\InstallIcon.bmp")
|
||||
#SET(CPACK_NSIS_INSTALLED_ICON_NAME "bin\\\\MyExecutable.exe")
|
||||
SET(CPACK_NSIS_DISPLAY_NAME "PolyVox SDK ${POLYVOX_VERSION}")
|
||||
SET(CPACK_NSIS_HELP_LINK "http:\\\\\\\\thermite3d.org/phpBB/")
|
||||
SET(CPACK_NSIS_URL_INFO_ABOUT "http:\\\\\\\\thermite3d.org")
|
||||
SET(CPACK_NSIS_CONTACT "matt@milliams.com")
|
||||
SET(CPACK_NSIS_MODIFY_PATH ON)
|
||||
ELSE(WIN32 AND NOT UNIX)
|
||||
#SET(CPACK_STRIP_FILES "bin/MyExecutable")
|
||||
#SET(CPACK_SOURCE_STRIP_FILES "")
|
||||
ENDIF(WIN32 AND NOT UNIX)
|
||||
#SET(CPACK_PACKAGE_EXECUTABLES "MyExecutable" "My Executable")
|
||||
|
||||
INCLUDE(CPack)
|
||||
|
||||
CPACK_ADD_COMPONENT(library DISPLAY_NAME "Library" DESCRIPTION "The runtime libraries" REQUIRED)
|
||||
CPACK_ADD_COMPONENT(development DISPLAY_NAME "Development" DESCRIPTION "Files required for developing with PolyVox" DEPENDS library)
|
||||
CPACK_ADD_COMPONENT(example DISPLAY_NAME "OpenGL Example" DESCRIPTION "A PolyVox example application using OpenGL" DEPENDS library)
|
||||
cpack_add_component_group(bindings DISPLAY_NAME "Bindings" DESCRIPTION "Language bindings")
|
||||
CPACK_ADD_COMPONENT(python DISPLAY_NAME "Python Bindings" DESCRIPTION "PolyVox bindings for the Python language" DISABLED GROUP bindings DEPENDS library)
|
||||
|
@ -1,5 +1,5 @@
|
||||
PolyVox - The voxel management and manipulation library
|
||||
=======================================================
|
||||
PolyVox is the core technology which lies behind our games. It is a fast, lightweight C++ library for the storage and processing of volumetric (voxel-based) environments. It has applications in both games and medical/scientific visualisation, and is released under the terms of the `zlib license <http://www.tldrlegal.com/l/ZLIB>`_.
|
||||
|
||||
PolyVox - The voxel management and manipulation library
|
||||
=======================================================
|
||||
PolyVox is the core technology which lies behind our games. It is a fast, lightweight C++ library for the storage and processing of volumetric (voxel-based) environments. It has applications in both games and medical/scientific visualisation, and is released under the terms of the `zlib license <http://www.tldrlegal.com/l/ZLIB>`_.
|
||||
|
||||
PolyVox is a relatively low-level library, and you will need experience in C++ and computer graphics/shaders to use it effectively. It is designed to be easily integrated into existing applications and is independent of your chosen graphics API. For more details please see `this page <http://www.volumesoffun.com/polyvox-about/>`_ on our website.
|
130
TODO.txt
130
TODO.txt
@ -1,65 +1,65 @@
|
||||
Discussed on forums
|
||||
===================
|
||||
Implement RLE compressor, and use it for blocks in memory and saving to disk.
|
||||
Replace shared_ptr's with intrinsic_ptrs?
|
||||
Make decimator work with cubic mesh
|
||||
Raycaster.
|
||||
|
||||
Short term
|
||||
==========
|
||||
Sort awkward use of 'offset'
|
||||
Replace float with uchar for material.
|
||||
Mesh smoothing (surface nets?)
|
||||
Mesh filters/modifiers - A 'translate' modifier?
|
||||
|
||||
|
||||
For Version 1.0
|
||||
===============
|
||||
Implement Memory Pool
|
||||
Clean up normal code - make normal generation a seperate pass.
|
||||
Implement mesh smoothing.
|
||||
Refine interface to mesh generateion - flags structure?
|
||||
Refine interface to volumes and iterators.
|
||||
Implement block volume tidy() funtion.
|
||||
Remove hard-coded region size.
|
||||
Seperate namespaces - PolyVoxCore, PolyVoxUtil, PolyVoxImpl
|
||||
Move getChangedRegionGeometry() out of PolyVon and into Thermite?
|
||||
Remove/refactor IndexedSurfacePatch? Incorporate into RegionGeometry?
|
||||
Change vertex format to ints?
|
||||
Check licensing, #regions, etc.
|
||||
Decimated version of marching cubes should use less memory.
|
||||
Unit test - compare output to reference implementation
|
||||
Sort awkward use of 'offset' in decimated marching cubes.
|
||||
Use of LinearVolume instead of arrays.
|
||||
Add API docs
|
||||
Add manual
|
||||
Finish OpenGL sample.
|
||||
VolumeChangeTracker can be more conservitive regarding when neighbouring regions are modified.
|
||||
|
||||
For Version 2.0
|
||||
===============
|
||||
Detect detatched regions.
|
||||
Handle mesh generation for detatched regions.
|
||||
Generate ambient lighting from volume?
|
||||
Utility function for closing outside surfaces?
|
||||
Consider how seperate surface should be generated for a single region.
|
||||
Consider transparent materials like glass.
|
||||
Allow writing meshes into volumes?
|
||||
|
||||
Documentation
|
||||
=============
|
||||
Define the following terms:
|
||||
-Voxel
|
||||
-Cell
|
||||
-Volume
|
||||
-Region
|
||||
-Block
|
||||
|
||||
Packaging
|
||||
=========
|
||||
Create components for the NSIS installer (Library, bindings, examples, documentation) - Half done
|
||||
Add License
|
||||
Add images for installer (and icons)
|
||||
Set LZMA compression
|
||||
Find a way to include both debug and release builds?
|
||||
The .lib files should be part of the 'development' configuration?
|
||||
Discussed on forums
|
||||
===================
|
||||
Implement RLE compressor, and use it for blocks in memory and saving to disk.
|
||||
Replace shared_ptr's with intrinsic_ptrs?
|
||||
Make decimator work with cubic mesh
|
||||
Raycaster.
|
||||
|
||||
Short term
|
||||
==========
|
||||
Sort awkward use of 'offset'
|
||||
Replace float with uchar for material.
|
||||
Mesh smoothing (surface nets?)
|
||||
Mesh filters/modifiers - A 'translate' modifier?
|
||||
|
||||
|
||||
For Version 1.0
|
||||
===============
|
||||
Implement Memory Pool
|
||||
Clean up normal code - make normal generation a seperate pass.
|
||||
Implement mesh smoothing.
|
||||
Refine interface to mesh generateion - flags structure?
|
||||
Refine interface to volumes and iterators.
|
||||
Implement block volume tidy() funtion.
|
||||
Remove hard-coded region size.
|
||||
Seperate namespaces - PolyVoxCore, PolyVoxUtil, PolyVoxImpl
|
||||
Move getChangedRegionGeometry() out of PolyVon and into Thermite?
|
||||
Remove/refactor IndexedSurfacePatch? Incorporate into RegionGeometry?
|
||||
Change vertex format to ints?
|
||||
Check licensing, #regions, etc.
|
||||
Decimated version of marching cubes should use less memory.
|
||||
Unit test - compare output to reference implementation
|
||||
Sort awkward use of 'offset' in decimated marching cubes.
|
||||
Use of LinearVolume instead of arrays.
|
||||
Add API docs
|
||||
Add manual
|
||||
Finish OpenGL sample.
|
||||
VolumeChangeTracker can be more conservitive regarding when neighbouring regions are modified.
|
||||
|
||||
For Version 2.0
|
||||
===============
|
||||
Detect detatched regions.
|
||||
Handle mesh generation for detatched regions.
|
||||
Generate ambient lighting from volume?
|
||||
Utility function for closing outside surfaces?
|
||||
Consider how seperate surface should be generated for a single region.
|
||||
Consider transparent materials like glass.
|
||||
Allow writing meshes into volumes?
|
||||
|
||||
Documentation
|
||||
=============
|
||||
Define the following terms:
|
||||
-Voxel
|
||||
-Cell
|
||||
-Volume
|
||||
-Region
|
||||
-Block
|
||||
|
||||
Packaging
|
||||
=========
|
||||
Create components for the NSIS installer (Library, bindings, examples, documentation) - Half done
|
||||
Add License
|
||||
Add images for installer (and icons)
|
||||
Set LZMA compression
|
||||
Find a way to include both debug and release builds?
|
||||
The .lib files should be part of the 'development' configuration?
|
||||
|
@ -1,10 +1,10 @@
|
||||
%module Array
|
||||
%{
|
||||
#include "PolyVoxImpl\SubArray.h"
|
||||
#include "Array.h"
|
||||
%}
|
||||
|
||||
%include "PolyVoxImpl\SubArray.h"
|
||||
%include "Array.h"
|
||||
|
||||
%template(Array3IndexAndMaterial) PolyVox::Array<3, PolyVox::IndexAndMaterial>;
|
||||
%module Array
|
||||
%{
|
||||
#include "PolyVoxImpl\SubArray.h"
|
||||
#include "Array.h"
|
||||
%}
|
||||
|
||||
%include "PolyVoxImpl\SubArray.h"
|
||||
%include "Array.h"
|
||||
|
||||
%template(Array3IndexAndMaterial) PolyVox::Array<3, PolyVox::IndexAndMaterial>;
|
@ -1,65 +1,65 @@
|
||||
# Copyright (c) 2009-2013 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
option(ENABLE_BINDINGS "Build bindings" ON)
|
||||
if(ENABLE_BINDINGS)
|
||||
find_package(SWIG)
|
||||
mark_as_advanced(SWIG_DIR SWIG_VERSION)
|
||||
find_package(PythonLibs 3)
|
||||
if(CMAKE_VERSION VERSION_LESS "2.8.6")
|
||||
set_package_info(SWIG "Bindings generator" http://www.swig.org)
|
||||
set_package_info(PythonLibs "Programming language" http://www.python.org)
|
||||
else()
|
||||
set_package_properties(SWIG PROPERTIES DESCRIPTION "Bindings generator" URL http://www.swig.org)
|
||||
set_package_properties(PythonLibs PROPERTIES DESCRIPTION "Programming language" URL http://www.python.org)
|
||||
endif()
|
||||
if(SWIG_FOUND)
|
||||
set(BUILD_BINDINGS ON CACHE BOOL "Will the bindings be built" FORCE)
|
||||
include(${SWIG_USE_FILE})
|
||||
|
||||
set(CMAKE_SWIG_FLAGS "")
|
||||
set_source_files_properties(PolyVoxCore.i PROPERTIES CPLUSPLUS ON)
|
||||
|
||||
if(PYTHONLIBS_FOUND)
|
||||
include_directories(${PYTHON_INCLUDE_PATH})
|
||||
include_directories(${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include/PolyVoxCore)
|
||||
link_directories(${PolyVoxCore_BINARY_DIR})
|
||||
|
||||
#set_source_files_properties(PolyVoxCore.i PROPERTIES SWIG_FLAGS "-builtin")
|
||||
set(SWIG_MODULE_PolyVoxCorePython_EXTRA_FLAGS "-py3")
|
||||
swig_add_module(PolyVoxCorePython python PolyVoxCore.i)
|
||||
swig_link_libraries(PolyVoxCorePython ${PYTHON_LIBRARIES} PolyVoxCore)
|
||||
set_target_properties(${SWIG_MODULE_PolyVoxCorePython_REAL_NAME} PROPERTIES OUTPUT_NAME _PolyVoxCore)
|
||||
#set_target_properties(${SWIG_MODULE_PolyVoxCore_REAL_NAME} PROPERTIES SUFFIX ".pyd")
|
||||
SET_PROPERTY(TARGET ${SWIG_MODULE_PolyVoxCorePython_REAL_NAME} PROPERTY FOLDER "Bindings")
|
||||
endif()
|
||||
|
||||
set(SWIG_MODULE_PolyVoxCoreCSharp_EXTRA_FLAGS "-dllimport;PolyVoxCoreCSharp") #This _should_ be inside UseSWIG.cmake - http://www.cmake.org/Bug/view.php?id=13814
|
||||
swig_add_module(PolyVoxCoreCSharp csharp PolyVoxCore.i)
|
||||
swig_link_libraries(PolyVoxCoreCSharp PolyVoxCore)
|
||||
SET_PROPERTY(TARGET ${SWIG_MODULE_PolyVoxCoreCSharp_REAL_NAME} PROPERTY FOLDER "Bindings")
|
||||
else()
|
||||
set(BUILD_BINDINGS OFF CACHE BOOL "Will the bindings be built" FORCE)
|
||||
endif()
|
||||
else()
|
||||
set(BUILD_BINDINGS OFF CACHE BOOL "Will the bindings be built" FORCE)
|
||||
endif()
|
||||
mark_as_advanced(FORCE BUILD_BINDINGS)
|
||||
# Copyright (c) 2009-2013 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
option(ENABLE_BINDINGS "Build bindings" OFF) #Off by default
|
||||
if(ENABLE_BINDINGS)
|
||||
find_package(SWIG)
|
||||
mark_as_advanced(SWIG_DIR SWIG_VERSION)
|
||||
find_package(PythonLibs 3)
|
||||
if(CMAKE_VERSION VERSION_LESS "2.8.6")
|
||||
set_package_info(SWIG "Bindings generator" http://www.swig.org)
|
||||
set_package_info(PythonLibs "Programming language" http://www.python.org)
|
||||
else()
|
||||
set_package_properties(SWIG PROPERTIES DESCRIPTION "Bindings generator" URL http://www.swig.org)
|
||||
set_package_properties(PythonLibs PROPERTIES DESCRIPTION "Programming language" URL http://www.python.org)
|
||||
endif()
|
||||
if(SWIG_FOUND)
|
||||
set(BUILD_BINDINGS ON CACHE BOOL "Will the bindings be built" FORCE)
|
||||
include(${SWIG_USE_FILE})
|
||||
|
||||
set(CMAKE_SWIG_FLAGS "")
|
||||
set_source_files_properties(PolyVoxCore.i PROPERTIES CPLUSPLUS ON)
|
||||
|
||||
include_directories(${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include/PolyVoxCore)
|
||||
if(PYTHONLIBS_FOUND)
|
||||
include_directories(${PYTHON_INCLUDE_PATH})
|
||||
link_directories(${PolyVoxCore_BINARY_DIR})
|
||||
|
||||
#set_source_files_properties(PolyVoxCore.i PROPERTIES SWIG_FLAGS "-builtin")
|
||||
set(SWIG_MODULE_PolyVoxCorePython_EXTRA_FLAGS "-py3")
|
||||
swig_add_module(PolyVoxCorePython python PolyVoxCore.i)
|
||||
swig_link_libraries(PolyVoxCorePython ${PYTHON_LIBRARIES} PolyVoxCore)
|
||||
set_target_properties(${SWIG_MODULE_PolyVoxCorePython_REAL_NAME} PROPERTIES OUTPUT_NAME _PolyVoxCore)
|
||||
#set_target_properties(${SWIG_MODULE_PolyVoxCore_REAL_NAME} PROPERTIES SUFFIX ".pyd")
|
||||
SET_PROPERTY(TARGET ${SWIG_MODULE_PolyVoxCorePython_REAL_NAME} PROPERTY FOLDER "Bindings")
|
||||
endif()
|
||||
|
||||
set(SWIG_MODULE_PolyVoxCoreCSharp_EXTRA_FLAGS "-dllimport;PolyVoxCoreCSharp") #This _should_ be inside UseSWIG.cmake - http://www.cmake.org/Bug/view.php?id=13814
|
||||
swig_add_module(PolyVoxCoreCSharp csharp PolyVoxCore.i)
|
||||
swig_link_libraries(PolyVoxCoreCSharp PolyVoxCore)
|
||||
SET_PROPERTY(TARGET ${SWIG_MODULE_PolyVoxCoreCSharp_REAL_NAME} PROPERTY FOLDER "Bindings")
|
||||
else()
|
||||
set(BUILD_BINDINGS OFF CACHE BOOL "Will the bindings be built" FORCE)
|
||||
endif()
|
||||
else()
|
||||
set(BUILD_BINDINGS OFF CACHE BOOL "Will the bindings be built" FORCE)
|
||||
endif()
|
||||
mark_as_advanced(FORCE BUILD_BINDINGS)
|
9
bindings/Chunk.i
Normal file
9
bindings/Chunk.i
Normal file
@ -0,0 +1,9 @@
|
||||
%module Chunk
|
||||
%{
|
||||
#include "Chunk.h"
|
||||
%}
|
||||
|
||||
%include "Chunk.h"
|
||||
|
||||
VOLUMETYPES(Chunk)
|
||||
|
9
bindings/CubicSurfaceExtractor.i
Normal file
9
bindings/CubicSurfaceExtractor.i
Normal file
@ -0,0 +1,9 @@
|
||||
%module CubicSurfaceExtractor
|
||||
%{
|
||||
#include "CubicSurfaceExtractor.h"
|
||||
%}
|
||||
|
||||
%include "CubicSurfaceExtractor.h"
|
||||
|
||||
%template(extractCubicMeshSimpleVolumeuint8) extractCubicMesh<PolyVox::PagedVolume<uint8_t> >;
|
||||
//EXTRACTORS(CubicSurfaceExtractor)
|
@ -1,8 +1,8 @@
|
||||
%module CubicSurfaceExtractorWithNormals
|
||||
%{
|
||||
#include "CubicSurfaceExtractorWithNormals.h"
|
||||
%}
|
||||
|
||||
%include "CubicSurfaceExtractorWithNormals.h"
|
||||
|
||||
%template(CubicSurfaceExtractorWithNormalsSimpleVolumeuint8) PolyVox::CubicSurfaceExtractorWithNormals<PolyVox::SimpleVolume<uint8_t>, PolyVox::DefaultIsQuadNeeded<uint8_t> >;
|
||||
%module CubicSurfaceExtractorWithNormals
|
||||
%{
|
||||
#include "CubicSurfaceExtractorWithNormals.h"
|
||||
%}
|
||||
|
||||
%include "CubicSurfaceExtractorWithNormals.h"
|
||||
|
||||
%template(CubicSurfaceExtractorWithNormalsSimpleVolumeuint8) PolyVox::CubicSurfaceExtractorWithNormals<PolyVox::SimpleVolume<uint8_t>, PolyVox::DefaultIsQuadNeeded<uint8_t> >;
|
@ -5,5 +5,5 @@
|
||||
|
||||
%include "MeshDecimator.h"
|
||||
|
||||
%template(MeshDecimatorMaterial8) PolyVox::MeshDecimator<PolyVox::Material8>;
|
||||
%template(MeshDecimatorMaterial8) PolyVox::MeshDecimator<PolyVox::Material8>;
|
||||
%template(MeshDecimatorDensity8) PolyVox::MeshDecimator<PolyVox::Density8>;
|
50
bindings/PagedVolume.i
Normal file
50
bindings/PagedVolume.i
Normal file
@ -0,0 +1,50 @@
|
||||
%module PagedVolume
|
||||
|
||||
#pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
|
||||
|
||||
namespace PolyVox
|
||||
{
|
||||
class PolyVox::PagedVolume_Chunk {
|
||||
public:
|
||||
PagedVolume_Chunk(Vector3DInt32 v3dPosition, uint16_t uSideLength, PolyVox::PagedVolume_Pager* pPager = nullptr);
|
||||
~PagedVolume_Chunk();
|
||||
|
||||
VoxelType* getData(void) const;
|
||||
uint32_t getDataSizeInBytes(void) const;
|
||||
|
||||
VoxelType getVoxel(uint16_t uXPos, uint16_t uYPos, uint16_t uZPos) const;
|
||||
VoxelType getVoxel(const Vector3DUint16& v3dPos) const;
|
||||
|
||||
void setVoxelAt(uint16_t uXPos, uint16_t uYPos, uint16_t uZPos, VoxelType tValue);
|
||||
void setVoxelAt(const Vector3DUint16& v3dPos, VoxelType tValue);
|
||||
};
|
||||
|
||||
class PolyVox::PagedVolume_Pager {
|
||||
public:
|
||||
/// Constructor
|
||||
PagedVolume_Pager() {};
|
||||
/// Destructor
|
||||
virtual ~PagedVolume_Pager() {};
|
||||
|
||||
virtual void pageIn(const Region& region, PagedVolume_Chunk* pChunk) = 0;
|
||||
virtual void pageOut(const Region& region, PagedVolume_Chunk* pChunk) = 0;
|
||||
};
|
||||
}
|
||||
|
||||
%{
|
||||
#include "PagedVolume.h"
|
||||
%}
|
||||
|
||||
%include "PagedVolume.h"
|
||||
|
||||
%{
|
||||
namespace PolyVox
|
||||
{
|
||||
// SWIG thinks that Inner is a global class, so we need to trick the C++
|
||||
// compiler into understanding this so called global type.
|
||||
typedef PagedVolume<int8_t>::Pager PagedVolume_Pager;
|
||||
typedef PagedVolume<int8_t>::Chunk PagedVolume_Chunk;
|
||||
}
|
||||
%}
|
||||
|
||||
VOLUMETYPES(PagedVolume)
|
@ -1,99 +1,93 @@
|
||||
%module PolyVoxCore
|
||||
|
||||
#define POLYVOX_API
|
||||
%include "PolyVoxCore/Impl/CompilerCapabilities.h"
|
||||
%include "Impl/TypeDef.h"
|
||||
#define __attribute__(x) //Silence DEPRECATED errors
|
||||
|
||||
//This macro allows us to use Python properties on our classes
|
||||
%define PROPERTY(type,name,getter,setter)
|
||||
%extend type {
|
||||
%pythoncode %{
|
||||
__swig_getmethods__["name"] = getter
|
||||
__swig_setmethods__["name"] = setter
|
||||
if _newclass: name = property(getter, setter)
|
||||
%}
|
||||
};
|
||||
%enddef
|
||||
|
||||
//Put this in an %extend section to wrap operator<< as __str__
|
||||
%define STR()
|
||||
const char* __str__() {
|
||||
std::ostringstream out;
|
||||
out << *$self;
|
||||
return out.str().c_str();
|
||||
}
|
||||
%enddef
|
||||
|
||||
//Centralise this to avoid repeating ourselves
|
||||
//This macro will be called in the volume interface files to define the various volume types.
|
||||
%define VOLUMETYPES(class)
|
||||
%template(class ## int8) PolyVox::class<int8_t>;
|
||||
%template(class ## int16) PolyVox::class<int16_t>;
|
||||
%template(class ## int32) PolyVox::class<int32_t>;
|
||||
%template(class ## uint8) PolyVox::class<uint8_t>;
|
||||
%template(class ## uint16) PolyVox::class<uint16_t>;
|
||||
%template(class ## uint32) PolyVox::class<uint32_t>;
|
||||
%template(class ## float) PolyVox::class<float>;
|
||||
%enddef
|
||||
|
||||
//Template based on voxel type
|
||||
%define EXTRACTOR(class, volumetype)
|
||||
%template(class ## volumetype ## int8) PolyVox::class<PolyVox::volumetype<int8_t> >;
|
||||
%template(class ## volumetype ## int16) PolyVox::class<PolyVox::volumetype<int16_t> >;
|
||||
%template(class ## volumetype ## int32) PolyVox::class<PolyVox::volumetype<int32_t> >;
|
||||
%template(class ## volumetype ## uint8) PolyVox::class<PolyVox::volumetype<uint8_t> >;
|
||||
%template(class ## volumetype ## uint16) PolyVox::class<PolyVox::volumetype<uint16_t> >;
|
||||
%template(class ## volumetype ## uint32) PolyVox::class<PolyVox::volumetype<uint32_t> >;
|
||||
%template(class ## volumetype ## float) PolyVox::class<PolyVox::volumetype<float> >;
|
||||
%enddef
|
||||
|
||||
//Template based on volume type
|
||||
%define EXTRACTORS(shortname)
|
||||
EXTRACTOR(shortname, SimpleVolume)
|
||||
EXTRACTOR(shortname, RawVolume)
|
||||
EXTRACTOR(shortname, LargeVolume)
|
||||
%enddef
|
||||
|
||||
%feature("autodoc", "1");
|
||||
|
||||
#ifdef SWIGPYTHON
|
||||
//This will rename "operator=" to "assign" since Python doesn't have assignment
|
||||
%rename(assign) *::operator=;
|
||||
#endif
|
||||
#ifdef SWIGCSHARP
|
||||
//These operators are not wrappable in C# and their function is provided by other means
|
||||
%ignore *::operator=;
|
||||
%ignore *::operator+=;
|
||||
%ignore *::operator-=;
|
||||
%ignore *::operator*=;
|
||||
%ignore *::operator/=;
|
||||
%ignore *::operator<<; //This is covered by STR()
|
||||
#endif
|
||||
|
||||
%include "stdint.i"
|
||||
%include "std_vector.i"
|
||||
%include "Vector.i"
|
||||
%include "DefaultMarchingCubesController.i"
|
||||
%include "Region.i"
|
||||
%include "Block.i"
|
||||
%include "CompressedBlock.i"
|
||||
%include "UncompressedBlock.i"
|
||||
%include "BlockCompressor.i"
|
||||
%include "Pager.i"
|
||||
%include "FilePager.i"
|
||||
%include "MinizBlockCompressor.i"
|
||||
%include "RLEBlockCompressor.i"
|
||||
%include "BaseVolume.i"
|
||||
%include "SimpleVolume.i"
|
||||
%include "RawVolume.i"
|
||||
%include "LargeVolume.i"
|
||||
//%include "SubArray.i"
|
||||
//%include "Array.i"
|
||||
%include "VertexTypes.i"
|
||||
%include "SurfaceMesh.i"
|
||||
%include "MarchingCubesSurfaceExtractor.i"
|
||||
%include "CubicSurfaceExtractor.i"
|
||||
%include "CubicSurfaceExtractorWithNormals.i"
|
||||
%include "Raycast.i"
|
||||
%include "Picking.i"
|
||||
%module PolyVoxCore
|
||||
|
||||
#define POLYVOX_API
|
||||
%include "Impl/TypeDef.h"
|
||||
#define __attribute__(x) //Silence DEPRECATED errors
|
||||
|
||||
//This macro allows us to use Python properties on our classes
|
||||
%define PROPERTY(type,name,getter,setter)
|
||||
%extend type {
|
||||
%pythoncode %{
|
||||
__swig_getmethods__["name"] = getter
|
||||
__swig_setmethods__["name"] = setter
|
||||
if _newclass: name = property(getter, setter)
|
||||
%}
|
||||
};
|
||||
%enddef
|
||||
|
||||
//Put this in an %extend section to wrap operator<< as __str__
|
||||
%define STR()
|
||||
const char* __str__() {
|
||||
std::ostringstream out;
|
||||
out << *$self;
|
||||
return out.str().c_str();
|
||||
}
|
||||
%enddef
|
||||
|
||||
//Centralise this to avoid repeating ourselves
|
||||
//This macro will be called in the volume interface files to define the various volume types.
|
||||
%define VOLUMETYPES(class)
|
||||
%template(class ## int8) PolyVox::class<int8_t>;
|
||||
//%template(class ## int16) PolyVox::class<int16_t>;
|
||||
//%template(class ## int32) PolyVox::class<int32_t>;
|
||||
//%template(class ## uint8) PolyVox::class<uint8_t>;
|
||||
//%template(class ## uint16) PolyVox::class<uint16_t>;
|
||||
//%template(class ## uint32) PolyVox::class<uint32_t>;
|
||||
//%template(class ## float) PolyVox::class<float>;
|
||||
%enddef
|
||||
|
||||
//Template based on voxel type
|
||||
%define EXTRACTOR(class, volumetype)
|
||||
%template(class ## volumetype ## int8) PolyVox::class<PolyVox::volumetype<int8_t> >;
|
||||
//%template(class ## volumetype ## int16) PolyVox::class<PolyVox::volumetype<int16_t> >;
|
||||
//%template(class ## volumetype ## int32) PolyVox::class<PolyVox::volumetype<int32_t> >;
|
||||
//%template(class ## volumetype ## uint8) PolyVox::class<PolyVox::volumetype<uint8_t> >;
|
||||
//%template(class ## volumetype ## uint16) PolyVox::class<PolyVox::volumetype<uint16_t> >;
|
||||
//%template(class ## volumetype ## uint32) PolyVox::class<PolyVox::volumetype<uint32_t> >;
|
||||
//%template(class ## volumetype ## float) PolyVox::class<PolyVox::volumetype<float> >;
|
||||
%enddef
|
||||
|
||||
//Template based on volume type
|
||||
%define EXTRACTORS(shortname)
|
||||
EXTRACTOR(shortname, PagedVolume)
|
||||
EXTRACTOR(shortname, RawVolume)
|
||||
%enddef
|
||||
|
||||
%feature("autodoc", "1");
|
||||
|
||||
#ifdef SWIGPYTHON
|
||||
//This will rename "operator=" to "assign" since Python doesn't have assignment
|
||||
%rename(assign) *::operator=;
|
||||
#endif
|
||||
#ifdef SWIGCSHARP
|
||||
//These operators are not wrappable in C# and their function is provided by other means
|
||||
%ignore *::operator=;
|
||||
%ignore *::operator+=;
|
||||
%ignore *::operator-=;
|
||||
%ignore *::operator*=;
|
||||
%ignore *::operator/=;
|
||||
%ignore *::operator<<; //This is covered by STR()
|
||||
#endif
|
||||
|
||||
%include "stdint.i"
|
||||
%include "std_vector.i"
|
||||
%include "Vector.i"
|
||||
%include "DefaultMarchingCubesController.i"
|
||||
%include "Region.i"
|
||||
//%include "Chunk.i"
|
||||
//%include "CompressedBlock.i"
|
||||
//%include "UncompressedBlock.i"
|
||||
//%include "BlockCompressor.i"
|
||||
//%include "Pager.i"
|
||||
//%include "FilePager.i"
|
||||
//%include "MinizBlockCompressor.i"
|
||||
//%include "RLEBlockCompressor.i"
|
||||
%include "BaseVolume.i"
|
||||
//%include "RawVolume.i"
|
||||
%include "PagedVolume.i"
|
||||
//%include "VertexTypes.i"
|
||||
//%include "SurfaceMesh.i"
|
||||
////%include "MarchingCubesSurfaceExtractor.i"
|
||||
////%include "CubicSurfaceExtractor.i"
|
||||
//%include "Raycast.i"
|
||||
//%include "Picking.i"
|
@ -1,9 +1,9 @@
|
||||
%module SimpleVolumeSampler
|
||||
%{
|
||||
#include "SimpleVolume.h"
|
||||
%}
|
||||
|
||||
%include "SimpleVolume.h"
|
||||
|
||||
%template(SimpleVolumeSamplerMaterial8) PolyVox::SimpleVolume::Sampler<PolyVox::Material8>;
|
||||
%module SimpleVolumeSampler
|
||||
%{
|
||||
#include "SimpleVolume.h"
|
||||
%}
|
||||
|
||||
%include "SimpleVolume.h"
|
||||
|
||||
%template(SimpleVolumeSamplerMaterial8) PolyVox::SimpleVolume::Sampler<PolyVox::Material8>;
|
||||
%template(SimpleVolumeSamplerDensity8) PolyVox::SimpleVolume::Sampler<PolyVox::Density8>;
|
@ -1,9 +1,9 @@
|
||||
%module SubArray
|
||||
%{
|
||||
#include "PolyVoxImpl\SubArray.h"
|
||||
%}
|
||||
|
||||
%include "PolyVoxImpl\SubArray.h"
|
||||
|
||||
//%template(SubArray) PolyVox::SubArray<uint32_t, PolyVox::IndexAndMaterial>;
|
||||
%module SubArray
|
||||
%{
|
||||
#include "PolyVoxImpl\SubArray.h"
|
||||
%}
|
||||
|
||||
%include "PolyVoxImpl\SubArray.h"
|
||||
|
||||
//%template(SubArray) PolyVox::SubArray<uint32_t, PolyVox::IndexAndMaterial>;
|
||||
//%template(SubArray) PolyVox::SubArray<uint32_t, PolyVox::IndexAndMaterial>;
|
20
bindings/SurfaceMesh.i
Normal file
20
bindings/SurfaceMesh.i
Normal file
@ -0,0 +1,20 @@
|
||||
%module SurfaceMesh
|
||||
%{
|
||||
#include "Region.h"
|
||||
#include "Vertex.h"
|
||||
#include "Mesh.h"
|
||||
%}
|
||||
|
||||
%include "Region.h"
|
||||
%include "Vertex.h"
|
||||
%include "Mesh.h"
|
||||
|
||||
//%template(VertexTypeVector) std::vector<PolyVox::VertexType>;
|
||||
//%template(PositionMaterialVector) std::vector<PolyVox::PositionMaterial>;
|
||||
//%template(PositionMaterialNormalVector) std::vector<PolyVox::PositionMaterialNormal>;
|
||||
//%template(LodRecordVector) std::vector<PolyVox::LodRecord>;
|
||||
//%template(uint8Vector) std::vector<uint8_t>;
|
||||
//%template(uint32Vector) std::vector<uint32_t>;
|
||||
|
||||
%template(MeshPositionMaterial) PolyVox::Mesh<PolyVox::CubicVertex<uint8_t>, uint16_t >;
|
||||
%template(MeshPositionMaterialNormal) PolyVox::Mesh<PolyVox::MarchingCubesVertex<uint8_t>, uint16_t >;
|
@ -1,6 +1,6 @@
|
||||
%module TypeDef
|
||||
%{
|
||||
#include "PolyVoxImpl/TypeDef.h"
|
||||
%}
|
||||
|
||||
%module TypeDef
|
||||
%{
|
||||
#include "PolyVoxImpl/TypeDef.h"
|
||||
%}
|
||||
|
||||
%include "PolyVoxImpl/TypeDef.h"
|
@ -1,121 +1,121 @@
|
||||
%module Vector
|
||||
%{
|
||||
#include "Vector.h"
|
||||
#include <sstream>
|
||||
%}
|
||||
|
||||
%include "Vector.h"
|
||||
|
||||
#ifdef SWIGPYTHON
|
||||
PROPERTY(PolyVox::Vector, x, getX, setX)
|
||||
PROPERTY(PolyVox::Vector, y, getY, setY)
|
||||
PROPERTY(PolyVox::Vector, z, getZ, setZ)
|
||||
#endif
|
||||
|
||||
%rename(Plus) operator +;
|
||||
%rename(Minus) operator -;
|
||||
%rename(Multiply) operator *;
|
||||
%rename(Divide) operator /;
|
||||
%rename(Equal) operator ==;
|
||||
%rename(NotEqual) operator !=;
|
||||
|
||||
%extend PolyVox::Vector {
|
||||
#ifdef SWIGPYTHON
|
||||
PolyVox::Vector __add__(const PolyVox::Vector& rhs) {
|
||||
return *$self + rhs;
|
||||
}
|
||||
PolyVox::Vector __sub__(const PolyVox::Vector& rhs) {
|
||||
return *$self - rhs;
|
||||
}
|
||||
PolyVox::Vector __div__(const PolyVox::Vector& rhs) {
|
||||
return *$self / rhs;
|
||||
}
|
||||
PolyVox::Vector __div__(const StorageType& rhs) {
|
||||
return *$self / rhs;
|
||||
}
|
||||
PolyVox::Vector __mul__(const PolyVox::Vector& rhs) {
|
||||
return *$self * rhs;
|
||||
}
|
||||
PolyVox::Vector __mul__(const StorageType& rhs) {
|
||||
return *$self * rhs;
|
||||
}
|
||||
#endif
|
||||
STR()
|
||||
};
|
||||
|
||||
%feature("pythonprepend") PolyVox::Vector::operator< %{
|
||||
import warnings
|
||||
warnings.warn("deprecated", DeprecationWarning)
|
||||
%}
|
||||
|
||||
//%csattributes PolyVox::Vector::operator< "[System.Obsolete(\"deprecated\")]"
|
||||
|
||||
%define VECTOR3(StorageType,OperationType,ReducedStorageType)
|
||||
#if SWIGCSHARP
|
||||
%extend PolyVox::Vector<3,StorageType,OperationType> {
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator+(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self + rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator-(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self - rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator*(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self * rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator/(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self / rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator*(const StorageType& rhs) {return *$self * rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator/(const StorageType& rhs) {return *$self / rhs;}
|
||||
};
|
||||
%typemap(cscode) PolyVox::Vector<3,StorageType,OperationType> %{
|
||||
public static Vector3D##StorageType operator+(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Plus(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator-(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Minus(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator*(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Multiply(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator/(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Divide(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator*(Vector3D##StorageType lhs, $typemap(cstype, StorageType) rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Multiply(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator/(Vector3D##StorageType lhs, $typemap(cstype, StorageType) rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Divide(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public bool Equals(Vector3D##StorageType rhs) {
|
||||
if ((object)rhs == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return Equal(rhs);
|
||||
}
|
||||
%}
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::operator<; //This is deprecated
|
||||
#endif
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::Vector(ReducedStorageType,ReducedStorageType,ReducedStorageType,ReducedStorageType);
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::Vector(ReducedStorageType,ReducedStorageType);
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::getW() const;
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::setW(ReducedStorageType);
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::setElements(ReducedStorageType,ReducedStorageType,ReducedStorageType,ReducedStorageType);
|
||||
%template(Vector3D ## StorageType) PolyVox::Vector<3,StorageType,OperationType>;
|
||||
%enddef
|
||||
|
||||
VECTOR3(float,float,float)
|
||||
VECTOR3(double,double,double)
|
||||
VECTOR3(int8_t,int32_t,signed char)
|
||||
VECTOR3(uint8_t,int32_t,unsigned char)
|
||||
VECTOR3(int16_t,int32_t,signed short)
|
||||
VECTOR3(uint16_t,int32_t,unsigned short)
|
||||
VECTOR3(int32_t,int32_t,signed int)
|
||||
VECTOR3(uint32_t,int32_t,unsigned int)
|
||||
|
||||
//%rename(assign) Vector3DFloat::operator=;
|
||||
%module Vector
|
||||
%{
|
||||
#include "Vector.h"
|
||||
#include <sstream>
|
||||
%}
|
||||
|
||||
%include "Vector.h"
|
||||
|
||||
#ifdef SWIGPYTHON
|
||||
PROPERTY(PolyVox::Vector, x, getX, setX)
|
||||
PROPERTY(PolyVox::Vector, y, getY, setY)
|
||||
PROPERTY(PolyVox::Vector, z, getZ, setZ)
|
||||
#endif
|
||||
|
||||
%rename(Plus) operator +;
|
||||
%rename(Minus) operator -;
|
||||
%rename(Multiply) operator *;
|
||||
%rename(Divide) operator /;
|
||||
%rename(Equal) operator ==;
|
||||
%rename(NotEqual) operator !=;
|
||||
|
||||
%extend PolyVox::Vector {
|
||||
#ifdef SWIGPYTHON
|
||||
PolyVox::Vector __add__(const PolyVox::Vector& rhs) {
|
||||
return *$self + rhs;
|
||||
}
|
||||
PolyVox::Vector __sub__(const PolyVox::Vector& rhs) {
|
||||
return *$self - rhs;
|
||||
}
|
||||
PolyVox::Vector __div__(const PolyVox::Vector& rhs) {
|
||||
return *$self / rhs;
|
||||
}
|
||||
PolyVox::Vector __div__(const StorageType& rhs) {
|
||||
return *$self / rhs;
|
||||
}
|
||||
PolyVox::Vector __mul__(const PolyVox::Vector& rhs) {
|
||||
return *$self * rhs;
|
||||
}
|
||||
PolyVox::Vector __mul__(const StorageType& rhs) {
|
||||
return *$self * rhs;
|
||||
}
|
||||
#endif
|
||||
STR()
|
||||
};
|
||||
|
||||
%feature("pythonprepend") PolyVox::Vector::operator< %{
|
||||
import warnings
|
||||
warnings.warn("deprecated", DeprecationWarning)
|
||||
%}
|
||||
|
||||
//%csattributes PolyVox::Vector::operator< "[System.Obsolete(\"deprecated\")]"
|
||||
|
||||
%define VECTOR3(StorageType,OperationType,ReducedStorageType)
|
||||
#if SWIGCSHARP
|
||||
%extend PolyVox::Vector<3,StorageType,OperationType> {
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator+(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self + rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator-(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self - rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator*(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self * rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator/(const PolyVox::Vector<3,StorageType,OperationType>& rhs) {return *$self / rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator*(const StorageType& rhs) {return *$self * rhs;}
|
||||
PolyVox::Vector<3,StorageType,OperationType> operator/(const StorageType& rhs) {return *$self / rhs;}
|
||||
};
|
||||
%typemap(cscode) PolyVox::Vector<3,StorageType,OperationType> %{
|
||||
public static Vector3D##StorageType operator+(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Plus(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator-(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Minus(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator*(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Multiply(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator/(Vector3D##StorageType lhs, Vector3D##StorageType rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Divide(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator*(Vector3D##StorageType lhs, $typemap(cstype, StorageType) rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Multiply(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public static Vector3D##StorageType operator/(Vector3D##StorageType lhs, $typemap(cstype, StorageType) rhs) {
|
||||
Vector3D##StorageType newVec = new Vector3D##StorageType();
|
||||
newVec = lhs.Divide(rhs);
|
||||
return newVec;
|
||||
}
|
||||
public bool Equals(Vector3D##StorageType rhs) {
|
||||
if ((object)rhs == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return Equal(rhs);
|
||||
}
|
||||
%}
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::operator<; //This is deprecated
|
||||
#endif
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::Vector(ReducedStorageType,ReducedStorageType,ReducedStorageType,ReducedStorageType);
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::Vector(ReducedStorageType,ReducedStorageType);
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::getW() const;
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::setW(ReducedStorageType);
|
||||
%ignore PolyVox::Vector<3,StorageType,OperationType>::setElements(ReducedStorageType,ReducedStorageType,ReducedStorageType,ReducedStorageType);
|
||||
%template(Vector3D ## StorageType) PolyVox::Vector<3,StorageType,OperationType>;
|
||||
%enddef
|
||||
|
||||
VECTOR3(float,float,float)
|
||||
VECTOR3(double,double,double)
|
||||
VECTOR3(int8_t,int32_t,signed char)
|
||||
VECTOR3(uint8_t,int32_t,unsigned char)
|
||||
VECTOR3(int16_t,int32_t,signed short)
|
||||
VECTOR3(uint16_t,int32_t,unsigned short)
|
||||
VECTOR3(int32_t,int32_t,signed int)
|
||||
VECTOR3(uint32_t,int32_t,unsigned int)
|
||||
|
||||
//%rename(assign) Vector3DFloat::operator=;
|
@ -1,13 +1,13 @@
|
||||
%module VertexTypes
|
||||
%{
|
||||
#include "Impl/TypeDef.h"
|
||||
#include "Vector.h"
|
||||
#include "VertexTypes.h"
|
||||
%}
|
||||
|
||||
%include "Impl/TypeDef.h"
|
||||
%include "Vector.h"
|
||||
%include "VertexTypes.h"
|
||||
|
||||
//%template (PositionMaterial) PolyVox::PositionMaterial;
|
||||
%module VertexTypes
|
||||
%{
|
||||
#include "Impl/TypeDef.h"
|
||||
#include "Vector.h"
|
||||
#include "Vertex.h"
|
||||
%}
|
||||
|
||||
%include "Impl/TypeDef.h"
|
||||
%include "Vector.h"
|
||||
%include "Vertex.h"
|
||||
|
||||
//%template (PositionMaterial) PolyVox::PositionMaterial;
|
||||
//%template (PositionMaterialNormal) PolyVox::PositionMaterialNormal;
|
@ -1,133 +0,0 @@
|
||||
# - Check which parts of the C++11 standard the compiler supports
|
||||
#
|
||||
# When found it will set the following variables
|
||||
#
|
||||
# CXX11_COMPILER_FLAGS - the compiler flags needed to get C++11 features
|
||||
#
|
||||
# HAS_CXX11_AUTO - auto keyword
|
||||
# HAS_CXX11_AUTO_RET_TYPE - function declaration with deduced return types
|
||||
# HAS_CXX11_CLASS_OVERRIDE - override and final keywords for classes and methods
|
||||
# HAS_CXX11_CONSTEXPR - constexpr keyword
|
||||
# HAS_CXX11_CSTDINT_H - cstdint header
|
||||
# HAS_CXX11_DECLTYPE - decltype keyword
|
||||
# HAS_CXX11_FUNC - __func__ preprocessor constant
|
||||
# HAS_CXX11_INITIALIZER_LIST - initializer list
|
||||
# HAS_CXX11_LAMBDA - lambdas
|
||||
# HAS_CXX11_LIB_REGEX - regex library
|
||||
# HAS_CXX11_LONG_LONG - long long signed & unsigned types
|
||||
# HAS_CXX11_NULLPTR - nullptr
|
||||
# HAS_CXX11_RVALUE_REFERENCES - rvalue references
|
||||
# HAS_CXX11_SIZEOF_MEMBER - sizeof() non-static members
|
||||
# HAS_CXX11_STATIC_ASSERT - static_assert()
|
||||
# HAS_CXX11_VARIADIC_TEMPLATES - variadic templates
|
||||
|
||||
#=============================================================================
|
||||
# Copyright 2011,2012 Rolf Eike Beer <eike@sf-mail.de>
|
||||
# Copyright 2012 Andreas Weis
|
||||
#
|
||||
# Distributed under the OSI-approved BSD License (the "License");
|
||||
# see accompanying file Copyright.txt for details.
|
||||
#
|
||||
# This software is distributed WITHOUT ANY WARRANTY; without even the
|
||||
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
# See the License for more information.
|
||||
#=============================================================================
|
||||
# (To distribute this file outside of CMake, substitute the full
|
||||
# License text for the above reference.)
|
||||
|
||||
if (NOT CMAKE_CXX_COMPILER_LOADED)
|
||||
message(FATAL_ERROR "CheckCXX11Features modules only works if language CXX is enabled")
|
||||
endif ()
|
||||
|
||||
cmake_minimum_required(VERSION 2.8.3)
|
||||
|
||||
#
|
||||
### Check for needed compiler flags
|
||||
#
|
||||
include(CheckCXXCompilerFlag)
|
||||
check_cxx_compiler_flag("-std=c++11" _HAS_CXX11_FLAG)
|
||||
if (NOT _HAS_CXX11_FLAG)
|
||||
check_cxx_compiler_flag("-std=c++0x" _HAS_CXX0X_FLAG)
|
||||
endif ()
|
||||
|
||||
if (_HAS_CXX11_FLAG)
|
||||
set(CXX11_COMPILER_FLAGS "-std=c++11")
|
||||
elseif (_HAS_CXX0X_FLAG)
|
||||
set(CXX11_COMPILER_FLAGS "-std=c++0x")
|
||||
endif ()
|
||||
|
||||
function(cxx11_check_feature FEATURE_NAME RESULT_VAR)
|
||||
if (NOT DEFINED ${RESULT_VAR})
|
||||
set(_bindir "${CMAKE_CURRENT_BINARY_DIR}/cxx11_${FEATURE_NAME}")
|
||||
|
||||
set(_SRCFILE_BASE ${CMAKE_CURRENT_LIST_DIR}/CheckCXX11Features/cxx11-test-${FEATURE_NAME})
|
||||
set(_LOG_NAME "\"${FEATURE_NAME}\"")
|
||||
message(STATUS "Checking C++11 support for ${_LOG_NAME}")
|
||||
|
||||
set(_SRCFILE "${_SRCFILE_BASE}.cpp")
|
||||
set(_SRCFILE_FAIL "${_SRCFILE_BASE}_fail.cpp")
|
||||
set(_SRCFILE_FAIL_COMPILE "${_SRCFILE_BASE}_fail_compile.cpp")
|
||||
|
||||
if (CROSS_COMPILING)
|
||||
try_compile(${RESULT_VAR} "${_bindir}" "${_SRCFILE}"
|
||||
COMPILE_DEFINITIONS "${CXX11_COMPILER_FLAGS}")
|
||||
if (${RESULT_VAR} AND EXISTS ${_SRCFILE_FAIL})
|
||||
try_compile(${RESULT_VAR} "${_bindir}_fail" "${_SRCFILE_FAIL}"
|
||||
COMPILE_DEFINITIONS "${CXX11_COMPILER_FLAGS}")
|
||||
endif (${RESULT_VAR} AND EXISTS ${_SRCFILE_FAIL})
|
||||
else (CROSS_COMPILING)
|
||||
try_run(_RUN_RESULT_VAR _COMPILE_RESULT_VAR
|
||||
"${_bindir}" "${_SRCFILE}"
|
||||
COMPILE_DEFINITIONS "${CXX11_COMPILER_FLAGS}")
|
||||
if (_COMPILE_RESULT_VAR AND NOT _RUN_RESULT_VAR)
|
||||
set(${RESULT_VAR} TRUE)
|
||||
else (_COMPILE_RESULT_VAR AND NOT _RUN_RESULT_VAR)
|
||||
set(${RESULT_VAR} FALSE)
|
||||
endif (_COMPILE_RESULT_VAR AND NOT _RUN_RESULT_VAR)
|
||||
if (${RESULT_VAR} AND EXISTS ${_SRCFILE_FAIL})
|
||||
try_run(_RUN_RESULT_VAR _COMPILE_RESULT_VAR
|
||||
"${_bindir}_fail" "${_SRCFILE_FAIL}"
|
||||
COMPILE_DEFINITIONS "${CXX11_COMPILER_FLAGS}")
|
||||
if (_COMPILE_RESULT_VAR AND _RUN_RESULT_VAR)
|
||||
set(${RESULT_VAR} TRUE)
|
||||
else (_COMPILE_RESULT_VAR AND _RUN_RESULT_VAR)
|
||||
set(${RESULT_VAR} FALSE)
|
||||
endif (_COMPILE_RESULT_VAR AND _RUN_RESULT_VAR)
|
||||
endif (${RESULT_VAR} AND EXISTS ${_SRCFILE_FAIL})
|
||||
endif (CROSS_COMPILING)
|
||||
if (${RESULT_VAR} AND EXISTS ${_SRCFILE_FAIL_COMPILE})
|
||||
try_compile(_TMP_RESULT "${_bindir}_fail_compile" "${_SRCFILE_FAIL_COMPILE}"
|
||||
COMPILE_DEFINITIONS "${CXX11_COMPILER_FLAGS}")
|
||||
if (_TMP_RESULT)
|
||||
set(${RESULT_VAR} FALSE)
|
||||
else (_TMP_RESULT)
|
||||
set(${RESULT_VAR} TRUE)
|
||||
endif (_TMP_RESULT)
|
||||
endif (${RESULT_VAR} AND EXISTS ${_SRCFILE_FAIL_COMPILE})
|
||||
|
||||
if (${RESULT_VAR})
|
||||
message(STATUS "Checking C++11 support for ${_LOG_NAME}: works")
|
||||
else (${RESULT_VAR})
|
||||
message(STATUS "Checking C++11 support for ${_LOG_NAME}: not supported")
|
||||
endif (${RESULT_VAR})
|
||||
set(${RESULT_VAR} ${${RESULT_VAR}} CACHE INTERNAL "C++11 support for ${_LOG_NAME}")
|
||||
endif (NOT DEFINED ${RESULT_VAR})
|
||||
endfunction(cxx11_check_feature)
|
||||
|
||||
#cxx11_check_feature("__func__" HAS_CXX11_FUNC)
|
||||
#cxx11_check_feature("auto" HAS_CXX11_AUTO)
|
||||
#cxx11_check_feature("auto_ret_type" HAS_CXX11_AUTO_RET_TYPE)
|
||||
#cxx11_check_feature("class_override_final" HAS_CXX11_CLASS_OVERRIDE)
|
||||
cxx11_check_feature("constexpr" HAS_CXX11_CONSTEXPR)
|
||||
cxx11_check_feature("cstdint" HAS_CXX11_CSTDINT_H)
|
||||
#cxx11_check_feature("decltype" HAS_CXX11_DECLTYPE)
|
||||
#cxx11_check_feature("initializer_list" HAS_CXX11_INITIALIZER_LIST)
|
||||
#cxx11_check_feature("lambda" HAS_CXX11_LAMBDA)
|
||||
#cxx11_check_feature("long_long" HAS_CXX11_LONG_LONG)
|
||||
#cxx11_check_feature("nullptr" HAS_CXX11_NULLPTR)
|
||||
#cxx11_check_feature("regex" HAS_CXX11_LIB_REGEX)
|
||||
#cxx11_check_feature("rvalue-references" HAS_CXX11_RVALUE_REFERENCES)
|
||||
#cxx11_check_feature("sizeof_member" HAS_CXX11_SIZEOF_MEMBER)
|
||||
cxx11_check_feature("static_assert" HAS_CXX11_STATIC_ASSERT)
|
||||
#cxx11_check_feature("variadic_templates" HAS_CXX11_VARIADIC_TEMPLATES)
|
||||
cxx11_check_feature("shared_ptr" HAS_CXX11_SHARED_PTR)
|
@ -1,8 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
if (!__func__)
|
||||
return 1;
|
||||
if (!(*__func__))
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
|
||||
int main()
|
||||
{
|
||||
auto i = 5;
|
||||
auto f = 3.14159f;
|
||||
auto d = 3.14159;
|
||||
bool ret = (
|
||||
(sizeof(f) < sizeof(d)) &&
|
||||
(sizeof(i) == sizeof(int))
|
||||
);
|
||||
return ret ? 0 : 1;
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
// must fail because there is no initializer
|
||||
auto i;
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
auto foo(int i) -> int {
|
||||
return i - 1;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
return foo(1);
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
class base {
|
||||
public:
|
||||
virtual int foo(int a)
|
||||
{ return 4 + a; }
|
||||
int bar(int a) final
|
||||
{ return a - 2; }
|
||||
};
|
||||
|
||||
class sub final : public base {
|
||||
public:
|
||||
virtual int foo(int a) override
|
||||
{ return 8 + 2 * a; };
|
||||
};
|
||||
|
||||
int main(void)
|
||||
{
|
||||
base b;
|
||||
sub s;
|
||||
|
||||
return (b.foo(2) * 2 == s.foo(2)) ? 0 : 1;
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
class base {
|
||||
public:
|
||||
virtual int foo(int a)
|
||||
{ return 4 + a; }
|
||||
virtual int bar(int a) final
|
||||
{ return a - 2; }
|
||||
};
|
||||
|
||||
class sub final : public base {
|
||||
public:
|
||||
virtual int foo(int a) override
|
||||
{ return 8 + 2 * a; };
|
||||
virtual int bar(int a)
|
||||
{ return a; }
|
||||
};
|
||||
|
||||
class impossible : public sub { };
|
||||
|
||||
int main(void)
|
||||
{
|
||||
base b;
|
||||
sub s;
|
||||
|
||||
return 1;
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
constexpr int square(int x)
|
||||
{
|
||||
return x*x;
|
||||
}
|
||||
|
||||
constexpr int the_answer()
|
||||
{
|
||||
return 42;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int test_arr[square(3)];
|
||||
bool ret = (
|
||||
(square(the_answer()) == 1764) &&
|
||||
(sizeof(test_arr)/sizeof(test_arr[0]) == 9)
|
||||
);
|
||||
return ret ? 0 : 1;
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
#include <cstdint>
|
||||
|
||||
int main()
|
||||
{
|
||||
bool test =
|
||||
(sizeof(int8_t) == 1) &&
|
||||
(sizeof(int16_t) == 2) &&
|
||||
(sizeof(int32_t) == 4) &&
|
||||
(sizeof(int64_t) == 8);
|
||||
return test ? 0 : 1;
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
bool check_size(int i)
|
||||
{
|
||||
return sizeof(int) == sizeof(decltype(i));
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
bool ret = check_size(42);
|
||||
return ret ? 0 : 1;
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
#include <vector>
|
||||
|
||||
class seq {
|
||||
public:
|
||||
seq(std::initializer_list<int> list);
|
||||
|
||||
int length() const;
|
||||
private:
|
||||
std::vector<int> m_v;
|
||||
};
|
||||
|
||||
seq::seq(std::initializer_list<int> list)
|
||||
: m_v(list)
|
||||
{
|
||||
}
|
||||
|
||||
int seq::length() const
|
||||
{
|
||||
return m_v.size();
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
seq a = {18, 20, 2, 0, 4, 7};
|
||||
|
||||
return (a.length() == 6) ? 0 : 1;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
int main()
|
||||
{
|
||||
int ret = 0;
|
||||
return ([&ret]() -> int { return ret; })();
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
long long l;
|
||||
unsigned long long ul;
|
||||
|
||||
return ((sizeof(l) >= 8) && (sizeof(ul) >= 8)) ? 0 : 1;
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
void *v = nullptr;
|
||||
|
||||
return v ? 1 : 0;
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
int i = nullptr;
|
||||
|
||||
return 1;
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
#include <algorithm>
|
||||
#include <regex>
|
||||
|
||||
int parse_line(std::string const& line)
|
||||
{
|
||||
std::string tmp;
|
||||
if(std::regex_search(line, std::regex("(\\s)+(-)?(\\d)+//(-)?(\\d)+(\\s)+"))) {
|
||||
tmp = std::regex_replace(line, std::regex("(-)?(\\d)+//(-)?(\\d)+"), std::string("V"));
|
||||
} else if(std::regex_search(line, std::regex("(\\s)+(-)?(\\d)+/(-)?(\\d)+(\\s)+"))) {
|
||||
tmp = std::regex_replace(line, std::regex("(-)?(\\d)+/(-)?(\\d)+"), std::string("V"));
|
||||
} else if(std::regex_search(line, std::regex("(\\s)+(-)?(\\d)+/(-)?(\\d)+/(-)?(\\d)+(\\s)+"))) {
|
||||
tmp = std::regex_replace(line, std::regex("(-)?(\\d)+/(-)?(\\d)+/(-)?(\\d)+"), std::string("V"));
|
||||
} else {
|
||||
tmp = std::regex_replace(line, std::regex("(-)?(\\d)+"), std::string("V"));
|
||||
}
|
||||
return static_cast<int>(std::count(tmp.begin(), tmp.end(), 'V'));
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
bool test = (parse_line("f 7/7/7 -3/3/-3 2/-2/2") == 3) &&
|
||||
(parse_line("f 7//7 3//-3 -2//2") == 3) &&
|
||||
(parse_line("f 7/7 3/-3 -2/2") == 3) &&
|
||||
(parse_line("f 7 3 -2") == 3);
|
||||
return test ? 0 : 1;
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
#include <cassert>
|
||||
|
||||
class rvmove {
|
||||
public:
|
||||
void *ptr;
|
||||
char *array;
|
||||
|
||||
rvmove()
|
||||
: ptr(0),
|
||||
array(new char[10])
|
||||
{
|
||||
ptr = this;
|
||||
}
|
||||
|
||||
rvmove(rvmove &&other)
|
||||
: ptr(other.ptr),
|
||||
array(other.array)
|
||||
{
|
||||
other.array = 0;
|
||||
other.ptr = 0;
|
||||
}
|
||||
|
||||
~rvmove()
|
||||
{
|
||||
assert(((ptr != 0) && (array != 0)) || ((ptr == 0) && (array == 0)));
|
||||
delete[] array;
|
||||
}
|
||||
|
||||
rvmove &operator=(rvmove &&other)
|
||||
{
|
||||
delete[] array;
|
||||
ptr = other.ptr;
|
||||
array = other.array;
|
||||
other.array = 0;
|
||||
other.ptr = 0;
|
||||
return *this;
|
||||
}
|
||||
|
||||
static rvmove create()
|
||||
{
|
||||
return rvmove();
|
||||
}
|
||||
private:
|
||||
rvmove(const rvmove &);
|
||||
rvmove &operator=(const rvmove &);
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
rvmove mine;
|
||||
if (mine.ptr != &mine)
|
||||
return 1;
|
||||
mine = rvmove::create();
|
||||
if (mine.ptr == &mine)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
#include <memory>
|
||||
|
||||
int main()
|
||||
{
|
||||
std::shared_ptr<int> test;
|
||||
return 0;
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
struct foo {
|
||||
char bar;
|
||||
int baz;
|
||||
};
|
||||
|
||||
int main(void)
|
||||
{
|
||||
bool ret = (
|
||||
(sizeof(foo::bar) == 1) &&
|
||||
(sizeof(foo::baz) >= sizeof(foo::bar)) &&
|
||||
(sizeof(foo) >= sizeof(foo::bar) + sizeof(foo::baz))
|
||||
);
|
||||
return ret ? 0 : 1;
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
struct foo {
|
||||
int baz;
|
||||
double bar;
|
||||
};
|
||||
|
||||
int main(void)
|
||||
{
|
||||
return (sizeof(foo::bar) == 4) ? 0 : 1;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
static_assert(0 < 1, "your ordering of integers is screwed");
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
int main(void)
|
||||
{
|
||||
static_assert(1 < 0, "your ordering of integers is screwed");
|
||||
return 0;
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
int Accumulate()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
template<typename T, typename... Ts>
|
||||
int Accumulate(T v, Ts... vs)
|
||||
{
|
||||
return v + Accumulate(vs...);
|
||||
}
|
||||
|
||||
template<int... Is>
|
||||
int CountElements()
|
||||
{
|
||||
return sizeof...(Is);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int acc = Accumulate(1, 2, 3, 4, -5);
|
||||
int count = CountElements<1,2,3,4,5>();
|
||||
return ((acc == 5) && (count == 5)) ? 0 : 1;
|
||||
}
|
@ -1,49 +1,49 @@
|
||||
# Copyright (c) 2010-2012 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
find_program(SPHINXBUILD_EXECUTABLE sphinx-build DOC "The location of the sphinx-build executable")
|
||||
|
||||
#if(SPHINXBUILD_EXECUTABLE AND QT_QCOLLECTIONGENERATOR_EXECUTABLE)
|
||||
if(SPHINXBUILD_EXECUTABLE)
|
||||
message(STATUS "Found `sphinx-build` at ${SPHINXBUILD_EXECUTABLE}")
|
||||
set(BUILD_MANUAL ON PARENT_SCOPE)
|
||||
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/conf.in.py ${CMAKE_CURRENT_BINARY_DIR}/conf.py @ONLY)
|
||||
#Generates the HTML docs and the Qt help file which can be opened with "assistant -collectionFile thermite.qhc"
|
||||
#add_custom_target(manual ${SPHINXBUILD_EXECUTABLE} -b qthelp ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${QT_QCOLLECTIONGENERATOR_EXECUTABLE} polyvox.qhcp -o polyvox.qhc)
|
||||
add_custom_target(manual
|
||||
${SPHINXBUILD_EXECUTABLE} -b html
|
||||
-c ${CMAKE_CURRENT_BINARY_DIR} #Load the conf.py from the binary dir
|
||||
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMENT "Building PolyVox manual"
|
||||
)
|
||||
add_dependencies(manual doc)
|
||||
set_target_properties(manual PROPERTIES PROJECT_LABEL "Manual") #Set label seen in IDE
|
||||
SET_PROPERTY(TARGET manual PROPERTY FOLDER "Documentation")
|
||||
else()
|
||||
if(NOT SPHINXBUILD_EXECUTABLE)
|
||||
message(STATUS "`sphinx-build` was not found. Try setting SPHINXBUILD_EXECUTABLE to its location.")
|
||||
endif()
|
||||
if(NOT QT_QCOLLECTIONGENERATOR_EXECUTABLE)
|
||||
message(STATUS "`qhelpgenerator` was not found. Try setting QT_QCOLLECTIONGENERATOR_EXECUTABLE to its location.")
|
||||
endif()
|
||||
set(BUILD_MANUAL OFF PARENT_SCOPE)
|
||||
endif()
|
||||
# Copyright (c) 2010-2012 Matt Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
find_program(SPHINXBUILD_EXECUTABLE sphinx-build DOC "The location of the sphinx-build executable")
|
||||
|
||||
#if(SPHINXBUILD_EXECUTABLE AND QT_QCOLLECTIONGENERATOR_EXECUTABLE)
|
||||
if(SPHINXBUILD_EXECUTABLE)
|
||||
message(STATUS "Found `sphinx-build` at ${SPHINXBUILD_EXECUTABLE}")
|
||||
set(BUILD_MANUAL ON PARENT_SCOPE)
|
||||
|
||||
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/conf.in.py ${CMAKE_CURRENT_BINARY_DIR}/conf.py @ONLY)
|
||||
#Generates the HTML docs and the Qt help file which can be opened with "assistant -collectionFile thermite.qhc"
|
||||
#add_custom_target(manual ${SPHINXBUILD_EXECUTABLE} -b qthelp ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} COMMAND ${QT_QCOLLECTIONGENERATOR_EXECUTABLE} polyvox.qhcp -o polyvox.qhc)
|
||||
add_custom_target(manual
|
||||
${SPHINXBUILD_EXECUTABLE} -b html
|
||||
-c ${CMAKE_CURRENT_BINARY_DIR} #Load the conf.py from the binary dir
|
||||
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMENT "Building PolyVox manual"
|
||||
)
|
||||
add_dependencies(manual doc)
|
||||
set_target_properties(manual PROPERTIES PROJECT_LABEL "Manual") #Set label seen in IDE
|
||||
SET_PROPERTY(TARGET manual PROPERTY FOLDER "Documentation")
|
||||
else()
|
||||
if(NOT SPHINXBUILD_EXECUTABLE)
|
||||
message(STATUS "`sphinx-build` was not found. Try setting SPHINXBUILD_EXECUTABLE to its location.")
|
||||
endif()
|
||||
if(NOT QT_QCOLLECTIONGENERATOR_EXECUTABLE)
|
||||
message(STATUS "`qhelpgenerator` was not found. Try setting QT_QCOLLECTIONGENERATOR_EXECUTABLE to its location.")
|
||||
endif()
|
||||
set(BUILD_MANUAL OFF PARENT_SCOPE)
|
||||
endif()
|
||||
|
@ -5,45 +5,42 @@ PolyVox includes a number of error handling features designed to help you identi
|
||||
|
||||
Logging
|
||||
=======
|
||||
PolyVox has a simple logging mechanism which allows it to write messages with an associated severity (from Debug up to Fatal). It is possible to redirect the output of these logging functions so you can integrate them with your applications logging framework or suppress them completely.
|
||||
PolyVox has a simple logging mechanism which allows it to write messages with an associated severity (from Debug up to Fatal). This logging mechanism is not really intended for use by client code (i.e. calling the logging macros from your own application) but you can of course do so at your own risk. However, it is possible to redirect the output of these logging functions so you can integrate them with your applications logging framework or suppress them completely.
|
||||
|
||||
The following functions are used as follows within PolyVox (note that newlines are appended automatically):
|
||||
Fatal messages are only issued in non-recoverable scenarios when the application is about to crash, and may provide the last piece of information you have about what went wrong. Error messages are issued when something has happened which prevents successful completion of a task, for example if you provide invalid parameters to a function (error messages are also issued whenever an exception is thrown). Warning messages mean the system was able to continue but the results may not be what you expected. Info messages are used for general information about what PolyVox is doing. Debug and trace messages produce very verbose output and a lot of detail about what PolyVox is doing internally. In general, debug messages are used for tasks the user has directly initiated (e.g. they might provide time information for surface extraction) while trace messages are used for things which happen spontaneously (such as data being paged out of memory).
|
||||
|
||||
To redirect log messages you can subclass Logger, create an instance, and set it as active as follows::
|
||||
|
||||
.. sourcecode :: c++
|
||||
|
||||
logTrace() << "Trace Message";
|
||||
logDebug() << "Debug Message";
|
||||
logInfo() << "Info Message";
|
||||
logWarning() << "Warning Message";
|
||||
logError() << "Error Message";
|
||||
logFatal() << "Fatal Message";
|
||||
class CustomLogger : public Logger
|
||||
{
|
||||
public:
|
||||
CustomLogger() : Logger() {}
|
||||
virtual ~CustomLogger() {}
|
||||
|
||||
Fatal messages are only issued in non-recoverable scenarios when the application is about to crash, and may provide the last peice of information you have about what went wrong. Error messages are issued when something has happened which prevents sucessful completion of a task, for example if you provide invalid parameters to a function (error messages are also issued whenever an exception is thrown). Warning messages mean the system was able to continue but the results may not be what you expected. Info messages are used for general information about what PolyVox is doing. Debug and trace messages produce very verbose output and a lot of detail about what PolyVox is doing internally. In general, debug messages are used for tasks the user has directly initiated (e.g. they might provide time information for surface extraction) while trace messages are used for things which happen spontaneously (such as data being paged out of memory). Trace messages are most likely to clutter up your logs and so are most easily suppressed.
|
||||
|
||||
To redirect log messages you can provide an implementation of std::ostream and apply it with one of the functions below:
|
||||
|
||||
.. sourcecode :: c++
|
||||
|
||||
setTraceStream(&myOutputStream);
|
||||
setDebugStream(&myOutputStream);
|
||||
setInfoStream(&myOutputStream);
|
||||
setWarningStream(&myOutputStream);
|
||||
setErrorStream(&myOutputStream);
|
||||
setFatalStream(&myOutputStream);
|
||||
|
||||
PolyVox provides a function called 'getNullStream()' which returns a stream which consumes all input without writing it anywhere. You can use this to supress particular log streams. For example, you can suppress the Trace stream with:
|
||||
|
||||
.. sourcecode :: c++
|
||||
|
||||
setTraceStream(getNullStream());
|
||||
void logTraceMessage(const std::string& message) { /* Do something with the message */ }
|
||||
void logDebugMessage(const std::string& message) { /* Do something with the message */ }
|
||||
void logInfoMessage(const std::string& message) { /* Do something with the message */ }
|
||||
void logWarningMessage(const std::string& message) { /* Do something with the message */ }
|
||||
void logErrorMessage(const std::string& message) { /* Do something with the message */ }
|
||||
void logFatalMessage(const std::string& message) { /* Do something with the message */ }
|
||||
};
|
||||
|
||||
Or you could direct it to std::cout with:
|
||||
CustomLogger* myCustomLogger = new CustomLogger();
|
||||
|
||||
setLogger(myCustomLogger);
|
||||
|
||||
When shutting down you should then do something like the following:
|
||||
|
||||
.. sourcecode :: c++
|
||||
|
||||
setTraceStream(&(std::cout));
|
||||
setLogger(myCustomLogger);
|
||||
delete myCustomLogger;
|
||||
|
||||
Note that by default the fatal, error and warning streams go to std::cerr, the info stream goes to std:cout, and the debug and trace streams are suppressed.
|
||||
Note that the default implementation (DefaultLogger) sends the fatal, error and warning streams to std::cerr, the info stream to std:cout, and that the debug and trace streams are suppressed.
|
||||
|
||||
PolyVox logging can be disabled completely in Config.h by undefining POLYVOX_LOG_TRACE_ENABLED through to POLYVOX_LOG_FATAL_ENABLED. Each of these can be disabled individually and the corresponding code will then be completely stripped from PolyVox. This is a compile-time setting - if you wish to change the log level at run-time then in your own implementation you could implement a filtering mechanism which only does something with the messages if some 'log severity' setting is greater than a certain threshold which can be changed at runtime.
|
||||
|
||||
Exceptions
|
||||
==========
|
||||
|
@ -1,25 +1,25 @@
|
||||
**************************
|
||||
Frequently Asked Questions
|
||||
**************************
|
||||
|
||||
Should I store my environment in a single big volume or break it down into several smaller ones?
|
||||
------------------------------------------------------------------------------------------------
|
||||
In most cases you should store you data in a single big volume, unless you are sure you understand the implications of doing otherwise.
|
||||
|
||||
Most algorithms in PolyVox operate on only a single volume (the exception to this are some of the image processing algorithms which use source and destination volumes, but even they use a *single* source and a *single* destination). The reason for this is that many algorithms require fast access to the neighbours of any given voxel. As an example, the surface extractors need to look at the neighbours of a voxel in order to determine whether triangles should be generated.
|
||||
|
||||
PolyVox volumes make it easy to access these neighbours, but the situation gets complex on the edge of a volume because the neighbouring voxels may not exist. It is possible to define a border value (which will be returned whenever you try to read a voxel outside the volume) but this doesn't handle all scenarios in the desired way. Often the most practical solution is to make the volume slightly larger than the data it needs to contain, and then avoid having your algorithms go right to the edge.
|
||||
|
||||
Having established that edge cases can be problematic, we can now see that storing your data as a set of adjacent volumes is undesirable because these edge cases then exist throughout the data set. This causes a lot of problems such as gaps between pieces of extracted terrain or discontinuities in the computed normals.
|
||||
|
||||
The usual reason why people attempt to break their terrain into separate volumes is so that they can perform some more advanced memory management for very big terrain, for example by only loading particular volumes into memory when they are within a certain distance from the camera. However, this kind of paging behaviour is already implemented by the LargeVolume class. The LargeVolume internally stores its data as a set of blocks, and does it in such a way that it is able to perform neighbourhood access across block boundaries. Whenever you find yourself trying to break terrain data into separate volumes you should probably use the LargeVolume instead.
|
||||
|
||||
Note that although you should only use a single volume for your data, it is still recommended that you split the mesh data into multiple pieces so that they can be culled against the view frustum, and so that you can update the smaller pieces more quickly when you need to. You can extract meshes from different parts of the volume by passing a Region to the surface extractor.
|
||||
|
||||
Lastly, note that there are exceptions to the 'one volume' rule. An example might be if you had a number of planets in space, in which case each planet could safely be a separate volume. These planets never touch, and so the artifacts which would occur on volume boundaries do not cause a problem.
|
||||
|
||||
Can I combine smooth meshes with cubic ones?
|
||||
--------------------------------------------
|
||||
We have never attempted to do this but in theory it should be possible. One option is simply to generate two meshes (one using the MarchingCubesSurfaceExtractor and the other using the CubicSurfaceExtractor) and render them on top of each other while allowing the depth buffer to resolve the intersections. Combining these two meshes into a single mesh is likely to be difficult as they use different vertex formats and have different texturing requirements (see the document on texture mapping).
|
||||
|
||||
**************************
|
||||
Frequently Asked Questions
|
||||
**************************
|
||||
|
||||
Should I store my environment in a single big volume or break it down into several smaller ones?
|
||||
------------------------------------------------------------------------------------------------
|
||||
In most cases you should store you data in a single big volume, unless you are sure you understand the implications of doing otherwise.
|
||||
|
||||
Most algorithms in PolyVox operate on only a single volume (the exception to this are some of the image processing algorithms which use source and destination volumes, but even they use a *single* source and a *single* destination). The reason for this is that many algorithms require fast access to the neighbours of any given voxel. As an example, the surface extractors need to look at the neighbours of a voxel in order to determine whether triangles should be generated.
|
||||
|
||||
PolyVox volumes make it easy to access these neighbours, but the situation gets complex on the edge of a volume because the neighbouring voxels may not exist. It is possible to define a border value (which will be returned whenever you try to read a voxel outside the volume) but this doesn't handle all scenarios in the desired way. Often the most practical solution is to make the volume slightly larger than the data it needs to contain, and then avoid having your algorithms go right to the edge.
|
||||
|
||||
Having established that edge cases can be problematic, we can now see that storing your data as a set of adjacent volumes is undesirable because these edge cases then exist throughout the data set. This causes a lot of problems such as gaps between pieces of extracted terrain or discontinuities in the computed normals.
|
||||
|
||||
The usual reason why people attempt to break their terrain into separate volumes is so that they can perform some more advanced memory management for very big terrain, for example by only loading particular volumes into memory when they are within a certain distance from the camera. However, this kind of paging behaviour is already implemented by the LargeVolume class. The LargeVolume internally stores its data as a set of blocks, and does it in such a way that it is able to perform neighbourhood access across block boundaries. Whenever you find yourself trying to break terrain data into separate volumes you should probably use the LargeVolume instead.
|
||||
|
||||
Note that although you should only use a single volume for your data, it is still recommended that you split the mesh data into multiple pieces so that they can be culled against the view frustum, and so that you can update the smaller pieces more quickly when you need to. You can extract meshes from different parts of the volume by passing a Region to the surface extractor.
|
||||
|
||||
Lastly, note that there are exceptions to the 'one volume' rule. An example might be if you had a number of planets in space, in which case each planet could safely be a separate volume. These planets never touch, and so the artifacts which would occur on volume boundaries do not cause a problem.
|
||||
|
||||
Can I combine smooth meshes with cubic ones?
|
||||
--------------------------------------------
|
||||
We have never attempted to do this but in theory it should be possible. One option is simply to generate two meshes (one using the MarchingCubesSurfaceExtractor and the other using the CubicSurfaceExtractor) and render them on top of each other while allowing the depth buffer to resolve the intersections. Combining these two meshes into a single mesh is likely to be difficult as they use different vertex formats and have different texturing requirements (see the document on texture mapping).
|
||||
|
||||
An alternative possibility may be to create a new surface extractor based on the Surface Nets (link) algorithm. The idea here is that the mesh would start with a cubic shape, but as the net was stretched it would be smoothed. The degree of smoothing could be controlled by a voxel property which could allow the full range from cubic to smooth to exist in a single mesh. As mentioned above, this may mean that some extra work has to be put into a fragment shader which is capable of texturing this kind of mesh. Come by the forums of you want to discuss this further.
|
@ -1,48 +1,48 @@
|
||||
***************
|
||||
Level of Detail
|
||||
***************
|
||||
When the PolyVox surface extractors are applied to volume data the resulting mesh can contain a very high number of triangles. For large voxel worlds this can cause both performance and memory problems. The performance problems occur due the the load on the vertex shader which has to process a large number of vertices, and also due to the setup costs of a large number of tiny (possibly sub-pixel) triangles. The memory costs result simply from having a large amount of data which does not actually contribute to the visual appearance of the scene.
|
||||
|
||||
For these reasons it is desirable to reduce the triangle count of the meshes as far as possible, especially as meshes move away from the camera. This document describes the various approaches which are available within PolyVox to achieve this. Generally these approaches are different for cubic meshes vs smooth meshes and so we address these cases separately.
|
||||
|
||||
Cubic Meshes
|
||||
============
|
||||
A naive implementation of a cubic surface extractor would generate a mesh containing a quad for voxel face which lies on the boundary between a solid and an empty voxel. The CubicSurfaceExtractor is indeed capable of generating such a mesh, but it also provides the option to merge adjacent quads into a single quad subject to various conditions being satisfied (e.g. the faces must have the same material). This merging process drastically reduces the amount of geometry which must be drawn but does not modify the shape of the mesh. Because of these desirable properties such merging is performed by default, but it can be disabled if necessary.
|
||||
|
||||
To our knowledge the only drawback of performing this quad merging is that it can create T-junctions in the resulting mesh. T-junctions are an undesirable property of mesh geometry because they can cause tiny cracks (usually just seen as flickering pixels) to occur between quads. The figure below shows a mesh before quad merging, a mesh where the merged quads have caused T-junctions, and how the resulting rendering might look (note the single pixel holes along the quad border).
|
||||
|
||||
*Add figure here...*
|
||||
|
||||
Vertices C and D are supposed to lie exactly along the line which has A and B as its end points, so in theory the mesh should be valid and should render correctly. The reason T-junctions cause a problem in practice is due to limitations of the floating point number representation. Depending on the transformations which are applied, it may be that the positions of C and/or D can not be represented precisely enough to exactly lie on the line between A and B.
|
||||
|
||||
*Demo correct mesh. mention we don't have a solution to generate it.*
|
||||
|
||||
Whether it's a problem in practice depends on hardware precision (16/32 bit), distance from origin, number of transforms which are applied, and probably a number of other factors. We have yet to investigate.
|
||||
|
||||
We don't currently have a real solution to this problem. In Voxeliens the borders between voxels were darkened to simulate ambient occlusion and this had the desirable side effect of making any flickering pixels very hard to see. It's also possible that anti-aliasing strategies can reduce the problem, and storing vertex positions as integers may help as well. Lastly, it may be possible to construct some kind of post-process which would repair the image where it identifies single pixel discontinuities in the depth buffer.
|
||||
|
||||
Smooth Meshes
|
||||
=============
|
||||
Level of detail for smooth meshes is a lot more complex than for cubic ones, and we'll admit upfront that we do not currently have a good solution to this problem. None the less, we do have a couple of partial solutions which you might be able to use or adapt for your specific scenario.
|
||||
|
||||
Techniques for performing level of detail on smooth meshes basically fall into two categories. The first category involves reducing the resolution of the volume data and then running the surface extractor on the smaller volume. This naturally generates a lower detail mesh which must then be scaled up to match the other meshes in the scene. The second category involves generating the mesh at full detail and then using traditional mesh simplification techniques to reduces the number of triangles. Both techniques are explored in more detail below.
|
||||
|
||||
Volume Reduction
|
||||
----------------
|
||||
The VolumeResampler class can be used to copy volume data from a source region to a destination region, and it handles the resampling of the voxel values in the event that the source and destination regions are not the same size. This is exactly what we need for implementing level of detail and the principle is demonstrated by the SmoothLOD sample (see the documentation for the SmoothLOD sample for more information).
|
||||
|
||||
One of the problems with this approach is that the lower resolution mesh does not *exactly* line up with the higher resolution mesh, and this can cause cracks to be visible where the two meshes meet. The SmoothLOD sample attempts to avoid this problem by overlapping the meshes slightly but this may not be effective in all situations or from all viewpoints.
|
||||
|
||||
An alternative is the Transvoxel algorithm (link) developed by Eric Lengyel. This essentially extends the original Marching Cubes lookup table with additional entries which handle seamless transitions between LOD levels, and it is a very promising solution to level of detail for voxel terrain. At this point in time we do not have an implementation of this algorithm but work is being undertaking in the area. For the latest developments see: http://www.volumesoffun.com/phpBB3/viewtopic.php?f=2&t=338
|
||||
|
||||
However, in all volume reduction approaches there is some uncertainty about how materials should be handled. Creating a lower resolution volume means that several voxel values from the high resolution volume need to be combined into a single value. For density values this is straightforward as a simple average gives good results, but it is not clear how this extends to material identifiers. Averaging them doesn't make sense, and it is hard to imagine an approach which would not lead to visible artifacts as LOD levels change. Perhaps the visible effects can be reduced by blending between two LOD levels, but more investigation needs to be done here.
|
||||
|
||||
Mesh Simplification
|
||||
-------------------
|
||||
The other main approach is to generate the mesh at the full resolution and then reduce the number of triangles using a postprocessing step. This can draw on the large body of mesh simplification research (link to survey) and typically involves merging adjacent faces or collapsing vertices. When using this approach there are a couple of additional complications compared to the implementations which are normally seen.
|
||||
|
||||
The first additional complication is that the decimation algorithm needs to preserve material boundaries so that they don't move between LOD levels. When choosing whether a particular simplification can be made (i.e deciding if one vertex can be collapsed on to another or whether two faces can be merged) a metric is usually used to determine how much the simplification would affect the visual appearance of the mesh. When working with smooth voxel meshes this metric needs to also consider the material identifiers.
|
||||
|
||||
We also need to ensure that the metric preserves the geometric boundary of the mesh, so that no cracks are visible when a simplified mesh is place next to an original one. Maintaining this geometric boundary can be difficult, as the straightforward approach of locking the edge vertices in place will tend to limit the amount of simplification which can be performed. Alternatively, cracks can be allowed to develop if they are later hidden through the use of 'skirts' around the resulting mesh.
|
||||
|
||||
PolyVox used to contain code for performing simplification of the smooth voxel meshes, but unfortunately it had significant performance and functionality issues. Therefore it has been deprecated and it will be removed in a future version of the library. We will instead investigate the use of external mesh simplification libraries and OpenMesh (link) may be a good candidate here.
|
||||
***************
|
||||
Level of Detail
|
||||
***************
|
||||
When the PolyVox surface extractors are applied to volume data the resulting mesh can contain a very high number of triangles. For large voxel worlds this can cause both performance and memory problems. The performance problems occur due the the load on the vertex shader which has to process a large number of vertices, and also due to the setup costs of a large number of tiny (possibly sub-pixel) triangles. The memory costs result simply from having a large amount of data which does not actually contribute to the visual appearance of the scene.
|
||||
|
||||
For these reasons it is desirable to reduce the triangle count of the meshes as far as possible, especially as meshes move away from the camera. This document describes the various approaches which are available within PolyVox to achieve this. Generally these approaches are different for cubic meshes vs smooth meshes and so we address these cases separately.
|
||||
|
||||
Cubic Meshes
|
||||
============
|
||||
A naive implementation of a cubic surface extractor would generate a mesh containing a quad for voxel face which lies on the boundary between a solid and an empty voxel. The CubicSurfaceExtractor is indeed capable of generating such a mesh, but it also provides the option to merge adjacent quads into a single quad subject to various conditions being satisfied (e.g. the faces must have the same material). This merging process drastically reduces the amount of geometry which must be drawn but does not modify the shape of the mesh. Because of these desirable properties such merging is performed by default, but it can be disabled if necessary.
|
||||
|
||||
To our knowledge the only drawback of performing this quad merging is that it can create T-junctions in the resulting mesh. T-junctions are an undesirable property of mesh geometry because they can cause tiny cracks (usually just seen as flickering pixels) to occur between quads. The figure below shows a mesh before quad merging, a mesh where the merged quads have caused T-junctions, and how the resulting rendering might look (note the single pixel holes along the quad border).
|
||||
|
||||
*Add figure here...*
|
||||
|
||||
Vertices C and D are supposed to lie exactly along the line which has A and B as its end points, so in theory the mesh should be valid and should render correctly. The reason T-junctions cause a problem in practice is due to limitations of the floating point number representation. Depending on the transformations which are applied, it may be that the positions of C and/or D can not be represented precisely enough to exactly lie on the line between A and B.
|
||||
|
||||
*Demo correct mesh. mention we don't have a solution to generate it.*
|
||||
|
||||
Whether it's a problem in practice depends on hardware precision (16/32 bit), distance from origin, number of transforms which are applied, and probably a number of other factors. We have yet to investigate.
|
||||
|
||||
We don't currently have a real solution to this problem. In Voxeliens the borders between voxels were darkened to simulate ambient occlusion and this had the desirable side effect of making any flickering pixels very hard to see. It's also possible that anti-aliasing strategies can reduce the problem, and storing vertex positions as integers may help as well. Lastly, it may be possible to construct some kind of post-process which would repair the image where it identifies single pixel discontinuities in the depth buffer.
|
||||
|
||||
Smooth Meshes
|
||||
=============
|
||||
Level of detail for smooth meshes is a lot more complex than for cubic ones, and we'll admit upfront that we do not currently have a good solution to this problem. None the less, we do have a couple of partial solutions which you might be able to use or adapt for your specific scenario.
|
||||
|
||||
Techniques for performing level of detail on smooth meshes basically fall into two categories. The first category involves reducing the resolution of the volume data and then running the surface extractor on the smaller volume. This naturally generates a lower detail mesh which must then be scaled up to match the other meshes in the scene. The second category involves generating the mesh at full detail and then using traditional mesh simplification techniques to reduces the number of triangles. Both techniques are explored in more detail below.
|
||||
|
||||
Volume Reduction
|
||||
----------------
|
||||
The VolumeResampler class can be used to copy volume data from a source region to a destination region, and it handles the resampling of the voxel values in the event that the source and destination regions are not the same size. This is exactly what we need for implementing level of detail and the principle is demonstrated by the SmoothLOD sample (see the documentation for the SmoothLOD sample for more information).
|
||||
|
||||
One of the problems with this approach is that the lower resolution mesh does not *exactly* line up with the higher resolution mesh, and this can cause cracks to be visible where the two meshes meet. The SmoothLOD sample attempts to avoid this problem by overlapping the meshes slightly but this may not be effective in all situations or from all viewpoints.
|
||||
|
||||
An alternative is the Transvoxel algorithm (link) developed by Eric Lengyel. This essentially extends the original Marching Cubes lookup table with additional entries which handle seamless transitions between LOD levels, and it is a very promising solution to level of detail for voxel terrain. At this point in time we do not have an implementation of this algorithm but work is being undertaking in the area. For the latest developments see: http://www.volumesoffun.com/phpBB3/viewtopic.php?f=2&t=338
|
||||
|
||||
However, in all volume reduction approaches there is some uncertainty about how materials should be handled. Creating a lower resolution volume means that several voxel values from the high resolution volume need to be combined into a single value. For density values this is straightforward as a simple average gives good results, but it is not clear how this extends to material identifiers. Averaging them doesn't make sense, and it is hard to imagine an approach which would not lead to visible artifacts as LOD levels change. Perhaps the visible effects can be reduced by blending between two LOD levels, but more investigation needs to be done here.
|
||||
|
||||
Mesh Simplification
|
||||
-------------------
|
||||
The other main approach is to generate the mesh at the full resolution and then reduce the number of triangles using a postprocessing step. This can draw on the large body of mesh simplification research (link to survey) and typically involves merging adjacent faces or collapsing vertices. When using this approach there are a couple of additional complications compared to the implementations which are normally seen.
|
||||
|
||||
The first additional complication is that the decimation algorithm needs to preserve material boundaries so that they don't move between LOD levels. When choosing whether a particular simplification can be made (i.e deciding if one vertex can be collapsed on to another or whether two faces can be merged) a metric is usually used to determine how much the simplification would affect the visual appearance of the mesh. When working with smooth voxel meshes this metric needs to also consider the material identifiers.
|
||||
|
||||
We also need to ensure that the metric preserves the geometric boundary of the mesh, so that no cracks are visible when a simplified mesh is place next to an original one. Maintaining this geometric boundary can be difficult, as the straightforward approach of locking the edge vertices in place will tend to limit the amount of simplification which can be performed. Alternatively, cracks can be allowed to develop if they are later hidden through the use of 'skirts' around the resulting mesh.
|
||||
|
||||
PolyVox used to contain code for performing simplification of the smooth voxel meshes, but unfortunately it had significant performance and functionality issues. Therefore it has been deprecated and it will be removed in a future version of the library. We will instead investigate the use of external mesh simplification libraries and OpenMesh (link) may be a good candidate here.
|
||||
|
@ -1,45 +1,45 @@
|
||||
********
|
||||
Lighting
|
||||
********
|
||||
Lighting is an important part of creating a realistic scene, and fortunately most common lighting solutions can be easily applied to PolyVox meshes. In this document we describe how to implement dynamic lighting and ambient occlusion with PolyVox.
|
||||
|
||||
Dynamic Lighting
|
||||
================
|
||||
In general, any lighting solution for real-time 3D graphics should be directly applicable to PolyVox meshes.
|
||||
|
||||
Normal Calculation for Smooth Meshes
|
||||
------------------------------------
|
||||
When working with smooth voxel terrain meshes, PolyVox provides vertex normals as part of the extracted surface mesh. A common approach for computing these normals would be to compute normals for each face in the mesh, and then compute the vertex normals as a weighted average of the normals of the faces which share it. Actually this is not the approach used by PolyVox, as PolyVox instead computes the vertex normals directly from the underlying volume data.
|
||||
|
||||
More specifically, PolyVox is able to compute the *gradient* of the volume data at any given point using well established image processing methods. The normalised gradient value is used as the vertex normal and in general it is smoother than the value computed by averaging neighbouring faces. Actually there are two approaches to this gradient computation known as *Central Differencing* and *Sobel Filter*. The central differencing approach is generally recommended but the Sobel filter can be used to obtain slightly smoother results but with lower performance. See the MarchingCubesSurfaceExtractor documentation for details on how to select between these (check this exists...).
|
||||
|
||||
Normal Calculation for Cubic Meshes
|
||||
-----------------------------------
|
||||
For cubic meshes PolyVox doesn't actually generate any vertex normals at all, and this is often a source of confusion for new users. The reason for this is that we wish to to perform per-face lighting rather than per-vertex lighting. Considering the case of a single cube, if we wanted to perform per-face lighting based on per-vertex normals then the normals cannot be shared between adjacent faces and so each vertex needs to be duplicated three times (one for each face which uses it). This means we would need 24 vertices to represent a cube which intuitively should only need eight vertices.
|
||||
|
||||
Therefore PolyVox does not generate per-vertex normals for cubic meshes, and as a result the cubic mesh's vertices are both smaller and less numerous. Of course, we still need a way to obtain normals for lighting calculations and so our suggestion is to compute the normals in a fragment program using the *derivative operations* which are provided by modern graphics hardware.
|
||||
|
||||
The description here is rather oversimplified, but the idea behind these operation is that they can tell you how much a variable has changed between two adjacent pixels. If we use our fragment world space position as the input to these derivative operations then we can obtain two vectors which lie on the surface of our face. The cross product of these then gives us a vector which is perpendicular to both and which is therefore our normal.
|
||||
|
||||
Further information about the derivative operations can be found in the OpenGL/Direct3D API documentation, but the implementation in code is quite simple. Firstly you need to make sure that you have access to the fragments world space position in your shader, which means you need to pass it through from the vertex shader. Then you can use the following code in your fragment shader:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
vec3 worldNormal = cross(dFdy(inWorldPosition.xyz), dFdx(inWorldPosition.xyz));
|
||||
worldNormal = normalize(worldNormal);
|
||||
|
||||
**TODO: Check the normal direction**
|
||||
|
||||
Similar code can be implemented in HLSL but you may need to invert the normal due to coordinate system differences between the two APIs. Also, be aware that it may be necessary to use OpenGL ES XXX extension in order to access this derivative functionality on mobile hardware.
|
||||
|
||||
Shadows
|
||||
-------
|
||||
To date we have only experimented with shadow maps as a solution to the real time shadowing problem and have found they work very well for both casting and receiving. The approach is essentially the same as for any other geometry and the usual approaches can be used for setting up the projection and for filtering the result. One PolyVox specific tip we can give is that you don't need to take account of materials when rendering into the shadow map as you always draw in black, so if you are splitting you geometry for material blending or for handling a large number of materials then you don't need to do this when rendering shadows. Using separate shadow geometry with all materials combined may decrease your batch count in this case.
|
||||
|
||||
The most widely used alternative to shadow maps is shadow volumes but we have not tested these with PolyVox. We do not expect these will provide a good solution because meshes usually require additional edge information to allow the shadow volume to be extruded from the silhouette and PolyVox does not provide this. Even if this edge information could be calculated, it would be invalidated each time the mesh changed which would make dynamic terrain more difficult.
|
||||
|
||||
Overall we would recommend you make use of shadow maps for dynamic shadows.
|
||||
|
||||
Ambient Occlusion
|
||||
=================
|
||||
********
|
||||
Lighting
|
||||
********
|
||||
Lighting is an important part of creating a realistic scene, and fortunately most common lighting solutions can be easily applied to PolyVox meshes. In this document we describe how to implement dynamic lighting and ambient occlusion with PolyVox.
|
||||
|
||||
Dynamic Lighting
|
||||
================
|
||||
In general, any lighting solution for real-time 3D graphics should be directly applicable to PolyVox meshes.
|
||||
|
||||
Normal Calculation for Smooth Meshes
|
||||
------------------------------------
|
||||
When working with smooth voxel terrain meshes, PolyVox provides vertex normals as part of the extracted surface mesh. A common approach for computing these normals would be to compute normals for each face in the mesh, and then compute the vertex normals as a weighted average of the normals of the faces which share it. Actually this is not the approach used by PolyVox, as PolyVox instead computes the vertex normals directly from the underlying volume data.
|
||||
|
||||
More specifically, PolyVox is able to compute the *gradient* of the volume data at any given point using well established image processing methods. The normalised gradient value is used as the vertex normal and in general it is smoother than the value computed by averaging neighbouring faces. Actually there are two approaches to this gradient computation known as *Central Differencing* and *Sobel Filter*. The central differencing approach is generally recommended but the Sobel filter can be used to obtain slightly smoother results but with lower performance. See the MarchingCubesSurfaceExtractor documentation for details on how to select between these (check this exists...).
|
||||
|
||||
Normal Calculation for Cubic Meshes
|
||||
-----------------------------------
|
||||
For cubic meshes PolyVox doesn't actually generate any vertex normals at all, and this is often a source of confusion for new users. The reason for this is that we wish to to perform per-face lighting rather than per-vertex lighting. Considering the case of a single cube, if we wanted to perform per-face lighting based on per-vertex normals then the normals cannot be shared between adjacent faces and so each vertex needs to be duplicated three times (one for each face which uses it). This means we would need 24 vertices to represent a cube which intuitively should only need eight vertices.
|
||||
|
||||
Therefore PolyVox does not generate per-vertex normals for cubic meshes, and as a result the cubic mesh's vertices are both smaller and less numerous. Of course, we still need a way to obtain normals for lighting calculations and so our suggestion is to compute the normals in a fragment program using the *derivative operations* which are provided by modern graphics hardware.
|
||||
|
||||
The description here is rather oversimplified, but the idea behind these operation is that they can tell you how much a variable has changed between two adjacent pixels. If we use our fragment world space position as the input to these derivative operations then we can obtain two vectors which lie on the surface of our face. The cross product of these then gives us a vector which is perpendicular to both and which is therefore our normal.
|
||||
|
||||
Further information about the derivative operations can be found in the OpenGL/Direct3D API documentation, but the implementation in code is quite simple. Firstly you need to make sure that you have access to the fragments world space position in your shader, which means you need to pass it through from the vertex shader. Then you can use the following code in your fragment shader:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
vec3 worldNormal = cross(dFdy(inWorldPosition.xyz), dFdx(inWorldPosition.xyz));
|
||||
worldNormal = normalize(worldNormal);
|
||||
|
||||
**TODO: Check the normal direction**
|
||||
|
||||
Similar code can be implemented in HLSL but you may need to invert the normal due to coordinate system differences between the two APIs. Also, be aware that it may be necessary to use OpenGL ES XXX extension in order to access this derivative functionality on mobile hardware.
|
||||
|
||||
Shadows
|
||||
-------
|
||||
To date we have only experimented with shadow maps as a solution to the real time shadowing problem and have found they work very well for both casting and receiving. The approach is essentially the same as for any other geometry and the usual approaches can be used for setting up the projection and for filtering the result. One PolyVox specific tip we can give is that you don't need to take account of materials when rendering into the shadow map as you always draw in black, so if you are splitting you geometry for material blending or for handling a large number of materials then you don't need to do this when rendering shadows. Using separate shadow geometry with all materials combined may decrease your batch count in this case.
|
||||
|
||||
The most widely used alternative to shadow maps is shadow volumes but we have not tested these with PolyVox. We do not expect these will provide a good solution because meshes usually require additional edge information to allow the shadow volume to be extruded from the silhouette and PolyVox does not provide this. Even if this edge information could be calculated, it would be invalidated each time the mesh changed which would make dynamic terrain more difficult.
|
||||
|
||||
Overall we would recommend you make use of shadow maps for dynamic shadows.
|
||||
|
||||
Ambient Occlusion
|
||||
=================
|
||||
This is an area in which we want to undertake more research in order to get effective ambient occlusion into PolyVox scenes. In the mean time SSAO has proved to be a popular solution.
|
@ -1,4 +1,4 @@
|
||||
=================
|
||||
Modifying Terrain
|
||||
=================
|
||||
=================
|
||||
Modifying Terrain
|
||||
=================
|
||||
This document has yet to be written.
|
@ -1,38 +1,38 @@
|
||||
*************
|
||||
Prerequisites
|
||||
*************
|
||||
The PolyVox library is aimed at experienced games and graphics programmers who wish to incorporate voxel environments into their applications. It is not a drop in solution, but instead provides a set of building blocks which you can use to construct a complete system. Most of the functionality could be considered quite low-level. For example, it provides mesh extractors to generate a surface from volume data but requires the application developer to handle all tasks related to scene management and rendering of such data.
|
||||
|
||||
As a result you will need a decent amount of graphics programming experience to effectively make use of the library. The purpose of this document is to highlight some of the core areas with which you will need to be familiar. In some cases we also provide links to places where you can find more information about the subject in question.
|
||||
|
||||
You should also be aware that voxel terrain is still an open research area and has not yet seen widespread adoption in games and simulations. There are many questions to which we do not currently know the best answer and so you may have to do some research and experimentation yourself when trying to obtain your desired result. Please do let us know if you come up with a trick or technique which you think could benefit other users.
|
||||
|
||||
Programming
|
||||
===========
|
||||
This section describes some of the programming concepts with which you will need to be familiar:
|
||||
|
||||
**C++:** PolyVox is written using the C++ language and we expect this is what the majority of our users will be developing in. You will need to be familiar with the basic process of building and linking against external libraries as well as setting up your development environment. Note that you do have the option of working with other languages via the SWIG bindings but you may not have as much flexibility with this approach.
|
||||
|
||||
**Templates:** PolyVox also makes heavy use of template programming in order to be both fast and generic, so familiarity with templates will be very useful. You shouldn't need to do much template programming yourself but an understanding of them will help you understand errors and resolve any problems.
|
||||
|
||||
**Callbacks:** Several of the algorithms in PolyVox can be customised through the use of callbacks. In general there are sensible defaults provided, but for maximum control you may wish to learn how to define you own. In general the principle is similar to the way in which callbacks are used in the STL.
|
||||
|
||||
Graphics Concepts
|
||||
=================
|
||||
Several core graphics principles will be useful in understanding and using PolyVox:
|
||||
|
||||
**Volume representation:** PolyVox revolves around the idea of storing and manipulating volume data and using this as a representation of a 3d world. This is a fairly intuitive extension of traditional heightmap terrain but does require the ability to 'think in 3D'. You will need to understand that data stored in this way can become very large, and understand the idea that paging and compression can be used to combat this.
|
||||
|
||||
**Mesh representation:** Most PolyVox projects will involve using one of the surface extractors, which output their data as index and vertex buffers. Therefore you will need to understand this representation in order to pass the data to your rendering engine or in order to perform further modifications to it. You can find out about more about this here: (ADD LINK)
|
||||
|
||||
**Image processing:** For certain advanced application an understanding of image processing methods can be useful. For example the process of blurring an image via a low pass filter can be used to effectively smooth out voxel terrain. There are plans to add more image processing operations to PolyVox particularly with regard to morphological operations which you might want to use to modify your environment.
|
||||
|
||||
Rendering
|
||||
=========
|
||||
**Runtime geometry creation:** PolyVox is independent of any particular graphics API which means it outputs its data using API-neutral structures such as index and vertex buffers (as mentioned above). You will need to write the code which converts these structures into a format which your API or engine can understand. This is not a difficult task but does require some knowledge of the rendering technology which you are using.
|
||||
|
||||
**Scene management:** PolyVox is only responsible for providing you with the mesh data to be displayed, so you application or engine will need to make sensible decisions about how this data should be organised in terms of a spatial structure (octree, bounding volumes tree, etc). It will also need to provide some approach to visibility determination such as frustum culling or a more advanced approach. If you are integrating PolyVox with an existing rendering engine then you should find that many of these aspects are already handled for you.
|
||||
|
||||
**Shader programming:** The meshes which are generated by PolyVox are very basic in terms of the vertex data they provide. You get vertex positions, a material identifier, and sometimes vertex normals. It is the responsibility of application programmer to decide how to use this data to create visually interesting renderings. This means you will almost certainly want to make use of shader programs. Of course, in our texturing (LINK) and lighting (LINK) documents you will find many ideas and common solutions, but you will need strong shader programming experience to make effective use of these.
|
||||
|
||||
*************
|
||||
Prerequisites
|
||||
*************
|
||||
The PolyVox library is aimed at experienced games and graphics programmers who wish to incorporate voxel environments into their applications. It is not a drop in solution, but instead provides a set of building blocks which you can use to construct a complete system. Most of the functionality could be considered quite low-level. For example, it provides mesh extractors to generate a surface from volume data but requires the application developer to handle all tasks related to scene management and rendering of such data.
|
||||
|
||||
As a result you will need a decent amount of graphics programming experience to effectively make use of the library. The purpose of this document is to highlight some of the core areas with which you will need to be familiar. In some cases we also provide links to places where you can find more information about the subject in question.
|
||||
|
||||
You should also be aware that voxel terrain is still an open research area and has not yet seen widespread adoption in games and simulations. There are many questions to which we do not currently know the best answer and so you may have to do some research and experimentation yourself when trying to obtain your desired result. Please do let us know if you come up with a trick or technique which you think could benefit other users.
|
||||
|
||||
Programming
|
||||
===========
|
||||
This section describes some of the programming concepts with which you will need to be familiar:
|
||||
|
||||
**C++:** PolyVox is written using the C++ language and we expect this is what the majority of our users will be developing in. You will need to be familiar with the basic process of building and linking against external libraries as well as setting up your development environment. Note that you do have the option of working with other languages via the SWIG bindings but you may not have as much flexibility with this approach.
|
||||
|
||||
**Templates:** PolyVox also makes heavy use of template programming in order to be both fast and generic, so familiarity with templates will be very useful. You shouldn't need to do much template programming yourself but an understanding of them will help you understand errors and resolve any problems.
|
||||
|
||||
**Callbacks:** Several of the algorithms in PolyVox can be customised through the use of callbacks. In general there are sensible defaults provided, but for maximum control you may wish to learn how to define you own. In general the principle is similar to the way in which callbacks are used in the STL.
|
||||
|
||||
Graphics Concepts
|
||||
=================
|
||||
Several core graphics principles will be useful in understanding and using PolyVox:
|
||||
|
||||
**Volume representation:** PolyVox revolves around the idea of storing and manipulating volume data and using this as a representation of a 3d world. This is a fairly intuitive extension of traditional heightmap terrain but does require the ability to 'think in 3D'. You will need to understand that data stored in this way can become very large, and understand the idea that paging and compression can be used to combat this.
|
||||
|
||||
**Mesh representation:** Most PolyVox projects will involve using one of the surface extractors, which output their data as index and vertex buffers. Therefore you will need to understand this representation in order to pass the data to your rendering engine or in order to perform further modifications to it. You can find out about more about this here: (ADD LINK)
|
||||
|
||||
**Image processing:** For certain advanced application an understanding of image processing methods can be useful. For example the process of blurring an image via a low pass filter can be used to effectively smooth out voxel terrain. There are plans to add more image processing operations to PolyVox particularly with regard to morphological operations which you might want to use to modify your environment.
|
||||
|
||||
Rendering
|
||||
=========
|
||||
**Runtime geometry creation:** PolyVox is independent of any particular graphics API which means it outputs its data using API-neutral structures such as index and vertex buffers (as mentioned above). You will need to write the code which converts these structures into a format which your API or engine can understand. This is not a difficult task but does require some knowledge of the rendering technology which you are using.
|
||||
|
||||
**Scene management:** PolyVox is only responsible for providing you with the mesh data to be displayed, so you application or engine will need to make sensible decisions about how this data should be organised in terms of a spatial structure (octree, bounding volumes tree, etc). It will also need to provide some approach to visibility determination such as frustum culling or a more advanced approach. If you are integrating PolyVox with an existing rendering engine then you should find that many of these aspects are already handled for you.
|
||||
|
||||
**Shader programming:** The meshes which are generated by PolyVox are very basic in terms of the vertex data they provide. You get vertex positions, a material identifier, and sometimes vertex normals. It is the responsibility of application programmer to decide how to use this data to create visually interesting renderings. This means you will almost certainly want to make use of shader programs. Of course, in our texturing (LINK) and lighting (LINK) documents you will find many ideas and common solutions, but you will need strong shader programming experience to make effective use of these.
|
||||
|
||||
If you don't have much experience with shader programming then there are many free resources available. The Cg Tutorial (LINK) provides a good introduction here (the concepts are applicable to other shader languages) as does the documentation for the main graphics (LINK to OpenGL docs) APIs (Link to D3D docs). there is nothing special about PolyVox meshes so you would be advised to practice development on simple meshes such as spheres and cubes before trying to apply it to the output of the mesh extractors.
|
@ -1,151 +1,151 @@
|
||||
***************
|
||||
Texture Mapping
|
||||
***************
|
||||
The PolyVox library is only concerned with operations on volume data (such as extracting a mesh from from a volume) and deliberately avoids the issue of rendering any resulting polygon meshes. This means PolyVox is not tied to any particular graphics API or rendering engine, and makes it much easier to integrate PolyVox with existing technology, because in general a PolyVox mesh can be treated the same as any other mesh. However, the texturing of a PolyVox mesh is usually handled a little differently, and so the purpose of this document is to provide some ideas about where to start with this process.
|
||||
|
||||
This document is aimed at readers in one of two positions:
|
||||
|
||||
1. You are trying to texture 'Minecraft-style' terrain with cubic blocks and a number of different materials.
|
||||
2. You are trying to texture smooth terrain produced by the Marching Cubes (or similar) algorithm.
|
||||
|
||||
These are certainly not the limit of PolyVox, and you can choose much more advanced texturing approaches if you wish. For example, in the past we have texture mapped a voxel Earth from a cube map and used an animated *procedural* texture (based on Perlin noise) for the magma at the center of the Earth. However, if you are aiming for such advanced techniques then we assume you understand the basics in this document and have enough knowledge to expand the ideas yourself. But do feel free to drop by and ask questions on our forum.
|
||||
|
||||
Traditionally meshes are textured by providing a pair of UV texture coordinates for each vertex, and these UV coordinates determine which parts of a texture maps to each vertex. The process of texturing PolyVox meshes is more complex for a couple of reasons:
|
||||
|
||||
1. PolyVox does not provide UV coordinates for each vertex.
|
||||
2. Voxel terrain (particularly Minecraft-style) often involves many more textures than the GPU can read at a time.
|
||||
|
||||
By reading this document you should learn how to work around the above problems, though you will almost certainly need to follow provided links and do some further reading as we have only summarised the key ideas here.
|
||||
|
||||
Mapping textures to mesh geometry
|
||||
=================================
|
||||
The lack of UV coordinates means some lateral thinking is required in order to apply texture maps to meshes. But before we get to that, we will first try to explain the rational behind PolyVox not providing UV coordinates in the first place. This rational is different for the smooth voxel meshes vs the cubic voxel meshes.
|
||||
|
||||
Rational
|
||||
--------
|
||||
The problem with texturing smooth voxel meshes is that the geometry can get very complex and it is not clear how the mapping between mesh geometry and a texture should be performed. In a traditional heightmap-based terrain this relationship is obvious as the texture map and heightmap simply line up directly. But for more complex shapes some form of 'UV unwrapping' is usually performed to define this relationship. This is usually done by an artist with the help of a 3D modeling package and so is a semi-automatic process, but it is time consuming and driven by the artists idea of what looks right for their particular scene. Even though fully automatic UV unwrapping is possible it is usually prohibitively slow.
|
||||
|
||||
Even if such an unwrapping were possible in a reasonable time frame, the next problem is that it would be invalidated as soon as the mesh changed. Enabling dynamic manipulation is one of the appealing factors of voxel terrain, and if this use case were discarded then the user may as well just model their terrain in an existing 3D modelling package and texture there. For these reasons we do not attempt to generate UV coordinates for smooth voxel meshes.
|
||||
|
||||
The rational in the cubic case is almost the opposite. For Minecraft style terrain you want to simply line up an instance of a texture with each face of a cube, and generating the texture coordinates for this is very easy. In fact it's so easy that there's no point in doing it - the logic can instead be implemented in a shader which in turn allows the amount of data in each vertex to be reduced.
|
||||
|
||||
Triplanar Texturing
|
||||
-------------------
|
||||
The most common approach to texture mapping smooth voxel terrain is to use *triplanar texturing*. The basic idea is to project a texture along all three main axes and blend between the three texture samples according to the surface normal. As an example, suppose that we wish to write a fragment shader to apply a single texture to our terrain, and assume that we have access to both the world space position of the fragment and also its normalised surface normal. Also, note that your textures should be set to wrap because the world space position will quickly go outside the bounds of 0.0-1.0. The world space position will need to have been passed through from earlier in the pipeline while the normal can be computed using one of the approaches in the lighting (link) document. The shader code would then look something like this [footnote: code is untested as is simplified compared to real world code. hopefully it compiles, but if not it should still give you an idea of how it works]:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
// Take the three texture samples
|
||||
vec4 sampleX = texture2d(inputTexture, worldSpacePos.yz); // Project along x axis
|
||||
vec4 sampleY = texture2d(inputTexture, worldSpacePos.xz); // Project along y axis
|
||||
vec4 sampleZ = texture2d(inputTexture, worldSpacePos.xy); // Project along z axis
|
||||
|
||||
// Blend the samples according to the normal
|
||||
vec4 blendedColour = sampleX * normal.x + sampleY * normal.y + sampleZ * normal.z;
|
||||
|
||||
Note that this approach will lead to the texture repeating once every world unit, and so in practice you may wish to scale the world space positions to make the texture appear the desired size. Also this technique can be extended to work with normal mapping though we won't go into the details here.
|
||||
|
||||
This idea of triplanar texturing can be applied to the cubic meshes as well, and in some ways it can be considered to be even simpler. With cubic meshes the normal always points exactly along one of the main axes, and so it is not necessary to sample the texture three times nor to blend the results. Instead you can use conditional branching in the fragment shader to determine which pair of values out of {x,y,z} should be used as the texture coordinates. Something like:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
vec4 sample = vec4(0, 0, 0, 0); // We'll fill this in below
|
||||
// Assume the normal is normalised.
|
||||
if(normal.x > 0.9) // x must be one while y and z are zero
|
||||
{
|
||||
//Project onto yz plane
|
||||
sample = texture2D(inputTexture, worldSpacePos.yz);
|
||||
}
|
||||
// Now similar logic for the other two axes.
|
||||
.
|
||||
.
|
||||
.
|
||||
|
||||
You might also choose to sample a different texture for each of the axes, in order to apply a different texture to each face of your cube. If so, you probably want to pack your different face textures together using an approach similar to those described later in this document for multiple material textures. Another (untested) idea would be to use the normal to select a face on a 1x1x1 cubemap, and have the cubemap face contain an index value for addressing the correct face texture. This could bypass the conditional logic above.
|
||||
|
||||
Using the material identifier
|
||||
-----------------------------
|
||||
So far we have assumed that only a single material is being used for the entire voxel world, but this is seldom the case. It is common to associate a particular material with each voxel so that it can represent rock, wood, sand or any other type of material as required. The usual approach is to store a simple integer identifier with each voxel, and then map this identifier to material properties within your application.
|
||||
|
||||
Both the CubicSurfaceExtractor and the MarchingCubesSurfacExtractor understand the concept of a material being associated with a voxel, and they will take this into account when generating a mesh. Specifically, they will both copy the material identifier into the vertex data of the output mesh, so you can pass it through to your shaders and use it to affect the way the surface is rendered.
|
||||
|
||||
The following code snippet assumes that you have passed the material identifier to your shaders and that you can access it in the fragment shader. It then chooses which colour to draw the polygon based on this identifier:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
vec4 fragmentColour = vec4(1, 1, 1, 1); // Default value
|
||||
if(materialId < 0.5) //Avoid '==' when working with floats.
|
||||
{
|
||||
fragmentColour = vec4(1, 0, 0, 1) // Draw material 0 as red.
|
||||
}
|
||||
else if(materialId < 1.5) //Avoid '==' when working with floats.
|
||||
{
|
||||
fragmentColour = vec4(0, 1, 0, 1) // Draw material 1 as green.
|
||||
}
|
||||
else if(materialId < 2.5) //Avoid '==' when working with floats.
|
||||
{
|
||||
fragmentColour = vec4(0, 0, 1, 1) // Draw material 2 as blue.
|
||||
}
|
||||
.
|
||||
.
|
||||
.
|
||||
|
||||
This is a very simple example, and such use of conditional branching within the shader may not be the best approach as it incurs some performance overhead and becomes unwieldy with a large number of materials. Other approaches include encoding a colour directly into the material identifier, or using the identifier as an index into a texture atlas or array.
|
||||
|
||||
Note that PolyVox currently stores that material identifier for the vertex as a float, but this will probably change in the future to use the same type as is stored in the volume. It will then be up to you which type you pass to the GPU (older GPUs may not support integer values) but if you do use floats then watch out for precision issues and avoid equality comparisons.
|
||||
|
||||
Blending between materials
|
||||
--------------------------
|
||||
An additional complication when working with smooth voxel terrain is that it is usually desirable to blend smoothly between adjacent voxels with different materials. This situation does not occur with cubic meshes because the texture is considered to be per-face instead of per-vertex, and PolyVox enforces this by ensuring that all the vertices of a given face have the same material.
|
||||
|
||||
With a smooth mesh it is possible for each of the three vertices of any given triangle to have different material identifiers. If this is not explicitly handled then the graphics hardware will interpolate these material values across the face of the triangle. Fundamentally, the concept of interpolating between material identifiers does not make sense, because if we have (for example) 1='grass', 2='rock' and 3='sand' then it does not make sense to say rock is the average of grass and sand.
|
||||
|
||||
Correctly handling of this is a surprising difficult problem. For now, the best approach is described in our article 'Volumetric representation of virtual terrain' which appeared in Game Engine Gems Volume 1 and which is freely available through the Google Books preview here: http://books.google.com/books?id=WNfD2u8nIlIC&lpg=PR1&dq=game%20engine%20gems&pg=PA39#v=onepage&q&f=false
|
||||
|
||||
As off October 2012 we are actively researching alternative solutions to this problem though it will be some time before the results become available.
|
||||
|
||||
Actual implementation of these material blending approaches is left as an exercise to the reader, though it is possible that in the future we will add some utility functions to PolyVox to assist with tasks such as splitting the mesh or adding the required extra vertex attributes. Our test implementations have performed the mesh processing on the CPU before the mesh is uploaded to the graphics card, but it does seem like there is a lot of potential for implementing these approaches in the geometry shader.
|
||||
|
||||
Storage of textures
|
||||
===================
|
||||
The other major challenge in texturing voxel based geometry is handling the large number of textures which such environments often require. As an example, a game like Minecraft has hundreds of different material types each with their own texture. The traditional approach to mesh texturing is to bind textures to *texture units* on the GPU before rendering a batch, but even modern GPUs only allow between 16-64 textures to be bound at a time. In this section we discuss various solutions to overcoming this limitation.
|
||||
|
||||
There are various trade offs involved, but if you are targeting hardware with support for *texture arrays* (available from OpenGL 3 and Direct3D 10 on-wards) then we can save you some time and tell you that they are almost certainly the best solution. Otherwise you have to understand the various pros and cons of the other approaches described below.
|
||||
|
||||
Separate texture units
|
||||
----------------------
|
||||
Before we make things unnecessarily complicated, you should consider whether you do actually need the hundreds of textures discussed earlier. If you actually only need a few textures then the simplest solution may indeed be to pass them in via different texture units. You can then select the desired textures using a series of if statements, or a switch statement if the material identifiers are integer values. There is probably some performance overhead here, but you may find it is acceptable for a small number of textures. Keep in mind that you may need to reserve some texture units for additional texture data such as normal maps or shadow maps.
|
||||
|
||||
Splitting the mesh
|
||||
------------------
|
||||
If your required number of textures do indeed exceed the available number of textures units then one option is to break the mesh down into a number of pieces. Let's say you have a mesh which contains one hundred different materials. As an extreme solution you could break it down into one hundred separate meshes, and for each mesh you could then bind the required single texture before drawing the geometry. Obviously this will dramatically increase the batch count of your scene and so is not recommended.
|
||||
|
||||
A more practical approach would be to break the mesh into a smaller number of pieces such that each mesh uses several textures but less than the maximum number of texture units. For example, our mesh with one hundred materials could be split into ten meshes, the first of which contains those triangles using materials 0-9, the seconds contains those triangles using materials 10-19, and so forth. There is a trade off here between the number of batches and the number of textures units used per batch.
|
||||
|
||||
Furthermore, you could realise that although your terrain may use hundreds of different textures, any given region is likely to use only a small fraction of those. We have yet to experiment with this, but it seems if you region uses only (for example) materials 12, 47, and 231, then you could conceptually map these materials to the first three textures slots. This means that for each region you draw the mapping between material IDs and texture units would be different. This may require some complex logic in the application but could allow you to do much more with only a few texture units. We will investigate this further in the future.
|
||||
|
||||
Texture atlases
|
||||
---------------
|
||||
Probably the most widely used method is to pack a number of textures together into a single large texture, and to our knowledge this is the approach used by Minecraft. For example, if each of your textures are 256x256 texels, and if the maximum texture size supported by your target hardware is 4096x4096 texels, then you can pack 16 x 16 = 256 small textures into the larger one. If this isn't enough (or if your input textures are larger than 256x256) then you can also combine this approach with multiple texture units or with the mesh splitting described previously.
|
||||
|
||||
However, there are a number of problems with packing textures like this. Most obviously, it limits the size of your textures as they now have to be significantly smaller then the maximum texture size. Whether this is a problem will really depend on your application.
|
||||
|
||||
Next, it means you have to adjust your UV coordinates to correctly address a given texture inside the atlas. UV coordinates for a single texture would normally vary between 0.0 and 1.0 in both dimensions, but when packed into a texture atlas each texture uses only a small part of this range. You will need to apply offsets and scaling factors to your UV coordinates to address your texture correctly.
|
||||
|
||||
However, the biggest problem with texture atlases is that they causes problems with texture filtering and with mipmaps. The filtering problem occurs because graphics hardware usually samples the surrounding texels and performs linear interpolation to compute the colour of a given sample point, but when multiple textures are packed together these surrounding texels can actually come from a neighbouring packed texture rather than wrapping round to sample on the other side of the same packed texture. The mipmap problem occurs because for the highest mipmap levels (such as 1x1 or 2x2) multiple textures are being are being averaged together.
|
||||
|
||||
It is possible to combat these problems but the solutions are non-trivial. You will want to limit the number of miplevels which you use, and probably provide custom shader code to handle the wrapping of texture coordinates, the sampling of MIP maps, and the calculation of interpolated values. You can also try adding a border around all your packed textures, perhaps by duplicating each texture and offsetting by half its size. Even so, it's not clear to us at this point whether the the various artifacts can be completely removed. Minecraft handles it by completely disabling texture filtering and using the resulting pixelated look as part of its aesthetic.
|
||||
|
||||
3D texture slices
|
||||
-----------------
|
||||
The idea here is similar to the texture atlas approach, but rather than packing texture side-by-side in an atlas they are instead packed as slices in a 3D texture. We haven't actually tested this but in theory it may have a couple of benefits. Firstly, it simplifies the addressing of the texture as there is no need to offset/scale the UV coordinates, and the W coordinate (the slice index) can be more easily computed from the material identifier. Secondly, a single volume texture will usually be able to hold more texels than a single 2D texture (for example, 512x512x512 is bigger than 4096x4096). Lastly, it should simplify the filtering problem as packed textures are no longer tiled and so should wrap correctly.
|
||||
|
||||
However, MIP mapping will probably be more complex than the texture atlas case because even the first MIP level will involve combining adjacent slices. Volume textures are also not so widely supported and may be particularly problematic on mobile hardware.
|
||||
|
||||
Texture arrays
|
||||
--------------
|
||||
These provide the perfect solution to the problem of handling a large number of textures... at least if they are supported by your hardware. They were introduced with OpenGL 3 and Direct3D 10 but older versions of OpenGL may still be able to access the functionality via extensions. They allow you to bind an array of textures to the shader, and the advantage compared to a texture atlas is that the hardware understands that the textures are separate and so avoids the filtering and mipmapping issues. Beyond the hardware requirements, the only real limitation is that all the textures must be the same size.
|
||||
|
||||
Bindless rendering
|
||||
------------------
|
||||
***************
|
||||
Texture Mapping
|
||||
***************
|
||||
The PolyVox library is only concerned with operations on volume data (such as extracting a mesh from from a volume) and deliberately avoids the issue of rendering any resulting polygon meshes. This means PolyVox is not tied to any particular graphics API or rendering engine, and makes it much easier to integrate PolyVox with existing technology, because in general a PolyVox mesh can be treated the same as any other mesh. However, the texturing of a PolyVox mesh is usually handled a little differently, and so the purpose of this document is to provide some ideas about where to start with this process.
|
||||
|
||||
This document is aimed at readers in one of two positions:
|
||||
|
||||
1. You are trying to texture 'Minecraft-style' terrain with cubic blocks and a number of different materials.
|
||||
2. You are trying to texture smooth terrain produced by the Marching Cubes (or similar) algorithm.
|
||||
|
||||
These are certainly not the limit of PolyVox, and you can choose much more advanced texturing approaches if you wish. For example, in the past we have texture mapped a voxel Earth from a cube map and used an animated *procedural* texture (based on Perlin noise) for the magma at the center of the Earth. However, if you are aiming for such advanced techniques then we assume you understand the basics in this document and have enough knowledge to expand the ideas yourself. But do feel free to drop by and ask questions on our forum.
|
||||
|
||||
Traditionally meshes are textured by providing a pair of UV texture coordinates for each vertex, and these UV coordinates determine which parts of a texture maps to each vertex. The process of texturing PolyVox meshes is more complex for a couple of reasons:
|
||||
|
||||
1. PolyVox does not provide UV coordinates for each vertex.
|
||||
2. Voxel terrain (particularly Minecraft-style) often involves many more textures than the GPU can read at a time.
|
||||
|
||||
By reading this document you should learn how to work around the above problems, though you will almost certainly need to follow provided links and do some further reading as we have only summarised the key ideas here.
|
||||
|
||||
Mapping textures to mesh geometry
|
||||
=================================
|
||||
The lack of UV coordinates means some lateral thinking is required in order to apply texture maps to meshes. But before we get to that, we will first try to explain the rational behind PolyVox not providing UV coordinates in the first place. This rational is different for the smooth voxel meshes vs the cubic voxel meshes.
|
||||
|
||||
Rational
|
||||
--------
|
||||
The problem with texturing smooth voxel meshes is that the geometry can get very complex and it is not clear how the mapping between mesh geometry and a texture should be performed. In a traditional heightmap-based terrain this relationship is obvious as the texture map and heightmap simply line up directly. But for more complex shapes some form of 'UV unwrapping' is usually performed to define this relationship. This is usually done by an artist with the help of a 3D modeling package and so is a semi-automatic process, but it is time consuming and driven by the artists idea of what looks right for their particular scene. Even though fully automatic UV unwrapping is possible it is usually prohibitively slow.
|
||||
|
||||
Even if such an unwrapping were possible in a reasonable time frame, the next problem is that it would be invalidated as soon as the mesh changed. Enabling dynamic manipulation is one of the appealing factors of voxel terrain, and if this use case were discarded then the user may as well just model their terrain in an existing 3D modelling package and texture there. For these reasons we do not attempt to generate UV coordinates for smooth voxel meshes.
|
||||
|
||||
The rational in the cubic case is almost the opposite. For Minecraft style terrain you want to simply line up an instance of a texture with each face of a cube, and generating the texture coordinates for this is very easy. In fact it's so easy that there's no point in doing it - the logic can instead be implemented in a shader which in turn allows the amount of data in each vertex to be reduced.
|
||||
|
||||
Triplanar Texturing
|
||||
-------------------
|
||||
The most common approach to texture mapping smooth voxel terrain is to use *triplanar texturing*. The basic idea is to project a texture along all three main axes and blend between the three texture samples according to the surface normal. As an example, suppose that we wish to write a fragment shader to apply a single texture to our terrain, and assume that we have access to both the world space position of the fragment and also its normalised surface normal. Also, note that your textures should be set to wrap because the world space position will quickly go outside the bounds of 0.0-1.0. The world space position will need to have been passed through from earlier in the pipeline while the normal can be computed using one of the approaches in the lighting (link) document. The shader code would then look something like this [footnote: code is untested as is simplified compared to real world code. hopefully it compiles, but if not it should still give you an idea of how it works]:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
// Take the three texture samples
|
||||
vec4 sampleX = texture2d(inputTexture, worldSpacePos.yz); // Project along x axis
|
||||
vec4 sampleY = texture2d(inputTexture, worldSpacePos.xz); // Project along y axis
|
||||
vec4 sampleZ = texture2d(inputTexture, worldSpacePos.xy); // Project along z axis
|
||||
|
||||
// Blend the samples according to the normal
|
||||
vec4 blendedColour = sampleX * normal.x + sampleY * normal.y + sampleZ * normal.z;
|
||||
|
||||
Note that this approach will lead to the texture repeating once every world unit, and so in practice you may wish to scale the world space positions to make the texture appear the desired size. Also this technique can be extended to work with normal mapping though we won't go into the details here.
|
||||
|
||||
This idea of triplanar texturing can be applied to the cubic meshes as well, and in some ways it can be considered to be even simpler. With cubic meshes the normal always points exactly along one of the main axes, and so it is not necessary to sample the texture three times nor to blend the results. Instead you can use conditional branching in the fragment shader to determine which pair of values out of {x,y,z} should be used as the texture coordinates. Something like:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
vec4 sample = vec4(0, 0, 0, 0); // We'll fill this in below
|
||||
// Assume the normal is normalised.
|
||||
if(normal.x > 0.9) // x must be one while y and z are zero
|
||||
{
|
||||
//Project onto yz plane
|
||||
sample = texture2D(inputTexture, worldSpacePos.yz);
|
||||
}
|
||||
// Now similar logic for the other two axes.
|
||||
.
|
||||
.
|
||||
.
|
||||
|
||||
You might also choose to sample a different texture for each of the axes, in order to apply a different texture to each face of your cube. If so, you probably want to pack your different face textures together using an approach similar to those described later in this document for multiple material textures. Another (untested) idea would be to use the normal to select a face on a 1x1x1 cubemap, and have the cubemap face contain an index value for addressing the correct face texture. This could bypass the conditional logic above.
|
||||
|
||||
Using the material identifier
|
||||
-----------------------------
|
||||
So far we have assumed that only a single material is being used for the entire voxel world, but this is seldom the case. It is common to associate a particular material with each voxel so that it can represent rock, wood, sand or any other type of material as required. The usual approach is to store a simple integer identifier with each voxel, and then map this identifier to material properties within your application.
|
||||
|
||||
Both the CubicSurfaceExtractor and the MarchingCubesSurfacExtractor understand the concept of a material being associated with a voxel, and they will take this into account when generating a mesh. Specifically, they will both copy the material identifier into the vertex data of the output mesh, so you can pass it through to your shaders and use it to affect the way the surface is rendered.
|
||||
|
||||
The following code snippet assumes that you have passed the material identifier to your shaders and that you can access it in the fragment shader. It then chooses which colour to draw the polygon based on this identifier:
|
||||
|
||||
.. sourcecode:: glsl
|
||||
|
||||
vec4 fragmentColour = vec4(1, 1, 1, 1); // Default value
|
||||
if(materialId < 0.5) //Avoid '==' when working with floats.
|
||||
{
|
||||
fragmentColour = vec4(1, 0, 0, 1) // Draw material 0 as red.
|
||||
}
|
||||
else if(materialId < 1.5) //Avoid '==' when working with floats.
|
||||
{
|
||||
fragmentColour = vec4(0, 1, 0, 1) // Draw material 1 as green.
|
||||
}
|
||||
else if(materialId < 2.5) //Avoid '==' when working with floats.
|
||||
{
|
||||
fragmentColour = vec4(0, 0, 1, 1) // Draw material 2 as blue.
|
||||
}
|
||||
.
|
||||
.
|
||||
.
|
||||
|
||||
This is a very simple example, and such use of conditional branching within the shader may not be the best approach as it incurs some performance overhead and becomes unwieldy with a large number of materials. Other approaches include encoding a colour directly into the material identifier, or using the identifier as an index into a texture atlas or array.
|
||||
|
||||
Note that PolyVox currently stores that material identifier for the vertex as a float, but this will probably change in the future to use the same type as is stored in the volume. It will then be up to you which type you pass to the GPU (older GPUs may not support integer values) but if you do use floats then watch out for precision issues and avoid equality comparisons.
|
||||
|
||||
Blending between materials
|
||||
--------------------------
|
||||
An additional complication when working with smooth voxel terrain is that it is usually desirable to blend smoothly between adjacent voxels with different materials. This situation does not occur with cubic meshes because the texture is considered to be per-face instead of per-vertex, and PolyVox enforces this by ensuring that all the vertices of a given face have the same material.
|
||||
|
||||
With a smooth mesh it is possible for each of the three vertices of any given triangle to have different material identifiers. If this is not explicitly handled then the graphics hardware will interpolate these material values across the face of the triangle. Fundamentally, the concept of interpolating between material identifiers does not make sense, because if we have (for example) 1='grass', 2='rock' and 3='sand' then it does not make sense to say rock is the average of grass and sand.
|
||||
|
||||
Correctly handling of this is a surprising difficult problem. For now, the best approach is described in our article 'Volumetric representation of virtual terrain' which appeared in Game Engine Gems Volume 1 and which is freely available through the Google Books preview here: http://books.google.com/books?id=WNfD2u8nIlIC&lpg=PR1&dq=game%20engine%20gems&pg=PA39#v=onepage&q&f=false
|
||||
|
||||
As off October 2012 we are actively researching alternative solutions to this problem though it will be some time before the results become available.
|
||||
|
||||
Actual implementation of these material blending approaches is left as an exercise to the reader, though it is possible that in the future we will add some utility functions to PolyVox to assist with tasks such as splitting the mesh or adding the required extra vertex attributes. Our test implementations have performed the mesh processing on the CPU before the mesh is uploaded to the graphics card, but it does seem like there is a lot of potential for implementing these approaches in the geometry shader.
|
||||
|
||||
Storage of textures
|
||||
===================
|
||||
The other major challenge in texturing voxel based geometry is handling the large number of textures which such environments often require. As an example, a game like Minecraft has hundreds of different material types each with their own texture. The traditional approach to mesh texturing is to bind textures to *texture units* on the GPU before rendering a batch, but even modern GPUs only allow between 16-64 textures to be bound at a time. In this section we discuss various solutions to overcoming this limitation.
|
||||
|
||||
There are various trade offs involved, but if you are targeting hardware with support for *texture arrays* (available from OpenGL 3 and Direct3D 10 on-wards) then we can save you some time and tell you that they are almost certainly the best solution. Otherwise you have to understand the various pros and cons of the other approaches described below.
|
||||
|
||||
Separate texture units
|
||||
----------------------
|
||||
Before we make things unnecessarily complicated, you should consider whether you do actually need the hundreds of textures discussed earlier. If you actually only need a few textures then the simplest solution may indeed be to pass them in via different texture units. You can then select the desired textures using a series of if statements, or a switch statement if the material identifiers are integer values. There is probably some performance overhead here, but you may find it is acceptable for a small number of textures. Keep in mind that you may need to reserve some texture units for additional texture data such as normal maps or shadow maps.
|
||||
|
||||
Splitting the mesh
|
||||
------------------
|
||||
If your required number of textures do indeed exceed the available number of textures units then one option is to break the mesh down into a number of pieces. Let's say you have a mesh which contains one hundred different materials. As an extreme solution you could break it down into one hundred separate meshes, and for each mesh you could then bind the required single texture before drawing the geometry. Obviously this will dramatically increase the batch count of your scene and so is not recommended.
|
||||
|
||||
A more practical approach would be to break the mesh into a smaller number of pieces such that each mesh uses several textures but less than the maximum number of texture units. For example, our mesh with one hundred materials could be split into ten meshes, the first of which contains those triangles using materials 0-9, the seconds contains those triangles using materials 10-19, and so forth. There is a trade off here between the number of batches and the number of textures units used per batch.
|
||||
|
||||
Furthermore, you could realise that although your terrain may use hundreds of different textures, any given region is likely to use only a small fraction of those. We have yet to experiment with this, but it seems if you region uses only (for example) materials 12, 47, and 231, then you could conceptually map these materials to the first three textures slots. This means that for each region you draw the mapping between material IDs and texture units would be different. This may require some complex logic in the application but could allow you to do much more with only a few texture units. We will investigate this further in the future.
|
||||
|
||||
Texture atlases
|
||||
---------------
|
||||
Probably the most widely used method is to pack a number of textures together into a single large texture, and to our knowledge this is the approach used by Minecraft. For example, if each of your textures are 256x256 texels, and if the maximum texture size supported by your target hardware is 4096x4096 texels, then you can pack 16 x 16 = 256 small textures into the larger one. If this isn't enough (or if your input textures are larger than 256x256) then you can also combine this approach with multiple texture units or with the mesh splitting described previously.
|
||||
|
||||
However, there are a number of problems with packing textures like this. Most obviously, it limits the size of your textures as they now have to be significantly smaller then the maximum texture size. Whether this is a problem will really depend on your application.
|
||||
|
||||
Next, it means you have to adjust your UV coordinates to correctly address a given texture inside the atlas. UV coordinates for a single texture would normally vary between 0.0 and 1.0 in both dimensions, but when packed into a texture atlas each texture uses only a small part of this range. You will need to apply offsets and scaling factors to your UV coordinates to address your texture correctly.
|
||||
|
||||
However, the biggest problem with texture atlases is that they causes problems with texture filtering and with mipmaps. The filtering problem occurs because graphics hardware usually samples the surrounding texels and performs linear interpolation to compute the colour of a given sample point, but when multiple textures are packed together these surrounding texels can actually come from a neighbouring packed texture rather than wrapping round to sample on the other side of the same packed texture. The mipmap problem occurs because for the highest mipmap levels (such as 1x1 or 2x2) multiple textures are being are being averaged together.
|
||||
|
||||
It is possible to combat these problems but the solutions are non-trivial. You will want to limit the number of miplevels which you use, and probably provide custom shader code to handle the wrapping of texture coordinates, the sampling of MIP maps, and the calculation of interpolated values. You can also try adding a border around all your packed textures, perhaps by duplicating each texture and offsetting by half its size. Even so, it's not clear to us at this point whether the the various artifacts can be completely removed. Minecraft handles it by completely disabling texture filtering and using the resulting pixelated look as part of its aesthetic.
|
||||
|
||||
3D texture slices
|
||||
-----------------
|
||||
The idea here is similar to the texture atlas approach, but rather than packing texture side-by-side in an atlas they are instead packed as slices in a 3D texture. We haven't actually tested this but in theory it may have a couple of benefits. Firstly, it simplifies the addressing of the texture as there is no need to offset/scale the UV coordinates, and the W coordinate (the slice index) can be more easily computed from the material identifier. Secondly, a single volume texture will usually be able to hold more texels than a single 2D texture (for example, 512x512x512 is bigger than 4096x4096). Lastly, it should simplify the filtering problem as packed textures are no longer tiled and so should wrap correctly.
|
||||
|
||||
However, MIP mapping will probably be more complex than the texture atlas case because even the first MIP level will involve combining adjacent slices. Volume textures are also not so widely supported and may be particularly problematic on mobile hardware.
|
||||
|
||||
Texture arrays
|
||||
--------------
|
||||
These provide the perfect solution to the problem of handling a large number of textures... at least if they are supported by your hardware. They were introduced with OpenGL 3 and Direct3D 10 but older versions of OpenGL may still be able to access the functionality via extensions. They allow you to bind an array of textures to the shader, and the advantage compared to a texture atlas is that the hardware understands that the textures are separate and so avoids the filtering and mipmapping issues. Beyond the hardware requirements, the only real limitation is that all the textures must be the same size.
|
||||
|
||||
Bindless rendering
|
||||
------------------
|
||||
We don't have much to say about this option as it needs significant research, but bindless rendering is one of the new OpenGL extensions to come out of Nvidia. The idea is that it removes the abstraction of needing to 'bind' a texture to a particular texture unit, and instead allows more direct access to the texture data on the GPU. This means you can have access to a much larger number of textures from your shader. Sounds useful, but we've yet to investigate it.
|
@ -1,67 +1,69 @@
|
||||
*********
|
||||
Threading
|
||||
*********
|
||||
Modern computing hardware typically contains a large number of processors, and so users of PolyVox often want to know how they can best make use of these from their applications.
|
||||
|
||||
PolyVox does not make any guarantees about thread-safety, and does not contain any threading primitives to protect access to data structures. You can still make use of PolyVox from multiple threads, but you will have to take responsibility for enforcing thread safety yourself (e.g. by providing thread safe wrappers around the volume classes). If you do want to use PolyVox is a multi-threaded context then this document provides some tips and tricks that you might find useful.
|
||||
|
||||
However, be aware that we do not have a lot of expertise in threading, and this is part of the reason why it is not explicitly addressed within PolyVox. If you do have more experience and believe any of this information to be misleading then please do post on the forums to discuss it.
|
||||
|
||||
Volumes
|
||||
=======
|
||||
Volumes are a core aspect of PolyVox, and so a natural question is whether it is safe to simultaneously access a given volume from multiple threads. The answer to this is actually fairly complex and is also dependent on the type of volume which is being used.
|
||||
|
||||
RawVolume
|
||||
---------
|
||||
The RawVolume has a very simple internal structure in which the data is stored as a single array which is never moved or resized. Because of this property it is indeed safe to perform multiple simultaneous *reads* of the data from different threads. However, it is generally not safe to perform simultaneous writes from different threads, or even to write from only one thread while other threads are reading.
|
||||
|
||||
The reason why simultaneous writes can be problematic should be fairly obvious - if two different threads try to write to the same voxel then the result will depend on which thread writes first. But why can't we write from one thread and read from another one? The problem here is that the the CPU may implement some kind of caching mechanism and/or choose to store data in registers. If a write operation occurs before a read, then the read *may* still obtain the old value because the cache has not been updated yet. There may even be a cache for each thread (particularly if running on multiple processors).
|
||||
|
||||
If we assume for a moment that each voxel is a simple integer, then the rules for accessing a single voxel from multiple threads are the same as the rules for accessing integers from multiple threads. There is some useful information about this available on the web, including a discussion on StackOverflow: http://stackoverflow.com/questions/4588915/can-an-integer-be-shared-between-threads-safely
|
||||
|
||||
If nothing else, this serves to illustrate that multi-threaded access even to something as simple as an integer can be surprisingly complex and architecture dependant.
|
||||
|
||||
However, all this has been in the context of accessing a *single* voxel from multiple threads... what if we carefully design our algorithm such that different threads access different parts of the volume which never overlap? Unfortunately I don't believe this is a solution either. Caching mechanisms seldom operate on individual elements but instead tend to cache larger chunks of data on the grounds that data accesses are usually localised. So it's quite possible that accessing a given voxel will cause another voxel to be cached.
|
||||
|
||||
C++ does provide the 'volatile' keyword which can be used to ensure a variable is updated immediately (rather than being cached) but this is still not sufficient for thread safe code. It also has performance implications which we would like to avoid. More information about volatile and multitheaded programming can be found here: http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/
|
||||
|
||||
Lastly, note that PolyVox volumes are templatised which means the voxel type might be something other than a simple int. However we don't think this actually makes a difference given that so few guarantees are made anyway, and it should still be safe to perform multiple concurrent reads for more complex types.
|
||||
|
||||
LargeVolume
|
||||
-----------
|
||||
The LargeVolume provides even less thread safety than the RawVolume, in that even concurrent read operations can cause problems. The reason for this is the more complex memory management which is performed behind the scenes, and which allows pieces of volume data to be moved around and deleted. For example, a read of a single voxel may mean that the block of data associated with that voxel has to be paged in to memory, which in turn may mean that another block of data has to be paged out of memory. If second thread was halfway through reading a voxel in this second block of data then a problem will occur.
|
||||
|
||||
In the future we may do a more comprehensive analysis of thread safety in the LargeVolume, but for now you should assume that any multithreaded access can cause problems.
|
||||
|
||||
Consequences of abuse
|
||||
---------------------
|
||||
We have outlined above the rules for multithreaded access of volumes, but what actually happens if you violate these? There's a couple of things to watch out for:
|
||||
|
||||
- As mentioned, performing unprotected writes to the volume can cause problems because the data may be copied into the CPU cache and/or registers, and so a subsequent read could retrieve the old value. This is not what you want but probably won't be fatal (i.e. it shouldn't crash). It would basically manifest itself as data corruption.
|
||||
- If you access the LargeVolume in a multithreaded fashion then you risk trying to access data which has been removed by another thread, and in this case you will get undefined behaviour. This will probably be a crash (out of bounds access) but really anything could happen.
|
||||
|
||||
Surface Extraction
|
||||
==================
|
||||
Despite the lack of thread safety built in to PolyVox, it is still possible and often desirable to make use of multiple threads for tasks such as surface extraction. Performing surface extraction does not require write access to the data, and we've already established that you can safely perform reads from different threads *provided you are not using the LargeVolume*.
|
||||
|
||||
Combining multiple surface extraction threads with the *LargeVolume* is something we will need to experiment with in the future, to determine how it can be improved.
|
||||
|
||||
In the future we will expand this section to discuss how to split surface extraction across a number of threads, but for now please see Section XX of the book chapter 'Volumetric Representation of Virtual environments', available for free here: http://books.google.nl/books?id=WNfD2u8nIlIC&lpg=PR1&dq=game+engine+gems&pg=PA39&redir_esc=y#v=onepage&q&f=false
|
||||
|
||||
GPU thread safety
|
||||
=================
|
||||
Be aware that even if you successfully perform surface across multiple threads you still need to take care when uploading the data to the GPU. For Direct3D 9.0 and OpenGL 2.0 it is only possible to upload data from the main thread (or more accurately the one which owns the rendering context). So after you have performed your multi-threaded surface extraction you need to bring the data back to the main thread for uploading to the GPU.
|
||||
|
||||
More recent versions of the Direct3D and OpenGL APIs lift this restriction and provide means of accessing GPU resources from multiple threads. Please consult the documentation for your API for details.
|
||||
|
||||
Future work
|
||||
===========
|
||||
Threading support is not a high priority for PolyVox because it can be implemented by the user at a higher level. However, there are a couple of areas we may investigate in the future.
|
||||
|
||||
Thread safe volume wrapper
|
||||
--------------------------
|
||||
It might be useful to provide a thread safe wrapper around the volume classes, and this could possibly be included in the PolyVox utilities or as a extra library. This thread safe wrapper could be templatised to work with any internal volume type, and could itself be a volume so that it can be used directly with the existing algorithms.
|
||||
|
||||
OpenMP
|
||||
------
|
||||
*********
|
||||
Threading
|
||||
*********
|
||||
Modern computing hardware typically contains a large number of processors, and so users of PolyVox often want to know how they can best make use of these from their applications.
|
||||
|
||||
PolyVox does not make any guarantees about thread-safety, and does not contain any threading primitives to protect access to data structures. You can still make use of PolyVox from multiple threads, but you will have to take responsibility for enforcing thread safety yourself (e.g. by providing thread safe wrappers around the volume classes). If you do want to use PolyVox is a multi-threaded context then this document provides some tips and tricks that you might find useful.
|
||||
|
||||
However, be aware that we do not have a lot of expertise in threading, and this is part of the reason why it is not explicitly addressed within PolyVox. If you do have more experience and believe any of this information to be misleading then please do post on the forums to discuss it.
|
||||
|
||||
Volumes
|
||||
=======
|
||||
Volumes are a core aspect of PolyVox, and so a natural question is whether it is safe to simultaneously access a given volume from multiple threads. The answer to this is actually fairly complex and is also dependent on the type of volume which is being used.
|
||||
|
||||
RawVolume
|
||||
---------
|
||||
The RawVolume has a very simple internal structure in which the data is stored as a single array which is never moved or resized. Because of this property it is indeed safe to perform multiple simultaneous *reads* of the data from different threads. However, it is generally not safe to perform simultaneous writes from different threads, or even to write from only one thread while other threads are reading.
|
||||
|
||||
The reason why simultaneous writes can be problematic should be fairly obvious - if two different threads try to write to the same voxel then the result will depend on which thread writes first. But why can't we write from one thread and read from another one? The problem here is that the the CPU may implement some kind of caching mechanism and/or choose to store data in registers. If a write operation occurs before a read, then the read *may* still obtain the old value because the cache has not been updated yet. There may even be a cache for each thread (particularly if running on multiple processors).
|
||||
|
||||
If we assume for a moment that each voxel is a simple integer, then the rules for accessing a single voxel from multiple threads are the same as the rules for accessing integers from multiple threads. There is some useful information about this available on the web, including a discussion on StackOverflow: http://stackoverflow.com/questions/4588915/can-an-integer-be-shared-between-threads-safely
|
||||
|
||||
If nothing else, this serves to illustrate that multi-threaded access even to something as simple as an integer can be surprisingly complex and architecture dependant.
|
||||
|
||||
However, all this has been in the context of accessing a *single* voxel from multiple threads... what if we carefully design our algorithm such that different threads access different parts of the volume which never overlap? Unfortunately I don't believe this is a solution either. Caching mechanisms seldom operate on individual elements but instead tend to cache larger chunks of data on the grounds that data accesses are usually localised. So it's quite possible that accessing a given voxel will cause another voxel to be cached.
|
||||
|
||||
C++ does provide the 'volatile' keyword which can be used to ensure a variable is updated immediately (rather than being cached) but this is still not sufficient for thread safe code. It also has performance implications which we would like to avoid. More information about volatile and multitheaded programming can be found here: http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/
|
||||
|
||||
Lastly, note that PolyVox volumes are templatised which means the voxel type might be something other than a simple int. However we don't think this actually makes a difference given that so few guarantees are made anyway, and it should still be safe to perform multiple concurrent reads for more complex types.
|
||||
|
||||
PagedVolume
|
||||
-----------
|
||||
NOTE: The info below is based on LargeVolume, which PagedVolume has replaced. It is likely that the same limitations apply but this has not been well tested. We do intend to improve the thread safty of PagedVolume in the future.
|
||||
|
||||
The LargeVolume provides even less thread safety than the RawVolume, in that even concurrent read operations can cause problems. The reason for this is the more complex memory management which is performed behind the scenes, and which allows pieces of volume data to be moved around and deleted. For example, a read of a single voxel may mean that the block of data associated with that voxel has to be paged in to memory, which in turn may mean that another block of data has to be paged out of memory. If second thread was halfway through reading a voxel in this second block of data then a problem will occur.
|
||||
|
||||
In the future we may do a more comprehensive analysis of thread safety in the LargeVolume, but for now you should assume that any multithreaded access can cause problems.
|
||||
|
||||
Consequences of abuse
|
||||
---------------------
|
||||
We have outlined above the rules for multithreaded access of volumes, but what actually happens if you violate these? There's a couple of things to watch out for:
|
||||
|
||||
- As mentioned, performing unprotected writes to the volume can cause problems because the data may be copied into the CPU cache and/or registers, and so a subsequent read could retrieve the old value. This is not what you want but probably won't be fatal (i.e. it shouldn't crash). It would basically manifest itself as data corruption.
|
||||
- If you access the LargeVolume in a multithreaded fashion then you risk trying to access data which has been removed by another thread, and in this case you will get undefined behaviour. This will probably be a crash (out of bounds access) but really anything could happen.
|
||||
|
||||
Surface Extraction
|
||||
==================
|
||||
Despite the lack of thread safety built in to PolyVox, it is still possible and often desirable to make use of multiple threads for tasks such as surface extraction. Performing surface extraction does not require write access to the data, and we've already established that you can safely perform reads from different threads *provided you are not using the LargeVolume*.
|
||||
|
||||
Combining multiple surface extraction threads with the *LargeVolume* is something we will need to experiment with in the future, to determine how it can be improved.
|
||||
|
||||
In the future we will expand this section to discuss how to split surface extraction across a number of threads, but for now please see Section XX of the book chapter 'Volumetric Representation of Virtual environments', available for free here: http://books.google.nl/books?id=WNfD2u8nIlIC&lpg=PR1&dq=game+engine+gems&pg=PA39&redir_esc=y#v=onepage&q&f=false
|
||||
|
||||
GPU thread safety
|
||||
=================
|
||||
Be aware that even if you successfully perform surface across multiple threads you still need to take care when uploading the data to the GPU. For Direct3D 9.0 and OpenGL 2.0 it is only possible to upload data from the main thread (or more accurately the one which owns the rendering context). So after you have performed your multi-threaded surface extraction you need to bring the data back to the main thread for uploading to the GPU.
|
||||
|
||||
More recent versions of the Direct3D and OpenGL APIs lift this restriction and provide means of accessing GPU resources from multiple threads. Please consult the documentation for your API for details.
|
||||
|
||||
Future work
|
||||
===========
|
||||
Threading support is not a high priority for PolyVox because it can be implemented by the user at a higher level. However, there are a couple of areas we may investigate in the future.
|
||||
|
||||
Thread safe volume wrapper
|
||||
--------------------------
|
||||
It might be useful to provide a thread safe wrapper around the volume classes, and this could possibly be included in the PolyVox utilities or as a extra library. This thread safe wrapper could be templatised to work with any internal volume type, and could itself be a volume so that it can be used directly with the existing algorithms.
|
||||
|
||||
OpenMP
|
||||
------
|
||||
This is a standard for extending C++ with compiler directives which allow the compiler to automatically parallelise sections of code. Most likely this could be used to parallelise some of the loops which occur in image processing tasks.
|
@ -1,4 +1,4 @@
|
||||
Changelog
|
||||
#########
|
||||
|
||||
.. include:: ../CHANGELOG.txt
|
||||
Changelog
|
||||
#########
|
||||
|
||||
.. include:: ../CHANGELOG.txt
|
||||
|
@ -1,232 +1,232 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# PolyVox documentation build configuration file, created by
|
||||
# sphinx-quickstart on Tue Jul 6 14:46:57 2010.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
sys.path.append('@CMAKE_CURRENT_SOURCE_DIR@/_extensions')
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinxcontrib.doxylink']
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'PolyVox'
|
||||
copyright = u'2013, David Williams, Matt Williams'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '@POLYVOX_VERSION@'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '@POLYVOX_VERSION@'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
language = "en"
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = ['_build']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'default'
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = []
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_static']
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = ''
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
#htmlhelp_basename = 'PolyVoxdoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
# The paper size ('letter' or 'a4').
|
||||
#latex_paper_size = 'letter'
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#latex_font_size = '10pt'
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
latex_documents = [
|
||||
('index', 'PolyVox.tex', u'PolyVox Documentation',
|
||||
u'David Williams, Matt Williams', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#latex_preamble = ''
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'polyvox', u'PolyVox Documentation',
|
||||
[u'David Williams, Matt Williams'], 1)
|
||||
]
|
||||
|
||||
|
||||
# Example configuration for intersphinx: refer to the Python standard library.
|
||||
#intersphinx_mapping = {'http://docs.python.org/': None}
|
||||
|
||||
doxylink = {
|
||||
'polyvox' : ('@CMAKE_CURRENT_BINARY_DIR@/../library/PolyVox.tag', '../library/doc/html/') #Make this '../api/' for uploading
|
||||
}
|
||||
|
||||
#This must be lowercase for QtHelp
|
||||
qthelp_basename = "polyvox"
|
||||
|
||||
primary_domain = "c++"
|
||||
|
||||
# Default higlighting scheme to use for `code-block` directives
|
||||
highlight_language = "c++"
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# PolyVox documentation build configuration file, created by
|
||||
# sphinx-quickstart on Tue Jul 6 14:46:57 2010.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
sys.path.append('@CMAKE_CURRENT_SOURCE_DIR@/_extensions')
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinxcontrib.doxylink']
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'PolyVox'
|
||||
copyright = u'2013, David Williams, Matt Williams'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '@POLYVOX_VERSION@'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '@POLYVOX_VERSION@'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
language = "en"
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = ['_build']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'default'
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = []
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_static']
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = ''
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
#htmlhelp_basename = 'PolyVoxdoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
# The paper size ('letter' or 'a4').
|
||||
#latex_paper_size = 'letter'
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#latex_font_size = '10pt'
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
latex_documents = [
|
||||
('index', 'PolyVox.tex', u'PolyVox Documentation',
|
||||
u'David Williams, Matt Williams', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#latex_preamble = ''
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'polyvox', u'PolyVox Documentation',
|
||||
[u'David Williams, Matt Williams'], 1)
|
||||
]
|
||||
|
||||
|
||||
# Example configuration for intersphinx: refer to the Python standard library.
|
||||
#intersphinx_mapping = {'http://docs.python.org/': None}
|
||||
|
||||
doxylink = {
|
||||
'polyvox' : ('@CMAKE_CURRENT_BINARY_DIR@/../library/PolyVox.tag', '../library/doc/html/') #Make this '../api/' for uploading
|
||||
}
|
||||
|
||||
#This must be lowercase for QtHelp
|
||||
qthelp_basename = "polyvox"
|
||||
|
||||
primary_domain = "c++"
|
||||
|
||||
# Default higlighting scheme to use for `code-block` directives
|
||||
highlight_language = "c++"
|
||||
|
@ -1,41 +1,41 @@
|
||||
Welcome to PolyVox's documentation!
|
||||
===================================
|
||||
|
||||
User Guide:
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
Prerequisites
|
||||
install
|
||||
principles
|
||||
Lighting
|
||||
TextureMapping
|
||||
ModifyingTerrain
|
||||
LevelOfDetail
|
||||
Threading
|
||||
ErrorHandling
|
||||
|
||||
Examples:
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
tutorial1
|
||||
python-bindings
|
||||
|
||||
Other Information:
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
changelog
|
||||
FAQ
|
||||
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`search`
|
||||
|
||||
Welcome to PolyVox's documentation!
|
||||
===================================
|
||||
|
||||
User Guide:
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
Prerequisites
|
||||
install
|
||||
principles
|
||||
Lighting
|
||||
TextureMapping
|
||||
ModifyingTerrain
|
||||
LevelOfDetail
|
||||
Threading
|
||||
ErrorHandling
|
||||
|
||||
Examples:
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
tutorial1
|
||||
python-bindings
|
||||
|
||||
Other Information:
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
changelog
|
||||
FAQ
|
||||
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`search`
|
||||
|
||||
|
@ -1 +1 @@
|
||||
.. include:: ../INSTALL.txt
|
||||
.. include:: ../INSTALL.txt
|
||||
|
@ -1,155 +1,155 @@
|
||||
@ECHO OFF
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set BUILDDIR=_build
|
||||
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
|
||||
if NOT "%PAPER%" == "" (
|
||||
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
|
||||
)
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
if "%1" == "help" (
|
||||
:help
|
||||
echo.Please use `make ^<target^>` where ^<target^> is one of
|
||||
echo. html to make standalone HTML files
|
||||
echo. dirhtml to make HTML files named index.html in directories
|
||||
echo. singlehtml to make a single large HTML file
|
||||
echo. pickle to make pickle files
|
||||
echo. json to make JSON files
|
||||
echo. htmlhelp to make HTML files and a HTML help project
|
||||
echo. qthelp to make HTML files and a qthelp project
|
||||
echo. devhelp to make HTML files and a Devhelp project
|
||||
echo. epub to make an epub
|
||||
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
|
||||
echo. text to make text files
|
||||
echo. man to make manual pages
|
||||
echo. changes to make an overview over all changed/added/deprecated items
|
||||
echo. linkcheck to check all external links for integrity
|
||||
echo. doctest to run all doctests embedded in the documentation if enabled
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "clean" (
|
||||
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
|
||||
del /q /s %BUILDDIR%\*
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "html" (
|
||||
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "dirhtml" (
|
||||
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "singlehtml" (
|
||||
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pickle" (
|
||||
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
|
||||
echo.
|
||||
echo.Build finished; now you can process the pickle files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "json" (
|
||||
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
|
||||
echo.
|
||||
echo.Build finished; now you can process the JSON files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "htmlhelp" (
|
||||
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
|
||||
echo.
|
||||
echo.Build finished; now you can run HTML Help Workshop with the ^
|
||||
.hhp project file in %BUILDDIR%/htmlhelp.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "qthelp" (
|
||||
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
|
||||
echo.
|
||||
echo.Build finished; now you can run "qcollectiongenerator" with the ^
|
||||
.qhcp project file in %BUILDDIR%/qthelp, like this:
|
||||
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PolyVox.qhcp
|
||||
echo.To view the help file:
|
||||
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PolyVox.ghc
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "devhelp" (
|
||||
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
|
||||
echo.
|
||||
echo.Build finished.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "epub" (
|
||||
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
|
||||
echo.
|
||||
echo.Build finished. The epub file is in %BUILDDIR%/epub.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latex" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
echo.
|
||||
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "text" (
|
||||
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
|
||||
echo.
|
||||
echo.Build finished. The text files are in %BUILDDIR%/text.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "man" (
|
||||
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
|
||||
echo.
|
||||
echo.Build finished. The manual pages are in %BUILDDIR%/man.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "changes" (
|
||||
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
|
||||
echo.
|
||||
echo.The overview file is in %BUILDDIR%/changes.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "linkcheck" (
|
||||
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
|
||||
echo.
|
||||
echo.Link check complete; look for any errors in the above output ^
|
||||
or in %BUILDDIR%/linkcheck/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "doctest" (
|
||||
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
|
||||
echo.
|
||||
echo.Testing of doctests in the sources finished, look at the ^
|
||||
results in %BUILDDIR%/doctest/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
:end
|
||||
@ECHO OFF
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set BUILDDIR=_build
|
||||
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
|
||||
if NOT "%PAPER%" == "" (
|
||||
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
|
||||
)
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
if "%1" == "help" (
|
||||
:help
|
||||
echo.Please use `make ^<target^>` where ^<target^> is one of
|
||||
echo. html to make standalone HTML files
|
||||
echo. dirhtml to make HTML files named index.html in directories
|
||||
echo. singlehtml to make a single large HTML file
|
||||
echo. pickle to make pickle files
|
||||
echo. json to make JSON files
|
||||
echo. htmlhelp to make HTML files and a HTML help project
|
||||
echo. qthelp to make HTML files and a qthelp project
|
||||
echo. devhelp to make HTML files and a Devhelp project
|
||||
echo. epub to make an epub
|
||||
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
|
||||
echo. text to make text files
|
||||
echo. man to make manual pages
|
||||
echo. changes to make an overview over all changed/added/deprecated items
|
||||
echo. linkcheck to check all external links for integrity
|
||||
echo. doctest to run all doctests embedded in the documentation if enabled
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "clean" (
|
||||
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
|
||||
del /q /s %BUILDDIR%\*
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "html" (
|
||||
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "dirhtml" (
|
||||
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "singlehtml" (
|
||||
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
|
||||
echo.
|
||||
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "pickle" (
|
||||
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
|
||||
echo.
|
||||
echo.Build finished; now you can process the pickle files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "json" (
|
||||
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
|
||||
echo.
|
||||
echo.Build finished; now you can process the JSON files.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "htmlhelp" (
|
||||
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
|
||||
echo.
|
||||
echo.Build finished; now you can run HTML Help Workshop with the ^
|
||||
.hhp project file in %BUILDDIR%/htmlhelp.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "qthelp" (
|
||||
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
|
||||
echo.
|
||||
echo.Build finished; now you can run "qcollectiongenerator" with the ^
|
||||
.qhcp project file in %BUILDDIR%/qthelp, like this:
|
||||
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PolyVox.qhcp
|
||||
echo.To view the help file:
|
||||
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PolyVox.ghc
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "devhelp" (
|
||||
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
|
||||
echo.
|
||||
echo.Build finished.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "epub" (
|
||||
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
|
||||
echo.
|
||||
echo.Build finished. The epub file is in %BUILDDIR%/epub.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "latex" (
|
||||
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
|
||||
echo.
|
||||
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "text" (
|
||||
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
|
||||
echo.
|
||||
echo.Build finished. The text files are in %BUILDDIR%/text.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "man" (
|
||||
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
|
||||
echo.
|
||||
echo.Build finished. The manual pages are in %BUILDDIR%/man.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "changes" (
|
||||
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
|
||||
echo.
|
||||
echo.The overview file is in %BUILDDIR%/changes.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "linkcheck" (
|
||||
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
|
||||
echo.
|
||||
echo.Link check complete; look for any errors in the above output ^
|
||||
or in %BUILDDIR%/linkcheck/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%1" == "doctest" (
|
||||
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
|
||||
echo.
|
||||
echo.Testing of doctests in the sources finished, look at the ^
|
||||
results in %BUILDDIR%/doctest/output.txt.
|
||||
goto end
|
||||
)
|
||||
|
||||
:end
|
||||
|
@ -1,14 +1,14 @@
|
||||
**********************
|
||||
Principles of PolyVox
|
||||
**********************
|
||||
|
||||
.. warning ::
|
||||
This section is being written and is just a skeleton for now
|
||||
|
||||
PolyVox provides a library for managing 3D arrays (volumes) of data (voxels). It gives you the tools to iterate through, randomly access, read and write volumes. It supports any type you'd like to represent each voxel whether it's just an ``int`` or a class which encapsulates both density and colour.
|
||||
|
||||
Once you have a volume, PolyVox provides a number of tools for turning it into something that you can pass to your rendering engine. These are called `surface extractors`.
|
||||
|
||||
Each surface extractor needs to be told how to interperet your voxel type and that is done using...
|
||||
|
||||
Link to a page describing how to write your own voxel type and link it to a surface extractor...
|
||||
**********************
|
||||
Principles of PolyVox
|
||||
**********************
|
||||
|
||||
.. warning ::
|
||||
This section is being written and is just a skeleton for now
|
||||
|
||||
PolyVox provides a library for managing 3D arrays (volumes) of data (voxels). It gives you the tools to iterate through, randomly access, read and write volumes. It supports any type you'd like to represent each voxel whether it's just an ``int`` or a class which encapsulates both density and colour.
|
||||
|
||||
Once you have a volume, PolyVox provides a number of tools for turning it into something that you can pass to your rendering engine. These are called `surface extractors`.
|
||||
|
||||
Each surface extractor needs to be told how to interperet your voxel type and that is done using...
|
||||
|
||||
Link to a page describing how to write your own voxel type and link it to a surface extractor...
|
||||
|
@ -1,166 +1,166 @@
|
||||
**********************
|
||||
Tutorial 1 - Basic use
|
||||
**********************
|
||||
|
||||
Introduction
|
||||
============
|
||||
This tutorial covers the basic use of the PolyVox API. After reading this tutorial you should have a good idea how to create a PolyVox volume and fill it with data, extract a triangle mesh representing the surface, and render the result. This tutorial assumes you are already familiar with the basic concepts behind PolyVox (see the :doc:`principles of polyvox <principles>` document if not), and are reasonably confident with 3D graphics and C++. It also assumes you have already got PolyVox installed on your system, if this is not the case then please consult :doc:`installation guide <install>`.
|
||||
|
||||
The code samples and text in this tutorial correspond directly to the BasicExample which comes with PolyVox. This example uses the Qt toolkit for window and input handling, and for providing an OpenGL context to render into. In this tutorial we will omit code which performs these tasks and will instead focus on on the PolyVox code. You can consult the `Qt documentation <http://doc.qt.nokia.com/latest/>`_ if you want more information about these other aspects of the system.
|
||||
|
||||
Creating a volume
|
||||
=================
|
||||
To get started, we need to include the following headers:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
#include "PolyVoxCore/CubicSurfaceExtractorWithNormals.h"
|
||||
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
|
||||
#include "PolyVoxCore/SurfaceMesh.h"
|
||||
#include "PolyVoxCore/SimpleVolume.h"
|
||||
|
||||
The most fundamental construct when working with PolyVox is that of the volume. This is represented by the :polyvox:`SimpleVolume` class which stores a 3D grid of voxels. Our basic example application creates a volume with the following line of code:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(63, 63, 63)));
|
||||
|
||||
As can be seen, the SimpleVolume class is templated upon the voxel type. This means it is straightforward to create a volume of integers, floats, or a custom voxel type (see the :polyvox:`SimpleVolume documentation <PolyVox::SimpleVolume>` for more details). In this particular case we have created a volume in which each voxel is of type `uint8_t` which is an unsigned 8-bit integer.
|
||||
|
||||
Next, we set some of the voxels in the volume to be 'solid' in order to create a large sphere in the centre of the volume. We do this with the following function call:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
createSphereInVolume(volData, 30);
|
||||
|
||||
Note that this function is part of the BasicExample (rather than being part of the PolyVox library) and is implemented as follows:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
void createSphereInVolume(SimpleVolume<uint8_t>& volData, float fRadius)
|
||||
{
|
||||
//This vector hold the position of the center of the volume
|
||||
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
|
||||
|
||||
//This three-level for loop iterates over every voxel in the volume
|
||||
for (int z = 0; z < volData.getDepth(); z++)
|
||||
{
|
||||
for (int y = 0; y < volData.getHeight(); y++)
|
||||
{
|
||||
for (int x = 0; x < volData.getWidth(); x++)
|
||||
{
|
||||
//Store our current position as a vector...
|
||||
Vector3DFloat v3dCurrentPos(x,y,z);
|
||||
//And compute how far the current position is from the center of the volume
|
||||
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
|
||||
|
||||
uint8_t uVoxelValue = 0;
|
||||
|
||||
//If the current voxel is less than 'radius' units from the center then we make it solid.
|
||||
if(fDistToCenter <= fRadius)
|
||||
{
|
||||
//Our new voxel value
|
||||
uVoxelValue = 255;
|
||||
}
|
||||
|
||||
//Wrte the voxel value into the volume
|
||||
volData.setVoxelAt(x, y, z, uVoxelValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
This function takes as input the :polyvox:`SimpleVolume` in which we want to create the sphere, and also a radius specifying how large we want the sphere to be. In our case we have specified a radius of 30 voxels, which will fit nicely inside our :polyvox:`SimpleVolume` of dimensions 64x64x64.
|
||||
|
||||
Because this is a simple example function it always places the sphere at the centre of the volume. It computes this centre by halving the dimensions of the volume as given by the functions :polyvox:`SimpleVolume::getWidth`, :polyvox:`SimpleVolume::getHeight` and :polyvox:`SimpleVolume::getDepth`. The resulting position is stored using a :polyvox:`Vector3DFloat`. This is simply a typedef from our templatised :polyvox:`Vector` class, meaning that other sizes and storage types are available if you need them.
|
||||
|
||||
Next, the function uses a three-level 'for' loop to iterate over each voxel in the volume. For each voxel it computes the distance from the voxel to the centre of the volume. If this distance is less than or equal to the specified radius then the voxel forms part of the sphere and is made solid. During surface extraction, the voxel will be considered empty if it has a value of zero, and otherwise it will be considered solid. In our case we simply set it to 255 which is the largest value a uint8_t can contain.
|
||||
|
||||
Extracting the surface
|
||||
======================
|
||||
Now that we have built our volume we need to convert it into a triangle mesh for rendering. This process can be performed by the :polyvox:`CubicSurfaceExtractorWithNormals` class. An instance of the :polyvox:`CubicSurfaceExtractorWithNormals` is created as follows:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
SurfaceMesh<PositionMaterialNormal> mesh;
|
||||
CubicSurfaceExtractorWithNormals< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
|
||||
|
||||
The :polyvox:`CubicSurfaceExtractorWithNormals` takes a pointer to the volume data, and also it needs to be told which :polyvox:`Region` of the volume the extraction should be performed on (in more advanced applications this is useful for extracting only those parts of the volume which have been modified since the last extraction). For our purpose the :polyvox:`SimpleVolume` class provides a convenient :polyvox:`SimpleVolume::getEnclosingRegion` function which returns a :polyvox:`Region` representing the whole volume. The constructor also takes a pointer to a :polyvox:`SurfaceMesh` object where it will store the result, so we need to create one of these before we can construct the :polyvox:`CubicSurfaceExtractorWithNormals`.
|
||||
|
||||
The actual extraction happens in the :polyvox:`CubicSurfaceExtractorWithNormals::execute` function. This means you can set up a :polyvox:`CubicSurfaceExtractorWithNormals` with the required parameters and then actually execute it later. For this example we just call it straight away.
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
surfaceExtractor.execute();
|
||||
|
||||
This fills in our :polyvox:`SurfaceMesh` object, which basically contains an index and vertex buffer representing the desired triangle mesh.
|
||||
|
||||
Note: If you like you can try swapping the :polyvox:`CubicSurfaceExtractorWithNormals` for :polyvox:`MarchingCubesSurfaceExtractor`. We have already included the relevant header, and in the BasicExample you just need to change which line in commented out. The :polyvox:`MarchingCubesSurfaceExtractor` makes use of a smooth density field and will consider a voxel to be solid if it is above a threshold of half the voxel's maximum value (so in this case that's half of 255, which is 127).
|
||||
|
||||
Rendering the surface
|
||||
=====================
|
||||
Rendering the surface with OpenGL is handled by the OpenGLWidget class. Again, this is not part of PolyVox, it is simply an example based on Qt and OpenGL which demonstrates how rendering can be performed. Within this class there are mainly two functions which are of interest - the OpenGLWidget::setSurfaceMeshToRender() function which constructs OpenGL buffers from our :polyvox:`SurfaceMesh` and the OpenGLWidget::paintGL() function which is called each frame to perform the rendering.
|
||||
|
||||
The OpenGLWidget::setSurfaceMeshToRender() function is implemented as follows:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterialNormal>& surfaceMesh)
|
||||
{
|
||||
//Convienient access to the vertices and indices
|
||||
const vector<uint32_t>& vecIndices = surfaceMesh.getIndices();
|
||||
const vector<PositionMaterialNormal>& vecVertices = surfaceMesh.getVertices();
|
||||
|
||||
//Build an OpenGL index buffer
|
||||
glGenBuffers(1, &indexBuffer);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
const GLvoid* pIndices = static_cast<const GLvoid*>(&(vecIndices[0]));
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
|
||||
|
||||
//Build an OpenGL vertex buffer
|
||||
glGenBuffers(1, &vertexBuffer);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
|
||||
const GLvoid* pVertices = static_cast<const GLvoid*>(&(vecVertices[0]));
|
||||
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterialNormal), pVertices, GL_STATIC_DRAW);
|
||||
|
||||
m_uBeginIndex = 0;
|
||||
m_uEndIndex = vecIndices.size();
|
||||
}
|
||||
|
||||
We begin by obtaining direct access to the index and vertex buffer in the :polyvox:`SurfaceMesh` class in order to make the following code slightly cleaner. Both the :polyvox:`SurfaceMesh::getIndices` and :polyvox:`SurfaceMesh::getVertices` functions return an std::vector containing the relevant data.
|
||||
|
||||
The OpenGL functions which are called to construct the index and vertex buffer are best explained by the OpenGL documentation. In both cases we are making an exact copy of the data stored in the :polyvox:`SurfaceMesh`.
|
||||
|
||||
The begin and end indices are used in the OpenGLWidget::paintGL() to control what part of the index buffer is actually rendered. For this simple example we will render the whole buffer from '0' to 'vecIndices.size()'.
|
||||
|
||||
With the OpenGL index and vertex buffers set up, we can now look at the code which is called each frame to render them:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
void OpenGLWidget::paintGL()
|
||||
{
|
||||
//Clear the screen
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
//Set up the viewing transformation
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glLoadIdentity();
|
||||
glTranslatef(0.0f,0.0f,-100.0f); //Centre volume and move back
|
||||
glRotatef(-m_xRotation, 0.0f, 1.0f, 0.0f);
|
||||
glRotatef(-m_yRotation, 1.0f, 0.0f, 0.0f);
|
||||
glTranslatef(-32.0f,-32.0f,-32.0f); //Centre volume and move back
|
||||
|
||||
//Bind the index buffer
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
|
||||
//Bind the vertex buffer
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
|
||||
glVertexPointer(3, GL_FLOAT, sizeof(PositionMaterialNormal), 0);
|
||||
glNormalPointer(GL_FLOAT, sizeof(PositionMaterialNormal), (GLvoid*)12);
|
||||
|
||||
glDrawRangeElements(GL_TRIANGLES, m_uBeginIndex, m_uEndIndex-1, m_uEndIndex - m_uBeginIndex, GL_UNSIGNED_INT, 0);
|
||||
|
||||
//Error checking code here...
|
||||
}
|
||||
|
||||
**********************
|
||||
Tutorial 1 - Basic use
|
||||
**********************
|
||||
|
||||
Introduction
|
||||
============
|
||||
This tutorial covers the basic use of the PolyVox API. After reading this tutorial you should have a good idea how to create a PolyVox volume and fill it with data, extract a triangle mesh representing the surface, and render the result. This tutorial assumes you are already familiar with the basic concepts behind PolyVox (see the :doc:`principles of polyvox <principles>` document if not), and are reasonably confident with 3D graphics and C++. It also assumes you have already got PolyVox installed on your system, if this is not the case then please consult :doc:`installation guide <install>`.
|
||||
|
||||
The code samples and text in this tutorial correspond directly to the BasicExample which comes with PolyVox. This example uses the Qt toolkit for window and input handling, and for providing an OpenGL context to render into. In this tutorial we will omit code which performs these tasks and will instead focus on on the PolyVox code. You can consult the `Qt documentation <http://doc.qt.nokia.com/latest/>`_ if you want more information about these other aspects of the system.
|
||||
|
||||
Creating a volume
|
||||
=================
|
||||
To get started, we need to include the following headers:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
#include "PolyVoxCore/CubicSurfaceExtractorWithNormals.h"
|
||||
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
|
||||
#include "PolyVoxCore/SurfaceMesh.h"
|
||||
#include "PolyVoxCore/SimpleVolume.h"
|
||||
|
||||
The most fundamental construct when working with PolyVox is that of the volume. This is represented by the :polyvox:`SimpleVolume` class which stores a 3D grid of voxels. Our basic example application creates a volume with the following line of code:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(63, 63, 63)));
|
||||
|
||||
As can be seen, the SimpleVolume class is templated upon the voxel type. This means it is straightforward to create a volume of integers, floats, or a custom voxel type (see the :polyvox:`SimpleVolume documentation <PolyVox::SimpleVolume>` for more details). In this particular case we have created a volume in which each voxel is of type `uint8_t` which is an unsigned 8-bit integer.
|
||||
|
||||
Next, we set some of the voxels in the volume to be 'solid' in order to create a large sphere in the centre of the volume. We do this with the following function call:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
createSphereInVolume(volData, 30);
|
||||
|
||||
Note that this function is part of the BasicExample (rather than being part of the PolyVox library) and is implemented as follows:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
void createSphereInVolume(SimpleVolume<uint8_t>& volData, float fRadius)
|
||||
{
|
||||
//This vector hold the position of the center of the volume
|
||||
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
|
||||
|
||||
//This three-level for loop iterates over every voxel in the volume
|
||||
for (int z = 0; z < volData.getDepth(); z++)
|
||||
{
|
||||
for (int y = 0; y < volData.getHeight(); y++)
|
||||
{
|
||||
for (int x = 0; x < volData.getWidth(); x++)
|
||||
{
|
||||
//Store our current position as a vector...
|
||||
Vector3DFloat v3dCurrentPos(x,y,z);
|
||||
//And compute how far the current position is from the center of the volume
|
||||
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
|
||||
|
||||
uint8_t uVoxelValue = 0;
|
||||
|
||||
//If the current voxel is less than 'radius' units from the center then we make it solid.
|
||||
if(fDistToCenter <= fRadius)
|
||||
{
|
||||
//Our new voxel value
|
||||
uVoxelValue = 255;
|
||||
}
|
||||
|
||||
//Wrte the voxel value into the volume
|
||||
volData.setVoxelAt(x, y, z, uVoxelValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
This function takes as input the :polyvox:`SimpleVolume` in which we want to create the sphere, and also a radius specifying how large we want the sphere to be. In our case we have specified a radius of 30 voxels, which will fit nicely inside our :polyvox:`SimpleVolume` of dimensions 64x64x64.
|
||||
|
||||
Because this is a simple example function it always places the sphere at the centre of the volume. It computes this centre by halving the dimensions of the volume as given by the functions :polyvox:`SimpleVolume::getWidth`, :polyvox:`SimpleVolume::getHeight` and :polyvox:`SimpleVolume::getDepth`. The resulting position is stored using a :polyvox:`Vector3DFloat`. This is simply a typedef from our templatised :polyvox:`Vector` class, meaning that other sizes and storage types are available if you need them.
|
||||
|
||||
Next, the function uses a three-level 'for' loop to iterate over each voxel in the volume. For each voxel it computes the distance from the voxel to the centre of the volume. If this distance is less than or equal to the specified radius then the voxel forms part of the sphere and is made solid. During surface extraction, the voxel will be considered empty if it has a value of zero, and otherwise it will be considered solid. In our case we simply set it to 255 which is the largest value a uint8_t can contain.
|
||||
|
||||
Extracting the surface
|
||||
======================
|
||||
Now that we have built our volume we need to convert it into a triangle mesh for rendering. This process can be performed by the :polyvox:`CubicSurfaceExtractorWithNormals` class. An instance of the :polyvox:`CubicSurfaceExtractorWithNormals` is created as follows:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
SurfaceMesh<PositionMaterialNormal> mesh;
|
||||
CubicSurfaceExtractorWithNormals< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
|
||||
|
||||
The :polyvox:`CubicSurfaceExtractorWithNormals` takes a pointer to the volume data, and also it needs to be told which :polyvox:`Region` of the volume the extraction should be performed on (in more advanced applications this is useful for extracting only those parts of the volume which have been modified since the last extraction). For our purpose the :polyvox:`SimpleVolume` class provides a convenient :polyvox:`SimpleVolume::getEnclosingRegion` function which returns a :polyvox:`Region` representing the whole volume. The constructor also takes a pointer to a :polyvox:`SurfaceMesh` object where it will store the result, so we need to create one of these before we can construct the :polyvox:`CubicSurfaceExtractorWithNormals`.
|
||||
|
||||
The actual extraction happens in the :polyvox:`CubicSurfaceExtractorWithNormals::execute` function. This means you can set up a :polyvox:`CubicSurfaceExtractorWithNormals` with the required parameters and then actually execute it later. For this example we just call it straight away.
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
surfaceExtractor.execute();
|
||||
|
||||
This fills in our :polyvox:`SurfaceMesh` object, which basically contains an index and vertex buffer representing the desired triangle mesh.
|
||||
|
||||
Note: If you like you can try swapping the :polyvox:`CubicSurfaceExtractorWithNormals` for :polyvox:`MarchingCubesSurfaceExtractor`. We have already included the relevant header, and in the BasicExample you just need to change which line in commented out. The :polyvox:`MarchingCubesSurfaceExtractor` makes use of a smooth density field and will consider a voxel to be solid if it is above a threshold of half the voxel's maximum value (so in this case that's half of 255, which is 127).
|
||||
|
||||
Rendering the surface
|
||||
=====================
|
||||
Rendering the surface with OpenGL is handled by the OpenGLWidget class. Again, this is not part of PolyVox, it is simply an example based on Qt and OpenGL which demonstrates how rendering can be performed. Within this class there are mainly two functions which are of interest - the OpenGLWidget::setSurfaceMeshToRender() function which constructs OpenGL buffers from our :polyvox:`SurfaceMesh` and the OpenGLWidget::paintGL() function which is called each frame to perform the rendering.
|
||||
|
||||
The OpenGLWidget::setSurfaceMeshToRender() function is implemented as follows:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterialNormal>& surfaceMesh)
|
||||
{
|
||||
//Convienient access to the vertices and indices
|
||||
const vector<uint32_t>& vecIndices = surfaceMesh.getIndices();
|
||||
const vector<PositionMaterialNormal>& vecVertices = surfaceMesh.getVertices();
|
||||
|
||||
//Build an OpenGL index buffer
|
||||
glGenBuffers(1, &indexBuffer);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
const GLvoid* pIndices = static_cast<const GLvoid*>(&(vecIndices[0]));
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
|
||||
|
||||
//Build an OpenGL vertex buffer
|
||||
glGenBuffers(1, &vertexBuffer);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
|
||||
const GLvoid* pVertices = static_cast<const GLvoid*>(&(vecVertices[0]));
|
||||
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterialNormal), pVertices, GL_STATIC_DRAW);
|
||||
|
||||
m_uBeginIndex = 0;
|
||||
m_uEndIndex = vecIndices.size();
|
||||
}
|
||||
|
||||
We begin by obtaining direct access to the index and vertex buffer in the :polyvox:`SurfaceMesh` class in order to make the following code slightly cleaner. Both the :polyvox:`SurfaceMesh::getIndices` and :polyvox:`SurfaceMesh::getVertices` functions return an std::vector containing the relevant data.
|
||||
|
||||
The OpenGL functions which are called to construct the index and vertex buffer are best explained by the OpenGL documentation. In both cases we are making an exact copy of the data stored in the :polyvox:`SurfaceMesh`.
|
||||
|
||||
The begin and end indices are used in the OpenGLWidget::paintGL() to control what part of the index buffer is actually rendered. For this simple example we will render the whole buffer from '0' to 'vecIndices.size()'.
|
||||
|
||||
With the OpenGL index and vertex buffers set up, we can now look at the code which is called each frame to render them:
|
||||
|
||||
.. sourcecode:: c++
|
||||
|
||||
void OpenGLWidget::paintGL()
|
||||
{
|
||||
//Clear the screen
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
//Set up the viewing transformation
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glLoadIdentity();
|
||||
glTranslatef(0.0f,0.0f,-100.0f); //Centre volume and move back
|
||||
glRotatef(-m_xRotation, 0.0f, 1.0f, 0.0f);
|
||||
glRotatef(-m_yRotation, 1.0f, 0.0f, 0.0f);
|
||||
glTranslatef(-32.0f,-32.0f,-32.0f); //Centre volume and move back
|
||||
|
||||
//Bind the index buffer
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
|
||||
//Bind the vertex buffer
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
|
||||
glVertexPointer(3, GL_FLOAT, sizeof(PositionMaterialNormal), 0);
|
||||
glNormalPointer(GL_FLOAT, sizeof(PositionMaterialNormal), (GLvoid*)12);
|
||||
|
||||
glDrawRangeElements(GL_TRIANGLES, m_uBeginIndex, m_uEndIndex-1, m_uEndIndex - m_uBeginIndex, GL_UNSIGNED_INT, 0);
|
||||
|
||||
//Error checking code here...
|
||||
}
|
||||
|
||||
Again, the explanation of this code is best left to the OpenGL documentation. Note that is is called automatically by Qt each time the display needs to be updated.
|
@ -1,73 +1,74 @@
|
||||
# Copyright (c) 2010-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
|
||||
|
||||
PROJECT(BasicExample)
|
||||
|
||||
#Projects source files
|
||||
SET(SRC_FILES
|
||||
main.cpp
|
||||
OpenGLWidget.cpp
|
||||
)
|
||||
|
||||
#Projects headers files
|
||||
SET(INC_FILES
|
||||
OpenGLWidget.h
|
||||
)
|
||||
|
||||
add_definitions(-DGLEW_STATIC)
|
||||
|
||||
#"Sources" and "Headers" are the group names in Visual Studio.
|
||||
#They may have other uses too...
|
||||
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
|
||||
SOURCE_GROUP("Headers" FILES ${INC_FILES})
|
||||
|
||||
FIND_PACKAGE(OpenGL REQUIRED)
|
||||
|
||||
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
|
||||
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${GLEW_SOURCE_DIR})
|
||||
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
|
||||
|
||||
#Build
|
||||
ADD_EXECUTABLE(BasicExample ${SRC_FILES})
|
||||
IF(MSVC)
|
||||
SET_TARGET_PROPERTIES(BasicExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
|
||||
ENDIF(MSVC)
|
||||
TARGET_LINK_LIBRARIES(BasicExample glew ${QT_LIBRARIES} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
|
||||
SET_PROPERTY(TARGET BasicExample PROPERTY FOLDER "Examples")
|
||||
|
||||
#Install - Only install the example in Windows
|
||||
IF(WIN32)
|
||||
INSTALL(TARGETS BasicExample
|
||||
RUNTIME DESTINATION Examples/OpenGL/bin
|
||||
LIBRARY DESTINATION Examples/OpenGL/lib
|
||||
ARCHIVE DESTINATION Examples/OpenGL/lib
|
||||
COMPONENT example
|
||||
)
|
||||
|
||||
#.dlls should be installed in shared builds.
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
ENDIF(WIN32)
|
||||
# Copyright (c) 2010-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
PROJECT(BasicExample)
|
||||
|
||||
#Projects source files
|
||||
SET(SRC_FILES
|
||||
main.cpp
|
||||
../common/PolyVoxExample.cpp
|
||||
)
|
||||
|
||||
#Projects headers files
|
||||
SET(INC_FILES
|
||||
../common/OpenGLWidget.h
|
||||
../common/OpenGLWidget.inl
|
||||
../common/PolyVoxExample.h
|
||||
)
|
||||
|
||||
#"Sources" and "Headers" are the group names in Visual Studio.
|
||||
#They may have other uses too...
|
||||
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
|
||||
SOURCE_GROUP("Headers" FILES ${INC_FILES})
|
||||
|
||||
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
|
||||
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ../common)
|
||||
|
||||
#This will include the shader files inside the compiled binary
|
||||
QT5_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
|
||||
|
||||
# Put the resources in a seperate folder in Visual Studio
|
||||
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC})
|
||||
|
||||
#Build
|
||||
ADD_EXECUTABLE(BasicExample ${SRC_FILES} ${COMMON_RESOURCES_RCC})
|
||||
IF(MSVC)
|
||||
SET_TARGET_PROPERTIES(BasicExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127") #All warnings
|
||||
ENDIF(MSVC)
|
||||
TARGET_LINK_LIBRARIES(BasicExample Qt5::OpenGL)
|
||||
SET_PROPERTY(TARGET BasicExample PROPERTY FOLDER "Examples")
|
||||
|
||||
#Install - Only install the example in Windows
|
||||
IF(WIN32)
|
||||
INSTALL(TARGETS BasicExample
|
||||
RUNTIME DESTINATION Examples/OpenGL/bin
|
||||
LIBRARY DESTINATION Examples/OpenGL/lib
|
||||
ARCHIVE DESTINATION Examples/OpenGL/lib
|
||||
COMPONENT example
|
||||
)
|
||||
|
||||
#.dlls should be installed in shared builds.
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
ENDIF(WIN32)
|
||||
|
@ -1,152 +0,0 @@
|
||||
#include "OpenGLWidget.h"
|
||||
|
||||
#include <QMouseEvent>
|
||||
|
||||
using namespace PolyVox;
|
||||
using namespace std;
|
||||
|
||||
OpenGLWidget::OpenGLWidget(QWidget *parent)
|
||||
:QGLWidget(parent)
|
||||
,m_xRotation(0)
|
||||
,m_yRotation(0)
|
||||
{
|
||||
}
|
||||
|
||||
void OpenGLWidget::setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PositionMaterialNormal>& surfaceMesh)
|
||||
{
|
||||
//Convienient access to the vertices and indices
|
||||
const vector<uint32_t>& vecIndices = surfaceMesh.getIndices();
|
||||
const vector<PositionMaterialNormal>& vecVertices = surfaceMesh.getVertices();
|
||||
|
||||
//Build an OpenGL index buffer
|
||||
glGenBuffers(1, &indexBuffer);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
const GLvoid* pIndices = static_cast<const GLvoid*>(&(vecIndices[0]));
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
|
||||
|
||||
//Build an OpenGL vertex buffer
|
||||
glGenBuffers(1, &vertexBuffer);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
|
||||
const GLvoid* pVertices = static_cast<const GLvoid*>(&(vecVertices[0]));
|
||||
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(PositionMaterialNormal), pVertices, GL_STATIC_DRAW);
|
||||
|
||||
m_uBeginIndex = 0;
|
||||
m_uEndIndex = vecIndices.size();
|
||||
}
|
||||
|
||||
void OpenGLWidget::initializeGL()
|
||||
{
|
||||
//We need GLEW to access recent OpenGL functionality
|
||||
std::cout << "Initialising GLEW...";
|
||||
GLenum result = glewInit();
|
||||
if (result == GLEW_OK)
|
||||
{
|
||||
std::cout << "success" << std::endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Problem: glewInit failed, something is seriously wrong. */
|
||||
std::cout << "failed" << std::endl;
|
||||
std::cout << "Initialising GLEW failed with the following error: " << glewGetErrorString(result) << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
//Print out some information about the OpenGL implementation.
|
||||
std::cout << "OpenGL Implementation Details:" << std::endl;
|
||||
if(glGetString(GL_VENDOR))
|
||||
std::cout << "\tGL_VENDOR: " << glGetString(GL_VENDOR) << std::endl;
|
||||
if(glGetString(GL_RENDERER))
|
||||
std::cout << "\tGL_RENDERER: " << glGetString(GL_RENDERER) << std::endl;
|
||||
if(glGetString(GL_VERSION))
|
||||
std::cout << "\tGL_VERSION: " << glGetString(GL_VERSION) << std::endl;
|
||||
if(glGetString(GL_SHADING_LANGUAGE_VERSION))
|
||||
std::cout << "\tGL_SHADING_LANGUAGE_VERSION: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
|
||||
|
||||
//Check our version of OpenGL is recent enough.
|
||||
//We need at least 1.5 for vertex buffer objects,
|
||||
if (!GLEW_VERSION_1_5)
|
||||
{
|
||||
std::cout << "Error: You need OpenGL version 1.5 to run this example." << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
//Set up the clear colour
|
||||
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
glClearDepth(1.0f);
|
||||
|
||||
//Enable the depth buffer
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glDepthFunc(GL_LEQUAL);
|
||||
|
||||
//Anable smooth lighting
|
||||
glEnable(GL_LIGHTING);
|
||||
glEnable(GL_LIGHT0);
|
||||
glShadeModel(GL_SMOOTH);
|
||||
|
||||
//We'll be rendering with index/vertex arrays
|
||||
glEnableClientState(GL_VERTEX_ARRAY);
|
||||
glEnableClientState(GL_NORMAL_ARRAY);
|
||||
}
|
||||
|
||||
void OpenGLWidget::resizeGL(int w, int h)
|
||||
{
|
||||
//Setup the viewport
|
||||
glViewport(0, 0, w, h);
|
||||
|
||||
//Set up the projection matrix
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glLoadIdentity();
|
||||
float frustumSize = 32.0f; //Half the volume size
|
||||
float aspect = static_cast<float>(width()) / static_cast<float>(height());
|
||||
glOrtho(frustumSize*aspect, -frustumSize*aspect, frustumSize, -frustumSize, 1.0, 1000);
|
||||
}
|
||||
|
||||
void OpenGLWidget::paintGL()
|
||||
{
|
||||
//Clear the screen
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
//Set up the viewing transformation
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glLoadIdentity();
|
||||
glTranslatef(0.0f,0.0f,-100.0f); //Centre volume and move back
|
||||
glRotatef(-m_xRotation, 0.0f, 1.0f, 0.0f);
|
||||
glRotatef(-m_yRotation, 1.0f, 0.0f, 0.0f);
|
||||
glTranslatef(-32.0f,-32.0f,-32.0f); //Centre volume and move back
|
||||
|
||||
//Bind the index buffer
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
|
||||
|
||||
//Bind the vertex buffer
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
|
||||
glVertexPointer(3, GL_FLOAT, sizeof(PositionMaterialNormal), 0);
|
||||
glNormalPointer(GL_FLOAT, sizeof(PositionMaterialNormal), (GLvoid*)12);
|
||||
|
||||
glDrawRangeElements(GL_TRIANGLES, m_uBeginIndex, m_uEndIndex-1, m_uEndIndex - m_uBeginIndex, GL_UNSIGNED_INT, 0);
|
||||
|
||||
GLenum errCode = glGetError();
|
||||
if(errCode != GL_NO_ERROR)
|
||||
{
|
||||
//What has replaced getErrorString() in the latest OpenGL?
|
||||
std::cout << "OpenGL Error: " << errCode << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
|
||||
{
|
||||
m_CurrentMousePos = event->pos();
|
||||
m_LastFrameMousePos = m_CurrentMousePos;
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
|
||||
{
|
||||
m_CurrentMousePos = event->pos();
|
||||
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
|
||||
m_xRotation += diff.x();
|
||||
m_yRotation += diff.y();
|
||||
m_LastFrameMousePos = m_CurrentMousePos;
|
||||
|
||||
update();
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#ifndef __BasicExample_OpenGLWidget_H__
|
||||
#define __BasicExample_OpenGLWidget_H__
|
||||
|
||||
#include "PolyVoxCore/SurfaceMesh.h"
|
||||
|
||||
#include "glew/glew.h"
|
||||
|
||||
#include <QGLWidget>
|
||||
|
||||
class OpenGLWidget : public QGLWidget
|
||||
{
|
||||
public:
|
||||
//Constructor
|
||||
OpenGLWidget(QWidget *parent);
|
||||
|
||||
//Mouse handling
|
||||
void mouseMoveEvent(QMouseEvent* event);
|
||||
void mousePressEvent(QMouseEvent* event);
|
||||
|
||||
//Convert a SrfaceMesh to OpenGL index/vertex buffers
|
||||
void setSurfaceMeshToRender(const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& surfaceMesh);
|
||||
|
||||
protected:
|
||||
//Qt OpenGL functions
|
||||
void initializeGL();
|
||||
void resizeGL(int w, int h);
|
||||
void paintGL();
|
||||
|
||||
private:
|
||||
//Index/vertex buffer data
|
||||
GLuint m_uBeginIndex;
|
||||
GLuint m_uEndIndex;
|
||||
GLuint noOfIndices;
|
||||
GLuint indexBuffer;
|
||||
GLuint vertexBuffer;
|
||||
|
||||
//Mouse data
|
||||
QPoint m_LastFrameMousePos;
|
||||
QPoint m_CurrentMousePos;
|
||||
int m_xRotation;
|
||||
int m_yRotation;
|
||||
};
|
||||
|
||||
#endif //__BasicExample_OpenGLWidget_H__
|
@ -1,98 +1,108 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "OpenGLWidget.h"
|
||||
|
||||
#include "PolyVoxCore/CubicSurfaceExtractorWithNormals.h"
|
||||
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
|
||||
#include "PolyVoxCore/SurfaceMesh.h"
|
||||
#include "PolyVoxCore/SimpleVolume.h"
|
||||
|
||||
#include <QApplication>
|
||||
|
||||
//Use the PolyVox namespace
|
||||
using namespace PolyVox;
|
||||
|
||||
void createSphereInVolume(SimpleVolume<uint8_t>& volData, float fRadius)
|
||||
{
|
||||
//This vector hold the position of the center of the volume
|
||||
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
|
||||
|
||||
//This three-level for loop iterates over every voxel in the volume
|
||||
for (int z = 0; z < volData.getDepth(); z++)
|
||||
{
|
||||
for (int y = 0; y < volData.getHeight(); y++)
|
||||
{
|
||||
for (int x = 0; x < volData.getWidth(); x++)
|
||||
{
|
||||
//Store our current position as a vector...
|
||||
Vector3DFloat v3dCurrentPos(x,y,z);
|
||||
//And compute how far the current position is from the center of the volume
|
||||
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
|
||||
|
||||
uint8_t uVoxelValue = 0;
|
||||
|
||||
//If the current voxel is less than 'radius' units from the center then we make it solid.
|
||||
if(fDistToCenter <= fRadius)
|
||||
{
|
||||
//Our new voxel value
|
||||
uVoxelValue = 255;
|
||||
}
|
||||
|
||||
//Wrte the voxel value into the volume
|
||||
volData.setVoxelAt(x, y, z, uVoxelValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
// Show logs
|
||||
setTraceStream(&(std::cout));
|
||||
|
||||
//Create and show the Qt OpenGL window
|
||||
QApplication app(argc, argv);
|
||||
OpenGLWidget openGLWidget(0);
|
||||
openGLWidget.show();
|
||||
|
||||
//Create an empty volume and then place a sphere in it
|
||||
SimpleVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(63, 63, 63)));
|
||||
createSphereInVolume(volData, 30);
|
||||
|
||||
//A mesh object to hold the result of surface extraction
|
||||
SurfaceMesh<PositionMaterialNormal> mesh;
|
||||
|
||||
//Create a surface extractor. Comment out one of the following two lines to decide which type gets created.
|
||||
CubicSurfaceExtractorWithNormals< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
|
||||
//MarchingCubesSurfaceExtractor< SimpleVolume<uint8_t> > surfaceExtractor(&volData, volData.getEnclosingRegion(), &mesh);
|
||||
|
||||
//Execute the surface extractor.
|
||||
surfaceExtractor.execute();
|
||||
|
||||
//Pass the surface to the OpenGL window
|
||||
openGLWidget.setSurfaceMeshToRender(mesh);
|
||||
|
||||
//Run the message pump.
|
||||
return app.exec();
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "PolyVoxExample.h"
|
||||
|
||||
#include "PolyVox/CubicSurfaceExtractor.h"
|
||||
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
|
||||
#include "PolyVox/Mesh.h"
|
||||
#include "PolyVox/PagedVolume.h"
|
||||
|
||||
#include <QApplication>
|
||||
|
||||
//Use the PolyVox namespace
|
||||
using namespace PolyVox;
|
||||
|
||||
void createSphereInVolume(PagedVolume<uint8_t>& volData, float fRadius)
|
||||
{
|
||||
//This vector hold the position of the center of the volume
|
||||
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
|
||||
|
||||
//This three-level for loop iterates over every voxel in the volume
|
||||
for (int z = 0; z < volData.getDepth(); z++)
|
||||
{
|
||||
for (int y = 0; y < volData.getHeight(); y++)
|
||||
{
|
||||
for (int x = 0; x < volData.getWidth(); x++)
|
||||
{
|
||||
//Store our current position as a vector...
|
||||
Vector3DFloat v3dCurrentPos(x,y,z);
|
||||
//And compute how far the current position is from the center of the volume
|
||||
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
|
||||
|
||||
uint8_t uVoxelValue = 0;
|
||||
|
||||
//If the current voxel is less than 'radius' units from the center then we make it solid.
|
||||
if(fDistToCenter <= fRadius)
|
||||
{
|
||||
//Our new voxel value
|
||||
uVoxelValue = 255;
|
||||
}
|
||||
|
||||
//Wrte the voxel value into the volume
|
||||
volData.setVoxelAt(x, y, z, uVoxelValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class BasicExample : public PolyVoxExample
|
||||
{
|
||||
public:
|
||||
BasicExample(QWidget *parent)
|
||||
:PolyVoxExample(parent)
|
||||
{
|
||||
}
|
||||
|
||||
protected:
|
||||
void initializeExample() override
|
||||
{
|
||||
// Create an empty volume and then place a sphere in it
|
||||
PagedVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(63, 63, 63)));
|
||||
createSphereInVolume(volData, 30);
|
||||
|
||||
// Extract the surface for the specified region of the volume. Uncomment the line for the kind of surface extraction you want to see.
|
||||
auto mesh = extractCubicMesh(&volData, volData.getEnclosingRegion());
|
||||
//auto mesh = extractMarchingCubesMesh(&volData, volData.getEnclosingRegion());
|
||||
|
||||
// The surface extractor outputs the mesh in an efficient compressed format which is not directly suitable for rendering. The easiest approach is to
|
||||
// decode this on the CPU as shown below, though more advanced applications can upload the compressed mesh to the GPU and decompress in shader code.
|
||||
auto decodedMesh = decodeMesh(mesh);
|
||||
|
||||
//Pass the surface to the OpenGL window
|
||||
addMesh(decodedMesh);
|
||||
|
||||
setCameraTransform(QVector3D(100.0f, 100.0f, 100.0f), -(PI / 4.0f), PI + (PI / 4.0f));
|
||||
}
|
||||
};
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
//Create and show the Qt OpenGL window
|
||||
QApplication app(argc, argv);
|
||||
BasicExample openGLWidget(0);
|
||||
openGLWidget.show();
|
||||
|
||||
//Run the message pump.
|
||||
return app.exec();
|
||||
}
|
7
examples/CMakeLists.txt
Normal file
7
examples/CMakeLists.txt
Normal file
@ -0,0 +1,7 @@
|
||||
ADD_SUBDIRECTORY(common)
|
||||
ADD_SUBDIRECTORY(Basic)
|
||||
ADD_SUBDIRECTORY(Paging)
|
||||
ADD_SUBDIRECTORY(OpenGL)
|
||||
ADD_SUBDIRECTORY(SmoothLOD)
|
||||
ADD_SUBDIRECTORY(DecodeOnGPU)
|
||||
ADD_SUBDIRECTORY(Python)
|
68
examples/DecodeOnGPU/CMakeLists.txt
Normal file
68
examples/DecodeOnGPU/CMakeLists.txt
Normal file
@ -0,0 +1,68 @@
|
||||
# Copyright (c) 2010-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
PROJECT(DecodeOnGPUExample)
|
||||
|
||||
#Projects source files
|
||||
SET(SRC_FILES
|
||||
main.cpp
|
||||
../common/PolyVoxExample.cpp
|
||||
)
|
||||
|
||||
#Projects headers files
|
||||
SET(INC_FILES
|
||||
../common/OpenGLWidget.h
|
||||
../common/OpenGLWidget.inl
|
||||
../common/PolyVoxExample.h
|
||||
)
|
||||
|
||||
#"Sources" and "Headers" are the group names in Visual Studio.
|
||||
#They may have other uses too...
|
||||
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
|
||||
SOURCE_GROUP("Headers" FILES ${INC_FILES})
|
||||
|
||||
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
|
||||
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ../common)
|
||||
|
||||
#This will include the shader files inside the compiled binary
|
||||
QT5_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
|
||||
QT5_ADD_RESOURCES(DECODE_RESOURCES_RCC decode.qrc)
|
||||
|
||||
# Put the resources in a seperate folder in Visual Studio
|
||||
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC} decode.qrc ${DECODE_RESOURCES_RCC})
|
||||
|
||||
#Build
|
||||
ADD_EXECUTABLE(DecodeOnGPUExample ${SRC_FILES} ${COMMON_RESOURCES_RCC} ${DECODE_RESOURCES_RCC})
|
||||
IF(MSVC)
|
||||
SET_TARGET_PROPERTIES(DecodeOnGPUExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
|
||||
ENDIF(MSVC)
|
||||
TARGET_LINK_LIBRARIES(DecodeOnGPUExample Qt5::OpenGL)
|
||||
SET_PROPERTY(TARGET DecodeOnGPUExample PROPERTY FOLDER "Examples")
|
||||
|
||||
#Install - Only install the example in Windows
|
||||
IF(WIN32)
|
||||
INSTALL(TARGETS DecodeOnGPUExample
|
||||
RUNTIME DESTINATION Examples/OpenGL/bin
|
||||
LIBRARY DESTINATION Examples/OpenGL/lib
|
||||
ARCHIVE DESTINATION Examples/OpenGL/lib
|
||||
COMPONENT example
|
||||
)
|
||||
ENDIF(WIN32)
|
19
examples/DecodeOnGPU/decode.frag
Normal file
19
examples/DecodeOnGPU/decode.frag
Normal file
@ -0,0 +1,19 @@
|
||||
#version 130
|
||||
|
||||
// Passed in from the vertex shader
|
||||
in vec4 worldPosition;
|
||||
in vec4 worldNormal;
|
||||
|
||||
// the color that gets written to the display
|
||||
out vec4 outputColor;
|
||||
|
||||
void main()
|
||||
{
|
||||
// Again, for the purposes of these examples we cannot be sure that per-vertex normals are provided. A sensible fallback
|
||||
// is to use this little trick to compute per-fragment flat-shaded normals from the world positions using derivative operations.
|
||||
//vec3 normal = normalize(cross(dFdy(worldPosition.xyz), dFdx(worldPosition.xyz)));
|
||||
|
||||
// We are just using the normal as the output color, and making it lighter so it looks a bit nicer.
|
||||
// Obviously a real shader would also do texuring, lighting, or whatever is required for the application.
|
||||
outputColor = vec4(abs(worldNormal.xyz) * 0.5 + vec3(0.5, 0.5, 0.5), 1.0);
|
||||
}
|
6
examples/DecodeOnGPU/decode.qrc
Normal file
6
examples/DecodeOnGPU/decode.qrc
Normal file
@ -0,0 +1,6 @@
|
||||
<!DOCTYPE RCC><RCC version="1.0">
|
||||
<qresource>
|
||||
<file>decode.vert</file>
|
||||
<file>decode.frag</file>
|
||||
</qresource>
|
||||
</RCC>
|
46
examples/DecodeOnGPU/decode.vert
Normal file
46
examples/DecodeOnGPU/decode.vert
Normal file
@ -0,0 +1,46 @@
|
||||
#version 140
|
||||
|
||||
in uvec4 position; // This will be the position of the vertex in model-space
|
||||
in uint normal;
|
||||
|
||||
// The usual matrices are provided
|
||||
uniform mat4 projectionMatrix;
|
||||
uniform mat4 viewMatrix;
|
||||
uniform mat4 modelMatrix;
|
||||
|
||||
// This will be used by the fragment shader to calculate flat-shaded normals. This is an unconventional approach
|
||||
// but we use it in this example framework because not all surface extractor generate surface normals.
|
||||
out vec4 worldPosition;
|
||||
out vec4 worldNormal;
|
||||
|
||||
// Returns +/- 1
|
||||
vec2 signNotZero(vec2 v)
|
||||
{
|
||||
return vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
vec4 decodedPosition = position;
|
||||
decodedPosition.xyz = decodedPosition.xyz * (1.0 / 256.0);
|
||||
|
||||
//Get the encoded bytes of the normal
|
||||
uint encodedX = (normal >> 8u) & 0xFFu;
|
||||
uint encodedY = (normal) & 0xFFu;
|
||||
|
||||
// Map to range [-1.0, +1.0]
|
||||
vec2 e = vec2(encodedX, encodedY);
|
||||
e = e * vec2(1.0 / 127.5, 1.0 / 127.5);
|
||||
e = e - vec2(1.0, 1.0);
|
||||
|
||||
// Now decode normal using listing 2 of http://jcgt.org/published/0003/02/01/
|
||||
vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));
|
||||
if (v.z < 0) v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy);
|
||||
worldNormal.xyz = normalize(v);
|
||||
worldNormal.w = 1.0;
|
||||
|
||||
// Standard sequence of OpenGL transformations.
|
||||
worldPosition = modelMatrix * decodedPosition;
|
||||
vec4 cameraPosition = viewMatrix * worldPosition;
|
||||
gl_Position = projectionMatrix * cameraPosition;
|
||||
}
|
181
examples/DecodeOnGPU/main.cpp
Normal file
181
examples/DecodeOnGPU/main.cpp
Normal file
@ -0,0 +1,181 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "PolyVoxExample.h"
|
||||
|
||||
#include "PolyVox/CubicSurfaceExtractor.h"
|
||||
#include "PolyVox/MarchingCubesSurfaceExtractor.h"
|
||||
#include "PolyVox/Mesh.h"
|
||||
#include "PolyVox/PagedVolume.h"
|
||||
|
||||
#include <QApplication>
|
||||
|
||||
//Use the PolyVox namespace
|
||||
using namespace PolyVox;
|
||||
|
||||
void createSphereInVolume(PagedVolume<uint8_t>& volData, float fRadius)
|
||||
{
|
||||
//This vector hold the position of the center of the volume
|
||||
Vector3DFloat v3dVolCenter(volData.getWidth() / 2, volData.getHeight() / 2, volData.getDepth() / 2);
|
||||
|
||||
//This three-level for loop iterates over every voxel in the volume
|
||||
for (int z = 0; z < volData.getDepth(); z++)
|
||||
{
|
||||
for (int y = 0; y < volData.getHeight(); y++)
|
||||
{
|
||||
for (int x = 0; x < volData.getWidth(); x++)
|
||||
{
|
||||
//Store our current position as a vector...
|
||||
Vector3DFloat v3dCurrentPos(x,y,z);
|
||||
//And compute how far the current position is from the center of the volume
|
||||
float fDistToCenter = (v3dCurrentPos - v3dVolCenter).length();
|
||||
|
||||
uint8_t uVoxelValue = 0;
|
||||
|
||||
//If the current voxel is less than 'radius' units from the center then we make it solid.
|
||||
if(fDistToCenter <= fRadius)
|
||||
{
|
||||
//Our new voxel value
|
||||
uVoxelValue = 255;
|
||||
}
|
||||
|
||||
//Wrte the voxel value into the volume
|
||||
volData.setVoxelAt(x, y, z, uVoxelValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DecodeOnGPUExample : public PolyVoxExample
|
||||
{
|
||||
public:
|
||||
DecodeOnGPUExample(QWidget *parent)
|
||||
:PolyVoxExample(parent)
|
||||
{
|
||||
}
|
||||
|
||||
protected:
|
||||
void initializeExample() override
|
||||
{
|
||||
QSharedPointer<QGLShaderProgram> shader(new QGLShaderProgram);
|
||||
|
||||
if (!shader->addShaderFromSourceFile(QGLShader::Vertex, ":/decode.vert"))
|
||||
{
|
||||
std::cerr << shader->log().toStdString() << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (!shader->addShaderFromSourceFile(QGLShader::Fragment, ":/decode.frag"))
|
||||
{
|
||||
std::cerr << shader->log().toStdString() << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
setShader(shader);
|
||||
|
||||
//Create an empty volume and then place a sphere in it
|
||||
PagedVolume<uint8_t> volData(PolyVox::Region(Vector3DInt32(0, 0, 0), Vector3DInt32(63, 63, 63)));
|
||||
createSphereInVolume(volData, 30);
|
||||
|
||||
// Extract the surface for the specified region of the volume. Uncomment the line for the kind of surface extraction you want to see.
|
||||
//auto mesh = extractCubicMesh(&volData, volData.getEnclosingRegion());
|
||||
auto mesh = extractMarchingCubesMesh(&volData, volData.getEnclosingRegion());
|
||||
|
||||
// The surface extractor outputs the mesh in an efficient compressed format which is not directly suitable for rendering. The easiest approach is to
|
||||
// decode this on the CPU as shown below, though more advanced applications can upload the compressed mesh to the GPU and decompress in shader code.
|
||||
//auto decodedMesh = decodeMesh(mesh);
|
||||
|
||||
//Pass the surface to the OpenGL window
|
||||
OpenGLMeshData meshData = buildOpenGLMeshData(mesh);
|
||||
addMeshData(meshData);
|
||||
|
||||
setCameraTransform(QVector3D(100.0f, 100.0f, 100.0f), -(PI / 4.0f), PI + (PI / 4.0f));
|
||||
}
|
||||
|
||||
private:
|
||||
OpenGLMeshData buildOpenGLMeshData(const PolyVox::Mesh< PolyVox::MarchingCubesVertex< uint8_t > >& surfaceMesh, const PolyVox::Vector3DInt32& translation = PolyVox::Vector3DInt32(0, 0, 0), float scale = 1.0f)
|
||||
{
|
||||
// Convienient access to the vertices and indices
|
||||
const auto& vecIndices = surfaceMesh.getIndices();
|
||||
const auto& vecVertices = surfaceMesh.getVertices();
|
||||
|
||||
// This struct holds the OpenGL properties (buffer handles, etc) which will be used
|
||||
// to render our mesh. We copy the data from the PolyVox mesh into this structure.
|
||||
OpenGLMeshData meshData;
|
||||
|
||||
// Create the VAO for the mesh
|
||||
glGenVertexArrays(1, &(meshData.vertexArrayObject));
|
||||
glBindVertexArray(meshData.vertexArrayObject);
|
||||
|
||||
// The GL_ARRAY_BUFFER will contain the list of vertex positions
|
||||
glGenBuffers(1, &(meshData.vertexBuffer));
|
||||
glBindBuffer(GL_ARRAY_BUFFER, meshData.vertexBuffer);
|
||||
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(MarchingCubesVertex< uint8_t >), vecVertices.data(), GL_STATIC_DRAW);
|
||||
|
||||
// and GL_ELEMENT_ARRAY_BUFFER will contain the indices
|
||||
glGenBuffers(1, &(meshData.indexBuffer));
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshData.indexBuffer);
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), vecIndices.data(), GL_STATIC_DRAW);
|
||||
|
||||
// Every surface extractor outputs valid positions for the vertices, so tell OpenGL how these are laid out
|
||||
glEnableVertexAttribArray(0); // Attrib '0' is the vertex positions
|
||||
glVertexAttribIPointer(0, 3, GL_UNSIGNED_SHORT, sizeof(MarchingCubesVertex< uint8_t >), (GLvoid*)(offsetof(MarchingCubesVertex< uint8_t >, encodedPosition))); //take the first 3 floats from every sizeof(decltype(vecVertices)::value_type)
|
||||
|
||||
// Some surface extractors also generate normals, so tell OpenGL how these are laid out. If a surface extractor
|
||||
// does not generate normals then nonsense values are written into the buffer here and sghould be ignored by the
|
||||
// shader. This is mostly just to simplify this example code - in a real application you will know whether your
|
||||
// chosen surface extractor generates normals and can skip uploading them if not.
|
||||
glEnableVertexAttribArray(1); // Attrib '1' is the vertex normals.
|
||||
glVertexAttribIPointer(1, 1, GL_UNSIGNED_SHORT, sizeof(MarchingCubesVertex< uint8_t >), (GLvoid*)(offsetof(MarchingCubesVertex< uint8_t >, encodedNormal)));
|
||||
|
||||
// Finally a surface extractor will probably output additional data. This is highly application dependant. For this example code
|
||||
// we're just uploading it as a set of bytes which we can read individually, but real code will want to do something specialised here.
|
||||
glEnableVertexAttribArray(2); //We're talking about shader attribute '2'
|
||||
GLint size = (std::min)(sizeof(uint8_t), size_t(4)); // Can't upload more that 4 components (vec4 is GLSL's biggest type)
|
||||
glVertexAttribIPointer(2, size, GL_UNSIGNED_BYTE, sizeof(MarchingCubesVertex< uint8_t >), (GLvoid*)(offsetof(MarchingCubesVertex< uint8_t >, data)));
|
||||
|
||||
// We're done uploading and can now unbind.
|
||||
glBindVertexArray(0);
|
||||
|
||||
// A few additional properties can be copied across for use during rendering.
|
||||
meshData.noOfIndices = vecIndices.size();
|
||||
meshData.translation = QVector3D(translation.getX(), translation.getY(), translation.getZ());
|
||||
meshData.scale = scale;
|
||||
|
||||
// Set 16 or 32-bit index buffer size.
|
||||
meshData.indexType = sizeof(PolyVox::Mesh< PolyVox::MarchingCubesVertex< uint8_t > >::IndexType) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
|
||||
|
||||
return meshData;
|
||||
}
|
||||
};
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
//Create and show the Qt OpenGL window
|
||||
QApplication app(argc, argv);
|
||||
DecodeOnGPUExample openGLWidget(0);
|
||||
openGLWidget.show();
|
||||
|
||||
//Run the message pump.
|
||||
return app.exec();
|
||||
}
|
@ -1,81 +1,85 @@
|
||||
# Copyright (c) 2010-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
|
||||
|
||||
PROJECT(OpenGLExample)
|
||||
|
||||
#Projects source files
|
||||
SET(SRC_FILES
|
||||
main.cpp
|
||||
OpenGLImmediateModeSupport.cpp
|
||||
OpenGLSupport.cpp
|
||||
OpenGLVertexBufferObjectSupport.cpp
|
||||
OpenGLWidget.cpp
|
||||
Shapes.cpp
|
||||
)
|
||||
|
||||
#Projects headers files
|
||||
SET(INC_FILES
|
||||
OpenGLImmediateModeSupport.h
|
||||
OpenGLSupport.h
|
||||
OpenGLVertexBufferObjectSupport.h
|
||||
OpenGLWidget.h
|
||||
Shapes.h
|
||||
)
|
||||
|
||||
add_definitions(-DGLEW_STATIC)
|
||||
|
||||
#"Sources" and "Headers" are the group names in Visual Studio.
|
||||
#They may have other uses too...
|
||||
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
|
||||
SOURCE_GROUP("Headers" FILES ${INC_FILES})
|
||||
|
||||
FIND_PACKAGE(OpenGL REQUIRED)
|
||||
|
||||
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
|
||||
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxCore_BINARY_DIR}/include ${PolyVoxCore_SOURCE_DIR}/include ${GLEW_SOURCE_DIR})
|
||||
LINK_DIRECTORIES(${PolyVoxCore_BINARY_DIR})
|
||||
|
||||
#Build
|
||||
ADD_EXECUTABLE(OpenGLExample ${SRC_FILES})
|
||||
IF(MSVC)
|
||||
SET_TARGET_PROPERTIES(OpenGLExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
|
||||
ENDIF(MSVC)
|
||||
TARGET_LINK_LIBRARIES(OpenGLExample glew ${QT_LIBRARIES} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} PolyVoxCore)
|
||||
SET_PROPERTY(TARGET OpenGLExample PROPERTY FOLDER "Examples")
|
||||
|
||||
#Install - Only install the example in Windows
|
||||
IF(WIN32)
|
||||
INSTALL(TARGETS OpenGLExample
|
||||
RUNTIME DESTINATION Examples/OpenGL/bin
|
||||
LIBRARY DESTINATION Examples/OpenGL/lib
|
||||
ARCHIVE DESTINATION Examples/OpenGL/lib
|
||||
COMPONENT example
|
||||
)
|
||||
|
||||
#.dlls should be installed in shared builds.
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
ENDIF(WIN32)
|
||||
# Copyright (c) 2010-2012 David Williams
|
||||
#
|
||||
# This software is provided 'as-is', without any express or implied
|
||||
# warranty. In no event will the authors be held liable for any damages
|
||||
# arising from the use of this software.
|
||||
#
|
||||
# Permission is granted to anyone to use this software for any purpose,
|
||||
# including commercial applications, and to alter it and redistribute it
|
||||
# freely, subject to the following restrictions:
|
||||
#
|
||||
# 1. The origin of this software must not be misrepresented; you must not
|
||||
# claim that you wrote the original software. If you use this software
|
||||
# in a product, an acknowledgment in the product documentation would be
|
||||
# appreciated but is not required.
|
||||
#
|
||||
# 2. Altered source versions must be plainly marked as such, and must not be
|
||||
# misrepresented as being the original software.
|
||||
#
|
||||
# 3. This notice may not be removed or altered from any source
|
||||
# distribution.
|
||||
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
|
||||
|
||||
PROJECT(OpenGLExample)
|
||||
|
||||
#Projects source files
|
||||
SET(SRC_FILES
|
||||
main.cpp
|
||||
#OpenGLImmediateModeSupport.cpp
|
||||
#OpenGLSupport.cpp
|
||||
#OpenGLVertexBufferObjectSupport.cpp
|
||||
../common/PolyVoxExample.cpp
|
||||
Shapes.cpp
|
||||
)
|
||||
|
||||
#Projects headers files
|
||||
SET(INC_FILES
|
||||
#OpenGLImmediateModeSupport.h
|
||||
#OpenGLSupport.h
|
||||
#OpenGLVertexBufferObjectSupport.h
|
||||
../common/OpenGLWidget.h
|
||||
../common/OpenGLWidget.inl
|
||||
../common/PolyVoxExample.h
|
||||
Shapes.h
|
||||
)
|
||||
|
||||
#"Sources" and "Headers" are the group names in Visual Studio.
|
||||
#They may have other uses too...
|
||||
SOURCE_GROUP("Sources" FILES ${SRC_FILES})
|
||||
SOURCE_GROUP("Headers" FILES ${INC_FILES})
|
||||
|
||||
#Tell CMake the paths for OpenGL and for PolyVox (which is just relative to our current location)
|
||||
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR} ${PolyVoxHeaders_SOURCE_DIR} ../common)
|
||||
|
||||
#This will include the shader files inside the compiled binary
|
||||
QT5_ADD_RESOURCES(COMMON_RESOURCES_RCC ../common/example.qrc)
|
||||
QT5_ADD_RESOURCES(OPENGL_EXAMPLE_RESOURCES_RCC openglexample.qrc)
|
||||
|
||||
# Put the resources in a seperate folder in Visual Studio
|
||||
SOURCE_GROUP("Resource Files" FILES ../common/example.qrc ${COMMON_RESOURCES_RCC})
|
||||
|
||||
#Build
|
||||
ADD_EXECUTABLE(OpenGLExample ${SRC_FILES} ${COMMON_RESOURCES_RCC} ${OPENGL_EXAMPLE_RESOURCES_RCC})
|
||||
IF(MSVC)
|
||||
SET_TARGET_PROPERTIES(OpenGLExample PROPERTIES COMPILE_FLAGS "/W4 /wd4127")
|
||||
ENDIF(MSVC)
|
||||
TARGET_LINK_LIBRARIES(OpenGLExample Qt5::OpenGL)
|
||||
SET_PROPERTY(TARGET OpenGLExample PROPERTY FOLDER "Examples")
|
||||
|
||||
#Install - Only install the example in Windows
|
||||
IF(WIN32)
|
||||
INSTALL(TARGETS OpenGLExample
|
||||
RUNTIME DESTINATION Examples/OpenGL/bin
|
||||
LIBRARY DESTINATION Examples/OpenGL/lib
|
||||
ARCHIVE DESTINATION Examples/OpenGL/lib
|
||||
COMPONENT example
|
||||
)
|
||||
|
||||
#.dlls should be installed in shared builds.
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../release/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Release)
|
||||
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxCore.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
#INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/../../debug/PolyVoxUtil.dll DESTINATION Examples/OpenGL/bin CONFIGURATIONS Debug)
|
||||
ENDIF(WIN32)
|
||||
|
@ -1,63 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "OpenGLImmediateModeSupport.h"
|
||||
#include "OpenGLSupport.h"
|
||||
|
||||
#include "PolyVoxCore/SurfaceMesh.h"
|
||||
|
||||
using namespace PolyVox;
|
||||
using namespace std;
|
||||
|
||||
void renderRegionImmediateMode(PolyVox::SurfaceMesh<PositionMaterialNormal>& mesh, unsigned int uLodLevel)
|
||||
{
|
||||
const vector<PositionMaterialNormal>& vecVertices = mesh.getVertices();
|
||||
const vector<uint32_t>& vecIndices = mesh.getIndices();
|
||||
|
||||
int beginIndex = mesh.m_vecLodRecords[uLodLevel].beginIndex;
|
||||
int endIndex = mesh.m_vecLodRecords[uLodLevel].endIndex;
|
||||
|
||||
glBegin(GL_TRIANGLES);
|
||||
//for(vector<PolyVox::uint32_t>::const_iterator iterIndex = vecIndices.begin(); iterIndex != vecIndices.end(); ++iterIndex)
|
||||
for(int index = beginIndex; index < endIndex; ++index)
|
||||
{
|
||||
const PositionMaterialNormal& vertex = vecVertices[vecIndices[index]];
|
||||
const Vector3DFloat& v3dVertexPos = vertex.getPosition();
|
||||
//const Vector3DFloat v3dRegionOffset(uRegionX * g_uRegionSideLength, uRegionY * g_uRegionSideLength, uRegionZ * g_uRegionSideLength);
|
||||
const Vector3DFloat v3dFinalVertexPos = v3dVertexPos + static_cast<Vector3DFloat>(mesh.m_Region.getLowerCorner());
|
||||
|
||||
|
||||
|
||||
|
||||
uint8_t material = static_cast<uint8_t>(vertex.getMaterial() + 0.5);
|
||||
|
||||
OpenGLColour colour = convertMaterialIDToColour(material);
|
||||
|
||||
glColor3f(colour.red, colour.green, colour.blue);
|
||||
glNormal3f(vertex.getNormal().getX(), vertex.getNormal().getY(), vertex.getNormal().getZ());
|
||||
glVertex3f(v3dFinalVertexPos.getX(), v3dFinalVertexPos.getY(), v3dFinalVertexPos.getZ());
|
||||
|
||||
|
||||
}
|
||||
glEnd();
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#ifndef __OpenGLExample_OpenGLImmediateModeSupport_H__
|
||||
#define __OpenGLExample_OpenGLImmediateModeSupport_H__
|
||||
|
||||
#include "PolyVoxCore/PolyVoxForwardDeclarations.h"
|
||||
|
||||
#include "glew/glew.h"
|
||||
|
||||
void renderRegionImmediateMode(PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& mesh, unsigned int uLodLevel);
|
||||
|
||||
#endif //__OpenGLExample_OpenGLImmediateModeSupport_H__
|
@ -1,66 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "OpenGLSupport.h"
|
||||
|
||||
using namespace PolyVox;
|
||||
|
||||
OpenGLColour convertMaterialIDToColour(uint8_t materialID)
|
||||
{
|
||||
OpenGLColour colour;
|
||||
|
||||
switch(materialID)
|
||||
{
|
||||
case 1:
|
||||
colour.red = 1.0f;
|
||||
colour.green = 0.0f;
|
||||
colour.blue = 0.0f;
|
||||
break;
|
||||
case 2:
|
||||
colour.red = 0.0f;
|
||||
colour.green = 1.0f;
|
||||
colour.blue = 0.0f;
|
||||
break;
|
||||
case 3:
|
||||
colour.red = 0.0f;
|
||||
colour.green = 0.0f;
|
||||
colour.blue = 1.0f;
|
||||
break;
|
||||
case 4:
|
||||
colour.red = 1.0f;
|
||||
colour.green = 1.0f;
|
||||
colour.blue = 0.0f;
|
||||
break;
|
||||
case 5:
|
||||
colour.red = 1.0f;
|
||||
colour.green = 0.0f;
|
||||
colour.blue = 1.0f;
|
||||
break;
|
||||
default:
|
||||
colour.red = 1.0f;
|
||||
colour.green = 1.0f;
|
||||
colour.blue = 1.0f;
|
||||
}
|
||||
|
||||
return colour;
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#ifndef __OpenGLExample_OpenGLSupport_H__
|
||||
#define __OpenGLExample_OpenGLSupport_H__
|
||||
|
||||
#include "PolyVoxCore/PolyVoxForwardDeclarations.h"
|
||||
|
||||
#include "glew/glew.h"
|
||||
|
||||
struct OpenGLColour
|
||||
{
|
||||
GLfloat red;
|
||||
GLfloat green;
|
||||
GLfloat blue;
|
||||
};
|
||||
|
||||
OpenGLColour convertMaterialIDToColour(uint8_t materialID);
|
||||
|
||||
#endif //__OpenGLExample_OpenGLSupport_H__
|
@ -1,124 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "OpenGLSupport.h"
|
||||
#include "OpenGLVertexBufferObjectSupport.h"
|
||||
|
||||
#include "PolyVoxCore/SurfaceMesh.h"
|
||||
|
||||
using namespace PolyVox;
|
||||
using namespace std;
|
||||
|
||||
OpenGLSurfaceMesh BuildOpenGLSurfaceMesh(const SurfaceMesh<PositionMaterialNormal>& mesh)
|
||||
{
|
||||
//Represents our filled in OpenGL vertex and index buffer objects.
|
||||
OpenGLSurfaceMesh result;
|
||||
|
||||
//The source
|
||||
result.sourceMesh = &mesh;
|
||||
|
||||
//Convienient access to the vertices and indices
|
||||
const vector<PositionMaterialNormal>& vecVertices = mesh.getVertices();
|
||||
const vector<uint32_t>& vecIndices = mesh.getIndices();
|
||||
|
||||
//If we have any indices...
|
||||
if(!vecIndices.empty())
|
||||
{
|
||||
//Create an OpenGL index buffer
|
||||
glGenBuffers(1, &result.indexBuffer);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, result.indexBuffer);
|
||||
|
||||
//Get a pointer to the first index
|
||||
GLvoid* pIndices = (GLvoid*)(&(vecIndices[0]));
|
||||
|
||||
//Fill the OpenGL index buffer with our data.
|
||||
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vecIndices.size() * sizeof(uint32_t), pIndices, GL_STATIC_DRAW);
|
||||
}
|
||||
|
||||
result.noOfIndices = vecIndices.size();
|
||||
|
||||
glGenBuffers(1, &result.vertexBuffer);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, result.vertexBuffer);
|
||||
glBufferData(GL_ARRAY_BUFFER, vecVertices.size() * sizeof(GLfloat) * 9, 0, GL_STATIC_DRAW);
|
||||
GLfloat* ptr = (GLfloat*)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);
|
||||
|
||||
for(vector<PositionMaterialNormal>::const_iterator iterVertex = vecVertices.begin(); iterVertex != vecVertices.end(); ++iterVertex)
|
||||
{
|
||||
const PositionMaterialNormal& vertex = *iterVertex;
|
||||
const Vector3DFloat& v3dVertexPos = vertex.getPosition();
|
||||
//const Vector3DFloat v3dRegionOffset(uRegionX * g_uRegionSideLength, uRegionY * g_uRegionSideLength, uRegionZ * g_uRegionSideLength);
|
||||
const Vector3DFloat v3dFinalVertexPos = v3dVertexPos + static_cast<Vector3DFloat>(mesh.m_Region.getLowerCorner());
|
||||
|
||||
*ptr = v3dFinalVertexPos.getX();
|
||||
ptr++;
|
||||
*ptr = v3dFinalVertexPos.getY();
|
||||
ptr++;
|
||||
*ptr = v3dFinalVertexPos.getZ();
|
||||
ptr++;
|
||||
|
||||
*ptr = vertex.getNormal().getX();
|
||||
ptr++;
|
||||
*ptr = vertex.getNormal().getY();
|
||||
ptr++;
|
||||
*ptr = vertex.getNormal().getZ();
|
||||
ptr++;
|
||||
|
||||
uint8_t material = static_cast<uint8_t>(vertex.getMaterial() + 0.5);
|
||||
|
||||
OpenGLColour colour = convertMaterialIDToColour(material);
|
||||
|
||||
*ptr = colour.red;
|
||||
ptr++;
|
||||
*ptr = colour.green;
|
||||
ptr++;
|
||||
*ptr = colour.blue;
|
||||
ptr++;
|
||||
}
|
||||
|
||||
glUnmapBuffer(GL_ARRAY_BUFFER);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void renderRegionVertexBufferObject(const OpenGLSurfaceMesh& openGLSurfaceMesh, unsigned int uLodLevel)
|
||||
{
|
||||
int beginIndex = openGLSurfaceMesh.sourceMesh->m_vecLodRecords[uLodLevel].beginIndex;
|
||||
int endIndex = openGLSurfaceMesh.sourceMesh->m_vecLodRecords[uLodLevel].endIndex;
|
||||
glBindBuffer(GL_ARRAY_BUFFER, openGLSurfaceMesh.vertexBuffer);
|
||||
glVertexPointer(3, GL_FLOAT, 36, 0);
|
||||
glNormalPointer(GL_FLOAT, 36, (GLvoid*)12);
|
||||
glColorPointer(3, GL_FLOAT, 36, (GLvoid*)24);
|
||||
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, openGLSurfaceMesh.indexBuffer);
|
||||
|
||||
glEnableClientState(GL_VERTEX_ARRAY);
|
||||
glEnableClientState(GL_NORMAL_ARRAY);
|
||||
glEnableClientState(GL_COLOR_ARRAY);
|
||||
|
||||
//glDrawElements(GL_TRIANGLES, openGLSurfaceMesh.noOfIndices, GL_UNSIGNED_INT, 0);
|
||||
glDrawRangeElements(GL_TRIANGLES, beginIndex, endIndex-1, endIndex - beginIndex,/* openGLSurfaceMesh.noOfIndices,*/ GL_UNSIGNED_INT, 0);
|
||||
|
||||
glDisableClientState(GL_COLOR_ARRAY);
|
||||
glDisableClientState(GL_NORMAL_ARRAY);
|
||||
glDisableClientState(GL_VERTEX_ARRAY);
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#ifndef __OpenGLExample_OpenGLVertexBufferObjectSupport_H__
|
||||
#define __OpenGLExample_OpenGLVertexBufferObjectSupport_H__
|
||||
|
||||
#include "PolyVoxCore/PolyVoxForwardDeclarations.h"
|
||||
|
||||
#include "glew/glew.h"
|
||||
|
||||
struct OpenGLSurfaceMesh
|
||||
{
|
||||
GLulong noOfIndices;
|
||||
GLuint indexBuffer;
|
||||
GLuint vertexBuffer;
|
||||
const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>* sourceMesh;
|
||||
};
|
||||
|
||||
OpenGLSurfaceMesh BuildOpenGLSurfaceMesh(const PolyVox::SurfaceMesh<PolyVox::PositionMaterialNormal>& mesh);
|
||||
void renderRegionVertexBufferObject(const OpenGLSurfaceMesh& openGLSurfaceMesh, unsigned int uLodLevel);
|
||||
|
||||
#endif //__OpenGLExample_OpenGLVertexBufferObjectSupport_H__
|
@ -1,246 +0,0 @@
|
||||
/*******************************************************************************
|
||||
Copyright (c) 2005-2009 David Williams
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
*******************************************************************************/
|
||||
|
||||
#include "OpenGLWidget.h"
|
||||
|
||||
#include <QMouseEvent>
|
||||
|
||||
#include "PolyVoxCore/GradientEstimators.h"
|
||||
#include "PolyVoxCore/MaterialDensityPair.h"
|
||||
#include "PolyVoxCore/MarchingCubesSurfaceExtractor.h"
|
||||
|
||||
//Some namespaces we need
|
||||
using namespace std;
|
||||
using namespace PolyVox;
|
||||
using namespace std;
|
||||
|
||||
OpenGLWidget::OpenGLWidget(QWidget *parent)
|
||||
:QGLWidget(parent)
|
||||
,m_volData(0)
|
||||
{
|
||||
m_xRotation = 0;
|
||||
m_yRotation = 0;
|
||||
m_uRegionSideLength = 32;
|
||||
|
||||
timer = new QTimer(this);
|
||||
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
|
||||
timer->start(0);
|
||||
}
|
||||
|
||||
void OpenGLWidget::setVolume(PolyVox::LargeVolume<MaterialDensityPair44>* volData)
|
||||
{
|
||||
//First we free anything from the previous volume (if there was one).
|
||||
m_mapOpenGLSurfaceMeshes.clear();
|
||||
m_mapSurfaceMeshes.clear();
|
||||
m_volData = volData;
|
||||
|
||||
//If we have any volume data then generate the new surface patches.
|
||||
if(m_volData != 0)
|
||||
{
|
||||
m_uVolumeWidthInRegions = volData->getWidth() / m_uRegionSideLength;
|
||||
m_uVolumeHeightInRegions = volData->getHeight() / m_uRegionSideLength;
|
||||
m_uVolumeDepthInRegions = volData->getDepth() / m_uRegionSideLength;
|
||||
|
||||
//Our volume is broken down into cuboid regions, and we create one mesh for each region.
|
||||
//This three-level for loop iterates over each region.
|
||||
for(uint16_t uRegionZ = 0; uRegionZ < m_uVolumeDepthInRegions; ++uRegionZ)
|
||||
{
|
||||
std::cout << "uRegionZ = " << uRegionZ << " of " << m_uVolumeDepthInRegions << std::endl;
|
||||
for(uint16_t uRegionY = 0; uRegionY < m_uVolumeHeightInRegions; ++uRegionY)
|
||||
{
|
||||
for(uint16_t uRegionX = 0; uRegionX < m_uVolumeWidthInRegions; ++uRegionX)
|
||||
{
|
||||
//Compute the extents of the current region
|
||||
//FIXME - This is a little complex? PolyVox could
|
||||
//provide more functions for dealing with regions?
|
||||
int32_t regionStartX = uRegionX * m_uRegionSideLength;
|
||||
int32_t regionStartY = uRegionY * m_uRegionSideLength;
|
||||
int32_t regionStartZ = uRegionZ * m_uRegionSideLength;
|
||||
|
||||
int32_t regionEndX = regionStartX + m_uRegionSideLength;
|
||||
int32_t regionEndY = regionStartY + m_uRegionSideLength;
|
||||
int32_t regionEndZ = regionStartZ + m_uRegionSideLength;
|
||||
|
||||
Vector3DInt32 regLowerCorner(regionStartX, regionStartY, regionStartZ);
|
||||
Vector3DInt32 regUpperCorner(regionEndX, regionEndY, regionEndZ);
|
||||
|
||||
//Extract the surface for this region
|
||||
//extractSurface(m_volData, 0, PolyVox::Region(regLowerCorner, regUpperCorner), meshCurrent);
|
||||
|
||||
polyvox_shared_ptr< SurfaceMesh<PositionMaterialNormal> > mesh(new SurfaceMesh<PositionMaterialNormal>);
|
||||
MarchingCubesSurfaceExtractor< LargeVolume<MaterialDensityPair44> > surfaceExtractor(volData, PolyVox::Region(regLowerCorner, regUpperCorner), mesh.get());
|
||||
surfaceExtractor.execute();
|
||||
|
||||
//decimatedMesh->generateAveragedFaceNormals(true);
|
||||
|
||||
//computeNormalsForVertices(m_volData, *(decimatedMesh.get()), SOBEL_SMOOTHED);
|
||||
//*meshCurrent = getSmoothedSurface(*meshCurrent);
|
||||
//mesh->smooth(0.3f);
|
||||
//meshCurrent->generateAveragedFaceNormals(true);
|
||||
|
||||
if(mesh->m_vecTriangleIndices.size() > 0)
|
||||
{
|
||||
|
||||
|
||||
Vector3DUint8 v3dRegPos(uRegionX,uRegionY,uRegionZ);
|
||||
if(m_bUseOpenGLVertexBufferObjects)
|
||||
{
|
||||
OpenGLSurfaceMesh openGLSurfaceMesh = BuildOpenGLSurfaceMesh(*(mesh.get()));
|
||||
m_mapOpenGLSurfaceMeshes.insert(make_pair(v3dRegPos, openGLSurfaceMesh));
|
||||
}
|
||||
//else
|
||||
//{
|
||||
m_mapSurfaceMeshes.insert(make_pair(v3dRegPos, mesh));
|
||||
//}
|
||||
//delete meshCurrent;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Projection matrix is dependant on volume size, so we need to set it up again.
|
||||
setupProjectionMatrix();
|
||||
}
|
||||
}
|
||||
|
||||
void OpenGLWidget::initializeGL()
|
||||
{
|
||||
m_bUseOpenGLVertexBufferObjects = true;
|
||||
if(m_bUseOpenGLVertexBufferObjects)
|
||||
{
|
||||
//We need GLEW to access recent OpenGL functionality
|
||||
GLenum err = glewInit();
|
||||
if (GLEW_OK != err)
|
||||
{
|
||||
/* Problem: glewInit failed, something is seriously wrong. */
|
||||
cout << "GLEW Error: " << glewGetErrorString(err) << endl;
|
||||
}
|
||||
}
|
||||
|
||||
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
|
||||
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
|
||||
glClearDepth(1.0f); // Depth Buffer Setup
|
||||
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
|
||||
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
|
||||
glEnable ( GL_COLOR_MATERIAL );
|
||||
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
|
||||
|
||||
glEnable(GL_LIGHTING);
|
||||
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
|
||||
glEnable(GL_LIGHT0);
|
||||
|
||||
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
|
||||
|
||||
glShadeModel(GL_SMOOTH);
|
||||
}
|
||||
|
||||
void OpenGLWidget::resizeGL(int w, int h)
|
||||
{
|
||||
//Setup the viewport based on the window size
|
||||
glViewport(0, 0, w, h);
|
||||
|
||||
//Projection matrix is also dependant on the size of the current volume.
|
||||
if(m_volData)
|
||||
{
|
||||
setupProjectionMatrix();
|
||||
}
|
||||
}
|
||||
|
||||
void OpenGLWidget::paintGL()
|
||||
{
|
||||
if(m_volData)
|
||||
{
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
|
||||
|
||||
glMatrixMode(GL_MODELVIEW); // Select The Model View Matrix
|
||||
glLoadIdentity(); // Reset The Current Modelview Matrix
|
||||
|
||||
//Moves the camera back so we can see the volume
|
||||
glTranslatef(0.0f, 0.0f, -m_volData->getDiagonalLength());
|
||||
|
||||
glRotatef(m_xRotation, 1.0f, 0.0f, 0.0f);
|
||||
glRotatef(m_yRotation, 0.0f, 1.0f, 0.0f);
|
||||
|
||||
//Centre the volume on the origin
|
||||
glTranslatef(-g_uVolumeSideLength/2,-g_uVolumeSideLength/2,-g_uVolumeSideLength/2);
|
||||
|
||||
for(uint16_t uRegionZ = 0; uRegionZ < m_uVolumeDepthInRegions; ++uRegionZ)
|
||||
{
|
||||
for(uint16_t uRegionY = 0; uRegionY < m_uVolumeHeightInRegions; ++uRegionY)
|
||||
{
|
||||
for(uint16_t uRegionX = 0; uRegionX < m_uVolumeWidthInRegions; ++uRegionX)
|
||||
{
|
||||
Vector3DUint8 v3dRegPos(uRegionX,uRegionY,uRegionZ);
|
||||
if(m_mapSurfaceMeshes.find(v3dRegPos) != m_mapSurfaceMeshes.end())
|
||||
{
|
||||
polyvox_shared_ptr< SurfaceMesh<PositionMaterialNormal> > meshCurrent = m_mapSurfaceMeshes[v3dRegPos];
|
||||
unsigned int uLodLevel = 0; //meshCurrent->m_vecLodRecords.size() - 1;
|
||||
if(m_bUseOpenGLVertexBufferObjects)
|
||||
{
|
||||
renderRegionVertexBufferObject(m_mapOpenGLSurfaceMeshes[v3dRegPos], uLodLevel);
|
||||
}
|
||||
else
|
||||
{
|
||||
renderRegionImmediateMode(*meshCurrent, uLodLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GLenum errCode;
|
||||
const GLubyte *errString;
|
||||
|
||||
if ((errCode = glGetError()) != GL_NO_ERROR)
|
||||
{
|
||||
errString = gluErrorString(errCode);
|
||||
cout << "OpenGL Error: " << errString << endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void OpenGLWidget::mousePressEvent(QMouseEvent* event)
|
||||
{
|
||||
m_CurrentMousePos = event->pos();
|
||||
m_LastFrameMousePos = m_CurrentMousePos;
|
||||
}
|
||||
|
||||
void OpenGLWidget::mouseMoveEvent(QMouseEvent* event)
|
||||
{
|
||||
m_CurrentMousePos = event->pos();
|
||||
QPoint diff = m_CurrentMousePos - m_LastFrameMousePos;
|
||||
m_xRotation += diff.x();
|
||||
m_yRotation += diff.y();
|
||||
m_LastFrameMousePos = m_CurrentMousePos;;
|
||||
}
|
||||
|
||||
void OpenGLWidget::setupProjectionMatrix(void)
|
||||
{
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glLoadIdentity();
|
||||
|
||||
float frustumSize = m_volData->getDiagonalLength() / 2.0f;
|
||||
float aspect = static_cast<float>(width()) / static_cast<float>(height());
|
||||
|
||||
glOrtho(frustumSize*aspect, -frustumSize*aspect, frustumSize, -frustumSize, 1.0, 5000);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user