Merge current github/dev into pull request 760

This commit is contained in:
Dave Clyde 2016-07-16 20:52:54 -07:00
commit 61d0c66531
156 changed files with 2395 additions and 1083 deletions

View File

@ -26,14 +26,17 @@ project(OpenSubdiv)
cmake_minimum_required(VERSION 2.8.6) cmake_minimum_required(VERSION 2.8.6)
# Turn on folder support
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# Obtain OpenSubdiv API version from version.h file # Obtain OpenSubdiv API version from version.h file
if(EXISTS "${CMAKE_SOURCE_DIR}/opensubdiv/version.h") if(EXISTS "${OpenSubdiv_SOURCE_DIR}/opensubdiv/version.h")
file(STRINGS "${CMAKE_SOURCE_DIR}/opensubdiv/version.h" file(STRINGS "${OpenSubdiv_SOURCE_DIR}/opensubdiv/version.h"
OpenSubdiv_VERSION REGEX "^#define OPENSUBDIV_VERSION .*$") OpenSubdiv_VERSION REGEX "^#define OPENSUBDIV_VERSION .*$")
string(REPLACE "#define OPENSUBDIV_VERSION " "" OpenSubdiv_VERSION ${OpenSubdiv_VERSION}) string(REPLACE "#define OPENSUBDIV_VERSION " "" OpenSubdiv_VERSION ${OpenSubdiv_VERSION})
else() else()
message(FATAL_ERROR, "Cannot locate opensubdiv/version.h in CMAKE_SOURCE_DIR") message(FATAL_ERROR, "Cannot locate opensubdiv/version.h in ${OpenSubdiv_SOURCE_DIR}")
endif() endif()
# Evaluate 'soname' from OSD version # Evaluate 'soname' from OSD version
@ -204,37 +207,6 @@ elseif(MSVC)
# Turn on all warnings # Turn on all warnings
list(APPEND OSD_COMPILER_FLAGS /Wall) list(APPEND OSD_COMPILER_FLAGS /Wall)
# MSVC is unfortunately not standard conforming with regards to
# the alternative names for logical and bitwise operators:
# http://stackoverflow.com/questions/555505/c-alternative-tokens
# http://stackoverflow.com/questions/6006526/c-writing-or-instead-of
#
# This can be solved by including iso646.h, but that is a rather
# unsatisfactory solution since we then always have to remember to
# include this header file. Instead we define these operators
# ourselves as command line arguments to cl.exe.
#
# An alternative would be to compile with the /Za option
# (but unfortunately that breaks other code):
# http://msdn.microsoft.com/en-us/library/0k0w269d.aspx
list(APPEND OSD_COMPILER_FLAGS
/Dand=&&
/Dand_eq=&=
/Dbitand=&
/Dbitor=|
/Dcompl=~
/Dnot=!
/Dnot_eq=!=
/Dor=||
/Dor_eq=|=
# nvcc does not seem to like a caret being the last character
# in a command line defined preprocessor symbol, so add an
# empty trailing comment to avoid this.
/Dxor=^/**/
/Dxor_eq=^=
)
list(APPEND OSD_COMPILER_FLAGS list(APPEND OSD_COMPILER_FLAGS
/W3 # Use warning level recommended for production purposes. /W3 # Use warning level recommended for production purposes.
/WX # Treat all compiler warnings as errors. /WX # Treat all compiler warnings as errors.
@ -345,6 +317,7 @@ if(NOT NO_OPENGL AND NOT ANDROID AND NOT IOS)
endif() endif()
if(NOT NO_PTEX) if(NOT NO_PTEX)
find_package(PTex 2.0) find_package(PTex 2.0)
find_package(Zlib 1.2)
endif() endif()
if (OPENGL_FOUND AND NOT IOS) if (OPENGL_FOUND AND NOT IOS)
add_definitions( add_definitions(
@ -520,6 +493,7 @@ endif()
if(PTEX_FOUND) if(PTEX_FOUND)
add_definitions( add_definitions(
-DOPENSUBDIV_HAS_PTEX -DOPENSUBDIV_HAS_PTEX
-DPTEX_STATIC
) )
else() else()
if(NOT NO_PTEX) if(NOT NO_PTEX)
@ -593,20 +567,18 @@ endif()
# Macro for processing public headers into the build area for doxygen processing # Macro for processing public headers into the build area for doxygen processing
#set_property(GLOBAL PROPERTY USE_FOLDERS ON)
add_custom_target( public_headers ) add_custom_target( public_headers )
macro(_add_doxy_headers headers) macro(_add_doxy_headers headers)
if (NOT NO_DOC AND DOXYGEN_FOUND) if (NOT NO_DOC AND DOXYGEN_FOUND)
file(RELATIVE_PATH path "${CMAKE_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}" ) file(RELATIVE_PATH path "${OpenSubdiv_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}" )
string(REPLACE "/" "_" targetpath ${path}) string(REPLACE "/" "_" targetpath ${path})
foreach (header ${headers}) foreach (header ${headers})
set(infile "${CMAKE_CURRENT_SOURCE_DIR}/${header}") set(infile "${CMAKE_CURRENT_SOURCE_DIR}/${header}")
set(outfile "${CMAKE_BINARY_DIR}/public_headers/${path}/${header}") set(outfile "${OpenSubdiv_BINARY_DIR}/public_headers/${path}/${header}")
set(targetname "${targetpath}_${header}") set(targetname "${targetpath}_${header}")
add_custom_command( add_custom_command(
@ -622,7 +594,6 @@ macro(_add_doxy_headers headers)
add_custom_target(${targetname} DEPENDS "${outfile}") add_custom_target(${targetname} DEPENDS "${outfile}")
#set_target_properties(${targetname} PROPERTIES FOLDER "public_headers/")
list(APPEND headerfiles ${targetname} ) list(APPEND headerfiles ${targetname} )
endforeach() endforeach()
@ -662,10 +633,12 @@ function(_stringify src_files varname)
endfunction() endfunction()
# Macro wrapper for adding a non-cuda dependent executable # Macro wrapper for adding a non-cuda dependent executable
macro(_add_executable target) macro(_add_executable target folder)
add_executable(${target} ${ARGN}) add_executable(${target} ${ARGN})
set_target_properties(${target} PROPERTIES FOLDER ${folder})
if(CMAKE_COMPILER_IS_ICC) if(CMAKE_COMPILER_IS_ICC)
target_link_libraries(${target} ${ICC_LIBRARIES}) target_link_libraries(${target} ${ICC_LIBRARIES})
endif() endif()
@ -674,13 +647,15 @@ endmacro()
# Macro for adding a cuda executable if cuda is found and a regular # Macro for adding a cuda executable if cuda is found and a regular
# executable otherwise. # executable otherwise.
macro(_add_possibly_cuda_executable target) macro(_add_possibly_cuda_executable target folder)
if(CUDA_FOUND) if(CUDA_FOUND)
cuda_add_executable(${target} ${ARGN}) cuda_add_executable(${target} ${ARGN})
else() else()
add_executable(${target} ${ARGN}) add_executable(${target} ${ARGN})
endif() endif()
set_target_properties(${target} PROPERTIES FOLDER ${folder})
if(CMAKE_COMPILER_IS_ICC) if(CMAKE_COMPILER_IS_ICC)
target_link_libraries(${target} ${ICC_LIBRARIES}) target_link_libraries(${target} ${ICC_LIBRARIES})
endif() endif()
@ -689,35 +664,42 @@ endmacro()
# Macro for adding a cuda library if cuda is found and a regular # Macro for adding a cuda library if cuda is found and a regular
# library otherwise. # library otherwise.
macro(_add_possibly_cuda_library target) macro(_add_possibly_cuda_library target folder)
if(CUDA_FOUND) if(CUDA_FOUND)
cuda_add_library(${target} ${ARGN}) cuda_add_library(${target} ${ARGN})
else() else()
add_library(${target} ${ARGN}) add_library(${target} ${ARGN})
endif() endif()
set_target_properties(${target} PROPERTIES FOLDER ${folder})
endmacro() endmacro()
# Macro for adding a (potentially cuda) GLFW executable. # Macro for adding a (potentially cuda) GLFW executable.
macro(_add_glfw_executable target) macro(_add_glfw_executable target folder)
_add_possibly_cuda_executable(${target} ${ARGN}) _add_possibly_cuda_executable(${target} ${folder} ${ARGN})
if(WIN32) #
# Windows needs some of its dependency dll's copied into the same # manuelk : commenting this out as it seems to be causing more problems than
# directory as the executable. # it is worth. Moving glfw as a native git recursive dependency will make this
set( LIBRARIES ${GLFW_LIBRARIES}) # redundant anyway.
foreach (LIB ${LIBRARIES} ) #
string(REPLACE ".lib" ".dll" DLL ${LIB})
string(REPLACE ".LIB" ".DLL" DLL ${DLL}) # if(WIN32)
add_custom_command( # # Windows needs some of its dependency dll's copied into the same
TARGET ${target} POST_BUILD # # directory as the executable.
COMMAND ${CMAKE_COMMAND} -E copy_if_different # set(LIBRARIES ${GLFW_LIBRARIES})
${DLL} # foreach (LIB ${LIBRARIES} )
$<TARGET_FILE_DIR:${target}> # string(REPLACE ".lib" ".dll" DLL ${LIB})
) # string(REPLACE ".LIB" ".DLL" DLL ${DLL})
endforeach() # add_custom_command(
endif() # TARGET ${target} POST_BUILD
# COMMAND ${CMAKE_COMMAND} -E copy_if_different
# ${DLL}
# $<TARGET_FILE_DIR:${target}>
# )
# endforeach()
# endif()
endmacro() endmacro()

View File

@ -8,9 +8,10 @@ Feel free to use it and let us know what you think.
For more details about OpenSubdiv, see [Pixar Graphics Technologies](http://graphics.pixar.com). For more details about OpenSubdiv, see [Pixar Graphics Technologies](http://graphics.pixar.com).
* master : [![Build Status](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv.svg?branch=master)](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv) | | Linux | Windows |
|:------:|:-------:|:---------:|
* dev : [![Build Status](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv.svg?branch=dev)](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv) | master | [![Linux Build Status](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv.svg?branch=master)](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/mcmwg4q9m8kgi9im/branch/master?svg=true)](https://ci.appveyor.com/project/c64kernal/opensubdiv-ddr8q) |
| dev | [![Linux Build Status](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv.svg?branch=dev)](https://travis-ci.org/PixarAnimationStudios/OpenSubdiv) | [![Windows Build Status](https://ci.appveyor.com/api/projects/status/mcmwg4q9m8kgi9im/branch/dev?svg=true)](https://ci.appveyor.com/project/c64kernal/opensubdiv-ddr8q) |
## Documents ## Documents
* [User Documents] (http://graphics.pixar.com/opensubdiv/docs/intro.html) * [User Documents] (http://graphics.pixar.com/opensubdiv/docs/intro.html)
@ -65,7 +66,7 @@ For more details about OpenSubdiv, see [Pixar Graphics Technologies](http://grap
${GLEW_LOCATION}/lib/libGLEW.a (linux) ${GLEW_LOCATION}/lib/libGLEW.a (linux)
${GLEW_LOCATION}/lib/glew32.lib (windows) ${GLEW_LOCATION}/lib/glew32.lib (windows)
${GLFW_LOCATION}/include/glfw3.h ${GLFW_LOCATION}/include/GLFW/glfw3.h
${GLFW_LOCATION}/lib/libglfw3.a (linux) ${GLFW_LOCATION}/lib/libglfw3.a (linux)
${GLFW_LOCATION}/lib/glfw3.lib (windows) ${GLFW_LOCATION}/lib/glfw3.lib (windows)
``` ```

28
appveyor.yml Normal file
View File

@ -0,0 +1,28 @@
clone_folder: c:\projects\OpenSubdiv
branches:
only:
- master
- dev
- dev_appv
platform:
#- x86
- x64
configuration:
- 14 2015
#- 12 2013
build_script:
- cd c:\projects\OpenSubdiv
- mkdir build
- cd build
- cmake --version
- cmake -G "Visual Studio %Configuration%" -DNO_TBB=1 -DNO_OMP=1 -DNO_CUDA=1 -DNO_MAYA=1 -DNO_PTEX=1 -DNO_DOC=1 -DNO_CLEW=1 -DNO_OPENGL=1 -DNO_OPENCL=1 ..
- cmake --build . --config Release
test_script:
- cd c:\projects\OpenSubdiv\build
- ctest -C Release . --output-on-failure

View File

@ -101,15 +101,21 @@ else ()
DOC "The Ptex library") DOC "The Ptex library")
endif () endif ()
if (PTEX_INCLUDE_DIR AND EXISTS "${PTEX_INCLUDE_DIR}/Ptexture.h" ) if (PTEX_INCLUDE_DIR AND EXISTS "${PTEX_INCLUDE_DIR}/PtexVersion.h")
set (PTEX_VERSION_FILE "${PTEX_INCLUDE_DIR}/PtexVersion.h")
elseif (PTEX_INCLUDE_DIR AND EXISTS "${PTEX_INCLUDE_DIR}/Ptexture.h")
set (PTEX_VERSION_FILE "${PTEX_INCLUDE_DIR}/Ptexture.h")
endif()
file(STRINGS "${PTEX_INCLUDE_DIR}/Ptexture.h" TMP REGEX "^#define PtexAPIVersion.*$") if (PTEX_VERSION_FILE)
file(STRINGS "${PTEX_VERSION_FILE}" TMP REGEX "^#define PtexAPIVersion.*$")
string(REGEX MATCHALL "[0-9]+" API ${TMP}) string(REGEX MATCHALL "[0-9]+" API ${TMP})
file(STRINGS "${PTEX_INCLUDE_DIR}/Ptexture.h" TMP REGEX "^#define PtexFileMajorVersion.*$") file(STRINGS "${PTEX_VERSION_FILE}" TMP REGEX "^#define PtexFileMajorVersion.*$")
string(REGEX MATCHALL "[0-9]+" MAJOR ${TMP}) string(REGEX MATCHALL "[0-9]+" MAJOR ${TMP})
file(STRINGS "${PTEX_INCLUDE_DIR}/Ptexture.h" TMP REGEX "^#define PtexFileMinorVersion.*$") file(STRINGS "${PTEX_VERSION_FILE}" TMP REGEX "^#define PtexFileMinorVersion.*$")
string(REGEX MATCHALL "[0-9]+" MINOR ${TMP}) string(REGEX MATCHALL "[0-9]+" MINOR ${TMP})
set(PTEX_VERSION ${API}.${MAJOR}.${MINOR}) set(PTEX_VERSION ${API}.${MAJOR}.${MINOR})

View File

@ -85,6 +85,8 @@ if (WIN32)
set(WINPATH "${WINPATH}/vc11") set(WINPATH "${WINPATH}/vc11")
elseif (MSVC12) elseif (MSVC12)
set(WINPATH "${WINPATH}/vc12") set(WINPATH "${WINPATH}/vc12")
elseif (MSVC14)
set(WINPATH "${WINPATH}/vc14")
endif() endif()
list(APPEND TBB_LIB_ARCH ${WINPATH}) list(APPEND TBB_LIB_ARCH ${WINPATH})

View File

@ -31,7 +31,7 @@ if (DOXYGEN_FOUND)
add_custom_target(doc_doxy add_custom_target(doc_doxy
${DOXYGEN_EXECUTABLE} "${CMAKE_CURRENT_BINARY_DIR}/OpenSubdiv.doxy" ${DOXYGEN_EXECUTABLE} "${CMAKE_CURRENT_BINARY_DIR}/OpenSubdiv.doxy"
WORKING_DIRECTORY WORKING_DIRECTORY
"${CMAKE_BINARY_DIR}/public_headers/" "${OpenSubdiv_BINARY_DIR}/public_headers/"
DEPENDS DEPENDS
public_headers public_headers
COMMENT COMMENT
@ -184,7 +184,7 @@ if (DOCUTILS_FOUND AND PYTHONINTERP_FOUND)
get_filename_component(BASENAME ${tutorial} NAME_WE) get_filename_component(BASENAME ${tutorial} NAME_WE)
string(REGEX REPLACE "(/)" "_" TARGET_NAME ${tutorial}) string(REGEX REPLACE "(/)" "_" TARGET_NAME ${tutorial})
set(infile "${CMAKE_SOURCE_DIR}/tutorials/${tutorial}") set(infile "${OpenSubdiv_SOURCE_DIR}/tutorials/${tutorial}")
set(rstfile "${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}.rst") set(rstfile "${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}.rst")
set(htmlfile "${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}.html") set(htmlfile "${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}.html")

View File

@ -31,6 +31,34 @@
---- ----
Release 3.0.5
=============
Release 3.0.5 is a minor stability release with performance and correctness bug fixes.
**Bug Fixes**
- The previous release reduced transient memory use during PatchTable construction, but increased the amount of memory consumed by the resulting PatchTable itself, this regression has been fixed.
- The example Ptex texture sampling code has been fixed to prevent sampling beyond the texels for a face when multisample rasterization is enabled.
Release 3.0.4
=============
Release 3.0.4 is a minor stability release which includes important performance
and bug fixes.
**New Features**
- Added accessor methods to Far::LimitStencilTable to retrieve limit stencil data including derivative weights
- Added support for OpenCL event control to Osd::CLVertexBuffer and Osd::CLEvaluator
**Changes**
- Major reduction in memory use during Far::PatchTable construction for topologies with large numbers of extraordinary features
- Improved performance for GL and D3D11 tessellation control / hull shader execution when drawing BSpline patches with the single crease patch optimization enabled
**Bug Fixes**
- Restored support for drawing with fractional tessellation
- Fixed far_tutorial_6 to refine primvar data only up to the number of levels produced by topological refinement
- Fixed build warnings and errors reported by Visual Studio 2015
Release 3.0.3 Release 3.0.3
============= =============

View File

@ -39,7 +39,7 @@ if (NOT NO_OPENGL)
add_subdirectory(glPaintTest) add_subdirectory(glPaintTest)
endif() endif()
if (PTEX_FOUND) if (PTEX_FOUND AND ZLIB_FOUND)
add_subdirectory(glPtexViewer) add_subdirectory(glPtexViewer)
endif() endif()
@ -73,7 +73,7 @@ if (DXSDK_FOUND AND NOT NO_DX)
add_subdirectory(dxViewer) add_subdirectory(dxViewer)
if (PTEX_FOUND) if (PTEX_FOUND AND ZLIB_FOUND)
add_subdirectory(dxPtexViewer) add_subdirectory(dxPtexViewer)
endif() endif()

View File

@ -171,3 +171,11 @@ add_library(examples_common_obj
${EXAMPLES_COMMON_HEADER_FILES} ${EXAMPLES_COMMON_HEADER_FILES}
${INC_FILES} ${INC_FILES}
) )
set_target_properties(examples_common_obj
PROPERTIES
FOLDER "examples"
)

View File

@ -158,10 +158,10 @@ CLDeviceContext::HAS_CL_VERSION_1_1 () {
#ifdef OPENSUBDIV_HAS_CLEW #ifdef OPENSUBDIV_HAS_CLEW
static bool clewInitialized = false; static bool clewInitialized = false;
static bool clewLoadSuccess; static bool clewLoadSuccess;
if (not clewInitialized) { if (!clewInitialized) {
clewInitialized = true; clewInitialized = true;
clewLoadSuccess = clewInit() == CLEW_SUCCESS; clewLoadSuccess = clewInit() == CLEW_SUCCESS;
if (not clewLoadSuccess) { if (!clewLoadSuccess) {
error("Loading OpenCL failed.\n"); error("Loading OpenCL failed.\n");
} }
} }

View File

@ -63,7 +63,7 @@ static int _GetCudaDeviceForCurrentGLContext()
// If we don't have a current GL context, then choose the device which // If we don't have a current GL context, then choose the device which
// matches the current X11 screen number. // matches the current X11 screen number.
Display * display = glXGetCurrentDisplay(); Display * display = glXGetCurrentDisplay();
if (not display) { if (!display) {
display = XOpenDisplay(NULL); display = XOpenDisplay(NULL);
if (display) { if (display) {
int screen = DefaultScreen(display); int screen = DefaultScreen(display);
@ -90,7 +90,7 @@ static int _GetCudaDeviceForCurrentGLContext()
int interopDevices[1]; int interopDevices[1];
cudaError_t status = cudaGLGetDevices(&interopDeviceCount, interopDevices, cudaError_t status = cudaGLGetDevices(&interopDeviceCount, interopDevices,
1, cudaGLDeviceListCurrentFrame); 1, cudaGLDeviceListCurrentFrame);
if (status == cudaErrorNoDevice or interopDeviceCount != 1) { if (status == cudaErrorNoDevice || interopDeviceCount != 1) {
message("CUDA no interop devices found.\n"); message("CUDA no interop devices found.\n");
return 0; return 0;
} }

View File

@ -26,14 +26,14 @@
#include "ptexMipmapTextureLoader.h" #include "ptexMipmapTextureLoader.h"
#include <far/error.h> // XXX: to be replaced #include <far/error.h> // XXX: to be replaced
#include <Ptexture.h>
#include <D3D11.h> #include <D3D11.h>
#include <cassert> #include <cassert>
D3D11PtexMipmapTexture::D3D11PtexMipmapTexture() D3D11PtexMipmapTexture::D3D11PtexMipmapTexture()
: _width(0), _height(0), _depth(0), : _width(0), _height(0), _depth(0),
_layout(0), _texels(0), _layout(0), _texels(0),
_layoutSRV(0), _texelsSRV(0) _layoutSRV(0), _texelsSRV(0),
_memoryUsage(0)
{ {
} }
@ -96,25 +96,33 @@ genTextureBuffer(ID3D11DeviceContext *deviceContext, int size, void const * data
D3D11PtexMipmapTexture * D3D11PtexMipmapTexture *
D3D11PtexMipmapTexture::Create(ID3D11DeviceContext *deviceContext, D3D11PtexMipmapTexture::Create(ID3D11DeviceContext *deviceContext,
PtexTexture * reader, PtexTexture * reader,
int maxLevels) { int maxLevels,
size_t targetMemory) {
D3D11PtexMipmapTexture * result = NULL; D3D11PtexMipmapTexture * result = NULL;
int maxNumPages = D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; int maxNumPages = D3D10_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION;
// Read the ptex data and pack the texels // Read the ptex data and pack the texels
PtexMipmapTextureLoader loader(reader, maxNumPages, maxLevels); bool padAlpha = reader->numChannels()==3 && reader->dataType()!=Ptex::dt_float;
int numFaces = loader.GetNumFaces(); PtexMipmapTextureLoader loader(reader,
maxNumPages,
maxLevels,
targetMemory,
true, // seamlessMipmap
padAlpha);
int numChannels = reader->numChannels() + padAlpha,
numFaces = loader.GetNumFaces();
ID3D11Buffer *layout = genTextureBuffer(deviceContext, ID3D11Buffer *layout = genTextureBuffer(deviceContext,
numFaces * 6 * sizeof(short), numFaces * 6 * sizeof(short),
loader.GetLayoutBuffer()); loader.GetLayoutBuffer());
if (not layout) return NULL; if (!layout) return NULL;
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
int bpp = 0; int bpp = 0;
int numChannels = reader->numChannels();
switch (reader->dataType()) { switch (reader->dataType()) {
case Ptex::dt_uint16: case Ptex::dt_uint16:
switch (numChannels) { switch (numChannels) {
@ -138,7 +146,7 @@ D3D11PtexMipmapTexture::Create(ID3D11DeviceContext *deviceContext,
switch (numChannels) { switch (numChannels) {
case 1: format = DXGI_FORMAT_R16_FLOAT; break; case 1: format = DXGI_FORMAT_R16_FLOAT; break;
case 2: format = DXGI_FORMAT_R16G16_FLOAT; break; case 2: format = DXGI_FORMAT_R16G16_FLOAT; break;
case 3:assert(false); break; case 3: assert(false); break;
case 4: format = DXGI_FORMAT_R16G16B16A16_FLOAT; break; case 4: format = DXGI_FORMAT_R16G16B16A16_FLOAT; break;
} }
bpp = numChannels * 2; bpp = numChannels * 2;
@ -218,6 +226,7 @@ D3D11PtexMipmapTexture::Create(ID3D11DeviceContext *deviceContext,
result->_layoutSRV = layoutSRV; result->_layoutSRV = layoutSRV;
result->_texelsSRV = texelsSRV; result->_texelsSRV = texelsSRV;
result->_memoryUsage = loader.GetMemoryUsage();
return result; return result;
} }

View File

@ -27,7 +27,8 @@
#include <osd/nonCopyable.h> #include <osd/nonCopyable.h>
class PtexTexture; #include <Ptexture.h>
struct ID3D11Buffer; struct ID3D11Buffer;
struct ID3D11Texture2D; struct ID3D11Texture2D;
struct ID3D11DeviceContext; struct ID3D11DeviceContext;
@ -37,7 +38,8 @@ class D3D11PtexMipmapTexture : OpenSubdiv::Osd::NonCopyable<D3D11PtexMipmapTextu
public: public:
static D3D11PtexMipmapTexture * Create(ID3D11DeviceContext *deviceContext, static D3D11PtexMipmapTexture * Create(ID3D11DeviceContext *deviceContext,
PtexTexture * reader, PtexTexture * reader,
int maxLevels=10); int maxLevels=10,
size_t targetMemory=0);
/// Returns GLSL shader snippet to fetch ptex /// Returns GLSL shader snippet to fetch ptex
static const char *GetShaderSource(); static const char *GetShaderSource();
@ -53,6 +55,9 @@ public:
ID3D11ShaderResourceView **GetTexelsSRV() { return &_texelsSRV; } ID3D11ShaderResourceView **GetTexelsSRV() { return &_texelsSRV; }
/// Returns the amount of allocated memory (in byte)
size_t GetMemoryUsage() const { return _memoryUsage; }
~D3D11PtexMipmapTexture(); ~D3D11PtexMipmapTexture();
private: private:
@ -68,6 +73,8 @@ private:
ID3D11Texture2D *_texels; // texel data ID3D11Texture2D *_texels; // texel data
ID3D11ShaderResourceView *_layoutSRV; ID3D11ShaderResourceView *_layoutSRV;
ID3D11ShaderResourceView *_texelsSRV; ID3D11ShaderResourceView *_texelsSRV;
size_t _memoryUsage; // total amount of memory used (estimate)
}; };
#endif // OPENSUBDIV_EXAMPLES_D3D11_PTEX_TEXTURE_H #endif // OPENSUBDIV_EXAMPLES_D3D11_PTEX_TEXTURE_H

View File

@ -90,7 +90,7 @@ D3D11DrawConfig::CompileVertexShader(const std::string &target,
return false; return false;
} }
if (ppInputLayout and !*ppInputLayout) { if (ppInputLayout && !*ppInputLayout) {
hr = pd3dDevice->CreateInputLayout( hr = pd3dDevice->CreateInputLayout(
pInputElementDescs, numInputElements, pInputElementDescs, numInputElements,
pBlob->GetBufferPointer(), pBlob->GetBufferPointer(),

View File

@ -246,7 +246,7 @@ GLhud::Rebuild(int width, int height,
int framebufferWidth, int framebufferHeight) { int framebufferWidth, int framebufferHeight) {
Hud::Rebuild(width, height, framebufferWidth, framebufferHeight); Hud::Rebuild(width, height, framebufferWidth, framebufferHeight);
if (not _staticVbo) if (! _staticVbo)
return; return;
_staticVboSize = (int)getStaticVboSource().size(); _staticVboSize = (int)getStaticVboSource().size();

View File

@ -27,8 +27,6 @@
#include <osd/opengl.h> #include <osd/opengl.h>
#include <Ptexture.h>
GLPtexMipmapTexture::GLPtexMipmapTexture() GLPtexMipmapTexture::GLPtexMipmapTexture()
: _width(0), _height(0), _depth(0), _layout(0), _texels(0), _memoryUsage(0) : _width(0), _height(0), _depth(0), _layout(0), _texels(0), _memoryUsage(0)
{ {

View File

@ -28,10 +28,9 @@
#include <osd/nonCopyable.h> #include <osd/nonCopyable.h>
#include <osd/opengl.h> #include <osd/opengl.h>
#include <Ptexture.h>
#include <stdlib.h> #include <stdlib.h>
class PtexTexture;
class GLPtexMipmapTexture : OpenSubdiv::Osd::NonCopyable<GLPtexMipmapTexture> { class GLPtexMipmapTexture : OpenSubdiv::Osd::NonCopyable<GLPtexMipmapTexture> {
public: public:
static GLPtexMipmapTexture * Create(PtexTexture * reader, static GLPtexMipmapTexture * Create(PtexTexture * reader,

View File

@ -114,7 +114,7 @@ vec4 PtexLookupNearest(vec4 patchCoord,
sampler2DArray data, sampler2DArray data,
isamplerBuffer packings) isamplerBuffer packings)
{ {
vec2 uv = patchCoord.xy; vec2 uv = clamp(patchCoord.xy, vec2(0), vec2(1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID); PtexPacking ppack = getPtexPacking(packings, faceID);
vec2 coords = vec2(uv.x * ppack.width + ppack.uOffset, vec2 coords = vec2(uv.x * ppack.width + ppack.uOffset,
@ -127,7 +127,7 @@ vec4 PtexLookupNearest(vec4 patchCoord,
sampler2DArray data, sampler2DArray data,
isamplerBuffer packings) isamplerBuffer packings)
{ {
vec2 uv = patchCoord.xy; vec2 uv = clamp(patchCoord.xy, vec2(0), vec2(1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);
vec2 coords = vec2(uv.x * ppack.width + ppack.uOffset, vec2 coords = vec2(uv.x * ppack.width + ppack.uOffset,
@ -139,7 +139,7 @@ vec4 PtexLookupFast(vec4 patchCoord,
sampler2DArray data, sampler2DArray data,
isamplerBuffer packings) isamplerBuffer packings)
{ {
vec2 uv = patchCoord.xy; vec2 uv = clamp(patchCoord.xy, vec2(0), vec2(1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID); PtexPacking ppack = getPtexPacking(packings, faceID);
@ -154,7 +154,7 @@ vec4 PtexLookupFast(vec4 patchCoord,
sampler2DArray data, sampler2DArray data,
isamplerBuffer packings) isamplerBuffer packings)
{ {
vec2 uv = patchCoord.xy; vec2 uv = clamp(patchCoord.xy, vec2(0), vec2(1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);
@ -169,7 +169,7 @@ vec4 PtexLookup(vec4 patchCoord,
sampler2DArray data, sampler2DArray data,
isamplerBuffer packings) isamplerBuffer packings)
{ {
vec2 uv = patchCoord.xy; vec2 uv = clamp(patchCoord.xy, vec2(0), vec2(1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);
@ -203,7 +203,7 @@ vec4 PtexLookupQuadratic(out vec4 du,
sampler2DArray data, sampler2DArray data,
isamplerBuffer packings) isamplerBuffer packings)
{ {
vec2 uv = patchCoord.xy; vec2 uv = clamp(patchCoord.xy, vec2(0), vec2(1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);

View File

@ -79,7 +79,7 @@ unsigned char *loadHdr(const char *filename, HdrInfo *info, bool convertToFloat)
// read header // read header
while(true) { while(true) {
if (not fgets(buffer, MAXLINE, fp)) goto error; if (! fgets(buffer, MAXLINE, fp)) goto error;
if (buffer[0] == '\n') break; if (buffer[0] == '\n') break;
if (buffer[0] == '\r' && buffer[0] == '\n') break; if (buffer[0] == '\r' && buffer[0] == '\n') break;
if (strncmp(buffer, "#?", 2) == 0) { if (strncmp(buffer, "#?", 2) == 0) {
@ -92,16 +92,16 @@ unsigned char *loadHdr(const char *filename, HdrInfo *info, bool convertToFloat)
if (strncmp(info->format, "32-bit_rle_rgbe", 15)) goto error; if (strncmp(info->format, "32-bit_rle_rgbe", 15)) goto error;
// resolution // resolution
if (not fgets(buffer, MAXLINE, fp)) goto error; if (! fgets(buffer, MAXLINE, fp)) goto error;
{ {
int n = (int)strlen(buffer); int n = (int)strlen(buffer);
for (int i = 1; i < n; ++i) { for (int i = 1; i < n; ++i) {
if (buffer[i] == 'X') { if (buffer[i] == 'X') {
if (not (info->flag & HDR_Y_MAJOR)) info->flag |= HDR_X_MAJOR; if (! (info->flag & HDR_Y_MAJOR)) info->flag |= HDR_X_MAJOR;
info->flag |= (char)((buffer[i-1] == '-') ? HDR_X_DEC : 0); info->flag |= (char)((buffer[i-1] == '-') ? HDR_X_DEC : 0);
info->width = atoi(&buffer[i+1]); info->width = atoi(&buffer[i+1]);
} else if (buffer[i] == 'Y') { } else if (buffer[i] == 'Y') {
if (not (info->flag & HDR_X_MAJOR)) info->flag |= HDR_Y_MAJOR; if (! (info->flag & HDR_X_MAJOR)) info->flag |= HDR_Y_MAJOR;
info->flag |= (char)((buffer[i-1] == '-') ? HDR_Y_DEC : 0); info->flag |= (char)((buffer[i-1] == '-') ? HDR_Y_DEC : 0);
info->height = atoi(&buffer[i+1]); info->height = atoi(&buffer[i+1]);
} }
@ -128,7 +128,7 @@ unsigned char *loadHdr(const char *filename, HdrInfo *info, bool convertToFloat)
line = (unsigned char *)malloc(info->scanLength*4); line = (unsigned char *)malloc(info->scanLength*4);
for (int y = info->scanWidth-1; y >= 0; --y) { for (int y = info->scanWidth-1; y >= 0; --y) {
if (not readLine(line, info->scanLength, fp)) goto error; if (! readLine(line, info->scanLength, fp)) goto error;
for (int x = 0; x < info->scanLength; ++x) { for (int x = 0; x < info->scanLength; ++x) {
if (convertToFloat) { if (convertToFloat) {
float scale = powf(2.0f, float(line[x*4+3] - 128))/255.0f; float scale = powf(2.0f, float(line[x*4+3] - 128))/255.0f;

View File

@ -114,7 +114,7 @@ float4 PtexLookupNearest(float4 patchCoord,
Texture2DArray data, Texture2DArray data,
Buffer<uint> packings) Buffer<uint> packings)
{ {
float2 uv = patchCoord.xy; float2 uv = clamp(patchCoord.xy, float2(0,0), float2(1,1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID); PtexPacking ppack = getPtexPacking(packings, faceID);
float2 coords = float2(uv.x * ppack.width + ppack.uOffset, float2 coords = float2(uv.x * ppack.width + ppack.uOffset,
@ -127,7 +127,7 @@ float4 PtexLookupNearest(float4 patchCoord,
Texture2DArray data, Texture2DArray data,
Buffer<uint> packings) Buffer<uint> packings)
{ {
float2 uv = patchCoord.xy; float2 uv = clamp(patchCoord.xy, float2(0,0), float2(1,1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);
float2 coords = float2(uv.x * ppack.width + ppack.uOffset, float2 coords = float2(uv.x * ppack.width + ppack.uOffset,
@ -140,7 +140,7 @@ float4 PtexLookup(float4 patchCoord,
Texture2DArray data, Texture2DArray data,
Buffer<uint> packings) Buffer<uint> packings)
{ {
float2 uv = patchCoord.xy; float2 uv = clamp(patchCoord.xy, float2(0,0), float2(1,1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);
@ -174,7 +174,7 @@ float4 PtexLookupQuadratic(out float4 du,
Texture2DArray data, Texture2DArray data,
Buffer<uint> packings) Buffer<uint> packings)
{ {
float2 uv = patchCoord.xy; float2 uv = clamp(patchCoord.xy, float2(0,0), float2(1,1));
int faceID = int(patchCoord.w); int faceID = int(patchCoord.w);
PtexPacking ppack = getPtexPacking(packings, faceID, level); PtexPacking ppack = getPtexPacking(packings, faceID, level);

View File

@ -185,7 +185,7 @@ Hud::MouseClick(int x, int y)
for (std::vector<PullDown>::iterator it = _pulldowns.begin(); for (std::vector<PullDown>::iterator it = _pulldowns.begin();
it != _pulldowns.end(); ++it) { it != _pulldowns.end(); ++it) {
if (hitTest(*it, x, y)) { if (hitTest(*it, x, y)) {
if (not it->open) { if (! it->open) {
it->h = FONT_CHAR_HEIGHT; it->h = FONT_CHAR_HEIGHT;
it->h *= (int)it->labels.size(); it->h *= (int)it->labels.size();
it->open=true; it->open=true;
@ -200,7 +200,7 @@ Hud::MouseClick(int x, int y)
it->callback(it->values[it->selected]); it->callback(it->values[it->selected]);
} }
} else { } else {
it->open=not it->open; it->open=! it->open;
} }
} }
_requiresRebuildStatic = true; _requiresRebuildStatic = true;
@ -528,7 +528,7 @@ Hud::Rebuild(int width, int height, int framebufferWidth, int framebufferHeight)
x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_MIDDLE); x = drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_MIDDLE);
} }
drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_RIGHT); drawChar(_staticVboSource, x, y, 1, 1, 1, FONT_SLIDER_RIGHT);
int pos = (int)((it->value/float(it->max-it->min))*it->w); int pos = int(((it->value-it->min)/(it->max-it->min))*float(it->w));
drawChar(_staticVboSource, sx+pos, y, 1, 1, 0, FONT_SLIDER_CURSOR); drawChar(_staticVboSource, sx+pos, y, 1, 1, 0, FONT_SLIDER_CURSOR);
} }
// draw pulldowns // draw pulldowns

View File

@ -127,11 +127,12 @@ protected:
bool intStep; bool intStep;
void SetValue(float v) { void SetValue(float v) {
value = std::max(std::min(v, max), min); v = std::max(std::min(v, max), min);
if (intStep) { if (intStep) {
// MSVC 2010 does not have std::round() or roundf() // MSVC 2010 does not have std::round() or roundf()
value = v>0.0f ? floor(v+0.5f) : ceil(v-0.5f); v = v>0.0f ? floor(v+0.5f) : ceil(v-0.5f);
} }
value = v;
} }
}; };
@ -145,7 +146,7 @@ protected:
PullDownCallback callback; PullDownCallback callback;
void SetSelected(int idx) { void SetSelected(int idx) {
if (idx>=0 and idx<(int)labels.size()) { if (idx>=0 && idx<(int)labels.size()) {
selected=idx; selected=idx;
} }
} }

View File

@ -46,7 +46,7 @@ ObjAnim::InterpolatePositions(float time, float * positions, int stride) const {
assert(positions); assert(positions);
if ( _positions.empty() or (not _shape)) { if ( _positions.empty() || (! _shape)) {
//printf("Error: InterpolatePositions on unfit ObjAnim instance\n"); //printf("Error: InterpolatePositions on unfit ObjAnim instance\n");
return; return;
} }
@ -94,7 +94,7 @@ ObjAnim::Create(std::vector<char const *> objFiles, bool axis) {
Shape const * shape = 0; Shape const * shape = 0;
if (not objFiles.empty()) { if (! objFiles.empty()) {
anim = new ObjAnim; anim = new ObjAnim;
@ -102,7 +102,7 @@ ObjAnim::Create(std::vector<char const *> objFiles, bool axis) {
for (int i = 0; i < (int)objFiles.size(); ++i) { for (int i = 0; i < (int)objFiles.size(); ++i) {
if (not objFiles[i]) { if (! objFiles[i]) {
continue; continue;
} }

View File

@ -24,7 +24,6 @@
#include "ptexMipmapTextureLoader.h" #include "ptexMipmapTextureLoader.h"
#include <Ptexture.h>
#include <vector> #include <vector>
#include <list> #include <list>
#include <algorithm> #include <algorithm>
@ -44,7 +43,7 @@ PtexMipmapTextureLoader::Block::guttering(PtexMipmapTextureLoader *loader,
unsigned char * lineBuffer = new unsigned char[lineBufferSize]; unsigned char * lineBuffer = new unsigned char[lineBufferSize];
for (int edge = 0; edge < 4; edge++) { for (int edge = 0; edge < 4; edge++) {
int len = (edge == 0 or edge == 2) ? wid : hei; int len = (edge == 0 || edge == 2) ? wid : hei;
loader->sampleNeighbor(lineBuffer, this->index, edge, len, bpp); loader->sampleNeighbor(lineBuffer, this->index, edge, len, bpp);
unsigned char *s = lineBuffer, *d; unsigned char *s = lineBuffer, *d;
@ -173,11 +172,11 @@ PtexMipmapTextureLoader::Block::Generate(PtexMipmapTextureLoader *loader,
// instead of nothing. // instead of nothing.
limit = std::min(std::min(limit, ulog2_), vlog2_); limit = std::min(std::min(limit, ulog2_), vlog2_);
while (ulog2_ >= limit and vlog2_ >= limit while (ulog2_ >= limit && vlog2_ >= limit
and (maxLevels == -1 or level <= maxLevels)) { && (maxLevels == -1 || level <= maxLevels)) {
if (level % 2 == 1) if (level % 2 == 1)
uofs += (1<<(ulog2_+1))+2; uofs += (1<<(ulog2_+1))+2;
if ((level > 0) and (level % 2 == 0)) if ((level > 0) && (level % 2 == 0))
vofs += (1<<(vlog2_+1)) + 2; vofs += (1<<(vlog2_+1)) + 2;
unsigned char *dst = destination + vofs * stride + uofs * bpp; unsigned char *dst = destination + vofs * stride + uofs * bpp;
@ -229,7 +228,7 @@ struct PtexMipmapTextureLoader::Page
// returns true if a block can fit in this slot // returns true if a block can fit in this slot
bool Fits(const Block *block) { bool Fits(const Block *block) {
return (block->width <= width) and (block->height <= height); return (block->width <= width) && (block->height <= height);
} }
}; };
@ -375,8 +374,8 @@ public:
_currentFace = _ptex->getFaceInfo(_currentFace).adjface(2); _currentFace = _ptex->getFaceInfo(_currentFace).adjface(2);
_currentEdge = 1; _currentEdge = 1;
_mid = false; _mid = false;
} else if (info.isSubface() and } else if (info.isSubface() &&
(not _ptex->getFaceInfo(_currentFace).isSubface()) and (! _ptex->getFaceInfo(_currentFace).isSubface()) &&
_currentEdge == 3) { _currentEdge == 3) {
_mid = true; _mid = true;
_currentEdge = info.adjedge(_currentEdge); _currentEdge = info.adjedge(_currentEdge);
@ -405,8 +404,8 @@ public:
} }
} }
Ptex::FaceInfo nextFaceInfo = _ptex->getFaceInfo(_currentFace); Ptex::FaceInfo nextFaceInfo = _ptex->getFaceInfo(_currentFace);
if ((not _clockWise) and if ((! _clockWise) &&
(not info.isSubface()) and (nextFaceInfo.isSubface())) { (! info.isSubface()) && (nextFaceInfo.isSubface())) {
// needs tricky traverse for boundary subface... // needs tricky traverse for boundary subface...
if (_currentEdge == 3) { if (_currentEdge == 3) {
_currentFace = nextFaceInfo.adjface(2); _currentFace = nextFaceInfo.adjface(2);
@ -447,10 +446,11 @@ PtexMipmapTextureLoader::PtexMipmapTextureLoader(PtexTexture *ptex,
int maxNumPages, int maxNumPages,
int maxLevels, int maxLevels,
size_t targetMemory, size_t targetMemory,
bool seamlessMipmap) : bool seamlessMipmap,
bool padAlpha) :
_ptex(ptex), _maxLevels(maxLevels), _bpp(0), _ptex(ptex), _maxLevels(maxLevels), _bpp(0),
_pageWidth(0), _pageHeight(0), _texelBuffer(NULL), _layoutBuffer(NULL), _pageWidth(0), _pageHeight(0), _padAlpha(padAlpha),
_memoryUsage(0) _texelBuffer(NULL), _layoutBuffer(NULL), _memoryUsage(0)
{ {
// byte per pixel // byte per pixel
_bpp = ptex->numChannels() * Ptex::DataSize(ptex->dataType()); _bpp = ptex->numChannels() * Ptex::DataSize(ptex->dataType());
@ -474,6 +474,10 @@ PtexMipmapTextureLoader::PtexMipmapTextureLoader(PtexTexture *ptex,
optimizePacking(maxNumPages, targetMemory); optimizePacking(maxNumPages, targetMemory);
generateBuffers(); generateBuffers();
if (padAlpha) {
addAlphaChannel();
}
} }
PtexMipmapTextureLoader::~PtexMipmapTextureLoader() PtexMipmapTextureLoader::~PtexMipmapTextureLoader()
@ -485,6 +489,48 @@ PtexMipmapTextureLoader::~PtexMipmapTextureLoader()
delete _layoutBuffer; delete _layoutBuffer;
} }
// add alpha channel to texelbuffer :
// assumes the texel buffer has been generated and apply a raw copy
// into a larger buffer with an alpha channel padded in
// note : this is not a particularly elegant solution...
void
PtexMipmapTextureLoader::addAlphaChannel() {
assert(_ptex);
// allocate new larger texel buffer
int bpc = Ptex::DataSize(_ptex->dataType()),
srcStride = _ptex->numChannels() * bpc,
dstStride = srcStride + bpc;
size_t numTexels = _pageWidth * _pageHeight * _pages.size(),
memoryUsed = dstStride * numTexels;
unsigned char * texBuffer = new unsigned char[memoryUsed];
// loop over every texel & copy + pad
unsigned char const * src = _texelBuffer;
unsigned char * dest = texBuffer;
for (int i=0; i<numTexels; ++i, src+=srcStride, dest+=dstStride) {
memcpy(dest, src, srcStride);
/// set alpha to 1
switch (_ptex->dataType()) {
case Ptex::dt_uint8 : *(uint8_t *)(dest+srcStride)= 0xFF; break;
case Ptex::dt_uint16 : *(uint16_t *)(dest+srcStride) = 0xFFFF; break;
case Ptex::dt_half : *(uint16_t *)(dest+srcStride) = 0x3C00; break;
case Ptex::dt_float : *(float *)(dest+srcStride) = 1.0f; break;
}
}
// remove old buffer & adjust class members
delete [] _texelBuffer;
_texelBuffer = texBuffer;
_memoryUsage = memoryUsed;
_bpp = dstStride;
}
// resample border texels for guttering // resample border texels for guttering
// //
int int
@ -680,7 +726,7 @@ PtexMipmapTextureLoader::getCornerPixel(float *resultPixel, int numchannels,
+------+-------+ +------+-------+
*/ */
int adjface = fi.adjface(edge); int adjface = fi.adjface(edge);
if (adjface != -1 and !_ptex->getFaceInfo(adjface).isSubface()) { if (adjface != -1 && !_ptex->getFaceInfo(adjface).isSubface()) {
int adjedge = fi.adjedge(edge); int adjedge = fi.adjedge(edge);
Ptex::Res res(std::min((int)_blocks[adjface].ulog2, reslog2+1), Ptex::Res res(std::min((int)_blocks[adjface].ulog2, reslog2+1),
@ -722,7 +768,7 @@ PtexMipmapTextureLoader::getCornerPixel(float *resultPixel, int numchannels,
but the edge 0 is an adjacent edge to get D pixel. but the edge 0 is an adjacent edge to get D pixel.
*/ */
int adjface = fi.adjface(0); int adjface = fi.adjface(0);
if (adjface != -1 and !_ptex->getFaceInfo(adjface).isSubface()) { if (adjface != -1 && !_ptex->getFaceInfo(adjface).isSubface()) {
int adjedge = fi.adjedge(0); int adjedge = fi.adjedge(0);
Ptex::Res res(std::min((int)_blocks[adjface].ulog2, reslog2+1), Ptex::Res res(std::min((int)_blocks[adjface].ulog2, reslog2+1),
std::min((int)_blocks[adjface].vlog2, reslog2+1)); std::min((int)_blocks[adjface].vlog2, reslog2+1));
@ -756,7 +802,7 @@ PtexMipmapTextureLoader::getCornerPixel(float *resultPixel, int numchannels,
// iterate faces around the vertex // iterate faces around the vertex
int numFaces = 0; int numFaces = 0;
CornerIterator it(_ptex, face, edge, reslog2); CornerIterator it(_ptex, face, edge, reslog2);
for (; not it.IsDone(); it.Next(), ++numFaces) { for (; !it.IsDone(); it.Next(), ++numFaces) {
it.GetPixel(pixel); it.GetPixel(pixel);
// accumulate pixel value // accumulate pixel value
@ -769,7 +815,7 @@ PtexMipmapTextureLoader::getCornerPixel(float *resultPixel, int numchannels,
} }
} }
// if regular corner, returns diagonal pixel without averaging // if regular corner, returns diagonal pixel without averaging
if (numFaces == 4 and (not it.IsBoundary())) { if (numFaces == 4 && (! it.IsBoundary())) {
return true; return true;
} }
@ -793,7 +839,7 @@ PtexMipmapTextureLoader::getLevelDiff(int face, int edge)
int maxDiff = 0; int maxDiff = 0;
CornerIterator it(_ptex, face, edge, baseRes); CornerIterator it(_ptex, face, edge, baseRes);
for (; not it.IsDone(); it.Next()) { for (; !it.IsDone(); it.Next()) {
int res = _blocks[it.GetCurrentFace()].ulog2; int res = _blocks[it.GetCurrentFace()].ulog2;
if (it.IsSubface()) ++res; if (it.IsSubface()) ++res;
maxDiff = std::max(maxDiff, baseRes - res); maxDiff = std::max(maxDiff, baseRes - res);
@ -820,12 +866,12 @@ PtexMipmapTextureLoader::optimizePacking(int maxNumPages,
blocks.sort(Block::sort); blocks.sort(Block::sort);
// try to fit into the target memory size if specified // try to fit into the target memory size if specified
if (targetMemory != 0 and _bpp * numTexels > targetMemory) { if (targetMemory != 0 && _bpp * numTexels > targetMemory) {
size_t numTargetTexels = targetMemory / _bpp; size_t numTargetTexels = targetMemory / _bpp;
while (numTexels > numTargetTexels) { while (numTexels > numTargetTexels) {
Block *block = blocks.front(); Block *block = blocks.front();
if (block->ulog2 < 2 or block->vlog2 < 2) break; if (block->ulog2 < 2 || block->vlog2 < 2) break;
// pick a smaller mipmap // pick a smaller mipmap
numTexels -= block->GetNumTexels(); numTexels -= block->GetNumTexels();
@ -900,7 +946,7 @@ PtexMipmapTextureLoader::optimizePacking(int maxNumPages,
} }
// adjust the page flag to the first page with open slots // adjust the page flag to the first page with open slots
if (_pages.size() > (firstslot+1) and if (_pages.size() > (firstslot+1) &&
_pages[firstslot+1]->IsFull()) ++firstslot; _pages[firstslot+1]->IsFull()) ++firstslot;
} }

View File

@ -25,11 +25,11 @@
#ifndef OPENSUBDIV_EXAMPLES_PTEX_MIPMAP_TEXTURE_LOADER_H #ifndef OPENSUBDIV_EXAMPLES_PTEX_MIPMAP_TEXTURE_LOADER_H
#define OPENSUBDIV_EXAMPLES_PTEX_MIPMAP_TEXTURE_LOADER_H #define OPENSUBDIV_EXAMPLES_PTEX_MIPMAP_TEXTURE_LOADER_H
#include <Ptexture.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdint.h> #include <stdint.h>
#include <vector> #include <vector>
class PtexTexture;
class PtexMipmapTextureLoader { class PtexMipmapTextureLoader {
public: public:
@ -37,7 +37,8 @@ public:
int maxNumPages, int maxNumPages,
int maxLevels = -1, int maxLevels = -1,
size_t targetMemory = 0, size_t targetMemory = 0,
bool seamlessMipmap = true); bool seamlessMipmap = true,
bool padAlpha = false);
~PtexMipmapTextureLoader(); ~PtexMipmapTextureLoader();
@ -118,8 +119,8 @@ private:
unsigned char *pptr, int bpp, int stride); unsigned char *pptr, int bpp, int stride);
static bool sort(const Block *a, const Block *b) { static bool sort(const Block *a, const Block *b) {
return (a->height > b->height) or return (a->height > b->height) ||
((a->height == b->height) and (a->width > b->width)); ((a->height == b->height) && (a->width > b->width));
} }
}; };
@ -136,6 +137,7 @@ private:
int resampleBorder(int face, int edgeId, unsigned char *result, int resampleBorder(int face, int edgeId, unsigned char *result,
int dstLength, int bpp, int dstLength, int bpp,
float srcStart = 0.0f, float srcEnd = 1.0f); float srcStart = 0.0f, float srcEnd = 1.0f);
void addAlphaChannel();
std::vector<Block> _blocks; std::vector<Block> _blocks;
std::vector<Page *> _pages; std::vector<Page *> _pages;
@ -145,6 +147,8 @@ private:
int _bpp; int _bpp;
int _pageWidth, _pageHeight; int _pageWidth, _pageHeight;
bool _padAlpha;
unsigned char *_texelBuffer; unsigned char *_texelBuffer;
unsigned char *_layoutBuffer; unsigned char *_layoutBuffer;

View File

@ -25,7 +25,7 @@
#ifndef STOPWATCH_H #ifndef STOPWATCH_H
#define STOPWATCH_H #define STOPWATCH_H
#if (_WIN32 or _WIN64) #if (_WIN32 || _WIN64)
#include <windows.h> #include <windows.h>
#else #else
#include <sys/types.h> #include <sys/types.h>

View File

@ -26,12 +26,14 @@
set(SHADER_FILES set(SHADER_FILES
shader.hlsl shader.hlsl
skyshader.hlsl
) )
set(PLATFORM_LIBRARIES set(PLATFORM_LIBRARIES
"${OSD_LINK_TARGET}" "${OSD_LINK_TARGET}"
"${DXSDK_LIBRARIES}" "${DXSDK_LIBRARIES}"
"${PTEX_LIBRARY}" "${PTEX_LIBRARY}"
"${ZLIB_LIBRARY}"
) )
include_directories( include_directories(
@ -55,13 +57,14 @@ endif()
set(SOURCE_FILES set(SOURCE_FILES
dxPtexViewer.cpp dxPtexViewer.cpp
sky.cpp
) )
_stringify("${SHADER_FILES}" INC_FILES) _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_possibly_cuda_executable(dxPtexViewer WIN32 _add_possibly_cuda_executable(dxPtexViewer "examples" WIN32
"${SOURCE_FILES}" "${SOURCE_FILES}"
"${INC_FILES}" "${INC_FILES}"
$<TARGET_OBJECTS:regression_common_obj> $<TARGET_OBJECTS:regression_common_obj>

View File

@ -58,6 +58,8 @@
#include <osd/d3d11Mesh.h> #include <osd/d3d11Mesh.h>
OpenSubdiv::Osd::D3D11MeshInterface *g_mesh; OpenSubdiv::Osd::D3D11MeshInterface *g_mesh;
#include "./sky.h"
#include "Ptexture.h" #include "Ptexture.h"
#include "PtexUtils.h" #include "PtexUtils.h"
@ -67,6 +69,7 @@ OpenSubdiv::Osd::D3D11MeshInterface *g_mesh;
#include "../common/d3d11Hud.h" #include "../common/d3d11Hud.h"
#include "../common/d3d11PtexMipmapTexture.h" #include "../common/d3d11PtexMipmapTexture.h"
#include "../common/d3d11ShaderCache.h" #include "../common/d3d11ShaderCache.h"
#include "../common/hdr_reader.h"
#include <osd/hlslPatchShaderSource.h> #include <osd/hlslPatchShaderSource.h>
static const char *g_shaderSource = static const char *g_shaderSource =
@ -205,11 +208,16 @@ float g_animTime = 0;
std::vector<float> g_positions, std::vector<float> g_positions,
g_normals; g_normals;
std::vector<std::vector<float> > g_animPositions;
Sky * g_sky=0;
D3D11PtexMipmapTexture * g_osdPTexImage = 0; D3D11PtexMipmapTexture * g_osdPTexImage = 0;
D3D11PtexMipmapTexture * g_osdPTexDisplacement = 0; D3D11PtexMipmapTexture * g_osdPTexDisplacement = 0;
D3D11PtexMipmapTexture * g_osdPTexOcclusion = 0; D3D11PtexMipmapTexture * g_osdPTexOcclusion = 0;
D3D11PtexMipmapTexture * g_osdPTexSpecular = 0; D3D11PtexMipmapTexture * g_osdPTexSpecular = 0;
const char * g_ptexColorFilename; const char * g_ptexColorFilename;
size_t g_ptexMemoryUsage = 0;
ID3D11Device * g_pd3dDevice = NULL; ID3D11Device * g_pd3dDevice = NULL;
ID3D11DeviceContext * g_pd3dDeviceContext = NULL; ID3D11DeviceContext * g_pd3dDeviceContext = NULL;
@ -217,17 +225,63 @@ IDXGISwapChain * g_pSwapChain = NULL;
ID3D11RenderTargetView * g_pSwapChainRTV = NULL; ID3D11RenderTargetView * g_pSwapChainRTV = NULL;
ID3D11RasterizerState* g_pRasterizerState = NULL; ID3D11RasterizerState* g_pRasterizerState = NULL;
ID3D11InputLayout* g_pInputLayout = NULL; ID3D11InputLayout * g_pInputLayout = NULL;
ID3D11DepthStencilState* g_pDepthStencilState = NULL; ID3D11DepthStencilState * g_pDepthStencilState = NULL;
ID3D11Texture2D * g_pDepthStencilBuffer = NULL; ID3D11Texture2D * g_pDepthStencilBuffer = NULL;
ID3D11Buffer* g_pcbPerFrame = NULL; ID3D11Buffer * g_pcbPerFrame = NULL;
ID3D11Buffer* g_pcbTessellation = NULL; ID3D11Buffer * g_pcbTessellation = NULL;
ID3D11Buffer* g_pcbLighting = NULL; ID3D11Buffer * g_pcbLighting = NULL;
ID3D11Buffer* g_pcbConfig = NULL; ID3D11Buffer * g_pcbConfig = NULL;
ID3D11DepthStencilView* g_pDepthStencilView = NULL; ID3D11DepthStencilView * g_pDepthStencilView = NULL;
ID3D11Texture2D * g_diffuseEnvironmentMap = NULL;
ID3D11ShaderResourceView * g_diffuseEnvironmentSRV = NULL;
ID3D11Texture2D * g_specularEnvironmentMap = NULL;
ID3D11ShaderResourceView * g_specularEnvironmentSRV = NULL;
ID3D11SamplerState * g_iblSampler = NULL;
ID3D11Query * g_pipelineStatsQuery = NULL;
bool g_bDone = false; bool g_bDone = false;
//------------------------------------------------------------------------------
static ID3D11Texture2D *
createHDRTexture(ID3D11Device * device, char const * hdrFile) {
HdrInfo info;
unsigned char * image = loadHdr(hdrFile, &info, /*convertToFloat=*/true);
if (image) {
D3D11_TEXTURE2D_DESC texDesc;
ZeroMemory(&texDesc, sizeof(texDesc));
texDesc.Width = info.width;
texDesc.Height = info.height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA subData;
subData.pSysMem = (void *)image;
subData.SysMemPitch = info.width * 4 * sizeof(float);
ID3D11Texture2D * texture=0;
device->CreateTexture2D(&texDesc, &subData, &texture);
free(image);
return texture;
}
return 0;
}
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
static void static void
calcNormals(OpenSubdiv::Far::TopologyRefiner * refiner, calcNormals(OpenSubdiv::Far::TopologyRefiner * refiner,
@ -269,28 +323,61 @@ updateGeom() {
int nverts = (int)g_positions.size() / 3; int nverts = (int)g_positions.size() / 3;
std::vector<float> vertex; if (g_moveScale && g_adaptive && !g_animPositions.empty()) {
vertex.reserve(nverts*6);
const float *p = &g_positions[0]; // baked animation only works with adaptive for now
const float *n = &g_normals[0]; // (since non-adaptive requires normals)
int nkeys = (int)g_animPositions.size();
const float fps = 24.0f;
for (int i = 0; i < nverts; ++i) { float p = fmodf(g_animTime * fps, (float)nkeys);
float move = g_size*0.005f*cosf(p[0]*100/g_size+g_frame*0.01f); int key = (int)p;
vertex.push_back(p[0]); float b = p - key;
vertex.push_back(p[1]+g_moveScale*move);
vertex.push_back(p[2]); std::vector<float> vertex;
p += 3; vertex.reserve(nverts*3);
// if (g_adaptive == false) for (int vert = 0; vert<nverts; ++vert) {
{
vertex.push_back(n[0]); float const * p0 = &g_animPositions[key][vert*3],
vertex.push_back(n[1]); * p1 = &g_animPositions[(key+1)%nkeys][vert*3];
vertex.push_back(n[2]);
n += 3; for (int i=0; i<3; ++i, ++p0, ++p1) {
vertex.push_back(*p0*(1.0f-b) + *p1*b);
}
// adaptive patches don't need normals, but we do not have an
// an easy shader variant with positions only
vertex.push_back(0.0f);
vertex.push_back(0.0f);
vertex.push_back(0.0f);
} }
}
g_mesh->UpdateVertexBuffer(&vertex[0], 0, nverts); g_mesh->UpdateVertexBuffer(&vertex[0], 0, nverts);
} else {
std::vector<float> vertex;
vertex.reserve(nverts*6);
const float *p = &g_positions[0];
const float *n = &g_normals[0];
for (int i = 0; i < nverts; ++i) {
float move = g_size*0.005f*cosf(p[0]*100/g_size+g_frame*0.01f);
vertex.push_back(p[0]);
vertex.push_back(p[1]+g_moveScale*move);
vertex.push_back(p[2]);
p += 3;
// if (g_adaptive == false)
{
vertex.push_back(n[0]);
vertex.push_back(n[1]);
vertex.push_back(n[2]);
n += 3;
}
}
g_mesh->UpdateVertexBuffer(&vertex[0], 0, nverts);
}
Stopwatch s; Stopwatch s;
s.Start(); s.Start();
@ -371,6 +458,7 @@ createPTexGeo(PtexTexture * r) {
} }
} }
g_size=0.0f;
for (int j = 0; j < 3; ++j) { for (int j = 0; j < 3; ++j) {
g_center[j] = (min[j] + max[j]) * 0.5f; g_center[j] = (min[j] + max[j]) * 0.5f;
g_size += (max[j]-min[j])*(max[j]-min[j]); g_size += (max[j]-min[j])*(max[j]-min[j]);
@ -644,7 +732,7 @@ ShaderCache g_shaderCache;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
D3D11PtexMipmapTexture * D3D11PtexMipmapTexture *
createPtex(const char *filename) { createPtex(const char *filename, int memLimit) {
Ptex::String ptexError; Ptex::String ptexError;
printf("Loading ptex : %s\n", filename); printf("Loading ptex : %s\n", filename);
@ -663,8 +751,11 @@ createPtex(const char *filename) {
printf("Error in reading %s\n", filename); printf("Error in reading %s\n", filename);
exit(1); exit(1);
} }
size_t targetMemory = memLimit * 1024 * 1024; // MB
D3D11PtexMipmapTexture *osdPtex = D3D11PtexMipmapTexture::Create( D3D11PtexMipmapTexture *osdPtex = D3D11PtexMipmapTexture::Create(
g_pd3dDeviceContext, ptex, g_maxMipmapLevels); g_pd3dDeviceContext, ptex, g_maxMipmapLevels, targetMemory);
ptex->release(); ptex->release();
@ -689,7 +780,7 @@ createOsdMesh(int level, int kernel) {
// generate Hbr representation from ptex // generate Hbr representation from ptex
Shape * shape = createPTexGeo(ptexColor); Shape * shape = createPTexGeo(ptexColor);
if (not shape) { if (!shape) {
return; return;
} }
@ -726,7 +817,7 @@ createOsdMesh(int level, int kernel) {
g_mesh = NULL; g_mesh = NULL;
// Adaptive refinement currently supported only for catmull-clark scheme // Adaptive refinement currently supported only for catmull-clark scheme
bool doAdaptive = (g_adaptive != 0 and g_scheme == 0); bool doAdaptive = (g_adaptive != 0 && g_scheme == 0);
OpenSubdiv::Osd::MeshBitset bits; OpenSubdiv::Osd::MeshBitset bits;
bits.set(OpenSubdiv::Osd::MeshAdaptive, doAdaptive); bits.set(OpenSubdiv::Osd::MeshAdaptive, doAdaptive);
@ -835,6 +926,7 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
float ModelViewMatrix[16]; float ModelViewMatrix[16];
float ProjectionMatrix[16]; float ProjectionMatrix[16];
float ModelViewProjectionMatrix[16]; float ModelViewProjectionMatrix[16];
float ModelViewInverseMatrix[16];
}; };
if (! g_pcbPerFrame) { if (! g_pcbPerFrame) {
@ -861,9 +953,12 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
translate(pData->ModelViewMatrix, -g_center[0], -g_center[1], -g_center[2]); translate(pData->ModelViewMatrix, -g_center[0], -g_center[1], -g_center[2]);
identity(pData->ProjectionMatrix); identity(pData->ProjectionMatrix);
perspective(pData->ProjectionMatrix, 45.0, aspect, 0.01f, 500.0); perspective(pData->ProjectionMatrix, 45.0, aspect, g_size*0.001f, g_size+g_dolly);
multMatrix(pData->ModelViewProjectionMatrix, pData->ModelViewMatrix, pData->ProjectionMatrix); multMatrix(pData->ModelViewProjectionMatrix,
pData->ModelViewMatrix,
pData->ProjectionMatrix);
inverseMatrix(pData->ModelViewInverseMatrix,
pData->ModelViewMatrix);
g_pd3dDeviceContext->Unmap( g_pcbPerFrame, 0 ); g_pd3dDeviceContext->Unmap( g_pcbPerFrame, 0 );
} }
@ -971,6 +1066,19 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
g_pd3dDeviceContext->PSSetShaderResources(10, 1, g_osdPTexSpecular->GetTexelsSRV()); g_pd3dDeviceContext->PSSetShaderResources(10, 1, g_osdPTexSpecular->GetTexelsSRV());
g_pd3dDeviceContext->PSSetShaderResources(11, 1, g_osdPTexSpecular->GetLayoutSRV()); g_pd3dDeviceContext->PSSetShaderResources(11, 1, g_osdPTexSpecular->GetLayoutSRV());
} }
if (g_ibl) {
if (g_diffuseEnvironmentMap) {
g_pd3dDeviceContext->PSSetShaderResources(12, 1, &g_diffuseEnvironmentSRV);
}
if (g_specularEnvironmentMap) {
g_pd3dDeviceContext->PSSetShaderResources(13, 1, &g_specularEnvironmentSRV);
}
assert(g_iblSampler);
g_pd3dDeviceContext->PSSetSamplers(0, 1, &g_iblSampler);
}
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -1061,27 +1169,100 @@ drawModel() {
static void static void
display() { display() {
Stopwatch s;
s.Start();
float color[4] = {0.006f, 0.006f, 0.006f, 1.0f}; float color[4] = {0.006f, 0.006f, 0.006f, 1.0f};
g_pd3dDeviceContext->ClearRenderTargetView(g_pSwapChainRTV, color); g_pd3dDeviceContext->ClearRenderTargetView(g_pSwapChainRTV, color);
// Clear the depth buffer. // Clear the depth buffer.
g_pd3dDeviceContext->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0); g_pd3dDeviceContext->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
if (g_ibl && g_sky) {
float modelView[16], projection[16], mvp[16];
double aspect = g_width/(double)g_height;
identity(modelView);
rotate(modelView, g_rotate[1], 1, 0, 0);
rotate(modelView, g_rotate[0], 0, 1, 0);
perspective(projection, 45.0f, (float)aspect, g_size*0.001f, g_size+g_dolly);
multMatrix(mvp, modelView, projection);
g_sky->Draw(g_pd3dDeviceContext, mvp);
}
// this query can be slow : comment out #define to turn off
#define PIPELINE_STATISTICS
#ifdef PIPELINE_STATISTICS
g_pd3dDeviceContext->Begin(g_pipelineStatsQuery);
#endif // PIPELINE_STATISTICS
g_pd3dDeviceContext->OMSetDepthStencilState(g_pDepthStencilState, 1); g_pd3dDeviceContext->OMSetDepthStencilState(g_pDepthStencilState, 1);
g_pd3dDeviceContext->RSSetState(g_pRasterizerState); g_pd3dDeviceContext->RSSetState(g_pRasterizerState);
drawModel(); drawModel();
#ifdef PIPELINE_STATISTICS
g_pd3dDeviceContext->End(g_pipelineStatsQuery);
#endif // PIPELINE_STATISTICS
s.Stop();
float drawCpuTime = float(s.GetElapsed() * 1000.0f);
int timeElapsed = 0;
// XXXX TODO GPU cycles elapsed query
float drawGpuTime = timeElapsed / 1000.0f / 1000.0f;
UINT64 numPrimsGenerated = 0;
#ifdef PIPELINE_STATISTICS
D3D11_QUERY_DATA_PIPELINE_STATISTICS pipelineStats;
ZeroMemory(&pipelineStats, sizeof(pipelineStats));
while (S_OK != g_pd3dDeviceContext->GetData(g_pipelineStatsQuery, &pipelineStats, g_pipelineStatsQuery->GetDataSize(), 0));
numPrimsGenerated = pipelineStats.GSPrimitives;
#endif // PIPELINE_STATISTICS
if (g_hud->IsVisible()) {
g_fpsTimer.Stop(); g_fpsTimer.Stop();
double fps = 1.0/g_fpsTimer.GetElapsed(); float elapsed = (float)g_fpsTimer.GetElapsed();
if (!g_freeze)
g_animTime += elapsed;
g_fpsTimer.Start(); g_fpsTimer.Start();
g_hud->DrawString(10, -100, "# of Vertices = %d", g_mesh->GetNumVertices());
g_hud->DrawString(10, -60, "GPU TIME = %.3f ms", g_gpuTime); if (g_hud->IsVisible()) {
g_hud->DrawString(10, -40, "CPU TIME = %.3f ms", g_cpuTime);
g_hud->DrawString(10, -20, "FPS = %3.1f", fps); double fps = 1.0/elapsed;
// Avereage fps over a defined number of time samples for
// easier reading in the HUD
g_fpsTimeSamples[g_currentFpsTimeSample++] = float(fps);
if (g_currentFpsTimeSample >= NUM_FPS_TIME_SAMPLES)
g_currentFpsTimeSample = 0;
double averageFps = 0;
for (int i = 0; i < NUM_FPS_TIME_SAMPLES; ++i) {
averageFps += g_fpsTimeSamples[i]/(float)NUM_FPS_TIME_SAMPLES;
}
g_hud->DrawString(10, -220, "Ptex memory use : %.1f mb", g_ptexMemoryUsage/1024.0/1024.0);
g_hud->DrawString(10, -180, "Tess level (+/-): %d", g_tessLevel);
#ifdef PIPELINE_STATISTICS
if (numPrimsGenerated > 1000000) {
g_hud->DrawString(10, -160, "Primitives : %3.1f million",
(float)numPrimsGenerated/1000000.0);
} else if (numPrimsGenerated > 1000) {
g_hud->DrawString(10, -160, "Primitives : %3.1f thousand",
(float)numPrimsGenerated/1000.0);
} else {
g_hud->DrawString(10, -160, "Primitives : %d", numPrimsGenerated);
}
#endif // PIPELINE_STATISTICS
g_hud->DrawString(10, -140, "Vertices : %d", g_mesh->GetNumVertices());
g_hud->DrawString(10, -120, "Scheme : %s", g_scheme == 0 ? "CATMARK" : "LOOP");
g_hud->DrawString(10, -100, "GPU Kernel : %.3f ms", g_gpuTime);
g_hud->DrawString(10, -80, "CPU Kernel : %.3f ms", g_cpuTime);
g_hud->DrawString(10, -60, "GPU Draw : %.3f ms", drawGpuTime);
g_hud->DrawString(10, -40, "CPU Draw : %.3f ms", drawCpuTime);
g_hud->DrawString(10, -20, "FPS : %3.1f", fps);
} }
g_hud->Flush(); g_hud->Flush();
@ -1120,7 +1301,7 @@ motion(int x, int y) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && g_mbutton[1] && !g_mbutton[2]) or } else if ((g_mbutton[0] && g_mbutton[1] && !g_mbutton[2]) ||
(!g_mbutton[0] && !g_mbutton[1] && g_mbutton[2])) { (!g_mbutton[0] && !g_mbutton[1] && g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1191,7 +1372,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL #ifdef OPENSUBDIV_HAS_OPENCL
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
if (g_clDeviceContext.Initialize(g_pd3dDeviceContext) == false) { if (g_clDeviceContext.Initialize(g_pd3dDeviceContext) == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
exit(1); exit(1);
@ -1199,7 +1380,7 @@ callbackKernel(int k) {
} }
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize(g_pd3dDevice) == false) { if (g_cudaDeviceContext.Initialize(g_pd3dDevice) == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1293,50 +1474,77 @@ initHUD() {
g_hud = new D3D11hud(g_pd3dDeviceContext); g_hud = new D3D11hud(g_pd3dDeviceContext);
g_hud->Init(g_width, g_height); g_hud->Init(g_width, g_height);
g_hud->AddRadioButton(0, "CPU (K)", true, 10, 10, callbackKernel, kCPU, 'K');
#ifdef OPENSUBDIV_HAS_OPENMP if (g_osdPTexOcclusion != NULL) {
g_hud->AddRadioButton(0, "OPENMP", false, 10, 30, callbackKernel, kOPENMP, 'K'); g_hud->AddCheckBox("Ambient Occlusion (A)", g_occlusion,
#endif -200, 570, callbackCheckBox, HUD_CB_DISPLAY_OCCLUSION, 'a');
#ifdef OPENSUBDIV_HAS_TBB
g_hud->AddRadioButton(0, "TBB", false, 10, 50, callbackKernel, kTBB, 'K');
#endif
#ifdef OPENSUBDIV_HAS_CUDA
g_hud->AddRadioButton(0, "CUDA", false, 10, 70, callbackKernel, kCUDA, 'K');
#endif
#ifdef OPENSUBDIV_HAS_OPENCL
if (CLDeviceContext::HAS_CL_VERSION_1_1()) {
g_hud->AddRadioButton(0, "OPENCL", false, 10, 90, callbackKernel, kCL, 'K');
} }
#endif if (g_osdPTexSpecular != NULL)
g_hud->AddRadioButton(0, "DirectCompute", false, 10, 110, callbackKernel, kDirectCompute, 'K'); g_hud->AddCheckBox("Specular (S)", g_specular,
-200, 590, callbackCheckBox, HUD_CB_DISPLAY_SPECULAR, 's');
if (g_diffuseEnvironmentMap || g_diffuseEnvironmentMap) {
g_hud->AddCheckBox("IBL (I)", g_ibl,
-200, 610, callbackCheckBox, HUD_CB_IBL, 'i');
}
g_hud->AddCheckBox("Animate vertices (M)", g_moveScale != 0.0,
10, 30, callbackCheckBox, HUD_CB_ANIMATE_VERTICES, 'm');
g_hud->AddCheckBox("Screen space LOD (V)", g_screenSpaceTess,
10, 50, callbackCheckBox, HUD_CB_VIEW_LOD, 'v');
g_hud->AddCheckBox("Fractional spacing (T)", g_fractionalSpacing,
10, 70, callbackCheckBox, HUD_CB_FRACTIONAL_SPACING, 't');
g_hud->AddCheckBox("Frustum Patch Culling (B)", g_patchCull,
10, 90, callbackCheckBox, HUD_CB_PATCH_CULL, 'b');
g_hud->AddCheckBox("Bloom (Y)", g_bloom,
10, 110, callbackCheckBox, HUD_CB_BLOOM, 'y');
g_hud->AddCheckBox("Freeze (spc)", g_freeze,
10, 130, callbackCheckBox, HUD_CB_FREEZE, ' ');
g_hud->AddRadioButton(HUD_RB_SCHEME, "CATMARK", true, 10, 190, callbackScheme, 0);
g_hud->AddRadioButton(HUD_RB_SCHEME, "BILINEAR", false, 10, 210, callbackScheme, 1);
g_hud->AddCheckBox("Adaptive (`)", g_adaptive, g_hud->AddCheckBox("Adaptive (`)", g_adaptive,
10, 150, callbackCheckBox, HUD_CB_ADAPTIVE, '`'); 10, 300, callbackCheckBox, HUD_CB_ADAPTIVE, '`');
g_hud->AddRadioButton(HUD_RB_SCHEME, "CATMARK", true, 10, 190, callbackScheme, 0, 's');
g_hud->AddRadioButton(HUD_RB_SCHEME, "BILINEAR", false, 10, 210, callbackScheme, 1, 's');
for (int i = 1; i < 8; ++i) { for (int i = 1; i < 8; ++i) {
char level[16]; char level[16];
sprintf(level, "Lv. %d", i); sprintf(level, "Lv. %d", i);
g_hud->AddRadioButton(HUD_RB_LEVEL, level, i == g_level, g_hud->AddRadioButton(HUD_RB_LEVEL, level, i == g_level,
10, 220+i*20, callbackLevel, i, '0'+i); 10, 320+i*20, callbackLevel, i, '0'+i);
} }
g_hud->AddRadioButton(HUD_RB_WIRE, "Wire (W)", (g_wire == DISPLAY_WIRE), int compute_pulldown = g_hud->AddPullDown("Compute (K)", 475, 10, 300, callbackKernel, 'k');
100, 10, callbackWireframe, 0, 'w'); g_hud->AddPullDownButton(compute_pulldown, "CPU (K)", kCPU);
g_hud->AddRadioButton(HUD_RB_WIRE, "Shaded", (g_wire == DISPLAY_SHADED), #ifdef OPENSUBDIV_HAS_OPENMP
100, 30, callbackWireframe, 1, 'w'); g_hud->AddPullDownButton(compute_pulldown, "OPENMP", kOPENMP);
g_hud->AddRadioButton(HUD_RB_WIRE, "Wire on Shaded", (g_wire == DISPLAY_WIRE_ON_SHADED), #endif
100, 50, callbackWireframe, 2, 'w'); #ifdef OPENSUBDIV_HAS_TBB
g_hud->AddPullDownButton(compute_pulldown, "TBB", kTBB);
#endif
#ifdef OPENSUBDIV_HAS_CUDA
g_hud->AddPullDownButton(compute_pulldown, "CUDA", kCUDA);
#endif
#ifdef OPENSUBDIV_HAS_OPENCL
if (CLDeviceContext::HAS_CL_VERSION_1_1()) {
g_hud->AddPullDownButton(compute_pulldown, "OPENCL", kCL);
}
#endif
g_hud->AddPullDownButton(compute_pulldown, "DirectCompute", kDirectCompute);
int shading_pulldown = g_hud->AddPullDown("Shading (W)", 250, 10, 250, callbackWireframe, 'w');
g_hud->AddPullDownButton(shading_pulldown, "Wire", DISPLAY_WIRE, g_wire==DISPLAY_WIRE);
g_hud->AddPullDownButton(shading_pulldown, "Shaded", DISPLAY_SHADED, g_wire==DISPLAY_SHADED);
g_hud->AddPullDownButton(shading_pulldown, "Wire+Shaded", DISPLAY_WIRE_ON_SHADED, g_wire==DISPLAY_WIRE_ON_SHADED);
g_hud->AddLabel("Color (C)", -200, 10); g_hud->AddLabel("Color (C)", -200, 10);
g_hud->AddRadioButton(HUD_RB_COLOR, "None", (g_color == COLOR_NONE), g_hud->AddRadioButton(HUD_RB_COLOR, "None", (g_color == COLOR_NONE),
-200, 30, callbackColor, COLOR_NONE, 'c'); -200, 30, callbackColor, COLOR_NONE, 'c');
g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex Nearest", (g_color == COLOR_PTEX_NEAREST), g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex Nearest", (g_color == COLOR_PTEX_NEAREST),
-200, 50, callbackColor, COLOR_PTEX_NEAREST, 'c'); -200, 50, callbackColor, COLOR_PTEX_NEAREST, 'c');
g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex HW bilinear", (g_color == COLOR_PTEX_HW_BILINEAR), // Commented out : we need to add a texture sampler state to make this work
-200, 70, callbackColor, COLOR_PTEX_HW_BILINEAR, 'c'); //g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex HW bilinear", (g_color == COLOR_PTEX_HW_BILINEAR),
// -200, 70, callbackColor, COLOR_PTEX_HW_BILINEAR, 'c');
g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex bilinear", (g_color == COLOR_PTEX_BILINEAR), g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex bilinear", (g_color == COLOR_PTEX_BILINEAR),
-200, 90, callbackColor, COLOR_PTEX_BILINEAR, 'c'); -200, 90, callbackColor, COLOR_PTEX_BILINEAR, 'c');
g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex biquadratic", (g_color == COLOR_PTEX_BIQUADRATIC), g_hud->AddRadioButton(HUD_RB_COLOR, "Ptex biquadratic", (g_color == COLOR_PTEX_BIQUADRATIC),
@ -1353,9 +1561,10 @@ initHUD() {
g_hud->AddRadioButton(HUD_RB_DISPLACEMENT, "None", g_hud->AddRadioButton(HUD_RB_DISPLACEMENT, "None",
(g_displacement == DISPLACEMENT_NONE), (g_displacement == DISPLACEMENT_NONE),
-200, 220, callbackDisplacement, DISPLACEMENT_NONE, 'd'); -200, 220, callbackDisplacement, DISPLACEMENT_NONE, 'd');
g_hud->AddRadioButton(HUD_RB_DISPLACEMENT, "HW bilinear", // Commented out : we need to add a texture sampler state to make this work
(g_displacement == DISPLACEMENT_HW_BILINEAR), //g_hud->AddRadioButton(HUD_RB_DISPLACEMENT, "HW bilinear",
-200, 240, callbackDisplacement, DISPLACEMENT_HW_BILINEAR, 'd'); // (g_displacement == DISPLACEMENT_HW_BILINEAR),
// -200, 240, callbackDisplacement, DISPLACEMENT_HW_BILINEAR, 'd');
g_hud->AddRadioButton(HUD_RB_DISPLACEMENT, "Bilinear", g_hud->AddRadioButton(HUD_RB_DISPLACEMENT, "Bilinear",
(g_displacement == DISPLACEMENT_BILINEAR), (g_displacement == DISPLACEMENT_BILINEAR),
-200, 260, callbackDisplacement, DISPLACEMENT_BILINEAR, 'd'); -200, 260, callbackDisplacement, DISPLACEMENT_BILINEAR, 'd');
@ -1391,24 +1600,6 @@ initHUD() {
g_hud->AddCheckBox("Seamless Mipmap", g_seamless, g_hud->AddCheckBox("Seamless Mipmap", g_seamless,
-200, 530, callbackCheckBox, HUD_CB_SEAMLESS_MIPMAP, 'j'); -200, 530, callbackCheckBox, HUD_CB_SEAMLESS_MIPMAP, 'j');
if (g_osdPTexOcclusion != NULL) {
g_hud->AddCheckBox("Ambient Occlusion (A)", g_occlusion,
250, 10, callbackCheckBox, HUD_CB_DISPLAY_OCCLUSION, 'a');
}
if (g_osdPTexSpecular != NULL)
g_hud->AddCheckBox("Specular (S)", g_specular,
250, 30, callbackCheckBox, HUD_CB_DISPLAY_SPECULAR, 's');
g_hud->AddCheckBox("Animate vertices (M)", g_moveScale != 0.0,
450, 10, callbackCheckBox, HUD_CB_ANIMATE_VERTICES, 'm');
g_hud->AddCheckBox("Screen space LOD (V)", g_screenSpaceTess,
450, 30, callbackCheckBox, HUD_CB_VIEW_LOD, 'v');
g_hud->AddCheckBox("Fractional spacing (T)", g_fractionalSpacing,
450, 50, callbackCheckBox, HUD_CB_FRACTIONAL_SPACING, 't');
g_hud->AddCheckBox("Frustum Patch Culling (B)", g_patchCull,
450, 70, callbackCheckBox, HUD_CB_PATCH_CULL, 'b');
g_hud->AddCheckBox("Freeze (spc)", g_freeze,
450, 90, callbackCheckBox, HUD_CB_FREEZE, ' ');
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -1423,9 +1614,18 @@ initD3D11(HWND hWnd) {
UINT numDriverTypes = ARRAYSIZE(driverTypes); UINT numDriverTypes = ARRAYSIZE(driverTypes);
int width = g_width,
height = g_height;
if (g_fullscreen) {
HWND const desktop = GetDesktopWindow();
RECT rect;
GetWindowRect(desktop, &rect);
width = (int)rect.right;
height = (int)rect.bottom;
}
DXGI_SWAP_CHAIN_DESC hDXGISwapChainDesc; DXGI_SWAP_CHAIN_DESC hDXGISwapChainDesc;
hDXGISwapChainDesc.BufferDesc.Width = g_width; hDXGISwapChainDesc.BufferDesc.Width = width;
hDXGISwapChainDesc.BufferDesc.Height = g_height; hDXGISwapChainDesc.BufferDesc.Height = height;
hDXGISwapChainDesc.BufferDesc.RefreshRate.Numerator = 0; hDXGISwapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
hDXGISwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; hDXGISwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
hDXGISwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; hDXGISwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
@ -1436,7 +1636,7 @@ initD3D11(HWND hWnd) {
hDXGISwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; hDXGISwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
hDXGISwapChainDesc.BufferCount = 1; hDXGISwapChainDesc.BufferCount = 1;
hDXGISwapChainDesc.OutputWindow = hWnd; hDXGISwapChainDesc.OutputWindow = hWnd;
hDXGISwapChainDesc.Windowed = TRUE; hDXGISwapChainDesc.Windowed = !g_fullscreen;
hDXGISwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; hDXGISwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
hDXGISwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; hDXGISwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
@ -1449,7 +1649,7 @@ initD3D11(HWND hWnd) {
unsigned int deviceFlags = 0; unsigned int deviceFlags = 0;
#ifndef NDEBUG #ifndef NDEBUG
// XXX: this is problematic in some environments. // XXX: this is problematic in some environments.
// deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; // deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif #endif
hr = D3D11CreateDeviceAndSwapChain(NULL, hr = D3D11CreateDeviceAndSwapChain(NULL,
hDriverType, NULL, deviceFlags, NULL, 0, hDriverType, NULL, deviceFlags, NULL, 0,
@ -1552,6 +1752,14 @@ initD3D11(HWND hWnd) {
g_pd3dDevice->CreateDepthStencilState(&depthStencilDesc, &g_pDepthStencilState); g_pd3dDevice->CreateDepthStencilState(&depthStencilDesc, &g_pDepthStencilState);
assert(g_pDepthStencilState); assert(g_pDepthStencilState);
#ifdef PIPELINE_STATISTICS
// Create pipeline statistics query
D3D11_QUERY_DESC queryDesc;
ZeroMemory(&queryDesc, sizeof(D3D11_QUERY_DESC));
queryDesc.Query = D3D11_QUERY_PIPELINE_STATISTICS;
g_pd3dDevice->CreateQuery(&queryDesc, &g_pipelineStatsQuery);
#endif // PIPELINE_STATISTICS
return true; return true;
} }
@ -1694,6 +1902,23 @@ tokenize(std::string const & src) {
return result; return result;
} }
//------------------------------------------------------------------------------
void usage(const char *program) {
printf("Usage: %s [options] <color.ptx> [<displacement.ptx>] [occlusion.ptx>] "
"[specular.ptx] [pose.obj]...\n", program);
printf("Options: -l level : subdivision level\n");
printf(" -c count : frame count until exit (for profiler)\n");
printf(" -d <diffseEnvMap.hdr> : diffuse environment map for IBL\n");
printf(" -e <specularEnvMap.hdr> : specular environment map for IBL\n");
printf(" -s <shaderfile.glsl> : custom shader file\n");
printf(" -y : Y-up model\n");
printf(" -m level : max mimmap level (default=10)\n");
printf(" -x <ptex limit MB> : ptex target memory size\n");
printf(" --disp <scale> : Displacment scale\n");
}
//------------------------------------------------------------------------------
int WINAPI int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
@ -1735,6 +1960,7 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
const char *diffuseEnvironmentMap = NULL, *specularEnvironmentMap = NULL; const char *diffuseEnvironmentMap = NULL, *specularEnvironmentMap = NULL;
const char *colorFilename = NULL, *displacementFilename = NULL, const char *colorFilename = NULL, *displacementFilename = NULL,
*occlusionFilename = NULL, *specularFilename = NULL; *occlusionFilename = NULL, *specularFilename = NULL;
int memLimit;
for (int i = 0; i < (int)argv.size(); ++i) { for (int i = 0; i < (int)argv.size(); ++i) {
if (strstr(argv[i].c_str(), ".obj")) if (strstr(argv[i].c_str(), ".obj"))
@ -1747,10 +1973,14 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
diffuseEnvironmentMap = argv[++i].c_str(); diffuseEnvironmentMap = argv[++i].c_str();
else if (argv[i] == "-e") else if (argv[i] == "-e")
specularEnvironmentMap = argv[++i].c_str(); specularEnvironmentMap = argv[++i].c_str();
else if (argv[i] == "-f")
g_fullscreen = true;
else if (argv[i] == "-y") else if (argv[i] == "-y")
g_yup = true; g_yup = true;
else if (argv[i] == "-m") else if (argv[i] == "-m")
g_maxMipmapLevels = atoi(argv[++i].c_str()); g_maxMipmapLevels = atoi(argv[++i].c_str());
else if (argv[i] == "-x")
memLimit = atoi(argv[++i].c_str());
else if (argv[i] == "--disp") else if (argv[i] == "--disp")
g_displacementScale = (float)atof(argv[++i].c_str()); g_displacementScale = (float)atof(argv[++i].c_str());
else if (colorFilename == NULL) else if (colorFilename == NULL)
@ -1772,7 +2002,7 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
g_ptexColorFilename = colorFilename; g_ptexColorFilename = colorFilename;
if (g_ptexColorFilename == NULL) { if (g_ptexColorFilename == NULL) {
printf("Usage: \n"); usage(argv[0].c_str());
return 1; return 1;
} }
@ -1781,13 +2011,98 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
createOsdMesh(g_level, g_kernel); createOsdMesh(g_level, g_kernel);
// load ptex files // load ptex files
g_osdPTexImage = createPtex(colorFilename); g_osdPTexImage = createPtex(colorFilename, memLimit);
if (displacementFilename) if (displacementFilename)
g_osdPTexDisplacement = createPtex(displacementFilename); g_osdPTexDisplacement = createPtex(displacementFilename, memLimit);
if (occlusionFilename) if (occlusionFilename)
g_osdPTexOcclusion = createPtex(occlusionFilename); g_osdPTexOcclusion = createPtex(occlusionFilename, memLimit);
if (specularFilename) if (specularFilename)
g_osdPTexSpecular = createPtex(specularFilename); g_osdPTexSpecular = createPtex(specularFilename, memLimit);
g_ptexMemoryUsage =
(g_osdPTexImage ? g_osdPTexImage->GetMemoryUsage() : 0)
+ (g_osdPTexDisplacement ? g_osdPTexDisplacement->GetMemoryUsage() : 0)
+ (g_osdPTexOcclusion ? g_osdPTexOcclusion->GetMemoryUsage() : 0)
+ (g_osdPTexSpecular ? g_osdPTexSpecular->GetMemoryUsage() : 0);
// load animation obj sequences (optional)
if (!animobjs.empty()) {
for (int i = 0; i < (int)animobjs.size(); ++i) {
std::ifstream ifs(animobjs[i].c_str());
if (ifs) {
std::stringstream ss;
ss << ifs.rdbuf();
ifs.close();
printf("Reading %s\r", animobjs[i].c_str());
std::string str = ss.str();
Shape *shape = Shape::parseObj(str.c_str(), kCatmark);
if (shape->verts.size() != g_positions.size()) {
printf("Error: vertex count doesn't match.\n");
goto end;
}
g_animPositions.push_back(shape->verts);
delete shape;
} else {
printf("Error in reading %s\n", animobjs[i].c_str());
goto end;
}
}
printf("\n");
}
// IBL textures
if (diffuseEnvironmentMap) {
g_diffuseEnvironmentMap =
createHDRTexture(g_pd3dDevice, diffuseEnvironmentMap);
assert(g_diffuseEnvironmentMap);
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
g_pd3dDevice->CreateShaderResourceView(g_diffuseEnvironmentMap, &srvDesc, &g_diffuseEnvironmentSRV);
assert(g_diffuseEnvironmentSRV);
}
if (specularEnvironmentMap) {
g_specularEnvironmentMap =
createHDRTexture(g_pd3dDevice, specularEnvironmentMap);
assert(g_specularEnvironmentMap);
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
g_pd3dDevice->CreateShaderResourceView(g_specularEnvironmentMap, &srvDesc, &g_specularEnvironmentSRV);
assert(g_specularEnvironmentSRV);
}
if (g_diffuseEnvironmentMap || g_specularEnvironmentMap) {
// texture sampler
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc, sizeof(samplerDesc));
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
samplerDesc.AddressU = samplerDesc.AddressV = samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
samplerDesc.BorderColor[0] = samplerDesc.BorderColor[1] = samplerDesc.BorderColor[2] = samplerDesc.BorderColor[3] = 0.0f;
g_pd3dDevice->CreateSamplerState(&samplerDesc, &g_iblSampler);
g_sky = new Sky(g_pd3dDevice, g_specularEnvironmentMap!=0 ?
g_specularEnvironmentMap : g_diffuseEnvironmentMap);
}
initHUD(); initHUD();
@ -1803,7 +2118,7 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
TranslateMessage(&msg); TranslateMessage(&msg);
DispatchMessage(&msg); DispatchMessage(&msg);
} }
if (not g_freeze) if (!g_freeze)
g_frame++; g_frame++;
updateGeom(); updateGeom();

View File

@ -30,6 +30,7 @@ cbuffer Transform : register( b0 ) {
float4x4 ModelViewMatrix; float4x4 ModelViewMatrix;
float4x4 ProjectionMatrix; float4x4 ProjectionMatrix;
float4x4 ModelViewProjectionMatrix; float4x4 ModelViewProjectionMatrix;
float4x4 ModelViewInverseMatrix;
}; };
cbuffer Tessellation : register( b1 ) { cbuffer Tessellation : register( b1 ) {
@ -289,6 +290,31 @@ void gs_main( triangle OutputVertex input[3],
#endif #endif
// ---------------------------------------------------------------------------
// IBL lighting
// ---------------------------------------------------------------------------
Texture2D diffuseEnvironmentMap : register(t12);
Texture2D specularEnvironmentMap : register(t13);
SamplerState iblSampler : register(s0);
#define M_PI 3.14159265358
float4
gamma(float4 value, float g) {
return float4(pow(value.xyz, float3(g,g,g)), 1);
}
float4
getEnvironmentHDR(Texture2D tx, SamplerState sm, float3 dir)
{
dir = mul(ModelViewInverseMatrix, float4(dir, 0)).xyz;
float2 uv = float2((atan2(dir.x,dir.z)/M_PI+1)*0.5, (1-dir.y)*0.5);
return tx.Sample(sm, uv);
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Lighting // Lighting
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@ -559,8 +585,38 @@ ps_main(in OutputVertex input,
#else #else
float specular = 1.0; float specular = 1.0;
#endif #endif
// ------------ lighting --------------- // ------------ lighting ---------------
#ifdef USE_IBL
// non-plausible BRDF
float4 a = float4(0, 0, 0, 1); //ambientColor;
float4 d = getEnvironmentHDR(diffuseEnvironmentMap, iblSampler, normal);
float3 eye = normalize(input.position.xyz - float3(0,0,0));
float3 r = reflect(eye, normal);
float4 s = getEnvironmentHDR(specularEnvironmentMap, iblSampler, r);
const float fresnelBias = 0.01;
const float fresnelScale = 1.0;
const float fresnelPower = 3.5;
float F = fresnelBias + fresnelScale * pow(1.0+dot(normal,eye), fresnelPower);
// Geometric attenuation term (
float NoV = dot(normal, -eye);
float alpha = 0.75 * 0.75; // roughness ^ 2
float k = alpha * 0.5;
float G = NoV/(NoV*(1-k)+k);
a *= (1-occ);
d *= (1-occ);
s *= min(specular, (1-occ)) * (F*G);
float4 Cf = (a+d)*texColor*(1-F)/M_PI + s;
//Cf = gamma(Cf, 2.2);
#else
float4 Cf = lighting(texColor, input.position.xyz, normal, occ); float4 Cf = lighting(texColor, input.position.xyz, normal, occ);
#endif
// ------------ wireframe --------------- // ------------ wireframe ---------------
outColor = edgeColor(Cf, input.edgeDistance); outColor = edgeColor(Cf, input.edgeDistance);

View File

@ -0,0 +1,257 @@
//
// Copyright 2013 Nvidia
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "./sky.h"
#include "../common/d3d11Utils.h"
#include <cassert>
#include <vector>
static const char *g_skyShaderSource =
#include "skyshader.gen.h"
;
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
// shader constants
__declspec(align(16)) struct CB_CONSTANTS {
float ModelViewMatrix[16];
};
Sky::Sky(ID3D11Device * device, ID3D11Texture2D * environmentMap) :
numIndices(0),
vertexShader(0),
pixelShader(0),
shaderConstants(0),
texture(environmentMap), // we do not own this - we do not release it !
textureSRV(0),
textureSS(0),
inputLayout(0),
rasterizerState(0),
depthStencilState(0),
sphere(0),
sphereIndices(0) {
initialize(device);
}
Sky::~Sky() {
SAFE_RELEASE(vertexShader);
SAFE_RELEASE(pixelShader);
SAFE_RELEASE(shaderConstants);
SAFE_RELEASE(inputLayout);
SAFE_RELEASE(rasterizerState);
SAFE_RELEASE(depthStencilState);
SAFE_RELEASE(textureSS);
SAFE_RELEASE(textureSRV);
SAFE_RELEASE(sphere);
SAFE_RELEASE(sphereIndices);
}
void
Sky::initialize(ID3D11Device * device) {
// compile shaders
ID3DBlob * pVSBlob = D3D11Utils::CompileShader(g_skyShaderSource, "vs_main", "vs_5_0"),
* pPSBlob = D3D11Utils::CompileShader(g_skyShaderSource, "ps_main", "ps_5_0");
assert(pVSBlob && pPSBlob);
device->CreateVertexShader(pVSBlob->GetBufferPointer(),
pVSBlob->GetBufferSize(), NULL, &vertexShader);
assert(vertexShader);
device->CreatePixelShader(pPSBlob->GetBufferPointer(),
pPSBlob->GetBufferSize(), NULL, &pixelShader);
assert(pixelShader);
// VBO layout
D3D11_INPUT_ELEMENT_DESC inputElementDesc[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float)*3, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
device->CreateInputLayout(inputElementDesc, ARRAYSIZE(inputElementDesc),
pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &inputLayout);
assert(inputLayout);
// shader constants
D3D11_BUFFER_DESC cbDesc;
ZeroMemory(&cbDesc, sizeof(cbDesc));
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.MiscFlags = 0;
cbDesc.ByteWidth = sizeof(CB_CONSTANTS);
device->CreateBuffer(&cbDesc, NULL, &shaderConstants);
assert(shaderConstants);
// texture SRV
assert(texture);
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
device->CreateShaderResourceView(texture, &srvDesc, &textureSRV);
assert(textureSRV);
// texture sampler
D3D11_SAMPLER_DESC samplerDesc;
ZeroMemory(&samplerDesc, sizeof(samplerDesc));
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
samplerDesc.AddressU = samplerDesc.AddressV = samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
samplerDesc.BorderColor[0] = samplerDesc.BorderColor[1] = samplerDesc.BorderColor[2] = samplerDesc.BorderColor[3] = 0.0f;
device->CreateSamplerState(&samplerDesc, &textureSS);
// depth stencil state
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
depthStencilDesc.StencilEnable = false;
device->CreateDepthStencilState(&depthStencilDesc, &depthStencilState);
// rasterizer state
D3D11_RASTERIZER_DESC rasDesc;
rasDesc.FillMode = D3D11_FILL_SOLID;
rasDesc.CullMode = D3D11_CULL_NONE;
rasDesc.FrontCounterClockwise = FALSE;
rasDesc.DepthBias = 0;
rasDesc.DepthBiasClamp = 0;
rasDesc.DepthClipEnable = FALSE;
rasDesc.SlopeScaledDepthBias = 0.0f;
rasDesc.ScissorEnable = FALSE;
rasDesc.MultisampleEnable = FALSE;
rasDesc.AntialiasedLineEnable = FALSE;
device->CreateRasterizerState(&rasDesc, &rasterizerState);
assert(rasterizerState);
const int U_DIV = 20,
V_DIV = 20;
std::vector<float> vbo;
std::vector<int> indices;
for (int u = 0; u <= U_DIV; ++u) {
for (int v = 0; v < V_DIV; ++v) {
float s = float(2*M_PI*float(u)/U_DIV);
float t = float(M_PI*float(v)/(V_DIV-1));
vbo.push_back(-sin(t)*sin(s));
vbo.push_back(cos(t));
vbo.push_back(-sin(t)*cos(s));
vbo.push_back(u/float(U_DIV));
vbo.push_back(v/float(V_DIV));
if (v > 0 && u > 0) {
indices.push_back((u-1)*V_DIV+v-1);
indices.push_back(u*V_DIV+v-1);
indices.push_back((u-1)*V_DIV+v);
indices.push_back((u-1)*V_DIV+v);
indices.push_back(u*V_DIV+v-1);
indices.push_back(u*V_DIV+v);
}
}
}
D3D11_BUFFER_DESC bufferDesc;
D3D11_SUBRESOURCE_DATA subData;
// topology indices
ZeroMemory(&bufferDesc, sizeof(bufferDesc));
bufferDesc.ByteWidth = (int)indices.size() * sizeof(int);
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = sizeof(int);
ZeroMemory(&subData, sizeof(subData));
subData.pSysMem = &indices[0];
subData.SysMemPitch = 0;
subData.SysMemSlicePitch = 0;
device->CreateBuffer(&bufferDesc, &subData, &sphereIndices);
assert(sphereIndices);
// VBO
ZeroMemory(&bufferDesc, sizeof(bufferDesc));
bufferDesc.ByteWidth = (int)vbo.size() * sizeof(float);
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
ZeroMemory(&subData, sizeof(subData));
subData.pSysMem = &vbo[0];
device->CreateBuffer(&bufferDesc, &subData, &sphere);
assert(sphere);
numIndices = (int)indices.size();
}
void
Sky::Draw(ID3D11DeviceContext * deviceContext, float const mvp[16]) {
if (vertexShader==0 || pixelShader==0 || shaderConstants==0) return;
if (texture==0 || textureSRV==0 || textureSS==0) return;
if (sphere==0 || sphereIndices==0) return;
// update shader constants
D3D11_MAPPED_SUBRESOURCE MappedResource;
deviceContext->Map(shaderConstants, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource);
CB_CONSTANTS* pData = (CB_CONSTANTS*)MappedResource.pData;
memcpy(pData->ModelViewMatrix, mvp, 16*sizeof(float));
deviceContext->Unmap(shaderConstants, 0);
// draw
deviceContext->RSSetState(rasterizerState);
deviceContext->OMSetDepthStencilState(depthStencilState, 1);
deviceContext->VSSetShader(vertexShader, NULL, 0);
deviceContext->VSSetConstantBuffers(0, 1, &shaderConstants);
deviceContext->PSSetShader(pixelShader, NULL, 0);
deviceContext->PSSetShaderResources(0, 1, &textureSRV);
deviceContext->PSSetSamplers(0, 1, &textureSS);
UINT hStrides = 5*sizeof(float);
UINT hOffsets = 0;
deviceContext->IASetVertexBuffers(0, 1, &sphere, &hStrides, &hOffsets);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->IASetInputLayout(inputLayout);
deviceContext->IASetIndexBuffer(sphereIndices, DXGI_FORMAT_R32_UINT, 0);
deviceContext->DrawIndexed(numIndices, 0, 0);
}

View File

@ -0,0 +1,65 @@
//
// Copyright 2013 Nvidia
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include <D3D11.h>
#include <D3Dcompiler.h>
//
// Draws an environment sphere centered on the camera w/ a texture
//
class Sky {
public:
// Constructor (Sky does not own the texture asset)
Sky(ID3D11Device * device, ID3D11Texture2D * environmentMap);
~Sky();
void Draw(ID3D11DeviceContext * deviceContext, float const mvp[16]);
private:
void initialize(ID3D11Device * device);
private:
int numIndices;
ID3D11VertexShader * vertexShader;
ID3D11PixelShader * pixelShader;
ID3D11Buffer * shaderConstants;
ID3D11InputLayout * inputLayout;
ID3D11RasterizerState * rasterizerState;
ID3D11DepthStencilState * depthStencilState;
ID3D11Texture2D * texture;
ID3D11ShaderResourceView * textureSRV;
ID3D11SamplerState * textureSS;
ID3D11Buffer * sphere;
ID3D11Buffer * sphereIndices;
};

View File

@ -0,0 +1,80 @@
//
// Copyright 2013 Nvidia
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
struct VS_InputVertex {
float3 position : POSITION0;
float2 texCoord : TEXCOORD0;
};
struct VS_OutputVertex {
float4 position : SV_POSITION0;
float2 texCoord : TEXCOORD0;
};
cbuffer Transform : register( b0 ) {
float4x4 ModelViewMatrix;
};
//--------------------------------------------------------------
// sky vertex shader
//--------------------------------------------------------------
void vs_main(in VS_InputVertex input,
out VS_OutputVertex output) {
output.position = mul(ModelViewMatrix, float4(input.position,1));
output.texCoord = input.texCoord;
}
//--------------------------------------------------------------
// sky pixel shader
//--------------------------------------------------------------
struct PS_InputVertex {
float4 position : SV_POSITION0;
float2 texCoord : TEXCOORD0;
};
Texture2D tx : register(t0);
SamplerState sm : register(s0);
float4
gamma(float4 value, float g) {
return float4(pow(value.xyz, float3(g,g,g)), 1);
}
float4
ps_main(in PS_InputVertex input) : SV_Target {
float4 tex = tx.Sample(sm, input.texCoord.xy);
//float4 outColor = gamma(tex,0.4545);
float4 outColor = tex;
return outColor;
}

View File

@ -59,7 +59,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_possibly_cuda_executable(dxViewer WIN32 _add_possibly_cuda_executable(dxViewer "examples" WIN32
"${SOURCE_FILES}" "${SOURCE_FILES}"
"${INC_FILES}" "${INC_FILES}"
$<TARGET_OBJECTS:regression_common_obj> $<TARGET_OBJECTS:regression_common_obj>

View File

@ -292,8 +292,8 @@ createOsdMesh(ShapeDesc const & shapeDesc, int level, int kernel, Scheme scheme=
g_scheme = scheme; g_scheme = scheme;
// Adaptive refinement currently supported only for catmull-clark scheme // Adaptive refinement currently supported only for catmull-clark scheme
bool doAdaptive = (g_adaptive!=0 and g_scheme==kCatmark), bool doAdaptive = (g_adaptive!=0 && g_scheme==kCatmark),
doSingleCreasePatch = (g_singleCreasePatch!=0 and g_scheme==kCatmark); doSingleCreasePatch = (g_singleCreasePatch!=0 && g_scheme==kCatmark);
Osd::MeshBitset bits; Osd::MeshBitset bits;
bits.set(Osd::MeshAdaptive, doAdaptive); bits.set(Osd::MeshAdaptive, doAdaptive);
@ -643,7 +643,7 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
// only legacy gregory needs maxValence and numElements // only legacy gregory needs maxValence and numElements
// neither legacy gregory nor gregory basis need single crease // neither legacy gregory nor gregory basis need single crease
if (patch.GetDescriptor().GetType() == Descriptor::GREGORY or if (patch.GetDescriptor().GetType() == Descriptor::GREGORY ||
patch.GetDescriptor().GetType() == Descriptor::GREGORY_BOUNDARY) { patch.GetDescriptor().GetType() == Descriptor::GREGORY_BOUNDARY) {
int maxValence = g_mesh->GetMaxValence(); int maxValence = g_mesh->GetMaxValence();
int numElements = 6; int numElements = 6;
@ -668,7 +668,7 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
float ModelViewInverseMatrix[16]; float ModelViewInverseMatrix[16];
}; };
if (not g_pcbPerFrame) { if (! g_pcbPerFrame) {
D3D11_BUFFER_DESC cbDesc; D3D11_BUFFER_DESC cbDesc;
ZeroMemory(&cbDesc, sizeof(cbDesc)); ZeroMemory(&cbDesc, sizeof(cbDesc));
cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.Usage = D3D11_USAGE_DYNAMIC;
@ -711,7 +711,7 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
int PrimitiveIdBase; int PrimitiveIdBase;
}; };
if (not g_pcbTessellation) { if (! g_pcbTessellation) {
D3D11_BUFFER_DESC cbDesc; D3D11_BUFFER_DESC cbDesc;
ZeroMemory(&cbDesc, sizeof(cbDesc)); ZeroMemory(&cbDesc, sizeof(cbDesc));
cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.Usage = D3D11_USAGE_DYNAMIC;
@ -742,7 +742,7 @@ bindProgram(Effect effect, OpenSubdiv::Osd::PatchArray const & patch) {
float color[4]; float color[4];
}; };
if (not g_pcbMaterial) { if (! g_pcbMaterial) {
D3D11_BUFFER_DESC cbDesc; D3D11_BUFFER_DESC cbDesc;
ZeroMemory(&cbDesc, sizeof(cbDesc)); ZeroMemory(&cbDesc, sizeof(cbDesc));
cbDesc.Usage = D3D11_USAGE_DYNAMIC; cbDesc.Usage = D3D11_USAGE_DYNAMIC;
@ -947,7 +947,7 @@ motion(int x, int y) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && g_mbutton[1] && !g_mbutton[2]) or } else if ((g_mbutton[0] && g_mbutton[1] && !g_mbutton[2]) ||
(!g_mbutton[0] && !g_mbutton[1] && g_mbutton[2])) { (!g_mbutton[0] && !g_mbutton[1] && g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1043,7 +1043,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL_DX_INTEROP #ifdef OPENSUBDIV_HAS_OPENCL_DX_INTEROP
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
if (g_clDeviceContext.Initialize(g_pd3dDeviceContext) == false) { if (g_clDeviceContext.Initialize(g_pd3dDeviceContext) == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
exit(1); exit(1);
@ -1051,7 +1051,7 @@ callbackKernel(int k) {
} }
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize(g_pd3dDevice) == false) { if (g_cudaDeviceContext.Initialize(g_pd3dDevice) == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1551,7 +1551,7 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
NULL); NULL);
std::vector<std::string> args = tokenize(lpCmdLine); std::vector<std::string> args = tokenize(lpCmdLine);
for (int i=0; i<args.size(); ++i) { for (size_t i=0; i<args.size(); ++i) {
std::ifstream ifs(args[i]); std::ifstream ifs(args[i]);
if (ifs) { if (ifs) {
std::stringstream ss; std::stringstream ss;
@ -1598,7 +1598,7 @@ WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmd
TranslateMessage(&msg); TranslateMessage(&msg);
DispatchMessage(&msg); DispatchMessage(&msg);
} }
if (not g_freeze) if (! g_freeze)
g_frame++; g_frame++;
updateGeom(); updateGeom();

View File

@ -54,7 +54,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_glfw_executable(farViewer _add_glfw_executable(farViewer "examples"
farViewer.cpp farViewer.cpp
gl_fontutils.cpp gl_fontutils.cpp
gl_mesh.cpp gl_mesh.cpp

View File

@ -42,10 +42,6 @@
GLFWwindow* g_window=0; GLFWwindow* g_window=0;
GLFWmonitor* g_primary=0; GLFWmonitor* g_primary=0;
#if _MSC_VER
#define snprintf _snprintf
#endif
#include <osd/cpuGLVertexBuffer.h> #include <osd/cpuGLVertexBuffer.h>
#include <far/patchTableFactory.h> #include <far/patchTableFactory.h>
@ -70,6 +66,12 @@ GLFWmonitor* g_primary=0;
#include <set> #include <set>
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <cstdio>
#if _MSC_VER
#define snprintf _snprintf
#endif
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
int g_level = 3, int g_level = 3,
@ -236,7 +238,7 @@ static void
createEdgeNumbers(OpenSubdiv::Far::TopologyRefiner const & refiner, createEdgeNumbers(OpenSubdiv::Far::TopologyRefiner const & refiner,
std::vector<Vertex> const & vertexBuffer, bool ids=false, bool sharpness=false) { std::vector<Vertex> const & vertexBuffer, bool ids=false, bool sharpness=false) {
if (ids or sharpness) { if (ids || sharpness) {
int maxlevel = refiner.GetMaxLevel(), int maxlevel = refiner.GetMaxLevel(),
firstvert = 0; firstvert = 0;
@ -343,7 +345,7 @@ static void
createPatchNumbers(OpenSubdiv::Far::PatchTable const & patchTable, createPatchNumbers(OpenSubdiv::Far::PatchTable const & patchTable,
std::vector<Vertex> const & vertexBuffer) { std::vector<Vertex> const & vertexBuffer) {
if (not g_currentPatch) if (! g_currentPatch)
return; return;
int patchID = g_currentPatch-1, int patchID = g_currentPatch-1,
@ -386,7 +388,7 @@ createFVarPatchNumbers(OpenSubdiv::Far::PatchTable const & patchTable,
int patch = g_currentPatch-1; int patch = g_currentPatch-1;
static char buf[16]; static char buf[16];
if (patch>=0 and patch<patchTable.GetNumPatchesTotal()) { if (patch>=0 && patch<patchTable.GetNumPatchesTotal()) {
OpenSubdiv::Far::PatchTable::PatchHandle handle; OpenSubdiv::Far::PatchTable::PatchHandle handle;
handle.patchIndex = patch; handle.patchIndex = patch;
@ -412,7 +414,7 @@ createFVarPatches(OpenSubdiv::Far::TopologyRefiner const & refiner,
OpenSubdiv::Far::PatchTable const & patchTable, OpenSubdiv::Far::PatchTable const & patchTable,
std::vector<Vertex> const & fvarBuffer) { std::vector<Vertex> const & fvarBuffer) {
assert(not fvarBuffer.empty()); assert(!fvarBuffer.empty());
static int channel = 0; static int channel = 0;
@ -611,7 +613,7 @@ createFarGLMesh(Shape * shape, int maxlevel) {
// //
std::vector<Vertex> fvarBuffer; std::vector<Vertex> fvarBuffer;
Far::PatchTable * patchTable = 0; Far::PatchTable * patchTable = 0;
bool createFVarWire = g_FarDrawFVarPatches or g_FarDrawFVarVerts; bool createFVarWire = g_FarDrawFVarPatches || g_FarDrawFVarVerts;
if (g_Adaptive) { if (g_Adaptive) {
Far::PatchTableFactory::Options options; Far::PatchTableFactory::Options options;
@ -683,7 +685,7 @@ createFarGLMesh(Shape * shape, int maxlevel) {
stencilTable = Far::StencilTableFactory::Create(*refiner, options); stencilTable = Far::StencilTableFactory::Create(*refiner, options);
// append local point stencils if needed // append local point stencils if needed
if (patchTable and patchTable->GetLocalPointStencilTable()) { if (patchTable && patchTable->GetLocalPointStencilTable()) {
if (Far::StencilTable const * stencilTableWithLocalPoints = if (Far::StencilTable const * stencilTableWithLocalPoints =
Far::StencilTableFactory::AppendLocalPointStencilTable( Far::StencilTableFactory::AppendLocalPointStencilTable(
*refiner, stencilTable, *refiner, stencilTable,
@ -732,7 +734,7 @@ createFarGLMesh(Shape * shape, int maxlevel) {
createFaceNumbers(*refiner, vertexBuffer); createFaceNumbers(*refiner, vertexBuffer);
} }
if (g_FarDrawPtexIDs and patchTable) { if (g_FarDrawPtexIDs && patchTable) {
createPtexNumbers(*patchTable, vertexBuffer); createPtexNumbers(*patchTable, vertexBuffer);
} }
@ -740,11 +742,11 @@ createFarGLMesh(Shape * shape, int maxlevel) {
createPatchNumbers(*patchTable, vertexBuffer); createPatchNumbers(*patchTable, vertexBuffer);
} }
if (g_Adaptive and g_FarDrawGregogyBasis) { if (g_Adaptive && g_FarDrawGregogyBasis) {
createGregoryBasis(*patchTable, vertexBuffer); createGregoryBasis(*patchTable, vertexBuffer);
} }
if (g_Adaptive and createFVarWire) { if (g_Adaptive && createFVarWire) {
createFVarPatches(*refiner, *patchTable, fvarBuffer); createFVarPatches(*refiner, *patchTable, fvarBuffer);
createFVarPatchNumbers(*patchTable, fvarBuffer); createFVarPatchNumbers(*patchTable, fvarBuffer);
} }
@ -772,7 +774,7 @@ createFarGLMesh(Shape * shape, int maxlevel) {
g_controlMeshDisplay.SetTopology(refiner->GetLevel(0)); g_controlMeshDisplay.SetTopology(refiner->GetLevel(0));
// save coarse points in a GPU buffer (used for control mesh display) // save coarse points in a GPU buffer (used for control mesh display)
if (not g_controlMeshDisplayVBO) { if (! g_controlMeshDisplayVBO) {
glGenBuffers(1, &g_controlMeshDisplayVBO); glGenBuffers(1, &g_controlMeshDisplayVBO);
} }
glBindBuffer(GL_ARRAY_BUFFER, g_controlMeshDisplayVBO); glBindBuffer(GL_ARRAY_BUFFER, g_controlMeshDisplayVBO);
@ -805,7 +807,7 @@ createFarGLMesh(Shape * shape, int maxlevel) {
static void static void
createMeshes(ShapeDesc const & desc, int maxlevel) { createMeshes(ShapeDesc const & desc, int maxlevel) {
if (not g_font) { if (! g_font) {
g_font = new GLFont(g_hud.GetFontTexture()); g_font = new GLFont(g_hud.GetFontTexture());
} }
g_font->Clear(); g_font->Clear();
@ -921,15 +923,15 @@ display() {
} }
g_far_glmesh.Draw(comp, g_transformUB, g_lightingUB); g_far_glmesh.Draw(comp, g_transformUB, g_lightingUB);
if (g_Adaptive and g_FarDrawGregogyBasis) { if (g_Adaptive && g_FarDrawGregogyBasis) {
gregoryWire.Draw(GLMesh::COMP_VERT, g_transformUB, g_lightingUB); gregoryWire.Draw(GLMesh::COMP_VERT, g_transformUB, g_lightingUB);
gregoryWire.Draw(GLMesh::COMP_EDGE, g_transformUB, g_lightingUB); gregoryWire.Draw(GLMesh::COMP_EDGE, g_transformUB, g_lightingUB);
} }
if (g_Adaptive and g_FarDrawFVarVerts) { if (g_Adaptive && g_FarDrawFVarVerts) {
fvarVerts.Draw(GLMesh::COMP_VERT, g_transformUB, g_lightingUB); fvarVerts.Draw(GLMesh::COMP_VERT, g_transformUB, g_lightingUB);
} }
if (g_Adaptive and g_FarDrawFVarPatches) { if (g_Adaptive && g_FarDrawFVarPatches) {
fvarWire.Draw(GLMesh::COMP_EDGE, g_transformUB, g_lightingUB); fvarWire.Draw(GLMesh::COMP_EDGE, g_transformUB, g_lightingUB);
} }
@ -964,9 +966,9 @@ display() {
* format0 = "Current Patch : %d/%d (%s - %d CVs)", * format0 = "Current Patch : %d/%d (%s - %d CVs)",
* format1 = "Current Patch : %d/%d (%s - %d CVs) fvar: (%s - %d CVs)"; * format1 = "Current Patch : %d/%d (%s - %d CVs) fvar: (%s - %d CVs)";
if (g_Adaptive and g_currentPatch) { if (g_Adaptive && g_currentPatch) {
if (g_FarDrawFVarPatches or g_FarDrawFVarVerts) { if (g_FarDrawFVarPatches || g_FarDrawFVarVerts) {
g_hud.DrawString(g_width/2-200, 225, format1, g_hud.DrawString(g_width/2-200, 225, format1,
g_currentPatch-1, g_numPatches-1, g_currentPatch-1, g_numPatches-1,
@ -1018,7 +1020,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1289,7 +1291,7 @@ initHUD() {
g_hud.AddPullDownButton(fvar_pulldown, "FVAR_LINEAR_ALL", g_hud.AddPullDownButton(fvar_pulldown, "FVAR_LINEAR_ALL",
SdcOptions::FVAR_LINEAR_ALL, g_fvarInterpolation==SdcOptions::FVAR_LINEAR_ALL); SdcOptions::FVAR_LINEAR_ALL, g_fvarInterpolation==SdcOptions::FVAR_LINEAR_ALL);
if (not g_font) { if (! g_font) {
g_font = new GLFont( g_hud.GetFontTexture() ); g_font = new GLFont( g_hud.GetFontTexture() );
} }
} }
@ -1318,7 +1320,7 @@ uninitGL() {
static void static void
idle() { idle() {
if (g_repeatCount != 0 and g_frame >= g_repeatCount) if (g_repeatCount != 0 && g_frame >= g_repeatCount)
g_running = 0; g_running = 0;
} }
@ -1347,7 +1349,7 @@ int main(int argc, char ** argv)
} }
initShapes(); initShapes();
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1362,7 +1364,7 @@ int main(int argc, char ** argv)
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (! g_primary) {
int count=0; int count=0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1377,8 +1379,8 @@ int main(int argc, char ** argv)
} }
} }
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, if (! (g_window=glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL))) { fullscreen && g_primary ? g_primary : NULL, NULL))) {
printf("Failed to open window.\n"); printf("Failed to open window.\n");
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -65,7 +65,7 @@ void GLFont::bindProgram() {
#include "fontShader.gen.h" #include "fontShader.gen.h"
; ;
// Update and bind transform state // Update and bind transform state
if (not _program) { if (! _program) {
_program = glCreateProgram(); _program = glCreateProgram();
@ -106,15 +106,15 @@ void GLFont::bindProgram() {
} }
glUseProgram(_program); glUseProgram(_program);
if (not _scale) { if (! _scale) {
_scale = glGetUniformLocation(_program, "scale"); _scale = glGetUniformLocation(_program, "scale");
} }
if (not _attrPosition) { if (! _attrPosition) {
_attrPosition = glGetAttribLocation(_program, "position"); _attrPosition = glGetAttribLocation(_program, "position");
} }
if (not _attrData) { if (! _attrData) {
_attrData = glGetAttribLocation(_program, "data"); _attrData = glGetAttribLocation(_program, "data");
} }
} }
@ -163,13 +163,13 @@ void GLFont::Draw(GLuint transformUB) {
return; return;
} }
assert(_VAO and _VBO); assert(_VAO && _VBO);
glBindVertexArray(_VAO); glBindVertexArray(_VAO);
bindProgram(); bindProgram();
if (not _transformBinding) { if (! _transformBinding) {
GLuint uboIndex = glGetUniformBlockIndex(_program, "Transform"); GLuint uboIndex = glGetUniformBlockIndex(_program, "Transform");
if (uboIndex != GL_INVALID_INDEX) if (uboIndex != GL_INVALID_INDEX)

View File

@ -87,7 +87,7 @@ getFaceTexture() {
#include "face_texture.h" #include "face_texture.h"
if (not g_faceTexture) { if (! g_faceTexture) {
glGenTextures(1, &g_faceTexture); glGenTextures(1, &g_faceTexture);
glBindTexture(GL_TEXTURE_2D, g_faceTexture); glBindTexture(GL_TEXTURE_2D, g_faceTexture);
@ -742,13 +742,13 @@ GLMesh::InitializeDeviceBuffers() {
// copy buffers to device // copy buffers to device
for (int i=0; i<COMP_NUM_COMPONENTS; ++i) { for (int i=0; i<COMP_NUM_COMPONENTS; ++i) {
if (not _VAO[i]) { if (! _VAO[i]) {
glGenVertexArrays(1, &_VAO[i]); glGenVertexArrays(1, &_VAO[i]);
} }
glBindVertexArray(_VAO[i]); glBindVertexArray(_VAO[i]);
if (not _vbo[i].empty()) { if (! _vbo[i].empty()) {
if (not _VBO[i]) { if (! _VBO[i]) {
glGenBuffers(1, &_VBO[i]); glGenBuffers(1, &_VBO[i]);
} }
glBindBuffer(GL_ARRAY_BUFFER, _VBO[i]); glBindBuffer(GL_ARRAY_BUFFER, _VBO[i]);
@ -768,9 +768,9 @@ GLMesh::InitializeDeviceBuffers() {
} }
} }
if (not _eao[i].empty()) { if (! _eao[i].empty()) {
if (not _EAO[i]) { if (! _EAO[i]) {
glGenBuffers(1, &_EAO[i]); glGenBuffers(1, &_EAO[i]);
} }
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _EAO[i]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _EAO[i]);
@ -780,7 +780,7 @@ GLMesh::InitializeDeviceBuffers() {
GLUtils::CheckGLErrors("init"); GLUtils::CheckGLErrors("init");
} }
if (not _faceColors.empty()) { if (! _faceColors.empty()) {
_TBOfaceColors = createTextureBuffer(_faceColors, GL_RGBA32F); _TBOfaceColors = createTextureBuffer(_faceColors, GL_RGBA32F);
} }
@ -829,7 +829,7 @@ bindProgram( char const * shaderSource,
lightingBinding=1; lightingBinding=1;
// Update and bind transform state // Update and bind transform state
if (not *program) { if (! *program) {
*program = glCreateProgram(); *program = glCreateProgram();

View File

@ -84,7 +84,7 @@ public:
void Initialize(Options options, void Initialize(Options options,
std::vector<OpenSubdiv::HbrFace<T> const *> const & faces) { std::vector<OpenSubdiv::HbrFace<T> const *> const & faces) {
assert(not faces.empty()); assert(!faces.empty());
OpenSubdiv::HbrMesh<T> const * hmesh = faces[0]->GetMesh(); OpenSubdiv::HbrMesh<T> const * hmesh = faces[0]->GetMesh();

View File

@ -50,7 +50,7 @@ if( TBB_FOUND )
) )
endif() endif()
_add_glfw_executable(glEvalLimit _add_glfw_executable(glEvalLimit "examples"
glEvalLimit.cpp glEvalLimit.cpp
particles.cpp particles.cpp
particles.h particles.h

View File

@ -354,12 +354,12 @@ public:
} }
virtual void UpdatePatchCoords( virtual void UpdatePatchCoords(
std::vector<Osd::PatchCoord> const &patchCoords) { std::vector<Osd::PatchCoord> const &patchCoords) {
if (_patchCoords and if (_patchCoords &&
_patchCoords->GetNumVertices() != (int)patchCoords.size()) { _patchCoords->GetNumVertices() != (int)patchCoords.size()) {
delete _patchCoords; delete _patchCoords;
_patchCoords = NULL; _patchCoords = NULL;
} }
if (not _patchCoords) { if (! _patchCoords) {
_patchCoords = EVAL_VERTEX_BUFFER::Create(5, _patchCoords = EVAL_VERTEX_BUFFER::Create(5,
(int)patchCoords.size(), (int)patchCoords.size(),
_deviceContext); _deviceContext);
@ -901,12 +901,12 @@ display() {
static void static void
idle() { idle() {
if (not g_freeze) if (! g_freeze)
g_frame++; g_frame++;
updateGeom(); updateGeom();
if (g_repeatCount != 0 and g_frame >= g_repeatCount) if (g_repeatCount != 0 && g_frame >= g_repeatCount)
g_running = 0; g_running = 0;
} }
@ -924,7 +924,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1038,7 +1038,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL #ifdef OPENSUBDIV_HAS_OPENCL
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
if (g_clDeviceContext.Initialize() == false) { if (g_clDeviceContext.Initialize() == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
exit(1); exit(1);
@ -1046,7 +1046,7 @@ callbackKernel(int k) {
} }
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize() == false) { if (g_cudaDeviceContext.Initialize() == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1233,7 +1233,7 @@ int main(int argc, char **argv) {
initShapes(); initShapes();
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1248,7 +1248,7 @@ int main(int argc, char **argv) {
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (! g_primary) {
int count=0; int count=0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1263,8 +1263,8 @@ int main(int argc, char **argv) {
} }
} }
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, if (! (g_window=glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL))) { fullscreen && g_primary ? g_primary : NULL, NULL))) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -55,7 +55,7 @@ public:
p->t += dp[1] * _speed; p->t += dp[1] * _speed;
// make sure particles can't skip more than 1 face boundary at a time // make sure particles can't skip more than 1 face boundary at a time
assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f)); assert((p->s>-2.0f) && (p->s<2.0f) && (p->t>-2.0f) && (p->t<2.0f));
// check if the particle is jumping a boundary // check if the particle is jumping a boundary
// note: a particle can jump 2 edges at a time (a "diagonal" jump) // note: a particle can jump 2 edges at a time (a "diagonal" jump)
@ -70,7 +70,7 @@ public:
// warp the particle to the other side of the boundary // warp the particle to the other side of the boundary
STParticles::WarpParticle(_adjacency, edge, p, dp); STParticles::WarpParticle(_adjacency, edge, p, dp);
} }
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f)); assert((p->s>=0.0f) && (p->s<=1.0f) && (p->t>=0.0f) && (p->t<=1.0f));
// resolve particle positions into patch handles // resolve particle positions into patch handles
OpenSubdiv::Far::PatchTable::PatchHandle const *handle = OpenSubdiv::Far::PatchTable::PatchHandle const *handle =
@ -193,7 +193,7 @@ Rotate(int rot, STParticles::Position * p, float * dp) {
case 2: FlipS(p, dp); FlipT(p, dp); break; case 2: FlipS(p, dp); FlipT(p, dp); break;
case 3: FlipT(p, dp); SwapST(p, dp); break; case 3: FlipT(p, dp); SwapST(p, dp); break;
} }
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f)); assert((p->s>=0.0f) && (p->s<=1.0f) && (p->t>=0.0f) && (p->t<=1.0f));
} }
inline void inline void
@ -202,7 +202,7 @@ Trim(STParticles::Position * p) {
if (p->s>=1.0f) p->s = p->s - 1.0f; if (p->s>=1.0f) p->s = p->s - 1.0f;
if (p->t <0.0f) p->t = 1.0f + p->t; if (p->t <0.0f) p->t = 1.0f + p->t;
if (p->t>=1.0f) p->t = p->t - 1.0f; if (p->t>=1.0f) p->t = p->t - 1.0f;
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f)); assert((p->s>=0.0f) && (p->s<=1.0f) && (p->t>=0.0f) && (p->t<=1.0f));
} }
inline void inline void
@ -231,13 +231,13 @@ Bounce(int edge, STParticles::Position * p, float * dp) {
// because 'diagonal' cases aren't handled, stick particles to edges when // because 'diagonal' cases aren't handled, stick particles to edges when
// if they cross 2 boundaries // if they cross 2 boundaries
Clamp(p); Clamp(p);
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f)); assert((p->s>=0.0f) && (p->s<=1.0f) && (p->t>=0.0f) && (p->t<=1.0f));
} }
void void
STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency, STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency,
int edge, Position * p, float * dp) { int edge, Position * p, float * dp) {
assert(p->ptexIndex<(int)adjacency.size() and (edge>=0 and edge<4)); assert(p->ptexIndex<(int)adjacency.size() && (edge>=0 && edge<4));
FaceInfo const & f = adjacency[p->ptexIndex]; FaceInfo const & f = adjacency[p->ptexIndex];
@ -263,7 +263,7 @@ STParticles::WarpParticle(std::vector<FaceInfo> const &adjacency,
p->ptexIndex = afid; // move particle to adjacent face p->ptexIndex = afid; // move particle to adjacent face
} }
} }
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f)); assert((p->s>=0.0f) && (p->s<=1.0f) && (p->t>=0.0f) && (p->t<=1.0f));
} }
STParticles::~STParticles() { STParticles::~STParticles() {
@ -297,7 +297,7 @@ STParticles::Update(float deltaTime) {
p->t += dp[1] * speed; p->t += dp[1] * speed;
// make sure particles can't skip more than 1 face boundary at a time // make sure particles can't skip more than 1 face boundary at a time
assert((p->s>-2.0f) and (p->s<2.0f) and (p->t>-2.0f) and (p->t<2.0f)); assert((p->s>-2.0f) && (p->s<2.0f) && (p->t>-2.0f) && (p->t<2.0f));
// check if the particle is jumping a boundary // check if the particle is jumping a boundary
// note: a particle can jump 2 edges at a time (a "diagonal" jump) // note: a particle can jump 2 edges at a time (a "diagonal" jump)
@ -313,7 +313,7 @@ STParticles::Update(float deltaTime) {
// warp the particle to the other side of the boundary // warp the particle to the other side of the boundary
WarpParticle(_adjacency, edge, p, dp); WarpParticle(_adjacency, edge, p, dp);
} }
assert((p->s>=0.0f) and (p->s<=1.0f) and (p->t>=0.0f) and (p->t<=1.0f)); assert((p->s>=0.0f) && (p->s<=1.0f) && (p->t>=0.0f) && (p->t<=1.0f));
// resolve particle positions into patch handles // resolve particle positions into patch handles
OpenSubdiv::Far::PatchTable::PatchHandle const *handle = OpenSubdiv::Far::PatchTable::PatchHandle const *handle =

View File

@ -54,7 +54,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_glfw_executable(glFVarViewer _add_glfw_executable(glFVarViewer "examples"
glFVarViewer.cpp glFVarViewer.cpp
"${SHADER_FILES}" "${SHADER_FILES}"
"${INC_FILES}" "${INC_FILES}"

View File

@ -361,7 +361,7 @@ rebuildMesh() {
g_scheme = scheme; g_scheme = scheme;
// Adaptive refinement currently supported only for catmull-clark scheme // Adaptive refinement currently supported only for catmull-clark scheme
bool doAdaptive = (g_adaptive!=0 and g_scheme==kCatmark); bool doAdaptive = (g_adaptive!=0 && g_scheme==kCatmark);
OpenSubdiv::Osd::MeshBitset bits; OpenSubdiv::Osd::MeshBitset bits;
bits.set(OpenSubdiv::Osd::MeshAdaptive, doAdaptive); bits.set(OpenSubdiv::Osd::MeshAdaptive, doAdaptive);
@ -532,7 +532,7 @@ public:
// face varying width // face varying width
ss << "#define OSD_FVAR_WIDTH 2\n"; ss << "#define OSD_FVAR_WIDTH 2\n";
if (not effectDesc.desc.IsAdaptive()) { if (! effectDesc.desc.IsAdaptive()) {
ss << "#define SHADING_FACEVARYING_UNIFORM_SUBDIVISION\n"; ss << "#define SHADING_FACEVARYING_UNIFORM_SUBDIVISION\n";
} }
@ -821,7 +821,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_uvPan[0] -= (x - g_prev_x) * 2 / g_uvScale / static_cast<float>(g_width/2); g_uvPan[0] -= (x - g_prev_x) * 2 / g_uvScale / static_cast<float>(g_width/2);
g_uvPan[1] += (y - g_prev_y) * 2 / g_uvScale / static_cast<float>(g_height); g_uvPan[1] += (y - g_prev_y) * 2 / g_uvScale / static_cast<float>(g_height);
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// scale // scale
g_uvScale += g_uvScale*0.01f*(x - g_prev_x); g_uvScale += g_uvScale*0.01f*(x - g_prev_x);
@ -836,7 +836,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1046,12 +1046,12 @@ initGL() {
static void static void
idle() { idle() {
if (not g_freeze) if (! g_freeze)
g_frame++; g_frame++;
updateGeom(); updateGeom();
if (g_repeatCount != 0 and g_frame >= g_repeatCount) if (g_repeatCount != 0 && g_frame >= g_repeatCount)
g_running = 0; g_running = 0;
} }
@ -1097,7 +1097,7 @@ int main(int argc, char ** argv) {
OpenSubdiv::Far::SetErrorCallback(callbackError); OpenSubdiv::Far::SetErrorCallback(callbackError);
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1111,7 +1111,7 @@ int main(int argc, char ** argv) {
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (! g_primary) {
int count = 0; int count = 0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1126,8 +1126,8 @@ int main(int argc, char ** argv) {
} }
} }
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, if (! (g_window=glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL))) { fullscreen && g_primary ? g_primary : NULL, NULL))) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -57,7 +57,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_glfw_executable(glImaging _add_glfw_executable(glImaging "examples"
"${SOURCE_FILES}" "${SOURCE_FILES}"
"${SHADER_FILES}" "${SHADER_FILES}"
"${INC_FILES}" "${INC_FILES}"

View File

@ -521,7 +521,7 @@ int main(int argc, char ** argv) {
#endif #endif
} }
if (not glfwInit()) { if (! glfwInit()) {
std::cout << "Failed to initialize GLFW\n"; std::cout << "Failed to initialize GLFW\n";
return 1; return 1;
} }
@ -532,7 +532,7 @@ int main(int argc, char ** argv) {
GLUtils::SetMinimumGLVersion(); GLUtils::SetMinimumGLVersion();
GLFWwindow *window = glfwCreateWindow(width, height, windowTitle, NULL, NULL); GLFWwindow *window = glfwCreateWindow(width, height, windowTitle, NULL, NULL);
if (not window) { if (! window) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
} }

View File

@ -50,7 +50,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_glfw_executable(glPaintTest _add_glfw_executable(glPaintTest "examples"
glPaintTest.cpp glPaintTest.cpp
"${SHADER_FILES}" "${SHADER_FILES}"
"${INC_FILES}" "${INC_FILES}"

View File

@ -832,7 +832,7 @@ motion(GLFWwindow * w, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -860,7 +860,7 @@ mouse(GLFWwindow * w, int button, int state, int /* mods */) {
g_mbutton[button] = (state == GLFW_PRESS); g_mbutton[button] = (state == GLFW_PRESS);
} }
if (not glfwGetKey(w, GLFW_KEY_LEFT_ALT)) { if (! glfwGetKey(w, GLFW_KEY_LEFT_ALT)) {
if (g_mbutton[0] && !g_mbutton[1] && !g_mbutton[2]) { if (g_mbutton[0] && !g_mbutton[1] && !g_mbutton[2]) {
drawStroke(g_prev_x, g_prev_y); drawStroke(g_prev_x, g_prev_y);
} }
@ -1100,7 +1100,7 @@ int main(int argc, char ** argv) {
OpenSubdiv::Far::SetErrorCallback(callbackError); OpenSubdiv::Far::SetErrorCallback(callbackError);
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1115,7 +1115,7 @@ int main(int argc, char ** argv) {
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (! g_primary) {
int count=0; int count=0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1130,8 +1130,8 @@ int main(int argc, char ** argv) {
} }
} }
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, if (! (g_window=glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL))) { fullscreen && g_primary ? g_primary : NULL, NULL))) {
printf("Failed to open window.\n"); printf("Failed to open window.\n");
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -35,6 +35,7 @@ list(APPEND PLATFORM_LIBRARIES
"${OPENGL_LIBRARY}" "${OPENGL_LIBRARY}"
"${GLFW_LIBRARIES}" "${GLFW_LIBRARIES}"
"${PTEX_LIBRARY}" "${PTEX_LIBRARY}"
"${ZLIB_LIBRARY}"
) )
include_directories( include_directories(
@ -59,7 +60,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
_add_glfw_executable(glPtexViewer _add_glfw_executable(glPtexViewer "examples"
glPtexViewer.cpp glPtexViewer.cpp
"${SHADER_FILES}" "${SHADER_FILES}"
"${INC_FILES}" "${INC_FILES}"

View File

@ -346,7 +346,7 @@ updateGeom() {
int nverts = (int)g_positions.size() / 3; int nverts = (int)g_positions.size() / 3;
if (g_moveScale and g_adaptive and not g_animPositions.empty()) { if (g_moveScale && g_adaptive && !g_animPositions.empty()) {
// baked animation only works with adaptive for now // baked animation only works with adaptive for now
// (since non-adaptive requires normals) // (since non-adaptive requires normals)
int nkey = (int)g_animPositions.size(); int nkey = (int)g_animPositions.size();
@ -875,7 +875,7 @@ createOsdMesh(int level, int kernel) {
// generate Shape representation from ptex // generate Shape representation from ptex
Shape * shape = createPTexGeo(ptexColor); Shape * shape = createPTexGeo(ptexColor);
if (not shape) { if (!shape) {
return; return;
} }
@ -901,7 +901,7 @@ createOsdMesh(int level, int kernel) {
g_mesh = NULL; g_mesh = NULL;
// Adaptive refinement currently supported only for catmull-clark scheme // Adaptive refinement currently supported only for catmull-clark scheme
bool doAdaptive = (g_adaptive != 0 and g_scheme == 0); bool doAdaptive = (g_adaptive != 0 && g_scheme == 0);
OpenSubdiv::Osd::MeshBitset bits; OpenSubdiv::Osd::MeshBitset bits;
bits.set(OpenSubdiv::Osd::MeshAdaptive, doAdaptive); bits.set(OpenSubdiv::Osd::MeshAdaptive, doAdaptive);
@ -1394,7 +1394,7 @@ display() {
g_fpsTimer.Stop(); g_fpsTimer.Stop();
float elapsed = (float)g_fpsTimer.GetElapsed(); float elapsed = (float)g_fpsTimer.GetElapsed();
if (not g_freeze) if (!g_freeze)
g_animTime += elapsed; g_animTime += elapsed;
g_fpsTimer.Start(); g_fpsTimer.Start();
@ -1466,7 +1466,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1510,7 +1510,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL #ifdef OPENSUBDIV_HAS_OPENCL
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
// Initialize OpenCL // Initialize OpenCL
if (g_clDeviceContext.Initialize() == false) { if (g_clDeviceContext.Initialize() == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
@ -1519,7 +1519,7 @@ callbackKernel(int k) {
} }
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize() == false) { if (g_cudaDeviceContext.Initialize() == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1616,10 +1616,10 @@ callbackSlider(float value, int data) {
//------------------------------------------------------------------------------- //-------------------------------------------------------------------------------
void void
reloadShaderFile() { reloadShaderFile() {
if (not g_shaderFilename) return; if (!g_shaderFilename) return;
std::ifstream ifs(g_shaderFilename); std::ifstream ifs(g_shaderFilename);
if (not ifs) return; if (!ifs) return;
printf("Load shader %s\n", g_shaderFilename); printf("Load shader %s\n", g_shaderFilename);
std::stringstream ss; std::stringstream ss;
@ -1661,7 +1661,7 @@ keyboard(GLFWwindow *, int key, int /* scancode */, int event, int /* mods */) {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
void void
idle() { idle() {
if (not g_freeze) if (!g_freeze)
g_frame++; g_frame++;
updateGeom(); updateGeom();
@ -1778,7 +1778,7 @@ int main(int argc, char ** argv) {
} }
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (!glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1792,7 +1792,7 @@ int main(int argc, char ** argv) {
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (!g_primary) {
int count = 0; int count = 0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1807,8 +1807,8 @@ int main(int argc, char ** argv) {
} }
} }
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, if (!(g_window=glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL))) { fullscreen && g_primary ? g_primary : NULL, NULL))) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
return 1; return 1;
@ -1866,7 +1866,7 @@ int main(int argc, char ** argv) {
g_hud.AddCheckBox("Specular (S)", g_specular, g_hud.AddCheckBox("Specular (S)", g_specular,
-200, 590, callbackCheckBox, HUD_CB_DISPLAY_SPECULAR, 's'); -200, 590, callbackCheckBox, HUD_CB_DISPLAY_SPECULAR, 's');
if (diffuseEnvironmentMap or specularEnvironmentMap) { if (diffuseEnvironmentMap || specularEnvironmentMap) {
g_hud.AddCheckBox("IBL (I)", g_ibl, g_hud.AddCheckBox("IBL (I)", g_ibl,
-200, 610, callbackCheckBox, HUD_CB_IBL, 'i'); -200, 610, callbackCheckBox, HUD_CB_IBL, 'i');
} }
@ -2015,7 +2015,7 @@ int main(int argc, char ** argv) {
+ (g_osdPTexSpecular ? g_osdPTexSpecular->GetMemoryUsage() : 0); + (g_osdPTexSpecular ? g_osdPTexSpecular->GetMemoryUsage() : 0);
// load animation obj sequences (optional) // load animation obj sequences (optional)
if (not animobjs.empty()) { if (!animobjs.empty()) {
for (int i = 0; i < (int)animobjs.size(); ++i) { for (int i = 0; i < (int)animobjs.size(); ++i) {
std::ifstream ifs(animobjs[i].c_str()); std::ifstream ifs(animobjs[i].c_str());
if (ifs) { if (ifs) {

View File

@ -54,7 +54,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_glfw_executable(glShareTopology _add_glfw_executable(glShareTopology "examples"
glShareTopology.cpp glShareTopology.cpp
sceneBase.cpp sceneBase.cpp
"${SHADER_FILES}" "${SHADER_FILES}"

View File

@ -786,7 +786,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -928,7 +928,7 @@ rebuildTopology() {
g_defaultShapes[i].scheme, g_defaultShapes[i].scheme,
g_defaultShapes[i].isLeftHanded); g_defaultShapes[i].isLeftHanded);
bool varying = (g_displayStyle==kVarying or g_displayStyle==kVaryingInterleaved); bool varying = (g_displayStyle==kVarying || g_displayStyle==kVaryingInterleaved);
g_scene->AddTopology(shape, g_level, varying); g_scene->AddTopology(shape, g_level, varying);
delete shape; delete shape;
@ -978,7 +978,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL #ifdef OPENSUBDIV_HAS_OPENCL
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
if (g_clDeviceContext.Initialize() == false) { if (g_clDeviceContext.Initialize() == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
exit(1); exit(1);
@ -987,7 +987,7 @@ callbackKernel(int k) {
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize() == false) { if (g_cudaDeviceContext.Initialize() == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1143,7 +1143,7 @@ initGL() {
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
static void static void
idle() { idle() {
if (not g_freeze) { if (! g_freeze) {
++g_frame; ++g_frame;
updateGeom(); updateGeom();
refine(); refine();
@ -1175,7 +1175,7 @@ int main(int argc, char ** argv) {
Far::SetErrorCallback(callbackError); Far::SetErrorCallback(callbackError);
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1184,7 +1184,7 @@ int main(int argc, char ** argv) {
GLUtils::SetMinimumGLVersion(); GLUtils::SetMinimumGLVersion();
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, NULL, NULL))) { if (! (g_window=glfwCreateWindow(g_width, g_height, windowTitle, NULL, NULL))) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -43,7 +43,7 @@ if( OPENCL_FOUND )
include_directories("${OPENCL_INCLUDE_DIRS}") include_directories("${OPENCL_INCLUDE_DIRS}")
endif() endif()
_add_glfw_executable(glStencilViewer _add_glfw_executable(glStencilViewer "examples"
glStencilViewer.cpp glStencilViewer.cpp
"${INC_FILES}" "${INC_FILES}"
$<TARGET_OBJECTS:regression_common_obj> $<TARGET_OBJECTS:regression_common_obj>

View File

@ -454,15 +454,15 @@ public:
void EnableVertexAttributes( ) { void EnableVertexAttributes( ) {
long int offset = 0; GLvoid * offset = 0;
for (AttrList::iterator i=_attrs.begin(); i!=_attrs.end(); ++i) { for (AttrList::iterator i=_attrs.begin(); i!=_attrs.end(); ++i) {
glEnableVertexAttribArray( i->location ); glEnableVertexAttribArray( i->location );
glVertexAttribPointer( i->location, i->size, glVertexAttribPointer( i->location, i->size,
GL_FLOAT, GL_FALSE, sizeof(GLfloat) * _attrStride, (void*)offset); GL_FLOAT, GL_FALSE, sizeof(GLfloat) * _attrStride, (GLvoid*)offset);
offset += sizeof(GLfloat) * i->size; offset = (GLubyte*)offset + sizeof(GLfloat) * i->size;
} }
} }
GLuint GetUniformScale() const { GLuint GetUniformScale() const {
@ -480,8 +480,8 @@ public:
void Use( ) { void Use( ) {
if (not _program) { if (! _program) {
assert( _vtxSrc and _frgSrc ); assert( _vtxSrc && _frgSrc );
_program = glCreateProgram(); _program = glCreateProgram();
@ -645,6 +645,8 @@ linkDefaultPrograms() {
g_samplesProgram.SetFragShaderSource(fsSrc); g_samplesProgram.SetFragShaderSource(fsSrc);
g_samplesProgram.AddAttribute( "position",3 ); g_samplesProgram.AddAttribute( "position",3 );
g_samplesProgram.AddAttribute( "uTangent",3 );
g_samplesProgram.AddAttribute( "vTangent",3 );
} }
return true; return true;
@ -747,12 +749,12 @@ display() {
static void static void
idle() { idle() {
if (not g_freeze) if (! g_freeze)
g_frame++; g_frame++;
updateGeom(); updateGeom();
if (g_repeatCount != 0 and g_frame >= g_repeatCount) if (g_repeatCount != 0 && g_frame >= g_repeatCount)
g_running = 0; g_running = 0;
} }
@ -769,7 +771,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -856,7 +858,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL #ifdef OPENSUBDIV_HAS_OPENCL
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
if (g_clDeviceContext.Initialize() == false) { if (g_clDeviceContext.Initialize() == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
exit(1); exit(1);
@ -864,7 +866,7 @@ callbackKernel(int k) {
} }
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize() == false) { if (g_cudaDeviceContext.Initialize() == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1035,7 +1037,7 @@ int main(int argc, char **argv) {
initShapes(); initShapes();
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1050,7 +1052,7 @@ int main(int argc, char **argv) {
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (! g_primary) {
int count=0; int count=0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1065,8 +1067,8 @@ int main(int argc, char **argv) {
} }
} }
if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, if (! (g_window=glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL))) { fullscreen && g_primary ? g_primary : NULL, NULL))) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -53,7 +53,7 @@ _stringify("${SHADER_FILES}" INC_FILES)
include_directories("${CMAKE_CURRENT_BINARY_DIR}") include_directories("${CMAKE_CURRENT_BINARY_DIR}")
_add_glfw_executable(glViewer _add_glfw_executable(glViewer "examples"
glViewer.cpp glViewer.cpp
"${SHADER_FILES}" "${SHADER_FILES}"
"${INC_FILES}" "${INC_FILES}"

View File

@ -90,7 +90,7 @@ OpenSubdiv::Osd::GLLegacyGregoryPatchTable *g_legacyGregoryPatchTable = NULL;
source is returned. If glew in not available during compile time the version source is returned. If glew in not available during compile time the version
is determined*/ is determined*/
static const char *shaderSource(){ static const char *shaderSource(){
#if not defined(OSD_USES_GLEW) #if ! defined(OSD_USES_GLEW)
static const char *res = static const char *res =
#if defined(GL_ARB_tessellation_shader) || defined(GL_VERSION_4_0) #if defined(GL_ARB_tessellation_shader) || defined(GL_VERSION_4_0)
@ -299,7 +299,7 @@ updateGeom() {
int nverts = 0; int nverts = 0;
int stride = (g_shadingMode == kShadingInterleavedVaryingColor ? 7 : 3); int stride = (g_shadingMode == kShadingInterleavedVaryingColor ? 7 : 3);
if (g_objAnim and g_currentShape==0) { if (g_objAnim && g_currentShape==0) {
nverts = g_objAnim->GetShape()->GetNumVertices(), nverts = g_objAnim->GetShape()->GetNumVertices(),
@ -311,7 +311,7 @@ updateGeom() {
g_objAnim->InterpolatePositions(g_animTime, &vertex[0], stride); g_objAnim->InterpolatePositions(g_animTime, &vertex[0], stride);
if (g_shadingMode == kShadingVaryingColor or if (g_shadingMode == kShadingVaryingColor ||
g_shadingMode == kShadingInterleavedVaryingColor) { g_shadingMode == kShadingInterleavedVaryingColor) {
const float *p = &g_objAnim->GetShape()->verts[0]; const float *p = &g_objAnim->GetShape()->verts[0];
@ -415,7 +415,7 @@ rebuildMesh() {
ShapeDesc const &shapeDesc = g_defaultShapes[g_currentShape]; ShapeDesc const &shapeDesc = g_defaultShapes[g_currentShape];
int level = g_level; int level = g_level;
int kernel = g_kernel; int kernel = g_kernel;
bool doAnim = g_objAnim and g_currentShape==0; bool doAnim = g_objAnim && g_currentShape==0;
Scheme scheme = shapeDesc.scheme; Scheme scheme = shapeDesc.scheme;
Shape const * shape = 0; Shape const * shape = 0;
@ -443,9 +443,9 @@ rebuildMesh() {
g_mesh = NULL; g_mesh = NULL;
// Adaptive refinement currently supported only for catmull-clark scheme // Adaptive refinement currently supported only for catmull-clark scheme
bool doAdaptive = (g_adaptive!=0 and scheme==kCatmark); bool doAdaptive = (g_adaptive!=0 && scheme==kCatmark);
bool interleaveVarying = g_shadingMode == kShadingInterleavedVaryingColor; bool interleaveVarying = g_shadingMode == kShadingInterleavedVaryingColor;
bool doSingleCreasePatch = (g_singleCreasePatch!=0 and scheme==kCatmark); bool doSingleCreasePatch = (g_singleCreasePatch!=0 && scheme==kCatmark);
Osd::MeshBitset bits; Osd::MeshBitset bits;
bits.set(Osd::MeshAdaptive, doAdaptive); bits.set(Osd::MeshAdaptive, doAdaptive);
@ -458,7 +458,7 @@ rebuildMesh() {
int numVertexElements = 3; int numVertexElements = 3;
int numVaryingElements = int numVaryingElements =
(g_shadingMode == kShadingVaryingColor or interleaveVarying) ? 4 : 0; (g_shadingMode == kShadingVaryingColor || interleaveVarying) ? 4 : 0;
if (kernel == kCPU) { if (kernel == kCPU) {
@ -551,7 +551,7 @@ rebuildMesh() {
printf("Unsupported kernel %s\n", getKernelName(kernel)); printf("Unsupported kernel %s\n", getKernelName(kernel));
} }
if (g_shadingMode == kShadingFaceVaryingColor and shape->HasUV()) { if (g_shadingMode == kShadingFaceVaryingColor && shape->HasUV()) {
std::vector<float> fvarData; std::vector<float> fvarData;
@ -570,7 +570,7 @@ rebuildMesh() {
Osd::GLLegacyGregoryPatchTable::Create(g_mesh->GetFarPatchTable()); Osd::GLLegacyGregoryPatchTable::Create(g_mesh->GetFarPatchTable());
} }
if (not doAnim) { if (! doAnim) {
delete shape; delete shape;
} }
@ -758,7 +758,7 @@ public:
case kShadingFaceVaryingColor: case kShadingFaceVaryingColor:
ss << "#define OSD_FVAR_WIDTH 2\n"; ss << "#define OSD_FVAR_WIDTH 2\n";
ss << "#define SHADING_FACEVARYING_COLOR\n"; ss << "#define SHADING_FACEVARYING_COLOR\n";
if (not effectDesc.desc.IsAdaptive()) { if (! effectDesc.desc.IsAdaptive()) {
ss << "#define SHADING_FACEVARYING_UNIFORM_SUBDIVISION\n"; ss << "#define SHADING_FACEVARYING_UNIFORM_SUBDIVISION\n";
} }
break; break;
@ -987,7 +987,7 @@ bindProgram(Effect effect,
// only legacy gregory needs maxValence and numElements // only legacy gregory needs maxValence and numElements
// neither legacy gregory nor gregory basis need single crease // neither legacy gregory nor gregory basis need single crease
typedef OpenSubdiv::Far::PatchDescriptor Descriptor; typedef OpenSubdiv::Far::PatchDescriptor Descriptor;
if (patch.GetDescriptor().GetType() == Descriptor::GREGORY or if (patch.GetDescriptor().GetType() == Descriptor::GREGORY ||
patch.GetDescriptor().GetType() == Descriptor::GREGORY_BOUNDARY) { patch.GetDescriptor().GetType() == Descriptor::GREGORY_BOUNDARY) {
int maxValence = g_mesh->GetMaxValence(); int maxValence = g_mesh->GetMaxValence();
int numElements = (g_shadingMode == kShadingInterleavedVaryingColor ? 7 : 3); int numElements = (g_shadingMode == kShadingInterleavedVaryingColor ? 7 : 3);
@ -1171,7 +1171,7 @@ display() {
g_fpsTimer.Stop(); g_fpsTimer.Stop();
float elapsed = (float)g_fpsTimer.GetElapsed(); float elapsed = (float)g_fpsTimer.GetElapsed();
if (not g_freeze) { if (! g_freeze) {
g_animTime += elapsed; g_animTime += elapsed;
} }
g_fpsTimer.Start(); g_fpsTimer.Start();
@ -1234,7 +1234,7 @@ motion(GLFWwindow *, double dx, double dy) {
// pan // pan
g_pan[0] -= g_dolly*(x - g_prev_x)/g_width; g_pan[0] -= g_dolly*(x - g_prev_x)/g_width;
g_pan[1] += g_dolly*(y - g_prev_y)/g_height; g_pan[1] += g_dolly*(y - g_prev_y)/g_height;
} else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) or } else if ((g_mbutton[0] && !g_mbutton[1] && g_mbutton[2]) ||
(!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) { (!g_mbutton[0] && g_mbutton[1] && !g_mbutton[2])) {
// dolly // dolly
g_dolly -= g_dolly*0.01f*(x - g_prev_x); g_dolly -= g_dolly*0.01f*(x - g_prev_x);
@ -1328,9 +1328,9 @@ callbackDisplayStyle(int b) {
static void static void
callbackShadingMode(int b) { callbackShadingMode(int b) {
if (g_shadingMode == kShadingVaryingColor or b == kShadingVaryingColor or if (g_shadingMode == kShadingVaryingColor || b == kShadingVaryingColor ||
g_shadingMode == kShadingInterleavedVaryingColor or b == kShadingInterleavedVaryingColor or g_shadingMode == kShadingInterleavedVaryingColor || b == kShadingInterleavedVaryingColor ||
g_shadingMode == kShadingFaceVaryingColor or b == kShadingFaceVaryingColor) { g_shadingMode == kShadingFaceVaryingColor || b == kShadingFaceVaryingColor) {
// need to rebuild for varying reconstruct // need to rebuild for varying reconstruct
g_shadingMode = b; g_shadingMode = b;
rebuildMesh(); rebuildMesh();
@ -1350,7 +1350,7 @@ callbackKernel(int k) {
g_kernel = k; g_kernel = k;
#ifdef OPENSUBDIV_HAS_OPENCL #ifdef OPENSUBDIV_HAS_OPENCL
if (g_kernel == kCL and (not g_clDeviceContext.IsInitialized())) { if (g_kernel == kCL && (!g_clDeviceContext.IsInitialized())) {
if (g_clDeviceContext.Initialize() == false) { if (g_clDeviceContext.Initialize() == false) {
printf("Error in initializing OpenCL\n"); printf("Error in initializing OpenCL\n");
exit(1); exit(1);
@ -1358,7 +1358,7 @@ callbackKernel(int k) {
} }
#endif #endif
#ifdef OPENSUBDIV_HAS_CUDA #ifdef OPENSUBDIV_HAS_CUDA
if (g_kernel == kCUDA and (not g_cudaDeviceContext.IsInitialized())) { if (g_kernel == kCUDA && (!g_cudaDeviceContext.IsInitialized())) {
if (g_cudaDeviceContext.Initialize() == false) { if (g_cudaDeviceContext.Initialize() == false) {
printf("Error in initializing Cuda\n"); printf("Error in initializing Cuda\n");
exit(1); exit(1);
@ -1584,12 +1584,12 @@ initGL() {
static void static void
idle() { idle() {
if (not g_freeze) { if (! g_freeze) {
g_frame++; g_frame++;
updateGeom(); updateGeom();
} }
if (g_repeatCount != 0 and g_frame >= g_repeatCount) if (g_repeatCount != 0 && g_frame >= g_repeatCount)
g_running = 0; g_running = 0;
} }
@ -1641,7 +1641,7 @@ int main(int argc, char ** argv) {
} }
} }
if (not animobjs.empty()) { if (! animobjs.empty()) {
g_defaultShapes.push_back(ShapeDesc(animobjs[0], "", kCatmark)); g_defaultShapes.push_back(ShapeDesc(animobjs[0], "", kCatmark));
@ -1655,7 +1655,7 @@ int main(int argc, char ** argv) {
OpenSubdiv::Far::SetErrorCallback(callbackErrorOsd); OpenSubdiv::Far::SetErrorCallback(callbackErrorOsd);
glfwSetErrorCallback(callbackErrorGLFW); glfwSetErrorCallback(callbackErrorGLFW);
if (not glfwInit()) { if (! glfwInit()) {
printf("Failed to initialize GLFW\n"); printf("Failed to initialize GLFW\n");
return 1; return 1;
} }
@ -1670,7 +1670,7 @@ int main(int argc, char ** argv) {
// apparently glfwGetPrimaryMonitor fails under linux : if no primary, // apparently glfwGetPrimaryMonitor fails under linux : if no primary,
// settle for the first one in the list // settle for the first one in the list
if (not g_primary) { if (! g_primary) {
int count = 0; int count = 0;
GLFWmonitor ** monitors = glfwGetMonitors(&count); GLFWmonitor ** monitors = glfwGetMonitors(&count);
@ -1686,9 +1686,9 @@ int main(int argc, char ** argv) {
} }
g_window = glfwCreateWindow(g_width, g_height, windowTitle, g_window = glfwCreateWindow(g_width, g_height, windowTitle,
fullscreen and g_primary ? g_primary : NULL, NULL); fullscreen && g_primary ? g_primary : NULL, NULL);
if (not g_window) { if (! g_window) {
std::cerr << "Failed to create OpenGL context.\n"; std::cerr << "Failed to create OpenGL context.\n";
glfwTerminate(); glfwTerminate();
return 1; return 1;

View File

@ -111,14 +111,14 @@ add_custom_target(maya_polySmoothNode_melScripts
COMMAND COMMAND
${CMAKE_COMMAND} -E copy ${CMAKE_COMMAND} -E copy
"${CMAKE_CURRENT_SOURCE_DIR}/mayaPolySmooth.mel" "${CMAKE_CURRENT_SOURCE_DIR}/mayaPolySmooth.mel"
"${CMAKE_BINARY_DIR}/${CMAKE_LIBDIR_BASE}/mayaPolySmooth.mel" "${OpenSubdiv_BINARY_DIR}/${CMAKE_LIBDIR_BASE}/mayaPolySmooth.mel"
DEPENDS DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/mayaPolySmooth.mel" "${CMAKE_CURRENT_SOURCE_DIR}/mayaPolySmooth.mel"
) )
install( install(
FILES FILES
"${CMAKE_BINARY_DIR}/${CMAKE_LIBDIR_BASE}/mayaPolySmooth.mel" "${OpenSubdiv_BINARY_DIR}/${CMAKE_LIBDIR_BASE}/mayaPolySmooth.mel"
DESTINATION DESTINATION
"${CMAKE_PLUGINDIR_BASE}" "${CMAKE_PLUGINDIR_BASE}"
) )

View File

@ -797,7 +797,7 @@ MayaPolySmooth::compute( const MPlug& plug, MDataBlock& data ) {
int subdivisionLevel = data.inputValue(a_subdivisionLevels).asInt(); int subdivisionLevel = data.inputValue(a_subdivisionLevels).asInt();
short stateH = data.inputValue(state).asShort(); short stateH = data.inputValue(state).asShort();
if ((subdivisionLevel > 0) and (stateH !=1)) { if ((subdivisionLevel > 0) && (stateH !=1)) {
// == Retrieve input mesh ==================================== // == Retrieve input mesh ====================================
// Get attr values // Get attr values
@ -1212,9 +1212,9 @@ MStatus initializePlugin( MObject obj ) {
// Source UI scripts // Source UI scripts
MString path = plugin.loadPath()+"/mayaPolySmooth.mel"; MString path = plugin.loadPath()+"/mayaPolySmooth.mel";
if (not MGlobal::sourceFile(path)) { if (!MGlobal::sourceFile(path)) {
path = "mayaPolySmooth.mel"; path = "mayaPolySmooth.mel";
if (not MGlobal::sourceFile(path)) { if (!MGlobal::sourceFile(path)) {
MGlobal::displayWarning("Failed to source mayaPolySmooth.mel."); MGlobal::displayWarning("Failed to source mayaPolySmooth.mel.");
} }
} }

View File

@ -145,7 +145,12 @@ if (NOT NO_LIB)
$<TARGET_OBJECTS:far_obj> $<TARGET_OBJECTS:far_obj>
$<TARGET_OBJECTS:osd_cpu_obj> $<TARGET_OBJECTS:osd_cpu_obj>
) )
set_target_properties(osd_static_cpu PROPERTIES OUTPUT_NAME osdCPU CLEAN_DIRECT_OUTPUT 1) set_target_properties(osd_static_cpu
PROPERTIES
OUTPUT_NAME osdCPU
CLEAN_DIRECT_OUTPUT 1
FOLDER "opensubdiv"
)
target_link_libraries(osd_static_cpu target_link_libraries(osd_static_cpu
${PLATFORM_CPU_LIBRARIES} ${PLATFORM_CPU_LIBRARIES}
@ -156,7 +161,7 @@ if (NOT NO_LIB)
if( OSD_GPU ) if( OSD_GPU )
# this macro uses FindCUDA.cmake to compile .cu kernel files # this macro uses FindCUDA.cmake to compile .cu kernel files
# the target then adds the other obj dependencies and include files # the target then adds the other obj dependencies and include files
_add_possibly_cuda_library(osd_static_gpu _add_possibly_cuda_library(osd_static_gpu "opensubdiv"
STATIC STATIC
version.cpp version.cpp
$<TARGET_OBJECTS:osd_gpu_obj> $<TARGET_OBJECTS:osd_gpu_obj>
@ -210,7 +215,7 @@ if (NOT NO_LIB)
#--------------------------------------------------- #---------------------------------------------------
if( OSD_GPU ) if( OSD_GPU )
_add_possibly_cuda_library(osd_dynamic_gpu _add_possibly_cuda_library(osd_dynamic_gpu "opensubdiv"
SHARED SHARED
version.cpp version.cpp
$<TARGET_OBJECTS:osd_gpu_obj> $<TARGET_OBJECTS:osd_gpu_obj>

View File

@ -84,6 +84,11 @@ if (NOT NO_LIB)
${PUBLIC_HEADER_FILES} ${PUBLIC_HEADER_FILES}
) )
set_target_properties(far_obj
PROPERTIES
FOLDER "opensubdiv"
)
endif() endif()
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------

View File

@ -56,7 +56,7 @@ EndCapBSplineBasisPatchFactory::EndCapBSplineBasisPatchFactory(
_refiner(&refiner), _numVertices(0), _numPatches(0) { _refiner(&refiner), _numVertices(0), _numPatches(0) {
// Sanity check: the mesh must be adaptively refined // Sanity check: the mesh must be adaptively refined
assert(not refiner.IsUniform()); assert(! refiner.IsUniform());
// Reserve the patch point stencils. Ideally topology refiner // Reserve the patch point stencils. Ideally topology refiner
// would have an API to return how many endcap patches will be required. // would have an API to return how many endcap patches will be required.
@ -77,6 +77,7 @@ EndCapBSplineBasisPatchFactory::EndCapBSplineBasisPatchFactory(
ConstIndexArray ConstIndexArray
EndCapBSplineBasisPatchFactory::GetPatchPoints( EndCapBSplineBasisPatchFactory::GetPatchPoints(
Vtr::internal::Level const * level, Index thisFace, Vtr::internal::Level const * level, Index thisFace,
Vtr::internal::Level::VSpan const cornerSpans[],
PatchTableFactory::PatchFaceTag const *levelPatchTags, PatchTableFactory::PatchFaceTag const *levelPatchTags,
int levelVertOffset) { int levelVertOffset) {
@ -85,7 +86,7 @@ EndCapBSplineBasisPatchFactory::GetPatchPoints(
// if it's boundary, fallback to use GregoryBasis // if it's boundary, fallback to use GregoryBasis
if (patchTag._boundaryCount > 0) { if (patchTag._boundaryCount > 0) {
return getPatchPointsFromGregoryBasis( return getPatchPointsFromGregoryBasis(
level, thisFace, facePoints, levelVertOffset); level, thisFace, cornerSpans, facePoints, levelVertOffset);
} }
// there's a short-cut when the face contains only 1 extraordinary vertex. // there's a short-cut when the face contains only 1 extraordinary vertex.
@ -99,7 +100,7 @@ EndCapBSplineBasisPatchFactory::GetPatchPoints(
// more than one extraoridinary vertices. // more than one extraoridinary vertices.
// fallback to use GregoryBasis // fallback to use GregoryBasis
return getPatchPointsFromGregoryBasis( return getPatchPointsFromGregoryBasis(
level, thisFace, facePoints, levelVertOffset); level, thisFace, cornerSpans, facePoints, levelVertOffset);
} }
irregular = i; irregular = i;
} }
@ -113,6 +114,7 @@ EndCapBSplineBasisPatchFactory::GetPatchPoints(
ConstIndexArray ConstIndexArray
EndCapBSplineBasisPatchFactory::getPatchPointsFromGregoryBasis( EndCapBSplineBasisPatchFactory::getPatchPointsFromGregoryBasis(
Vtr::internal::Level const * level, Index thisFace, Vtr::internal::Level const * level, Index thisFace,
Vtr::internal::Level::VSpan const cornerSpans[],
ConstIndexArray facePoints, int levelVertOffset) { ConstIndexArray facePoints, int levelVertOffset) {
// XXX: For now, always create new 16 indices for each patch. // XXX: For now, always create new 16 indices for each patch.
@ -124,7 +126,7 @@ EndCapBSplineBasisPatchFactory::getPatchPointsFromGregoryBasis(
_patchPoints.push_back(_numVertices + offset); _patchPoints.push_back(_numVertices + offset);
++_numVertices; ++_numVertices;
} }
GregoryBasis::ProtoBasis basis(*level, thisFace, levelVertOffset, -1); GregoryBasis::ProtoBasis basis(*level, thisFace, cornerSpans, levelVertOffset, -1);
// XXX: temporary hack. we should traverse topology and find existing // XXX: temporary hack. we should traverse topology and find existing
// vertices if available // vertices if available
// //

View File

@ -80,12 +80,14 @@ public:
/// ///
ConstIndexArray GetPatchPoints( ConstIndexArray GetPatchPoints(
Vtr::internal::Level const * level, Index faceIndex, Vtr::internal::Level const * level, Index faceIndex,
Vtr::internal::Level::VSpan const cornerSpans[],
PatchTableFactory::PatchFaceTag const * levelPatchTags, PatchTableFactory::PatchFaceTag const * levelPatchTags,
int levelVertOffset); int levelVertOffset);
private: private:
ConstIndexArray getPatchPointsFromGregoryBasis( ConstIndexArray getPatchPointsFromGregoryBasis(
Vtr::internal::Level const * level, Index thisFace, Vtr::internal::Level const * level, Index thisFace,
Vtr::internal::Level::VSpan const cornerSpans[],
ConstIndexArray facePoints, ConstIndexArray facePoints,
int levelVertOffset); int levelVertOffset);

View File

@ -50,7 +50,7 @@ EndCapGregoryBasisPatchFactory::EndCapGregoryBasisPatchFactory(
_numGregoryBasisVertices(0), _numGregoryBasisPatches(0) { _numGregoryBasisVertices(0), _numGregoryBasisPatches(0) {
// Sanity check: the mesh must be adaptively refined // Sanity check: the mesh must be adaptively refined
assert(not refiner.IsUniform()); assert(! refiner.IsUniform());
// Reserve the patch point stencils. Ideally topology refiner // Reserve the patch point stencils. Ideally topology refiner
// would have an API to return how many endcap patches will be required. // would have an API to return how many endcap patches will be required.
@ -77,7 +77,8 @@ EndCapGregoryBasisPatchFactory::Create(TopologyRefiner const & refiner,
// Gregory patches are end-caps: they only exist on max-level // Gregory patches are end-caps: they only exist on max-level
Vtr::internal::Level const & level = refiner.getLevel(refiner.GetMaxLevel()); Vtr::internal::Level const & level = refiner.getLevel(refiner.GetMaxLevel());
GregoryBasis::ProtoBasis basis(level, faceIndex, 0, fvarChannel); // Is this method used/supported? If so, needs corner spans (and vert offset?)...
GregoryBasis::ProtoBasis basis(level, faceIndex, 0, 0, fvarChannel);
GregoryBasis * result = new GregoryBasis; GregoryBasis * result = new GregoryBasis;
basis.Copy(result); basis.Copy(result);
@ -86,16 +87,14 @@ EndCapGregoryBasisPatchFactory::Create(TopologyRefiner const & refiner,
} }
bool bool
EndCapGregoryBasisPatchFactory::addPatchBasis(Index faceIndex, EndCapGregoryBasisPatchFactory::addPatchBasis(Vtr::internal::Level const & level, Index faceIndex,
Vtr::internal::Level::VSpan const cornerSpans[],
bool verticesMask[4][5], bool verticesMask[4][5],
int levelVertOffset) { int levelVertOffset) {
// Gregory patches only exist on the hight
Vtr::internal::Level const & level = _refiner->getLevel(_refiner->GetMaxLevel());
// Gather the CVs that influence the Gregory patch and their relative // Gather the CVs that influence the Gregory patch and their relative
// weights in a basis // weights in a basis
GregoryBasis::ProtoBasis basis(level, faceIndex, levelVertOffset, -1); GregoryBasis::ProtoBasis basis(level, faceIndex, cornerSpans, levelVertOffset, -1);
for (int i = 0; i < 4; ++i) { for (int i = 0; i < 4; ++i) {
if (verticesMask[i][0]) { if (verticesMask[i][0]) {
@ -131,8 +130,10 @@ EndCapGregoryBasisPatchFactory::addPatchBasis(Index faceIndex,
ConstIndexArray ConstIndexArray
EndCapGregoryBasisPatchFactory::GetPatchPoints( EndCapGregoryBasisPatchFactory::GetPatchPoints(
Vtr::internal::Level const * level, Index faceIndex, Vtr::internal::Level const * level, Index faceIndex,
Vtr::internal::Level::VSpan const cornerSpans[],
PatchTableFactory::PatchFaceTag const * levelPatchTags, PatchTableFactory::PatchFaceTag const * levelPatchTags,
int levelVertOffset) { int levelVertOffset) {
// allocate indices (awkward) // allocate indices (awkward)
// assert(Vtr::INDEX_INVALID==0xFFFFFFFF); // assert(Vtr::INDEX_INVALID==0xFFFFFFFF);
for (int i = 0; i < 20; ++i) { for (int i = 0; i < 20; ++i) {
@ -164,8 +165,8 @@ EndCapGregoryBasisPatchFactory::GetPatchPoints(
// - exist (no boundary) // - exist (no boundary)
// - have already been processed (known CV indices) // - have already been processed (known CV indices)
// - are also Gregory basis patches // - are also Gregory basis patches
if (adjface!=Vtr::INDEX_INVALID and (adjface < faceIndex) and if (adjface!=Vtr::INDEX_INVALID && (adjface < faceIndex) &&
(not levelPatchTags[adjface]._isRegular)) { (! levelPatchTags[adjface]._isRegular)) {
ConstIndexArray aedges = level->getFaceEdges(adjface); ConstIndexArray aedges = level->getFaceEdges(adjface);
int aedge = aedges.FindIndexIn4Tuple(edge); int aedge = aedges.FindIndexIn4Tuple(edge);
@ -190,8 +191,8 @@ EndCapGregoryBasisPatchFactory::GetPatchPoints(
break; break;
} }
assert(ptr assert(ptr
and srcBasisIdx>=0 && srcBasisIdx>=0
and srcBasisIdx<(int)_faceIndices.size()); && srcBasisIdx<(int)_faceIndices.size());
// Copy the indices of CVs from the face on the other side of the // Copy the indices of CVs from the face on the other side of the
// shared edge // shared edge
@ -227,7 +228,7 @@ EndCapGregoryBasisPatchFactory::GetPatchPoints(
_faceIndices.push_back(faceIndex); _faceIndices.push_back(faceIndex);
// add basis // add basis
addPatchBasis(faceIndex, newVerticesMask, levelVertOffset); addPatchBasis(*level, faceIndex, cornerSpans, newVerticesMask, levelVertOffset);
++_numGregoryBasisPatches; ++_numGregoryBasisPatches;

View File

@ -98,6 +98,8 @@ public:
/// @param level vtr refinement level /// @param level vtr refinement level
/// ///
/// @param faceIndex vtr faceIndex at the level /// @param faceIndex vtr faceIndex at the level
//
/// @param cornerSpans information about topology for each corner of patch
/// ///
/// @param levelPatchTags Array of patchTags for all faces in the level /// @param levelPatchTags Array of patchTags for all faces in the level
/// ///
@ -105,6 +107,7 @@ public:
/// ///
ConstIndexArray GetPatchPoints( ConstIndexArray GetPatchPoints(
Vtr::internal::Level const * level, Index faceIndex, Vtr::internal::Level const * level, Index faceIndex,
Vtr::internal::Level::VSpan const cornerSpans[],
PatchTableFactory::PatchFaceTag const * levelPatchTags, PatchTableFactory::PatchFaceTag const * levelPatchTags,
int levelVertOffset); int levelVertOffset);
@ -112,8 +115,9 @@ private:
/// Creates a basis for the vertices specified in mask on the face and /// Creates a basis for the vertices specified in mask on the face and
/// accumates it /// accumates it
bool addPatchBasis(Index faceIndex, bool newVerticesMask[4][5], bool addPatchBasis(Vtr::internal::Level const & level, Index faceIndex,
int levelVertOffset); Vtr::internal::Level::VSpan const cornerSpans[],
bool newVerticesMask[4][5], int levelVertOffset);
StencilTable *_vertexStencils; StencilTable *_vertexStencils;
StencilTable *_varyingStencils; StencilTable *_varyingStencils;

View File

@ -31,6 +31,7 @@
#include <cassert> #include <cassert>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <cstdio>
namespace OpenSubdiv { namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION { namespace OPENSUBDIV_VERSION {
@ -100,6 +101,7 @@ inline float computeCoefficient(int valence) {
GregoryBasis::ProtoBasis::ProtoBasis( GregoryBasis::ProtoBasis::ProtoBasis(
Vtr::internal::Level const & level, Index faceIndex, Vtr::internal::Level const & level, Index faceIndex,
Vtr::internal::Level::VSpan const cornerSpans[],
int levelVertOffset, int fvarChannel) { int levelVertOffset, int fvarChannel) {
// XXX: This function is subject to refactor in 3.1 // XXX: This function is subject to refactor in 3.1
@ -110,8 +112,7 @@ GregoryBasis::ProtoBasis::ProtoBasis(
assert(facePoints.size()==4); assert(facePoints.size()==4);
int maxvalence = level.getMaxValence(), int maxvalence = level.getMaxValence(),
valences[4], valences[4];
zerothNeighbors[4];
// XXX: a temporary hack for the performance issue // XXX: a temporary hack for the performance issue
// ensure Point has a capacity for the neighborhood of // ensure Point has a capacity for the neighborhood of
@ -140,29 +141,32 @@ GregoryBasis::ProtoBasis::ProtoBasis(
// the first phase // the first phase
for (int vid=0; vid<4; ++vid) { for (int vid=0; vid<4; ++vid) {
// save for varying stencils // save for varying stencils
varyingIndex[vid] = facePoints[vid] + levelVertOffset; varyingIndex[vid] = facePoints[vid] + levelVertOffset;
int ringSize = int ringSize = 0;
level.gatherQuadRegularRingAroundVertex( if (cornerSpans[vid]._numFaces == 0) {
facePoints[vid], manifoldRings[vid], fvarChannel); ringSize = level.gatherQuadRegularRingAroundVertex( facePoints[vid],
manifoldRings[vid], fvarChannel);
} else {
ringSize = level.gatherQuadRegularPartialRingAroundVertex( facePoints[vid],
cornerSpans[vid],
manifoldRings[vid], fvarChannel);
}
int valence; // when the corner vertex is on a boundary (ring-size is odd), valence is
// negated and the ring is padded to replicate the last entry
if (ringSize & 1) { if (ringSize & 1) {
// boundary vertex
manifoldRings[vid][ringSize] = manifoldRings[vid][ringSize-1]; manifoldRings[vid][ringSize] = manifoldRings[vid][ringSize-1];
++ringSize; ++ringSize;
valence = -ringSize/2; valences[vid] = -ringSize/2;
} else { } else {
valence = ringSize/2; valences[vid] = ringSize/2;
} }
int ivalence = abs(valence);
valences[vid] = valence;
Index boundaryEdgeNeighbors[2], int valence = valences[vid];
currentNeighbor = 0, int ivalence = abs(valence);
zerothNeighbor=0,
ibefore=0;
for (int i=0; i<ivalence; ++i) { for (int i=0; i<ivalence; ++i) {
@ -175,35 +179,13 @@ GregoryBasis::ProtoBasis::ProtoBasis(
idx_neighbor_m = (manifoldRings[vid][2*im + 0]), idx_neighbor_m = (manifoldRings[vid][2*im + 0]),
idx_diagonal_m = (manifoldRings[vid][2*im + 1]); idx_diagonal_m = (manifoldRings[vid][2*im + 1]);
bool boundaryNeighbor = (level.getVertexEdges(idx_neighbor).size() >
level.getVertexFaces(idx_neighbor).size());
if (fvarChannel>=0) {
// XXXX manuelk need logic to check for boundary in fvar
boundaryNeighbor = false;
}
if (boundaryNeighbor) {
if (currentNeighbor<2) {
boundaryEdgeNeighbors[currentNeighbor] = idx_neighbor;
}
++currentNeighbor;
if (currentNeighbor==1) {
ibefore = zerothNeighbor = i;
} else {
if (i-ibefore==1) {
std::swap(boundaryEdgeNeighbors[0], boundaryEdgeNeighbors[1]);
zerothNeighbor = i;
}
}
}
float d = float(ivalence)+5.0f; float d = float(ivalence)+5.0f;
f[i].Clear(4); f[i].Clear(4);
f[i].AddWithWeight(facePoints[vid], float(ivalence)/d); f[i].AddWithWeight(facePoints[vid], float(ivalence)/d);
f[i].AddWithWeight(idx_neighbor_p, 2.0f/d); f[i].AddWithWeight(idx_neighbor_p, 2.0f/d);
f[i].AddWithWeight(idx_neighbor, 2.0f/d); f[i].AddWithWeight(idx_neighbor, 2.0f/d);
f[i].AddWithWeight(idx_diagonal, 1.0f/d); f[i].AddWithWeight(idx_diagonal, 1.0f/d);
P[vid].AddWithWeight(f[i], 1.0f/float(ivalence)); P[vid].AddWithWeight(f[i], 1.0f/float(ivalence));
int rid = vid * maxvalence + i; int rid = vid * maxvalence + i;
@ -214,11 +196,6 @@ GregoryBasis::ProtoBasis::ProtoBasis(
r[rid].AddWithWeight(idx_diagonal_m, -1.0f/6.0f); r[rid].AddWithWeight(idx_diagonal_m, -1.0f/6.0f);
} }
zerothNeighbors[vid] = zerothNeighbor;
if (currentNeighbor == 1) {
boundaryEdgeNeighbors[1] = boundaryEdgeNeighbors[0];
}
for (int i=0; i<ivalence; ++i) { for (int i=0; i<ivalence; ++i) {
int im = (i+ivalence-1)%ivalence; int im = (i+ivalence-1)%ivalence;
float c0 = 0.5f * csf(ivalence-3, 2*i); float c0 = 0.5f * csf(ivalence-3, 2*i);
@ -235,14 +212,14 @@ GregoryBasis::ProtoBasis::ProtoBasis(
// Boundary gregory case: // Boundary gregory case:
if (valence < 0) { if (valence < 0) {
Index boundaryEdgeNeighbors[2] = { manifoldRings[vid][0],
manifoldRings[vid][ringSize-1] };
P[vid].Clear(stencilCapacity); P[vid].Clear(stencilCapacity);
if (ivalence>2) { P[vid].AddWithWeight(boundaryEdgeNeighbors[0], 1.0f/6.0f);
P[vid].AddWithWeight(boundaryEdgeNeighbors[0], 1.0f/6.0f); P[vid].AddWithWeight(boundaryEdgeNeighbors[1], 1.0f/6.0f);
P[vid].AddWithWeight(boundaryEdgeNeighbors[1], 1.0f/6.0f); P[vid].AddWithWeight(facePoints[vid], 4.0f/6.0f);
P[vid].AddWithWeight(facePoints[vid], 4.0f/6.0f);
} else {
P[vid].AddWithWeight(facePoints[vid], 1.0f);
}
float k = float(float(ivalence) - 1.0f); //k is the number of faces float k = float(float(ivalence) - 1.0f); //k is the number of faces
float c = cosf(float(M_PI)/k); float c = cosf(float(M_PI)/k);
float s = sinf(float(M_PI)/k); float s = sinf(float(M_PI)/k);
@ -250,7 +227,7 @@ GregoryBasis::ProtoBasis::ProtoBasis(
float alpha_0k = -((1.0f+2.0f*c)*sqrtf(1.0f+c))/((3.0f*k+c)*sqrtf(1.0f-c)); float alpha_0k = -((1.0f+2.0f*c)*sqrtf(1.0f+c))/((3.0f*k+c)*sqrtf(1.0f-c));
float beta_0 = s/(3.0f*k + c); float beta_0 = s/(3.0f*k + c);
int idx_diagonal = manifoldRings[vid][2*zerothNeighbor + 1]; int idx_diagonal = manifoldRings[vid][1];
e0[vid].Clear(stencilCapacity); e0[vid].Clear(stencilCapacity);
e0[vid].AddWithWeight(boundaryEdgeNeighbors[0], 1.0f/6.0f); e0[vid].AddWithWeight(boundaryEdgeNeighbors[0], 1.0f/6.0f);
@ -264,13 +241,11 @@ GregoryBasis::ProtoBasis::ProtoBasis(
for (int x=1; x<ivalence-1; ++x) { for (int x=1; x<ivalence-1; ++x) {
Index curri = ((x + zerothNeighbor)%ivalence);
float alpha = (4.0f*sinf((float(M_PI) * float(x))/k))/(3.0f*k+c), float alpha = (4.0f*sinf((float(M_PI) * float(x))/k))/(3.0f*k+c),
beta = (sinf((float(M_PI) * float(x))/k) + sinf((float(M_PI) * float(x+1))/k))/(3.0f*k+c); beta = (sinf((float(M_PI) * float(x))/k) + sinf((float(M_PI) * float(x+1))/k))/(3.0f*k+c);
Index idx_neighbor = manifoldRings[vid][2*curri + 0], Index idx_neighbor = manifoldRings[vid][2*x + 0],
idx_diagonal = manifoldRings[vid][2*curri + 1]; idx_diagonal = manifoldRings[vid][2*x + 1];
e1[vid].AddWithWeight(idx_neighbor, alpha); e1[vid].AddWithWeight(idx_neighbor, alpha);
e1[vid].AddWithWeight(idx_diagonal, beta); e1[vid].AddWithWeight(idx_diagonal, beta);
@ -316,7 +291,7 @@ GregoryBasis::ProtoBasis::ProtoBasis(
Point Ep_im = P[im]; Point Ep_im = P[im];
if (valences[ip]<-2) { if (valences[ip]<-2) {
Index j = (np + prev_p - zerothNeighbors[ip]) % np; Index j = (np + prev_p) % np;
Em_ip.AddWithWeight(e0[ip], cosf((float(M_PI)*j)/float(np-1))); Em_ip.AddWithWeight(e0[ip], cosf((float(M_PI)*j)/float(np-1)));
Em_ip.AddWithWeight(e1[ip], sinf((float(M_PI)*j)/float(np-1))); Em_ip.AddWithWeight(e1[ip], sinf((float(M_PI)*j)/float(np-1)));
} else { } else {
@ -325,7 +300,7 @@ GregoryBasis::ProtoBasis::ProtoBasis(
} }
if (valences[im]<-2) { if (valences[im]<-2) {
Index j = (nm + start_m - zerothNeighbors[im]) % nm; Index j = (nm + start_m) % nm;
Ep_im.AddWithWeight(e0[im], cosf((float(M_PI)*j)/float(nm-1))); Ep_im.AddWithWeight(e0[im], cosf((float(M_PI)*j)/float(nm-1)));
Ep_im.AddWithWeight(e1[im], sinf((float(M_PI)*j)/float(nm-1))); Ep_im.AddWithWeight(e1[im], sinf((float(M_PI)*j)/float(nm-1)));
} else { } else {
@ -371,8 +346,8 @@ GregoryBasis::ProtoBasis::ProtoBasis(
Fm[vid].AddWithWeight(rp[prev], -1.0f/3.0f); Fm[vid].AddWithWeight(rp[prev], -1.0f/3.0f);
} else if (valences[vid] < -2) { } else if (valences[vid] < -2) {
Index jp = (ivalence + start - zerothNeighbors[vid]) % ivalence, Index jp = (ivalence + start) % ivalence,
jm = (ivalence + prev - zerothNeighbors[vid]) % ivalence; jm = (ivalence + prev) % ivalence;
float s1 = 3-2*csf(n-3,2)-csf(np-3,2), float s1 = 3-2*csf(n-3,2)-csf(np-3,2),
s2 = 2*csf(n-3,2), s2 = 2*csf(n-3,2),

View File

@ -189,6 +189,7 @@ public:
ProtoBasis(Vtr::internal::Level const & level, ProtoBasis(Vtr::internal::Level const & level,
Vtr::Index faceIndex, Vtr::Index faceIndex,
Vtr::internal::Level::VSpan const cornerSpans[],
int levelVertOffset, int levelVertOffset,
int fvarChannel); int fvarChannel);

View File

@ -195,7 +195,7 @@ inline void Spline<BASIS_BILINEAR>::GetPatchWeights(PatchParam const & param,
point[3] = sC * t; point[3] = sC * t;
} }
if (derivS and derivT) { if (derivS && derivT) {
float dScale = (float)(1 << param.GetDepth()); float dScale = (float)(1 << param.GetDepth());
derivS[0] = -tC * dScale; derivS[0] = -tC * dScale;
@ -276,7 +276,7 @@ void Spline<BASIS>::GetPatchWeights(PatchParam const & param,
} }
} }
if (derivS and derivT) { if (derivS && derivT) {
// Compute the tensor product weight of the differentiated (s,t) basis // Compute the tensor product weight of the differentiated (s,t) basis
// function corresponding to each control vertex (scaled accordingly): // function corresponding to each control vertex (scaled accordingly):
@ -403,8 +403,8 @@ void GetGregoryWeights(PatchParam const & param,
// unclear if the approximations will hold up under surface analysis involving higher // unclear if the approximations will hold up under surface analysis involving higher
// order differentiation. // order differentiation.
// //
if (deriv1 and deriv2) { if (deriv1 && deriv2) {
bool find_second_partials = deriv1 and deriv12 and deriv22; bool find_second_partials = deriv1 && deriv12 && deriv22;
// Remember to include derivative scaling in all assignments below: // Remember to include derivative scaling in all assignments below:
float dScale = (float)(1 << param.GetDepth()); float dScale = (float)(1 << param.GetDepth());
float d2Scale = dScale * dScale; float d2Scale = dScale * dScale;

View File

@ -95,7 +95,7 @@ public:
/// \brief Returns true if the type is an adaptive patch /// \brief Returns true if the type is an adaptive patch
static inline bool IsAdaptive(Type type) { static inline bool IsAdaptive(Type type) {
return (type>=LOOP and type<=GREGORY_BASIS); return (type>=LOOP && type<=GREGORY_BASIS);
} }
/// \brief Returns true if the type is an adaptive patch /// \brief Returns true if the type is an adaptive patch

View File

@ -71,7 +71,7 @@ PatchMap::initialize( PatchTable const & patchTable ) {
narrays = (int)patchTable.GetNumPatchArrays(), narrays = (int)patchTable.GetNumPatchArrays(),
npatches = (int)patchTable.GetNumPatchesTotal(); npatches = (int)patchTable.GetNumPatchesTotal();
if (not narrays or not npatches) if (! narrays || ! npatches)
return; return;
// populate subpatch handles vector // populate subpatch handles vector
@ -141,12 +141,12 @@ PatchMap::initialize( PatchTable const & patchTable ) {
if (j==pdepth) { if (j==pdepth) {
// we have reached the depth of the sub-patch : add a leaf // we have reached the depth of the sub-patch : add a leaf
assert( not node->children[quadrant].isSet ); assert( ! node->children[quadrant].isSet );
node->SetChild(quadrant, handleIndex, true); node->SetChild(quadrant, handleIndex, true);
break; break;
} else { } else {
// travel down the child node of the corresponding quadrant // travel down the child node of the corresponding quadrant
if (not node->children[quadrant].isSet) { if (! node->children[quadrant].isSet) {
// create a new branch in the quadrant // create a new branch in the quadrant
node = addChild(quadtree, node, quadrant); node = addChild(quadtree, node, quadrant);
} else { } else {

View File

@ -151,7 +151,7 @@ PatchMap::FindPatch( int faceid, float u, float v ) const {
if (faceid>=(int)_quadtree.size()) if (faceid>=(int)_quadtree.size())
return NULL; return NULL;
assert( (u>=0.0f) and (u<=1.0f) and (v>=0.0f) and (v<=1.0f) ); assert( (u>=0.0f) && (u<=1.0f) && (v>=0.0f) && (v<=1.0f) );
QuadNode const * node = &_quadtree[faceid]; QuadNode const * node = &_quadtree[faceid];
@ -166,7 +166,7 @@ PatchMap::FindPatch( int faceid, float u, float v ) const {
assert(quadrant>=0); assert(quadrant>=0);
// is the quadrant a hole ? // is the quadrant a hole ?
if (not node->children[quadrant].isSet) if (! node->children[quadrant].isSet)
return 0; return 0;
if (node->children[quadrant].isLeaf) { if (node->children[quadrant].isLeaf) {

View File

@ -357,7 +357,7 @@ PatchTable::IsFeatureAdaptive() const {
for (int i=0; i<GetNumPatchArrays(); ++i) { for (int i=0; i<GetNumPatchArrays(); ++i) {
PatchDescriptor const & desc = _patchArrays[i].desc; PatchDescriptor const & desc = _patchArrays[i].desc;
if (desc.GetType()>=PatchDescriptor::REGULAR and if (desc.GetType()>=PatchDescriptor::REGULAR &&
desc.GetType()<=PatchDescriptor::GREGORY_BASIS) { desc.GetType()<=PatchDescriptor::GREGORY_BASIS) {
return true; return true;
} }
@ -393,7 +393,7 @@ PatchTable::getPatchFVarValues(int patch, int channel) const {
int ncvs = PatchDescriptor::GetNumFVarControlVertices(c.patchesType); int ncvs = PatchDescriptor::GetNumFVarControlVertices(c.patchesType);
return ConstIndexArray(&c.patchValues[patch * ncvs], ncvs); return ConstIndexArray(&c.patchValues[patch * ncvs], ncvs);
} else { } else {
assert(patch<(int)c.patchValuesOffsets.size() and assert(patch<(int)c.patchValuesOffsets.size() &&
patch<(int)c.patchTypes.size()); patch<(int)c.patchTypes.size());
return ConstIndexArray(&c.patchValues[c.patchValuesOffsets[patch]], return ConstIndexArray(&c.patchValues[c.patchValuesOffsets[patch]],
PatchDescriptor::GetNumFVarControlVertices(c.patchTypes[patch])); PatchDescriptor::GetNumFVarControlVertices(c.patchTypes[patch]));

View File

@ -350,7 +350,7 @@ PatchTableFactory::allocateVertexTables(PatchTable * table, int /* nlevels */, b
ncvs += table->GetNumControlVertices(i); ncvs += table->GetNumControlVertices(i);
} }
if (ncvs==0 or npatches==0) if (ncvs==0 || npatches==0)
return; return;
table->_patchVerts.resize( ncvs ); table->_patchVerts.resize( ncvs );
@ -369,8 +369,8 @@ void
PatchTableFactory::allocateFVarChannels(TopologyRefiner const & refiner, PatchTableFactory::allocateFVarChannels(TopologyRefiner const & refiner,
Options options, int npatches, PatchTable * table) { Options options, int npatches, PatchTable * table) {
assert(options.generateFVarTables and assert(options.generateFVarTables &&
refiner.GetNumFVarChannels()>0 and npatches>0 and table); refiner.GetNumFVarChannels()>0 && npatches>0 && table);
// Create a channel cursor to iterate over client-selected channels or // Create a channel cursor to iterate over client-selected channels or
// default to the channels found in the TopologyRefiner // default to the channels found in the TopologyRefiner
@ -411,7 +411,7 @@ PatchTableFactory::gatherFVarData(AdaptiveContext & context, int level,
(void)levelFaceOffset; // not used (void)levelFaceOffset; // not used
(void)fofss; // not used (void)fofss; // not used
if (not context.RequiresFVarPatches()) { if (! context.RequiresFVarPatches()) {
return 0; return 0;
} }
@ -542,7 +542,7 @@ PatchTableFactory::createUniform(TopologyRefiner const & refiner, Options option
assert(refiner.IsUniform()); assert(refiner.IsUniform());
// ensure that triangulateQuads is only set for quadrilateral schemes // ensure that triangulateQuads is only set for quadrilateral schemes
options.triangulateQuads &= (refiner.GetSchemeType()==Sdc::SCHEME_BILINEAR or options.triangulateQuads &= (refiner.GetSchemeType()==Sdc::SCHEME_BILINEAR ||
refiner.GetSchemeType()==Sdc::SCHEME_CATMARK); refiner.GetSchemeType()==Sdc::SCHEME_CATMARK);
// level=0 may contain n-gons, which are not supported in PatchTable. // level=0 may contain n-gons, which are not supported in PatchTable.
@ -601,7 +601,7 @@ PatchTableFactory::createUniform(TopologyRefiner const & refiner, Options option
allocateVertexTables( table, 0, /*hasSharpness=*/false ); allocateVertexTables( table, 0, /*hasSharpness=*/false );
FVarChannelCursor fvc(refiner, options); FVarChannelCursor fvc(refiner, options);
bool generateFVarPatches = (options.generateFVarTables and fvc.size()>0); bool generateFVarPatches = (options.generateFVarTables && fvc.size()>0);
if (generateFVarPatches) { if (generateFVarPatches) {
int npatches = table->GetNumPatchesTotal(); int npatches = table->GetNumPatchesTotal();
allocateFVarChannels(refiner, options, npatches, table); allocateFVarChannels(refiner, options, npatches, table);
@ -639,7 +639,7 @@ PatchTableFactory::createUniform(TopologyRefiner const & refiner, Options option
if (level>=firstlevel) { if (level>=firstlevel) {
for (int face=0; face<nfaces; ++face) { for (int face=0; face<nfaces; ++face) {
if (refiner.HasHoles() and refLevel.IsFaceHole(face)) { if (refiner.HasHoles() && refLevel.IsFaceHole(face)) {
continue; continue;
} }
@ -696,7 +696,7 @@ PatchTableFactory::createUniform(TopologyRefiner const & refiner, Options option
PatchTable * PatchTable *
PatchTableFactory::createAdaptive(TopologyRefiner const & refiner, Options options) { PatchTableFactory::createAdaptive(TopologyRefiner const & refiner, Options options) {
assert(not refiner.IsUniform()); assert(! refiner.IsUniform());
PtexIndices ptexIndices(refiner); PtexIndices ptexIndices(refiner);
@ -872,16 +872,16 @@ PatchTableFactory::identifyAdaptivePatches(AdaptiveContext & context) {
bool hasXOrdinaryVertex = compFaceVertTag._xordinary; bool hasXOrdinaryVertex = compFaceVertTag._xordinary;
patchTag._hasPatch = true; patchTag._hasPatch = true;
patchTag._isRegular = not hasXOrdinaryVertex or hasNonManifoldVertex; patchTag._isRegular = ! hasXOrdinaryVertex || hasNonManifoldVertex;
// single crease patch optimization // single crease patch optimization
if (context.options.useSingleCreasePatch and if (context.options.useSingleCreasePatch &&
not hasXOrdinaryVertex and not hasBoundaryVertex and not hasNonManifoldVertex) { ! hasXOrdinaryVertex && ! hasBoundaryVertex && ! hasNonManifoldVertex) {
Vtr::ConstIndexArray fEdges = level->getFaceEdges(faceIndex); Vtr::ConstIndexArray fEdges = level->getFaceEdges(faceIndex);
Vtr::internal::Level::ETag compFaceETag = level->getFaceCompositeETag(fEdges); Vtr::internal::Level::ETag compFaceETag = level->getFaceCompositeETag(fEdges);
if (compFaceETag._semiSharp or compFaceETag._infSharp) { if (compFaceETag._semiSharp || compFaceETag._infSharp) {
float sharpness = 0; float sharpness = 0;
int rotation = 0; int rotation = 0;
if (level->isSingleCreasePatch(faceIndex, &sharpness, &rotation)) { if (level->isSingleCreasePatch(faceIndex, &sharpness, &rotation)) {
@ -902,7 +902,7 @@ PatchTableFactory::identifyAdaptivePatches(AdaptiveContext & context) {
// for regular patches, though an irregular patch or extrapolated boundary patch // for regular patches, though an irregular patch or extrapolated boundary patch
// is really necessary in future for some non-manifold cases. // is really necessary in future for some non-manifold cases.
// //
if (hasBoundaryVertex or hasNonManifoldVertex) { if (hasBoundaryVertex || hasNonManifoldVertex) {
Vtr::ConstIndexArray fEdges = level->getFaceEdges(faceIndex); Vtr::ConstIndexArray fEdges = level->getFaceEdges(faceIndex);
int boundaryEdgeMask = ((level->getEdgeTag(fEdges[0])._boundary) << 0) | int boundaryEdgeMask = ((level->getEdgeTag(fEdges[0])._boundary) << 0) |
@ -971,7 +971,7 @@ PatchTableFactory::identifyAdaptivePatches(AdaptiveContext & context) {
bool approxSmoothCornerWithRegularPatch = true; bool approxSmoothCornerWithRegularPatch = true;
if (approxSmoothCornerWithRegularPatch) { if (approxSmoothCornerWithRegularPatch) {
if (!patchTag._isRegular and (patchTag._boundaryCount == 2)) { if (!patchTag._isRegular && (patchTag._boundaryCount == 2)) {
// We may have a sharp corner opposite/adjacent an xordinary vertex -- // We may have a sharp corner opposite/adjacent an xordinary vertex --
// need to make sure there is only one xordinary vertex and that it // need to make sure there is only one xordinary vertex and that it
// is the corner vertex. // is the corner vertex.
@ -987,7 +987,7 @@ PatchTableFactory::identifyAdaptivePatches(AdaptiveContext & context) {
if (xordCount == 1) { if (xordCount == 1) {
// We require the vertex opposite the xordinary vertex be interior: // We require the vertex opposite the xordinary vertex be interior:
if (not level->getVertexTag(fVerts[(xordVertex + 2) % 4])._boundary) { if (! level->getVertexTag(fVerts[(xordVertex + 2) % 4])._boundary) {
patchTag._isRegular = true; patchTag._isRegular = true;
} }
} }
@ -1162,7 +1162,7 @@ PatchTableFactory::populateAdaptivePatches(
} }
const PatchFaceTag& patchTag = levelPatchTags[faceIndex]; const PatchFaceTag& patchTag = levelPatchTags[faceIndex];
if (not patchTag._hasPatch) { if (! patchTag._hasPatch) {
continue; continue;
} }
@ -1223,19 +1223,24 @@ PatchTableFactory::populateAdaptivePatches(
// emit end patch. end patch should be in the max level (until we implement DFAS) // emit end patch. end patch should be in the max level (until we implement DFAS)
assert(i==refiner.GetMaxLevel()); assert(i==refiner.GetMaxLevel());
// identify relevant spans around the corner vertices for the irregular patches
// (this is just a stub for now -- leaving the span "size" to zero, as constructed,
// indicates to use the full neighborhood)...
Vtr::internal::Level::VSpan cornerSpans[4];
// switch endcap patchtype by option // switch endcap patchtype by option
switch(context.options.GetEndCapType()) { switch(context.options.GetEndCapType()) {
case Options::ENDCAP_GREGORY_BASIS: case Options::ENDCAP_GREGORY_BASIS:
{ {
// note: this call will be moved into vtr::level. // note: this call will be moved into vtr::level.
ConstIndexArray cvs = endCapGregoryBasis->GetPatchPoints( ConstIndexArray cvs = endCapGregoryBasis->GetPatchPoints(
level, faceIndex, levelPatchTags, levelVertOffset); level, faceIndex, cornerSpans, levelPatchTags, levelVertOffset);
for (int j = 0; j < cvs.size(); ++j) iptrs.GP[j] = cvs[j]; for (int j = 0; j < cvs.size(); ++j) iptrs.GP[j] = cvs[j];
iptrs.GP += cvs.size(); iptrs.GP += cvs.size();
pptrs.GP = computePatchParam( pptrs.GP = computePatchParam(
refiner, ptexIndices, i, faceIndex, /*boundary*/0, /*transition*/0, pptrs.GP); refiner, ptexIndices, i, faceIndex, /*boundary*/0, /*transition*/0, pptrs.GP);
if (sptrs.R) *sptrs.R++ = assignSharpnessIndex(0, table->_sharpnessValues); if (sptrs.GP) *sptrs.GP++ = assignSharpnessIndex(0, table->_sharpnessValues);
fofss.GP += gatherFVarData(context, fofss.GP += gatherFVarData(context,
i, faceIndex, levelFaceOffset, i, faceIndex, levelFaceOffset,
0, levelFVarVertOffsets, fofss.GP, fptrs.GP); 0, levelFVarVertOffsets, fofss.GP, fptrs.GP);
@ -1244,7 +1249,7 @@ PatchTableFactory::populateAdaptivePatches(
case Options::ENDCAP_BSPLINE_BASIS: case Options::ENDCAP_BSPLINE_BASIS:
{ {
ConstIndexArray cvs = endCapBSpline->GetPatchPoints( ConstIndexArray cvs = endCapBSpline->GetPatchPoints(
level, faceIndex, levelPatchTags, levelVertOffset); level, faceIndex, cornerSpans, levelPatchTags, levelVertOffset);
for (int j = 0; j < cvs.size(); ++j) iptrs.R[j] = cvs[j]; for (int j = 0; j < cvs.size(); ++j) iptrs.R[j] = cvs[j];
iptrs.R += cvs.size(); iptrs.R += cvs.size();
@ -1266,7 +1271,7 @@ PatchTableFactory::populateAdaptivePatches(
iptrs.G += cvs.size(); iptrs.G += cvs.size();
pptrs.G = computePatchParam( pptrs.G = computePatchParam(
refiner, ptexIndices, i, faceIndex, /*boundary*/0, /*transition*/0, pptrs.G); refiner, ptexIndices, i, faceIndex, /*boundary*/0, /*transition*/0, pptrs.G);
if (sptrs.R) *sptrs.R++ = assignSharpnessIndex(0, table->_sharpnessValues); if (sptrs.G) *sptrs.G++ = assignSharpnessIndex(0, table->_sharpnessValues);
fofss.G += gatherFVarData(context, fofss.G += gatherFVarData(context,
i, faceIndex, levelFaceOffset, i, faceIndex, levelFaceOffset,
0, levelFVarVertOffsets, fofss.G, fptrs.G); 0, levelFVarVertOffsets, fofss.G, fptrs.G);
@ -1275,7 +1280,7 @@ PatchTableFactory::populateAdaptivePatches(
iptrs.GB += cvs.size(); iptrs.GB += cvs.size();
pptrs.GB = computePatchParam( pptrs.GB = computePatchParam(
refiner, ptexIndices, i, faceIndex, /*boundary*/0, /*transition*/0, pptrs.GB); refiner, ptexIndices, i, faceIndex, /*boundary*/0, /*transition*/0, pptrs.GB);
if (sptrs.R) *sptrs.R++ = assignSharpnessIndex(0, table->_sharpnessValues); if (sptrs.GB) *sptrs.GB++ = assignSharpnessIndex(0, table->_sharpnessValues);
fofss.GB += gatherFVarData(context, fofss.GB += gatherFVarData(context,
i, faceIndex, levelFaceOffset, i, faceIndex, levelFaceOffset,
0, levelFVarVertOffsets, fofss.GB, fptrs.GB); 0, levelFVarVertOffsets, fofss.GB, fptrs.GB);
@ -1303,10 +1308,19 @@ PatchTableFactory::populateAdaptivePatches(
} }
// finalize end patches // finalize end patches
if (localPointStencils) if (localPointStencils && localPointStencils->GetNumStencils() > 0) {
localPointStencils->generateOffsets(); localPointStencils->finalize();
if (localPointVaryingStencils) } else {
localPointVaryingStencils->generateOffsets(); delete localPointStencils;
localPointStencils = NULL;
}
if (localPointVaryingStencils && localPointVaryingStencils->GetNumStencils() > 0) {
localPointVaryingStencils->finalize();
} else {
delete localPointVaryingStencils;
localPointVaryingStencils = NULL;
}
switch(context.options.GetEndCapType()) { switch(context.options.GetEndCapType()) {
case Options::ENDCAP_GREGORY_BASIS: case Options::ENDCAP_GREGORY_BASIS:

View File

@ -265,7 +265,7 @@ template <class T, class U>
inline void inline void
PrimvarRefiner::Interpolate(int level, T const & src, U & dst) const { PrimvarRefiner::Interpolate(int level, T const & src, U & dst) const {
assert(level>0 and level<=(int)_refiner._refinements.size()); assert(level>0 && level<=(int)_refiner._refinements.size());
switch (_refiner._subdivType) { switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK: case Sdc::SCHEME_CATMARK:
@ -290,7 +290,7 @@ template <class T, class U>
inline void inline void
PrimvarRefiner::InterpolateFaceVarying(int level, T const & src, U & dst, int channel) const { PrimvarRefiner::InterpolateFaceVarying(int level, T const & src, U & dst, int channel) const {
assert(level>0 and level<=(int)_refiner._refinements.size()); assert(level>0 && level<=(int)_refiner._refinements.size());
switch (_refiner._subdivType) { switch (_refiner._subdivType) {
case Sdc::SCHEME_CATMARK: case Sdc::SCHEME_CATMARK:
@ -387,7 +387,7 @@ template <class T, class U>
inline void inline void
PrimvarRefiner::InterpolateFaceUniform(int level, T const & src, U & dst) const { PrimvarRefiner::InterpolateFaceUniform(int level, T const & src, U & dst) const {
assert(level>0 and level<=(int)_refiner._refinements.size()); assert(level>0 && level<=(int)_refiner._refinements.size());
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1); Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & child = refinement.child(); Vtr::internal::Level const & child = refinement.child();
@ -404,7 +404,7 @@ template <class T, class U>
inline void inline void
PrimvarRefiner::InterpolateVarying(int level, T const & src, U & dst) const { PrimvarRefiner::InterpolateVarying(int level, T const & src, U & dst) const {
assert(level>0 and level<=(int)_refiner._refinements.size()); assert(level>0 && level<=(int)_refiner._refinements.size());
Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1); Vtr::internal::Refinement const & refinement = _refiner.getRefinement(level-1);
Vtr::internal::Level const & parent = refinement.parent(); Vtr::internal::Level const & parent = refinement.parent();

View File

@ -150,7 +150,7 @@ PtexIndices::GetAdjacency(
// o----------o----------o // o----------o----------o
// v0 v1 // v0 v1
*/ */
assert(quadrant>=0 and quadrant<fedges.size()); assert(quadrant>=0 && quadrant<fedges.size());
int nextQuadrant = (quadrant+1) % fedges.size(), int nextQuadrant = (quadrant+1) % fedges.size(),
prevQuadrant = (quadrant+fedges.size()-1) % fedges.size(); prevQuadrant = (quadrant+fedges.size()-1) % fedges.size();

View File

@ -265,7 +265,7 @@ private:
// //
// Additionally, if the client does not want the resulting verts // Additionally, if the client does not want the resulting verts
// compacted, do not attempt to combine weights. // compacted, do not attempt to combine weights.
if (_compactWeights and !_dests.empty() and _dests[lastOffset] == dst) { if (_compactWeights && !_dests.empty() && _dests[lastOffset] == dst) {
// tableSize is exactly _sources.size(), but using tableSize is // tableSize is exactly _sources.size(), but using tableSize is
// significantly faster. // significantly faster.
@ -293,7 +293,7 @@ private:
// a way that the current stencil being built is always at the end of // a way that the current stencil being built is always at the end of
// the array, so if the dests array is empty or back() doesn't match // the array, so if the dests array is empty or back() doesn't match
// dst, then we just started building a new stencil. // dst, then we just started building a new stencil.
if (_dests.empty() or dst != _dests.back()) { if (_dests.empty() || dst != _dests.back()) {
// _indices and _sizes always have num(stencils) elements so that // _indices and _sizes always have num(stencils) elements so that
// stencils can be directly looked up by their index in these // stencils can be directly looked up by their index in these
// arrays. So here, ensure that they are large enough to hold the // arrays. So here, ensure that they are large enough to hold the
@ -470,8 +470,8 @@ void
StencilBuilder::Index::AddWithWeight(Stencil const& src, StencilBuilder::Index::AddWithWeight(Stencil const& src,
float weight, float du, float dv, float duu, float duv, float dvv) float weight, float du, float dv, float duu, float duv, float dvv)
{ {
if (isWeightZero(weight) and isWeightZero(du) and isWeightZero(dv) and if (isWeightZero(weight) && isWeightZero(du) && isWeightZero(dv) &&
isWeightZero(duu) and isWeightZero(duv) and isWeightZero(dvv)) { isWeightZero(duu) && isWeightZero(duv) && isWeightZero(dvv)) {
return; return;
} }

View File

@ -81,7 +81,7 @@ namespace {
for ( size_t i=start; i<offsets->size(); i++ ) { for ( size_t i=start; i<offsets->size(); i++ ) {
// Once we've copied out all the control verts, jump to the offset // Once we've copied out all the control verts, jump to the offset
// where the actual stencils begin. // where the actual stencils begin.
if (includeCoarseVerts and (int)i == numControlVerts) if (includeCoarseVerts && (int)i == numControlVerts)
i = firstOffset; i = firstOffset;
// Copy the stencil. // Copy the stencil.

View File

@ -208,6 +208,12 @@ protected:
// Reserves the table arrays (factory helper) // Reserves the table arrays (factory helper)
void reserve(int nstencils, int nelems); void reserve(int nstencils, int nelems);
// Reallocates the table arrays to remove excess capacity (factory helper)
void shrinkToFit();
// Performs any final operations on internal tables (factory helper)
void finalize();
protected: protected:
StencilTable() : _numControlVertices(0) {} StencilTable() : _numControlVertices(0) {}
StencilTable(int numControlVerts) StencilTable(int numControlVerts)
@ -416,7 +422,7 @@ StencilTable::update(T const *controlValues, T *values,
values += start; values += start;
} }
if (end<start or end<0) { if (end<start || end<0) {
end = GetNumStencils(); end = GetNumStencils();
} }
@ -458,10 +464,23 @@ StencilTable::reserve(int nstencils, int nelems) {
_weights.reserve(nelems); _weights.reserve(nelems);
} }
inline void
StencilTable::shrinkToFit() {
std::vector<int>(_sizes).swap(_sizes);
std::vector<Index>(_indices).swap(_indices);
std::vector<float>(_weights).swap(_weights);
}
inline void
StencilTable::finalize() {
shrinkToFit();
generateOffsets();
}
// Returns a Stencil at index i in the table // Returns a Stencil at index i in the table
inline Stencil inline Stencil
StencilTable::GetStencil(Index i) const { StencilTable::GetStencil(Index i) const {
assert((not _offsets.empty()) and i<(int)_offsets.size()); assert((! _offsets.empty()) && i<(int)_offsets.size());
Index ofs = _offsets[i]; Index ofs = _offsets[i];
@ -485,7 +504,7 @@ LimitStencilTable::resize(int nstencils, int nelems) {
// Returns a LimitStencil at index i in the table // Returns a LimitStencil at index i in the table
inline LimitStencil inline LimitStencil
LimitStencilTable::GetLimitStencil(Index i) const { LimitStencilTable::GetLimitStencil(Index i) const {
assert((not GetOffsets().empty()) and i<(int)GetOffsets().size()); assert((! GetOffsets().empty()) && i<(int)GetOffsets().size());
Index ofs = GetOffsets()[i]; Index ofs = GetOffsets()[i];

View File

@ -76,7 +76,7 @@ StencilTableFactory::Create(TopologyRefiner const & refiner,
Options options) { Options options) {
int maxlevel = std::min(int(options.maxLevel), refiner.GetMaxLevel()); int maxlevel = std::min(int(options.maxLevel), refiner.GetMaxLevel());
if (maxlevel==0 and (not options.generateControlVerts)) { if (maxlevel==0 && (! options.generateControlVerts)) {
StencilTable * result = new StencilTable; StencilTable * result = new StencilTable;
result->_numControlVertices = refiner.GetLevel(0).GetNumVertices(); result->_numControlVertices = refiner.GetLevel(0).GetNumVertices();
return result; return result;
@ -98,7 +98,7 @@ StencilTableFactory::Create(TopologyRefiner const & refiner,
refiner.GetLevel(0).GetNumVertices()); refiner.GetLevel(0).GetNumVertices());
for (int level=1; level<=maxlevel; ++level) { for (int level=1; level<=maxlevel; ++level) {
if (not interpolateVarying) { if (! interpolateVarying) {
primvarRefiner.Interpolate(level, srcIndex, dstIndex); primvarRefiner.Interpolate(level, srcIndex, dstIndex);
} else { } else {
primvarRefiner.InterpolateVarying(level, srcIndex, dstIndex); primvarRefiner.InterpolateVarying(level, srcIndex, dstIndex);
@ -110,7 +110,7 @@ StencilTableFactory::Create(TopologyRefiner const & refiner,
dstIndex = dstIndex[refiner.GetLevel(level).GetNumVertices()]; dstIndex = dstIndex[refiner.GetLevel(level).GetNumVertices()];
if (not options.factorizeIntermediateLevels) { if (! options.factorizeIntermediateLevels) {
// All previous verts are considered as coarse verts, as a // All previous verts are considered as coarse verts, as a
// result, we don't update the srcIndex and update the coarse // result, we don't update the srcIndex and update the coarse
// vertex count. // vertex count.
@ -119,7 +119,7 @@ StencilTableFactory::Create(TopologyRefiner const & refiner,
} }
size_t firstOffset = refiner.GetLevel(0).GetNumVertices(); size_t firstOffset = refiner.GetLevel(0).GetNumVertices();
if (not options.generateIntermediateLevels) if (! options.generateIntermediateLevels)
firstOffset = srcIndex.GetOffset(); firstOffset = srcIndex.GetOffset();
// Copy stencils from the StencilBuilder into the StencilTable. // Copy stencils from the StencilBuilder into the StencilTable.
@ -146,7 +146,7 @@ StencilTableFactory::Create(int numTables, StencilTable const ** tables) {
// other Create() API returns an empty stencil instead of NULL. // other Create() API returns an empty stencil instead of NULL.
// They need to be consistent. // They need to be consistent.
if ( (numTables<=0) or (not tables)) { if ( (numTables<=0) || (! tables)) {
return NULL; return NULL;
} }
@ -160,7 +160,7 @@ StencilTableFactory::Create(int numTables, StencilTable const ** tables) {
// allow the tables could have a null entry. // allow the tables could have a null entry.
if (!st) continue; if (!st) continue;
if (ncvs >= 0 and st->GetNumControlVertices() != ncvs) { if (ncvs >= 0 && st->GetNumControlVertices() != ncvs) {
return NULL; return NULL;
} }
ncvs = st->GetNumControlVertices(); ncvs = st->GetNumControlVertices();
@ -211,8 +211,9 @@ StencilTableFactory::AppendLocalPointStencilTable(
bool factorize) { bool factorize) {
// factorize and append. // factorize and append.
if (baseStencilTable == NULL or if (baseStencilTable == NULL ||
localPointStencilTable == NULL) return NULL; localPointStencilTable == NULL ||
localPointStencilTable->GetNumStencils() == 0) return NULL;
// baseStencilTable can be built with or without singular stencils // baseStencilTable can be built with or without singular stencils
// (single weight of 1.0f) as place-holders for coarse mesh vertices. // (single weight of 1.0f) as place-holders for coarse mesh vertices.
@ -359,7 +360,7 @@ LimitStencilTableFactory::Create(TopologyRefiner const & refiner,
int maxlevel = refiner.GetMaxLevel(); int maxlevel = refiner.GetMaxLevel();
StencilTable const * cvstencils = cvStencilsIn; StencilTable const * cvstencils = cvStencilsIn;
if (not cvstencils) { if (! cvstencils) {
// Generate stencils for the control vertices - this is necessary to // Generate stencils for the control vertices - this is necessary to
// properly factorize patches with control vertices at level 0 (natural // properly factorize patches with control vertices at level 0 (natural
// regular patches, such as in a torus) // regular patches, such as in a torus)
@ -389,7 +390,7 @@ LimitStencilTableFactory::Create(TopologyRefiner const & refiner,
// If a stencil table was given, use it, otherwise, create a new one // If a stencil table was given, use it, otherwise, create a new one
PatchTable const * patchtable = patchTableIn; PatchTable const * patchtable = patchTableIn;
if (not patchtable) { if (! patchtable) {
// XXXX (manuelk) If no patch-table was passed, we should be able to // XXXX (manuelk) If no patch-table was passed, we should be able to
// infer the patches fairly easily from the refiner. Once more tags // infer the patches fairly easily from the refiner. Once more tags
// have been added to the refiner, maybe we can remove the need for the // have been added to the refiner, maybe we can remove the need for the
@ -401,7 +402,7 @@ LimitStencilTableFactory::Create(TopologyRefiner const & refiner,
patchtable = PatchTableFactory::Create(refiner, options); patchtable = PatchTableFactory::Create(refiner, options);
if (not cvStencilsIn) { if (! cvStencilsIn) {
// if cvstencils is just created above, append endcap stencils // if cvstencils is just created above, append endcap stencils
if (StencilTable const *localPointStencilTable = if (StencilTable const *localPointStencilTable =
patchtable->GetLocalPointStencilTable()) { patchtable->GetLocalPointStencilTable()) {
@ -415,15 +416,15 @@ LimitStencilTableFactory::Create(TopologyRefiner const & refiner,
} else { } else {
// Sanity checks // Sanity checks
if (patchtable->IsFeatureAdaptive()==uniform) { if (patchtable->IsFeatureAdaptive()==uniform) {
if (not cvStencilsIn) { if (! cvStencilsIn) {
assert(cvstencils and cvstencils!=cvStencilsIn); assert(cvstencils && cvstencils!=cvStencilsIn);
delete cvstencils; delete cvstencils;
} }
return 0; return 0;
} }
} }
assert(patchtable and cvstencils); assert(patchtable && cvstencils);
// Create a patch-map to locate sub-patches faster // Create a patch-map to locate sub-patches faster
PatchMap patchmap( *patchtable ); PatchMap patchmap( *patchtable );
@ -468,11 +469,11 @@ LimitStencilTableFactory::Create(TopologyRefiner const & refiner,
} }
} }
if (not cvStencilsIn) { if (! cvStencilsIn) {
delete cvstencils; delete cvstencils;
} }
if (not patchTableIn) { if (! patchTableIn) {
delete patchtable; delete patchtable;
} }

View File

@ -95,7 +95,7 @@ bool
TopologyRefinerFactory<TopologyDescriptor>::assignComponentTags( TopologyRefinerFactory<TopologyDescriptor>::assignComponentTags(
TopologyRefiner & refiner, TopologyDescriptor const & desc) { TopologyRefiner & refiner, TopologyDescriptor const & desc) {
if ((desc.numCreases>0) and desc.creaseVertexIndexPairs and desc.creaseWeights) { if ((desc.numCreases>0) && desc.creaseVertexIndexPairs && desc.creaseWeights) {
int const * vertIndexPairs = desc.creaseVertexIndexPairs; int const * vertIndexPairs = desc.creaseVertexIndexPairs;
for (int edge=0; edge<desc.numCreases; ++edge, vertIndexPairs+=2) { for (int edge=0; edge<desc.numCreases; ++edge, vertIndexPairs+=2) {
@ -113,13 +113,13 @@ TopologyRefinerFactory<TopologyDescriptor>::assignComponentTags(
} }
} }
if ((desc.numCorners>0) and desc.cornerVertexIndices and desc.cornerWeights) { if ((desc.numCorners>0) && desc.cornerVertexIndices && desc.cornerWeights) {
for (int vert=0; vert<desc.numCorners; ++vert) { for (int vert=0; vert<desc.numCorners; ++vert) {
int idx = desc.cornerVertexIndices[vert]; int idx = desc.cornerVertexIndices[vert];
if (idx >= 0 and idx < getNumBaseVertices(refiner)) { if (idx >= 0 && idx < getNumBaseVertices(refiner)) {
setBaseVertexSharpness(refiner, idx, desc.cornerWeights[vert]); setBaseVertexSharpness(refiner, idx, desc.cornerWeights[vert]);
} else { } else {
char msg[1024]; char msg[1024];

View File

@ -360,7 +360,7 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
considerFVarChannels = false; considerFVarChannels = false;
for (int channel = 0; channel < numFVarChannels; ++channel) { for (int channel = 0; channel < numFVarChannels; ++channel) {
if (not level.getFVarLevel(channel).isLinear()) { if (! level.getFVarLevel(channel).isLinear()) {
considerFVarChannels = true; considerFVarChannels = true;
break; break;
} }
@ -425,7 +425,7 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
} else if (compFaceVTag._rule & Sdc::Crease::RULE_DART) { } else if (compFaceVTag._rule & Sdc::Crease::RULE_DART) {
// Any occurrence of a Dart vertex requires isolation // Any occurrence of a Dart vertex requires isolation
selectFace = true; selectFace = true;
} else if (not (compFaceVTag._rule & Sdc::Crease::RULE_SMOOTH)) { } else if (! (compFaceVTag._rule & Sdc::Crease::RULE_SMOOTH)) {
// None of the vertices is Smooth, so we have all vertices either Crease or Corner. // None of the vertices is Smooth, so we have all vertices either Crease or Corner.
// Though some may be regular patches, this currently warrants isolation as we only // Though some may be regular patches, this currently warrants isolation as we only
// support regular patches with one corner or one boundary, i.e. with one or more // support regular patches with one corner or one boundary, i.e. with one or more
@ -435,12 +435,12 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
// Any semi-sharp feature at or around the vertex warrants isolation -- unless we // Any semi-sharp feature at or around the vertex warrants isolation -- unless we
// optimize for the single-crease patch, i.e. only edge sharpness of a constant value // optimize for the single-crease patch, i.e. only edge sharpness of a constant value
// along the entire regular patch boundary (quickly exclude the Corner case first): // along the entire regular patch boundary (quickly exclude the Corner case first):
if (considerSingleCreasePatch && not (compFaceVTag._rule & Sdc::Crease::RULE_CORNER)) { if (considerSingleCreasePatch && ! (compFaceVTag._rule & Sdc::Crease::RULE_CORNER)) {
selectFace = not level.isSingleCreasePatch(face); selectFace = ! level.isSingleCreasePatch(face);
} else { } else {
selectFace = true; selectFace = true;
} }
} else if (not compFaceVTag._boundary) { } else if (! compFaceVTag._boundary) {
// At this point we are left with a mix of smooth and inf-sharp features. If not // At this point we are left with a mix of smooth and inf-sharp features. If not
// on a boundary, the interior inf-sharp features need isolation -- unless we are // on a boundary, the interior inf-sharp features need isolation -- unless we are
// again optimizing for the single-crease patch, infinitely sharp in this case. // again optimizing for the single-crease patch, infinitely sharp in this case.
@ -449,12 +449,12 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
// is kept separate for the inf-sharp case: a separate and much more efficient // is kept separate for the inf-sharp case: a separate and much more efficient
// test can be made for the inf-sharp case, and there are other opportunities here // test can be made for the inf-sharp case, and there are other opportunities here
// to optimize for regular patches at infinitely sharp corners. // to optimize for regular patches at infinitely sharp corners.
if (considerSingleCreasePatch && not (compFaceVTag._rule & Sdc::Crease::RULE_CORNER)) { if (considerSingleCreasePatch && ! (compFaceVTag._rule & Sdc::Crease::RULE_CORNER)) {
selectFace = not level.isSingleCreasePatch(face); selectFace = ! level.isSingleCreasePatch(face);
} else { } else {
selectFace = true; selectFace = true;
} }
} else if (not (compFaceVTag._rule & Sdc::Crease::RULE_CORNER)) { } else if (! (compFaceVTag._rule & Sdc::Crease::RULE_CORNER)) {
// We are now left with boundary faces -- if no Corner vertex, we have a mix of both // We are now left with boundary faces -- if no Corner vertex, we have a mix of both
// regular Smooth and Crease vertices on a boundary face, which can only be a regular // regular Smooth and Crease vertices on a boundary face, which can only be a regular
// boundary patch, so don't isolate. // boundary patch, so don't isolate.
@ -462,7 +462,7 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
} else { } else {
// The last case with at least one Corner vertex and one Smooth (interior) vertex -- // The last case with at least one Corner vertex and one Smooth (interior) vertex --
// distinguish the regular corner case from others: // distinguish the regular corner case from others:
if (not compFaceVTag._corner) { if (! compFaceVTag._corner) {
// We may consider interior sharp corners as regular in future, but for now we // We may consider interior sharp corners as regular in future, but for now we
// only accept a topological corner for the regular corner case: // only accept a topological corner for the regular corner case:
selectFace = true; selectFace = true;
@ -485,8 +485,8 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
// If still not selected, inspect the face-varying channels (when present) for similar // If still not selected, inspect the face-varying channels (when present) for similar
// irregular features requiring isolation: // irregular features requiring isolation:
// //
if (not selectFace and considerFVarChannels) { if (! selectFace && considerFVarChannels) {
for (int channel = 0; not selectFace && (channel < numFVarChannels); ++channel) { for (int channel = 0; ! selectFace && (channel < numFVarChannels); ++channel) {
Vtr::internal::FVarLevel const & fvarLevel = level.getFVarLevel(channel); Vtr::internal::FVarLevel const & fvarLevel = level.getFVarLevel(channel);
// //
@ -501,7 +501,7 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
fvarLevel.getFaceCompositeValueTag(faceValues, faceVerts); fvarLevel.getFaceCompositeValueTag(faceValues, faceVerts);
// No mismatch in topology -> no need to further isolate... // No mismatch in topology -> no need to further isolate...
if (not compFVarFaceTag._mismatch) continue; if (! compFVarFaceTag._mismatch) continue;
if (compFVarFaceTag._xordinary) { if (compFVarFaceTag._xordinary) {
// An xordinary boundary value always requires isolation: // An xordinary boundary value always requires isolation:
@ -514,10 +514,10 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
Vtr::internal::Level::VTag compFVarVTag = Vtr::internal::Level::VTag compFVarVTag =
fvarLevel.getFaceCompositeValueAndVTag(faceValues, faceVerts, fvarVTags); fvarLevel.getFaceCompositeValueAndVTag(faceValues, faceVerts, fvarVTags);
if (not (compFVarVTag._rule & Sdc::Crease::RULE_SMOOTH)) { if (! (compFVarVTag._rule & Sdc::Crease::RULE_SMOOTH)) {
// No Smooth corners so too many boundaries/corners -- need to isolate: // No Smooth corners so too many boundaries/corners -- need to isolate:
selectFace = true; selectFace = true;
} else if (not (compFVarVTag._rule & Sdc::Crease::RULE_CORNER)) { } else if (! (compFVarVTag._rule & Sdc::Crease::RULE_CORNER)) {
// A mix of Smooth and Crease corners -- must be regular so don't isolate: // A mix of Smooth and Crease corners -- must be regular so don't isolate:
selectFace = false; selectFace = false;
} else { } else {
@ -537,7 +537,7 @@ TopologyRefiner::selectFeatureAdaptiveComponents(Vtr::internal::SparseSelector&
// (the topological corner tag catches this above). Verify that the corner // (the topological corner tag catches this above). Verify that the corner
// vertex is opposite the smooth vertex (and consider doing this above)... // vertex is opposite the smooth vertex (and consider doing this above)...
// //
if (not selectFace && (level.getDepth() == 0)) { if (! selectFace && (level.getDepth() == 0)) {
if (fvarVTags[0]._infSharp && fvarVTags[2]._boundary) selectFace = true; if (fvarVTags[0]._infSharp && fvarVTags[2]._boundary) selectFace = true;
if (fvarVTags[1]._infSharp && fvarVTags[3]._boundary) selectFace = true; if (fvarVTags[1]._infSharp && fvarVTags[3]._boundary) selectFace = true;
if (fvarVTags[2]._infSharp && fvarVTags[0]._boundary) selectFace = true; if (fvarVTags[2]._infSharp && fvarVTags[0]._boundary) selectFace = true;

View File

@ -66,7 +66,7 @@ public:
bool IsUniform() const { return _isUniform; } bool IsUniform() const { return _isUniform; }
/// \brief Returns the number of refinement levels /// \brief Returns the number of refinement levels
int GetNumLevels() const { return (int)_levels.size(); } int GetNumLevels() const { return (int)_farLevels.size(); }
/// \brief Returns the highest level of refinement /// \brief Returns the highest level of refinement
int GetMaxLevel() const { return _maxLevel; } int GetMaxLevel() const { return _maxLevel; }

View File

@ -125,7 +125,7 @@ TopologyRefinerFactoryBase::prepareComponentTopologyAssignment(TopologyRefiner&
bool completeMissingTopology = (baseLevel.getNumEdges() == 0); bool completeMissingTopology = (baseLevel.getNumEdges() == 0);
if (completeMissingTopology) { if (completeMissingTopology) {
if (not baseLevel.completeTopologyFromFaceVertices()) { if (! baseLevel.completeTopologyFromFaceVertices()) {
char msg[1024]; char msg[1024];
snprintf(msg, 1024, "Failure in TopologyRefinerFactory<>::Create() -- " snprintf(msg, 1024, "Failure in TopologyRefinerFactory<>::Create() -- "
"vertex with valence %d > %d max.", "vertex with valence %d > %d max.",
@ -142,7 +142,7 @@ TopologyRefinerFactoryBase::prepareComponentTopologyAssignment(TopologyRefiner&
} }
if (fullValidation) { if (fullValidation) {
if (not baseLevel.validateTopology(callback, callbackData)) { if (! baseLevel.validateTopology(callback, callbackData)) {
if (completeMissingTopology) { if (completeMissingTopology) {
Error(FAR_RUNTIME_ERROR, "Failure in TopologyRefinerFactory<>::Create() -- " Error(FAR_RUNTIME_ERROR, "Failure in TopologyRefinerFactory<>::Create() -- "
"invalid topology detected from partial specification."); "invalid topology detected from partial specification.");
@ -240,7 +240,7 @@ TopologyRefinerFactoryBase::prepareComponentTagsAndSharpness(TopologyRefiner& re
// more than two incident faces. In these cases there are more incident // more than two incident faces. In these cases there are more incident
// faces than edges (1 more for each additional "fin") and no boundaries. // faces than edges (1 more for each additional "fin") and no boundaries.
// //
if (not ((nonManifoldEdgeCount == 2) && (boundaryEdgeCount == 0) && (vFaces.size() > vEdges.size()))) { if (! ((nonManifoldEdgeCount == 2) && (boundaryEdgeCount == 0) && (vFaces.size() > vEdges.size()))) {
vSharpness = Sdc::Crease::SHARPNESS_INFINITE; vSharpness = Sdc::Crease::SHARPNESS_INFINITE;
} }
} }

View File

@ -319,7 +319,7 @@ TopologyRefinerFactory<MESH>::Create(MESH const& mesh, Options options) {
TopologyRefiner * refiner = new TopologyRefiner(options.schemeType, options.schemeOptions); TopologyRefiner * refiner = new TopologyRefiner(options.schemeType, options.schemeOptions);
if (not populateBaseLevel(*refiner, mesh, options)) { if (! populateBaseLevel(*refiner, mesh, options)) {
delete refiner; delete refiner;
return 0; return 0;
} }
@ -349,8 +349,8 @@ TopologyRefinerFactory<MESH>::populateBaseLevel(TopologyRefiner& refiner, MESH c
// an inventory of all components and their relations that is used to allocate buffers // an inventory of all components and their relations that is used to allocate buffers
// to be efficiently populated in the subsequent topology assignment step. // to be efficiently populated in the subsequent topology assignment step.
// //
if (not resizeComponentTopology(refiner, mesh)) return false; if (! resizeComponentTopology(refiner, mesh)) return false;
if (not prepareComponentTopologySizing(refiner)) return false; if (! prepareComponentTopologySizing(refiner)) return false;
// //
// Assignment of the topology -- this is a required specialization for MESH. If edges // Assignment of the topology -- this is a required specialization for MESH. If edges
@ -361,21 +361,21 @@ TopologyRefinerFactory<MESH>::populateBaseLevel(TopologyRefiner& refiner, MESH c
TopologyCallback callback = reinterpret_cast<TopologyCallback>(reportInvalidTopology); TopologyCallback callback = reinterpret_cast<TopologyCallback>(reportInvalidTopology);
void const * userData = &mesh; void const * userData = &mesh;
if (not assignComponentTopology(refiner, mesh)) return false; if (! assignComponentTopology(refiner, mesh)) return false;
if (not prepareComponentTopologyAssignment(refiner, validate, callback, userData)) return false; if (! prepareComponentTopologyAssignment(refiner, validate, callback, userData)) return false;
// //
// User assigned and internal tagging of components -- an optional specialization for // User assigned and internal tagging of components -- an optional specialization for
// MESH. Allows the specification of sharpness values, holes, etc. // MESH. Allows the specification of sharpness values, holes, etc.
// //
if (not assignComponentTags(refiner, mesh)) return false; if (! assignComponentTags(refiner, mesh)) return false;
if (not prepareComponentTagsAndSharpness(refiner)) return false; if (! prepareComponentTagsAndSharpness(refiner)) return false;
// //
// Defining channels of face-varying primvar data -- an optional specialization for MESH. // Defining channels of face-varying primvar data -- an optional specialization for MESH.
// //
if (not assignFaceVaryingTopology(refiner, mesh)) return false; if (! assignFaceVaryingTopology(refiner, mesh)) return false;
if (not prepareFaceVaryingChannels(refiner)) return false; if (! prepareFaceVaryingChannels(refiner)) return false;
return true; return true;
} }

View File

@ -317,6 +317,11 @@ add_library(osd_cpu_obj
${PUBLIC_HEADER_FILES} ${PUBLIC_HEADER_FILES}
) )
set_target_properties(osd_cpu_obj
PROPERTIES
FOLDER "opensubdiv"
)
if( GPU_SOURCE_FILES ) if( GPU_SOURCE_FILES )
add_library(osd_gpu_obj add_library(osd_gpu_obj
OBJECT OBJECT
@ -325,6 +330,12 @@ if( GPU_SOURCE_FILES )
${PUBLIC_HEADER_FILES} ${PUBLIC_HEADER_FILES}
${INC_FILES} ${INC_FILES}
) )
set_target_properties(osd_gpu_obj
PROPERTIES
FOLDER "opensubdiv"
)
endif() endif()
_add_doxy_headers( "${DOXY_HEADER_FILES}" ) _add_doxy_headers( "${DOXY_HEADER_FILES}" )

View File

@ -84,8 +84,8 @@ struct BufferDescriptor {
/// True if the descriptors are identical /// True if the descriptors are identical
bool operator == (BufferDescriptor const &other) const { bool operator == (BufferDescriptor const &other) const {
return (offset == other.offset and return (offset == other.offset &&
length == other.length and length == other.length &&
stride == other.stride); stride == other.stride);
} }

View File

@ -66,31 +66,31 @@ static clEnqueueReleaseD3D11Objects_fn clEnqueueReleaseD3D11Objects = NULL;
static void resolveInteropFunctions() { static void resolveInteropFunctions() {
if (not clCreateFromD3D11Buffer) { if (! clCreateFromD3D11Buffer) {
clCreateFromD3D11Buffer = clCreateFromD3D11Buffer =
(clCreateFromD3D11Buffer_fn) (clCreateFromD3D11Buffer_fn)
clGetExtensionFunctionAddress("clCreateFromD3D11BufferKHR"); clGetExtensionFunctionAddress("clCreateFromD3D11BufferKHR");
} }
if (not clCreateFromD3D11Buffer) { if (! clCreateFromD3D11Buffer) {
clCreateFromD3D11Buffer = clCreateFromD3D11Buffer =
(clCreateFromD3D11Buffer_fn) (clCreateFromD3D11Buffer_fn)
clGetExtensionFunctionAddress("clCreateFromD3D11BufferNV"); clGetExtensionFunctionAddress("clCreateFromD3D11BufferNV");
} }
if (not clEnqueueAcquireD3D11Objects) { if (! clEnqueueAcquireD3D11Objects) {
clEnqueueAcquireD3D11Objects = (clEnqueueAcquireD3D11Objects_fn) clEnqueueAcquireD3D11Objects = (clEnqueueAcquireD3D11Objects_fn)
clGetExtensionFunctionAddress("clEnqueueAcquireD3D11ObjectsKHR"); clGetExtensionFunctionAddress("clEnqueueAcquireD3D11ObjectsKHR");
} }
if (not clEnqueueAcquireD3D11Objects) { if (! clEnqueueAcquireD3D11Objects) {
clEnqueueAcquireD3D11Objects = (clEnqueueAcquireD3D11Objects_fn) clEnqueueAcquireD3D11Objects = (clEnqueueAcquireD3D11Objects_fn)
clGetExtensionFunctionAddress("clEnqueueAcquireD3D11ObjectsNV"); clGetExtensionFunctionAddress("clEnqueueAcquireD3D11ObjectsNV");
} }
if (not clEnqueueReleaseD3D11Objects) { if (! clEnqueueReleaseD3D11Objects) {
clEnqueueReleaseD3D11Objects = (clEnqueueReleaseD3D11Objects_fn) clEnqueueReleaseD3D11Objects = (clEnqueueReleaseD3D11Objects_fn)
clGetExtensionFunctionAddress("clEnqueueReleaseD3D11ObjectsKHR"); clGetExtensionFunctionAddress("clEnqueueReleaseD3D11ObjectsKHR");
} }
if (not clEnqueueReleaseD3D11Objects) { if (! clEnqueueReleaseD3D11Objects) {
clEnqueueReleaseD3D11Objects = (clEnqueueReleaseD3D11Objects_fn) clEnqueueReleaseD3D11Objects = (clEnqueueReleaseD3D11Objects_fn)
clGetExtensionFunctionAddress("clEnqueueReleaseD3D11ObjectsNV"); clGetExtensionFunctionAddress("clEnqueueReleaseD3D11ObjectsNV");
} }
@ -178,9 +178,9 @@ CLD3D11VertexBuffer::allocate(cl_context clContext, ID3D11Device *device) {
return false; return false;
} }
if (not clCreateFromD3D11Buffer) { if (! clCreateFromD3D11Buffer) {
resolveInteropFunctions(); resolveInteropFunctions();
if (not clCreateFromD3D11Buffer) { if (! clCreateFromD3D11Buffer) {
return false; return false;
} }
} }
@ -200,9 +200,9 @@ CLD3D11VertexBuffer::map(cl_command_queue queue) {
if (_clMapped) return; if (_clMapped) return;
_clQueue = queue; _clQueue = queue;
if (not clEnqueueAcquireD3D11Objects) { if (! clEnqueueAcquireD3D11Objects) {
resolveInteropFunctions(); resolveInteropFunctions();
if (not clEnqueueAcquireD3D11Objects) { if (! clEnqueueAcquireD3D11Objects) {
return; return;
} }
} }
@ -214,10 +214,10 @@ CLD3D11VertexBuffer::map(cl_command_queue queue) {
void void
CLD3D11VertexBuffer::unmap() { CLD3D11VertexBuffer::unmap() {
if (not _clMapped) return; if (! _clMapped) return;
if (not clEnqueueReleaseD3D11Objects) { if (! clEnqueueReleaseD3D11Objects) {
resolveInteropFunctions(); resolveInteropFunctions();
if (not clEnqueueReleaseD3D11Objects) { if (! clEnqueueReleaseD3D11Objects) {
return; return;
} }
} }

View File

@ -204,7 +204,10 @@ CLEvaluator::EvalStencils(cl_mem src, BufferDescriptor const &srcDesc,
cl_mem offsets, cl_mem offsets,
cl_mem indices, cl_mem indices,
cl_mem weights, cl_mem weights,
int start, int end) const { int start, int end,
unsigned int numStartEvents,
const cl_event* startEvents,
cl_event* endEvent) const {
if (end <= start) return true; if (end <= start) return true;
size_t globalWorkSize = (size_t)(end - start); size_t globalWorkSize = (size_t)(end - start);
@ -222,7 +225,7 @@ CLEvaluator::EvalStencils(cl_mem src, BufferDescriptor const &srcDesc,
cl_int errNum = clEnqueueNDRangeKernel( cl_int errNum = clEnqueueNDRangeKernel(
_clCommandQueue, _stencilKernel, 1, NULL, _clCommandQueue, _stencilKernel, 1, NULL,
&globalWorkSize, NULL, 0, NULL, NULL); &globalWorkSize, NULL, numStartEvents, startEvents, endEvent);
if (errNum != CL_SUCCESS) { if (errNum != CL_SUCCESS) {
Far::Error(Far::FAR_RUNTIME_ERROR, Far::Error(Far::FAR_RUNTIME_ERROR,
@ -230,7 +233,10 @@ CLEvaluator::EvalStencils(cl_mem src, BufferDescriptor const &srcDesc,
return false; return false;
} }
if (endEvent == NULL)
{
clFinish(_clCommandQueue); clFinish(_clCommandQueue);
}
return true; return true;
} }
@ -245,7 +251,10 @@ CLEvaluator::EvalStencils(cl_mem src, BufferDescriptor const &srcDesc,
cl_mem weights, cl_mem weights,
cl_mem duWeights, cl_mem duWeights,
cl_mem dvWeights, cl_mem dvWeights,
int start, int end) const { int start, int end,
unsigned int numStartEvents,
const cl_event* startEvents,
cl_event* endEvent) const {
if (end <= start) return true; if (end <= start) return true;
size_t globalWorkSize = (size_t)(end - start); size_t globalWorkSize = (size_t)(end - start);
@ -271,7 +280,7 @@ CLEvaluator::EvalStencils(cl_mem src, BufferDescriptor const &srcDesc,
cl_int errNum = clEnqueueNDRangeKernel( cl_int errNum = clEnqueueNDRangeKernel(
_clCommandQueue, _stencilDerivKernel, 1, NULL, _clCommandQueue, _stencilDerivKernel, 1, NULL,
&globalWorkSize, NULL, 0, NULL, NULL); &globalWorkSize, NULL, numStartEvents, startEvents, endEvent);
if (errNum != CL_SUCCESS) { if (errNum != CL_SUCCESS) {
Far::Error(Far::FAR_RUNTIME_ERROR, Far::Error(Far::FAR_RUNTIME_ERROR,
@ -279,7 +288,10 @@ CLEvaluator::EvalStencils(cl_mem src, BufferDescriptor const &srcDesc,
return false; return false;
} }
if (endEvent == NULL)
{
clFinish(_clCommandQueue); clFinish(_clCommandQueue);
}
return true; return true;
} }
@ -292,7 +304,10 @@ CLEvaluator::EvalPatches(cl_mem src, BufferDescriptor const &srcDesc,
cl_mem patchCoordsBuffer, cl_mem patchCoordsBuffer,
cl_mem patchArrayBuffer, cl_mem patchArrayBuffer,
cl_mem patchIndexBuffer, cl_mem patchIndexBuffer,
cl_mem patchParamBuffer) const { cl_mem patchParamBuffer,
unsigned int numStartEvents,
const cl_event* startEvents,
cl_event* endEvent) const {
size_t globalWorkSize = (size_t)(numPatchCoords); size_t globalWorkSize = (size_t)(numPatchCoords);
@ -313,7 +328,7 @@ CLEvaluator::EvalPatches(cl_mem src, BufferDescriptor const &srcDesc,
cl_int errNum = clEnqueueNDRangeKernel( cl_int errNum = clEnqueueNDRangeKernel(
_clCommandQueue, _patchKernel, 1, NULL, _clCommandQueue, _patchKernel, 1, NULL,
&globalWorkSize, NULL, 0, NULL, NULL); &globalWorkSize, NULL, numStartEvents, startEvents, endEvent);
if (errNum != CL_SUCCESS) { if (errNum != CL_SUCCESS) {
Far::Error(Far::FAR_RUNTIME_ERROR, Far::Error(Far::FAR_RUNTIME_ERROR,
@ -321,7 +336,10 @@ CLEvaluator::EvalPatches(cl_mem src, BufferDescriptor const &srcDesc,
return false; return false;
} }
if (endEvent == NULL)
{
clFinish(_clCommandQueue); clFinish(_clCommandQueue);
}
return true; return true;
} }

View File

@ -158,6 +158,19 @@ public:
/// cl_command_queue GetCommandQueue() /// cl_command_queue GetCommandQueue()
/// methods. /// methods.
/// ///
/// @param numStartEvents the number of events in the array pointed to by
/// startEvents.
///
/// @param startEvents points to an array of cl_event which will determine
/// when it is safe for the OpenCL device to begin work
/// or NULL if it can begin immediately.
///
/// @param endEvent pointer to a cl_event which will recieve a copy of
/// the cl_event which indicates when all work for this
/// call has completed. This cl_event has an incremented
/// reference count and should be released via
/// clReleaseEvent(). NULL if not required.
///
template <typename SRC_BUFFER, typename DST_BUFFER, template <typename SRC_BUFFER, typename DST_BUFFER,
typename STENCIL_TABLE, typename DEVICE_CONTEXT> typename STENCIL_TABLE, typename DEVICE_CONTEXT>
static bool EvalStencils( static bool EvalStencils(
@ -165,12 +178,16 @@ public:
DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc, DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc,
STENCIL_TABLE const *stencilTable, STENCIL_TABLE const *stencilTable,
CLEvaluator const *instance, CLEvaluator const *instance,
DEVICE_CONTEXT deviceContext) { DEVICE_CONTEXT deviceContext,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) {
if (instance) { if (instance) {
return instance->EvalStencils(srcBuffer, srcDesc, return instance->EvalStencils(srcBuffer, srcDesc,
dstBuffer, dstDesc, dstBuffer, dstDesc,
stencilTable); stencilTable,
numStartEvents, startEvents, endEvent);
} else { } else {
// Create an instance on demand (slow) // Create an instance on demand (slow)
instance = Create(srcDesc, dstDesc, instance = Create(srcDesc, dstDesc,
@ -180,7 +197,8 @@ public:
if (instance) { if (instance) {
bool r = instance->EvalStencils(srcBuffer, srcDesc, bool r = instance->EvalStencils(srcBuffer, srcDesc,
dstBuffer, dstDesc, dstBuffer, dstDesc,
stencilTable); stencilTable,
numStartEvents, startEvents, endEvent);
delete instance; delete instance;
return r; return r;
} }
@ -230,6 +248,19 @@ public:
/// cl_command_queue GetCommandQueue() /// cl_command_queue GetCommandQueue()
/// methods. /// methods.
/// ///
/// @param numStartEvents the number of events in the array pointed to by
/// startEvents.
///
/// @param startEvents points to an array of cl_event which will determine
/// when it is safe for the OpenCL device to begin work
/// or NULL if it can begin immediately.
///
/// @param endEvent pointer to a cl_event which will recieve a copy of
/// the cl_event which indicates when all work for this
/// call has completed. This cl_event has an incremented
/// reference count and should be released via
/// clReleaseEvent(). NULL if not required.
///
template <typename SRC_BUFFER, typename DST_BUFFER, template <typename SRC_BUFFER, typename DST_BUFFER,
typename STENCIL_TABLE, typename DEVICE_CONTEXT> typename STENCIL_TABLE, typename DEVICE_CONTEXT>
static bool EvalStencils( static bool EvalStencils(
@ -239,14 +270,18 @@ public:
DST_BUFFER *dvBuffer, BufferDescriptor const &dvDesc, DST_BUFFER *dvBuffer, BufferDescriptor const &dvDesc,
STENCIL_TABLE const *stencilTable, STENCIL_TABLE const *stencilTable,
CLEvaluator const *instance, CLEvaluator const *instance,
DEVICE_CONTEXT deviceContext) { DEVICE_CONTEXT deviceContext,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) {
if (instance) { if (instance) {
return instance->EvalStencils(srcBuffer, srcDesc, return instance->EvalStencils(srcBuffer, srcDesc,
dstBuffer, dstDesc, dstBuffer, dstDesc,
duBuffer, duDesc, duBuffer, duDesc,
dvBuffer, dvDesc, dvBuffer, dvDesc,
stencilTable); stencilTable,
numStartEvents, startEvents, endEvent);
} else { } else {
// Create an instance on demand (slow) // Create an instance on demand (slow)
instance = Create(srcDesc, dstDesc, duDesc, dvDesc, instance = Create(srcDesc, dstDesc, duDesc, dvDesc,
@ -256,7 +291,8 @@ public:
dstBuffer, dstDesc, dstBuffer, dstDesc,
duBuffer, duDesc, duBuffer, duDesc,
dvBuffer, dvDesc, dvBuffer, dvDesc,
stencilTable); stencilTable,
numStartEvents, startEvents, endEvent);
delete instance; delete instance;
return r; return r;
} }
@ -271,7 +307,10 @@ public:
bool EvalStencils( bool EvalStencils(
SRC_BUFFER *srcBuffer, BufferDescriptor const &srcDesc, SRC_BUFFER *srcBuffer, BufferDescriptor const &srcDesc,
DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc, DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc,
STENCIL_TABLE const *stencilTable) const { STENCIL_TABLE const *stencilTable,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const {
return EvalStencils(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc, return EvalStencils(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc,
dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc, dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc,
stencilTable->GetSizesBuffer(), stencilTable->GetSizesBuffer(),
@ -279,7 +318,8 @@ public:
stencilTable->GetIndicesBuffer(), stencilTable->GetIndicesBuffer(),
stencilTable->GetWeightsBuffer(), stencilTable->GetWeightsBuffer(),
0, 0,
stencilTable->GetNumStencils()); stencilTable->GetNumStencils(),
numStartEvents, startEvents, endEvent);
} }
/// Generic compute function. /// Generic compute function.
@ -291,7 +331,10 @@ public:
DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc, DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc,
DST_BUFFER *duBuffer, BufferDescriptor const &duDesc, DST_BUFFER *duBuffer, BufferDescriptor const &duDesc,
DST_BUFFER *dvBuffer, BufferDescriptor const &dvDesc, DST_BUFFER *dvBuffer, BufferDescriptor const &dvDesc,
STENCIL_TABLE const *stencilTable) const { STENCIL_TABLE const *stencilTable,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const {
return EvalStencils(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc, return EvalStencils(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc,
dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc, dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc,
duBuffer->BindCLBuffer(_clCommandQueue), duDesc, duBuffer->BindCLBuffer(_clCommandQueue), duDesc,
@ -303,7 +346,8 @@ public:
stencilTable->GetDuWeightsBuffer(), stencilTable->GetDuWeightsBuffer(),
stencilTable->GetDvWeightsBuffer(), stencilTable->GetDvWeightsBuffer(),
0, 0,
stencilTable->GetNumStencils()); stencilTable->GetNumStencils(),
numStartEvents, startEvents, endEvent);
} }
/// Dispatch the CL compute kernel asynchronously. /// Dispatch the CL compute kernel asynchronously.
@ -315,7 +359,10 @@ public:
cl_mem indices, cl_mem indices,
cl_mem weights, cl_mem weights,
int start, int start,
int end) const; int end,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const;
/// Dispatch the CL compute kernel asynchronously. /// Dispatch the CL compute kernel asynchronously.
/// returns false if the kernel hasn't been compiled yet. /// returns false if the kernel hasn't been compiled yet.
@ -330,7 +377,10 @@ public:
cl_mem duWeights, cl_mem duWeights,
cl_mem dvWeights, cl_mem dvWeights,
int start, int start,
int end) const; int end,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const;
/// ---------------------------------------------------------------------- /// ----------------------------------------------------------------------
/// ///
@ -373,6 +423,19 @@ public:
/// cl_command_queue GetCommandQueue() /// cl_command_queue GetCommandQueue()
/// methods. /// methods.
/// ///
/// @param numStartEvents the number of events in the array pointed to by
/// startEvents.
///
/// @param startEvents points to an array of cl_event which will determine
/// when it is safe for the OpenCL device to begin work
/// or NULL if it can begin immediately.
///
/// @param endEvent pointer to a cl_event which will recieve a copy of
/// the cl_event which indicates when all work for this
/// call has completed. This cl_event has an incremented
/// reference count and should be released via
/// clReleaseEvent(). NULL if not required.
///
template <typename SRC_BUFFER, typename DST_BUFFER, template <typename SRC_BUFFER, typename DST_BUFFER,
typename PATCHCOORD_BUFFER, typename PATCH_TABLE, typename PATCHCOORD_BUFFER, typename PATCH_TABLE,
typename DEVICE_CONTEXT> typename DEVICE_CONTEXT>
@ -383,13 +446,17 @@ public:
PATCHCOORD_BUFFER *patchCoords, PATCHCOORD_BUFFER *patchCoords,
PATCH_TABLE *patchTable, PATCH_TABLE *patchTable,
CLEvaluator const *instance, CLEvaluator const *instance,
DEVICE_CONTEXT deviceContext) { DEVICE_CONTEXT deviceContext,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) {
if (instance) { if (instance) {
return instance->EvalPatches(srcBuffer, srcDesc, return instance->EvalPatches(srcBuffer, srcDesc,
dstBuffer, dstDesc, dstBuffer, dstDesc,
numPatchCoords, patchCoords, numPatchCoords, patchCoords,
patchTable); patchTable,
numStartEvents, startEvents, endEvent);
} else { } else {
// Create an instance on demand (slow) // Create an instance on demand (slow)
(void)deviceContext; // unused (void)deviceContext; // unused
@ -401,7 +468,8 @@ public:
bool r = instance->EvalPatches(srcBuffer, srcDesc, bool r = instance->EvalPatches(srcBuffer, srcDesc,
dstBuffer, dstDesc, dstBuffer, dstDesc,
numPatchCoords, patchCoords, numPatchCoords, patchCoords,
patchTable); patchTable,
numStartEvents, startEvents, endEvent);
delete instance; delete instance;
return r; return r;
} }
@ -452,6 +520,19 @@ public:
/// cl_command_queue GetCommandQueue() /// cl_command_queue GetCommandQueue()
/// methods. /// methods.
/// ///
/// @param numStartEvents the number of events in the array pointed to by
/// startEvents.
///
/// @param startEvents points to an array of cl_event which will determine
/// when it is safe for the OpenCL device to begin work
/// or NULL if it can begin immediately.
///
/// @param endEvent pointer to a cl_event which will recieve a copy of
/// the cl_event which indicates when all work for this
/// call has completed. This cl_event has an incremented
/// reference count and should be released via
/// clReleaseEvent(). NULL if not required.
///
template <typename SRC_BUFFER, typename DST_BUFFER, template <typename SRC_BUFFER, typename DST_BUFFER,
typename PATCHCOORD_BUFFER, typename PATCH_TABLE, typename PATCHCOORD_BUFFER, typename PATCH_TABLE,
typename DEVICE_CONTEXT> typename DEVICE_CONTEXT>
@ -464,7 +545,10 @@ public:
PATCHCOORD_BUFFER *patchCoords, PATCHCOORD_BUFFER *patchCoords,
PATCH_TABLE *patchTable, PATCH_TABLE *patchTable,
CLEvaluator const *instance, CLEvaluator const *instance,
DEVICE_CONTEXT deviceContext) { DEVICE_CONTEXT deviceContext,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) {
if (instance) { if (instance) {
return instance->EvalPatches(srcBuffer, srcDesc, return instance->EvalPatches(srcBuffer, srcDesc,
@ -472,7 +556,8 @@ public:
duBuffer, duDesc, duBuffer, duDesc,
dvBuffer, dvDesc, dvBuffer, dvDesc,
numPatchCoords, patchCoords, numPatchCoords, patchCoords,
patchTable); patchTable,
numStartEvents, startEvents, endEvent);
} else { } else {
// Create an instance on demand (slow) // Create an instance on demand (slow)
(void)deviceContext; // unused (void)deviceContext; // unused
@ -483,7 +568,8 @@ public:
duBuffer, duDesc, duBuffer, duDesc,
dvBuffer, dvDesc, dvBuffer, dvDesc,
numPatchCoords, patchCoords, numPatchCoords, patchCoords,
patchTable); patchTable,
numStartEvents, startEvents, endEvent);
delete instance; delete instance;
return r; return r;
} }
@ -515,6 +601,19 @@ public:
/// ///
/// @param patchTable CLPatchTable or equivalent /// @param patchTable CLPatchTable or equivalent
/// ///
/// @param numStartEvents the number of events in the array pointed to by
/// startEvents.
///
/// @param startEvents points to an array of cl_event which will determine
/// when it is safe for the OpenCL device to begin work
/// or NULL if it can begin immediately.
///
/// @param endEvent pointer to a cl_event which will recieve a copy of
/// the cl_event which indicates when all work for this
/// call has completed. This cl_event has an incremented
/// reference count and should be released via
/// clReleaseEvent(). NULL if not required.
///
template <typename SRC_BUFFER, typename DST_BUFFER, template <typename SRC_BUFFER, typename DST_BUFFER,
typename PATCHCOORD_BUFFER, typename PATCH_TABLE> typename PATCHCOORD_BUFFER, typename PATCH_TABLE>
bool EvalPatches( bool EvalPatches(
@ -522,7 +621,10 @@ public:
DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc, DST_BUFFER *dstBuffer, BufferDescriptor const &dstDesc,
int numPatchCoords, int numPatchCoords,
PATCHCOORD_BUFFER *patchCoords, PATCHCOORD_BUFFER *patchCoords,
PATCH_TABLE *patchTable) const { PATCH_TABLE *patchTable,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const {
return EvalPatches(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc, return EvalPatches(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc,
dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc, dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc,
@ -532,7 +634,8 @@ public:
patchCoords->BindCLBuffer(_clCommandQueue), patchCoords->BindCLBuffer(_clCommandQueue),
patchTable->GetPatchArrayBuffer(), patchTable->GetPatchArrayBuffer(),
patchTable->GetPatchIndexBuffer(), patchTable->GetPatchIndexBuffer(),
patchTable->GetPatchParamBuffer()); patchTable->GetPatchParamBuffer(),
numStartEvents, startEvents, endEvent);
} }
/// \brief Generic limit eval function with derivatives. This function has /// \brief Generic limit eval function with derivatives. This function has
@ -569,6 +672,19 @@ public:
/// ///
/// @param patchTable CLPatchTable or equivalent /// @param patchTable CLPatchTable or equivalent
/// ///
/// @param numStartEvents the number of events in the array pointed to by
/// startEvents.
///
/// @param startEvents points to an array of cl_event which will determine
/// when it is safe for the OpenCL device to begin work
/// or NULL if it can begin immediately.
///
/// @param endEvent pointer to a cl_event which will recieve a copy of
/// the cl_event which indicates when all work for this
/// call has completed. This cl_event has an incremented
/// reference count and should be released via
/// clReleaseEvent(). NULL if not required.
///
template <typename SRC_BUFFER, typename DST_BUFFER, template <typename SRC_BUFFER, typename DST_BUFFER,
typename PATCHCOORD_BUFFER, typename PATCH_TABLE> typename PATCHCOORD_BUFFER, typename PATCH_TABLE>
bool EvalPatches( bool EvalPatches(
@ -578,7 +694,10 @@ public:
DST_BUFFER *dvBuffer, BufferDescriptor const &dvDesc, DST_BUFFER *dvBuffer, BufferDescriptor const &dvDesc,
int numPatchCoords, int numPatchCoords,
PATCHCOORD_BUFFER *patchCoords, PATCHCOORD_BUFFER *patchCoords,
PATCH_TABLE *patchTable) const { PATCH_TABLE *patchTable,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const {
return EvalPatches(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc, return EvalPatches(srcBuffer->BindCLBuffer(_clCommandQueue), srcDesc,
dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc, dstBuffer->BindCLBuffer(_clCommandQueue), dstDesc,
@ -588,7 +707,8 @@ public:
patchCoords->BindCLBuffer(_clCommandQueue), patchCoords->BindCLBuffer(_clCommandQueue),
patchTable->GetPatchArrayBuffer(), patchTable->GetPatchArrayBuffer(),
patchTable->GetPatchIndexBuffer(), patchTable->GetPatchIndexBuffer(),
patchTable->GetPatchParamBuffer()); patchTable->GetPatchParamBuffer(),
numStartEvents, startEvents, endEvent);
} }
bool EvalPatches(cl_mem src, BufferDescriptor const &srcDesc, bool EvalPatches(cl_mem src, BufferDescriptor const &srcDesc,
@ -599,7 +719,10 @@ public:
cl_mem patchCoordsBuffer, cl_mem patchCoordsBuffer,
cl_mem patchArrayBuffer, cl_mem patchArrayBuffer,
cl_mem patchIndexBuffer, cl_mem patchIndexBuffer,
cl_mem patchParamsBuffer) const; cl_mem patchParamsBuffer,
unsigned int numStartEvents=0,
const cl_event* startEvents=NULL,
cl_event* endEvent=NULL) const;
/// ---------------------------------------------------------------------- /// ----------------------------------------------------------------------
/// ///

View File

@ -138,7 +138,7 @@ CLGLVertexBuffer::map(cl_command_queue queue) {
void void
CLGLVertexBuffer::unmap() { CLGLVertexBuffer::unmap() {
if (not _clMapped) return; if (! _clMapped) return;
clEnqueueReleaseGLObjects(_clQueue, 1, &_clMemory, 0, 0, 0); clEnqueueReleaseGLObjects(_clQueue, 1, &_clMemory, 0, 0, 0);
_clMapped = false; _clMapped = false;
} }

View File

@ -54,12 +54,15 @@ CLVertexBuffer::Create(int numElements, int numVertices,
} }
void void
CLVertexBuffer::UpdateData(const float *src, int startVertex, int numVertices, cl_command_queue queue) { CLVertexBuffer::UpdateData(const float *src, int startVertex, int numVertices, cl_command_queue queue,
cl_event* startEvents, unsigned int numStartEvents, cl_event* endEvent) {
size_t size = _numElements * numVertices * sizeof(float); size_t size = _numElements * numVertices * sizeof(float);
size_t offset = startVertex * _numElements * sizeof(float); size_t offset = startVertex * _numElements * sizeof(float);
clEnqueueWriteBuffer(queue, _clMemory, true, offset, size, src, 0, NULL, NULL); cl_bool blocking = (endEvent == NULL) ? CL_TRUE : CL_FALSE;
cl_int err = clEnqueueWriteBuffer(queue, _clMemory, blocking, offset, size, src, numStartEvents, startEvents, endEvent);
assert(err == CL_SUCCESS);
} }
int int

View File

@ -56,12 +56,14 @@ public:
/// This method is meant to be used in client code in order to provide coarse /// This method is meant to be used in client code in order to provide coarse
/// vertices data to Osd. /// vertices data to Osd.
void UpdateData(const float *src, int startVertex, int numVertices, cl_command_queue clQueue); void UpdateData(const float *src, int startVertex, int numVertices, cl_command_queue clQueue,
cl_event* startEvents = NULL, unsigned int numStartEvents = 0, cl_event* endEvent = NULL);
template<typename DEVICE_CONTEXT> template<typename DEVICE_CONTEXT>
void UpdateData(const float *src, int startVertex, int numVertices, void UpdateData(const float *src, int startVertex, int numVertices,
DEVICE_CONTEXT context) { DEVICE_CONTEXT context,
UpdateData(src, startVertex, numVertices, context->GetCommandQueue()); cl_event* startEvents = NULL, unsigned int numStartEvents = 0, cl_event* endEvent = NULL) {
UpdateData(src, startVertex, numVertices, context->GetCommandQueue(), startEvents, numStartEvents, endEvent);
} }
/// Returns how many elements defined in this vertex buffer. /// Returns how many elements defined in this vertex buffer.

View File

@ -88,12 +88,12 @@ CpuGLVertexBuffer::BindCpuBuffer() {
GLuint GLuint
CpuGLVertexBuffer::BindVBO(void * /*deviceContext*/) { CpuGLVertexBuffer::BindVBO(void * /*deviceContext*/) {
if (not _dataDirty) if (! _dataDirty)
return _vbo; return _vbo;
int size = GetNumElements() * GetNumVertices() * sizeof(float); int size = GetNumElements() * GetNumVertices() * sizeof(float);
if (not _vbo) { if (! _vbo) {
glGenBuffers(1, &_vbo); glGenBuffers(1, &_vbo);
} }

View File

@ -52,7 +52,7 @@ static inline void
addWithWeight(float *dst, const float *src, int srcIndex, float weight, addWithWeight(float *dst, const float *src, int srcIndex, float weight,
BufferDescriptor const &desc) { BufferDescriptor const &desc) {
assert(src and dst); assert(src && dst);
src = elementAtIndex(src, srcIndex, desc); src = elementAtIndex(src, srcIndex, desc);
for (int k = 0; k < desc.length; ++k) { for (int k = 0; k < desc.length; ++k) {
dst[k] += src[k] * weight; dst[k] += src[k] * weight;
@ -62,7 +62,7 @@ addWithWeight(float *dst, const float *src, int srcIndex, float weight,
static inline void static inline void
copy(float *dst, int dstIndex, const float *src, BufferDescriptor const &desc) { copy(float *dst, int dstIndex, const float *src, BufferDescriptor const &desc) {
assert(src and dst); assert(src && dst);
dst = elementAtIndex(dst, dstIndex, desc); dst = elementAtIndex(dst, dstIndex, desc);
memcpy(dst, src, desc.length*sizeof(float)); memcpy(dst, src, desc.length*sizeof(float));
@ -77,7 +77,7 @@ CpuEvalStencils(float const * src, BufferDescriptor const &srcDesc,
float const * weights, float const * weights,
int start, int end) { int start, int end) {
assert(start>=0 and start<end); assert(start>=0 && start<end);
if (start>0) { if (start>0) {
sizes += start; sizes += start;
@ -88,15 +88,15 @@ CpuEvalStencils(float const * src, BufferDescriptor const &srcDesc,
src += srcDesc.offset; src += srcDesc.offset;
dst += dstDesc.offset; dst += dstDesc.offset;
if (srcDesc.length == 4 and dstDesc.length == 4 and if (srcDesc.length == 4 && dstDesc.length == 4 &&
srcDesc.stride == 4 and dstDesc.stride == 4) { srcDesc.stride == 4 && dstDesc.stride == 4) {
// SIMD fast path for aligned primvar data (4 floats) // SIMD fast path for aligned primvar data (4 floats)
ComputeStencilKernel<4>(src, dst, ComputeStencilKernel<4>(src, dst,
sizes, indices, weights, start, end); sizes, indices, weights, start, end);
} else if (srcDesc.length == 8 and dstDesc.length == 8 and } else if (srcDesc.length == 8 && dstDesc.length == 8 &&
srcDesc.stride == 8 and dstDesc.stride == 8) { srcDesc.stride == 8 && dstDesc.stride == 8) {
// SIMD fast path for aligned primvar data (8 floats) // SIMD fast path for aligned primvar data (8 floats)
ComputeStencilKernel<8>(src, dst, ComputeStencilKernel<8>(src, dst,

View File

@ -61,7 +61,7 @@ CpuEvalStencils(float const * src, BufferDescriptor const &srcDesc,
// SIMD ICC optimization of the stencil kernel // SIMD ICC optimization of the stencil kernel
// //
#if defined ( __INTEL_COMPILER ) or defined ( __ICC ) #if defined ( __INTEL_COMPILER ) || defined ( __ICC )
#define __ALIGN_DATA __declspec(align(32)) #define __ALIGN_DATA __declspec(align(32))
#else #else
#define __ALIGN_DATA #define __ALIGN_DATA
@ -86,7 +86,7 @@ ComputeStencilKernel(float const * vertexSrc,
for (int i=start; i<end; ++i) { for (int i=start; i<end; ++i) {
// Clear // Clear
#if defined ( __INTEL_COMPILER ) or defined ( __ICC ) #if defined ( __INTEL_COMPILER ) || defined ( __ICC )
#pragma simd #pragma simd
#pragma vector aligned #pragma vector aligned
#endif #endif
@ -99,7 +99,7 @@ ComputeStencilKernel(float const * vertexSrc,
weight = *weights; weight = *weights;
// AddWithWeight // AddWithWeight
#if defined ( __INTEL_COMPILER ) or defined ( __ICC ) #if defined ( __INTEL_COMPILER ) || defined ( __ICC )
#pragma simd #pragma simd
#pragma vector aligned #pragma vector aligned
#endif #endif
@ -108,7 +108,7 @@ ComputeStencilKernel(float const * vertexSrc,
} }
} }
#if defined ( __INTEL_COMPILER ) or defined ( __ICC ) #if defined ( __INTEL_COMPILER ) || defined ( __ICC )
#pragma simd #pragma simd
#pragma vector aligned #pragma vector aligned
#endif #endif

View File

@ -443,7 +443,7 @@ void CudaEvalStencils(
const int * sizes, const int * offsets, const int * indices, const int * sizes, const int * offsets, const int * indices,
const float * weights, const float * weights,
int start, int end) { int start, int end) {
if (length == 0 or srcStride == 0 or dstStride == 0 or (end <= start)) { if (length == 0 || srcStride == 0 || dstStride == 0 || (end <= start)) {
return; return;
} }

View File

@ -204,8 +204,11 @@ D3D11ComputeEvaluator::Compile(BufferDescriptor const &srcDesc,
return false; return false;
} }
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
| D3D10_SHADER_RESOURCES_MAY_ALIAS; #if defined(D3D10_SHADER_RESOURCES_MAY_ALIAS)
dwShaderFlags |= D3D10_SHADER_RESOURCES_MAY_ALIAS;
#endif
#ifdef _DEBUG #ifdef _DEBUG
dwShaderFlags |= D3DCOMPILE_DEBUG; dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif #endif

View File

@ -59,7 +59,7 @@ D3D11LegacyGregoryPatchTable::Create(Far::PatchTable const *farPatchTable,
Far::PatchTable::QuadOffsetsTable const & Far::PatchTable::QuadOffsetsTable const &
quadOffsetsTable = farPatchTable->GetQuadOffsetsTable(); quadOffsetsTable = farPatchTable->GetQuadOffsetsTable();
if (not valenceTable.empty()) { if (! valenceTable.empty()) {
D3D11_BUFFER_DESC bd; D3D11_BUFFER_DESC bd;
bd.ByteWidth = UINT(valenceTable.size() * sizeof(unsigned int)); bd.ByteWidth = UINT(valenceTable.size() * sizeof(unsigned int));
bd.Usage = D3D11_USAGE_DEFAULT; bd.Usage = D3D11_USAGE_DEFAULT;
@ -91,7 +91,7 @@ D3D11LegacyGregoryPatchTable::Create(Far::PatchTable const *farPatchTable,
} }
} }
if (not quadOffsetsTable.empty()) { if (! quadOffsetsTable.empty()) {
D3D11_BUFFER_DESC bd; D3D11_BUFFER_DESC bd;
bd.ByteWidth = UINT(quadOffsetsTable.size() * sizeof(unsigned int)); bd.ByteWidth = UINT(quadOffsetsTable.size() * sizeof(unsigned int));
bd.Usage = D3D11_USAGE_DEFAULT; bd.Usage = D3D11_USAGE_DEFAULT;

View File

@ -75,7 +75,7 @@ D3D11VertexBuffer::UpdateData(const float *src, int startVertex, int numVertices
return; return;
} }
int size = GetNumElements() * numVertices * sizeof(float); unsigned int size = GetNumElements() * numVertices * sizeof(float);
memcpy((float*)resource.pData + startVertex * _numElements, src, size); memcpy((float*)resource.pData + startVertex * _numElements, src, size);

View File

@ -57,7 +57,7 @@ GLLegacyGregoryPatchTable::Create(Far::PatchTable const *farPatchTable) {
Far::PatchTable::QuadOffsetsTable const & Far::PatchTable::QuadOffsetsTable const &
quadOffsetsTable = farPatchTable->GetQuadOffsetsTable(); quadOffsetsTable = farPatchTable->GetQuadOffsetsTable();
if (not valenceTable.empty()) { if (! valenceTable.empty()) {
GLuint buffer; GLuint buffer;
glGenBuffers(1, &buffer); glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer);
@ -71,7 +71,7 @@ GLLegacyGregoryPatchTable::Create(Far::PatchTable const *farPatchTable) {
glDeleteBuffers(1, &buffer); glDeleteBuffers(1, &buffer);
} }
if (not quadOffsetsTable.empty()) { if (! quadOffsetsTable.empty()) {
GLuint buffer; GLuint buffer;
glGenBuffers(1, &buffer); glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer);

View File

@ -72,6 +72,12 @@
// mix(input[c].var, input[d].var, UV.x), UV.y) // mix(input[c].var, input[d].var, UV.x), UV.y)
#endif #endif
// For now, fractional spacing is supported only with screen space tessellation
#ifndef OSD_ENABLE_SCREENSPACE_TESSELLATION
#undef OSD_FRACTIONAL_EVEN_SPACING
#undef OSD_FRACTIONAL_ODD_SPACING
#endif
#if defined OSD_FRACTIONAL_EVEN_SPACING #if defined OSD_FRACTIONAL_EVEN_SPACING
#define OSD_SPACING fractional_even_spacing #define OSD_SPACING fractional_even_spacing
#elif defined OSD_FRACTIONAL_ODD_SPACING #elif defined OSD_FRACTIONAL_ODD_SPACING
@ -1086,19 +1092,27 @@ OsdFlipMatrix(mat4 m)
m[0][3], m[0][2], m[0][1], m[0][0]); m[0][3], m[0][2], m[0][1], m[0][0]);
} }
// Regular BSpline to Bezier
uniform mat4 Q = mat4(
1.f/6.f, 4.f/6.f, 1.f/6.f, 0.f,
0.f, 4.f/6.f, 2.f/6.f, 0.f,
0.f, 2.f/6.f, 4.f/6.f, 0.f,
0.f, 1.f/6.f, 4.f/6.f, 1.f/6.f
);
// Infinitely Sharp (boundary)
uniform mat4 Mi = mat4(
1.f/6.f, 4.f/6.f, 1.f/6.f, 0.f,
0.f, 4.f/6.f, 2.f/6.f, 0.f,
0.f, 2.f/6.f, 4.f/6.f, 0.f,
0.f, 0.f, 1.f, 0.f
);
// convert BSpline cv to Bezier cv // convert BSpline cv to Bezier cv
void void
OsdComputePerPatchVertexBSpline(ivec3 patchParam, int ID, vec3 cv[16], OsdComputePerPatchVertexBSpline(ivec3 patchParam, int ID, vec3 cv[16],
out OsdPerPatchVertexBezier result) out OsdPerPatchVertexBezier result)
{ {
// Regular BSpline to Bezier
mat4 Q = mat4(
1.f/6.f, 4.f/6.f, 1.f/6.f, 0.f,
0.f, 4.f/6.f, 2.f/6.f, 0.f,
0.f, 2.f/6.f, 4.f/6.f, 0.f,
0.f, 1.f/6.f, 4.f/6.f, 1.f/6.f
);
result.patchParam = patchParam; result.patchParam = patchParam;
int i = ID%4; int i = ID%4;
@ -1106,15 +1120,10 @@ OsdComputePerPatchVertexBSpline(ivec3 patchParam, int ID, vec3 cv[16],
#if defined OSD_PATCH_ENABLE_SINGLE_CREASE #if defined OSD_PATCH_ENABLE_SINGLE_CREASE
// Infinitely Sharp (boundary) vec3 P = vec3(0); // 0 to 1-2^(-Sf)
mat4 Mi = mat4( vec3 P1 = vec3(0); // 1-2^(-Sf) to 1-2^(-Sc)
1.f/6.f, 4.f/6.f, 1.f/6.f, 0.f, vec3 P2 = vec3(0); // 1-2^(-Sc) to 1
0.f, 4.f/6.f, 2.f/6.f, 0.f,
0.f, 2.f/6.f, 4.f/6.f, 0.f,
0.f, 0.f, 1.f, 0.f
);
mat4 Mj, Ms;
float sharpness = OsdGetPatchSharpness(patchParam); float sharpness = OsdGetPatchSharpness(patchParam);
if (sharpness > 0) { if (sharpness > 0) {
float Sf = floor(sharpness); float Sf = floor(sharpness);
@ -1122,59 +1131,74 @@ OsdComputePerPatchVertexBSpline(ivec3 patchParam, int ID, vec3 cv[16],
float Sr = fract(sharpness); float Sr = fract(sharpness);
mat4 Mf = OsdComputeMs(Sf); mat4 Mf = OsdComputeMs(Sf);
mat4 Mc = OsdComputeMs(Sc); mat4 Mc = OsdComputeMs(Sc);
Mj = (1-Sr) * Mf + Sr * Mi; mat4 Mj = (1-Sr) * Mf + Sr * Mi;
Ms = (1-Sr) * Mf + Sr * Mc; mat4 Ms = (1-Sr) * Mf + Sr * Mc;
float s0 = 1 - pow(2, -floor(sharpness)); float s0 = 1 - pow(2, -floor(sharpness));
float s1 = 1 - pow(2, -ceil(sharpness)); float s1 = 1 - pow(2, -ceil(sharpness));
result.vSegments = vec2(s0, s1); result.vSegments = vec2(s0, s1);
} else {
Mj = Ms = Mi;
result.vSegments = vec2(0);
}
result.P = vec3(0); // 0 to 1-2^(-Sf)
result.P1 = vec3(0); // 1-2^(-Sf) to 1-2^(-Sc)
result.P2 = vec3(0); // 1-2^(-Sc) to 1
mat4 MUi, MUj, MUs; mat4 MUi = Q, MUj = Q, MUs = Q;
mat4 MVi, MVj, MVs; mat4 MVi = Q, MVj = Q, MVs = Q;
MUi = MUj = MUs = Q;
MVi = MVj = MVs = Q;
int boundaryMask = OsdGetPatchBoundaryMask(patchParam); int boundaryMask = OsdGetPatchBoundaryMask(patchParam);
if ((boundaryMask & 1) != 0) { if ((boundaryMask & 1) != 0) {
MVi = OsdFlipMatrix(Mi); MVi = OsdFlipMatrix(Mi);
MVj = OsdFlipMatrix(Mj); MVj = OsdFlipMatrix(Mj);
MVs = OsdFlipMatrix(Ms); MVs = OsdFlipMatrix(Ms);
}
if ((boundaryMask & 2) != 0) {
MUi = Mi;
MUj = Mj;
MUs = Ms;
}
if ((boundaryMask & 4) != 0) {
MVi = Mi;
MVj = Mj;
MVs = Ms;
}
if ((boundaryMask & 8) != 0) {
MUi = OsdFlipMatrix(Mi);
MUj = OsdFlipMatrix(Mj);
MUs = OsdFlipMatrix(Ms);
}
vec3 Hi[4], Hj[4], Hs[4];
for (int l=0; l<4; ++l) {
Hi[l] = Hj[l] = Hs[l] = vec3(0);
for (int k=0; k<4; ++k) {
Hi[l] += MUi[i][k] * cv[l*4 + k];
Hj[l] += MUj[i][k] * cv[l*4 + k];
Hs[l] += MUs[i][k] * cv[l*4 + k];
} }
} if ((boundaryMask & 2) != 0) {
for (int k=0; k<4; ++k) { MUi = Mi;
result.P += MVi[j][k]*Hi[k]; MUj = Mj;
result.P1 += MVj[j][k]*Hj[k]; MUs = Ms;
result.P2 += MVs[j][k]*Hs[k]; }
if ((boundaryMask & 4) != 0) {
MVi = Mi;
MVj = Mj;
MVs = Ms;
}
if ((boundaryMask & 8) != 0) {
MUi = OsdFlipMatrix(Mi);
MUj = OsdFlipMatrix(Mj);
MUs = OsdFlipMatrix(Ms);
}
vec3 Hi[4], Hj[4], Hs[4];
for (int l=0; l<4; ++l) {
Hi[l] = Hj[l] = Hs[l] = vec3(0);
for (int k=0; k<4; ++k) {
Hi[l] += MUi[i][k] * cv[l*4 + k];
Hj[l] += MUj[i][k] * cv[l*4 + k];
Hs[l] += MUs[i][k] * cv[l*4 + k];
}
}
for (int k=0; k<4; ++k) {
P += MVi[j][k]*Hi[k];
P1 += MVj[j][k]*Hj[k];
P2 += MVs[j][k]*Hs[k];
}
result.P = P;
result.P1 = P1;
result.P2 = P2;
} else {
result.vSegments = vec2(0);
OsdComputeBSplineBoundaryPoints(cv, patchParam);
vec3 Hi[4];
for (int l=0; l<4; ++l) {
Hi[l] = vec3(0);
for (int k=0; k<4; ++k) {
Hi[l] += Q[i][k] * cv[l*4 + k];
}
}
for (int k=0; k<4; ++k) {
P += Q[j][k]*Hi[k];
}
result.P = P;
result.P1 = P;
result.P2 = P;
} }
#else #else
OsdComputeBSplineBoundaryPoints(cv, patchParam); OsdComputeBSplineBoundaryPoints(cv, patchParam);

Some files were not shown because too many files have changed in this diff Show More